diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..7f4470eb6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,242 @@ +[*.{props,targets}] +indent_style = tab +indent_size = 4 +charset = utf-8 + +[*.{csproj}] +indent_style = space +indent_size = 2 +charset = utf-8 + +# C# files +[*.cs] +max_line_length = 120 +charset = utf-8 + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_style = tab +indent_size = 4 +tab_width = 4 + +# New line preferences +end_of_line = lf +insert_final_newline = true + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = true + +# this. and Me. preferences +dotnet_style_qualification_for_event = false:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_property = false:silent + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = omit_if_default:suggestion + +# Expression-level preferences +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_object_initializer = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:silent +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion + +# Field preferences +dotnet_style_readonly_field = true:suggestion + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:suggestion + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false:none +csharp_style_var_for_built_in_types = false:none +csharp_style_var_when_type_is_apparent = false:suggestion + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_lambdas = true:none +csharp_style_expression_bodied_local_functions = false:none +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_operators = false:none +csharp_style_expression_bodied_properties = true:none + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_switch_expression = true:silent + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_local_function = true:suggestion +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:silent + +# Code-block preferences +csharp_prefer_braces = when_multiline:suggestion +csharp_prefer_simple_using_statement = true:suggestion + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_pattern_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:suggestion + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = false +csharp_new_line_before_else = false +csharp_new_line_before_finally = false +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = anonymous_methods,methods +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = false +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = false + +# Space preferences +csharp_space_after_cast = true +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = true +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = true +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = true +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.types_should_be_pascalcase.symbols = types +dotnet_naming_rule.types_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_or_internal_field_should_be_camelcase.severity = suggestion +dotnet_naming_rule.private_or_internal_field_should_be_camelcase.symbols = private_or_internal_field +dotnet_naming_rule.private_or_internal_field_should_be_camelcase.style = camelcase + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.private_or_internal_field.applicable_kinds = field +dotnet_naming_symbols.private_or_internal_field.applicable_accessibilities = internal, private, private_protected +dotnet_naming_symbols.private_or_internal_field.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascalcase.required_prefix = +dotnet_naming_style.pascalcase.required_suffix = +dotnet_naming_style.pascalcase.word_separator = +dotnet_naming_style.pascalcase.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +dotnet_naming_style.camelcase.required_prefix = +dotnet_naming_style.camelcase.required_suffix = +dotnet_naming_style.camelcase.word_separator = +dotnet_naming_style.camelcase.capitalization = camel_case + +# specify StringComparison for correctness +dotnet_diagnostic.CA1309.severity = error + +# generated code from the project +[*.g.cs] +generated_code = true +dotnet_diagnostic.BI1234.severity = silent + +# Visual Basic files +[*.vb] +max_line_length = 120 +charset = utf-8 + +# Indentation and spacing +indent_style = tab +indent_size = 4 +tab_width = 4 + +# New line preferences +end_of_line = lf +insert_final_newline = true diff --git a/AQTapDemo/AQTapDemoViewController.cs b/AQTapDemo/AQTapDemoViewController.cs index 3fd428db0..99d07a270 100644 --- a/AQTapDemo/AQTapDemoViewController.cs +++ b/AQTapDemo/AQTapDemoViewController.cs @@ -33,10 +33,8 @@ using Foundation; using UIKit; -namespace AQTapDemo -{ - public partial class AQTapDemoViewController : UIViewController - { +namespace AQTapDemo { + public partial class AQTapDemoViewController : UIViewController { CCFWebRadioPlayer player; public AQTapDemoViewController () diff --git a/AQTapDemo/AppDelegate.cs b/AQTapDemo/AppDelegate.cs index 8047efee4..32defd785 100644 --- a/AQTapDemo/AppDelegate.cs +++ b/AQTapDemo/AppDelegate.cs @@ -8,11 +8,9 @@ using Foundation; using UIKit; -namespace AQTapDemo -{ +namespace AQTapDemo { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; AQTapDemoViewController viewController; @@ -28,7 +26,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/AQTapDemo/CCFWebRadioPlayer.cs b/AQTapDemo/CCFWebRadioPlayer.cs index 0d7f65f5e..b90a51ba6 100644 --- a/AQTapDemo/CCFWebRadioPlayer.cs +++ b/AQTapDemo/CCFWebRadioPlayer.cs @@ -34,12 +34,9 @@ using AudioUnit; using System.Diagnostics; -namespace AQTapDemo -{ - public class CCFWebRadioPlayer - { - class ConnectionDelegate : NSUrlConnectionDataDelegate - { +namespace AQTapDemo { + public class CCFWebRadioPlayer { + class ConnectionDelegate : NSUrlConnectionDataDelegate { AudioFileStream audioFileStream; public ConnectionDelegate (AudioFileStream stream) @@ -63,7 +60,7 @@ public override void ReceivedData (NSUrlConnection connection, NSData data) AudioUnit.AudioUnit convertToEffectUnit; AudioUnit.AudioUnit convertFromEffectUnit; AUGraph auGraph; - readonly IntPtr[] preRenderData = new IntPtr[20]; + readonly IntPtr [] preRenderData = new IntPtr [20]; AudioTimeStamp renderTimeStamp; int totalPacketsReceived; @@ -209,7 +206,7 @@ uint TapProc (AudioQueueProcessingTap audioQueueTap, uint inNumberOfFrames, ref throw new ApplicationException (); for (int channel = 0; channel < data.Count; channel++) { - preRenderData[channel] = data [channel].Data; + preRenderData [channel] = data [channel].Data; data.SetData (channel, IntPtr.Zero); } @@ -239,7 +236,7 @@ void StreamPacketsProc (object sender, PacketReceivedEventArgs args) if (audioQueue.AllocateBuffer (args.Bytes, out buffer) != AudioQueueStatus.Ok) throw new ApplicationException (); - buffer->AudioDataByteSize = (uint)args.Bytes; + buffer->AudioDataByteSize = (uint) args.Bytes; buffer->CopyToAudioData (args.InputData, args.Bytes); if (audioQueue.EnqueueBuffer (buffer, args.PacketDescriptions) != AudioQueueStatus.Ok) diff --git a/AUSoundTriggeredPlayingSoundMemoryBased/ExtAudioBufferPlayer.cs b/AUSoundTriggeredPlayingSoundMemoryBased/ExtAudioBufferPlayer.cs index bf3f19c6e..ffbf81023 100644 --- a/AUSoundTriggeredPlayingSoundMemoryBased/ExtAudioBufferPlayer.cs +++ b/AUSoundTriggeredPlayingSoundMemoryBased/ExtAudioBufferPlayer.cs @@ -8,45 +8,40 @@ using UIKit; using Foundation; -namespace AUSoundTriggeredPlayingSoundMemoryBased -{ - class ExtAudioBufferPlayer : IDisposable - { +namespace AUSoundTriggeredPlayingSoundMemoryBased { + class ExtAudioBufferPlayer : IDisposable { const float PlayDurarion = 0.5f; const int FramesToPlay = (int) (SampleRate * PlayDurarion); const int Threshold = 30; - const int SampleRate = 44100; + const int SampleRate = 44100; readonly CFUrl url; - AudioComponent audioComponent; + AudioComponent audioComponent; AudioUnit.AudioUnit audioUnit; - ExtAudioFile extAudioFile; - AudioBuffers buffer; - AudioStreamBasicDescription srcFormat; - AudioStreamBasicDescription dstFormat; - int numberOfChannels; - int triggered; + ExtAudioFile extAudioFile; + AudioBuffers buffer; + AudioStreamBasicDescription srcFormat; + AudioStreamBasicDescription dstFormat; + int numberOfChannels; + int triggered; public long TotalFrames { get; private set; } long currentFrame; - public long CurrentFrame - { - set - { - long frame = value; - frame = Math.Max(frame, 0); + public long CurrentFrame { + set { + long frame = value; + frame = Math.Max (frame, 0); currentFrame = frame % TotalFrames; - } - get - { - return currentFrame; - } - } + } + get { + return currentFrame; + } + } public double SignalLevel { get; private set; } - public ExtAudioBufferPlayer(CFUrl url) + public ExtAudioBufferPlayer (CFUrl url) { this.url = url; @@ -55,7 +50,7 @@ public ExtAudioBufferPlayer(CFUrl url) AudioSession.Resumed += OnAudioSessionResumed; PrepareAudioUnit (); - PrepareExtAudioFile(); + PrepareExtAudioFile (); audioUnit.Initialize (); audioUnit.Start (); @@ -68,7 +63,7 @@ void OnAudioSessionResumed (object sender, EventArgs e) audioUnit.Start (); } - AudioUnitStatus RenderCallback(AudioUnitRenderActionFlags actionFlags, AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, AudioBuffers data) + AudioUnitStatus RenderCallback (AudioUnitRenderActionFlags actionFlags, AudioTimeStamp timeStamp, uint busNumber, uint numberFrames, AudioBuffers data) { // getting microphone input signal audioUnit.Render (ref actionFlags, timeStamp, 1, numberFrames, data); @@ -80,26 +75,26 @@ AudioUnitStatus RenderCallback(AudioUnitRenderActionFlags actionFlags, AudioTime // Getting signal level // https://en.wikipedia.org/wiki/Root_mean_square float sqrSum = 0; - for (int j = 0; j < numberFrames; j++) { - float v = Marshal.ReadInt16(outL, j * sizeof(Int16)); + for (int j = 0; j < numberFrames; j++) { + float v = Marshal.ReadInt16 (outL, j * sizeof (Int16)); sqrSum += (v * v); } - SignalLevel = (float)Math.Sqrt (sqrSum / numberFrames); + SignalLevel = (float) Math.Sqrt (sqrSum / numberFrames); if (triggered <= 0 && SignalLevel > Threshold) triggered = FramesToPlay; // playing sound unsafe { - var outLPtr = (int*)outL.ToPointer (); - var outRPtr = (int*)outR.ToPointer (); + var outLPtr = (int*) outL.ToPointer (); + var outRPtr = (int*) outR.ToPointer (); for (int i = 0; i < numberFrames; i++) { triggered = Math.Max (0, triggered - 1); if (triggered > 0) { - var buf0 = (int*)buffer [0].Data; - var buf1 = (int*)buffer [numberOfChannels - 1].Data; + var buf0 = (int*) buffer [0].Data; + var buf1 = (int*) buffer [numberOfChannels - 1].Data; ++CurrentFrame; *outLPtr++ = buf0 [currentFrame]; @@ -115,37 +110,36 @@ AudioUnitStatus RenderCallback(AudioUnitRenderActionFlags actionFlags, AudioTime return AudioUnitStatus.NoError; } - void PrepareExtAudioFile() - { - extAudioFile = ExtAudioFile.OpenUrl(url); + void PrepareExtAudioFile () + { + extAudioFile = ExtAudioFile.OpenUrl (url); CheckValue (extAudioFile, "ExtAudioFile.OpenUrl failed"); srcFormat = extAudioFile.FileDataFormat; // This is how you say,“When you convert the data, this is the format I’d like to receive.” // The client data format must be PCM. In other words, you can’t use a single ExtAudioFile to convert between two compressed formats. - extAudioFile.ClientDataFormat = dstFormat; + extAudioFile.ClientDataFormat = dstFormat; - // getting total frame + // getting total frame TotalFrames = extAudioFile.FileLengthFrames; - // Allocating AudioBufferList - buffer = new AudioBuffers(srcFormat.ChannelsPerFrame); - for (int i = 0; i < buffer.Count; ++i) - { - int size = (int)(sizeof(int) * TotalFrames); - buffer.SetData(i, Marshal.AllocHGlobal(size), size); - } + // Allocating AudioBufferList + buffer = new AudioBuffers (srcFormat.ChannelsPerFrame); + for (int i = 0; i < buffer.Count; ++i) { + int size = (int) (sizeof (int) * TotalFrames); + buffer.SetData (i, Marshal.AllocHGlobal (size), size); + } numberOfChannels = srcFormat.ChannelsPerFrame; - // Reading all frame into the buffer - ExtAudioFileError status; - extAudioFile.Read((uint)TotalFrames, buffer, out status); - if (status != ExtAudioFileError.OK) - throw new ApplicationException(); - } + // Reading all frame into the buffer + ExtAudioFileError status; + extAudioFile.Read ((uint) TotalFrames, buffer, out status); + if (status != ExtAudioFileError.OK) + throw new ApplicationException (); + } - void PrepareAudioUnit() + void PrepareAudioUnit () { // All iPhones and iPads have microphones, but early iPod touches did not if (!AudioSession.AudioInputAvailable) { @@ -155,16 +149,16 @@ void PrepareAudioUnit() } // Getting AudioComponent Remote output - audioComponent = AudioComponent.FindComponent(AudioTypeOutput.Remote); + audioComponent = AudioComponent.FindComponent (AudioTypeOutput.Remote); CheckValue (audioComponent); // creating an audio unit instance - audioUnit = new AudioUnit.AudioUnit(audioComponent); + audioUnit = new AudioUnit.AudioUnit (audioComponent); AudioUnitStatus status; - status = audioUnit.SetEnableIO(true, AudioUnitScopeType.Input, 1); + status = audioUnit.SetEnableIO (true, AudioUnitScopeType.Input, 1); CheckStatus (status); - status = audioUnit.SetEnableIO(true, AudioUnitScopeType.Output, 0); + status = audioUnit.SetEnableIO (true, AudioUnitScopeType.Output, 0); CheckStatus (status); dstFormat = new AudioStreamBasicDescription { @@ -178,10 +172,10 @@ void PrepareAudioUnit() BitsPerChannel = 16 }; - audioUnit.SetAudioFormat(dstFormat, AudioUnitScopeType.Input, 0); - audioUnit.SetAudioFormat(dstFormat, AudioUnitScopeType.Output, 1); + audioUnit.SetAudioFormat (dstFormat, AudioUnitScopeType.Input, 0); + audioUnit.SetAudioFormat (dstFormat, AudioUnitScopeType.Output, 1); - status = audioUnit.SetRenderCallback(RenderCallback, AudioUnitScopeType.Input, 0); + status = audioUnit.SetRenderCallback (RenderCallback, AudioUnitScopeType.Input, 0); CheckStatus (status); } @@ -203,11 +197,11 @@ void CheckStatus (AudioUnitStatus status) throw new InvalidProgramException (); } - public void Dispose() - { - audioUnit.Stop(); - audioUnit.Dispose(); - extAudioFile.Dispose(); - } - } + public void Dispose () + { + audioUnit.Stop (); + audioUnit.Dispose (); + extAudioFile.Dispose (); + } + } } diff --git a/AUSoundTriggeredPlayingSoundMemoryBased/Main.cs b/AUSoundTriggeredPlayingSoundMemoryBased/Main.cs index 36cc5d00e..3dc537ed6 100644 --- a/AUSoundTriggeredPlayingSoundMemoryBased/Main.cs +++ b/AUSoundTriggeredPlayingSoundMemoryBased/Main.cs @@ -1,25 +1,22 @@ using Foundation; using UIKit; -namespace AUSoundTriggeredPlayingSoundMemoryBased -{ - public class Application - { - static void Main (string[] args) +namespace AUSoundTriggeredPlayingSoundMemoryBased { + public class Application { + static void Main (string [] args) { UIApplication.Main (args); } } // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // If you have defined a view, add it here: // window.AddSubview (navigationController.View); - window.RootViewController = new MainView (); + window.RootViewController = new MainView (); window.MakeKeyAndVisible (); return true; diff --git a/AUSoundTriggeredPlayingSoundMemoryBased/MainView.cs b/AUSoundTriggeredPlayingSoundMemoryBased/MainView.cs index dde5fad39..81d7ef476 100644 --- a/AUSoundTriggeredPlayingSoundMemoryBased/MainView.cs +++ b/AUSoundTriggeredPlayingSoundMemoryBased/MainView.cs @@ -3,30 +3,28 @@ using Foundation; using UIKit; -namespace AUSoundTriggeredPlayingSoundMemoryBased -{ - public partial class MainView : UIViewController - { - ExtAudioBufferPlayer player; - NSTimer timer; - bool isTimerAvailable; - - public MainView() : base("MainView", null) - { - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - var url = CFUrl.FromFile("loop_stereo.aif"); - player = new ExtAudioBufferPlayer(url); - - // setting audio session - _slider.ValueChanged += OnSliderValueChanged; - _slider.MaxValue = player.TotalFrames; - - isTimerAvailable = true; +namespace AUSoundTriggeredPlayingSoundMemoryBased { + public partial class MainView : UIViewController { + ExtAudioBufferPlayer player; + NSTimer timer; + bool isTimerAvailable; + + public MainView () : base ("MainView", null) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var url = CFUrl.FromFile ("loop_stereo.aif"); + player = new ExtAudioBufferPlayer (url); + + // setting audio session + _slider.ValueChanged += OnSliderValueChanged; + _slider.MaxValue = player.TotalFrames; + + isTimerAvailable = true; timer = NSTimer.CreateRepeatingTimer (TimeSpan.FromMilliseconds (100), _ => { if (isTimerAvailable) { @@ -37,15 +35,15 @@ public override void ViewDidLoad() } ); - NSRunLoop.Current.AddTimer(timer, NSRunLoopMode.Default); - } + NSRunLoop.Current.AddTimer (timer, NSRunLoopMode.Default); + } - void OnSliderValueChanged(object sender, EventArgs e) - { - isTimerAvailable = false; - player.CurrentFrame = (long)_slider.Value; - isTimerAvailable = true; - } - } + void OnSliderValueChanged (object sender, EventArgs e) + { + isTimerAvailable = false; + player.CurrentFrame = (long) _slider.Value; + isTimerAvailable = true; + } + } } diff --git a/AUSoundTriggeredPlayingSoundMemoryBased/Properties/AssemblyInfo.cs b/AUSoundTriggeredPlayingSoundMemoryBased/Properties/AssemblyInfo.cs index 5a8b6798f..9383e994d 100644 --- a/AUSoundTriggeredPlayingSoundMemoryBased/Properties/AssemblyInfo.cs +++ b/AUSoundTriggeredPlayingSoundMemoryBased/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 -[assembly: AssemblyTitle("Monotouch_SoundRecording_vs")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Monotouch_SoundRecording_vs")] -[assembly: AssemblyCopyright("Copyright © 2010")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("Monotouch_SoundRecording_vs")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("Monotouch_SoundRecording_vs")] +[assembly: AssemblyCopyright ("Copyright © 2010")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です -[assembly: Guid("0c0a16cc-33f1-4622-b9c9-f569c46824ab")] +[assembly: Guid ("0c0a16cc-33f1-4622-b9c9-f569c46824ab")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // @@ -32,5 +32,5 @@ // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionDebugView.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionDebugView.cs index f79b550a7..ff0b02c89 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionDebugView.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionDebugView.cs @@ -10,10 +10,8 @@ using ObjCRuntime; using UIKit; -namespace AVCompositionDebugVieweriOS -{ - public partial class APLCompositionDebugView : UIView - { +namespace AVCompositionDebugVieweriOS { + public partial class APLCompositionDebugView : UIView { private const int GapAfterRows = 4; private const int IdealRowHeight = 40; private const int BannerHeight = 20; @@ -89,12 +87,12 @@ private void ProcessVideoComposition (AVMutableVideoComposition videoComposition while (layerInstruction.GetOpacityRamp (startTime, ref startOpacity, ref endOpacity, ref timeRange)) { if (CMTime.Compare (startTime, CMTime.Zero) == 0 && - CMTime.Compare (timeRange.Start, CMTime.Zero) == 1) { - ramp.Add (new CGPoint ((float)timeRange.Start.Seconds, startOpacity)); + CMTime.Compare (timeRange.Start, CMTime.Zero) == 1) { + ramp.Add (new CGPoint ((float) timeRange.Start.Seconds, startOpacity)); } CMTime endTime = CMTime.Add (timeRange.Start, timeRange.Duration); - ramp.Add (new CGPoint ((float)endTime.Seconds, endOpacity)); + ramp.Add (new CGPoint ((float) endTime.Seconds, endOpacity)); startTime = CMTime.Add (timeRange.Start, timeRange.Duration); } @@ -127,20 +125,20 @@ private void ProcessAudioMix (AVMutableAudioMix audioMix) while (input.GetVolumeRamp (startTime, ref startVolume, ref endVolume, ref timeRange)) { if (CMTime.Compare (startTime, CMTime.Zero) == 0 && - CMTime.Compare (timeRange.Start, CMTime.Zero) == 1) { + CMTime.Compare (timeRange.Start, CMTime.Zero) == 1) { ramp.Add (new CGPoint (0f, 1f)); - ramp.Add (new CGPoint ((float)timeRange.Start.Seconds, startVolume)); + ramp.Add (new CGPoint ((float) timeRange.Start.Seconds, startVolume)); } - ramp.Add (new CGPoint ((float)timeRange.Start.Seconds, startVolume)); + ramp.Add (new CGPoint ((float) timeRange.Start.Seconds, startVolume)); CMTime endTime = CMTime.Add (timeRange.Start, timeRange.Duration); - ramp.Add (new CGPoint ((float)endTime.Seconds, endVolume)); + ramp.Add (new CGPoint ((float) endTime.Seconds, endVolume)); startTime = CMTime.Add (timeRange.Start, timeRange.Duration); } if (CMTime.Compare (startTime, duration) == -1) { - ramp.Add (new CGPoint ((float)duration.Seconds, endVolume)); + ramp.Add (new CGPoint ((float) duration.Seconds, endVolume)); } mixTracks.Add (ramp); @@ -179,11 +177,11 @@ public override void Draw (CGRect rect) float rowHeight = IdealRowHeight; if (numRows > 0) { - float maxRowHeight = (float)(rect.Size.Height - totalBannerHeight) / numRows; + float maxRowHeight = (float) (rect.Size.Height - totalBannerHeight) / numRows; rowHeight = Math.Min (rowHeight, maxRowHeight); } - float runningTop = (float)rect.Y; + float runningTop = (float) rect.Y; var bannerRect = rect; bannerRect.Height = BannerHeight; bannerRect.Y = runningTop; @@ -193,16 +191,16 @@ public override void Draw (CGRect rect) rowRect.X += LeftInsetToMatchTimeSlider; rowRect.Width -= (LeftInsetToMatchTimeSlider + RightInsetToMatchTimeSlider); - compositionRectWidth = (float)rowRect.Size.Width; + compositionRectWidth = (float) rowRect.Size.Width; if (duration.Seconds != 0) - scaledDurationToWidth = compositionRectWidth / (float)duration.Seconds; + scaledDurationToWidth = compositionRectWidth / (float) duration.Seconds; else scaledDurationToWidth = 0; if (compositionTracks != null) { DrawCompositionTracks (bannerRect, rowRect, ref runningTop); - DrawMarker (rowRect, (float)rect.Y); + DrawMarker (rowRect, (float) rect.Y); } if (videoCompositionStages != null) @@ -220,13 +218,13 @@ private void DrawCompositionTracks (CGRect bannerRect, CGRect rowRect, ref float NSString compositionTitle = new NSString ("AVComposition"); compositionTitle.DrawString (bannerRect, UIFont.PreferredCaption1); - runningTop += (float)bannerRect.Height; + runningTop += (float) bannerRect.Height; foreach (List track in compositionTracks) { rowRect.Y = runningTop; CGRect segmentRect = rowRect; foreach (APLCompositionTrackSegmentInfo segment in track) { - segmentRect.Width = (float)segment.TimeRange.Duration.Seconds * scaledDurationToWidth; + segmentRect.Width = (float) segment.TimeRange.Duration.Seconds * scaledDurationToWidth; if (segment.Empty) { context.SetFillColor (0.00f, 0.00f, 0.00f, 1.00f); @@ -252,7 +250,7 @@ private void DrawCompositionTracks (CGRect bannerRect, CGRect rowRect, ref float segmentRect.X += segmentRect.Width; } - runningTop += (float)rowRect.Height; + runningTop += (float) rowRect.Height; } runningTop += GapAfterRows; } @@ -265,13 +263,13 @@ private void DrawAudioMixTracks (CGRect bannerRect, CGRect rowRect, ref float ru NSString compositionTitle = new NSString ("AVAudioMix"); compositionTitle.DrawString (bannerRect, UIFont.PreferredCaption1); - runningTop += (float)bannerRect.Height; + runningTop += (float) bannerRect.Height; foreach (List mixTrack in audioMixTracks) { rowRect.Y = runningTop; CGRect rampRect = rowRect; - rampRect.Width = (float)duration.Seconds * scaledDurationToWidth; + rampRect.Width = (float) duration.Seconds * scaledDurationToWidth; rampRect = rampRect.Inset (3f, 3f); context.SetFillColor (0.55f, 0.02f, 0.02f, 1.00f); // darker red @@ -292,8 +290,8 @@ private void DrawAudioMixTracks (CGRect bannerRect, CGRect rowRect, ref float ru pointInRow.X = rampRect.X + timeVolumePoint.X * scaledDurationToWidth; pointInRow.Y = rampRect.Y + (0.9f - 0.8f * timeVolumePoint.Y) * rampRect.Height; - pointInRow.X = (float)Math.Max (pointInRow.X, rampRect.GetMinX ()); - pointInRow.X = (float)Math.Min (pointInRow.X, rampRect.GetMaxX ()); + pointInRow.X = (float) Math.Max (pointInRow.X, rampRect.GetMinX ()); + pointInRow.X = (float) Math.Min (pointInRow.X, rampRect.GetMaxX ()); if (firstPoint) { context.MoveTo (pointInRow.X, pointInRow.Y); @@ -303,7 +301,7 @@ private void DrawAudioMixTracks (CGRect bannerRect, CGRect rowRect, ref float ru } } context.StrokePath (); - runningTop += (float)rowRect.Height; + runningTop += (float) rowRect.Height; } runningTop += GapAfterRows; @@ -312,7 +310,7 @@ private void DrawAudioMixTracks (CGRect bannerRect, CGRect rowRect, ref float ru private void DrawMarker (CGRect rowRect, float position) { if (Layer.Sublayers != null) { - Layer.Sublayers = new CALayer[0]; + Layer.Sublayers = new CALayer [0]; } var visibleRect = Layer.Bounds; @@ -371,12 +369,12 @@ private void DrawVideoCompositionTracks (CGRect bannerRect, CGRect rowRect, ref var compositionTitle = new NSString ("AVComposition"); compositionTitle.DrawString (bannerRect, UIFont.PreferredCaption1); - runningTop += (float)bannerRect.Height; + runningTop += (float) bannerRect.Height; rowRect.Y = runningTop; CGRect stageRect = rowRect; foreach (APLVideoCompositionStageInfo stage in videoCompositionStages) { - stageRect.Width = (float)stage.TimeRange.Duration.Seconds * scaledDurationToWidth; + stageRect.Width = (float) stage.TimeRange.Duration.Seconds * scaledDurationToWidth; int layerCount = stage.LayerNames.Count; CGRect layerRect = stageRect; @@ -411,7 +409,7 @@ private void DrawVideoCompositionTracks (CGRect bannerRect, CGRect rowRect, ref if (rampArray.Count > 0) { CGRect rampRect = bufferRect; - rampRect.Width = (float)duration.Seconds * scaledDurationToWidth; + rampRect.Width = (float) duration.Seconds * scaledDurationToWidth; rampRect = rampRect.Inset (3f, 3f); context.BeginPath (); @@ -423,11 +421,11 @@ private void DrawVideoCompositionTracks (CGRect bannerRect, CGRect rowRect, ref CGPoint timeVolumePoint = point; CGPoint pointInRow = new CGPoint (); - pointInRow.X = (float)HorizontalPositionForTime (CMTime.FromSeconds (timeVolumePoint.X, 1)) - 9.0f; + pointInRow.X = (float) HorizontalPositionForTime (CMTime.FromSeconds (timeVolumePoint.X, 1)) - 9.0f; pointInRow.Y = rampRect.Y + (0.9f - 0.8f * timeVolumePoint.Y) * rampRect.Height; - pointInRow.X = (float)Math.Max (pointInRow.X, rampRect.GetMinX ()); - pointInRow.X = (float)Math.Min (pointInRow.X, rampRect.GetMaxX ()); + pointInRow.X = (float) Math.Max (pointInRow.X, rampRect.GetMinX ()); + pointInRow.X = (float) Math.Min (pointInRow.X, rampRect.GetMaxX ()); if (firstPoint) { context.MoveTo (pointInRow.X, pointInRow.Y); @@ -441,7 +439,7 @@ private void DrawVideoCompositionTracks (CGRect bannerRect, CGRect rowRect, ref } stageRect.X += stageRect.Width; } - runningTop += (float)rowRect.Height; + runningTop += (float) rowRect.Height; runningTop += GapAfterRows; } @@ -461,13 +459,13 @@ private int GetNumberOfRows () int nummerOfRows = 0; if (compositionTracks != null) - nummerOfRows += (int)compositionTracks.Count; + nummerOfRows += (int) compositionTracks.Count; if (audioMixTracks != null) - nummerOfRows += (int)audioMixTracks.Count; + nummerOfRows += (int) audioMixTracks.Count; if (videoCompositionStages != null) - nummerOfRows += (int)videoCompositionStages.Count; + nummerOfRows += (int) videoCompositionStages.Count; return nummerOfRows; } diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionTrackSegmentInfo.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionTrackSegmentInfo.cs index d10da9323..790d75632 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionTrackSegmentInfo.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLCompositionTrackSegmentInfo.cs @@ -7,10 +7,8 @@ using CoreMedia; using System.Collections.Generic; -namespace AVCompositionDebugVieweriOS -{ - public class APLCompositionTrackSegmentInfo : NSObject - { +namespace AVCompositionDebugVieweriOS { + public class APLCompositionTrackSegmentInfo : NSObject { public CMTimeRange TimeRange { get; set; } public bool Empty { get; set; } diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLPlayerView.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLPlayerView.cs index 8081f2a4b..631d20939 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLPlayerView.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLPlayerView.cs @@ -6,14 +6,12 @@ using ObjCRuntime; using UIKit; -namespace AVCompositionDebugVieweriOS -{ - public partial class APLPlayerView : UIView - { +namespace AVCompositionDebugVieweriOS { + public partial class APLPlayerView : UIView { [Export ("layerClass")] public static Class LayerClass () { - return new Class (typeof(AVPlayerLayer)); + return new Class (typeof (AVPlayerLayer)); } public AVPlayer Player { diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLVideoCompositionStageInfo.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLVideoCompositionStageInfo.cs index f94eabb11..15b5d806f 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLVideoCompositionStageInfo.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLVideoCompositionStageInfo.cs @@ -9,10 +9,8 @@ using Foundation; using UIKit; -namespace AVCompositionDebugVieweriOS -{ - public class APLVideoCompositionStageInfo : NSObject - { +namespace AVCompositionDebugVieweriOS { + public class APLVideoCompositionStageInfo : NSObject { public CMTimeRange TimeRange { get; set; } public List LayerNames { get; set; } public Dictionary> OpacityRamps { get; set; } diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLViewController.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLViewController.cs index 51c5f0388..1f439018d 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLViewController.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/APLViewController.cs @@ -7,10 +7,8 @@ using Foundation; using UIKit; -namespace AVCompositionDebugVieweriOS -{ - public partial class APLViewController : UIViewController - { +namespace AVCompositionDebugVieweriOS { + public partial class APLViewController : UIViewController { /* nanoseconds per second */ private const int NSEC_PER_SEC = 1000000000; public static NSString AVCustomEditPlayerViewControllerStatusObservationContext = new NSString ("AVCustomEditPlayerViewControllerStatusObservationContext"); @@ -120,16 +118,16 @@ private void ScrubToSliderValue (float currentValue) { double duration = PlayerItemDuration.Seconds; - float width = (float)scrubber.Bounds.Width; + float width = (float) scrubber.Bounds.Width; double time = duration * currentValue; double tolerance = 1.0f * duration / width; ScrubIsInFlight = true; Player.Seek (CMTime.FromSeconds (time, NSEC_PER_SEC), - CMTime.FromSeconds (tolerance, NSEC_PER_SEC), - CMTime.FromSeconds (tolerance, NSEC_PER_SEC), - HandleScrubToSliderValueComplete + CMTime.FromSeconds (tolerance, NSEC_PER_SEC), + CMTime.FromSeconds (tolerance, NSEC_PER_SEC), + HandleScrubToSliderValueComplete ); } @@ -172,7 +170,7 @@ private void SetupEditingAndPlayback () var dispatchGroup = DispatchGroup.Create (); - string[] assetKeysToLoadandTest = new string[] { + string [] assetKeysToLoadandTest = new string [] { "tracks", "duration", "composable" @@ -184,7 +182,7 @@ private void SetupEditingAndPlayback () dispatchGroup.DispatchAsync (DispatchQueue.MainQueue, SynchronizeWithEditor); } - private void LoadAsset (AVUrlAsset asset, string[] assetKeysToLoadandTest, DispatchGroup dispatchGroup) + private void LoadAsset (AVUrlAsset asset, string [] assetKeysToLoadandTest, DispatchGroup dispatchGroup) { dispatchGroup.Enter (); asset.LoadValuesAsynchronously (assetKeysToLoadandTest, () => { @@ -244,8 +242,8 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio { var ch = new NSObservedChange (change); if (context == AVCustomEditPlayerViewControllerRateObservationContext.Handle) { - float newRate = ((NSNumber)ch.NewValue).FloatValue; - NSNumber oldRateNum = (NSNumber)ch.OldValue; + float newRate = ((NSNumber) ch.NewValue).FloatValue; + NSNumber oldRateNum = (NSNumber) ch.OldValue; if (oldRateNum != null && newRate != oldRateNum.FloatValue) { UpdatePlayPauseButton (); UpdateScrubber (); @@ -300,7 +298,7 @@ private void AddTimeObserverToPlayer () double duration = PlayerItemDuration.Seconds; if (duration != 0) { - float width = (float)scrubber.Bounds.Width; + float width = (float) scrubber.Bounds.Width; double interval = 0.5 * duration / width; if (interval > 1.0) { @@ -308,11 +306,12 @@ private void AddTimeObserverToPlayer () } timeObserver = Player.AddPeriodicTimeObserver (CMTime.FromSeconds (interval, NSEC_PER_SEC), - DispatchQueue.MainQueue, - delegate { - UpdateScrubber (); - UpdateTimeLabel (); - }); + DispatchQueue.MainQueue, + delegate + { + UpdateScrubber (); + UpdateTimeLabel (); + }); } } @@ -331,7 +330,7 @@ private void UpdateTimeLabel () if (double.IsInfinity (secondes)) secondes = 0; - int secondsInt = (int)Math.Round (secondes); + int secondsInt = (int) Math.Round (secondes); int minutes = secondsInt / 60; secondsInt -= minutes * 60; @@ -345,7 +344,7 @@ private void UpdateScrubber () double duration = PlayerItemDuration.Seconds; if (!double.IsInfinity (duration)) { double time = Player.CurrentTime.Seconds; - scrubber.Value = (float)(time / duration); + scrubber.Value = (float) (time / duration); } else scrubber.Value = 0.0f; } @@ -369,7 +368,7 @@ private void SynchronizePlayerWithEditor () if (PlayerItem != null) { PlayerItem.SeekingWaitsForVideoCompositionRendering = true; PlayerItem.AddObserver (this, new NSString ("status"), NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, - AVCustomEditPlayerViewControllerStatusObservationContext.Handle); + AVCustomEditPlayerViewControllerStatusObservationContext.Handle); playToEndObserver = AVPlayerItem.Notifications.ObserveDidPlayToEndTime (PlayToEndNotificationHandler); } diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/AppDelegate.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/AppDelegate.cs index 8875344a7..bcbb8f731 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/AppDelegate.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace AVCompositionDebugVieweriOS -{ +namespace AVCompositionDebugVieweriOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/Main.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/Main.cs index 295ea8a5e..f235e8299 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/Main.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace AVCompositionDebugVieweriOS -{ - public class Application - { +namespace AVCompositionDebugVieweriOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/SimpleEditor.cs b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/SimpleEditor.cs index e984a3cc2..3f3a663b6 100644 --- a/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/SimpleEditor.cs +++ b/AVCompositionDebugVieweriOS/AVCompositionDebugVieweriOS/SimpleEditor.cs @@ -6,10 +6,8 @@ using AVFoundation; using CoreGraphics; -namespace AVCompositionDebugVieweriOS -{ - public class SimpleEditor : NSObject - { +namespace AVCompositionDebugVieweriOS { + public class SimpleEditor : NSObject { public List Clips { get; set; } public List ClipTimeRanges { get; set; } @@ -29,22 +27,21 @@ public AVMutableComposition Composition { public AVMutableVideoComposition VideoComposition { get; set; } public AVMutableAudioMix AudioMix { get; set; } - public AVPlayerItem PlayerItem - { + public AVPlayerItem PlayerItem { get { AVPlayerItem playerItem = AVPlayerItem.FromAsset (Composition); - playerItem.VideoComposition = VideoComposition; + playerItem.VideoComposition = VideoComposition; playerItem.AudioMix = AudioMix; return playerItem; } } - public SimpleEditor () : base() + public SimpleEditor () : base () { } - private void BuildTransitionComposition(AVMutableComposition composition, AVMutableVideoComposition videoComposition, AVMutableAudioMix audioMix) + private void BuildTransitionComposition (AVMutableComposition composition, AVMutableVideoComposition videoComposition, AVMutableAudioMix audioMix) { CMTime nextClipStartTime = CMTime.Zero; int clipsCount = Clips.Count; @@ -56,10 +53,10 @@ private void BuildTransitionComposition(AVMutableComposition composition, AVMuta for (int i = 0; i < clipsCount; i++) { NSValue clipTimeRange = ClipTimeRanges [i]; - if(clipTimeRange != null) { + if (clipTimeRange != null) { CMTime halfClipDuration = clipTimeRange.CMTimeRangeValue.Duration; halfClipDuration.TimeScale *= 2; - transitionDuration = CMTime.GetMinimum(transitionDuration,halfClipDuration); + transitionDuration = CMTime.GetMinimum (transitionDuration, halfClipDuration); } } @@ -73,11 +70,11 @@ private void BuildTransitionComposition(AVMutableComposition composition, AVMuta composition.AddMutableTrack (AVMediaType.Audio, 0) }; - var passThroughTimeRanges = new CMTimeRange[clipsCount]; - var transitionTimeRanges = new CMTimeRange[clipsCount]; + var passThroughTimeRanges = new CMTimeRange [clipsCount]; + var transitionTimeRanges = new CMTimeRange [clipsCount]; // Place clips into alternating video & audio tracks in composition, overlapped by transitionDuration. - for(int i = 0; i < clipsCount; i++) { + for (int i = 0; i < clipsCount; i++) { int alternatingIndex = i % 2; AVAsset asset = Clips [i]; NSValue clipTimeRange = ClipTimeRanges [i]; @@ -91,29 +88,27 @@ private void BuildTransitionComposition(AVMutableComposition composition, AVMuta } NSError error; AVAssetTrack clipVideoTrack = asset.TracksWithMediaType (AVMediaType.Video) [0]; - compositionVideoTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipVideoTrack, nextClipStartTime,out error); + compositionVideoTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipVideoTrack, nextClipStartTime, out error); AVAssetTrack clipAudioTrack = asset.TracksWithMediaType (AVMediaType.Audio) [0]; - compositionAudioTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipAudioTrack, nextClipStartTime,out error); + compositionAudioTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipAudioTrack, nextClipStartTime, out error); // Remember the time range in which this clip should pass through. // First clip ends with a transition. // Second clip begins with a transition. // Exclude that transition from the pass through time ranges - CMTimeRange timeRange = new CMTimeRange(); + CMTimeRange timeRange = new CMTimeRange (); timeRange.Start = nextClipStartTime; timeRange.Duration = timeRangeInAsset.Duration; passThroughTimeRanges [i] = timeRange; - if (i > 0) - { - passThroughTimeRanges[i].Start = CMTime.Add(passThroughTimeRanges[i].Start,transitionDuration); - passThroughTimeRanges[i].Duration = CMTime.Subtract(passThroughTimeRanges[i].Duration,transitionDuration); + if (i > 0) { + passThroughTimeRanges [i].Start = CMTime.Add (passThroughTimeRanges [i].Start, transitionDuration); + passThroughTimeRanges [i].Duration = CMTime.Subtract (passThroughTimeRanges [i].Duration, transitionDuration); } - if(i + 1 < clipsCount) - { - passThroughTimeRanges[i].Duration = CMTime.Subtract(passThroughTimeRanges[i].Duration,transitionDuration); + if (i + 1 < clipsCount) { + passThroughTimeRanges [i].Duration = CMTime.Subtract (passThroughTimeRanges [i].Duration, transitionDuration); } // The end of this clip will overlap the start of the next by transitionDuration. @@ -122,11 +117,9 @@ private void BuildTransitionComposition(AVMutableComposition composition, AVMuta nextClipStartTime = CMTime.Subtract (nextClipStartTime, transitionDuration); // Remember the time range for the transition to the next item - if(i + 1 < clipsCount) - { - transitionTimeRanges [i] = new CMTimeRange () - { - Start = nextClipStartTime, + if (i + 1 < clipsCount) { + transitionTimeRanges [i] = new CMTimeRange () { + Start = nextClipStartTime, Duration = transitionDuration }; @@ -137,19 +130,17 @@ private void BuildTransitionComposition(AVMutableComposition composition, AVMuta List trackMixArray = new List (); // Set up the video composition if we are to perform crossfade transitions between clips. - for (int i = 0; i < clipsCount; i++) - { + for (int i = 0; i < clipsCount; i++) { int alternatingIndex = i % 2; AVMutableVideoCompositionInstruction passThroughInstructions = AVMutableVideoCompositionInstruction.Create () as AVMutableVideoCompositionInstruction; passThroughInstructions.TimeRange = passThroughTimeRanges [i]; AVMutableVideoCompositionLayerInstruction passThroughLayerInstructions = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [alternatingIndex]); - passThroughInstructions.LayerInstructions = new AVVideoCompositionLayerInstruction[] { passThroughLayerInstructions }; + passThroughInstructions.LayerInstructions = new AVVideoCompositionLayerInstruction [] { passThroughLayerInstructions }; instructions.Add (passThroughInstructions); - if (i + 1 < clipsCount) - { + if (i + 1 < clipsCount) { var transitionInstruction = AVMutableVideoCompositionInstruction.Create () as AVMutableVideoCompositionInstruction; transitionInstruction.TimeRange = transitionTimeRanges [i]; var fromLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [alternatingIndex]); @@ -157,33 +148,32 @@ private void BuildTransitionComposition(AVMutableComposition composition, AVMuta // Fade in the toLayer by setting a ramp from 0.0 to 1.0. toLayer.SetOpacityRamp (0.0f, 1.0f, transitionTimeRanges [i]); - transitionInstruction.LayerInstructions = new AVVideoCompositionLayerInstruction[] + transitionInstruction.LayerInstructions = new AVVideoCompositionLayerInstruction [] { toLayer, fromLayer, }; - instructions.Add(transitionInstruction); + instructions.Add (transitionInstruction); // Add AudioMix to fade in the volume ramps - var trackMix = AVMutableAudioMixInputParameters.FromTrack(compositionAudioTracks[0]); - trackMix.SetVolumeRamp (1f, 0f, transitionTimeRanges[0]); + var trackMix = AVMutableAudioMixInputParameters.FromTrack (compositionAudioTracks [0]); + trackMix.SetVolumeRamp (1f, 0f, transitionTimeRanges [0]); trackMixArray.Add (trackMix); - trackMix = AVMutableAudioMixInputParameters.FromTrack (compositionAudioTracks[1]); - trackMix.SetVolumeRamp (0f, 1f, transitionTimeRanges[0]); - trackMix.SetVolumeRamp (1f, 1f, passThroughTimeRanges[1]); + trackMix = AVMutableAudioMixInputParameters.FromTrack (compositionAudioTracks [1]); + trackMix.SetVolumeRamp (0f, 1f, transitionTimeRanges [0]); + trackMix.SetVolumeRamp (1f, 1f, passThroughTimeRanges [1]); trackMixArray.Add (trackMix); } } videoComposition.Instructions = instructions.ToArray (); - audioMix.InputParameters = trackMixArray.ToArray(); + audioMix.InputParameters = trackMixArray.ToArray (); } - public void BuildCompositionObjects(Boolean playBack) + public void BuildCompositionObjects (Boolean playBack) { - if (Clips == null || Clips.Count == 0) - { + if (Clips == null || Clips.Count == 0) { Composition = null; VideoComposition = null; AudioMix = null; @@ -198,8 +188,7 @@ public void BuildCompositionObjects(Boolean playBack) composition1.NaturalSize = videoSize; BuildTransitionComposition (composition1, videoComposition1, audioMix); - if (videoComposition1 != null) - { + if (videoComposition1 != null) { videoComposition1.FrameDuration = new CMTime (1, 30); videoComposition1.RenderSize = videoSize; } diff --git a/AVCustomEdit/AVCustomEdit/AppDelegate.cs b/AVCustomEdit/AVCustomEdit/AppDelegate.cs index e8ad2e5da..b896f933a 100644 --- a/AVCustomEdit/AVCustomEdit/AppDelegate.cs +++ b/AVCustomEdit/AVCustomEdit/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace AVCustomEdit -{ +namespace AVCustomEdit { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -18,4 +16,4 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } } -} \ No newline at end of file +} diff --git a/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositionInstruction.cs b/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositionInstruction.cs index 8d72ea9e6..8670ce8b9 100644 --- a/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositionInstruction.cs +++ b/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositionInstruction.cs @@ -3,78 +3,73 @@ using Foundation; using ObjCRuntime; -namespace AVCustomEdit -{ - public class CustomVideoCompositionInstruction : AVVideoCompositionInstruction - { - private readonly NSNumber[] requiredSourceTrackIds; - private readonly bool enablePostProcessing; - private readonly int passthroughTrackId; - private readonly bool containsTweening; - private readonly CMTimeRange timeRange; - - public CustomVideoCompositionInstruction() : base() { } - - public CustomVideoCompositionInstruction(int passthroughTrackId, CMTimeRange timeRange) : base() - { - this.passthroughTrackId = passthroughTrackId; - this.requiredSourceTrackIds = null; - this.timeRange = timeRange; - this.containsTweening = false; - this.enablePostProcessing = false; - } - - public CustomVideoCompositionInstruction(NSNumber[] sourceTracksIds, CMTimeRange timeRange) : base() - { - this.requiredSourceTrackIds = sourceTracksIds; - this.passthroughTrackId = 0; - this.timeRange = timeRange; - this.containsTweening = true; - this.enablePostProcessing = false; - } - - public int ForegroundTrackId { get; set; } - - public int BackgroundTrackId { get; set; } - - public override int PassthroughTrackID => this.passthroughTrackId; - - public override NSNumber[] RequiredSourceTrackIDs => this.requiredSourceTrackIds; - - public override CMTimeRange TimeRange => this.timeRange; - - public override bool EnablePostProcessing => this.enablePostProcessing; - - public override bool ContainsTweening => this.containsTweening; - - [return: Release] - public override NSObject Copy() - { - return CustomVideoCompositionInstruction.Copy(this); - } - - [return: Release] - public override NSObject MutableCopy() - { - return CustomVideoCompositionInstruction.Copy(this); - } - - public static CustomVideoCompositionInstruction Copy(CustomVideoCompositionInstruction current) - { - CustomVideoCompositionInstruction result = null; - if (current.RequiredSourceTrackIDs != null && current.RequiredSourceTrackIDs.Length > 0) - { - result = new CustomVideoCompositionInstruction(current.RequiredSourceTrackIDs, current.TimeRange); - } - else - { - result = new CustomVideoCompositionInstruction(current.PassthroughTrackID, current.TimeRange); - } - - result.ForegroundTrackId = current.ForegroundTrackId; - result.BackgroundTrackId = current.BackgroundTrackId; - - return result; - } - } -} \ No newline at end of file +namespace AVCustomEdit { + public class CustomVideoCompositionInstruction : AVVideoCompositionInstruction { + private readonly NSNumber [] requiredSourceTrackIds; + private readonly bool enablePostProcessing; + private readonly int passthroughTrackId; + private readonly bool containsTweening; + private readonly CMTimeRange timeRange; + + public CustomVideoCompositionInstruction () : base () { } + + public CustomVideoCompositionInstruction (int passthroughTrackId, CMTimeRange timeRange) : base () + { + this.passthroughTrackId = passthroughTrackId; + this.requiredSourceTrackIds = null; + this.timeRange = timeRange; + this.containsTweening = false; + this.enablePostProcessing = false; + } + + public CustomVideoCompositionInstruction (NSNumber [] sourceTracksIds, CMTimeRange timeRange) : base () + { + this.requiredSourceTrackIds = sourceTracksIds; + this.passthroughTrackId = 0; + this.timeRange = timeRange; + this.containsTweening = true; + this.enablePostProcessing = false; + } + + public int ForegroundTrackId { get; set; } + + public int BackgroundTrackId { get; set; } + + public override int PassthroughTrackID => this.passthroughTrackId; + + public override NSNumber [] RequiredSourceTrackIDs => this.requiredSourceTrackIds; + + public override CMTimeRange TimeRange => this.timeRange; + + public override bool EnablePostProcessing => this.enablePostProcessing; + + public override bool ContainsTweening => this.containsTweening; + + [return: Release] + public override NSObject Copy () + { + return CustomVideoCompositionInstruction.Copy (this); + } + + [return: Release] + public override NSObject MutableCopy () + { + return CustomVideoCompositionInstruction.Copy (this); + } + + public static CustomVideoCompositionInstruction Copy (CustomVideoCompositionInstruction current) + { + CustomVideoCompositionInstruction result = null; + if (current.RequiredSourceTrackIDs != null && current.RequiredSourceTrackIDs.Length > 0) { + result = new CustomVideoCompositionInstruction (current.RequiredSourceTrackIDs, current.TimeRange); + } else { + result = new CustomVideoCompositionInstruction (current.PassthroughTrackID, current.TimeRange); + } + + result.ForegroundTrackId = current.ForegroundTrackId; + result.BackgroundTrackId = current.BackgroundTrackId; + + return result; + } + } +} diff --git a/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositor.cs b/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositor.cs index e48a5915c..8447cfb0d 100644 --- a/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositor.cs +++ b/AVCustomEdit/AVCustomEdit/Custom Compositors/CustomVideoCompositor.cs @@ -6,169 +6,155 @@ using Foundation; using System; -namespace AVCustomEdit -{ - public class CrossDissolveCompositor : CustomVideoCompositor - { - public CrossDissolveCompositor(IntPtr handle) : base(handle) - { - Render = new CrossDissolveRenderer(); - } - - public CrossDissolveCompositor(AVVideoComposition videoComposition) : base(videoComposition) - { - Render = new CrossDissolveRenderer(); - } - } - - public class DiagonalWipeCompositor : CustomVideoCompositor - { - public DiagonalWipeCompositor(IntPtr handle) : base(handle) - { - Render = new DiagonalWipeRenderer(); - } - - public DiagonalWipeCompositor(AVVideoComposition videoComposition) : base(videoComposition) - { - Render = new DiagonalWipeRenderer(); - } - } - - public class CustomVideoCompositor : AVVideoCompositing - { - private bool shouldCancelAllRequests; - private bool renderContextDidChange; - private DispatchQueue renderingQueue; - private DispatchQueue renderContextQueue; - private AVVideoCompositionRenderContext renderContext; - //private CVPixelBuffer previousBuffer; - - public CustomVideoCompositor(IntPtr handle) : base(handle) - { - renderingQueue = new DispatchQueue("com.apple.aplcustomvideocompositor.renderingqueue"); - renderContextQueue = new DispatchQueue("com.apple.aplcustomvideocompositor.rendercontextqueue"); - //previousBuffer = null; - renderContextDidChange = false; - } - - public CustomVideoCompositor(AVVideoComposition videoComposition) - { - renderingQueue = new DispatchQueue("com.apple.aplcustomvideocompositor.renderingqueue"); - renderContextQueue = new DispatchQueue("com.apple.aplcustomvideocompositor.rendercontextqueue"); - //previousBuffer = null; - renderContextDidChange = false; - } - - public OpenGLRenderer Render { get; set; } - - public override NSDictionary SourcePixelBufferAttributes() - { - return new NSDictionary(CVPixelBuffer.PixelFormatTypeKey, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, - CVPixelBuffer.OpenGLESCompatibilityKey, true); - } - - public override NSDictionary RequiredPixelBufferAttributesForRenderContext() - { - return new NSDictionary(CVPixelBuffer.PixelFormatTypeKey, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, - CVPixelBuffer.OpenGLESCompatibilityKey, true); - } - - public override void RenderContextChanged(AVVideoCompositionRenderContext newRenderContext) - { - renderContextQueue.DispatchSync(() => - { - renderContext = newRenderContext; - renderContextDidChange = true; - }); - } - - public override void StartVideoCompositionRequest(AVAsynchronousVideoCompositionRequest request) - { - renderingQueue.DispatchAsync(() => - { - // Check if all pending requests have been cancelled - if (shouldCancelAllRequests) - { - request.FinishCancelledRequest(); - } - else - { - // Get the next rendererd pixel buffer - var resultPixels = NewRenderedPixelBufferForRequest(request, out NSError error); - if (resultPixels != null) - { - // The resulting pixelbuffer from OpenGL renderer is passed along to the request - request.FinishWithComposedVideoFrame(resultPixels); - resultPixels.Dispose(); - resultPixels = null; - } - else - { - request.FinishWithError(error); - } - } - }); - } - - public override void CancelAllPendingVideoCompositionRequests() - { - // pending requests will call finishCancelledRequest, those already rendering will call finishWithComposedVideoFrame - shouldCancelAllRequests = true; - - renderingQueue.DispatchAsync(() => - { - // start accepting requests again - shouldCancelAllRequests = false; - }); - } - - #region Utilities methods - - private static double FactorForTimeInRange(CMTime time, CMTimeRange range) - { - var elapsed = CMTime.Subtract(time, range.Start); - return elapsed.Seconds / range.Duration.Seconds; - } - - private CVPixelBuffer NewRenderedPixelBufferForRequest(AVAsynchronousVideoCompositionRequest request, out NSError error) - { - CVPixelBuffer dstPixels; - - // tweenFactor indicates how far within that timeRange are we rendering this frame. This is normalized to vary between 0.0 and 1.0. - // 0.0 indicates the time at first frame in that videoComposition timeRange - // 1.0 indicates the time at last frame in that videoComposition timeRange - var tweenFactor = (float)FactorForTimeInRange(request.CompositionTime, request.VideoCompositionInstruction.TimeRange); - - var currentInstruction = request.VideoCompositionInstruction as CustomVideoCompositionInstruction; - - // Source pixel buffers are used as inputs while rendering the transition - var foregroundSourceBuffer = request.SourceFrameByTrackID(currentInstruction.ForegroundTrackId); - var backgroundSourceBuffer = request.SourceFrameByTrackID(currentInstruction.BackgroundTrackId); - - // Destination pixel buffer into which we render the output - dstPixels = renderContext.CreatePixelBuffer(); - - // Recompute normalized render transform everytime the render context changes - if (renderContextDidChange) - { - // The renderTransform returned by the renderContext is in X: [0, w] and Y: [0, h] coordinate system - // But since in this sample we render using OpenGLES which has its coordinate system between [-1, 1] we compute a normalized transform - var renderSize = renderContext.Size; - var destinationSize = new CGSize(dstPixels.Width, dstPixels.Height); - var renderContextTransform = new CGAffineTransform(renderSize.Width / 2, 0, 0, renderSize.Height / 2, renderSize.Width / 2, renderSize.Height / 2); - var destinationTransform = new CGAffineTransform(2 / destinationSize.Width, 0, 0, 2 / destinationSize.Height, -1, -1); - var normalizedRenderTransform = CGAffineTransform.Multiply(CGAffineTransform.Multiply(renderContextTransform, renderContext.RenderTransform), destinationTransform); - Render.RenderTransform = normalizedRenderTransform; - - renderContextDidChange = false; - } - - Render.RenderPixelBuffer(dstPixels, foregroundSourceBuffer, backgroundSourceBuffer, tweenFactor); - - error = null; - return dstPixels; - } - } - - #endregion -} \ No newline at end of file +namespace AVCustomEdit { + public class CrossDissolveCompositor : CustomVideoCompositor { + public CrossDissolveCompositor (IntPtr handle) : base (handle) + { + Render = new CrossDissolveRenderer (); + } + + public CrossDissolveCompositor (AVVideoComposition videoComposition) : base (videoComposition) + { + Render = new CrossDissolveRenderer (); + } + } + + public class DiagonalWipeCompositor : CustomVideoCompositor { + public DiagonalWipeCompositor (IntPtr handle) : base (handle) + { + Render = new DiagonalWipeRenderer (); + } + + public DiagonalWipeCompositor (AVVideoComposition videoComposition) : base (videoComposition) + { + Render = new DiagonalWipeRenderer (); + } + } + + public class CustomVideoCompositor : AVVideoCompositing { + private bool shouldCancelAllRequests; + private bool renderContextDidChange; + private DispatchQueue renderingQueue; + private DispatchQueue renderContextQueue; + private AVVideoCompositionRenderContext renderContext; + //private CVPixelBuffer previousBuffer; + + public CustomVideoCompositor (IntPtr handle) : base (handle) + { + renderingQueue = new DispatchQueue ("com.apple.aplcustomvideocompositor.renderingqueue"); + renderContextQueue = new DispatchQueue ("com.apple.aplcustomvideocompositor.rendercontextqueue"); + //previousBuffer = null; + renderContextDidChange = false; + } + + public CustomVideoCompositor (AVVideoComposition videoComposition) + { + renderingQueue = new DispatchQueue ("com.apple.aplcustomvideocompositor.renderingqueue"); + renderContextQueue = new DispatchQueue ("com.apple.aplcustomvideocompositor.rendercontextqueue"); + //previousBuffer = null; + renderContextDidChange = false; + } + + public OpenGLRenderer Render { get; set; } + + public override NSDictionary SourcePixelBufferAttributes () + { + return new NSDictionary (CVPixelBuffer.PixelFormatTypeKey, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, + CVPixelBuffer.OpenGLESCompatibilityKey, true); + } + + public override NSDictionary RequiredPixelBufferAttributesForRenderContext () + { + return new NSDictionary (CVPixelBuffer.PixelFormatTypeKey, CVPixelFormatType.CV420YpCbCr8BiPlanarVideoRange, + CVPixelBuffer.OpenGLESCompatibilityKey, true); + } + + public override void RenderContextChanged (AVVideoCompositionRenderContext newRenderContext) + { + renderContextQueue.DispatchSync (() => { + renderContext = newRenderContext; + renderContextDidChange = true; + }); + } + + public override void StartVideoCompositionRequest (AVAsynchronousVideoCompositionRequest request) + { + renderingQueue.DispatchAsync (() => { + // Check if all pending requests have been cancelled + if (shouldCancelAllRequests) { + request.FinishCancelledRequest (); + } else { + // Get the next rendererd pixel buffer + var resultPixels = NewRenderedPixelBufferForRequest (request, out NSError error); + if (resultPixels != null) { + // The resulting pixelbuffer from OpenGL renderer is passed along to the request + request.FinishWithComposedVideoFrame (resultPixels); + resultPixels.Dispose (); + resultPixels = null; + } else { + request.FinishWithError (error); + } + } + }); + } + + public override void CancelAllPendingVideoCompositionRequests () + { + // pending requests will call finishCancelledRequest, those already rendering will call finishWithComposedVideoFrame + shouldCancelAllRequests = true; + + renderingQueue.DispatchAsync (() => { + // start accepting requests again + shouldCancelAllRequests = false; + }); + } + + #region Utilities methods + + private static double FactorForTimeInRange (CMTime time, CMTimeRange range) + { + var elapsed = CMTime.Subtract (time, range.Start); + return elapsed.Seconds / range.Duration.Seconds; + } + + private CVPixelBuffer NewRenderedPixelBufferForRequest (AVAsynchronousVideoCompositionRequest request, out NSError error) + { + CVPixelBuffer dstPixels; + + // tweenFactor indicates how far within that timeRange are we rendering this frame. This is normalized to vary between 0.0 and 1.0. + // 0.0 indicates the time at first frame in that videoComposition timeRange + // 1.0 indicates the time at last frame in that videoComposition timeRange + var tweenFactor = (float) FactorForTimeInRange (request.CompositionTime, request.VideoCompositionInstruction.TimeRange); + + var currentInstruction = request.VideoCompositionInstruction as CustomVideoCompositionInstruction; + + // Source pixel buffers are used as inputs while rendering the transition + var foregroundSourceBuffer = request.SourceFrameByTrackID (currentInstruction.ForegroundTrackId); + var backgroundSourceBuffer = request.SourceFrameByTrackID (currentInstruction.BackgroundTrackId); + + // Destination pixel buffer into which we render the output + dstPixels = renderContext.CreatePixelBuffer (); + + // Recompute normalized render transform everytime the render context changes + if (renderContextDidChange) { + // The renderTransform returned by the renderContext is in X: [0, w] and Y: [0, h] coordinate system + // But since in this sample we render using OpenGLES which has its coordinate system between [-1, 1] we compute a normalized transform + var renderSize = renderContext.Size; + var destinationSize = new CGSize (dstPixels.Width, dstPixels.Height); + var renderContextTransform = new CGAffineTransform (renderSize.Width / 2, 0, 0, renderSize.Height / 2, renderSize.Width / 2, renderSize.Height / 2); + var destinationTransform = new CGAffineTransform (2 / destinationSize.Width, 0, 0, 2 / destinationSize.Height, -1, -1); + var normalizedRenderTransform = CGAffineTransform.Multiply (CGAffineTransform.Multiply (renderContextTransform, renderContext.RenderTransform), destinationTransform); + Render.RenderTransform = normalizedRenderTransform; + + renderContextDidChange = false; + } + + Render.RenderPixelBuffer (dstPixels, foregroundSourceBuffer, backgroundSourceBuffer, tweenFactor); + + error = null; + return dstPixels; + } + } + + #endregion +} diff --git a/AVCustomEdit/AVCustomEdit/Main.cs b/AVCustomEdit/AVCustomEdit/Main.cs index 1f847d76e..4e359a7ea 100644 --- a/AVCustomEdit/AVCustomEdit/Main.cs +++ b/AVCustomEdit/AVCustomEdit/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace AVCustomEdit -{ - public class Application - { +namespace AVCustomEdit { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { @@ -12,4 +10,4 @@ static void Main (string [] args) UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/AVCustomEdit/AVCustomEdit/OpenGL Renderers/CrossDissolveRenderer.cs b/AVCustomEdit/AVCustomEdit/OpenGL Renderers/CrossDissolveRenderer.cs index fbf562655..2b3fb3e6e 100644 --- a/AVCustomEdit/AVCustomEdit/OpenGL Renderers/CrossDissolveRenderer.cs +++ b/AVCustomEdit/AVCustomEdit/OpenGL Renderers/CrossDissolveRenderer.cs @@ -3,188 +3,183 @@ using OpenTK.Graphics.ES20; using System; -namespace AVCustomEdit -{ - public class CrossDissolveRenderer : OpenGLRenderer - { - public override void RenderPixelBuffer(CoreVideo.CVPixelBuffer destinationPixelBuffer, CoreVideo.CVPixelBuffer foregroundPixelBuffer, CoreVideo.CVPixelBuffer backgroundPixelBuffer, float tween) - { - EAGLContext.SetCurrentContext(CurrentContext); - if (foregroundPixelBuffer != null || backgroundPixelBuffer != null) - { - var foregroundLumaTexture = LumaTextureForPixelBuffer(foregroundPixelBuffer); - var foregroundChromaTexture = ChromaTextureForPixelBuffer(foregroundPixelBuffer); - - var backgroundLumaTexture = LumaTextureForPixelBuffer(backgroundPixelBuffer); - var backgroundChromaTexture = ChromaTextureForPixelBuffer(backgroundPixelBuffer); - - var destLumaTexture = LumaTextureForPixelBuffer(destinationPixelBuffer); - var destChromaTexture = ChromaTextureForPixelBuffer(destinationPixelBuffer); - - GL.UseProgram(ProgramY); - - // Set the render transform - float[] preferredRenderTransform = - { - (float)RenderTransform.xx, (float)RenderTransform.xy, (float)RenderTransform.x0, 0.0f, - (float)RenderTransform.yx, (float)RenderTransform.yy, (float)RenderTransform.y0, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f, - }; - - GL.UniformMatrix4(Uniforms[(int)Uniform.Render_Transform_Y], 1, false, preferredRenderTransform); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, OffscreenBufferHandle); - GL.Viewport(0, 0, (int)destinationPixelBuffer.GetWidthOfPlane(0), (int)destinationPixelBuffer.GetHeightOfPlane(0)); - - // Y planes of foreground and background frame are used to render the Y plane of the destination frame - GL.ActiveTexture(TextureUnit.Texture0); - GL.BindTexture(foregroundLumaTexture.Target, foregroundLumaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - GL.ActiveTexture(TextureUnit.Texture1); - GL.BindTexture(backgroundLumaTexture.Target, backgroundLumaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - // Attach the destination texture as a color attachment to the off screen frame buffer - GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, destLumaTexture.Target, destLumaTexture.Name, 0); - - if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) - { - Console.Error.WriteLine($"Failed to make complete framebuffer object {GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)}"); - goto bail; - } - - GL.ClearColor(0f, 0f, 0f, 1f); - GL.Clear(ClearBufferMask.ColorBufferBit); - - float[] quadVertexData1 = - { - -1.0f, 1.0f, - 1.0f, 1.0f, - -1.0f, -1.0f, - 1.0f, -1.0f, - }; +namespace AVCustomEdit { + public class CrossDissolveRenderer : OpenGLRenderer { + public override void RenderPixelBuffer (CoreVideo.CVPixelBuffer destinationPixelBuffer, CoreVideo.CVPixelBuffer foregroundPixelBuffer, CoreVideo.CVPixelBuffer backgroundPixelBuffer, float tween) + { + EAGLContext.SetCurrentContext (CurrentContext); + if (foregroundPixelBuffer != null || backgroundPixelBuffer != null) { + var foregroundLumaTexture = LumaTextureForPixelBuffer (foregroundPixelBuffer); + var foregroundChromaTexture = ChromaTextureForPixelBuffer (foregroundPixelBuffer); + + var backgroundLumaTexture = LumaTextureForPixelBuffer (backgroundPixelBuffer); + var backgroundChromaTexture = ChromaTextureForPixelBuffer (backgroundPixelBuffer); + + var destLumaTexture = LumaTextureForPixelBuffer (destinationPixelBuffer); + var destChromaTexture = ChromaTextureForPixelBuffer (destinationPixelBuffer); + + GL.UseProgram (ProgramY); + + // Set the render transform + float [] preferredRenderTransform = + { + (float)RenderTransform.xx, (float)RenderTransform.xy, (float)RenderTransform.x0, 0.0f, + (float)RenderTransform.yx, (float)RenderTransform.yy, (float)RenderTransform.y0, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f, + }; + + GL.UniformMatrix4 (Uniforms [(int) Uniform.Render_Transform_Y], 1, false, preferredRenderTransform); + + GL.BindFramebuffer (FramebufferTarget.Framebuffer, OffscreenBufferHandle); + GL.Viewport (0, 0, (int) destinationPixelBuffer.GetWidthOfPlane (0), (int) destinationPixelBuffer.GetHeightOfPlane (0)); + + // Y planes of foreground and background frame are used to render the Y plane of the destination frame + GL.ActiveTexture (TextureUnit.Texture0); + GL.BindTexture (foregroundLumaTexture.Target, foregroundLumaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + GL.ActiveTexture (TextureUnit.Texture1); + GL.BindTexture (backgroundLumaTexture.Target, backgroundLumaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + // Attach the destination texture as a color attachment to the off screen frame buffer + GL.FramebufferTexture2D (FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, destLumaTexture.Target, destLumaTexture.Name, 0); + + if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { + Console.Error.WriteLine ($"Failed to make complete framebuffer object {GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer)}"); + goto bail; + } - // texture data varies from 0 -> 1, whereas vertex data varies from -1 -> 1 - float[] quadTextureData1 = - { - 0.5f + quadVertexData1[0] / 2, 0.5f + quadVertexData1[1] / 2, - 0.5f + quadVertexData1[2] / 2, 0.5f + quadVertexData1[3] / 2, - 0.5f + quadVertexData1[4] / 2, 0.5f + quadVertexData1[5] / 2, - 0.5f + quadVertexData1[6] / 2, 0.5f + quadVertexData1[7] / 2, - }; - - GL.Uniform1(Uniforms[(int)Uniform.Y], 0); - - GL.VertexAttribPointer((int)Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); - GL.EnableVertexAttribArray((int)Attrib.Vertex_Y); - - GL.VertexAttribPointer((int)Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_Y); - - // Blend function to draw the foreground frame - GL.Enable(EnableCap.Blend); - GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); - - // Draw the foreground frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 4); - - GL.Uniform1(Uniforms[(int)Uniform.Y], 1); - - GL.VertexAttribPointer((int)Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); - GL.EnableVertexAttribArray((int)Attrib.Vertex_Y); - - GL.VertexAttribPointer((int)Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_Y); - - // Blend function to draw the background frame - GL.BlendColor(0, 0, 0, tween); - GL.BlendFunc(BlendingFactorSrc.ConstantAlpha, BlendingFactorDest.OneMinusConstantAlpha); - - // Draw the background frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 4); + GL.ClearColor (0f, 0f, 0f, 1f); + GL.Clear (ClearBufferMask.ColorBufferBit); - // Perform similar operations as above for the UV plane - GL.UseProgram(ProgramUV); + float [] quadVertexData1 = + { + -1.0f, 1.0f, + 1.0f, 1.0f, + -1.0f, -1.0f, + 1.0f, -1.0f, + }; - GL.UniformMatrix4(Uniforms[(int)Uniform.Render_Transform_UV], 1, false, preferredRenderTransform); + // texture data varies from 0 -> 1, whereas vertex data varies from -1 -> 1 + float [] quadTextureData1 = + { + 0.5f + quadVertexData1[0] / 2, 0.5f + quadVertexData1[1] / 2, + 0.5f + quadVertexData1[2] / 2, 0.5f + quadVertexData1[3] / 2, + 0.5f + quadVertexData1[4] / 2, 0.5f + quadVertexData1[5] / 2, + 0.5f + quadVertexData1[6] / 2, 0.5f + quadVertexData1[7] / 2, + }; - // UV planes of foreground and background frame are used to render the UV plane of the destination frame - GL.ActiveTexture(TextureUnit.Texture2); - GL.BindTexture(foregroundChromaTexture.Target, foregroundChromaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - GL.ActiveTexture(TextureUnit.Texture3); - GL.BindTexture(backgroundChromaTexture.Target, backgroundChromaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); + GL.Uniform1 (Uniforms [(int) Uniform.Y], 0); - GL.Viewport(0, 0, (int)destinationPixelBuffer.GetWidthOfPlane(1), (int)destinationPixelBuffer.GetHeightOfPlane(1)); + GL.VertexAttribPointer ((int) Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_Y); - // Attach the destination texture as a color attachment to the off screen frame buffer - GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, destChromaTexture.Target, destChromaTexture.Name, 0); + GL.VertexAttribPointer ((int) Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_Y); + + // Blend function to draw the foreground frame + GL.Enable (EnableCap.Blend); + GL.BlendFunc (BlendingFactorSrc.One, BlendingFactorDest.Zero); + + // Draw the foreground frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); + + GL.Uniform1 (Uniforms [(int) Uniform.Y], 1); + + GL.VertexAttribPointer ((int) Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_Y); + + GL.VertexAttribPointer ((int) Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_Y); + + // Blend function to draw the background frame + GL.BlendColor (0, 0, 0, tween); + GL.BlendFunc (BlendingFactorSrc.ConstantAlpha, BlendingFactorDest.OneMinusConstantAlpha); + + // Draw the background frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); - if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) - { - Console.Error.WriteLine($"Failed to make complete framebuffer object {GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)}"); - goto bail; - } + // Perform similar operations as above for the UV plane + GL.UseProgram (ProgramUV); - GL.ClearColor(0f, 0f, 0f, 1f); - GL.Clear(ClearBufferMask.ColorBufferBit); + GL.UniformMatrix4 (Uniforms [(int) Uniform.Render_Transform_UV], 1, false, preferredRenderTransform); - GL.Uniform1(Uniforms[(int)Uniform.UV], 2); + // UV planes of foreground and background frame are used to render the UV plane of the destination frame + GL.ActiveTexture (TextureUnit.Texture2); + GL.BindTexture (foregroundChromaTexture.Target, foregroundChromaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); - GL.VertexAttribPointer((int)Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); - GL.EnableVertexAttribArray((int)Attrib.Vertex_UV); + GL.ActiveTexture (TextureUnit.Texture3); + GL.BindTexture (backgroundChromaTexture.Target, backgroundChromaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); - GL.VertexAttribPointer((int)Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_UV); + GL.Viewport (0, 0, (int) destinationPixelBuffer.GetWidthOfPlane (1), (int) destinationPixelBuffer.GetHeightOfPlane (1)); - GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); + // Attach the destination texture as a color attachment to the off screen frame buffer + GL.FramebufferTexture2D (FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, destChromaTexture.Target, destChromaTexture.Name, 0); - // Draw the foreground frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 4); + if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { + Console.Error.WriteLine ($"Failed to make complete framebuffer object {GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer)}"); + goto bail; + } - GL.Uniform1(Uniforms[(int)Uniform.UV], 3); + GL.ClearColor (0f, 0f, 0f, 1f); + GL.Clear (ClearBufferMask.ColorBufferBit); - GL.VertexAttribPointer((int)Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); - GL.EnableVertexAttribArray((int)Attrib.Vertex_UV); + GL.Uniform1 (Uniforms [(int) Uniform.UV], 2); - GL.VertexAttribPointer((int)Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_UV); + GL.VertexAttribPointer ((int) Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_UV); - GL.BlendColor(0, 0, 0, tween); - GL.BlendFunc(BlendingFactorSrc.ConstantAlpha, BlendingFactorDest.OneMinusConstantAlpha); + GL.VertexAttribPointer ((int) Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_UV); - // Draw the background frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 4); + GL.BlendFunc (BlendingFactorSrc.One, BlendingFactorDest.Zero); - GL.Flush(); + // Draw the foreground frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); - bail: - foregroundLumaTexture.Dispose(); - foregroundChromaTexture.Dispose(); - backgroundLumaTexture.Dispose(); - backgroundChromaTexture.Dispose(); - destLumaTexture.Dispose(); - destChromaTexture.Dispose(); + GL.Uniform1 (Uniforms [(int) Uniform.UV], 3); - _videoTextureCache.Flush(0); - EAGLContext.SetCurrentContext(null); - } - } - } -} \ No newline at end of file + GL.VertexAttribPointer ((int) Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_UV); + + GL.VertexAttribPointer ((int) Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_UV); + + GL.BlendColor (0, 0, 0, tween); + GL.BlendFunc (BlendingFactorSrc.ConstantAlpha, BlendingFactorDest.OneMinusConstantAlpha); + + // Draw the background frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); + + GL.Flush (); + + bail: + foregroundLumaTexture.Dispose (); + foregroundChromaTexture.Dispose (); + backgroundLumaTexture.Dispose (); + backgroundChromaTexture.Dispose (); + destLumaTexture.Dispose (); + destChromaTexture.Dispose (); + + _videoTextureCache.Flush (0); + EAGLContext.SetCurrentContext (null); + } + } + } +} diff --git a/AVCustomEdit/AVCustomEdit/OpenGL Renderers/DiagonalWipeRenderer.cs b/AVCustomEdit/AVCustomEdit/OpenGL Renderers/DiagonalWipeRenderer.cs index d0152b94b..b2740426d 100644 --- a/AVCustomEdit/AVCustomEdit/OpenGL Renderers/DiagonalWipeRenderer.cs +++ b/AVCustomEdit/AVCustomEdit/OpenGL Renderers/DiagonalWipeRenderer.cs @@ -3,19 +3,17 @@ using OpenTK.Graphics.ES20; using System; -namespace AVCustomEdit -{ - public class DiagonalWipeRenderer : OpenGLRenderer - { - private const int ForegroundTrack = 0; - private const int BackgroundTrack = 1; - - private CGPoint diagonalEnd1; - private CGPoint diagonalEnd2; - - private void QuadVertexCoordinates(ref float[] vertexCoordinates, int trackId, float tween) - { - /* +namespace AVCustomEdit { + public class DiagonalWipeRenderer : OpenGLRenderer { + private const int ForegroundTrack = 0; + private const int BackgroundTrack = 1; + + private CGPoint diagonalEnd1; + private CGPoint diagonalEnd2; + + private void QuadVertexCoordinates (ref float [] vertexCoordinates, int trackId, float tween) + { + /* diagonalEnd1 and diagonalEnd2 represent the endpoints of a line which partitions the frame on screen into the two parts. diagonalEnd1 @@ -30,250 +28,239 @@ diagonalEnd1 and diagonalEnd2 represent the endpoints of a line which partitions */ - if (tween <= 0.5f) - { - // The expectation here is that in half the timeRange of the transition we reach the diagonal of the frame - diagonalEnd1 = new CGPoint(1f - tween * 4f, -1f); - diagonalEnd2 = new CGPoint(1f, -1f + tween * 4f); - - vertexCoordinates[6] = (float)diagonalEnd2.X; - vertexCoordinates[7] = (float)diagonalEnd2.Y; - vertexCoordinates[8] = (float)diagonalEnd1.X; - vertexCoordinates[9] = (float)diagonalEnd1.Y; - } - else if (tween > 0.5f && tween < 1f) - { - if (trackId == ForegroundTrack) - { - diagonalEnd1 = new CGPoint(-1f, -1 + (tween - 0.5f) * 4f); - diagonalEnd2 = new CGPoint(1f - (tween - 0.5f) * 4f, 1f); - - vertexCoordinates[2] = (float)diagonalEnd2.X; - vertexCoordinates[3] = (float)diagonalEnd2.Y; - vertexCoordinates[4] = (float)diagonalEnd1.X; - vertexCoordinates[5] = (float)diagonalEnd1.Y; - vertexCoordinates[6] = (float)diagonalEnd1.X; - vertexCoordinates[7] = (float)diagonalEnd1.Y; - vertexCoordinates[8] = (float)diagonalEnd1.X; - vertexCoordinates[9] = (float)diagonalEnd1.Y; - } - else if (trackId == BackgroundTrack) - { - vertexCoordinates[4] = 1f; - vertexCoordinates[5] = 1f; - vertexCoordinates[6] = -1f; - vertexCoordinates[7] = -1f; - } - } - else if (tween >= 1f) - { - diagonalEnd1 = new CGPoint(1f, -1f); - diagonalEnd2 = new CGPoint(1f, -1f); - } - } - - public override void RenderPixelBuffer(CoreVideo.CVPixelBuffer destinationPixelBuffer, CoreVideo.CVPixelBuffer foregroundPixelBuffer, CoreVideo.CVPixelBuffer backgroundPixelBuffer, float tween) - { - EAGLContext.SetCurrentContext(CurrentContext); - - if (foregroundPixelBuffer != null || backgroundPixelBuffer != null) - { - var foregroundLumaTexture = LumaTextureForPixelBuffer(foregroundPixelBuffer); - var foregroundChromaTexture = ChromaTextureForPixelBuffer(foregroundPixelBuffer); - - var backgroundLumaTexture = LumaTextureForPixelBuffer(backgroundPixelBuffer); - var backgroundChromaTexture = ChromaTextureForPixelBuffer(backgroundPixelBuffer); - - var destLumaTexture = LumaTextureForPixelBuffer(destinationPixelBuffer); - var destChromaTexture = ChromaTextureForPixelBuffer(destinationPixelBuffer); - - GL.UseProgram(ProgramY); - - // Set the render transformq - float[] preferredRenderTransform = - { - (float)RenderTransform.xx, (float) RenderTransform.xy, (float)RenderTransform.x0, 0.0f, - (float)RenderTransform.yx, (float) RenderTransform.yy, (float)RenderTransform.y0, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - GL.UniformMatrix4(Uniforms[(int)Uniform.Y], 1, false, preferredRenderTransform); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, (int)OffscreenBufferHandle); - - GL.Viewport(0, 0, (int)destinationPixelBuffer.GetWidthOfPlane(0), (int)destinationPixelBuffer.GetHeightOfPlane(0)); - - // Y planes of foreground and background frame are used to render the Y plane of the destination frame - GL.ActiveTexture(TextureUnit.Texture0); - GL.BindTexture(foregroundLumaTexture.Target, foregroundLumaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - GL.ActiveTexture(TextureUnit.Texture1); - GL.BindTexture(backgroundLumaTexture.Target, backgroundLumaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - // Attach the destination texture as a color attachment to the off screen frame buffer - GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, - FramebufferSlot.ColorAttachment0, - destLumaTexture.Target, - destLumaTexture.Name, - 0); - - if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) - { - Console.WriteLine("Failed to make complete frmaebuffer object: {0}", GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)); - goto bail; - } - - GL.ClearColor(0f, 0f, 0f, 1f); - GL.Clear(ClearBufferMask.ColorBufferBit); - - float[] quadVertexData1 = - { - -1.0f, 1.0f, - 1.0f, 1.0f, - -1.0f, -1.0f, - 1.0f, -1.0f, - 1.0f, -1.0f, - }; - - // Compute the vertex data for the foreground frame at this instructionLerp - QuadVertexCoordinates(ref quadVertexData1, ForegroundTrack, tween); - - // texture data varies from 0 -> 1, whereas vertex data varies from -1 -> 1 - float[] quadTextureData1 = - { - 0.5f + quadVertexData1[0] / 2f, 0.5f + quadVertexData1[1] / 2f, - 0.5f + quadVertexData1[2] / 2f, 0.5f + quadVertexData1[3] / 2f, - 0.5f + quadVertexData1[4] / 2f, 0.5f + quadVertexData1[5] / 2f, - 0.5f + quadVertexData1[6] / 2f, 0.5f + quadVertexData1[7] / 2f, - 0.5f + quadVertexData1[8] / 2f, 0.5f + quadVertexData1[9] / 2f, - }; - - GL.Uniform1(Uniforms[(int)Uniform.Y], 0f); - - GL.VertexAttribPointer((int)Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); - GL.EnableVertexAttribArray((int)Attrib.Vertex_Y); - - GL.VertexAttribPointer((int)Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_Y); - - // Draw the foreground frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 5); - - float[] quadVertexData2 = - { - (float)diagonalEnd2.X, (float)diagonalEnd2.Y, - (float)diagonalEnd1.X, (float)diagonalEnd1.Y, - 1.0f, -1.0f, - 1.0f, -1.0f, - 1.0f, -1.0f, - }; - - // Compute the vertex data for the background frame at this instructionLerp - QuadVertexCoordinates(ref quadVertexData2, BackgroundTrack, tween); - - float[] quadTextureData2 = - { - 0.5f + quadVertexData2[0] / 2f, 0.5f + quadVertexData2[1] / 2f, - 0.5f + quadVertexData2[2] / 2f, 0.5f + quadVertexData2[3] / 2f, - 0.5f + quadVertexData2[4] / 2f, 0.5f + quadVertexData2[5] / 2f, - 0.5f + quadVertexData2[6] / 2f, 0.5f + quadVertexData2[7] / 2f, - 0.5f + quadVertexData2[8] / 2f, 0.5f + quadVertexData2[9] / 2f, - }; - - GL.Uniform1(Uniforms[(int)Uniform.Y], 1); - - GL.VertexAttribPointer((int)Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData2); - GL.EnableVertexAttribArray((int)Attrib.Vertex_Y); - - GL.VertexAttribPointer((int)Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData2); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_Y); - - // Draw the background frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 5); - - // Perform similar operations as above for the UV plane - GL.UseProgram(ProgramUV); - - GL.UniformMatrix4(Uniforms[(int)Uniform.Render_Transform_UV], 1, false, preferredRenderTransform); - - // UV planes of foreground and background frame are used to render the UV plane of the destination frame - GL.ActiveTexture(TextureUnit.Texture2); - GL.BindTexture(foregroundChromaTexture.Target, foregroundChromaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - GL.ActiveTexture(TextureUnit.Texture3); - GL.BindTexture(backgroundChromaTexture.Target, backgroundChromaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - GL.Viewport(0, 0, (int)destinationPixelBuffer.GetWidthOfPlane(1), (int)destinationPixelBuffer.GetHeightOfPlane(1)); - - // Attach the destination texture as a color attachment to the off screen frame buffer - GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, - FramebufferSlot.ColorAttachment0, - destChromaTexture.Target, - destChromaTexture.Name, - 0); - - if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) - { - Console.WriteLine("Failed to make complete framebuffer object: {0}", GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)); - goto bail; - } - - GL.ClearColor(0f, 0f, 0f, 1f); - GL.Clear(ClearBufferMask.ColorBufferBit); - - GL.Uniform1(Uniforms[(int)Uniform.UV], 2); - - GL.VertexAttribPointer((int)Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); - GL.EnableVertexAttribArray((int)Attrib.Vertex_UV); - - GL.VertexAttribPointer((int)Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_UV); - - // Draw the foreground frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 5); - - GL.Uniform1(Uniforms[(int)Uniform.UV], 3); - - GL.VertexAttribPointer((int)Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData2); - GL.EnableVertexAttribArray((int)Attrib.Vertex_UV); - - GL.VertexAttribPointer((int)Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData2); - GL.EnableVertexAttribArray((int)Attrib.TexCoord_UV); + if (tween <= 0.5f) { + // The expectation here is that in half the timeRange of the transition we reach the diagonal of the frame + diagonalEnd1 = new CGPoint (1f - tween * 4f, -1f); + diagonalEnd2 = new CGPoint (1f, -1f + tween * 4f); + + vertexCoordinates [6] = (float) diagonalEnd2.X; + vertexCoordinates [7] = (float) diagonalEnd2.Y; + vertexCoordinates [8] = (float) diagonalEnd1.X; + vertexCoordinates [9] = (float) diagonalEnd1.Y; + } else if (tween > 0.5f && tween < 1f) { + if (trackId == ForegroundTrack) { + diagonalEnd1 = new CGPoint (-1f, -1 + (tween - 0.5f) * 4f); + diagonalEnd2 = new CGPoint (1f - (tween - 0.5f) * 4f, 1f); + + vertexCoordinates [2] = (float) diagonalEnd2.X; + vertexCoordinates [3] = (float) diagonalEnd2.Y; + vertexCoordinates [4] = (float) diagonalEnd1.X; + vertexCoordinates [5] = (float) diagonalEnd1.Y; + vertexCoordinates [6] = (float) diagonalEnd1.X; + vertexCoordinates [7] = (float) diagonalEnd1.Y; + vertexCoordinates [8] = (float) diagonalEnd1.X; + vertexCoordinates [9] = (float) diagonalEnd1.Y; + } else if (trackId == BackgroundTrack) { + vertexCoordinates [4] = 1f; + vertexCoordinates [5] = 1f; + vertexCoordinates [6] = -1f; + vertexCoordinates [7] = -1f; + } + } else if (tween >= 1f) { + diagonalEnd1 = new CGPoint (1f, -1f); + diagonalEnd2 = new CGPoint (1f, -1f); + } + } + + public override void RenderPixelBuffer (CoreVideo.CVPixelBuffer destinationPixelBuffer, CoreVideo.CVPixelBuffer foregroundPixelBuffer, CoreVideo.CVPixelBuffer backgroundPixelBuffer, float tween) + { + EAGLContext.SetCurrentContext (CurrentContext); + + if (foregroundPixelBuffer != null || backgroundPixelBuffer != null) { + var foregroundLumaTexture = LumaTextureForPixelBuffer (foregroundPixelBuffer); + var foregroundChromaTexture = ChromaTextureForPixelBuffer (foregroundPixelBuffer); + + var backgroundLumaTexture = LumaTextureForPixelBuffer (backgroundPixelBuffer); + var backgroundChromaTexture = ChromaTextureForPixelBuffer (backgroundPixelBuffer); + + var destLumaTexture = LumaTextureForPixelBuffer (destinationPixelBuffer); + var destChromaTexture = ChromaTextureForPixelBuffer (destinationPixelBuffer); + + GL.UseProgram (ProgramY); + + // Set the render transformq + float [] preferredRenderTransform = + { + (float)RenderTransform.xx, (float) RenderTransform.xy, (float)RenderTransform.x0, 0.0f, + (float)RenderTransform.yx, (float) RenderTransform.yy, (float)RenderTransform.y0, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f + }; + + GL.UniformMatrix4 (Uniforms [(int) Uniform.Y], 1, false, preferredRenderTransform); + + GL.BindFramebuffer (FramebufferTarget.Framebuffer, (int) OffscreenBufferHandle); + + GL.Viewport (0, 0, (int) destinationPixelBuffer.GetWidthOfPlane (0), (int) destinationPixelBuffer.GetHeightOfPlane (0)); + + // Y planes of foreground and background frame are used to render the Y plane of the destination frame + GL.ActiveTexture (TextureUnit.Texture0); + GL.BindTexture (foregroundLumaTexture.Target, foregroundLumaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + GL.ActiveTexture (TextureUnit.Texture1); + GL.BindTexture (backgroundLumaTexture.Target, backgroundLumaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + // Attach the destination texture as a color attachment to the off screen frame buffer + GL.FramebufferTexture2D (FramebufferTarget.Framebuffer, + FramebufferSlot.ColorAttachment0, + destLumaTexture.Target, + destLumaTexture.Name, + 0); + + if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { + Console.WriteLine ("Failed to make complete frmaebuffer object: {0}", GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer)); + goto bail; + } + + GL.ClearColor (0f, 0f, 0f, 1f); + GL.Clear (ClearBufferMask.ColorBufferBit); + + float [] quadVertexData1 = + { + -1.0f, 1.0f, + 1.0f, 1.0f, + -1.0f, -1.0f, + 1.0f, -1.0f, + 1.0f, -1.0f, + }; + + // Compute the vertex data for the foreground frame at this instructionLerp + QuadVertexCoordinates (ref quadVertexData1, ForegroundTrack, tween); + + // texture data varies from 0 -> 1, whereas vertex data varies from -1 -> 1 + float [] quadTextureData1 = + { + 0.5f + quadVertexData1[0] / 2f, 0.5f + quadVertexData1[1] / 2f, + 0.5f + quadVertexData1[2] / 2f, 0.5f + quadVertexData1[3] / 2f, + 0.5f + quadVertexData1[4] / 2f, 0.5f + quadVertexData1[5] / 2f, + 0.5f + quadVertexData1[6] / 2f, 0.5f + quadVertexData1[7] / 2f, + 0.5f + quadVertexData1[8] / 2f, 0.5f + quadVertexData1[9] / 2f, + }; + + GL.Uniform1 (Uniforms [(int) Uniform.Y], 0f); + + GL.VertexAttribPointer ((int) Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_Y); + + GL.VertexAttribPointer ((int) Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_Y); + + // Draw the foreground frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 5); + + float [] quadVertexData2 = + { + (float)diagonalEnd2.X, (float)diagonalEnd2.Y, + (float)diagonalEnd1.X, (float)diagonalEnd1.Y, + 1.0f, -1.0f, + 1.0f, -1.0f, + 1.0f, -1.0f, + }; + + // Compute the vertex data for the background frame at this instructionLerp + QuadVertexCoordinates (ref quadVertexData2, BackgroundTrack, tween); + + float [] quadTextureData2 = + { + 0.5f + quadVertexData2[0] / 2f, 0.5f + quadVertexData2[1] / 2f, + 0.5f + quadVertexData2[2] / 2f, 0.5f + quadVertexData2[3] / 2f, + 0.5f + quadVertexData2[4] / 2f, 0.5f + quadVertexData2[5] / 2f, + 0.5f + quadVertexData2[6] / 2f, 0.5f + quadVertexData2[7] / 2f, + 0.5f + quadVertexData2[8] / 2f, 0.5f + quadVertexData2[9] / 2f, + }; + + GL.Uniform1 (Uniforms [(int) Uniform.Y], 1); + + GL.VertexAttribPointer ((int) Attrib.Vertex_Y, 2, VertexAttribPointerType.Float, false, 0, quadVertexData2); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_Y); + + GL.VertexAttribPointer ((int) Attrib.TexCoord_Y, 2, VertexAttribPointerType.Float, false, 0, quadTextureData2); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_Y); + + // Draw the background frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 5); + + // Perform similar operations as above for the UV plane + GL.UseProgram (ProgramUV); + + GL.UniformMatrix4 (Uniforms [(int) Uniform.Render_Transform_UV], 1, false, preferredRenderTransform); + + // UV planes of foreground and background frame are used to render the UV plane of the destination frame + GL.ActiveTexture (TextureUnit.Texture2); + GL.BindTexture (foregroundChromaTexture.Target, foregroundChromaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + GL.ActiveTexture (TextureUnit.Texture3); + GL.BindTexture (backgroundChromaTexture.Target, backgroundChromaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + GL.Viewport (0, 0, (int) destinationPixelBuffer.GetWidthOfPlane (1), (int) destinationPixelBuffer.GetHeightOfPlane (1)); + + // Attach the destination texture as a color attachment to the off screen frame buffer + GL.FramebufferTexture2D (FramebufferTarget.Framebuffer, + FramebufferSlot.ColorAttachment0, + destChromaTexture.Target, + destChromaTexture.Name, + 0); + + if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { + Console.WriteLine ("Failed to make complete framebuffer object: {0}", GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer)); + goto bail; + } + + GL.ClearColor (0f, 0f, 0f, 1f); + GL.Clear (ClearBufferMask.ColorBufferBit); + + GL.Uniform1 (Uniforms [(int) Uniform.UV], 2); + + GL.VertexAttribPointer ((int) Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData1); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_UV); + + GL.VertexAttribPointer ((int) Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData1); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_UV); + + // Draw the foreground frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 5); + + GL.Uniform1 (Uniforms [(int) Uniform.UV], 3); + + GL.VertexAttribPointer ((int) Attrib.Vertex_UV, 2, VertexAttribPointerType.Float, false, 0, quadVertexData2); + GL.EnableVertexAttribArray ((int) Attrib.Vertex_UV); + + GL.VertexAttribPointer ((int) Attrib.TexCoord_UV, 2, VertexAttribPointerType.Float, false, 0, quadTextureData2); + GL.EnableVertexAttribArray ((int) Attrib.TexCoord_UV); + + // Draw the background frame + GL.DrawArrays (BeginMode.TriangleStrip, 0, 5); - // Draw the background frame - GL.DrawArrays(BeginMode.TriangleStrip, 0, 5); - - GL.Flush(); - - bail: - foregroundLumaTexture.Dispose(); - foregroundChromaTexture.Dispose(); - backgroundLumaTexture.Dispose(); - backgroundChromaTexture.Dispose(); - destLumaTexture.Dispose(); - destChromaTexture.Dispose(); - - // Periodic texture cache flush every frame - _videoTextureCache.Flush(0); - EAGLContext.SetCurrentContext(null); - } - } - } -} \ No newline at end of file + GL.Flush (); + + bail: + foregroundLumaTexture.Dispose (); + foregroundChromaTexture.Dispose (); + backgroundLumaTexture.Dispose (); + backgroundChromaTexture.Dispose (); + destLumaTexture.Dispose (); + destChromaTexture.Dispose (); + + // Periodic texture cache flush every frame + _videoTextureCache.Flush (0); + EAGLContext.SetCurrentContext (null); + } + } + } +} diff --git a/AVCustomEdit/AVCustomEdit/OpenGL Renderers/OpenGLRenderer.cs b/AVCustomEdit/AVCustomEdit/OpenGL Renderers/OpenGLRenderer.cs index d1311da1b..6d68ec2df 100644 --- a/AVCustomEdit/AVCustomEdit/OpenGL Renderers/OpenGLRenderer.cs +++ b/AVCustomEdit/AVCustomEdit/OpenGL Renderers/OpenGLRenderer.cs @@ -6,11 +6,9 @@ using System; using System.Text; -namespace AVCustomEdit -{ - public class OpenGLRenderer : NSObject - { - private const string VertShaderSource = @"attribute vec4 position; +namespace AVCustomEdit { + public class OpenGLRenderer : NSObject { + private const string VertShaderSource = @"attribute vec4 position; attribute vec2 texCoord; uniform mat4 renderTransform; varying vec2 texCoordVarying; @@ -20,254 +18,236 @@ void main() texCoordVarying = texCoord; }"; - private const string FragShaderYSource = @"varying highp vec2 texCoordVarying; + private const string FragShaderYSource = @"varying highp vec2 texCoordVarying; uniform sampler2D SamplerY; void main() { gl_FragColor.r = texture2D(SamplerY, texCoordVarying).r; }"; - private const string FragShaderUVSource = @"varying highp vec2 texCoordVarying; + private const string FragShaderUVSource = @"varying highp vec2 texCoordVarying; uniform sampler2D SamplerUV; void main() { gl_FragColor.rg = texture2D(SamplerUV, texCoordVarying).rg; }"; - public uint OffscreenBufferHandle; - - public OpenGLRenderer() - { - CurrentContext = new EAGLContext(EAGLRenderingAPI.OpenGLES2); - EAGLContext.SetCurrentContext(CurrentContext); - - SetupOffScreenRenderContext(); - LoadShaders(); - - EAGLContext.SetCurrentContext(null); - } - - public int ProgramY { get; set; } = -1; - public int ProgramUV { get; set; } = -1; - public CGAffineTransform RenderTransform { get; set; } - public CVOpenGLESTextureCache _videoTextureCache { get; set; } - public EAGLContext CurrentContext { get; set; } - public int[] Uniforms { get; set; } = new int[(int)Uniform.Num_Uniforms]; - - public virtual void RenderPixelBuffer(CVPixelBuffer destinationPixelBuffer, CVPixelBuffer foregroundPixelBuffer, CVPixelBuffer backgroundPixelBuffer, float tween) - { - DoesNotRecognizeSelector(new ObjCRuntime.Selector("_cmd")); - } - - public void SetupOffScreenRenderContext() - { - //-- Create CVOpenGLESTextureCacheRef for optimal CVPixelBufferRef to GLES texture conversion. - if (_videoTextureCache != null) - { - _videoTextureCache.Dispose(); - _videoTextureCache = null; - } - - _videoTextureCache = CVOpenGLESTextureCache.FromEAGLContext(CurrentContext); - - GL.Disable(EnableCap.DepthTest); - GL.GenFramebuffers(1, out OffscreenBufferHandle); - GL.BindFramebuffer(FramebufferTarget.Framebuffer, OffscreenBufferHandle); - } - - public virtual CVOpenGLESTexture LumaTextureForPixelBuffer(CVPixelBuffer pixelBuffer) - { - CVOpenGLESTexture lumaTexture = null; - if (_videoTextureCache == null) - { - Console.Error.WriteLine("No video texture cache"); - goto bail; - } - - // Periodic texture cache flush every frame - _videoTextureCache.Flush(0); - - // CVOpenGLTextureCacheCreateTextureFromImage will create GL texture optimally from CVPixelBufferRef. - // Y - lumaTexture = _videoTextureCache.TextureFromImage(pixelBuffer, - true, - All.RedExt, - (int)pixelBuffer.Width, - (int)pixelBuffer.Height, - All.RedExt, - DataType.UnsignedByte, - 0, - out CVReturn error); - - if (lumaTexture == null || error != CVReturn.Success) - { - Console.Error.WriteLine($"Error at creating luma texture using CVOpenGLESTextureCacheCreateTextureFromImage: {error}"); - } - - bail: - return lumaTexture; - } - - public virtual CVOpenGLESTexture ChromaTextureForPixelBuffer(CVPixelBuffer pixelBuffer) - { - CVOpenGLESTexture chromaTexture = null; - if (_videoTextureCache == null) - { - Console.Error.WriteLine("No video texture cache"); - goto bail; - } - - // Periodic texture cache flush every frame - _videoTextureCache.Flush(0); - - // CVOpenGLTextureCacheCreateTextureFromImage will create GL texture optimally from CVPixelBufferRef. - // UV - var height = pixelBuffer.GetHeightOfPlane(1); - var width = pixelBuffer.GetWidthOfPlane(1); - chromaTexture = _videoTextureCache.TextureFromImage(pixelBuffer, - true, - All.RgExt, - (int)width, - (int)height, - All.RgExt, - DataType.UnsignedByte, - 1, - out CVReturn error); - - if (chromaTexture == null || error != CVReturn.Success) - { - Console.Error.WriteLine($"Error at creating chroma texture using CVOpenGLESTextureCacheCreateTextureFromImage: {error}"); - } - - bail: - return chromaTexture; - } - - #region OpenGL ES 2 shader compilation - - private bool LoadShaders() - { - int vertShader, fragShaderY, fragShaderUV; - - // Create the shader program. - ProgramY = GL.CreateProgram(); - ProgramUV = GL.CreateProgram(); - - // Create and compile the vertex shader. - if (!CompileShader(ShaderType.VertexShader, VertShaderSource, out vertShader)) - { - Console.Error.WriteLine("Failed to compile vertex shader"); - return false; - } - - if (!CompileShader(ShaderType.FragmentShader, FragShaderYSource, out fragShaderY)) - { - Console.Error.WriteLine("Failed to compile Y fragment shader"); - return false; - } - - if (!CompileShader(ShaderType.FragmentShader, FragShaderUVSource, out fragShaderUV)) - { - Console.Error.WriteLine("Failed to compile UV fragment shader"); - return false; - } - - // Attach vertex shader to programY. - GL.AttachShader(ProgramY, vertShader); - - // Attach fragment shader to programY. - GL.AttachShader(ProgramY, fragShaderY); - - // Attach vertex shader to programUV. - GL.AttachShader(ProgramUV, vertShader); - - // Attach fragment shader to programUV. - GL.AttachShader(ProgramUV, fragShaderUV); - - // Bind attribute locations. This needs to be done prior to linking. - GL.BindAttribLocation(ProgramY, (int)Attrib.Vertex_Y, "position"); - GL.BindAttribLocation(ProgramY, (int)Attrib.TexCoord_Y, "texCoord"); - GL.BindAttribLocation(ProgramUV, (int)Attrib.Vertex_UV, "position"); - GL.BindAttribLocation(ProgramUV, (int)Attrib.TexCoord_UV, "texCoord"); - - // Link the program. - if (!LinkProgram(ProgramY) || !LinkProgram(ProgramUV)) - { - Console.Error.WriteLine("Failed to link program"); - if (vertShader != 0) - { - GL.DeleteShader(vertShader); - vertShader = 0; - } - - if (fragShaderY != 0) - { - GL.DeleteShader(fragShaderY); - fragShaderY = 0; - } - - if (fragShaderUV != 0) - { - GL.DeleteShader(fragShaderUV); - fragShaderUV = 0; - } - - if (ProgramY != 0) - { - GL.DeleteProgram(ProgramY); - ProgramY = 0; - } - - if (ProgramUV != 0) - { - GL.DeleteProgram(ProgramUV); - ProgramUV = 0; - } - - return false; - } - - // Get uniform locations. - Uniforms[(int)Uniform.Y] = GL.GetUniformLocation(ProgramY, "SamplerY"); - Uniforms[(int)Uniform.UV] = GL.GetUniformLocation(ProgramUV, "SamplerUV"); - Uniforms[(int)Uniform.Render_Transform_Y] = GL.GetUniformLocation(ProgramY, "renderTransform"); - Uniforms[(int)Uniform.Render_Transform_UV] = GL.GetUniformLocation(ProgramUV, "renderTransform"); - - // Release vertex and fragment shaders. - if (vertShader != 0) - { - GL.DetachShader(ProgramY, vertShader); - GL.DetachShader(ProgramUV, vertShader); - GL.DeleteShader(vertShader); - } - - if (fragShaderY != 0) - { - GL.DetachShader(ProgramY, fragShaderY); - GL.DeleteShader(fragShaderY); - } - - if (fragShaderUV != 0) - { - GL.DetachShader(ProgramUV, fragShaderUV); - GL.DeleteShader(fragShaderUV); - } - - return true; - } - - private static bool CompileShader(ShaderType type, string sourceString, out int shader) - { - if (string.IsNullOrEmpty(sourceString)) - { - Console.Error.WriteLine("Failed to load vertex shader: Empty source string"); - shader = 0; - return false; - } - - shader = GL.CreateShader(type); - GL.ShaderSource(shader, sourceString); - GL.CompileShader(shader); + public uint OffscreenBufferHandle; + + public OpenGLRenderer () + { + CurrentContext = new EAGLContext (EAGLRenderingAPI.OpenGLES2); + EAGLContext.SetCurrentContext (CurrentContext); + + SetupOffScreenRenderContext (); + LoadShaders (); + + EAGLContext.SetCurrentContext (null); + } + + public int ProgramY { get; set; } = -1; + public int ProgramUV { get; set; } = -1; + public CGAffineTransform RenderTransform { get; set; } + public CVOpenGLESTextureCache _videoTextureCache { get; set; } + public EAGLContext CurrentContext { get; set; } + public int [] Uniforms { get; set; } = new int [(int) Uniform.Num_Uniforms]; + + public virtual void RenderPixelBuffer (CVPixelBuffer destinationPixelBuffer, CVPixelBuffer foregroundPixelBuffer, CVPixelBuffer backgroundPixelBuffer, float tween) + { + DoesNotRecognizeSelector (new ObjCRuntime.Selector ("_cmd")); + } + + public void SetupOffScreenRenderContext () + { + //-- Create CVOpenGLESTextureCacheRef for optimal CVPixelBufferRef to GLES texture conversion. + if (_videoTextureCache != null) { + _videoTextureCache.Dispose (); + _videoTextureCache = null; + } + + _videoTextureCache = CVOpenGLESTextureCache.FromEAGLContext (CurrentContext); + + GL.Disable (EnableCap.DepthTest); + GL.GenFramebuffers (1, out OffscreenBufferHandle); + GL.BindFramebuffer (FramebufferTarget.Framebuffer, OffscreenBufferHandle); + } + + public virtual CVOpenGLESTexture LumaTextureForPixelBuffer (CVPixelBuffer pixelBuffer) + { + CVOpenGLESTexture lumaTexture = null; + if (_videoTextureCache == null) { + Console.Error.WriteLine ("No video texture cache"); + goto bail; + } + + // Periodic texture cache flush every frame + _videoTextureCache.Flush (0); + + // CVOpenGLTextureCacheCreateTextureFromImage will create GL texture optimally from CVPixelBufferRef. + // Y + lumaTexture = _videoTextureCache.TextureFromImage (pixelBuffer, + true, + All.RedExt, + (int) pixelBuffer.Width, + (int) pixelBuffer.Height, + All.RedExt, + DataType.UnsignedByte, + 0, + out CVReturn error); + + if (lumaTexture == null || error != CVReturn.Success) { + Console.Error.WriteLine ($"Error at creating luma texture using CVOpenGLESTextureCacheCreateTextureFromImage: {error}"); + } + + bail: + return lumaTexture; + } + + public virtual CVOpenGLESTexture ChromaTextureForPixelBuffer (CVPixelBuffer pixelBuffer) + { + CVOpenGLESTexture chromaTexture = null; + if (_videoTextureCache == null) { + Console.Error.WriteLine ("No video texture cache"); + goto bail; + } + + // Periodic texture cache flush every frame + _videoTextureCache.Flush (0); + + // CVOpenGLTextureCacheCreateTextureFromImage will create GL texture optimally from CVPixelBufferRef. + // UV + var height = pixelBuffer.GetHeightOfPlane (1); + var width = pixelBuffer.GetWidthOfPlane (1); + chromaTexture = _videoTextureCache.TextureFromImage (pixelBuffer, + true, + All.RgExt, + (int) width, + (int) height, + All.RgExt, + DataType.UnsignedByte, + 1, + out CVReturn error); + + if (chromaTexture == null || error != CVReturn.Success) { + Console.Error.WriteLine ($"Error at creating chroma texture using CVOpenGLESTextureCacheCreateTextureFromImage: {error}"); + } + + bail: + return chromaTexture; + } + + #region OpenGL ES 2 shader compilation + + private bool LoadShaders () + { + int vertShader, fragShaderY, fragShaderUV; + + // Create the shader program. + ProgramY = GL.CreateProgram (); + ProgramUV = GL.CreateProgram (); + + // Create and compile the vertex shader. + if (!CompileShader (ShaderType.VertexShader, VertShaderSource, out vertShader)) { + Console.Error.WriteLine ("Failed to compile vertex shader"); + return false; + } + + if (!CompileShader (ShaderType.FragmentShader, FragShaderYSource, out fragShaderY)) { + Console.Error.WriteLine ("Failed to compile Y fragment shader"); + return false; + } + + if (!CompileShader (ShaderType.FragmentShader, FragShaderUVSource, out fragShaderUV)) { + Console.Error.WriteLine ("Failed to compile UV fragment shader"); + return false; + } + + // Attach vertex shader to programY. + GL.AttachShader (ProgramY, vertShader); + + // Attach fragment shader to programY. + GL.AttachShader (ProgramY, fragShaderY); + + // Attach vertex shader to programUV. + GL.AttachShader (ProgramUV, vertShader); + + // Attach fragment shader to programUV. + GL.AttachShader (ProgramUV, fragShaderUV); + + // Bind attribute locations. This needs to be done prior to linking. + GL.BindAttribLocation (ProgramY, (int) Attrib.Vertex_Y, "position"); + GL.BindAttribLocation (ProgramY, (int) Attrib.TexCoord_Y, "texCoord"); + GL.BindAttribLocation (ProgramUV, (int) Attrib.Vertex_UV, "position"); + GL.BindAttribLocation (ProgramUV, (int) Attrib.TexCoord_UV, "texCoord"); + + // Link the program. + if (!LinkProgram (ProgramY) || !LinkProgram (ProgramUV)) { + Console.Error.WriteLine ("Failed to link program"); + if (vertShader != 0) { + GL.DeleteShader (vertShader); + vertShader = 0; + } + + if (fragShaderY != 0) { + GL.DeleteShader (fragShaderY); + fragShaderY = 0; + } + + if (fragShaderUV != 0) { + GL.DeleteShader (fragShaderUV); + fragShaderUV = 0; + } + + if (ProgramY != 0) { + GL.DeleteProgram (ProgramY); + ProgramY = 0; + } + + if (ProgramUV != 0) { + GL.DeleteProgram (ProgramUV); + ProgramUV = 0; + } + + return false; + } + + // Get uniform locations. + Uniforms [(int) Uniform.Y] = GL.GetUniformLocation (ProgramY, "SamplerY"); + Uniforms [(int) Uniform.UV] = GL.GetUniformLocation (ProgramUV, "SamplerUV"); + Uniforms [(int) Uniform.Render_Transform_Y] = GL.GetUniformLocation (ProgramY, "renderTransform"); + Uniforms [(int) Uniform.Render_Transform_UV] = GL.GetUniformLocation (ProgramUV, "renderTransform"); + + // Release vertex and fragment shaders. + if (vertShader != 0) { + GL.DetachShader (ProgramY, vertShader); + GL.DetachShader (ProgramUV, vertShader); + GL.DeleteShader (vertShader); + } + + if (fragShaderY != 0) { + GL.DetachShader (ProgramY, fragShaderY); + GL.DeleteShader (fragShaderY); + } + + if (fragShaderUV != 0) { + GL.DetachShader (ProgramUV, fragShaderUV); + GL.DeleteShader (fragShaderUV); + } + + return true; + } + + private static bool CompileShader (ShaderType type, string sourceString, out int shader) + { + if (string.IsNullOrEmpty (sourceString)) { + Console.Error.WriteLine ("Failed to load vertex shader: Empty source string"); + shader = 0; + return false; + } + + shader = GL.CreateShader (type); + GL.ShaderSource (shader, sourceString); + GL.CompileShader (shader); #if DEBUG GL.GetShader(shader, ShaderParameter.InfoLogLength, out int logLength); @@ -278,19 +258,18 @@ private static bool CompileShader(ShaderType type, string sourceString, out int } #endif - GL.GetShader(shader, ShaderParameter.CompileStatus, out int status); - if (status == 0) - { - GL.DeleteShader(shader); - return false; - } + GL.GetShader (shader, ShaderParameter.CompileStatus, out int status); + if (status == 0) { + GL.DeleteShader (shader); + return false; + } - return true; - } + return true; + } - private static bool LinkProgram(int program) - { - GL.LinkProgram(program); + private static bool LinkProgram (int program) + { + GL.LinkProgram (program); #if DEBUG GL.GetProgram(program, ProgramParameter.InfoLogLength, out int logLength); @@ -303,28 +282,26 @@ private static bool LinkProgram(int program) } #endif - GL.GetProgram(program, ProgramParameter.LinkStatus, out int status); - return status != 0; - } - } - - #endregion - - public enum Uniform - { - Y, - UV, - Render_Transform_Y, - Render_Transform_UV, - Num_Uniforms - } - - public enum Attrib - { - Vertex_Y, - TexCoord_Y, - Vertex_UV, - TexCoord_UV, - Num_Attributes - } -} \ No newline at end of file + GL.GetProgram (program, ProgramParameter.LinkStatus, out int status); + return status != 0; + } + } + + #endregion + + public enum Uniform { + Y, + UV, + Render_Transform_Y, + Render_Transform_UV, + Num_Uniforms + } + + public enum Attrib { + Vertex_Y, + TexCoord_Y, + Vertex_UV, + TexCoord_UV, + Num_Attributes + } +} diff --git a/AVCustomEdit/AVCustomEdit/PlayerView.cs b/AVCustomEdit/AVCustomEdit/PlayerView.cs index af61f8dad..dc51e74ad 100644 --- a/AVCustomEdit/AVCustomEdit/PlayerView.cs +++ b/AVCustomEdit/AVCustomEdit/PlayerView.cs @@ -1,35 +1,28 @@ -using AVFoundation; +using AVFoundation; using Foundation; using ObjCRuntime; using System; using UIKit; -namespace AVCustomEdit -{ - [Register("PlayerView")] - public class PlayerView : UIView - { - public PlayerView(IntPtr handle) : base(handle) { } +namespace AVCustomEdit { + [Register ("PlayerView")] + public class PlayerView : UIView { + public PlayerView (IntPtr handle) : base (handle) { } - public AVPlayer Player - { - get - { - return (this.Layer as AVPlayerLayer).Player; - } - set - { - (this.Layer as AVPlayerLayer).Player = value; - } - } + public AVPlayer Player { + get { + return (this.Layer as AVPlayerLayer).Player; + } + set { + (this.Layer as AVPlayerLayer).Player = value; + } + } - public static Class LayerClass - { - [Export("layerClass")] - get - { - return new Class(typeof(AVPlayerLayer)); - } - } - } + public static Class LayerClass { + [Export ("layerClass")] + get { + return new Class (typeof (AVPlayerLayer)); + } + } + } } diff --git a/AVCustomEdit/AVCustomEdit/SimpleEditor.cs b/AVCustomEdit/AVCustomEdit/SimpleEditor.cs index 8e12d9f45..e7125c7dd 100644 --- a/AVCustomEdit/AVCustomEdit/SimpleEditor.cs +++ b/AVCustomEdit/AVCustomEdit/SimpleEditor.cs @@ -3,210 +3,186 @@ using Foundation; using System.Collections.Generic; -namespace AVCustomEdit -{ - public class SimpleEditor : NSObject - { - private AVMutableComposition composition; - - private AVMutableVideoComposition videoComposition; - - public List Clips { get; set; } // array of AVURLAssets - - public List ClipTimeRanges { get; set; } - - public TransitionType TransitionType { get; set; } - - public CMTime TransitionDuration { get; set; } - - public AVPlayerItem PlayerItem { - get { - if (composition == null) - return null; - return new AVPlayerItem(this.composition) { VideoComposition = this.videoComposition }; - } - } - - private void BuildTransitionComposition(AVMutableComposition mutableComposition, AVMutableVideoComposition mutableVideoComposition) - { - var nextClipStartTime = CMTime.Zero; - var clipsCount = this.Clips.Count; - - // Make transitionDuration no greater than half the shortest clip duration. - var transitionDuration = this.TransitionDuration; - foreach (var clipTimeRange in this.ClipTimeRanges) - { - var halfClipDuration = clipTimeRange.Duration; - halfClipDuration.TimeScale *= 2; // You can halve a rational by doubling its denominator. - transitionDuration = CMTime.GetMinimum(transitionDuration, halfClipDuration); - } - - // Add two video tracks and two audio tracks. - var compositionVideoTracks = new AVMutableCompositionTrack[2]; - var compositionAudioTracks = new AVMutableCompositionTrack[2]; - - compositionVideoTracks[0] = mutableComposition.AddMutableTrack(AVMediaType.Video, 0); - compositionVideoTracks[1] = mutableComposition.AddMutableTrack(AVMediaType.Video, 0); - compositionAudioTracks[0] = mutableComposition.AddMutableTrack(AVMediaType.Audio, 0); - compositionAudioTracks[1] = mutableComposition.AddMutableTrack(AVMediaType.Audio, 0); - - var passThroughTimeRanges = new CMTimeRange[clipsCount]; - var transitionTimeRanges = new CMTimeRange[clipsCount]; - - // Place clips into alternating video & audio tracks in composition, overlapped by transitionDuration. - for (int i = 0; i < clipsCount; i++) - { - int alternatingIndex = i % 2; // alternating targets: 0, 1, 0, 1, ... - var asset = this.Clips[i]; - var timeRangeInAsset = this.ClipTimeRanges[i]; - - var clipVideoTrack = asset.TracksWithMediaType(AVMediaType.Video)[0]; - compositionVideoTracks[alternatingIndex].InsertTimeRange(timeRangeInAsset, clipVideoTrack, nextClipStartTime, out _); - - var clipAudioTrack = asset.TracksWithMediaType(AVMediaType.Audio)[0]; - compositionAudioTracks[alternatingIndex].InsertTimeRange(timeRangeInAsset, clipAudioTrack, nextClipStartTime, out _); - - // Remember the time range in which this clip should pass through. - // First clip ends with a transition. - // Second clip begins with a transition. - // Exclude that transition from the pass through time ranges - passThroughTimeRanges[i] = new CMTimeRange { Start = nextClipStartTime, Duration = timeRangeInAsset.Duration }; - - if (i > 0) - { - passThroughTimeRanges[i].Start = CMTime.Add(passThroughTimeRanges[i].Start, transitionDuration); - passThroughTimeRanges[i].Duration = CMTime.Subtract(passThroughTimeRanges[i].Duration, transitionDuration); - } - - if (i + 1 < clipsCount) - { - passThroughTimeRanges[i].Duration = CMTime.Subtract(passThroughTimeRanges[i].Duration, transitionDuration); - } - - // The end of this clip will overlap the start of the next by transitionDuration. - // (Note: this arithmetic falls apart if timeRangeInAsset.duration < 2 * transitionDuration.) - nextClipStartTime = CMTime.Add(nextClipStartTime, timeRangeInAsset.Duration); - nextClipStartTime = CMTime.Subtract(nextClipStartTime, transitionDuration); - - // Remember the time range for the transition to the next item. - if (i + 1 < clipsCount) - { - transitionTimeRanges[i] = new CMTimeRange { Start = nextClipStartTime, Duration = transitionDuration }; - } - } - - // Set up the video composition to perform cross dissolve or diagonal wipe transitions between clips. - var instructions = new List(); - - // Cycle between "pass through A", "transition from A to B", "pass through B" - for (int i = 0; i < clipsCount; i++) - { - int alternatingIndex = i % 2; // alternating targets - - if (mutableVideoComposition.CustomVideoCompositorClass != null) - { - var videoInstruction = new CustomVideoCompositionInstruction(compositionVideoTracks[alternatingIndex].TrackID, passThroughTimeRanges[i]); - instructions.Add(videoInstruction); - } - else - { - // Pass through clip i. - var passThroughInstruction = AVMutableVideoCompositionInstruction.Create() as AVMutableVideoCompositionInstruction; - passThroughInstruction.TimeRange = passThroughTimeRanges[i]; - - var passThroughLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack(compositionVideoTracks[alternatingIndex]); - passThroughInstruction.LayerInstructions = new[] { passThroughLayer }; - - instructions.Add(passThroughInstruction); - } - - if (i + 1 < clipsCount) - { - // Add transition from clip i to clip i+1. - if (mutableVideoComposition.CustomVideoCompositorClass != null) - { - var videoInstruction = new CustomVideoCompositionInstruction(new NSNumber[] - { - compositionVideoTracks[0].TrackID, - compositionVideoTracks[1].TrackID - }, transitionTimeRanges[i]); - - if (alternatingIndex == 0) - { - // First track -> Foreground track while compositing - videoInstruction.ForegroundTrackId = compositionVideoTracks[alternatingIndex].TrackID; - // Second track -> Background track while compositing - videoInstruction.BackgroundTrackId = compositionVideoTracks[1 - alternatingIndex].TrackID; - } - - instructions.Add(videoInstruction); - } - else - { - var transitionInstruction = AVMutableVideoCompositionInstruction.Create() as AVMutableVideoCompositionInstruction; - transitionInstruction.TimeRange = transitionTimeRanges[i]; - - var fromLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack(compositionVideoTracks[alternatingIndex]); - var toLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack(compositionVideoTracks[1 - alternatingIndex]); - - transitionInstruction.LayerInstructions = new[] { toLayer, fromLayer }; - instructions.Add(transitionInstruction); - } - } - } - - mutableVideoComposition.Instructions = instructions.ToArray(); - } - - public void BuildCompositionObjectsForPlayback(bool playback) - { - if (Clips == null || Clips.Count == 0) - { - this.composition = null; - this.videoComposition = null; - } - else - { - var videoSize = Clips[0].NaturalSize; - var mutableComposition = AVMutableComposition.Create(); - AVMutableVideoComposition mutableVideoComposition = null; - - mutableComposition.NaturalSize = videoSize; - - // With transitions: - // Place clips into alternating video & audio tracks in composition, overlapped by transitionDuration. - // Set up the video composition to cycle between "pass through A", "transition from A to B", - // "pass through B". - - mutableVideoComposition = AVMutableVideoComposition.Create(); - if (TransitionType == TransitionType.DiagonalWipeTransition) - { - mutableVideoComposition.CustomVideoCompositorClass = new ObjCRuntime.Class(typeof(DiagonalWipeCompositor)); - } - else - { - mutableVideoComposition.CustomVideoCompositorClass = new ObjCRuntime.Class(typeof(CrossDissolveCompositor)); - } - - BuildTransitionComposition(mutableComposition, mutableVideoComposition); - if (mutableVideoComposition != null) - { - // Every videoComposition needs these properties to be set: - mutableVideoComposition.FrameDuration = new CMTime(1, 30); - mutableVideoComposition.RenderSize = videoSize; - } - - this.composition = mutableComposition; - this.videoComposition = mutableVideoComposition; - } - } - - public AVAssetExportSession AssetExportSessionWithPreset(string presetName) - { - return new AVAssetExportSession(composition, presetName) - { - VideoComposition = videoComposition - }; - } - } -} \ No newline at end of file +namespace AVCustomEdit { + public class SimpleEditor : NSObject { + private AVMutableComposition composition; + + private AVMutableVideoComposition videoComposition; + + public List Clips { get; set; } // array of AVURLAssets + + public List ClipTimeRanges { get; set; } + + public TransitionType TransitionType { get; set; } + + public CMTime TransitionDuration { get; set; } + + public AVPlayerItem PlayerItem { + get { + if (composition == null) + return null; + return new AVPlayerItem (this.composition) { VideoComposition = this.videoComposition }; + } + } + + private void BuildTransitionComposition (AVMutableComposition mutableComposition, AVMutableVideoComposition mutableVideoComposition) + { + var nextClipStartTime = CMTime.Zero; + var clipsCount = this.Clips.Count; + + // Make transitionDuration no greater than half the shortest clip duration. + var transitionDuration = this.TransitionDuration; + foreach (var clipTimeRange in this.ClipTimeRanges) { + var halfClipDuration = clipTimeRange.Duration; + halfClipDuration.TimeScale *= 2; // You can halve a rational by doubling its denominator. + transitionDuration = CMTime.GetMinimum (transitionDuration, halfClipDuration); + } + + // Add two video tracks and two audio tracks. + var compositionVideoTracks = new AVMutableCompositionTrack [2]; + var compositionAudioTracks = new AVMutableCompositionTrack [2]; + + compositionVideoTracks [0] = mutableComposition.AddMutableTrack (AVMediaType.Video, 0); + compositionVideoTracks [1] = mutableComposition.AddMutableTrack (AVMediaType.Video, 0); + compositionAudioTracks [0] = mutableComposition.AddMutableTrack (AVMediaType.Audio, 0); + compositionAudioTracks [1] = mutableComposition.AddMutableTrack (AVMediaType.Audio, 0); + + var passThroughTimeRanges = new CMTimeRange [clipsCount]; + var transitionTimeRanges = new CMTimeRange [clipsCount]; + + // Place clips into alternating video & audio tracks in composition, overlapped by transitionDuration. + for (int i = 0; i < clipsCount; i++) { + int alternatingIndex = i % 2; // alternating targets: 0, 1, 0, 1, ... + var asset = this.Clips [i]; + var timeRangeInAsset = this.ClipTimeRanges [i]; + + var clipVideoTrack = asset.TracksWithMediaType (AVMediaType.Video) [0]; + compositionVideoTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipVideoTrack, nextClipStartTime, out _); + + var clipAudioTrack = asset.TracksWithMediaType (AVMediaType.Audio) [0]; + compositionAudioTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipAudioTrack, nextClipStartTime, out _); + + // Remember the time range in which this clip should pass through. + // First clip ends with a transition. + // Second clip begins with a transition. + // Exclude that transition from the pass through time ranges + passThroughTimeRanges [i] = new CMTimeRange { Start = nextClipStartTime, Duration = timeRangeInAsset.Duration }; + + if (i > 0) { + passThroughTimeRanges [i].Start = CMTime.Add (passThroughTimeRanges [i].Start, transitionDuration); + passThroughTimeRanges [i].Duration = CMTime.Subtract (passThroughTimeRanges [i].Duration, transitionDuration); + } + + if (i + 1 < clipsCount) { + passThroughTimeRanges [i].Duration = CMTime.Subtract (passThroughTimeRanges [i].Duration, transitionDuration); + } + + // The end of this clip will overlap the start of the next by transitionDuration. + // (Note: this arithmetic falls apart if timeRangeInAsset.duration < 2 * transitionDuration.) + nextClipStartTime = CMTime.Add (nextClipStartTime, timeRangeInAsset.Duration); + nextClipStartTime = CMTime.Subtract (nextClipStartTime, transitionDuration); + + // Remember the time range for the transition to the next item. + if (i + 1 < clipsCount) { + transitionTimeRanges [i] = new CMTimeRange { Start = nextClipStartTime, Duration = transitionDuration }; + } + } + + // Set up the video composition to perform cross dissolve or diagonal wipe transitions between clips. + var instructions = new List (); + + // Cycle between "pass through A", "transition from A to B", "pass through B" + for (int i = 0; i < clipsCount; i++) { + int alternatingIndex = i % 2; // alternating targets + + if (mutableVideoComposition.CustomVideoCompositorClass != null) { + var videoInstruction = new CustomVideoCompositionInstruction (compositionVideoTracks [alternatingIndex].TrackID, passThroughTimeRanges [i]); + instructions.Add (videoInstruction); + } else { + // Pass through clip i. + var passThroughInstruction = AVMutableVideoCompositionInstruction.Create () as AVMutableVideoCompositionInstruction; + passThroughInstruction.TimeRange = passThroughTimeRanges [i]; + + var passThroughLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [alternatingIndex]); + passThroughInstruction.LayerInstructions = new [] { passThroughLayer }; + + instructions.Add (passThroughInstruction); + } + + if (i + 1 < clipsCount) { + // Add transition from clip i to clip i+1. + if (mutableVideoComposition.CustomVideoCompositorClass != null) { + var videoInstruction = new CustomVideoCompositionInstruction (new NSNumber [] + { + compositionVideoTracks[0].TrackID, + compositionVideoTracks[1].TrackID + }, transitionTimeRanges [i]); + + if (alternatingIndex == 0) { + // First track -> Foreground track while compositing + videoInstruction.ForegroundTrackId = compositionVideoTracks [alternatingIndex].TrackID; + // Second track -> Background track while compositing + videoInstruction.BackgroundTrackId = compositionVideoTracks [1 - alternatingIndex].TrackID; + } + + instructions.Add (videoInstruction); + } else { + var transitionInstruction = AVMutableVideoCompositionInstruction.Create () as AVMutableVideoCompositionInstruction; + transitionInstruction.TimeRange = transitionTimeRanges [i]; + + var fromLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [alternatingIndex]); + var toLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [1 - alternatingIndex]); + + transitionInstruction.LayerInstructions = new [] { toLayer, fromLayer }; + instructions.Add (transitionInstruction); + } + } + } + + mutableVideoComposition.Instructions = instructions.ToArray (); + } + + public void BuildCompositionObjectsForPlayback (bool playback) + { + if (Clips == null || Clips.Count == 0) { + this.composition = null; + this.videoComposition = null; + } else { + var videoSize = Clips [0].NaturalSize; + var mutableComposition = AVMutableComposition.Create (); + AVMutableVideoComposition mutableVideoComposition = null; + + mutableComposition.NaturalSize = videoSize; + + // With transitions: + // Place clips into alternating video & audio tracks in composition, overlapped by transitionDuration. + // Set up the video composition to cycle between "pass through A", "transition from A to B", + // "pass through B". + + mutableVideoComposition = AVMutableVideoComposition.Create (); + if (TransitionType == TransitionType.DiagonalWipeTransition) { + mutableVideoComposition.CustomVideoCompositorClass = new ObjCRuntime.Class (typeof (DiagonalWipeCompositor)); + } else { + mutableVideoComposition.CustomVideoCompositorClass = new ObjCRuntime.Class (typeof (CrossDissolveCompositor)); + } + + BuildTransitionComposition (mutableComposition, mutableVideoComposition); + if (mutableVideoComposition != null) { + // Every videoComposition needs these properties to be set: + mutableVideoComposition.FrameDuration = new CMTime (1, 30); + mutableVideoComposition.RenderSize = videoSize; + } + + this.composition = mutableComposition; + this.videoComposition = mutableVideoComposition; + } + } + + public AVAssetExportSession AssetExportSessionWithPreset (string presetName) + { + return new AVAssetExportSession (composition, presetName) { + VideoComposition = videoComposition + }; + } + } +} diff --git a/AVCustomEdit/AVCustomEdit/TransitionTypeController.cs b/AVCustomEdit/AVCustomEdit/TransitionTypeController.cs index 7883afaf6..b44549dd4 100644 --- a/AVCustomEdit/AVCustomEdit/TransitionTypeController.cs +++ b/AVCustomEdit/AVCustomEdit/TransitionTypeController.cs @@ -2,67 +2,59 @@ using System; using UIKit; -namespace AVCustomEdit -{ - public interface ITransitionTypePickerDelegate - { - void DidPickTransitionType(TransitionType transitionType); - } - - public partial class TransitionTypeController : UITableViewController - { - public TransitionTypeController(IntPtr handle) : base(handle) { } - - public ITransitionTypePickerDelegate Delegate { get; set; } - - public TransitionType CurrentTransition { get; set; } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - switch (this.CurrentTransition) - { - case TransitionType.CrossDissolveTransition: - this.crossDissolveCell.Accessory = UITableViewCellAccessory.Checkmark; - break; - - case TransitionType.DiagonalWipeTransition: - this.diagonalWipeCell.Accessory = UITableViewCellAccessory.Checkmark; - break; - } - } - - partial void TransitionSelected(UIBarButtonItem sender) - { - this.Delegate.DidPickTransitionType(this.CurrentTransition); - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var selectedCell = tableView.CellAt(indexPath); - selectedCell.Accessory = UITableViewCellAccessory.Checkmark; - - if (selectedCell == this.diagonalWipeCell) - { - this.crossDissolveCell.Accessory = UITableViewCellAccessory.None; - this.CurrentTransition = TransitionType.DiagonalWipeTransition; - this.Delegate.DidPickTransitionType(TransitionType.DiagonalWipeTransition); - } - else if (selectedCell == this.crossDissolveCell) - { - this.diagonalWipeCell.Accessory = UITableViewCellAccessory.None; - this.CurrentTransition = TransitionType.CrossDissolveTransition; - this.Delegate.DidPickTransitionType(TransitionType.CrossDissolveTransition); - } - - tableView.DeselectRow(indexPath, true); - } - } - - public enum TransitionType - { - DiagonalWipeTransition = 0, - CrossDissolveTransition = 1, - } -} \ No newline at end of file +namespace AVCustomEdit { + public interface ITransitionTypePickerDelegate { + void DidPickTransitionType (TransitionType transitionType); + } + + public partial class TransitionTypeController : UITableViewController { + public TransitionTypeController (IntPtr handle) : base (handle) { } + + public ITransitionTypePickerDelegate Delegate { get; set; } + + public TransitionType CurrentTransition { get; set; } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + switch (this.CurrentTransition) { + case TransitionType.CrossDissolveTransition: + this.crossDissolveCell.Accessory = UITableViewCellAccessory.Checkmark; + break; + + case TransitionType.DiagonalWipeTransition: + this.diagonalWipeCell.Accessory = UITableViewCellAccessory.Checkmark; + break; + } + } + + partial void TransitionSelected (UIBarButtonItem sender) + { + this.Delegate.DidPickTransitionType (this.CurrentTransition); + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var selectedCell = tableView.CellAt (indexPath); + selectedCell.Accessory = UITableViewCellAccessory.Checkmark; + + if (selectedCell == this.diagonalWipeCell) { + this.crossDissolveCell.Accessory = UITableViewCellAccessory.None; + this.CurrentTransition = TransitionType.DiagonalWipeTransition; + this.Delegate.DidPickTransitionType (TransitionType.DiagonalWipeTransition); + } else if (selectedCell == this.crossDissolveCell) { + this.diagonalWipeCell.Accessory = UITableViewCellAccessory.None; + this.CurrentTransition = TransitionType.CrossDissolveTransition; + this.Delegate.DidPickTransitionType (TransitionType.CrossDissolveTransition); + } + + tableView.DeselectRow (indexPath, true); + } + } + + public enum TransitionType { + DiagonalWipeTransition = 0, + CrossDissolveTransition = 1, + } +} diff --git a/AVCustomEdit/AVCustomEdit/ViewController.cs b/AVCustomEdit/AVCustomEdit/ViewController.cs index e4779bf2e..512392ee9 100644 --- a/AVCustomEdit/AVCustomEdit/ViewController.cs +++ b/AVCustomEdit/AVCustomEdit/ViewController.cs @@ -1,4 +1,4 @@ -using AssetsLibrary; +using AssetsLibrary; using AVFoundation; using CoreFoundation; using CoreMedia; @@ -9,560 +9,502 @@ using System.IO; using UIKit; -namespace AVCustomEdit -{ - public partial class ViewController : UIViewController, IUIGestureRecognizerDelegate, ITransitionTypePickerDelegate - { - private readonly NSString StatusObservationContext = new NSString("AVCustomEditPlayerViewControllerStatusObservationContext"); - private readonly NSString RateObservationContext = new NSString("AVCustomEditPlayerViewControllerRateObservationContext"); - - private SimpleEditor editor; - - private List clips; - private List clipTimeRanges; - - private AVPlayer player; - private AVPlayerItem playerItem; - - private bool isPlaying; - private bool isScrubInFlight; - private bool isSeekToZeroBeforePlaying; - private float lastScrubSliderValue; - private float playRateToRestore; - private NSObject timeObserver; - - private float transitionDuration; - private TransitionType transitionType; - private bool isTransitionsEnabled; - - private NSTimer progressTimer; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.editor = new SimpleEditor(); - this.clips = new List(2); - this.clipTimeRanges = new List(2); - - // Defaults for the transition settings. - this.transitionType = TransitionType.DiagonalWipeTransition; - this.transitionDuration = 2f; - this.isTransitionsEnabled = true; - - this.UpdateScrubber(); - this.UpdateTimeLabel(); - - // Add the clips from the main bundle to create a composition using them - this.SetupEditingAndPlayback(); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - if (this.player == null) - { - this.isSeekToZeroBeforePlaying = false; - - this.player = new AVPlayer(); - this.player.AddObserver(this, "rate", NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, RateObservationContext.Handle); - this.playerView.Player = this.player; - } - - this.AddTimeObserverToPlayer(); - - // Build AVComposition and AVVideoComposition objects for playback - this.editor.BuildCompositionObjectsForPlayback(true); - this.SynchronizePlayerWithEditor(); - } - - public override void ViewWillDisappear(bool animated) - { - base.ViewWillDisappear(animated); - this.player.Pause(); - this.RemoveTimeObserverFromPlayer(); - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "Transition") - { - // Setup transition type picker controller before it is shown. - if ((segue.DestinationViewController as UINavigationController)?.TopViewController is TransitionTypeController transitionTypePickerController) - { - transitionTypePickerController.Delegate = this; - transitionTypePickerController.CurrentTransition = this.transitionType; - } - } - } - - #region Simple Editor - - private void SetupEditingAndPlayback() - { - var path1 = NSBundle.MainBundle.PathForResource("sample_clip1", "m4v"); - var path2 = NSBundle.MainBundle.PathForResource("sample_clip2", "mov"); - var asset1 = AVAsset.FromUrl(new NSUrl(path1, false)) as AVUrlAsset; - var asset2 = AVAsset.FromUrl(new NSUrl(path2, false)) as AVUrlAsset; - - var dispatchGroup = DispatchGroup.Create(); - string[] assetKeysToLoadAndTest = { "tracks", "duration", "composable" }; - - this.LoadAsset(asset1, assetKeysToLoadAndTest, dispatchGroup); - this.LoadAsset(asset2, assetKeysToLoadAndTest, dispatchGroup); - - // Wait until both assets are loaded - dispatchGroup.Notify(DispatchQueue.MainQueue, () => { - SynchronizeWithEditor(); - }); - } - - private void LoadAsset(AVAsset asset, string[] assetKeysToLoad, DispatchGroup dispatchGroup) - { - dispatchGroup.Enter(); - asset.LoadValuesAsynchronously(assetKeysToLoad, () => - { - bool add_asset = true; - // First test whether the values of each of the keys we need have been successfully loaded. - foreach (var key in assetKeysToLoad) - { - if (asset.StatusOfValue(key, out NSError error) == AVKeyValueStatus.Failed) - { - Console.WriteLine($"Key value loading failed for key:{key} with error: {error?.LocalizedDescription ?? ""}"); - add_asset = false; - break; - } - } - - if (!asset.Composable) - { - Console.WriteLine("Asset is not composable"); - add_asset = false; - } - - if (add_asset) - { - this.clips.Add(asset); - // This code assumes that both assets are atleast 5 seconds long. - var value = new CMTimeRange { Start = CMTime.FromSeconds(0, 1), Duration = CMTime.FromSeconds(5, 1) }; - this.clipTimeRanges.Add(value); - } - - dispatchGroup.Leave(); - }); - } - - private void SynchronizePlayerWithEditor() - { - if (this.player != null) - { - var playerItem = this.editor.PlayerItem; - if (this.playerItem != playerItem) - { - if (this.playerItem != null) - { - this.playerItem.RemoveObserver(this, "status"); - NSNotificationCenter.DefaultCenter.RemoveObserver(this, AVPlayerItem.DidPlayToEndTimeNotification, this.playerItem); - } - - this.playerItem = playerItem; - if (this.playerItem != null) - { - this.playerItem.SeekingWaitsForVideoCompositionRendering = true; - - // Observe the player item "status" key to determine when it is ready to play - this.playerItem.AddObserver(this, "status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); - - // When the player item has played to its end time we'll set a flag - // so that the next time the play method is issued the player will - // be reset to time zero first. - NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, this.PlayerItemDidReachEnd); - } - - this.player.ReplaceCurrentItemWithPlayerItem(this.playerItem); - } - } - } - - private void SynchronizeWithEditor() - { - // Clips - this.editor.Clips = new List (clips); - this.editor.ClipTimeRanges = new List (clipTimeRanges); - - // Transitions - if (this.isTransitionsEnabled) - { - this.editor.TransitionDuration = CMTime.FromSeconds(this.transitionDuration, 600); - this.editor.TransitionType = this.transitionType; - } - else - { - this.editor.TransitionDuration = CMTime.Invalid; - } - - // Build AVComposition and AVVideoComposition objects for playback - this.editor.BuildCompositionObjectsForPlayback(true); - this.SynchronizePlayerWithEditor(); - } - - #endregion - - #region Utilities - - private const int NSEC_PER_SEC = 1000000000; - - /// - /// Update the scrubber and time label periodically. - /// - private void AddTimeObserverToPlayer() - { - if (this.player?.CurrentItem != null && - this.player.CurrentItem.Status == AVPlayerItemStatus.ReadyToPlay) - { - var duration = this.GetPlayerItemDuration().Seconds; - if (!double.IsInfinity(duration)) - { - var width = this.scrubber.Bounds.Width; - var interval = 0.5 * duration / width; - - /* The time label needs to update at least once per second. */ - if (interval > 1.0) - { - interval = 1.0; - } - - timeObserver = this.player.AddPeriodicTimeObserver(CMTime.FromSeconds(interval, NSEC_PER_SEC), - DispatchQueue.MainQueue, - (time) => - { - this.UpdateScrubber(); - this.UpdateTimeLabel(); - }); - } - } - } - - private void RemoveTimeObserverFromPlayer() - { - if (this.timeObserver != null) - { - this.player.RemoveTimeObserver(this.timeObserver); - this.timeObserver.Dispose(); - this.timeObserver = null; - } - } - - private CMTime GetPlayerItemDuration() - { - var itemDuration = CMTime.Invalid; - - var playerItem = this.player?.CurrentItem; - if (playerItem?.Status == AVPlayerItemStatus.ReadyToPlay) - { - itemDuration = playerItem.Duration; - } - - // Will be kCMTimeInvalid if the item is not ready to play. - return itemDuration; - } - - public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) - { - if (context == this.RateObservationContext.Handle) - { - var changes = new NSObservedChange(change); - if (changes.NewValue is NSNumber newValue && - (changes.OldValue == null || (changes.OldValue is NSNumber oldRate && oldRate.FloatValue != newValue.FloatValue))) - { - this.isPlaying = (newValue.FloatValue != 0f) || (playRateToRestore != 0f); - this.UpdatePlayPauseButton(); - this.UpdateScrubber(); - this.UpdateTimeLabel(); - - // clear - newValue.Dispose(); - newValue = null; - } - } - else if (context == this.StatusObservationContext.Handle) - { - if (ofObject is AVPlayerItem playerItem) - { - if (playerItem.Status == AVPlayerItemStatus.ReadyToPlay) - { - /* Once the AVPlayerItem becomes ready to play, i.e. +namespace AVCustomEdit { + public partial class ViewController : UIViewController, IUIGestureRecognizerDelegate, ITransitionTypePickerDelegate { + private readonly NSString StatusObservationContext = new NSString ("AVCustomEditPlayerViewControllerStatusObservationContext"); + private readonly NSString RateObservationContext = new NSString ("AVCustomEditPlayerViewControllerRateObservationContext"); + + private SimpleEditor editor; + + private List clips; + private List clipTimeRanges; + + private AVPlayer player; + private AVPlayerItem playerItem; + + private bool isPlaying; + private bool isScrubInFlight; + private bool isSeekToZeroBeforePlaying; + private float lastScrubSliderValue; + private float playRateToRestore; + private NSObject timeObserver; + + private float transitionDuration; + private TransitionType transitionType; + private bool isTransitionsEnabled; + + private NSTimer progressTimer; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.editor = new SimpleEditor (); + this.clips = new List (2); + this.clipTimeRanges = new List (2); + + // Defaults for the transition settings. + this.transitionType = TransitionType.DiagonalWipeTransition; + this.transitionDuration = 2f; + this.isTransitionsEnabled = true; + + this.UpdateScrubber (); + this.UpdateTimeLabel (); + + // Add the clips from the main bundle to create a composition using them + this.SetupEditingAndPlayback (); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + if (this.player == null) { + this.isSeekToZeroBeforePlaying = false; + + this.player = new AVPlayer (); + this.player.AddObserver (this, "rate", NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, RateObservationContext.Handle); + this.playerView.Player = this.player; + } + + this.AddTimeObserverToPlayer (); + + // Build AVComposition and AVVideoComposition objects for playback + this.editor.BuildCompositionObjectsForPlayback (true); + this.SynchronizePlayerWithEditor (); + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + this.player.Pause (); + this.RemoveTimeObserverFromPlayer (); + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "Transition") { + // Setup transition type picker controller before it is shown. + if ((segue.DestinationViewController as UINavigationController)?.TopViewController is TransitionTypeController transitionTypePickerController) { + transitionTypePickerController.Delegate = this; + transitionTypePickerController.CurrentTransition = this.transitionType; + } + } + } + + #region Simple Editor + + private void SetupEditingAndPlayback () + { + var path1 = NSBundle.MainBundle.PathForResource ("sample_clip1", "m4v"); + var path2 = NSBundle.MainBundle.PathForResource ("sample_clip2", "mov"); + var asset1 = AVAsset.FromUrl (new NSUrl (path1, false)) as AVUrlAsset; + var asset2 = AVAsset.FromUrl (new NSUrl (path2, false)) as AVUrlAsset; + + var dispatchGroup = DispatchGroup.Create (); + string [] assetKeysToLoadAndTest = { "tracks", "duration", "composable" }; + + this.LoadAsset (asset1, assetKeysToLoadAndTest, dispatchGroup); + this.LoadAsset (asset2, assetKeysToLoadAndTest, dispatchGroup); + + // Wait until both assets are loaded + dispatchGroup.Notify (DispatchQueue.MainQueue, () => { + SynchronizeWithEditor (); + }); + } + + private void LoadAsset (AVAsset asset, string [] assetKeysToLoad, DispatchGroup dispatchGroup) + { + dispatchGroup.Enter (); + asset.LoadValuesAsynchronously (assetKeysToLoad, () => { + bool add_asset = true; + // First test whether the values of each of the keys we need have been successfully loaded. + foreach (var key in assetKeysToLoad) { + if (asset.StatusOfValue (key, out NSError error) == AVKeyValueStatus.Failed) { + Console.WriteLine ($"Key value loading failed for key:{key} with error: {error?.LocalizedDescription ?? ""}"); + add_asset = false; + break; + } + } + + if (!asset.Composable) { + Console.WriteLine ("Asset is not composable"); + add_asset = false; + } + + if (add_asset) { + this.clips.Add (asset); + // This code assumes that both assets are atleast 5 seconds long. + var value = new CMTimeRange { Start = CMTime.FromSeconds (0, 1), Duration = CMTime.FromSeconds (5, 1) }; + this.clipTimeRanges.Add (value); + } + + dispatchGroup.Leave (); + }); + } + + private void SynchronizePlayerWithEditor () + { + if (this.player != null) { + var playerItem = this.editor.PlayerItem; + if (this.playerItem != playerItem) { + if (this.playerItem != null) { + this.playerItem.RemoveObserver (this, "status"); + NSNotificationCenter.DefaultCenter.RemoveObserver (this, AVPlayerItem.DidPlayToEndTimeNotification, this.playerItem); + } + + this.playerItem = playerItem; + if (this.playerItem != null) { + this.playerItem.SeekingWaitsForVideoCompositionRendering = true; + + // Observe the player item "status" key to determine when it is ready to play + this.playerItem.AddObserver (this, "status", NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Initial, StatusObservationContext.Handle); + + // When the player item has played to its end time we'll set a flag + // so that the next time the play method is issued the player will + // be reset to time zero first. + NSNotificationCenter.DefaultCenter.AddObserver (AVPlayerItem.DidPlayToEndTimeNotification, this.PlayerItemDidReachEnd); + } + + this.player.ReplaceCurrentItemWithPlayerItem (this.playerItem); + } + } + } + + private void SynchronizeWithEditor () + { + // Clips + this.editor.Clips = new List (clips); + this.editor.ClipTimeRanges = new List (clipTimeRanges); + + // Transitions + if (this.isTransitionsEnabled) { + this.editor.TransitionDuration = CMTime.FromSeconds (this.transitionDuration, 600); + this.editor.TransitionType = this.transitionType; + } else { + this.editor.TransitionDuration = CMTime.Invalid; + } + + // Build AVComposition and AVVideoComposition objects for playback + this.editor.BuildCompositionObjectsForPlayback (true); + this.SynchronizePlayerWithEditor (); + } + + #endregion + + #region Utilities + + private const int NSEC_PER_SEC = 1000000000; + + /// + /// Update the scrubber and time label periodically. + /// + private void AddTimeObserverToPlayer () + { + if (this.player?.CurrentItem != null && + this.player.CurrentItem.Status == AVPlayerItemStatus.ReadyToPlay) { + var duration = this.GetPlayerItemDuration ().Seconds; + if (!double.IsInfinity (duration)) { + var width = this.scrubber.Bounds.Width; + var interval = 0.5 * duration / width; + + /* The time label needs to update at least once per second. */ + if (interval > 1.0) { + interval = 1.0; + } + + timeObserver = this.player.AddPeriodicTimeObserver (CMTime.FromSeconds (interval, NSEC_PER_SEC), + DispatchQueue.MainQueue, + (time) => { + this.UpdateScrubber (); + this.UpdateTimeLabel (); + }); + } + } + } + + private void RemoveTimeObserverFromPlayer () + { + if (this.timeObserver != null) { + this.player.RemoveTimeObserver (this.timeObserver); + this.timeObserver.Dispose (); + this.timeObserver = null; + } + } + + private CMTime GetPlayerItemDuration () + { + var itemDuration = CMTime.Invalid; + + var playerItem = this.player?.CurrentItem; + if (playerItem?.Status == AVPlayerItemStatus.ReadyToPlay) { + itemDuration = playerItem.Duration; + } + + // Will be kCMTimeInvalid if the item is not ready to play. + return itemDuration; + } + + public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) + { + if (context == this.RateObservationContext.Handle) { + var changes = new NSObservedChange (change); + if (changes.NewValue is NSNumber newValue && + (changes.OldValue == null || (changes.OldValue is NSNumber oldRate && oldRate.FloatValue != newValue.FloatValue))) { + this.isPlaying = (newValue.FloatValue != 0f) || (playRateToRestore != 0f); + this.UpdatePlayPauseButton (); + this.UpdateScrubber (); + this.UpdateTimeLabel (); + + // clear + newValue.Dispose (); + newValue = null; + } + } else if (context == this.StatusObservationContext.Handle) { + if (ofObject is AVPlayerItem playerItem) { + if (playerItem.Status == AVPlayerItemStatus.ReadyToPlay) { + /* Once the AVPlayerItem becomes ready to play, i.e. [playerItem status] == AVPlayerItemStatusReadyToPlay, its duration can be fetched from the item. */ - this.AddTimeObserverToPlayer(); - } - else if (playerItem.Status == AVPlayerItemStatus.Failed) - { - this.ReportError(this.playerItem.Error); - } - } - } - else - { - base.ObserveValue(keyPath, ofObject, change, context); - } - } - - private void UpdatePlayPauseButton() - { - var style = this.isPlaying ? UIBarButtonSystemItem.Pause : UIBarButtonSystemItem.Play; - using (var newPlayPauseButton = new UIBarButtonItem(style, (sender, e) => this.TogglePlayPause(sender as UIBarButtonItem))) - { - var items = this.toolbar.Items; - items[0] = newPlayPauseButton; - this.toolbar.SetItems(items, false); - - this.playPauseButton = newPlayPauseButton; - } - } - - private void UpdateTimeLabel() - { - var seconds = this.player != null ? this.player.CurrentTime.Seconds : 0d; - if (double.IsNaN(seconds)) - { - seconds = 0; - } - - this.currentTimeLabel.TextColor = UIColor.White; - this.currentTimeLabel.TextAlignment = UITextAlignment.Center; - this.currentTimeLabel.Text = TimeSpan.FromSeconds(seconds).ToString(@"mm\:ss"); - } - - private void UpdateScrubber() - { - var duration = this.GetPlayerItemDuration().Seconds; - if (!double.IsNaN(duration)) - { - var time = this.player.CurrentTime.Seconds; - this.scrubber.Value = (float)(time / duration); - } - else - { - this.scrubber.Value = 0f; - } - } - - private void UpdateProgress(AVAssetExportSession session) - { - if (session?.Status == AVAssetExportSessionStatus.Exporting) - { - this.exportProgressView.Progress = session.Progress; - } - } - - private void ReportError(NSError error) - { - if (error != null) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var alertView = UIAlertController.Create(error.LocalizedDescription, error.LocalizedRecoverySuggestion, UIAlertControllerStyle.Alert); - alertView.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - base.PresentViewController(alertView, true, null); - }); - } - } - - #endregion - - #region IBActions - - partial void TogglePlayPause(UIBarButtonItem sender) - { - this.isPlaying = !this.isPlaying; - if (this.isPlaying) - { - if (this.isSeekToZeroBeforePlaying) - { - this.player.Seek(CMTime.Zero); - this.isSeekToZeroBeforePlaying = false; - } - - this.player.Play(); - } - else - { - this.player.Pause(); - } - } - - partial void BeginScrubbing(UISlider sender) - { - this.isSeekToZeroBeforePlaying = false; - this.playRateToRestore = this.player.Rate; - this.player.Rate = 0f; - - this.RemoveTimeObserverFromPlayer(); - } - - partial void Scrub(UISlider sender) - { - this.lastScrubSliderValue = this.scrubber.Value; - if (!this.isScrubInFlight) - { - this.ScrubToSliderValue(this.lastScrubSliderValue); - } - } - - private void ScrubToSliderValue(float sliderValue) - { - var duration = this.GetPlayerItemDuration().Seconds; - if (!double.IsInfinity(duration)) - { - var width = this.scrubber.Bounds.Width; - - double time = duration * sliderValue; - double tolerance = 1d * duration / width; - - this.isScrubInFlight = true; - - this.player.Seek(CMTime.FromSeconds(time, NSEC_PER_SEC), - CMTime.FromSeconds(tolerance, NSEC_PER_SEC), - CMTime.FromSeconds(tolerance, NSEC_PER_SEC), - (finished) => - { - this.isScrubInFlight = false; - this.UpdateTimeLabel(); - }); - } - } - - partial void EndScrubbing(UISlider sender) - { - if (this.isScrubInFlight) - { - this.ScrubToSliderValue(this.lastScrubSliderValue); - } - - this.AddTimeObserverToPlayer(); - - this.player.Rate = this.playRateToRestore; - this.playRateToRestore = 0f; - } - - /// - /// Called when the player item has played to its end time - /// - private void PlayerItemDidReachEnd(NSNotification obj) - { - // After the movie has played to its end time, seek back to time zero to play it again. - this.isSeekToZeroBeforePlaying = true; - } - - partial void HandleTapGesture(UITapGestureRecognizer sender) - { - this.toolbar.Hidden = !this.toolbar.Hidden; - this.currentTimeLabel.Hidden = !this.currentTimeLabel.Hidden; - } - - partial void ExportToMovie(UIBarButtonItem sender) - { - this.exportProgressView.Hidden = false; - - this.player.Pause(); - this.playPauseButton.Enabled = false; - this.transitionButton.Enabled = false; - this.scrubber.Enabled = false; - this.exportButton.Enabled = false; - - this.editor.BuildCompositionObjectsForPlayback(false); - - // Get the export session from the editor - var session = this.editor.AssetExportSessionWithPreset(AVAssetExportSession.PresetMediumQuality); - - var filePath = Path.Combine(Path.GetTempPath(), "ExportedProject.mov"); - if (File.Exists(filePath)) - { - File.Delete(filePath); - } - - // If a preset that is not compatible with AVFileTypeQuickTimeMovie is used, one can use -[AVAssetExportSession supportedFileTypes] to obtain a supported file type for the output file and UTTypeCreatePreferredIdentifierForTag to obtain an appropriate path extension for the output file type. - session.OutputUrl = NSUrl.FromFilename(filePath); - session.OutputFileType = AVFileType.QuickTimeMovie; - - session.ExportAsynchronously(() => DispatchQueue.MainQueue.DispatchAsync(() => OnExportCompleted(session))); - - // Update progress view with export progress - this.progressTimer = NSTimer.CreateRepeatingTimer(0.5, d => this.UpdateProgress(session)); - NSRunLoop.Current.AddTimer(this.progressTimer, NSRunLoopMode.Default); - } - - private void OnExportCompleted(AVAssetExportSession session) - { - this.exportProgressView.Hidden = true; - this.currentTimeLabel.Hidden = false; - var outputURL = session.OutputUrl; - - this.progressTimer.Invalidate(); - this.progressTimer.Dispose(); - this.progressTimer = null; - - if (session.Status != AVAssetExportSessionStatus.Completed) - { - Console.WriteLine($"exportSession error:{session.Error}"); - this.ReportError(session.Error); - } - else - { - this.exportProgressView.Progress = 1f; - - // Save the exported movie to the camera roll - PHPhotoLibrary.RequestAuthorization((status) => - { - if(status == PHAuthorizationStatus.Authorized) - { - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => PHAssetChangeRequest.FromVideo(outputURL), - (successfully, error) => - { - if (error != null) - { - Console.WriteLine($"writeVideoToAssestsLibrary failed: {error}"); - this.ReportError(error); - } - - base.InvokeOnMainThread(() => - { - this.playPauseButton.Enabled = true; - this.transitionButton.Enabled = true; - this.scrubber.Enabled = true; - this.exportButton.Enabled = true; - }); - }); - } - }); - } - } - - #endregion - - #region Gesture recognizer delegate - - [Export("gestureRecognizer:shouldReceiveTouch:")] - public bool ShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch) - { - return touch.View == this.playerView; - } - - #endregion - - public void DidPickTransitionType(TransitionType transitionType) - { - this.transitionType = transitionType; - - // Let the editor know of the change in transition type. - this.SynchronizeWithEditor(); - - this.DismissViewController(true, null); - } - } -} \ No newline at end of file + this.AddTimeObserverToPlayer (); + } else if (playerItem.Status == AVPlayerItemStatus.Failed) { + this.ReportError (this.playerItem.Error); + } + } + } else { + base.ObserveValue (keyPath, ofObject, change, context); + } + } + + private void UpdatePlayPauseButton () + { + var style = this.isPlaying ? UIBarButtonSystemItem.Pause : UIBarButtonSystemItem.Play; + using (var newPlayPauseButton = new UIBarButtonItem (style, (sender, e) => this.TogglePlayPause (sender as UIBarButtonItem))) { + var items = this.toolbar.Items; + items [0] = newPlayPauseButton; + this.toolbar.SetItems (items, false); + + this.playPauseButton = newPlayPauseButton; + } + } + + private void UpdateTimeLabel () + { + var seconds = this.player != null ? this.player.CurrentTime.Seconds : 0d; + if (double.IsNaN (seconds)) { + seconds = 0; + } + + this.currentTimeLabel.TextColor = UIColor.White; + this.currentTimeLabel.TextAlignment = UITextAlignment.Center; + this.currentTimeLabel.Text = TimeSpan.FromSeconds (seconds).ToString (@"mm\:ss"); + } + + private void UpdateScrubber () + { + var duration = this.GetPlayerItemDuration ().Seconds; + if (!double.IsNaN (duration)) { + var time = this.player.CurrentTime.Seconds; + this.scrubber.Value = (float) (time / duration); + } else { + this.scrubber.Value = 0f; + } + } + + private void UpdateProgress (AVAssetExportSession session) + { + if (session?.Status == AVAssetExportSessionStatus.Exporting) { + this.exportProgressView.Progress = session.Progress; + } + } + + private void ReportError (NSError error) + { + if (error != null) { + DispatchQueue.MainQueue.DispatchAsync (() => { + var alertView = UIAlertController.Create (error.LocalizedDescription, error.LocalizedRecoverySuggestion, UIAlertControllerStyle.Alert); + alertView.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + base.PresentViewController (alertView, true, null); + }); + } + } + + #endregion + + #region IBActions + + partial void TogglePlayPause (UIBarButtonItem sender) + { + this.isPlaying = !this.isPlaying; + if (this.isPlaying) { + if (this.isSeekToZeroBeforePlaying) { + this.player.Seek (CMTime.Zero); + this.isSeekToZeroBeforePlaying = false; + } + + this.player.Play (); + } else { + this.player.Pause (); + } + } + + partial void BeginScrubbing (UISlider sender) + { + this.isSeekToZeroBeforePlaying = false; + this.playRateToRestore = this.player.Rate; + this.player.Rate = 0f; + + this.RemoveTimeObserverFromPlayer (); + } + + partial void Scrub (UISlider sender) + { + this.lastScrubSliderValue = this.scrubber.Value; + if (!this.isScrubInFlight) { + this.ScrubToSliderValue (this.lastScrubSliderValue); + } + } + + private void ScrubToSliderValue (float sliderValue) + { + var duration = this.GetPlayerItemDuration ().Seconds; + if (!double.IsInfinity (duration)) { + var width = this.scrubber.Bounds.Width; + + double time = duration * sliderValue; + double tolerance = 1d * duration / width; + + this.isScrubInFlight = true; + + this.player.Seek (CMTime.FromSeconds (time, NSEC_PER_SEC), + CMTime.FromSeconds (tolerance, NSEC_PER_SEC), + CMTime.FromSeconds (tolerance, NSEC_PER_SEC), + (finished) => { + this.isScrubInFlight = false; + this.UpdateTimeLabel (); + }); + } + } + + partial void EndScrubbing (UISlider sender) + { + if (this.isScrubInFlight) { + this.ScrubToSliderValue (this.lastScrubSliderValue); + } + + this.AddTimeObserverToPlayer (); + + this.player.Rate = this.playRateToRestore; + this.playRateToRestore = 0f; + } + + /// + /// Called when the player item has played to its end time + /// + private void PlayerItemDidReachEnd (NSNotification obj) + { + // After the movie has played to its end time, seek back to time zero to play it again. + this.isSeekToZeroBeforePlaying = true; + } + + partial void HandleTapGesture (UITapGestureRecognizer sender) + { + this.toolbar.Hidden = !this.toolbar.Hidden; + this.currentTimeLabel.Hidden = !this.currentTimeLabel.Hidden; + } + + partial void ExportToMovie (UIBarButtonItem sender) + { + this.exportProgressView.Hidden = false; + + this.player.Pause (); + this.playPauseButton.Enabled = false; + this.transitionButton.Enabled = false; + this.scrubber.Enabled = false; + this.exportButton.Enabled = false; + + this.editor.BuildCompositionObjectsForPlayback (false); + + // Get the export session from the editor + var session = this.editor.AssetExportSessionWithPreset (AVAssetExportSession.PresetMediumQuality); + + var filePath = Path.Combine (Path.GetTempPath (), "ExportedProject.mov"); + if (File.Exists (filePath)) { + File.Delete (filePath); + } + + // If a preset that is not compatible with AVFileTypeQuickTimeMovie is used, one can use -[AVAssetExportSession supportedFileTypes] to obtain a supported file type for the output file and UTTypeCreatePreferredIdentifierForTag to obtain an appropriate path extension for the output file type. + session.OutputUrl = NSUrl.FromFilename (filePath); + session.OutputFileType = AVFileType.QuickTimeMovie; + + session.ExportAsynchronously (() => DispatchQueue.MainQueue.DispatchAsync (() => OnExportCompleted (session))); + + // Update progress view with export progress + this.progressTimer = NSTimer.CreateRepeatingTimer (0.5, d => this.UpdateProgress (session)); + NSRunLoop.Current.AddTimer (this.progressTimer, NSRunLoopMode.Default); + } + + private void OnExportCompleted (AVAssetExportSession session) + { + this.exportProgressView.Hidden = true; + this.currentTimeLabel.Hidden = false; + var outputURL = session.OutputUrl; + + this.progressTimer.Invalidate (); + this.progressTimer.Dispose (); + this.progressTimer = null; + + if (session.Status != AVAssetExportSessionStatus.Completed) { + Console.WriteLine ($"exportSession error:{session.Error}"); + this.ReportError (session.Error); + } else { + this.exportProgressView.Progress = 1f; + + // Save the exported movie to the camera roll + PHPhotoLibrary.RequestAuthorization ((status) => { + if (status == PHAuthorizationStatus.Authorized) { + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => PHAssetChangeRequest.FromVideo (outputURL), + (successfully, error) => { + if (error != null) { + Console.WriteLine ($"writeVideoToAssestsLibrary failed: {error}"); + this.ReportError (error); + } + + base.InvokeOnMainThread (() => { + this.playPauseButton.Enabled = true; + this.transitionButton.Enabled = true; + this.scrubber.Enabled = true; + this.exportButton.Enabled = true; + }); + }); + } + }); + } + } + + #endregion + + #region Gesture recognizer delegate + + [Export ("gestureRecognizer:shouldReceiveTouch:")] + public bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch) + { + return touch.View == this.playerView; + } + + #endregion + + public void DidPickTransitionType (TransitionType transitionType) + { + this.transitionType = transitionType; + + // Let the editor know of the change in transition type. + this.SynchronizeWithEditor (); + + this.DismissViewController (true, null); + } + } +} diff --git a/AVTouchSample/AVTouch/AppDelegate.cs b/AVTouchSample/AVTouch/AppDelegate.cs index 0efb7df2d..a96208a24 100644 --- a/AVTouchSample/AVTouch/AppDelegate.cs +++ b/AVTouchSample/AVTouch/AppDelegate.cs @@ -1,23 +1,21 @@ -using Foundation; +using Foundation; using UIKit; -namespace AVTouch -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace AVTouch { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window { get; set; } + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/AVTouchSample/AVTouch/AvTouchViewController.cs b/AVTouchSample/AVTouch/AvTouchViewController.cs index 542ab9228..fba7da0d0 100644 --- a/AVTouchSample/AVTouch/AvTouchViewController.cs +++ b/AVTouchSample/AVTouch/AvTouchViewController.cs @@ -4,311 +4,282 @@ using System.IO; using UIKit; -namespace AVTouch -{ - public partial class AvTouchViewController : UIViewController - { - // amount to skip on rewind or fast forward - private const float SKIP_TIME = 1f; - // amount to play between skips - private const float SKIP_INTERVAL = .2f; - - private AVAudioPlayer player; - private NSTimer rewindTimer; - private NSTimer forwardTimer; - private NSTimer updateTimer; - - private bool inBackground; - - public AvTouchViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.updateTimer = null; - this.rewindTimer = null; - this.forwardTimer = null; - - // Load the the sample file, use mono or stero sample - var fileUrl = NSBundle.MainBundle.PathForResource("sample", "m4a"); - this.player = AVAudioPlayer.FromUrl(new NSUrl(fileUrl, false)); - if (this.player != null) - { - this.fileNameLabel.Text = $"Mono {Path.GetFileName(this.player.Url.RelativePath)} ({this.player.NumberOfChannels} ch)"; - this.UpdateViewForPlayerInfo(this.player); - this.UpdateViewForPlayerState(this.player); - this.player.NumberOfLoops = 1; - } - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - this.RegisterForBackgroundNotifications(); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - NSNotificationCenter.DefaultCenter.RemoveObserver(this); - } - - private void PausePlaybackForPlayer(AVAudioPlayer p) - { - p.Pause(); - this.UpdateViewForPlayerState(p); - } - - private void StartPlaybackForPlayer(AVAudioPlayer p) - { - if (p.Play()) - { - this.UpdateViewForPlayerState(p); - } - else - { - Console.WriteLine($"Could not play {p.Url}"); - } - } - - partial void PlayButtonPressed(UIBarButtonItem sender) - { - if (this.player.Playing) - { - this.PausePlaybackForPlayer(this.player); - } - else - { - this.StartPlaybackForPlayer(this.player); - } - } - - partial void RewindButtonPressed(UIBarButtonItem sender) - { - if (this.rewindTimer != null) - { - this.DestroyTimer(this.rewindTimer); - } - - this.rewindTimer = NSTimer.CreateRepeatingScheduledTimer(SKIP_INTERVAL, (timer) => this.Rewind(this.player)); - } - - partial void RewindButtonReleased(UIBarButtonItem sender) - { - if (this.rewindTimer != null) - { - this.DestroyTimer(this.rewindTimer); - this.rewindTimer = null; - } - } - - partial void ForwardButtonPressed(UIBarButtonItem sender) - { - if (this.forwardTimer != null) - { - this.DestroyTimer(this.forwardTimer); - } - - this.forwardTimer = NSTimer.CreateRepeatingScheduledTimer(SKIP_INTERVAL, (timer) => this.Forward(this.player)); - } - - partial void ForwardButtonReleased(UIBarButtonItem sender) - { - if (this.forwardTimer != null) - { - this.DestroyTimer(this.forwardTimer); - this.forwardTimer = null; - } - } - - partial void VolumeSliderMoved(UISlider sender) - { - this.player.Volume = sender.Value; - } - - partial void ProgressSliderMoved(UISlider sender) - { - this.player.CurrentTime = sender.Value; - this.UpdateCurrentTimeForPlayer(this.player); - } - - private void UpdateCurrentTimeForPlayer(AVAudioPlayer p) - { - this.currentTimeLabel.Text = TimeSpan.FromSeconds(player.CurrentTime).ToString(@"mm\:ss"); - this.progressSlider.Value = (float)p.CurrentTime; - } - - private void UpdateCurrentTime(AVAudioPlayer p) - { - this.UpdateCurrentTimeForPlayer(p); - } - - private void UpdateViewForPlayerState(AVAudioPlayer p) - { - this.UpdateCurrentTimeForPlayer(p); - - if (this.updateTimer != null) - { - this.DestroyTimer(this.updateTimer); - this.updateTimer = null; - } - - this.UpdatePlayButtonState(p); - - if (p.Playing) - { - this.lvlMeter.Player = p; - this.updateTimer = NSTimer.CreateRepeatingScheduledTimer(.01f, (timer) => this.UpdateCurrentTime(p)); - } - else - { - this.lvlMeter.Player = null; - this.updateTimer = null; - } - } - - private void UpdateViewForPlayerStateInBackground(AVAudioPlayer p) - { - this.UpdateCurrentTimeForPlayer(p); - this.UpdatePlayButtonState(p); - } - - private void UpdatePlayButtonState(AVAudioPlayer p) - { - var style = p.Playing ? UIBarButtonSystemItem.Pause : UIBarButtonSystemItem.Play; - using (var playButton = new UIBarButtonItem(style, (sender, e) => this.PlayButtonPressed(sender as UIBarButtonItem))) - { - var items = this.toolbar.Items; - items[3] = playButton; - this.toolbar.Items = items; - } - } - - private void UpdateViewForPlayerInfo(AVAudioPlayer p) - { - this.durationLabel.Text = TimeSpan.FromSeconds(p.Duration).ToString(@"mm\:ss"); - this.progressSlider.MaxValue = (float)p.Duration; - this.volumeSlider.Value = p.Volume; - } - - private void Rewind(AVAudioPlayer p) - { - p.CurrentTime -= SKIP_TIME; - this.UpdateCurrentTimeForPlayer(p); - } - - private void Forward(AVAudioPlayer p) - { - p.CurrentTime += SKIP_TIME; - this.UpdateCurrentTimeForPlayer(p); - } - - #region AVAudioPlayer delegate methods - - [Export("audioPlayerDidFinishPlaying:successfully:")] - public void FinishedPlaying(AVAudioPlayer p, bool flag) - { - if (!flag) - { - Console.WriteLine(@"Playback finished unsuccessfully"); - } - - p.CurrentTime = 0d; - if (this.inBackground) - { - this.UpdateViewForPlayerStateInBackground(p); - } - else - { - this.UpdateViewForPlayerState(p); - } - } - - [Export("audioPlayerDecodeErrorDidOccur:error:")] - public void DecoderError(AVAudioPlayer player, NSError error) - { - Console.WriteLine($"ERROR IN DECODE: {error}"); - } - - // We will only get these notifications if playback was interrupted - [Export("audioPlayerBeginInterruption:")] - public void BeginInterruption(AVAudioPlayer p) - { - Console.WriteLine("Interruption begin. Updating UI for new state"); - // the object has already been paused, we just need to update UI - if (this.inBackground) - { - this.UpdateViewForPlayerStateInBackground(p); - } - else - { - this.UpdateViewForPlayerState(p); - } - } - - [Export("audioPlayerEndInterruption:")] - public void EndInterruption(AVAudioPlayer p) - { - Console.WriteLine("Interruption ended. Resuming playback"); - StartPlaybackForPlayer(p); - } - - #endregion - - #region mark background notifications - - private void RegisterForBackgroundNotifications() - { - NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillResignActiveNotification, SetInBackgroundFlag); - NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillEnterForegroundNotification, ClearInBackgroundFlag); - } - - private void SetInBackgroundFlag(NSNotification notification) - { - this.inBackground = true; - } - - private void ClearInBackgroundFlag(NSNotification notification) - { - this.inBackground = false; - } - - #endregion - - private void DestroyTimer(NSTimer timer) - { - timer.Invalidate(); - timer.Dispose(); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (this.player != null) - { - this.player.Dispose(); - this.player = null; - } - - if (this.rewindTimer != null) - { - this.DestroyTimer(this.rewindTimer); - this.rewindTimer = null; - } - - if (this.forwardTimer != null) - { - this.DestroyTimer(this.forwardTimer); - this.forwardTimer = null; - } - - if (this.updateTimer != null) - { - this.DestroyTimer(this.updateTimer); - this.updateTimer = null; - } - } - } -} \ No newline at end of file +namespace AVTouch { + public partial class AvTouchViewController : UIViewController { + // amount to skip on rewind or fast forward + private const float SKIP_TIME = 1f; + // amount to play between skips + private const float SKIP_INTERVAL = .2f; + + private AVAudioPlayer player; + private NSTimer rewindTimer; + private NSTimer forwardTimer; + private NSTimer updateTimer; + + private bool inBackground; + + public AvTouchViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.updateTimer = null; + this.rewindTimer = null; + this.forwardTimer = null; + + // Load the the sample file, use mono or stero sample + var fileUrl = NSBundle.MainBundle.PathForResource ("sample", "m4a"); + this.player = AVAudioPlayer.FromUrl (new NSUrl (fileUrl, false)); + if (this.player != null) { + this.fileNameLabel.Text = $"Mono {Path.GetFileName (this.player.Url.RelativePath)} ({this.player.NumberOfChannels} ch)"; + this.UpdateViewForPlayerInfo (this.player); + this.UpdateViewForPlayerState (this.player); + this.player.NumberOfLoops = 1; + } + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + this.RegisterForBackgroundNotifications (); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + NSNotificationCenter.DefaultCenter.RemoveObserver (this); + } + + private void PausePlaybackForPlayer (AVAudioPlayer p) + { + p.Pause (); + this.UpdateViewForPlayerState (p); + } + + private void StartPlaybackForPlayer (AVAudioPlayer p) + { + if (p.Play ()) { + this.UpdateViewForPlayerState (p); + } else { + Console.WriteLine ($"Could not play {p.Url}"); + } + } + + partial void PlayButtonPressed (UIBarButtonItem sender) + { + if (this.player.Playing) { + this.PausePlaybackForPlayer (this.player); + } else { + this.StartPlaybackForPlayer (this.player); + } + } + + partial void RewindButtonPressed (UIBarButtonItem sender) + { + if (this.rewindTimer != null) { + this.DestroyTimer (this.rewindTimer); + } + + this.rewindTimer = NSTimer.CreateRepeatingScheduledTimer (SKIP_INTERVAL, (timer) => this.Rewind (this.player)); + } + + partial void RewindButtonReleased (UIBarButtonItem sender) + { + if (this.rewindTimer != null) { + this.DestroyTimer (this.rewindTimer); + this.rewindTimer = null; + } + } + + partial void ForwardButtonPressed (UIBarButtonItem sender) + { + if (this.forwardTimer != null) { + this.DestroyTimer (this.forwardTimer); + } + + this.forwardTimer = NSTimer.CreateRepeatingScheduledTimer (SKIP_INTERVAL, (timer) => this.Forward (this.player)); + } + + partial void ForwardButtonReleased (UIBarButtonItem sender) + { + if (this.forwardTimer != null) { + this.DestroyTimer (this.forwardTimer); + this.forwardTimer = null; + } + } + + partial void VolumeSliderMoved (UISlider sender) + { + this.player.Volume = sender.Value; + } + + partial void ProgressSliderMoved (UISlider sender) + { + this.player.CurrentTime = sender.Value; + this.UpdateCurrentTimeForPlayer (this.player); + } + + private void UpdateCurrentTimeForPlayer (AVAudioPlayer p) + { + this.currentTimeLabel.Text = TimeSpan.FromSeconds (player.CurrentTime).ToString (@"mm\:ss"); + this.progressSlider.Value = (float) p.CurrentTime; + } + + private void UpdateCurrentTime (AVAudioPlayer p) + { + this.UpdateCurrentTimeForPlayer (p); + } + + private void UpdateViewForPlayerState (AVAudioPlayer p) + { + this.UpdateCurrentTimeForPlayer (p); + + if (this.updateTimer != null) { + this.DestroyTimer (this.updateTimer); + this.updateTimer = null; + } + + this.UpdatePlayButtonState (p); + + if (p.Playing) { + this.lvlMeter.Player = p; + this.updateTimer = NSTimer.CreateRepeatingScheduledTimer (.01f, (timer) => this.UpdateCurrentTime (p)); + } else { + this.lvlMeter.Player = null; + this.updateTimer = null; + } + } + + private void UpdateViewForPlayerStateInBackground (AVAudioPlayer p) + { + this.UpdateCurrentTimeForPlayer (p); + this.UpdatePlayButtonState (p); + } + + private void UpdatePlayButtonState (AVAudioPlayer p) + { + var style = p.Playing ? UIBarButtonSystemItem.Pause : UIBarButtonSystemItem.Play; + using (var playButton = new UIBarButtonItem (style, (sender, e) => this.PlayButtonPressed (sender as UIBarButtonItem))) { + var items = this.toolbar.Items; + items [3] = playButton; + this.toolbar.Items = items; + } + } + + private void UpdateViewForPlayerInfo (AVAudioPlayer p) + { + this.durationLabel.Text = TimeSpan.FromSeconds (p.Duration).ToString (@"mm\:ss"); + this.progressSlider.MaxValue = (float) p.Duration; + this.volumeSlider.Value = p.Volume; + } + + private void Rewind (AVAudioPlayer p) + { + p.CurrentTime -= SKIP_TIME; + this.UpdateCurrentTimeForPlayer (p); + } + + private void Forward (AVAudioPlayer p) + { + p.CurrentTime += SKIP_TIME; + this.UpdateCurrentTimeForPlayer (p); + } + + #region AVAudioPlayer delegate methods + + [Export ("audioPlayerDidFinishPlaying:successfully:")] + public void FinishedPlaying (AVAudioPlayer p, bool flag) + { + if (!flag) { + Console.WriteLine (@"Playback finished unsuccessfully"); + } + + p.CurrentTime = 0d; + if (this.inBackground) { + this.UpdateViewForPlayerStateInBackground (p); + } else { + this.UpdateViewForPlayerState (p); + } + } + + [Export ("audioPlayerDecodeErrorDidOccur:error:")] + public void DecoderError (AVAudioPlayer player, NSError error) + { + Console.WriteLine ($"ERROR IN DECODE: {error}"); + } + + // We will only get these notifications if playback was interrupted + [Export ("audioPlayerBeginInterruption:")] + public void BeginInterruption (AVAudioPlayer p) + { + Console.WriteLine ("Interruption begin. Updating UI for new state"); + // the object has already been paused, we just need to update UI + if (this.inBackground) { + this.UpdateViewForPlayerStateInBackground (p); + } else { + this.UpdateViewForPlayerState (p); + } + } + + [Export ("audioPlayerEndInterruption:")] + public void EndInterruption (AVAudioPlayer p) + { + Console.WriteLine ("Interruption ended. Resuming playback"); + StartPlaybackForPlayer (p); + } + + #endregion + + #region mark background notifications + + private void RegisterForBackgroundNotifications () + { + NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillResignActiveNotification, SetInBackgroundFlag); + NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillEnterForegroundNotification, ClearInBackgroundFlag); + } + + private void SetInBackgroundFlag (NSNotification notification) + { + this.inBackground = true; + } + + private void ClearInBackgroundFlag (NSNotification notification) + { + this.inBackground = false; + } + + #endregion + + private void DestroyTimer (NSTimer timer) + { + timer.Invalidate (); + timer.Dispose (); + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (this.player != null) { + this.player.Dispose (); + this.player = null; + } + + if (this.rewindTimer != null) { + this.DestroyTimer (this.rewindTimer); + this.rewindTimer = null; + } + + if (this.forwardTimer != null) { + this.DestroyTimer (this.forwardTimer); + this.forwardTimer = null; + } + + if (this.updateTimer != null) { + this.DestroyTimer (this.updateTimer); + this.updateTimer = null; + } + } + } +} diff --git a/AVTouchSample/AVTouch/Helpers/CALevelMeter.cs b/AVTouchSample/AVTouch/Helpers/CALevelMeter.cs index 36835b6db..f2ce04bb7 100644 --- a/AVTouchSample/AVTouch/Helpers/CALevelMeter.cs +++ b/AVTouchSample/AVTouch/Helpers/CALevelMeter.cs @@ -6,303 +6,259 @@ using System.Collections.Generic; using UIKit; -namespace AVTouch -{ - [Register("CALevelMeter")] - public class CALevelMeter : UIView - { - private const float PeakFalloffPerSec = 0.7f; - private const float LevelFalloffPerSec = 0.8f; - private const float MinDbValue = -80f; - - // The AVAudioPlayer object - private AVAudioPlayer player; - - // Array of NSNumber objects: The indices of the channels to display in this meter - private int[] channelNumbers = new int[1] { 0 }; - - private bool showsPeaks; // Whether or not we show peak levels - private bool vertical; // Whether the view is oriented V or H - private bool useGL; // Whether or not to use OpenGL for drawing - - private MeterTable meterTable = new MeterTable(MinDbValue); - - private CADisplayLink updateTimer; - - private DateTime peakFalloffLastFire; - - private List subLevelMeters = new List(); - - public CALevelMeter(IntPtr handle) : base(handle) - { - this.showsPeaks = true; - this.vertical = this.Frame.Size.Width < this.Frame.Size.Height; - //useGL = true; - - this.LayoutSublevelMeters(); - this.RegisterForBackgroundNotifications(); - } - - [Export("initWithCoder:")] - public CALevelMeter(NSCoder coder) : base(coder) - { - this.showsPeaks = true; - this.vertical = this.Frame.Size.Width < this.Frame.Size.Height; - //useGL = true; - - this.LayoutSublevelMeters(); - this.RegisterForBackgroundNotifications(); - } - - public CALevelMeter(CGRect frame) : base(frame) - { - this.showsPeaks = true; - this.vertical = this.Frame.Size.Width < this.Frame.Size.Height; - //useGL = true; - - this.LayoutSublevelMeters(); - this.RegisterForBackgroundNotifications(); - } - - - - public AVAudioPlayer Player - { - get - { - return this.player; - } - - set - { - if (this.player == null && value != null) - { - this.SetupTimer(); - } - else if (this.player != null && value == null) - { - this.peakFalloffLastFire = DateTime.Now; - } - - this.player = value; - if (this.player != null) - { - this.player.MeteringEnabled = true; - // now check the number of channels in the new queue, we will need to reallocate if this has changed - if ((int)this.player.NumberOfChannels != this.channelNumbers.Length) - { - this.ChannelNumbers = this.player.NumberOfChannels < 2 ? new int[] { 0 } : new int[] { 0, 1 }; - } - } - else - { - foreach (var thisMeter in this.subLevelMeters) - { - thisMeter.SetNeedsDisplay(); - } - } - } - } - - public int[] ChannelNumbers - { - get - { - return this.channelNumbers; - } - - set - { - this.channelNumbers = value; - this.LayoutSublevelMeters(); - } - } - - public bool UseGL - { - get - { - return this.useGL; - } - - set - { - this.useGL = value; - this.LayoutSublevelMeters(); - } - } - - private void RegisterForBackgroundNotifications() - { - NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillResignActiveNotification, this.PauseTimer); - NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillEnterForegroundNotification, this.ResumeTimer); - } - - private void LayoutSublevelMeters() - { - foreach (var meter in this.subLevelMeters) - { - meter.RemoveFromSuperview(); - } - - this.subLevelMeters.Clear(); - - var totalRect = vertical ? new CGRect(0, 0, this.Frame.Size.Width + 2, this.Frame.Size.Height) : - new CGRect(0, 0, this.Frame.Size.Width, this.Frame.Size.Height + 2); - - for (int i = 0; i < this.channelNumbers.Length; i++) - { - CGRect fr; - if (vertical) - { - fr = new CGRect((float)totalRect.X + ((float)i) / this.channelNumbers.Length * totalRect.Width, - totalRect.Y, - (1f / this.channelNumbers.Length) * totalRect.Width - 2f, - totalRect.Height); - } - else - { - fr = new CGRect(totalRect.X, - (float)totalRect.Y + ((float)i) / this.channelNumbers.Length * totalRect.Height, - totalRect.Width, - (1f / this.channelNumbers.Length) * totalRect.Height - 2); - } - - LevelMeter newMeter = null; - if (useGL) - { - //newMeter = new GLLevelMeter(fr) { NumLights = 30, Vertical = vertical }; - } - else - { - newMeter = new LevelMeter(fr) { NumLights = 30, Vertical = this.vertical }; - } - - this.subLevelMeters.Add(newMeter); - this.AddSubview(newMeter); - newMeter.Dispose(); - newMeter = null; - } - } - - private void Refresh() - { - var success = false; - - // if we have no queue, but still have levels, gradually bring them down - if (player == null) - { - float maxLvl = -1f; - var thisFire = DateTime.Now; - // calculate how much time passed since the last draw - var timePassed = (thisFire - this.peakFalloffLastFire).TotalSeconds; - foreach (var thisMeter in this.subLevelMeters) - { - float newPeak, newLevel; - newLevel = (float)(thisMeter.Level - timePassed * LevelFalloffPerSec); - if (newLevel < 0) - { - newLevel = 0; - } - - thisMeter.Level = newLevel; - if (this.showsPeaks) - { - newPeak = (float)(thisMeter.PeakLevel - timePassed * PeakFalloffPerSec); - if (newPeak < 0) - { - newPeak = 0; - } - - thisMeter.PeakLevel = newPeak; - if (newPeak > maxLvl) - { - maxLvl = newPeak; - } - } - else if (newLevel > maxLvl) - { - maxLvl = newLevel; - } - - thisMeter.SetNeedsDisplay(); - } - - // stop the timer when the last level has hit 0 - if (maxLvl <= 0) - { - this.updateTimer.Invalidate(); - this.updateTimer.Dispose(); - this.updateTimer = null; - } - - this.peakFalloffLastFire = thisFire; - success = true; - } - else - { - this.player.UpdateMeters(); - - for (uint i = 0; i < this.channelNumbers.Length; i++) - { - int channelIdx = this.channelNumbers[i]; - var channelView = this.subLevelMeters[channelIdx]; - - if (channelIdx >= this.channelNumbers.Length) - goto bail; - if (channelIdx > 127) - goto bail; - - channelView.Level = this.meterTable.ValueAt(this.player.AveragePower(i)); - channelView.PeakLevel = this.showsPeaks ? this.meterTable.ValueAt(this.player.PeakPower(i)) : 0; - channelView.SetNeedsDisplay(); - success = true; - } - } - - bail: - - if (!success) - { - foreach (var thisMeter in this.subLevelMeters) - { - thisMeter.Level = 0; - thisMeter.SetNeedsDisplay(); - } - - Console.WriteLine("ERROR: metering failed\n"); - } - } - - private void SetupTimer() - { - if (this.updateTimer != null) - { - this.updateTimer.Invalidate(); - this.updateTimer.Dispose(); - this.updateTimer = null; - } - - this.updateTimer = CADisplayLink.Create(this.Refresh); - this.updateTimer.AddToRunLoop(NSRunLoop.Current, NSRunLoopMode.Default); - } - - private void PauseTimer(NSNotification notification) - { - if (this.updateTimer != null) - { - this.updateTimer.Invalidate(); - this.updateTimer.Dispose(); - this.updateTimer = null; - } - } - - private void ResumeTimer(NSNotification notification) - { - if (this.player != null) - { - this.SetupTimer(); - } - } - } -} \ No newline at end of file +namespace AVTouch { + [Register ("CALevelMeter")] + public class CALevelMeter : UIView { + private const float PeakFalloffPerSec = 0.7f; + private const float LevelFalloffPerSec = 0.8f; + private const float MinDbValue = -80f; + + // The AVAudioPlayer object + private AVAudioPlayer player; + + // Array of NSNumber objects: The indices of the channels to display in this meter + private int [] channelNumbers = new int [1] { 0 }; + + private bool showsPeaks; // Whether or not we show peak levels + private bool vertical; // Whether the view is oriented V or H + private bool useGL; // Whether or not to use OpenGL for drawing + + private MeterTable meterTable = new MeterTable (MinDbValue); + + private CADisplayLink updateTimer; + + private DateTime peakFalloffLastFire; + + private List subLevelMeters = new List (); + + public CALevelMeter (IntPtr handle) : base (handle) + { + this.showsPeaks = true; + this.vertical = this.Frame.Size.Width < this.Frame.Size.Height; + //useGL = true; + + this.LayoutSublevelMeters (); + this.RegisterForBackgroundNotifications (); + } + + [Export ("initWithCoder:")] + public CALevelMeter (NSCoder coder) : base (coder) + { + this.showsPeaks = true; + this.vertical = this.Frame.Size.Width < this.Frame.Size.Height; + //useGL = true; + + this.LayoutSublevelMeters (); + this.RegisterForBackgroundNotifications (); + } + + public CALevelMeter (CGRect frame) : base (frame) + { + this.showsPeaks = true; + this.vertical = this.Frame.Size.Width < this.Frame.Size.Height; + //useGL = true; + + this.LayoutSublevelMeters (); + this.RegisterForBackgroundNotifications (); + } + + + + public AVAudioPlayer Player { + get { + return this.player; + } + + set { + if (this.player == null && value != null) { + this.SetupTimer (); + } else if (this.player != null && value == null) { + this.peakFalloffLastFire = DateTime.Now; + } + + this.player = value; + if (this.player != null) { + this.player.MeteringEnabled = true; + // now check the number of channels in the new queue, we will need to reallocate if this has changed + if ((int) this.player.NumberOfChannels != this.channelNumbers.Length) { + this.ChannelNumbers = this.player.NumberOfChannels < 2 ? new int [] { 0 } : new int [] { 0, 1 }; + } + } else { + foreach (var thisMeter in this.subLevelMeters) { + thisMeter.SetNeedsDisplay (); + } + } + } + } + + public int [] ChannelNumbers { + get { + return this.channelNumbers; + } + + set { + this.channelNumbers = value; + this.LayoutSublevelMeters (); + } + } + + public bool UseGL { + get { + return this.useGL; + } + + set { + this.useGL = value; + this.LayoutSublevelMeters (); + } + } + + private void RegisterForBackgroundNotifications () + { + NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillResignActiveNotification, this.PauseTimer); + NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillEnterForegroundNotification, this.ResumeTimer); + } + + private void LayoutSublevelMeters () + { + foreach (var meter in this.subLevelMeters) { + meter.RemoveFromSuperview (); + } + + this.subLevelMeters.Clear (); + + var totalRect = vertical ? new CGRect (0, 0, this.Frame.Size.Width + 2, this.Frame.Size.Height) : + new CGRect (0, 0, this.Frame.Size.Width, this.Frame.Size.Height + 2); + + for (int i = 0; i < this.channelNumbers.Length; i++) { + CGRect fr; + if (vertical) { + fr = new CGRect ((float) totalRect.X + ((float) i) / this.channelNumbers.Length * totalRect.Width, + totalRect.Y, + (1f / this.channelNumbers.Length) * totalRect.Width - 2f, + totalRect.Height); + } else { + fr = new CGRect (totalRect.X, + (float) totalRect.Y + ((float) i) / this.channelNumbers.Length * totalRect.Height, + totalRect.Width, + (1f / this.channelNumbers.Length) * totalRect.Height - 2); + } + + LevelMeter newMeter = null; + if (useGL) { + //newMeter = new GLLevelMeter(fr) { NumLights = 30, Vertical = vertical }; + } else { + newMeter = new LevelMeter (fr) { NumLights = 30, Vertical = this.vertical }; + } + + this.subLevelMeters.Add (newMeter); + this.AddSubview (newMeter); + newMeter.Dispose (); + newMeter = null; + } + } + + private void Refresh () + { + var success = false; + + // if we have no queue, but still have levels, gradually bring them down + if (player == null) { + float maxLvl = -1f; + var thisFire = DateTime.Now; + // calculate how much time passed since the last draw + var timePassed = (thisFire - this.peakFalloffLastFire).TotalSeconds; + foreach (var thisMeter in this.subLevelMeters) { + float newPeak, newLevel; + newLevel = (float) (thisMeter.Level - timePassed * LevelFalloffPerSec); + if (newLevel < 0) { + newLevel = 0; + } + + thisMeter.Level = newLevel; + if (this.showsPeaks) { + newPeak = (float) (thisMeter.PeakLevel - timePassed * PeakFalloffPerSec); + if (newPeak < 0) { + newPeak = 0; + } + + thisMeter.PeakLevel = newPeak; + if (newPeak > maxLvl) { + maxLvl = newPeak; + } + } else if (newLevel > maxLvl) { + maxLvl = newLevel; + } + + thisMeter.SetNeedsDisplay (); + } + + // stop the timer when the last level has hit 0 + if (maxLvl <= 0) { + this.updateTimer.Invalidate (); + this.updateTimer.Dispose (); + this.updateTimer = null; + } + + this.peakFalloffLastFire = thisFire; + success = true; + } else { + this.player.UpdateMeters (); + + for (uint i = 0; i < this.channelNumbers.Length; i++) { + int channelIdx = this.channelNumbers [i]; + var channelView = this.subLevelMeters [channelIdx]; + + if (channelIdx >= this.channelNumbers.Length) + goto bail; + if (channelIdx > 127) + goto bail; + + channelView.Level = this.meterTable.ValueAt (this.player.AveragePower (i)); + channelView.PeakLevel = this.showsPeaks ? this.meterTable.ValueAt (this.player.PeakPower (i)) : 0; + channelView.SetNeedsDisplay (); + success = true; + } + } + + bail: + + if (!success) { + foreach (var thisMeter in this.subLevelMeters) { + thisMeter.Level = 0; + thisMeter.SetNeedsDisplay (); + } + + Console.WriteLine ("ERROR: metering failed\n"); + } + } + + private void SetupTimer () + { + if (this.updateTimer != null) { + this.updateTimer.Invalidate (); + this.updateTimer.Dispose (); + this.updateTimer = null; + } + + this.updateTimer = CADisplayLink.Create (this.Refresh); + this.updateTimer.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Default); + } + + private void PauseTimer (NSNotification notification) + { + if (this.updateTimer != null) { + this.updateTimer.Invalidate (); + this.updateTimer.Dispose (); + this.updateTimer = null; + } + } + + private void ResumeTimer (NSNotification notification) + { + if (this.player != null) { + this.SetupTimer (); + } + } + } +} diff --git a/AVTouchSample/AVTouch/Helpers/LevelMeter.cs b/AVTouchSample/AVTouch/Helpers/LevelMeter.cs index 346a06cf1..d1f27a4a1 100644 --- a/AVTouchSample/AVTouch/Helpers/LevelMeter.cs +++ b/AVTouchSample/AVTouch/Helpers/LevelMeter.cs @@ -3,256 +3,222 @@ using System; using UIKit; -namespace AVTouch -{ - /// - /// The LevelMeterColorThreshold struct is used to define the colors for the LevelMeter, and at what values each of those colors begins. - /// - public struct LevelMeterColorThreshold - { - public LevelMeterColorThreshold(float value, UIColor color) - { - MaxValue = value; - Color = color; - } - - /// - /// A value from 0 - 1. The maximum value shown in this color - /// - public float MaxValue { get; private set; } - - /// - /// A UIColor to be used for this value range - /// - public UIColor Color { get; private set; } - } - - public class LevelMeter : UIView - { - public LevelMeter(CGRect frame) : base(frame) - { - this.PerformInit(); - } - - public LevelMeter(NSCoder coder) : base(coder) - { - PerformInit(); - } - - /// - /// Whether the view is oriented V or H. This is initially automatically set based on the aspect ratio of the view. - /// - public bool Vertical { get; set; } - - /// - /// The background color of the lights - /// - public UIColor BgColor { get; set; } - - /// - /// The border color of the lights - /// - public UIColor BorderColor { get; set; } - - /// - /// Whether to use variable intensity lights. Has no effect if numLights == 0. - /// - public bool VariableLightIntensity { get; set; } - - /// - /// The current level, from 0 - 1 - /// - public float Level { get; set; } - - /// - /// Optional peak level, will be drawn if > 0 - /// - public float PeakLevel { get; set; } - - /// - /// The number of lights to show, or 0 to show a continuous bar - /// - public int NumLights { get; set; } - - public LevelMeterColorThreshold[] ColorThresholds { get; set; } - - private void PerformInit() - { - this.Level = 0; - this.NumLights = 0; - this.Vertical = this.Frame.Width < this.Frame.Height; - this.BgColor = UIColor.FromRGBA(0, 0, 0, 0.6f); - this.BorderColor = UIColor.FromRGBA(0f, 0f, 0, 1f); - this.ColorThresholds = new LevelMeterColorThreshold[] - { - new LevelMeterColorThreshold (0.25f, UIColor.FromRGBA (0, 1f, 0, 1f)), - new LevelMeterColorThreshold (0.8f, UIColor.FromRGBA (1f, 1f, 0, 1f)), - new LevelMeterColorThreshold (1, UIColor.FromRGBA (1f, 0, 0, 1f)), - }; - } - - public override void Draw(CGRect rect) - { - CGColorSpace cs = null; - CGContext ctx = null; - CGRect bds; - - using(ctx = UIGraphics.GetCurrentContext()) - { - using(cs = CGColorSpace.CreateDeviceRGB()) - { - if (this.Vertical) - { - ctx.TranslateCTM(0, this.Bounds.Height); - ctx.ScaleCTM(1, -1); - bds = this.Bounds; - } - else - { - ctx.TranslateCTM(0, this.Bounds.Height); - ctx.RotateCTM(-(float)Math.PI / 2); - bds = new CGRect(0, 0, this.Bounds.Height, this.Bounds.Width); - } - - ctx.SetFillColorSpace(cs); - ctx.SetStrokeColorSpace(cs); - - if (this.NumLights == 0) - { - float currentTop = 0; - - if (this.BgColor != null) - { - this.BgColor.SetColor(); - ctx.FillRect(bds); - } - - foreach (var thisTresh in this.ColorThresholds) - { - var value = Math.Min(thisTresh.MaxValue, this.Level); - - var fillRect = new CGRect(0, bds.Height * currentTop, bds.Width, bds.Height * (value - currentTop)); - thisTresh.Color.SetColor(); - ctx.FillRect(fillRect); - - if (this.Level < thisTresh.MaxValue) - break; - currentTop = value; - } - - if (this.BorderColor != null) - { - this.BorderColor.SetColor(); - bds.Inflate(-0.5f, -0.5f); - ctx.StrokeRect(bds); - } - } - else - { - float lightMinVal = 0; - float insetAmount, lightVSpace; - int peakLight = -1; - - lightVSpace = (float)bds.Height / this.NumLights; - if (lightVSpace < 4) - { - insetAmount = 0; - } - else if (lightVSpace < 8) - { - insetAmount = 0.5f; - } - else - { - insetAmount = 1; - } - - if (this.PeakLevel > 0) - { - peakLight = (int)(this.PeakLevel * this.NumLights); - if (peakLight >= this.NumLights) - { - peakLight = this.NumLights - 1; - } - } - - for (int light_i = 0; light_i < this.NumLights; light_i++) - { - float lightMaxVal = (light_i + 1) / (float)this.NumLights; - float lightIntensity; - CGRect lightRect; - UIColor lightColor; - - if (light_i == peakLight) - { - lightIntensity = 1; - } - else - { - lightIntensity = (Level - lightMinVal) / (lightMaxVal - lightMinVal); - lightIntensity = Clamp(0, lightIntensity, 1); - if (!this.VariableLightIntensity && lightIntensity > 0) - { - lightIntensity = 1; - } - } - - lightColor = this.ColorThresholds[0].Color; - int color_i = 0; - for (; color_i < this.ColorThresholds.Length - 1; color_i++) - { - var thisTresh = this.ColorThresholds[color_i]; - var nextTresh = this.ColorThresholds[color_i + 1]; - if (thisTresh.MaxValue <= lightMaxVal) - { - lightColor = nextTresh.Color; - } - } - - lightRect = new CGRect(0, bds.Height * light_i / (float)this.NumLights, bds.Width, bds.Height * (1f / this.NumLights)); - lightRect.Inset(insetAmount, insetAmount); - - if (this.BgColor != null) - { - this.BgColor.SetColor(); - ctx.FillRect(lightRect); - } - - if (lightIntensity == 1f) - { - lightColor.SetColor(); - ctx.FillRect(lightRect); - } - else if (lightIntensity > 0) - { - using (var clr = new CGColor(lightColor.CGColor, lightIntensity)) - { - ctx.SetFillColor(clr); - ctx.FillRect(lightRect); - } - } - - if (this.BorderColor != null) - { - this.BorderColor.SetColor(); - lightRect.Inset(0.5f, 0.5f); - ctx.StrokeRect(lightRect); - } - - lightMinVal = lightMaxVal; - } - } - } - } - } - - private static float Clamp(float min, float val, float max) - { - if (val < min) - return min; - if (val > max) - return max; - return val; - } - } -} \ No newline at end of file +namespace AVTouch { + /// + /// The LevelMeterColorThreshold struct is used to define the colors for the LevelMeter, and at what values each of those colors begins. + /// + public struct LevelMeterColorThreshold { + public LevelMeterColorThreshold (float value, UIColor color) + { + MaxValue = value; + Color = color; + } + + /// + /// A value from 0 - 1. The maximum value shown in this color + /// + public float MaxValue { get; private set; } + + /// + /// A UIColor to be used for this value range + /// + public UIColor Color { get; private set; } + } + + public class LevelMeter : UIView { + public LevelMeter (CGRect frame) : base (frame) + { + this.PerformInit (); + } + + public LevelMeter (NSCoder coder) : base (coder) + { + PerformInit (); + } + + /// + /// Whether the view is oriented V or H. This is initially automatically set based on the aspect ratio of the view. + /// + public bool Vertical { get; set; } + + /// + /// The background color of the lights + /// + public UIColor BgColor { get; set; } + + /// + /// The border color of the lights + /// + public UIColor BorderColor { get; set; } + + /// + /// Whether to use variable intensity lights. Has no effect if numLights == 0. + /// + public bool VariableLightIntensity { get; set; } + + /// + /// The current level, from 0 - 1 + /// + public float Level { get; set; } + + /// + /// Optional peak level, will be drawn if > 0 + /// + public float PeakLevel { get; set; } + + /// + /// The number of lights to show, or 0 to show a continuous bar + /// + public int NumLights { get; set; } + + public LevelMeterColorThreshold [] ColorThresholds { get; set; } + + private void PerformInit () + { + this.Level = 0; + this.NumLights = 0; + this.Vertical = this.Frame.Width < this.Frame.Height; + this.BgColor = UIColor.FromRGBA (0, 0, 0, 0.6f); + this.BorderColor = UIColor.FromRGBA (0f, 0f, 0, 1f); + this.ColorThresholds = new LevelMeterColorThreshold [] + { + new LevelMeterColorThreshold (0.25f, UIColor.FromRGBA (0, 1f, 0, 1f)), + new LevelMeterColorThreshold (0.8f, UIColor.FromRGBA (1f, 1f, 0, 1f)), + new LevelMeterColorThreshold (1, UIColor.FromRGBA (1f, 0, 0, 1f)), + }; + } + + public override void Draw (CGRect rect) + { + CGColorSpace cs = null; + CGContext ctx = null; + CGRect bds; + + using (ctx = UIGraphics.GetCurrentContext ()) { + using (cs = CGColorSpace.CreateDeviceRGB ()) { + if (this.Vertical) { + ctx.TranslateCTM (0, this.Bounds.Height); + ctx.ScaleCTM (1, -1); + bds = this.Bounds; + } else { + ctx.TranslateCTM (0, this.Bounds.Height); + ctx.RotateCTM (-(float) Math.PI / 2); + bds = new CGRect (0, 0, this.Bounds.Height, this.Bounds.Width); + } + + ctx.SetFillColorSpace (cs); + ctx.SetStrokeColorSpace (cs); + + if (this.NumLights == 0) { + float currentTop = 0; + + if (this.BgColor != null) { + this.BgColor.SetColor (); + ctx.FillRect (bds); + } + + foreach (var thisTresh in this.ColorThresholds) { + var value = Math.Min (thisTresh.MaxValue, this.Level); + + var fillRect = new CGRect (0, bds.Height * currentTop, bds.Width, bds.Height * (value - currentTop)); + thisTresh.Color.SetColor (); + ctx.FillRect (fillRect); + + if (this.Level < thisTresh.MaxValue) + break; + currentTop = value; + } + + if (this.BorderColor != null) { + this.BorderColor.SetColor (); + bds.Inflate (-0.5f, -0.5f); + ctx.StrokeRect (bds); + } + } else { + float lightMinVal = 0; + float insetAmount, lightVSpace; + int peakLight = -1; + + lightVSpace = (float) bds.Height / this.NumLights; + if (lightVSpace < 4) { + insetAmount = 0; + } else if (lightVSpace < 8) { + insetAmount = 0.5f; + } else { + insetAmount = 1; + } + + if (this.PeakLevel > 0) { + peakLight = (int) (this.PeakLevel * this.NumLights); + if (peakLight >= this.NumLights) { + peakLight = this.NumLights - 1; + } + } + + for (int light_i = 0; light_i < this.NumLights; light_i++) { + float lightMaxVal = (light_i + 1) / (float) this.NumLights; + float lightIntensity; + CGRect lightRect; + UIColor lightColor; + + if (light_i == peakLight) { + lightIntensity = 1; + } else { + lightIntensity = (Level - lightMinVal) / (lightMaxVal - lightMinVal); + lightIntensity = Clamp (0, lightIntensity, 1); + if (!this.VariableLightIntensity && lightIntensity > 0) { + lightIntensity = 1; + } + } + + lightColor = this.ColorThresholds [0].Color; + int color_i = 0; + for (; color_i < this.ColorThresholds.Length - 1; color_i++) { + var thisTresh = this.ColorThresholds [color_i]; + var nextTresh = this.ColorThresholds [color_i + 1]; + if (thisTresh.MaxValue <= lightMaxVal) { + lightColor = nextTresh.Color; + } + } + + lightRect = new CGRect (0, bds.Height * light_i / (float) this.NumLights, bds.Width, bds.Height * (1f / this.NumLights)); + lightRect.Inset (insetAmount, insetAmount); + + if (this.BgColor != null) { + this.BgColor.SetColor (); + ctx.FillRect (lightRect); + } + + if (lightIntensity == 1f) { + lightColor.SetColor (); + ctx.FillRect (lightRect); + } else if (lightIntensity > 0) { + using (var clr = new CGColor (lightColor.CGColor, lightIntensity)) { + ctx.SetFillColor (clr); + ctx.FillRect (lightRect); + } + } + + if (this.BorderColor != null) { + this.BorderColor.SetColor (); + lightRect.Inset (0.5f, 0.5f); + ctx.StrokeRect (lightRect); + } + + lightMinVal = lightMaxVal; + } + } + } + } + } + + private static float Clamp (float min, float val, float max) + { + if (val < min) + return min; + if (val > max) + return max; + return val; + } + } +} diff --git a/AVTouchSample/AVTouch/Helpers/MeterTable.cs b/AVTouchSample/AVTouch/Helpers/MeterTable.cs index f57066f87..6dd25703d 100644 --- a/AVTouchSample/AVTouch/Helpers/MeterTable.cs +++ b/AVTouchSample/AVTouch/Helpers/MeterTable.cs @@ -1,73 +1,64 @@ using System; -namespace AVTouch -{ - /// - /// Class for handling conversion from linear scale to dB - /// - public class MeterTable - { - private readonly float minDecibels; - private readonly float decibelResolution; - private readonly float scaleFactor; - private readonly float[] table; +namespace AVTouch { + /// + /// Class for handling conversion from linear scale to dB + /// + public class MeterTable { + private readonly float minDecibels; + private readonly float decibelResolution; + private readonly float scaleFactor; + private readonly float [] table; - /// - /// Initializes a new instance of the class. - /// - /// The decibel value of the minimum displayed amplitude. - /// The size of the table. The table needs to be large enough that there are no large gaps in the response. - /// This controls the curvature of the response. 2.0 is square root, 3.0 is cube root. But inRoot doesn't have to be integer valued, it could be 1.8 or 2.5, etc. - public MeterTable(float inMinDecibels = -80f, int inTableSize = 400, float inRoot = 2f) - { - if (inMinDecibels >= 0) - { - Console.WriteLine($"MeterTable {nameof(inMinDecibels)} must be negative"); - } + /// + /// Initializes a new instance of the class. + /// + /// The decibel value of the minimum displayed amplitude. + /// The size of the table. The table needs to be large enough that there are no large gaps in the response. + /// This controls the curvature of the response. 2.0 is square root, 3.0 is cube root. But inRoot doesn't have to be integer valued, it could be 1.8 or 2.5, etc. + public MeterTable (float inMinDecibels = -80f, int inTableSize = 400, float inRoot = 2f) + { + if (inMinDecibels >= 0) { + Console.WriteLine ($"MeterTable {nameof (inMinDecibels)} must be negative"); + } - this.minDecibels = inMinDecibels; - this.decibelResolution = (this.minDecibels / (inTableSize - 1)); - this.scaleFactor = 1f / this.decibelResolution; + this.minDecibels = inMinDecibels; + this.decibelResolution = (this.minDecibels / (inTableSize - 1)); + this.scaleFactor = 1f / this.decibelResolution; - this.table = new float[inTableSize]; + this.table = new float [inTableSize]; - var minAmp = this.DbToAmp(this.minDecibels); - var ampRange = 1d - minAmp; - var invAmpRange = 1d / ampRange; + var minAmp = this.DbToAmp (this.minDecibels); + var ampRange = 1d - minAmp; + var invAmpRange = 1d / ampRange; - var rroot = 1.0 / inRoot; - for (int i = 0; i < inTableSize; ++i) - { - var decibels = i * this.decibelResolution; - var amp = this.DbToAmp(decibels); - var adjAmp = (amp - minAmp) * invAmpRange; - this.table[i] = (float)Math.Pow(adjAmp, rroot); - } - } + var rroot = 1.0 / inRoot; + for (int i = 0; i < inTableSize; ++i) { + var decibels = i * this.decibelResolution; + var amp = this.DbToAmp (decibels); + var adjAmp = (amp - minAmp) * invAmpRange; + this.table [i] = (float) Math.Pow (adjAmp, rroot); + } + } - public float ValueAt(float inDecibels) - { - float result; - if (inDecibels < this.minDecibels) - { - result = 0f; - } - else if (inDecibels >= 0f) - { - result = 1f; - } - else - { - var index = (int)(inDecibels * this.scaleFactor); - result = this.table[index]; - } + public float ValueAt (float inDecibels) + { + float result; + if (inDecibels < this.minDecibels) { + result = 0f; + } else if (inDecibels >= 0f) { + result = 1f; + } else { + var index = (int) (inDecibels * this.scaleFactor); + result = this.table [index]; + } - return result; - } + return result; + } - private double DbToAmp(double db) - { - return Math.Pow(10d, 0.05d * db); - } - } -} \ No newline at end of file + private double DbToAmp (double db) + { + return Math.Pow (10d, 0.05d * db); + } + } +} diff --git a/AVTouchSample/AVTouch/Main.cs b/AVTouchSample/AVTouch/Main.cs index 56be39d46..903148675 100644 --- a/AVTouchSample/AVTouch/Main.cs +++ b/AVTouchSample/AVTouch/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace AVTouch -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace AVTouch { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/AppDelegate.cs b/AdaptiveElements/AdaptiveElements/AppDelegate.cs index c7bed8e73..f323ca4c4 100644 --- a/AdaptiveElements/AdaptiveElements/AppDelegate.cs +++ b/AdaptiveElements/AdaptiveElements/AppDelegate.cs @@ -1,23 +1,21 @@ -using Foundation; +using Foundation; using UIKit; -namespace AdaptiveElements -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace AdaptiveElements { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window { get; set; } + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/Design.cs b/AdaptiveElements/AdaptiveElements/Design.cs index 8763bed97..676e10946 100644 --- a/AdaptiveElements/AdaptiveElements/Design.cs +++ b/AdaptiveElements/AdaptiveElements/Design.cs @@ -1,47 +1,41 @@ -using System; +using System; using UIKit; -namespace AdaptiveElements -{ - /// - /// The ExampleContainerViewController can look and act differently depending on its size. - /// We call each way of acting differently a "design". - /// Design is a struct that encapsulates everything that distinguishes one design from another. - /// Its definition is specific to this particular sample app, but you may want to use the same concept in your own apps. - /// - public class Design - { - /// - /// Whether to be horizontal or vertical - /// - public UILayoutConstraintAxis Axis { get; set; } +namespace AdaptiveElements { + /// + /// The ExampleContainerViewController can look and act differently depending on its size. + /// We call each way of acting differently a "design". + /// Design is a struct that encapsulates everything that distinguishes one design from another. + /// Its definition is specific to this particular sample app, but you may want to use the same concept in your own apps. + /// + public class Design { + /// + /// Whether to be horizontal or vertical + /// + public UILayoutConstraintAxis Axis { get; set; } - /// - /// Whether the elements inside are small or large - /// - public ElementKind Kind { get; set; } + /// + /// Whether the elements inside are small or large + /// + public ElementKind Kind { get; set; } - /// - /// We also implement a computed read-only property, which returns the identifier - /// of the view controller in the storyboard that this design should use. - /// - public string ElementIdentifier - { - get - { - switch (this.Kind) - { - case ElementKind.Small: return "smallElement"; - case ElementKind.Large: return "largeElement"; - default: throw new NotImplementedException(); - } - } - } + /// + /// We also implement a computed read-only property, which returns the identifier + /// of the view controller in the storyboard that this design should use. + /// + public string ElementIdentifier { + get { + switch (this.Kind) { + case ElementKind.Small: return "smallElement"; + case ElementKind.Large: return "largeElement"; + default: throw new NotImplementedException (); + } + } + } - public enum ElementKind - { - Small, - Large - } - } -} \ No newline at end of file + public enum ElementKind { + Small, + Large + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/ExampleContainerViewController.cs b/AdaptiveElements/AdaptiveElements/ExampleContainerViewController.cs index cc79df5e7..6c062d54b 100644 --- a/AdaptiveElements/AdaptiveElements/ExampleContainerViewController.cs +++ b/AdaptiveElements/AdaptiveElements/ExampleContainerViewController.cs @@ -2,149 +2,142 @@ using System; using UIKit; -namespace AdaptiveElements -{ - /// - /// ExampleContainerViewController is the core of this sample code project. - /// It demonstrates: - /// - How to decide which design to use depending on the view's size - /// - How to apply the design to the UI - /// - How to correctly add and remove child view controllers - /// - public partial class ExampleContainerViewController : UIViewController - { - /// - /// It holds our 3 child view controllers. - /// They will either be instances of SmallElementViewController or LargeElementViewController. - /// - private readonly UIViewController[] elementViewControllers = { null, null, null }; - - /// - /// It is the design that is currently displayed in the view controller. - /// It is initially nil because no design has been displayed yet. - /// - private Design displayedDesign; - - public ExampleContainerViewController(IntPtr handle) : base(handle) { } - - public override void ViewWillLayoutSubviews() - { - /* +namespace AdaptiveElements { + /// + /// ExampleContainerViewController is the core of this sample code project. + /// It demonstrates: + /// - How to decide which design to use depending on the view's size + /// - How to apply the design to the UI + /// - How to correctly add and remove child view controllers + /// + public partial class ExampleContainerViewController : UIViewController { + /// + /// It holds our 3 child view controllers. + /// They will either be instances of SmallElementViewController or LargeElementViewController. + /// + private readonly UIViewController [] elementViewControllers = { null, null, null }; + + /// + /// It is the design that is currently displayed in the view controller. + /// It is initially nil because no design has been displayed yet. + /// + private Design displayedDesign; + + public ExampleContainerViewController (IntPtr handle) : base (handle) { } + + public override void ViewWillLayoutSubviews () + { + /* * In viewWillLayoutSubviews, we are guaranteed that our view's size, traits, etc. are up to date. * It's a good place to update anything that affects the layout of our subviews. * However, be careful, because this method is called frequently! * Do as little work as possible, and don't invalidate the layout of any superviews. */ - // Step 1: Find our size. - var size = base.View.Bounds.Size; + // Step 1: Find our size. + var size = base.View.Bounds.Size; - // Step 2: Decide what design to use, based on our rules. - var newDesign = this.DecideDesign(size); + // Step 2: Decide what design to use, based on our rules. + var newDesign = this.DecideDesign (size); - // Step 3: If the design is different than what is displayed, change the UI. - if (displayedDesign != newDesign) - { - this.ApplyDesign(newDesign); - this.displayedDesign = newDesign; - } - } + // Step 3: If the design is different than what is displayed, change the UI. + if (displayedDesign != newDesign) { + this.ApplyDesign (newDesign); + this.displayedDesign = newDesign; + } + } - private Design DecideDesign(CGSize size) - { - /* + private Design DecideDesign (CGSize size) + { + /* * Decide which Design is appropriate, given the size of our view, by applying rules. * * Note that these rules are _examples_, which produce good results in this particular sample app, * but they are not general rules that would automatically work in other apps. */ - /* + /* * Decision #1: Should our elements be laid out horizontally or vertically? * Rule: If the width is greater that the height, be horizontal, otherwise be vertical. */ - var axis = size.Width > size.Height ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical; + var axis = size.Width > size.Height ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical; - /* + /* * Decision #2: Should our elements be small or large? * Rule: If the width is less than a threshold value, be small, otherwise be large. * (We chose 750 as a threshold value since it produces reasonable results for this example, but there is nothing special about that number.) */ - const float widthThreshold = 750f; - var elementKind = size.Width < widthThreshold ? Design.ElementKind.Small : Design.ElementKind.Large; + const float widthThreshold = 750f; + var elementKind = size.Width < widthThreshold ? Design.ElementKind.Small : Design.ElementKind.Large; - // Return a Design encapsulating the results of those decisions. - return new Design { Axis = axis, Kind = elementKind }; - } + // Return a Design encapsulating the results of those decisions. + return new Design { Axis = axis, Kind = elementKind }; + } - private void ApplyDesign(Design newDesign) - { - /* + private void ApplyDesign (Design newDesign) + { + /* * Change the view controllers and views to display the new design. * Be careful to only change properties that need to be changed. */ - // Set the stack view's layout axis to horizontal or vertical. - if (this.displayedDesign?.Axis != newDesign.Axis) - { - this.stackView.Axis = newDesign.Axis; - } - - // Change the view controllers to the small or large kind. - if (this.displayedDesign?.Kind != newDesign.Kind) - { - // Repeat these steps for each of the element view controllers: - for (int i = 0; i < this.elementViewControllers.Length; i++) - { - var oldElementViewController = this.elementViewControllers[i]; - - // If an old view controller exists, then remove it from this container's child view controllers. - if (oldElementViewController != null) - { - this.RemoveOldElementViewController(oldElementViewController); - } - - // Create the new view controller. - var storyboard = UIStoryboard.FromName("Main", null); - var newElementViewController = storyboard.InstantiateViewController(newDesign.ElementIdentifier); - - // Add it as a child view controller of this container. - this.AddNewElementViewController(newElementViewController); - - // And remember it, so we can remove it later. - this.elementViewControllers[i] = newElementViewController; - } - } - } - - /* Helper functions to be a well-behaved container view controller: */ - - private void AddNewElementViewController(UIViewController elementViewController) - { - // Step 1: Add this view controller to our list of child view controllers. - // This will call elementViewController.willMove(toParentViewController: self). - base.AddChildViewController(elementViewController); - - // Step 2: Add the view controller's view to our view hierarchy. - this.stackView.AddArrangedSubview(elementViewController.View); - - // Step 3: Tell the view controller that it has moved, and `self` is the new parent. - elementViewController.DidMoveToParentViewController(this); - } - - private void RemoveOldElementViewController(UIViewController elementViewController) - { - // Step 1: Tell the view controller that it will move to having no parent view controller. - elementViewController.WillMoveToParentViewController(null); - - // Step 2: Remove the view controller's view from our view hierarchy. - elementViewController.View.RemoveFromSuperview(); - - // Step 3: Remove the view controller from our list of child view controllers. - // This will call elementViewController.didMove(toParentViewController: nil). - elementViewController.RemoveFromParentViewController(); - } - } -} \ No newline at end of file + // Set the stack view's layout axis to horizontal or vertical. + if (this.displayedDesign?.Axis != newDesign.Axis) { + this.stackView.Axis = newDesign.Axis; + } + + // Change the view controllers to the small or large kind. + if (this.displayedDesign?.Kind != newDesign.Kind) { + // Repeat these steps for each of the element view controllers: + for (int i = 0; i < this.elementViewControllers.Length; i++) { + var oldElementViewController = this.elementViewControllers [i]; + + // If an old view controller exists, then remove it from this container's child view controllers. + if (oldElementViewController != null) { + this.RemoveOldElementViewController (oldElementViewController); + } + + // Create the new view controller. + var storyboard = UIStoryboard.FromName ("Main", null); + var newElementViewController = storyboard.InstantiateViewController (newDesign.ElementIdentifier); + + // Add it as a child view controller of this container. + this.AddNewElementViewController (newElementViewController); + + // And remember it, so we can remove it later. + this.elementViewControllers [i] = newElementViewController; + } + } + } + + /* Helper functions to be a well-behaved container view controller: */ + + private void AddNewElementViewController (UIViewController elementViewController) + { + // Step 1: Add this view controller to our list of child view controllers. + // This will call elementViewController.willMove(toParentViewController: self). + base.AddChildViewController (elementViewController); + + // Step 2: Add the view controller's view to our view hierarchy. + this.stackView.AddArrangedSubview (elementViewController.View); + + // Step 3: Tell the view controller that it has moved, and `self` is the new parent. + elementViewController.DidMoveToParentViewController (this); + } + + private void RemoveOldElementViewController (UIViewController elementViewController) + { + // Step 1: Tell the view controller that it will move to having no parent view controller. + elementViewController.WillMoveToParentViewController (null); + + // Step 2: Remove the view controller's view from our view hierarchy. + elementViewController.View.RemoveFromSuperview (); + + // Step 3: Remove the view controller from our list of child view controllers. + // This will call elementViewController.didMove(toParentViewController: nil). + elementViewController.RemoveFromParentViewController (); + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/LargeElementViewController.cs b/AdaptiveElements/AdaptiveElements/LargeElementViewController.cs index f7e67b1b9..e279983b1 100644 --- a/AdaptiveElements/AdaptiveElements/LargeElementViewController.cs +++ b/AdaptiveElements/AdaptiveElements/LargeElementViewController.cs @@ -1,63 +1,57 @@ using System; using UIKit; -namespace AdaptiveElements -{ - /// - /// LargeElementViewController is used in two different ways: - /// 1. Contained within ExampleContainerViewController, when its width is large. - /// 2. Presented by SmallElementViewController, when the ExampleContainerViewController's width is small. - /// It shows a large version of the element.When it is presented, tapping on it will dismiss it. - /// - public partial class LargeElementViewController : UIViewController - { - private NSLayoutConstraint widthConstraint; - - public LargeElementViewController(IntPtr handle) : base(handle) { } - - public override void UpdateViewConstraints() - { - base.UpdateViewConstraints(); - - /* +namespace AdaptiveElements { + /// + /// LargeElementViewController is used in two different ways: + /// 1. Contained within ExampleContainerViewController, when its width is large. + /// 2. Presented by SmallElementViewController, when the ExampleContainerViewController's width is small. + /// It shows a large version of the element.When it is presented, tapping on it will dismiss it. + /// + public partial class LargeElementViewController : UIViewController { + private NSLayoutConstraint widthConstraint; + + public LargeElementViewController (IntPtr handle) : base (handle) { } + + public override void UpdateViewConstraints () + { + base.UpdateViewConstraints (); + + /* * If we are not being presented full-screen, * then add a constraint to make this view no wider than our superview's readable content guide. */ - if (base.PresentingViewController == null && - this.widthConstraint == null && - base.View.Superview != null) - { - this.widthConstraint = base.View.WidthAnchor.ConstraintLessThanOrEqualTo(base.View.Superview.ReadableContentGuide.WidthAnchor); - if (this.widthConstraint != null) - { - this.widthConstraint.Active = true; - } - } - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - /* + if (base.PresentingViewController == null && + this.widthConstraint == null && + base.View.Superview != null) { + this.widthConstraint = base.View.WidthAnchor.ConstraintLessThanOrEqualTo (base.View.Superview.ReadableContentGuide.WidthAnchor); + if (this.widthConstraint != null) { + this.widthConstraint.Active = true; + } + } + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + /* * When this view appears, if we are being presented, * add a tap gesture recognizer so we can dismiss when we are tapped. */ - if (this.IsBeingPresented) - { - var tapGestureRecognizer = new UITapGestureRecognizer(this.Tapped); - base.View.AddGestureRecognizer(tapGestureRecognizer); - } - } - - private void Tapped(UITapGestureRecognizer gestureRecognizer) - { - if (gestureRecognizer.State == UIGestureRecognizerState.Ended) - { - DismissViewController(true, null); - } - } - } -} \ No newline at end of file + if (this.IsBeingPresented) { + var tapGestureRecognizer = new UITapGestureRecognizer (this.Tapped); + base.View.AddGestureRecognizer (tapGestureRecognizer); + } + } + + private void Tapped (UITapGestureRecognizer gestureRecognizer) + { + if (gestureRecognizer.State == UIGestureRecognizerState.Ended) { + DismissViewController (true, null); + } + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/Main.cs b/AdaptiveElements/AdaptiveElements/Main.cs index f2c1874c3..6d49b05e8 100644 --- a/AdaptiveElements/AdaptiveElements/Main.cs +++ b/AdaptiveElements/AdaptiveElements/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace AdaptiveElements -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace AdaptiveElements { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/SimpleExampleViewController.cs b/AdaptiveElements/AdaptiveElements/SimpleExampleViewController.cs index eb720de28..979688d61 100644 --- a/AdaptiveElements/AdaptiveElements/SimpleExampleViewController.cs +++ b/AdaptiveElements/AdaptiveElements/SimpleExampleViewController.cs @@ -2,66 +2,61 @@ using System; using UIKit; -namespace AdaptiveElements -{ - /// - /// SimpleExampleViewController demonstrates how to use a view's size to determine an arrangement of its subviews. - /// Also, it shows how to add an animation effect during app size changes. - /// - public partial class SimpleExampleViewController : UIViewController - { - public SimpleExampleViewController(IntPtr handle) : base(handle) { } - - public override void ViewWillLayoutSubviews() - { - /* +namespace AdaptiveElements { + /// + /// SimpleExampleViewController demonstrates how to use a view's size to determine an arrangement of its subviews. + /// Also, it shows how to add an animation effect during app size changes. + /// + public partial class SimpleExampleViewController : UIViewController { + public SimpleExampleViewController (IntPtr handle) : base (handle) { } + + public override void ViewWillLayoutSubviews () + { + /* * In viewWillLayoutSubviews, we are guaranteed that our view's size, traits, etc. are up to date. * It's a good place to update anything that affects the layout of our subviews. * However, be careful, because this method is called frequently! * Do as little work as possible, and don't invalidate the layout of any superviews. */ - // Step 1: Find our size. - var size = base.View.Bounds.Size; + // Step 1: Find our size. + var size = base.View.Bounds.Size; - // Step 2: Decide what design to use, based on our rules. - var useWideDesign = size.Width > size.Height; + // Step 2: Decide what design to use, based on our rules. + var useWideDesign = size.Width > size.Height; - // Step 3: Apply the design to the UI. - this.stackView.Axis = useWideDesign ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical; - } + // Step 3: Apply the design to the UI. + this.stackView.Axis = useWideDesign ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical; + } - public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) - { - /* + public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) + { + /* * We override viewWillTransition(to size: with coordinator:) in order to add special behavior * when the app changes size, especially when the device is rotated. * In this demo app, we add an effect to make the items "pop" towards the viewer during the rotation, * and then go back to normal afterwards. */ - base.ViewWillTransitionToSize(toSize, coordinator); + base.ViewWillTransitionToSize (toSize, coordinator); - // If self.stackView is null, then our view has not yet been loaded, and there is nothing to do. - if (this.stackView != null) - { - // Add alongside and completion animations. - coordinator.AnimateAlongsideTransition((_) => - { - /* + // If self.stackView is null, then our view has not yet been loaded, and there is nothing to do. + if (this.stackView != null) { + // Add alongside and completion animations. + coordinator.AnimateAlongsideTransition ((_) => { + /* * Scale the stackView to be larger than normal. * This animates along with the rest of the rotation animation. */ - this.stackView.Transform = CGAffineTransform.MakeScale(1.4f, 1.4f); - }, (_) => - { - /* + this.stackView.Transform = CGAffineTransform.MakeScale (1.4f, 1.4f); + }, (_) => { + /* * The rotation animation is complete. Add an additional 0.5 second * animation to set the scale back to normal. */ - UIView.Animate(0.5f, () => this.stackView.Transform = CGAffineTransform.MakeIdentity()); - }); - } - } - } -} \ No newline at end of file + UIView.Animate (0.5f, () => this.stackView.Transform = CGAffineTransform.MakeIdentity ()); + }); + } + } + } +} diff --git a/AdaptiveElements/AdaptiveElements/SmallElementViewController.cs b/AdaptiveElements/AdaptiveElements/SmallElementViewController.cs index 6d5cdf58d..4830c8f70 100644 --- a/AdaptiveElements/AdaptiveElements/SmallElementViewController.cs +++ b/AdaptiveElements/AdaptiveElements/SmallElementViewController.cs @@ -1,70 +1,66 @@ using System; using UIKit; -namespace AdaptiveElements -{ - /// - /// SmallElementViewController is contained within ExampleContainerViewController. - /// It shows a small version of the element.Tapping on it presents a LargeElementViewController which shows more details. - /// - public partial class SmallElementViewController : UIViewController - { - public SmallElementViewController(IntPtr handle) : base(handle) { } +namespace AdaptiveElements { + /// + /// SmallElementViewController is contained within ExampleContainerViewController. + /// It shows a small version of the element.Tapping on it presents a LargeElementViewController which shows more details. + /// + public partial class SmallElementViewController : UIViewController { + public SmallElementViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - /* + /* * `ViewDidLoad()` is NOT the place to do everything. * However, it is a good place to do work that does not depend on * any other objects or views, and that will be the same no matter where this view controller is used. * In this view controller, the following code qualifies: */ - // Add a constraint to make this view always square. - var constraint = base.View.WidthAnchor.ConstraintEqualTo(base.View.HeightAnchor); - constraint.Active = true; + // Add a constraint to make this view always square. + var constraint = base.View.WidthAnchor.ConstraintEqualTo (base.View.HeightAnchor); + constraint.Active = true; - /* + /* * The SmallElementViewController is just a preview. * Tap on our view to show the details in the LargeElementViewController. */ - var tapGestureRecognizer = new UITapGestureRecognizer(this.Tapped); - base.View.AddGestureRecognizer(tapGestureRecognizer); - } + var tapGestureRecognizer = new UITapGestureRecognizer (this.Tapped); + base.View.AddGestureRecognizer (tapGestureRecognizer); + } - private void Tapped(UITapGestureRecognizer gestureRecognizer) - { - if (gestureRecognizer.State == UIGestureRecognizerState.Ended) - { - // Create the larger view controller: - var storyboard = UIStoryboard.FromName("Main", null); - var newElementViewController = storyboard.InstantiateViewController("largeElement"); + private void Tapped (UITapGestureRecognizer gestureRecognizer) + { + if (gestureRecognizer.State == UIGestureRecognizerState.Ended) { + // Create the larger view controller: + var storyboard = UIStoryboard.FromName ("Main", null); + var newElementViewController = storyboard.InstantiateViewController ("largeElement"); - /* + /* * And present it. * We use the `.overFullScreen` presentation style so the ExampleContainerViewController * underneath will go through the normal layout process, even while the presentation is active. */ - newElementViewController.ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen; - base.PresentViewController(newElementViewController, true, null); - } - } + newElementViewController.ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen; + base.PresentViewController (newElementViewController, true, null); + } + } - public override void WillMoveToParentViewController(UIViewController parent) - { - /* + public override void WillMoveToParentViewController (UIViewController parent) + { + /* * When we are removed from our parent view controller * (which could happen when the parent changes to a different Design), * if we presented the ElementViewController, then dismiss it. */ - if (parent == null && base.PresentedViewController != null) - { - this.DismissViewController(false, null); - } - } - } -} \ No newline at end of file + if (parent == null && base.PresentedViewController != null) { + this.DismissViewController (false, null); + } + } + } +} diff --git a/AirLocate/AirLocate/AppDelegate.cs b/AirLocate/AirLocate/AppDelegate.cs index ec5171045..9634ff30c 100644 --- a/AirLocate/AirLocate/AppDelegate.cs +++ b/AirLocate/AirLocate/AppDelegate.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace AirLocate -{ +namespace AirLocate { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { CLLocationManager locationManager; public override UIWindow Window { @@ -48,7 +46,7 @@ public override void ReceivedLocalNotification (UIApplication application, UILoc new UIAlertView (notification.AlertBody, String.Empty, null, "OK", null).Show (); } - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AirLocate/AirLocate/CalibrationBeginViewController.cs b/AirLocate/AirLocate/CalibrationBeginViewController.cs index 2bcdef57c..1d2db0a82 100644 --- a/AirLocate/AirLocate/CalibrationBeginViewController.cs +++ b/AirLocate/AirLocate/CalibrationBeginViewController.cs @@ -5,11 +5,9 @@ using Foundation; using UIKit; -namespace AirLocate -{ - public partial class CalibrationBeginViewController : UITableViewController - { - List[] beacons; +namespace AirLocate { + public partial class CalibrationBeginViewController : UITableViewController { + List [] beacons; CLLocationManager locationManager; List rangedRegions; bool inProgress; @@ -105,8 +103,8 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableview, nint section) { if (inProgress && (section == 0)) - return 1; - return beacons [GetNonEmptySection ((int)section)].Count; + return 1; + return beacons [GetNonEmptySection ((int) section)].Count; } public override string TitleForHeader (UITableView tableView, nint section) @@ -115,7 +113,7 @@ public override string TitleForHeader (UITableView tableView, nint section) if (((section == 0) && inProgress) || (NumberOfSections (tableView) == 0)) return null; - return ((CLProximity)GetNonEmptySection ((int)section)).ToString (); + return ((CLProximity) GetNonEmptySection ((int) section)).ToString (); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) diff --git a/AirLocate/AirLocate/CalibrationCalculator.cs b/AirLocate/AirLocate/CalibrationCalculator.cs index cbcdb4545..17a7578c5 100644 --- a/AirLocate/AirLocate/CalibrationCalculator.cs +++ b/AirLocate/AirLocate/CalibrationCalculator.cs @@ -5,22 +5,18 @@ using CoreLocation; using Foundation; -namespace AirLocate -{ - public class CalibrationCompletedEventArgs : EventArgs - { +namespace AirLocate { + public class CalibrationCompletedEventArgs : EventArgs { public int MeasurePower { get; set; } public NSError Error { get; set; } } - public class CalibrationProgressEventArgs : EventArgs - { + public class CalibrationProgressEventArgs : EventArgs { public float PercentComplete { get; set; } } - public class CalibrationCancelledError : NSError - { + public class CalibrationCancelledError : NSError { static NSString ErrorDomain = new NSString (Defaults.Identifier); public CalibrationCancelledError () : @@ -29,15 +25,14 @@ public CalibrationCancelledError () : } } - public class CalibrationCalculator - { + public class CalibrationCalculator { static NSString Rssi = new NSString ("rssi"); CLLocationManager locationManager; CLBeaconRegion region; bool isCalibrating; NSTimer timer; - List rangedBeacons; + List rangedBeacons; float percentComplete; public event EventHandler CalibrationCompletionHandler; @@ -46,7 +41,7 @@ public class CalibrationCalculator public CalibrationCalculator (CLBeaconRegion region, EventHandler handler) { this.region = region; - rangedBeacons = new List (); + rangedBeacons = new List (); CalibrationCompletionHandler = handler; locationManager = new CLLocationManager (); @@ -54,7 +49,8 @@ public CalibrationCalculator (CLBeaconRegion region, EventHandler handl timer = NSTimer.CreateTimer (20.0f, (r) => { locationManager.StopRangingBeacons (region); - DispatchQueue.DefaultGlobalQueue.DispatchAsync (new Action (delegate { + DispatchQueue.DefaultGlobalQueue.DispatchAsync (new Action (delegate + { NSError error = null; List allBeacons = new List (); int measuredPower = 0; if (!isCalibrating) { error = new CalibrationCancelledError (); } else { - foreach (CLBeacon[] beacons in rangedBeacons) { + foreach (CLBeacon [] beacons in rangedBeacons) { if (beacons.Length > 1) { error = new CalibrationCancelledError (); break; @@ -102,21 +99,23 @@ public void PerformCalibration (EventHandler handl if (allBeacons.Count == 0) { error = new CalibrationCancelledError (); } else { - allBeacons.Sort (delegate (CLBeacon x, CLBeacon y) { + allBeacons.Sort (delegate (CLBeacon x, CLBeacon y) + { return (x.ValueForKey (Rssi) as NSNumber).CompareTo (y.ValueForKey (Rssi)); }); float power = 0; int number = 0; - int outlierPadding = (int)(allBeacons.Count * 0.1f); + int outlierPadding = (int) (allBeacons.Count * 0.1f); for (int k = outlierPadding; k < allBeacons.Count - (outlierPadding * 2); k++) { - power += ((NSNumber)allBeacons [k].ValueForKey (Rssi)).FloatValue; + power += ((NSNumber) allBeacons [k].ValueForKey (Rssi)).FloatValue; number++; } - measuredPower = (int)power / number; + measuredPower = (int) power / number; } } - DispatchQueue.MainQueue.DispatchAsync (delegate { + DispatchQueue.MainQueue.DispatchAsync (delegate + { CalibrationCompletionHandler (this, new CalibrationCompletedEventArgs () { MeasurePower = measuredPower, Error = error diff --git a/AirLocate/AirLocate/CalibrationEndViewController.cs b/AirLocate/AirLocate/CalibrationEndViewController.cs index d9439a3bc..13b014260 100644 --- a/AirLocate/AirLocate/CalibrationEndViewController.cs +++ b/AirLocate/AirLocate/CalibrationEndViewController.cs @@ -2,10 +2,8 @@ using CoreGraphics; using UIKit; -namespace AirLocate -{ - public class CalibrationEndViewController : UIViewController - { +namespace AirLocate { + public class CalibrationEndViewController : UIViewController { int measured_power; public CalibrationEndViewController (int measuredPower) diff --git a/AirLocate/AirLocate/ConfigurationViewController.cs b/AirLocate/AirLocate/ConfigurationViewController.cs index 9f2132a7c..9459b7945 100644 --- a/AirLocate/AirLocate/ConfigurationViewController.cs +++ b/AirLocate/AirLocate/ConfigurationViewController.cs @@ -5,17 +5,14 @@ using Foundation; using UIKit; -namespace AirLocate -{ - class PeripheralManagerDelegate : CBPeripheralManagerDelegate - { +namespace AirLocate { + class PeripheralManagerDelegate : CBPeripheralManagerDelegate { public override void StateUpdated (CBPeripheralManager peripheral) { } } - public partial class ConfigurationViewController : UITableViewController - { + public partial class ConfigurationViewController : UITableViewController { bool enabled; NSUuid uuid; NSNumber major; diff --git a/AirLocate/AirLocate/Defaults.cs b/AirLocate/AirLocate/Defaults.cs index cdf185724..ad6c5a3ec 100644 --- a/AirLocate/AirLocate/Defaults.cs +++ b/AirLocate/AirLocate/Defaults.cs @@ -2,11 +2,9 @@ using System.Collections.Generic; using Foundation; -namespace AirLocate -{ - public static class Defaults - { - static NSUuid[] supportedProximityUuids; +namespace AirLocate { + public static class Defaults { + static NSUuid [] supportedProximityUuids; static NSNumber defaultPower; static Defaults () diff --git a/AirLocate/AirLocate/Helpers.cs b/AirLocate/AirLocate/Helpers.cs index 2bb10a1e6..5ccd943a1 100644 --- a/AirLocate/AirLocate/Helpers.cs +++ b/AirLocate/AirLocate/Helpers.cs @@ -2,10 +2,8 @@ using CoreLocation; using Foundation; -namespace AirLocate -{ - public static class Helpers - { +namespace AirLocate { + public static class Helpers { // create the CLBeaconRegion using the right contructor, returns null if input is invalid (no exceptions) public static CLBeaconRegion CreateRegion (NSUuid uuid, NSNumber major, NSNumber minor) diff --git a/AirLocate/AirLocate/MenuViewController.cs b/AirLocate/AirLocate/MenuViewController.cs index 025497673..e0744495c 100644 --- a/AirLocate/AirLocate/MenuViewController.cs +++ b/AirLocate/AirLocate/MenuViewController.cs @@ -2,11 +2,9 @@ using Foundation; using UIKit; -namespace AirLocate -{ - public partial class MenuViewController : UITableViewController - { - UIViewController[] controllers = new UIViewController [4]; +namespace AirLocate { + public partial class MenuViewController : UITableViewController { + UIViewController [] controllers = new UIViewController [4]; public MenuViewController (IntPtr handle) : base (handle) { @@ -15,10 +13,10 @@ public MenuViewController (IntPtr handle) : base (handle) public override void ViewDidLoad () { base.ViewDidLoad (); - controllers [0] = (UIViewController)Storyboard.InstantiateViewController ("MonitoringViewController"); + controllers [0] = (UIViewController) Storyboard.InstantiateViewController ("MonitoringViewController"); controllers [1] = new RangingViewController (UITableViewStyle.Plain); controllers [2] = new CalibrationBeginViewController (UITableViewStyle.Plain); - controllers [3] = (UIViewController)Storyboard.InstantiateViewController ("ConfigurationViewController"); + controllers [3] = (UIViewController) Storyboard.InstantiateViewController ("ConfigurationViewController"); } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) diff --git a/AirLocate/AirLocate/MonitoringViewController.cs b/AirLocate/AirLocate/MonitoringViewController.cs index 39bc1c623..5eb99f9cb 100644 --- a/AirLocate/AirLocate/MonitoringViewController.cs +++ b/AirLocate/AirLocate/MonitoringViewController.cs @@ -3,10 +3,8 @@ using CoreLocation; using UIKit; -namespace AirLocate -{ - public partial class MonitoringViewController : UITableViewController - { +namespace AirLocate { + public partial class MonitoringViewController : UITableViewController { bool enabled; NSUuid uuid; NSNumber major; @@ -32,7 +30,7 @@ public MonitoringViewController (IntPtr handle) : base (handle) public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); - CLBeaconRegion region = (CLBeaconRegion)locationManger.MonitoredRegions.AnyObject; + CLBeaconRegion region = (CLBeaconRegion) locationManger.MonitoredRegions.AnyObject; enabled = (region != null); if (enabled) { uuid = region.ProximityUuid; @@ -122,7 +120,7 @@ public override void ViewDidLoad () locationManger.StartMonitoring (region); } } else { - var region = (CLBeaconRegion)locationManger.MonitoredRegions.AnyObject; + var region = (CLBeaconRegion) locationManger.MonitoredRegions.AnyObject; if (region != null) locationManger.StopMonitoring (region); } diff --git a/AirLocate/AirLocate/RangingViewController.cs b/AirLocate/AirLocate/RangingViewController.cs index 2eb91f669..188162fca 100644 --- a/AirLocate/AirLocate/RangingViewController.cs +++ b/AirLocate/AirLocate/RangingViewController.cs @@ -5,11 +5,9 @@ using Foundation; using UIKit; -namespace AirLocate -{ - public partial class RangingViewController : UITableViewController - { - List[] beacons; +namespace AirLocate { + public partial class RangingViewController : UITableViewController { + List [] beacons; CLLocationManager locationManager; List rangedRegions; @@ -90,7 +88,7 @@ int GetNonEmptySection (int section) public override nint RowsInSection (UITableView tableview, nint section) { - return beacons [GetNonEmptySection ((int)section)].Count; + return beacons [GetNonEmptySection ((int) section)].Count; } public override string TitleForHeader (UITableView tableView, nint section) @@ -98,7 +96,7 @@ public override string TitleForHeader (UITableView tableView, nint section) if (NumberOfSections (tableView) == 0) return null; - return ((CLProximity)GetNonEmptySection ((int)section)).ToString (); + return ((CLProximity) GetNonEmptySection ((int) section)).ToString (); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) diff --git a/AirLocate/AirLocate/UuidPickerView.cs b/AirLocate/AirLocate/UuidPickerView.cs index eb247da1b..d55931679 100644 --- a/AirLocate/AirLocate/UuidPickerView.cs +++ b/AirLocate/AirLocate/UuidPickerView.cs @@ -2,10 +2,8 @@ using Foundation; using UIKit; -namespace AirLocate -{ - public class UuidPickerView : UIPickerView - { +namespace AirLocate { + public class UuidPickerView : UIPickerView { public UuidPickerView (UITextField uuidTextField) { @@ -14,8 +12,7 @@ public UuidPickerView (UITextField uuidTextField) Model = new UuidPickerViewModel (uuidTextField); } - class UuidPickerViewModel : UIPickerViewModel - { + class UuidPickerViewModel : UIPickerViewModel { UITextField field; @@ -26,7 +23,7 @@ public UuidPickerViewModel (UITextField uuidTextField) public override void Selected (UIPickerView picker, nint row, nint component) { - field.Text = Defaults.SupportedProximityUuids [(int)row].AsString (); + field.Text = Defaults.SupportedProximityUuids [(int) row].AsString (); } public override nint GetRowsInComponent (UIPickerView picker, nint component) @@ -41,7 +38,7 @@ public override nint GetComponentCount (UIPickerView picker) public override string GetTitle (UIPickerView picker, nint row, nint component) { - return Defaults.SupportedProximityUuids [(int)row].AsString (); + return Defaults.SupportedProximityUuids [(int) row].AsString (); } } } diff --git a/AppPrefs/AppDelegate.cs b/AppPrefs/AppDelegate.cs index f109737b2..0daeca2d0 100644 --- a/AppPrefs/AppDelegate.cs +++ b/AppPrefs/AppDelegate.cs @@ -1,16 +1,14 @@ using Foundation; using UIKit; -namespace AppPrefs -{ +namespace AppPrefs { /// /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations NSObject observer; @@ -18,8 +16,8 @@ public class AppDelegate : UIApplicationDelegate public override void FinishedLaunching (UIApplication application) { - Settings.LoadDefaultValues(); - observer = NSNotificationCenter.DefaultCenter.AddObserver ((NSString)"NSUserDefaultsDidChangeNotification", DefaultsChanged); + Settings.LoadDefaultValues (); + observer = NSNotificationCenter.DefaultCenter.AddObserver ((NSString) "NSUserDefaultsDidChangeNotification", DefaultsChanged); DefaultsChanged (null); } diff --git a/AppPrefs/AppPrefsViewController.cs b/AppPrefs/AppPrefsViewController.cs index 802b727f8..207fcd957 100644 --- a/AppPrefs/AppPrefsViewController.cs +++ b/AppPrefs/AppPrefsViewController.cs @@ -2,10 +2,8 @@ using System; using Foundation; -namespace AppPrefs -{ - public partial class AppPrefsViewController : UIViewController - { +namespace AppPrefs { + public partial class AppPrefsViewController : UIViewController { NSObject observer; public AppPrefsViewController (IntPtr handle) : base (handle) @@ -18,7 +16,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); TableView.Source = new MyUITableViewSource (); - observer = NSNotificationCenter.DefaultCenter.AddObserver ((NSString)"NSUserDefaultsDidChangeNotification", UpdateSettings); + observer = NSNotificationCenter.DefaultCenter.AddObserver ((NSString) "NSUserDefaultsDidChangeNotification", UpdateSettings); } @@ -49,26 +47,25 @@ void UpdateSettings (NSNotification obj) { // set table view background color switch (Settings.BackgroundColor) { - case BackgroundColors.Black: - this.TableView.BackgroundColor = UIColor.Black; - break; - case BackgroundColors.White: - this.TableView.BackgroundColor = UIColor.White; - break; - case BackgroundColors.Blue: - this.TableView.BackgroundColor = UIColor.Blue; - break; - case BackgroundColors.Pattern: - this.TableView.BackgroundColor = UIColor.GroupTableViewBackgroundColor; - break; + case BackgroundColors.Black: + this.TableView.BackgroundColor = UIColor.Black; + break; + case BackgroundColors.White: + this.TableView.BackgroundColor = UIColor.White; + break; + case BackgroundColors.Blue: + this.TableView.BackgroundColor = UIColor.Blue; + break; + case BackgroundColors.Pattern: + this.TableView.BackgroundColor = UIColor.GroupTableViewBackgroundColor; + break; } TableView.ReloadData (); } #region UITableViewDataSource - class MyUITableViewSource : UITableViewSource - { + class MyUITableViewSource : UITableViewSource { public override nint NumberOfSections (UITableView tableView) { return 1; diff --git a/AppPrefs/Main.cs b/AppPrefs/Main.cs index d2410dcac..28e9a5429 100644 --- a/AppPrefs/Main.cs +++ b/AppPrefs/Main.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace AppPrefs -{ - public class Application - { +namespace AppPrefs { + public class Application { /// /// This is the main entry point of the application. /// - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AppPrefs/Settings.cs b/AppPrefs/Settings.cs index 7545b5aca..3eb82ae36 100644 --- a/AppPrefs/Settings.cs +++ b/AppPrefs/Settings.cs @@ -1,7 +1,6 @@ using Foundation; -namespace AppPrefs -{ +namespace AppPrefs { public enum TextColors { Blue = 1, Red, @@ -18,12 +17,11 @@ public enum BackgroundColors { /// /// This class manages the system settings. /// - public class Settings - { - public static string FirstName { get; private set;} - public static string LastName { get; private set;} - public static TextColors TextColor { get; private set;} - public static BackgroundColors BackgroundColor { get; private set;} + public class Settings { + public static string FirstName { get; private set; } + public static string LastName { get; private set; } + public static TextColors TextColor { get; private set; } + public static BackgroundColors BackgroundColor { get; private set; } const string firstNameKey = "firstNameKey"; const string lastNameKey = "lastNameKey"; @@ -34,30 +32,30 @@ public static void LoadDefaultValues () { var settingsDict = new NSDictionary (NSBundle.MainBundle.PathForResource ("Settings.bundle/Root.plist", null)); - var prefSpecifierArray = settingsDict["PreferenceSpecifiers"] as NSArray; + var prefSpecifierArray = settingsDict ["PreferenceSpecifiers"] as NSArray; foreach (var prefItem in NSArray.FromArray (prefSpecifierArray)) { - var key = (NSString)prefItem["Key"]; + var key = (NSString) prefItem ["Key"]; if (key == null) continue; - var val = prefItem["DefaultValue"]; + var val = prefItem ["DefaultValue"]; switch (key.ToString ()) { - case firstNameKey: - FirstName = val.ToString (); - break; - case lastNameKey: - LastName = val.ToString (); - break; - case nameColorKey: - TextColor = (TextColors)((NSNumber)val).Int32Value; - break; - case backgroundColorKey: - BackgroundColor = (BackgroundColors)((NSNumber)val).Int32Value; - break; + case firstNameKey: + FirstName = val.ToString (); + break; + case lastNameKey: + LastName = val.ToString (); + break; + case nameColorKey: + TextColor = (TextColors) ((NSNumber) val).Int32Value; + break; + case backgroundColorKey: + BackgroundColor = (BackgroundColors) ((NSNumber) val).Int32Value; + break; } } - var appDefaults = new NSDictionary (firstNameKey, FirstName, lastNameKey, LastName, nameColorKey, (int)TextColor, backgroundColorKey, (int)BackgroundColor); + var appDefaults = new NSDictionary (firstNameKey, FirstName, lastNameKey, LastName, nameColorKey, (int) TextColor, backgroundColorKey, (int) BackgroundColor); NSUserDefaults.StandardUserDefaults.RegisterDefaults (appDefaults); } @@ -66,8 +64,8 @@ public static void SetupByPreferences () { FirstName = NSUserDefaults.StandardUserDefaults.StringForKey (firstNameKey); LastName = NSUserDefaults.StandardUserDefaults.StringForKey (lastNameKey); - TextColor = (TextColors)(int)NSUserDefaults.StandardUserDefaults.IntForKey (nameColorKey); - BackgroundColor = (BackgroundColors)(int)NSUserDefaults.StandardUserDefaults.IntForKey (backgroundColorKey); + TextColor = (TextColors) (int) NSUserDefaults.StandardUserDefaults.IntForKey (nameColorKey); + BackgroundColor = (BackgroundColors) (int) NSUserDefaults.StandardUserDefaults.IntForKey (backgroundColorKey); } } } diff --git a/Appearance/Appearance/AppDelegate.cs b/Appearance/Appearance/AppDelegate.cs index 7b4393371..28c13d734 100644 --- a/Appearance/Appearance/AppDelegate.cs +++ b/Appearance/Appearance/AppDelegate.cs @@ -1,23 +1,21 @@ -using Foundation; +using Foundation; using UIKit; -namespace Appearance -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace Appearance { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window { get; set; } + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/Appearance/Appearance/AppearanceViewController.cs b/Appearance/Appearance/AppearanceViewController.cs index 0288ce9f3..c138978d8 100644 --- a/Appearance/Appearance/AppearanceViewController.cs +++ b/Appearance/Appearance/AppearanceViewController.cs @@ -1,35 +1,33 @@ -using System; -using UIKit; - -namespace Appearance -{ - public partial class AppearanceViewController : UIViewController - { - public AppearanceViewController (IntPtr handle) : base (handle) - { - // Set the default appearance values - UIButton.Appearance.TintColor = UIColor.LightGray; - UIButton.Appearance.SetTitleColor(UIColor.FromRGB(0, 127, 14), UIControlState.Normal); +using System; +using UIKit; - UISlider.Appearance.ThumbTintColor = UIColor.Red; - UISlider.Appearance.MinimumTrackTintColor = UIColor.Orange; - UISlider.Appearance.MaximumTrackTintColor = UIColor.Yellow; +namespace Appearance { + public partial class AppearanceViewController : UIViewController { + public AppearanceViewController (IntPtr handle) : base (handle) + { + // Set the default appearance values + UIButton.Appearance.TintColor = UIColor.LightGray; + UIButton.Appearance.SetTitleColor (UIColor.FromRGB (0, 127, 14), UIControlState.Normal); - UIProgressView.Appearance.ProgressTintColor = UIColor.Yellow; - UIProgressView.Appearance.TrackTintColor = UIColor.Orange; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // setting the values directly OVERRIDES the Appearance defaults - slider2.ThumbTintColor = UIColor.FromRGB(0, 127, 70); - slider2.MinimumTrackTintColor = UIColor.FromRGB(66, 255, 63); - slider2.MaximumTrackTintColor = UIColor.FromRGB(197, 255, 132); - - progress2.ProgressTintColor = UIColor.FromRGB(66, 255, 63); - progress2.TrackTintColor = UIColor.FromRGB(197, 255, 132); - } - } -} \ No newline at end of file + UISlider.Appearance.ThumbTintColor = UIColor.Red; + UISlider.Appearance.MinimumTrackTintColor = UIColor.Orange; + UISlider.Appearance.MaximumTrackTintColor = UIColor.Yellow; + + UIProgressView.Appearance.ProgressTintColor = UIColor.Yellow; + UIProgressView.Appearance.TrackTintColor = UIColor.Orange; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // setting the values directly OVERRIDES the Appearance defaults + slider2.ThumbTintColor = UIColor.FromRGB (0, 127, 70); + slider2.MinimumTrackTintColor = UIColor.FromRGB (66, 255, 63); + slider2.MaximumTrackTintColor = UIColor.FromRGB (197, 255, 132); + + progress2.ProgressTintColor = UIColor.FromRGB (66, 255, 63); + progress2.TrackTintColor = UIColor.FromRGB (197, 255, 132); + } + } +} diff --git a/Appearance/Appearance/BlackViewController.cs b/Appearance/Appearance/BlackViewController.cs index 5fc691c71..51283a9ad 100644 --- a/Appearance/Appearance/BlackViewController.cs +++ b/Appearance/Appearance/BlackViewController.cs @@ -1,44 +1,41 @@ -using System; -using UIKit; - -namespace Appearance -{ - public partial class BlackViewController : UIViewController - { - private PlainView plainView; +using System; +using UIKit; - public BlackViewController (IntPtr handle) : base (handle) - { - var style = UIButton.AppearanceWhenContainedIn(typeof(PlainView)); - style.SetTitleColor(UIColor.Black, UIControlState.Normal); +namespace Appearance { + public partial class BlackViewController : UIViewController { + private PlainView plainView; - var style1 = UISlider.AppearanceWhenContainedIn(typeof(PlainView)); - style1.ThumbTintColor = UIColor.DarkGray; - style1.MaximumTrackTintColor = UIColor.Gray; - style1.MinimumTrackTintColor = UIColor.LightGray; - - var style2 = UIProgressView.AppearanceWhenContainedIn(typeof(PlainView)); - style2.ProgressTintColor = UIColor.DarkGray; - style2.TrackTintColor = UIColor.LightGray; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - View.BackgroundColor = UIColor.White; - - plainView = new PlainView { Frame = View.Bounds }; - View.AddSubview(plainView); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if(plainView != null) - { - plainView.Dispose(); - plainView = null; - } - } - } -} \ No newline at end of file + public BlackViewController (IntPtr handle) : base (handle) + { + var style = UIButton.AppearanceWhenContainedIn (typeof (PlainView)); + style.SetTitleColor (UIColor.Black, UIControlState.Normal); + + var style1 = UISlider.AppearanceWhenContainedIn (typeof (PlainView)); + style1.ThumbTintColor = UIColor.DarkGray; + style1.MaximumTrackTintColor = UIColor.Gray; + style1.MinimumTrackTintColor = UIColor.LightGray; + + var style2 = UIProgressView.AppearanceWhenContainedIn (typeof (PlainView)); + style2.ProgressTintColor = UIColor.DarkGray; + style2.TrackTintColor = UIColor.LightGray; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + View.BackgroundColor = UIColor.White; + + plainView = new PlainView { Frame = View.Bounds }; + View.AddSubview (plainView); + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (plainView != null) { + plainView.Dispose (); + plainView = null; + } + } + } +} diff --git a/Appearance/Appearance/BlueViewController.cs b/Appearance/Appearance/BlueViewController.cs index db3a8f8a1..ab66e4b1a 100644 --- a/Appearance/Appearance/BlueViewController.cs +++ b/Appearance/Appearance/BlueViewController.cs @@ -1,43 +1,40 @@ -using System; -using UIKit; - -namespace Appearance -{ - public partial class BlueViewController : UIViewController - { - private PlainView plainView; +using System; +using UIKit; - public BlueViewController (IntPtr handle) : base (handle) - { - var style = UIButton.AppearanceWhenContainedIn(typeof(PlainView)); - style.SetTitleColor(UIColor.Blue, UIControlState.Normal); +namespace Appearance { + public partial class BlueViewController : UIViewController { + private PlainView plainView; - var style1 = UISlider.AppearanceWhenContainedIn(typeof(PlainView)); - style1.ThumbTintColor = UIColor.Blue; - style1.MaximumTrackTintColor = UIColor.FromRGB(0, 114, 255); - style1.MinimumTrackTintColor = UIColor.FromRGB(0, 255, 255); - - var style2 = UIProgressView.AppearanceWhenContainedIn(typeof(PlainView)); - style2.ProgressTintColor = UIColor.FromRGB(150, 221, 255); - style2.TrackTintColor = UIColor.FromRGB(211, 255, 243); - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - plainView = new PlainView { Frame = View.Bounds, BackgroundColor = UIColor.FromRGB(201, 207, 255) }; - View.AddSubview(plainView); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (plainView != null) - { - plainView.Dispose(); - plainView = null; - } - } - } -} \ No newline at end of file + public BlueViewController (IntPtr handle) : base (handle) + { + var style = UIButton.AppearanceWhenContainedIn (typeof (PlainView)); + style.SetTitleColor (UIColor.Blue, UIControlState.Normal); + + var style1 = UISlider.AppearanceWhenContainedIn (typeof (PlainView)); + style1.ThumbTintColor = UIColor.Blue; + style1.MaximumTrackTintColor = UIColor.FromRGB (0, 114, 255); + style1.MinimumTrackTintColor = UIColor.FromRGB (0, 255, 255); + + var style2 = UIProgressView.AppearanceWhenContainedIn (typeof (PlainView)); + style2.ProgressTintColor = UIColor.FromRGB (150, 221, 255); + style2.TrackTintColor = UIColor.FromRGB (211, 255, 243); + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + plainView = new PlainView { Frame = View.Bounds, BackgroundColor = UIColor.FromRGB (201, 207, 255) }; + View.AddSubview (plainView); + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (plainView != null) { + plainView.Dispose (); + plainView = null; + } + } + } +} diff --git a/Appearance/Appearance/Main.cs b/Appearance/Appearance/Main.cs index aed2fc664..b2210edca 100644 --- a/Appearance/Appearance/Main.cs +++ b/Appearance/Appearance/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Appearance -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace Appearance { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/Appearance/Appearance/PlainView.cs b/Appearance/Appearance/PlainView.cs index e09c5e844..0479196ee 100644 --- a/Appearance/Appearance/PlainView.cs +++ b/Appearance/Appearance/PlainView.cs @@ -1,54 +1,49 @@ using CoreGraphics; using UIKit; -namespace Appearance -{ - public class PlainView : UIView - { - private UIProgressView progress; - private UIButton plainButton; - private UISlider slider; - - public PlainView() - { - slider = new UISlider(); - progress = new UIProgressView(); - plainButton = UIButton.FromType(UIButtonType.RoundedRect); - plainButton.SetTitle("Plain Button", UIControlState.Normal); - - plainButton.Frame = new CGRect(20, 150, 130, 40); - slider.Frame = new CGRect(20, 190, 250, 20); - progress.Frame = new CGRect(20, 230, 250, 20); - - slider.Value = 0.75f; - progress.Progress = 0.35f; - - AddSubview(plainButton); - AddSubview(slider); - AddSubview(progress); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (plainButton != null) - { - plainButton.Dispose(); - plainButton = null; - } - - if (slider != null) - { - slider.Dispose(); - slider = null; - } - - if (progress != null) - { - progress.Dispose(); - progress = null; - } - } - } -} \ No newline at end of file +namespace Appearance { + public class PlainView : UIView { + private UIProgressView progress; + private UIButton plainButton; + private UISlider slider; + + public PlainView () + { + slider = new UISlider (); + progress = new UIProgressView (); + plainButton = UIButton.FromType (UIButtonType.RoundedRect); + plainButton.SetTitle ("Plain Button", UIControlState.Normal); + + plainButton.Frame = new CGRect (20, 150, 130, 40); + slider.Frame = new CGRect (20, 190, 250, 20); + progress.Frame = new CGRect (20, 230, 250, 20); + + slider.Value = 0.75f; + progress.Progress = 0.35f; + + AddSubview (plainButton); + AddSubview (slider); + AddSubview (progress); + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + if (plainButton != null) { + plainButton.Dispose (); + plainButton = null; + } + + if (slider != null) { + slider.Dispose (); + slider = null; + } + + if (progress != null) { + progress.Dispose (); + progress = null; + } + } + } +} diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/AppDelegate.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/AppDelegate.cs index 3b9c84eba..955d85424 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/AppDelegate.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/AppDelegate.cs @@ -1,67 +1,64 @@ -using Foundation; +using Foundation; using UIKit; -namespace FingerPaint -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace FingerPaint { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window - { - get; - set; - } + public override UIWindow Window { + get; + set; + } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // create a new window instance based on the screen size - Window = new UIWindow(UIScreen.MainScreen.Bounds); + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // create a new window instance based on the screen size + Window = new UIWindow (UIScreen.MainScreen.Bounds); - // If you have defined a root view controller, set it here: - // Window.RootViewController = myViewController; - Window.RootViewController = new FingerPaintViewController(); + // If you have defined a root view controller, set it here: + // Window.RootViewController = myViewController; + Window.RootViewController = new FingerPaintViewController (); - // make the window visible - Window.MakeKeyAndVisible(); + // make the window visible + Window.MakeKeyAndVisible (); - return true; - } + return true; + } - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintCanvasView.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintCanvasView.cs index b017d257c..9534d4380 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintCanvasView.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintCanvasView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,117 +6,107 @@ using Foundation; using UIKit; -namespace FingerPaint -{ - class FingerPaintCanvasView : UIView - { - // Two collections for storing polylines - Dictionary inProgressPolylines = new Dictionary(); - List completedPolylines = new List(); - - public FingerPaintCanvasView() - { - BackgroundColor = UIColor.White; - MultipleTouchEnabled = true; - } - - public CGColor StrokeColor { set; get; } = new CGColor(1.0f, 0, 0); - - public float StrokeWidth { set; get; } = 2; - - public void Clear() - { - completedPolylines.Clear(); - SetNeedsDisplay(); - } - - public override void TouchesBegan(NSSet touches, UIEvent evt) - { - base.TouchesBegan(touches, evt); - - foreach (UITouch touch in touches.Cast()) - { - // Create a FingerPaintPolyline, set the initial point, and store it - FingerPaintPolyline polyline = new FingerPaintPolyline - { - Color = StrokeColor, - StrokeWidth = StrokeWidth, - }; - - polyline.Path.MoveToPoint(touch.LocationInView(this)); - inProgressPolylines.Add(touch.Handle, polyline); - } - SetNeedsDisplay(); - } - - public override void TouchesMoved(NSSet touches, UIEvent evt) - { - base.TouchesMoved(touches, evt); - - foreach (UITouch touch in touches.Cast()) - { - // Add point to path - inProgressPolylines[touch.Handle].Path.AddLineToPoint(touch.LocationInView(this)); - } - SetNeedsDisplay(); - } - - public override void TouchesEnded(NSSet touches, UIEvent evt) - { - base.TouchesEnded(touches, evt); - - foreach (UITouch touch in touches.Cast()) - { - // Get polyline from dictionary and remove it from dictionary - FingerPaintPolyline polyline = inProgressPolylines[touch.Handle]; - inProgressPolylines.Remove(touch.Handle); - - // Add final point to path and save with completed polylines - polyline.Path.AddLineToPoint(touch.LocationInView(this)); - completedPolylines.Add(polyline); - } - SetNeedsDisplay(); - } - - public override void TouchesCancelled(NSSet touches, UIEvent evt) - { - base.TouchesCancelled(touches, evt); - - foreach (UITouch touch in touches.Cast()) - { - inProgressPolylines.Remove(touch.Handle); - } - SetNeedsDisplay(); - } - - public override void Draw(CGRect rect) - { - base.Draw(rect); - - using (CGContext context = UIGraphics.GetCurrentContext()) - { - // Stroke settings - context.SetLineCap(CGLineCap.Round); - context.SetLineJoin(CGLineJoin.Round); - - // Draw the completed polylines - foreach (FingerPaintPolyline polyline in completedPolylines) - { - context.SetStrokeColor(polyline.Color); - context.SetLineWidth(polyline.StrokeWidth); - context.AddPath(polyline.Path); - context.DrawPath(CGPathDrawingMode.Stroke); - } - - // Draw the in-progress polylines - foreach (FingerPaintPolyline polyline in inProgressPolylines.Values) - { - context.SetStrokeColor(polyline.Color); - context.SetLineWidth(polyline.StrokeWidth); - context.AddPath(polyline.Path); - context.DrawPath(CGPathDrawingMode.Stroke); - } - } - } - } +namespace FingerPaint { + class FingerPaintCanvasView : UIView { + // Two collections for storing polylines + Dictionary inProgressPolylines = new Dictionary (); + List completedPolylines = new List (); + + public FingerPaintCanvasView () + { + BackgroundColor = UIColor.White; + MultipleTouchEnabled = true; + } + + public CGColor StrokeColor { set; get; } = new CGColor (1.0f, 0, 0); + + public float StrokeWidth { set; get; } = 2; + + public void Clear () + { + completedPolylines.Clear (); + SetNeedsDisplay (); + } + + public override void TouchesBegan (NSSet touches, UIEvent evt) + { + base.TouchesBegan (touches, evt); + + foreach (UITouch touch in touches.Cast ()) { + // Create a FingerPaintPolyline, set the initial point, and store it + FingerPaintPolyline polyline = new FingerPaintPolyline { + Color = StrokeColor, + StrokeWidth = StrokeWidth, + }; + + polyline.Path.MoveToPoint (touch.LocationInView (this)); + inProgressPolylines.Add (touch.Handle, polyline); + } + SetNeedsDisplay (); + } + + public override void TouchesMoved (NSSet touches, UIEvent evt) + { + base.TouchesMoved (touches, evt); + + foreach (UITouch touch in touches.Cast ()) { + // Add point to path + inProgressPolylines [touch.Handle].Path.AddLineToPoint (touch.LocationInView (this)); + } + SetNeedsDisplay (); + } + + public override void TouchesEnded (NSSet touches, UIEvent evt) + { + base.TouchesEnded (touches, evt); + + foreach (UITouch touch in touches.Cast ()) { + // Get polyline from dictionary and remove it from dictionary + FingerPaintPolyline polyline = inProgressPolylines [touch.Handle]; + inProgressPolylines.Remove (touch.Handle); + + // Add final point to path and save with completed polylines + polyline.Path.AddLineToPoint (touch.LocationInView (this)); + completedPolylines.Add (polyline); + } + SetNeedsDisplay (); + } + + public override void TouchesCancelled (NSSet touches, UIEvent evt) + { + base.TouchesCancelled (touches, evt); + + foreach (UITouch touch in touches.Cast ()) { + inProgressPolylines.Remove (touch.Handle); + } + SetNeedsDisplay (); + } + + public override void Draw (CGRect rect) + { + base.Draw (rect); + + using (CGContext context = UIGraphics.GetCurrentContext ()) { + // Stroke settings + context.SetLineCap (CGLineCap.Round); + context.SetLineJoin (CGLineJoin.Round); + + // Draw the completed polylines + foreach (FingerPaintPolyline polyline in completedPolylines) { + context.SetStrokeColor (polyline.Color); + context.SetLineWidth (polyline.StrokeWidth); + context.AddPath (polyline.Path); + context.DrawPath (CGPathDrawingMode.Stroke); + } + + // Draw the in-progress polylines + foreach (FingerPaintPolyline polyline in inProgressPolylines.Values) { + context.SetStrokeColor (polyline.Color); + context.SetLineWidth (polyline.StrokeWidth); + context.AddPath (polyline.Path); + context.DrawPath (CGPathDrawingMode.Stroke); + } + } + } + } } diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintPolyline.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintPolyline.cs index 0110f068a..17da1ea1a 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintPolyline.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintPolyline.cs @@ -1,19 +1,17 @@ using CoreGraphics; using System.Collections.Generic; -namespace FingerPaint -{ - class FingerPaintPolyline - { - public FingerPaintPolyline() - { - Path = new CGPath(); - } +namespace FingerPaint { + class FingerPaintPolyline { + public FingerPaintPolyline () + { + Path = new CGPath (); + } - public CGColor Color { set; get; } + public CGColor Color { set; get; } - public float StrokeWidth { set; get; } + public float StrokeWidth { set; get; } - public CGPath Path { private set; get; } - } -} \ No newline at end of file + public CGPath Path { private set; get; } + } +} diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintViewController.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintViewController.cs index 1497d234c..43ef1623b 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintViewController.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/FingerPaintViewController.cs @@ -1,194 +1,176 @@ using CoreGraphics; using UIKit; -namespace FingerPaint -{ - public partial class FingerPaintViewController : UIViewController - { - // UITextField derivative used for invoking picker views - class NoCaretField : UITextField - { - public NoCaretField() : base(new CGRect()) - { - BorderStyle = UITextBorderStyle.Line; - } - - public override CGRect GetCaretRectForPosition(UITextPosition position) - { - return new CGRect(); - } - } - - public FingerPaintViewController() - { - } - - public override void LoadView() - { - base.LoadView(); - - // White view covering entire screen - UIView contentView = new UIView() - { - BackgroundColor = UIColor.White - }; - View = contentView; - - // Vertical UIStackView offset from status bar - CGRect rect = UIScreen.MainScreen.Bounds; - rect.Y += 20; - rect.Height -= 20; - - UIStackView vertStackView = new UIStackView(rect) - { - Axis = UILayoutConstraintAxis.Vertical, - }; - contentView.Add(vertStackView); - - // Horizontal UIStackView for tools - UIStackView horzStackView = new UIStackView - { - Axis = UILayoutConstraintAxis.Horizontal, - Alignment = UIStackViewAlignment.Center, - Distribution = UIStackViewDistribution.EqualSpacing - }; - vertStackView.AddArrangedSubview(horzStackView); - - // FingerPaintCanvasView for drawing - FingerPaintCanvasView canvasView = new FingerPaintCanvasView(); - vertStackView.AddArrangedSubview(canvasView); - - // Add space at left to horizontal UIStackView - horzStackView.AddArrangedSubview(new UILabel(new CGRect(0, 0, 10, 10))); - - // Construct UIPickerView for choosing color, but don't add it to any view - PickerDataModel colorModel = new PickerDataModel - { - Items = - { - new NamedValue("Red", UIColor.Red), - new NamedValue("Green", UIColor.Green), - new NamedValue("Blue", UIColor.Blue), - new NamedValue("Cyan", UIColor.Cyan), - new NamedValue("Magenta", UIColor.Magenta), - new NamedValue("Yellow", UIColor.Yellow), - new NamedValue("Black", UIColor.Black), - new NamedValue("Gray", UIColor.Gray), - new NamedValue("White", UIColor.White) - } - }; - - UIPickerView colorPicker = new UIPickerView - { - Model = colorModel - }; - - // Ditto for UIPickerView for stroke thickness - PickerDataModel thicknessModel = new PickerDataModel - { - Items = - { - new NamedValue("Thin", 2), - new NamedValue("Thinish", 5), - new NamedValue("Medium", 10), - new NamedValue("Thickish", 20), - new NamedValue("Thick", 50) - } - }; - - UIPickerView thicknessPicker = new UIPickerView - { - Model = thicknessModel - }; - - // Create UIToolbar for dismissing picker when it's displayed - var toolbar = new UIToolbar(new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, 44)) - { - BarStyle = UIBarStyle.Default, - Translucent = true - }; - - // Set Font to be used in tools - UIFont font = UIFont.SystemFontOfSize(24); - - // Create a NoCaretField text field for invoking color picker & add to horizontal UIStackView - // (technique from Xamarin.Forms iOS PickerRenderer - UITextField colorTextField = new NoCaretField - { - Text = "Red", - InputView = colorPicker, - InputAccessoryView = toolbar, - Font = font - }; - horzStackView.AddArrangedSubview(colorTextField); - - // Use ValueChanged handler to change the color - colorModel.ValueChanged += (sender, args) => - { - colorTextField.Text = colorModel.SelectedItem.Name; - canvasView.StrokeColor = colorModel.SelectedItem.Value.CGColor; - }; - - // Ditto for the thickness - UITextField thicknessTextField = new NoCaretField - { - Text = "Thin", - InputView = thicknessPicker, - InputAccessoryView = toolbar, - Font = font - }; - horzStackView.AddArrangedSubview(thicknessTextField); - - thicknessModel.ValueChanged += (sender, args) => - { - thicknessTextField.Text = thicknessModel.SelectedItem.Name; - canvasView.StrokeWidth = thicknessModel.SelectedItem.Value; - }; - - // Now add a Done button to the toolbar to rest text fields - var spacer = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace); - var doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, (o, a) => - { - colorTextField.ResignFirstResponder(); - thicknessTextField.ResignFirstResponder(); - }); - - toolbar.SetItems(new[] { spacer, doneButton }, false); - - // Create the Clear button - UIButton button = new UIButton(UIButtonType.RoundedRect) - { - Font = font - }; - horzStackView.AddArrangedSubview(button); - - button.Layer.BorderColor = UIColor.Black.CGColor; - button.Layer.BorderWidth = 1; - button.Layer.CornerRadius = 10; - button.SetTitle("Clear", UIControlState.Normal); - button.SetTitleColor(UIColor.Black, UIControlState.Normal); - - button.TouchUpInside += (sender, args) => - { - canvasView.Clear(); - }; - - // Add space at right to horizontal UIStackView - horzStackView.AddArrangedSubview(new UILabel(new CGRect(0, 0, 10, 10))); - } - - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - - // Release any cached data, images, etc that aren't in use. - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Perform any additional setup after loading the view, typically from a nib. - } - } -} \ No newline at end of file +namespace FingerPaint { + public partial class FingerPaintViewController : UIViewController { + // UITextField derivative used for invoking picker views + class NoCaretField : UITextField { + public NoCaretField () : base (new CGRect ()) + { + BorderStyle = UITextBorderStyle.Line; + } + + public override CGRect GetCaretRectForPosition (UITextPosition position) + { + return new CGRect (); + } + } + + public FingerPaintViewController () + { + } + + public override void LoadView () + { + base.LoadView (); + + // White view covering entire screen + UIView contentView = new UIView () { + BackgroundColor = UIColor.White + }; + View = contentView; + + // Vertical UIStackView offset from status bar + CGRect rect = UIScreen.MainScreen.Bounds; + rect.Y += 20; + rect.Height -= 20; + + UIStackView vertStackView = new UIStackView (rect) { + Axis = UILayoutConstraintAxis.Vertical, + }; + contentView.Add (vertStackView); + + // Horizontal UIStackView for tools + UIStackView horzStackView = new UIStackView { + Axis = UILayoutConstraintAxis.Horizontal, + Alignment = UIStackViewAlignment.Center, + Distribution = UIStackViewDistribution.EqualSpacing + }; + vertStackView.AddArrangedSubview (horzStackView); + + // FingerPaintCanvasView for drawing + FingerPaintCanvasView canvasView = new FingerPaintCanvasView (); + vertStackView.AddArrangedSubview (canvasView); + + // Add space at left to horizontal UIStackView + horzStackView.AddArrangedSubview (new UILabel (new CGRect (0, 0, 10, 10))); + + // Construct UIPickerView for choosing color, but don't add it to any view + PickerDataModel colorModel = new PickerDataModel { + Items = + { + new NamedValue("Red", UIColor.Red), + new NamedValue("Green", UIColor.Green), + new NamedValue("Blue", UIColor.Blue), + new NamedValue("Cyan", UIColor.Cyan), + new NamedValue("Magenta", UIColor.Magenta), + new NamedValue("Yellow", UIColor.Yellow), + new NamedValue("Black", UIColor.Black), + new NamedValue("Gray", UIColor.Gray), + new NamedValue("White", UIColor.White) + } + }; + + UIPickerView colorPicker = new UIPickerView { + Model = colorModel + }; + + // Ditto for UIPickerView for stroke thickness + PickerDataModel thicknessModel = new PickerDataModel { + Items = + { + new NamedValue("Thin", 2), + new NamedValue("Thinish", 5), + new NamedValue("Medium", 10), + new NamedValue("Thickish", 20), + new NamedValue("Thick", 50) + } + }; + + UIPickerView thicknessPicker = new UIPickerView { + Model = thicknessModel + }; + + // Create UIToolbar for dismissing picker when it's displayed + var toolbar = new UIToolbar (new CGRect (0, 0, UIScreen.MainScreen.Bounds.Width, 44)) { + BarStyle = UIBarStyle.Default, + Translucent = true + }; + + // Set Font to be used in tools + UIFont font = UIFont.SystemFontOfSize (24); + + // Create a NoCaretField text field for invoking color picker & add to horizontal UIStackView + // (technique from Xamarin.Forms iOS PickerRenderer + UITextField colorTextField = new NoCaretField { + Text = "Red", + InputView = colorPicker, + InputAccessoryView = toolbar, + Font = font + }; + horzStackView.AddArrangedSubview (colorTextField); + + // Use ValueChanged handler to change the color + colorModel.ValueChanged += (sender, args) => { + colorTextField.Text = colorModel.SelectedItem.Name; + canvasView.StrokeColor = colorModel.SelectedItem.Value.CGColor; + }; + + // Ditto for the thickness + UITextField thicknessTextField = new NoCaretField { + Text = "Thin", + InputView = thicknessPicker, + InputAccessoryView = toolbar, + Font = font + }; + horzStackView.AddArrangedSubview (thicknessTextField); + + thicknessModel.ValueChanged += (sender, args) => { + thicknessTextField.Text = thicknessModel.SelectedItem.Name; + canvasView.StrokeWidth = thicknessModel.SelectedItem.Value; + }; + + // Now add a Done button to the toolbar to rest text fields + var spacer = new UIBarButtonItem (UIBarButtonSystemItem.FlexibleSpace); + var doneButton = new UIBarButtonItem (UIBarButtonSystemItem.Done, (o, a) => { + colorTextField.ResignFirstResponder (); + thicknessTextField.ResignFirstResponder (); + }); + + toolbar.SetItems (new [] { spacer, doneButton }, false); + + // Create the Clear button + UIButton button = new UIButton (UIButtonType.RoundedRect) { + Font = font + }; + horzStackView.AddArrangedSubview (button); + + button.Layer.BorderColor = UIColor.Black.CGColor; + button.Layer.BorderWidth = 1; + button.Layer.CornerRadius = 10; + button.SetTitle ("Clear", UIControlState.Normal); + button.SetTitleColor (UIColor.Black, UIControlState.Normal); + + button.TouchUpInside += (sender, args) => { + canvasView.Clear (); + }; + + // Add space at right to horizontal UIStackView + horzStackView.AddArrangedSubview (new UILabel (new CGRect (0, 0, 10, 10))); + } + + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Perform any additional setup after loading the view, typically from a nib. + } + } +} diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/Main.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/Main.cs index 6e563ff1a..55f04d476 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/Main.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace FingerPaint -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace FingerPaint { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/PickerDataModel.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/PickerDataModel.cs index 5c5b1c7e9..0007f4332 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/PickerDataModel.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/PickerDataModel.cs @@ -1,64 +1,59 @@ -using System; +using System; using System.Collections.Generic; using UIKit; -namespace FingerPaint -{ - class NamedValue - { - public NamedValue(string name, T value) - { - Name = name; - Value = value; - } - - public string Name { private set; get; } - - public T Value { private set; get; } - } - - class PickerDataModel : UIPickerViewModel - { - public event EventHandler ValueChanged; - - int selectedIndex = 0; - - public PickerDataModel() - { - Items = new List>(); - } - - public IList> Items { private set; get; } - - public NamedValue SelectedItem - { - get - { - return Items != null && - selectedIndex >= 0 && - selectedIndex < Items.Count ? Items[selectedIndex] : null; - } - } - - public override nint GetRowsInComponent(UIPickerView picker, nint component) - { - return Items != null ? Items.Count : 0; - } - - public override string GetTitle(UIPickerView picker, nint row, nint component) - { - return Items != null && Items.Count > row ? Items[(int)row].Name : null; - } - - public override nint GetComponentCount(UIPickerView picker) - { - return 1; - } - - public override void Selected(UIPickerView picker, nint row, nint component) - { - selectedIndex = (int)row; - ValueChanged?.Invoke(this, new EventArgs()); - } - } +namespace FingerPaint { + class NamedValue { + public NamedValue (string name, T value) + { + Name = name; + Value = value; + } + + public string Name { private set; get; } + + public T Value { private set; get; } + } + + class PickerDataModel : UIPickerViewModel { + public event EventHandler ValueChanged; + + int selectedIndex = 0; + + public PickerDataModel () + { + Items = new List> (); + } + + public IList> Items { private set; get; } + + public NamedValue SelectedItem { + get { + return Items != null && + selectedIndex >= 0 && + selectedIndex < Items.Count ? Items [selectedIndex] : null; + } + } + + public override nint GetRowsInComponent (UIPickerView picker, nint component) + { + return Items != null ? Items.Count : 0; + } + + public override string GetTitle (UIPickerView picker, nint row, nint component) + { + return Items != null && Items.Count > row ? Items [(int) row].Name : null; + } + + public override nint GetComponentCount (UIPickerView picker) + { + return 1; + } + + public override void Selected (UIPickerView picker, nint row, nint component) + { + selectedIndex = (int) row; + ValueChanged?.Invoke (this, new EventArgs ()); + } + } } diff --git a/ApplicationFundamentals/FingerPaint/FingerPaint/Properties/AssemblyInfo.cs b/ApplicationFundamentals/FingerPaint/FingerPaint/Properties/AssemblyInfo.cs index 30bfd4604..0f4af9a54 100644 --- a/ApplicationFundamentals/FingerPaint/FingerPaint/Properties/AssemblyInfo.cs +++ b/ApplicationFundamentals/FingerPaint/FingerPaint/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("FingerPaint")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("FingerPaint")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("FingerPaint")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("FingerPaint")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ee2a9ec7-2af2-44ce-9773-1c6884555740")] +[assembly: Guid ("ee2a9ec7-2af2-44ce-9773-1c6884555740")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ApplicationFundamentals/Touch_final/AppDelegate.cs b/ApplicationFundamentals/Touch_final/AppDelegate.cs index afc9f8c39..5867fc638 100644 --- a/ApplicationFundamentals/Touch_final/AppDelegate.cs +++ b/ApplicationFundamentals/Touch_final/AppDelegate.cs @@ -3,21 +3,19 @@ using Foundation; using UIKit; -namespace Touch -{ +namespace Touch { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // // This method is invoked when the application is about to move from active to inactive state. // @@ -26,19 +24,19 @@ public override UIWindow Window { public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/ApplicationFundamentals/Touch_final/Classes/CheckmarkGestureRecognizer.cs b/ApplicationFundamentals/Touch_final/Classes/CheckmarkGestureRecognizer.cs index 129a65af8..81f57a871 100644 --- a/ApplicationFundamentals/Touch_final/Classes/CheckmarkGestureRecognizer.cs +++ b/ApplicationFundamentals/Touch_final/Classes/CheckmarkGestureRecognizer.cs @@ -4,22 +4,20 @@ using Foundation; using UIKit; -namespace Touch -{ - public class CheckmarkGestureRecognizer : UIGestureRecognizer - { +namespace Touch { + public class CheckmarkGestureRecognizer : UIGestureRecognizer { #region Private Variables private CGPoint midpoint = CGPoint.Empty; private bool strokeUp = false; - #endregion + #endregion #region Override Methods /// /// Called when the touches end or the recognizer state fails /// - public override void Reset() + public override void Reset () { - base.Reset(); + base.Reset (); strokeUp = false; midpoint = CGPoint.Empty; @@ -28,25 +26,24 @@ public override void Reset() /// /// Is called when the fingers touch the screen. /// - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); + base.TouchesBegan (touches, evt); // we want one and only one finger - if (touches.Count != 1) - { + if (touches.Count != 1) { base.State = UIGestureRecognizerState.Failed; } - Console.WriteLine(base.State.ToString()); + Console.WriteLine (base.State.ToString ()); } /// /// Called when the touches are cancelled due to a phone call, etc. /// - public override void TouchesCancelled(NSSet touches, UIEvent evt) + public override void TouchesCancelled (NSSet touches, UIEvent evt) { - base.TouchesCancelled(touches, evt); + base.TouchesCancelled (touches, evt); // we fail the recognizer so that there isn't unexpected behavior // if the application comes back into view base.State = UIGestureRecognizerState.Failed; @@ -55,56 +52,50 @@ public override void TouchesCancelled(NSSet touches, UIEvent evt) /// /// Called when the fingers lift off the screen /// - public override void TouchesEnded(NSSet touches, UIEvent evt) + public override void TouchesEnded (NSSet touches, UIEvent evt) { - base.TouchesEnded(touches, evt); + base.TouchesEnded (touches, evt); // - if (base.State == UIGestureRecognizerState.Possible && strokeUp) - { + if (base.State == UIGestureRecognizerState.Possible && strokeUp) { base.State = UIGestureRecognizerState.Recognized; } - Console.WriteLine(base.State.ToString()); + Console.WriteLine (base.State.ToString ()); } /// /// Called when the fingers move /// - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); // if we haven't already failed - if (base.State != UIGestureRecognizerState.Failed) - { + if (base.State != UIGestureRecognizerState.Failed) { // get the current and previous touch point - CGPoint newPoint = (touches.AnyObject as UITouch).LocationInView(View); - CGPoint previousPoint = (touches.AnyObject as UITouch).PreviousLocationInView(View); + CGPoint newPoint = (touches.AnyObject as UITouch).LocationInView (View); + CGPoint previousPoint = (touches.AnyObject as UITouch).PreviousLocationInView (View); // if we're not already on the upstroke - if (!strokeUp) - { + if (!strokeUp) { // if we're moving down, just continue to set the midpoint at // whatever point we're at. when we start to stroke up, it'll stick // as the last point before we upticked - if (newPoint.X >= previousPoint.X && newPoint.Y >= previousPoint.Y) - { + if (newPoint.X >= previousPoint.X && newPoint.Y >= previousPoint.Y) { midpoint = newPoint; } // if we're stroking up (moving right x and up y [y axis is flipped]) - else if (newPoint.X >= previousPoint.X && newPoint.Y <= previousPoint.Y) - { + else if (newPoint.X >= previousPoint.X && newPoint.Y <= previousPoint.Y) { strokeUp = true; } // otherwise, we fail the recognizer - else - { + else { base.State = UIGestureRecognizerState.Failed; } } } - Console.WriteLine(base.State.ToString()); + Console.WriteLine (base.State.ToString ()); } #endregion } diff --git a/ApplicationFundamentals/Touch_final/CustomGestureViewController.cs b/ApplicationFundamentals/Touch_final/CustomGestureViewController.cs index 46bfb5aeb..2d1559a7c 100644 --- a/ApplicationFundamentals/Touch_final/CustomGestureViewController.cs +++ b/ApplicationFundamentals/Touch_final/CustomGestureViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace Touch -{ - partial class CustomGestureViewController : UIViewController - { +namespace Touch { + partial class CustomGestureViewController : UIViewController { #region Private Variables private bool isChecked = false; private CheckmarkGestureRecognizer checkmarkGesture; @@ -19,39 +17,35 @@ public CustomGestureViewController (IntPtr handle) : base (handle) #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Wire up the gesture recognizer - WireUpCheckmarkGestureRecognizer(); + WireUpCheckmarkGestureRecognizer (); } #endregion #region Private Methods - private void WireUpCheckmarkGestureRecognizer() + private void WireUpCheckmarkGestureRecognizer () { // Create the recognizer - checkmarkGesture = new CheckmarkGestureRecognizer(); + checkmarkGesture = new CheckmarkGestureRecognizer (); // Wire up the event handler - checkmarkGesture.AddTarget(() =>{ - if (checkmarkGesture.State == (UIGestureRecognizerState.Recognized | UIGestureRecognizerState.Ended)) - { - if (isChecked) - { - CheckboxImage.Image = UIImage.FromBundle("CheckBox_Unchecked.png"); - } - else - { - CheckboxImage.Image = UIImage.FromBundle("CheckBox_Checked.png"); + checkmarkGesture.AddTarget (() => { + if (checkmarkGesture.State == (UIGestureRecognizerState.Recognized | UIGestureRecognizerState.Ended)) { + if (isChecked) { + CheckboxImage.Image = UIImage.FromBundle ("CheckBox_Unchecked.png"); + } else { + CheckboxImage.Image = UIImage.FromBundle ("CheckBox_Checked.png"); } isChecked = !isChecked; } }); // Add the gesture recognizer to the view - View.AddGestureRecognizer(checkmarkGesture); + View.AddGestureRecognizer (checkmarkGesture); } #endregion } diff --git a/ApplicationFundamentals/Touch_final/GestureViewController.cs b/ApplicationFundamentals/Touch_final/GestureViewController.cs index 05b10ac95..7fcf8da37 100644 --- a/ApplicationFundamentals/Touch_final/GestureViewController.cs +++ b/ApplicationFundamentals/Touch_final/GestureViewController.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using CoreGraphics; -namespace Touch -{ - partial class GestureViewController : UIViewController - { +namespace Touch { + partial class GestureViewController : UIViewController { #region Private Variables private bool imageHighlighted = false; private CGRect originalImageFrame = CGRect.Empty; @@ -20,81 +18,76 @@ public GestureViewController (IntPtr handle) : base (handle) #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); Title = "Gesture Recognizers"; // Save initial state originalImageFrame = DragImage.Frame; - WireUpTapGestureRecognizer(); - WireUpDragGestureRecognizer(); + WireUpTapGestureRecognizer (); + WireUpDragGestureRecognizer (); } #endregion #region Private Methods - private void HandleDrag(UIPanGestureRecognizer recognizer) + private void HandleDrag (UIPanGestureRecognizer recognizer) { // If it's just began, cache the location of the image - if (recognizer.State == UIGestureRecognizerState.Began) - { + if (recognizer.State == UIGestureRecognizerState.Began) { originalImageFrame = DragImage.Frame; } // Move the image if the gesture is valid if (recognizer.State != (UIGestureRecognizerState.Cancelled | UIGestureRecognizerState.Failed - | UIGestureRecognizerState.Possible)) - { + | UIGestureRecognizerState.Possible)) { // Move the image by adding the offset to the object's frame - CGPoint offset = recognizer.TranslationInView(DragImage); + CGPoint offset = recognizer.TranslationInView (DragImage); CGRect newFrame = originalImageFrame; - newFrame.Offset(offset.X, offset.Y); + newFrame.Offset (offset.X, offset.Y); DragImage.Frame = newFrame; } } - private void WireUpDragGestureRecognizer() + private void WireUpDragGestureRecognizer () { // Create a new tap gesture - UIPanGestureRecognizer gesture = new UIPanGestureRecognizer(); + UIPanGestureRecognizer gesture = new UIPanGestureRecognizer (); // Wire up the event handler (have to use a selector) - gesture.AddTarget(() => HandleDrag(gesture)); + gesture.AddTarget (() => HandleDrag (gesture)); // Add the gesture recognizer to the view - DragImage.AddGestureRecognizer(gesture); + DragImage.AddGestureRecognizer (gesture); } - - private void WireUpTapGestureRecognizer() + + private void WireUpTapGestureRecognizer () { // Create a new tap gesture UITapGestureRecognizer tapGesture = null; // Report touch - Action action = () => { - TouchStatus.Text = string.Format("Image touched at: {0}",tapGesture.LocationOfTouch(0, DoubleTouchImage)); + Action action = () => { + TouchStatus.Text = string.Format ("Image touched at: {0}", tapGesture.LocationOfTouch (0, DoubleTouchImage)); // Toggle the image - if (imageHighlighted) - { - DoubleTouchImage.Image = UIImage.FromBundle("DoubleTapMe.png"); - } - else - { - DoubleTouchImage.Image = UIImage.FromBundle("DoubleTapMe_Highlighted.png"); + if (imageHighlighted) { + DoubleTouchImage.Image = UIImage.FromBundle ("DoubleTapMe.png"); + } else { + DoubleTouchImage.Image = UIImage.FromBundle ("DoubleTapMe_Highlighted.png"); } imageHighlighted = !imageHighlighted; }; - tapGesture = new UITapGestureRecognizer(action); + tapGesture = new UITapGestureRecognizer (action); // Configure it tapGesture.NumberOfTapsRequired = 2; // Add the gesture recognizer to the view - DoubleTouchImage.AddGestureRecognizer(tapGesture); + DoubleTouchImage.AddGestureRecognizer (tapGesture); } #endregion } diff --git a/ApplicationFundamentals/Touch_final/Main.cs b/ApplicationFundamentals/Touch_final/Main.cs index 413f72f04..a394d9824 100644 --- a/ApplicationFundamentals/Touch_final/Main.cs +++ b/ApplicationFundamentals/Touch_final/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace Touch -{ - public class Application - { +namespace Touch { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ApplicationFundamentals/Touch_final/MasterViewController.cs b/ApplicationFundamentals/Touch_final/MasterViewController.cs index bba498d9d..490bf684e 100644 --- a/ApplicationFundamentals/Touch_final/MasterViewController.cs +++ b/ApplicationFundamentals/Touch_final/MasterViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Touch -{ - public partial class MasterViewController : UITableViewController - { +namespace Touch { + public partial class MasterViewController : UITableViewController { DataSource dataSource; public MasterViewController (IntPtr handle) : base (handle) @@ -23,21 +21,21 @@ void AddNewItem (object sender, EventArgs args) dataSource.Objects.Insert (0, DateTime.Now); using (var indexPath = NSIndexPath.FromRowSection (0, 0)) - TableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. NavigationItem.LeftBarButtonItem = EditButtonItem; @@ -47,8 +45,7 @@ public override void ViewDidLoad () TableView.Source = dataSource = new DataSource (this); } - class DataSource : UITableViewSource - { + class DataSource : UITableViewSource { static readonly NSString CellIdentifier = new NSString ("Cell"); readonly List objects = new List (); readonly WeakReference _controller; @@ -76,7 +73,7 @@ public override nint RowsInSection (UITableView tableview, nint section) // Customize the appearance of table view cells. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (UITableViewCell)tableView.DequeueReusableCell (CellIdentifier, indexPath); + var cell = (UITableViewCell) tableView.DequeueReusableCell (CellIdentifier, indexPath); cell.TextLabel.Text = objects [indexPath.Row].ToString (); @@ -95,7 +92,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE // Delete the row from the data source. objects.RemoveAt (indexPath.Row); if (_controller.TryGetTarget (out var controller)) - controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); + controller.TableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); } else if (editingStyle == UITableViewCellEditingStyle.Insert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } diff --git a/ApplicationFundamentals/Touch_final/TouchViewController.cs b/ApplicationFundamentals/Touch_final/TouchViewController.cs index a7891cf48..706ec6aee 100644 --- a/ApplicationFundamentals/Touch_final/TouchViewController.cs +++ b/ApplicationFundamentals/Touch_final/TouchViewController.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using CoreGraphics; -namespace Touch -{ - partial class TouchViewController : UIViewController - { +namespace Touch { + partial class TouchViewController : UIViewController { #region Private Variables private bool imageHighlighted = false; private bool touchStartedInside; @@ -20,74 +18,65 @@ public TouchViewController (IntPtr handle) : base (handle) #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); Title = "Touches"; } - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); + base.TouchesBegan (touches, evt); // If Multitouch is enabled, report the number of fingers down TouchStatus.Text = string.Format ("Number of fingers {0}", touches.Count); // Get the current touch UITouch touch = touches.AnyObject as UITouch; - if (touch != null) - { + if (touch != null) { // Check to see if any of the images have been touched - if (TouchImage.Frame.Contains(touch.LocationInView(TouchView))) - { + if (TouchImage.Frame.Contains (touch.LocationInView (TouchView))) { // Fist image touched - TouchImage.Image = UIImage.FromBundle("TouchMe_Touched.png"); + TouchImage.Image = UIImage.FromBundle ("TouchMe_Touched.png"); TouchStatus.Text = "Touches Began"; - } else if (touch.TapCount == 2 && DoubleTouchImage.Frame.Contains(touch.LocationInView(TouchView))) - { + } else if (touch.TapCount == 2 && DoubleTouchImage.Frame.Contains (touch.LocationInView (TouchView))) { // Second image double-tapped, toggle bitmap - if (imageHighlighted) - { - DoubleTouchImage.Image = UIImage.FromBundle("DoubleTapMe.png"); + if (imageHighlighted) { + DoubleTouchImage.Image = UIImage.FromBundle ("DoubleTapMe.png"); TouchStatus.Text = "Double-Tapped Off"; - } - else - { - DoubleTouchImage.Image = UIImage.FromBundle("DoubleTapMe_Highlighted.png"); + } else { + DoubleTouchImage.Image = UIImage.FromBundle ("DoubleTapMe_Highlighted.png"); TouchStatus.Text = "Double-Tapped On"; } imageHighlighted = !imageHighlighted; - } else if (DragImage.Frame.Contains(touch.LocationInView(View))) - { + } else if (DragImage.Frame.Contains (touch.LocationInView (View))) { // Third image touched, prepare to drag touchStartedInside = true; } } } - public override void TouchesCancelled(NSSet touches, UIEvent evt) + public override void TouchesCancelled (NSSet touches, UIEvent evt) { - base.TouchesCancelled(touches, evt); + base.TouchesCancelled (touches, evt); // reset our tracking flags touchStartedInside = false; - TouchImage.Image = UIImage.FromBundle("TouchMe.png"); + TouchImage.Image = UIImage.FromBundle ("TouchMe.png"); TouchStatus.Text = ""; } - public override void TouchesEnded(NSSet touches, UIEvent evt) + public override void TouchesEnded (NSSet touches, UIEvent evt) { - base.TouchesEnded(touches, evt); + base.TouchesEnded (touches, evt); // get the touch UITouch touch = touches.AnyObject as UITouch; - if (touch != null) - { + if (touch != null) { //==== IMAGE TOUCH - if (TouchImage.Frame.Contains(touch.LocationInView(TouchView))) - { - TouchImage.Image = UIImage.FromBundle("TouchMe.png"); + if (TouchImage.Frame.Contains (touch.LocationInView (TouchView))) { + TouchImage.Image = UIImage.FromBundle ("TouchMe.png"); TouchStatus.Text = "Touches Ended"; } } @@ -95,27 +84,24 @@ public override void TouchesEnded(NSSet touches, UIEvent evt) touchStartedInside = false; } - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); // get the touch UITouch touch = touches.AnyObject as UITouch; - if (touch != null) - { + if (touch != null) { //==== IMAGE TOUCH - if (TouchImage.Frame.Contains(touch.LocationInView(TouchView))) - { + if (TouchImage.Frame.Contains (touch.LocationInView (TouchView))) { TouchStatus.Text = "Touches Moved"; } //==== IMAGE DRAG // check to see if the touch started in the dragme image - if (touchStartedInside) - { + if (touchStartedInside) { // move the shape - nfloat offsetX = touch.PreviousLocationInView(View).X - touch.LocationInView(View).X; - nfloat offsetY = touch.PreviousLocationInView(View).Y - touch.LocationInView(View).Y; - DragImage.Frame = new CGRect(new CGPoint(DragImage.Frame.X - offsetX, DragImage.Frame.Y - offsetY), DragImage.Frame.Size); + nfloat offsetX = touch.PreviousLocationInView (View).X - touch.LocationInView (View).X; + nfloat offsetY = touch.PreviousLocationInView (View).Y - touch.LocationInView (View).Y; + DragImage.Frame = new CGRect (new CGPoint (DragImage.Frame.X - offsetX, DragImage.Frame.Y - offsetY), DragImage.Frame.Size); } } } diff --git a/ApplicationFundamentals/Touch_start/AppDelegate.cs b/ApplicationFundamentals/Touch_start/AppDelegate.cs index afc9f8c39..5867fc638 100644 --- a/ApplicationFundamentals/Touch_start/AppDelegate.cs +++ b/ApplicationFundamentals/Touch_start/AppDelegate.cs @@ -3,21 +3,19 @@ using Foundation; using UIKit; -namespace Touch -{ +namespace Touch { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // // This method is invoked when the application is about to move from active to inactive state. // @@ -26,19 +24,19 @@ public override UIWindow Window { public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/ApplicationFundamentals/Touch_start/Classes/CheckmarkGestureRecognizer.cs b/ApplicationFundamentals/Touch_start/Classes/CheckmarkGestureRecognizer.cs index 129a65af8..81f57a871 100644 --- a/ApplicationFundamentals/Touch_start/Classes/CheckmarkGestureRecognizer.cs +++ b/ApplicationFundamentals/Touch_start/Classes/CheckmarkGestureRecognizer.cs @@ -4,22 +4,20 @@ using Foundation; using UIKit; -namespace Touch -{ - public class CheckmarkGestureRecognizer : UIGestureRecognizer - { +namespace Touch { + public class CheckmarkGestureRecognizer : UIGestureRecognizer { #region Private Variables private CGPoint midpoint = CGPoint.Empty; private bool strokeUp = false; - #endregion + #endregion #region Override Methods /// /// Called when the touches end or the recognizer state fails /// - public override void Reset() + public override void Reset () { - base.Reset(); + base.Reset (); strokeUp = false; midpoint = CGPoint.Empty; @@ -28,25 +26,24 @@ public override void Reset() /// /// Is called when the fingers touch the screen. /// - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); + base.TouchesBegan (touches, evt); // we want one and only one finger - if (touches.Count != 1) - { + if (touches.Count != 1) { base.State = UIGestureRecognizerState.Failed; } - Console.WriteLine(base.State.ToString()); + Console.WriteLine (base.State.ToString ()); } /// /// Called when the touches are cancelled due to a phone call, etc. /// - public override void TouchesCancelled(NSSet touches, UIEvent evt) + public override void TouchesCancelled (NSSet touches, UIEvent evt) { - base.TouchesCancelled(touches, evt); + base.TouchesCancelled (touches, evt); // we fail the recognizer so that there isn't unexpected behavior // if the application comes back into view base.State = UIGestureRecognizerState.Failed; @@ -55,56 +52,50 @@ public override void TouchesCancelled(NSSet touches, UIEvent evt) /// /// Called when the fingers lift off the screen /// - public override void TouchesEnded(NSSet touches, UIEvent evt) + public override void TouchesEnded (NSSet touches, UIEvent evt) { - base.TouchesEnded(touches, evt); + base.TouchesEnded (touches, evt); // - if (base.State == UIGestureRecognizerState.Possible && strokeUp) - { + if (base.State == UIGestureRecognizerState.Possible && strokeUp) { base.State = UIGestureRecognizerState.Recognized; } - Console.WriteLine(base.State.ToString()); + Console.WriteLine (base.State.ToString ()); } /// /// Called when the fingers move /// - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); // if we haven't already failed - if (base.State != UIGestureRecognizerState.Failed) - { + if (base.State != UIGestureRecognizerState.Failed) { // get the current and previous touch point - CGPoint newPoint = (touches.AnyObject as UITouch).LocationInView(View); - CGPoint previousPoint = (touches.AnyObject as UITouch).PreviousLocationInView(View); + CGPoint newPoint = (touches.AnyObject as UITouch).LocationInView (View); + CGPoint previousPoint = (touches.AnyObject as UITouch).PreviousLocationInView (View); // if we're not already on the upstroke - if (!strokeUp) - { + if (!strokeUp) { // if we're moving down, just continue to set the midpoint at // whatever point we're at. when we start to stroke up, it'll stick // as the last point before we upticked - if (newPoint.X >= previousPoint.X && newPoint.Y >= previousPoint.Y) - { + if (newPoint.X >= previousPoint.X && newPoint.Y >= previousPoint.Y) { midpoint = newPoint; } // if we're stroking up (moving right x and up y [y axis is flipped]) - else if (newPoint.X >= previousPoint.X && newPoint.Y <= previousPoint.Y) - { + else if (newPoint.X >= previousPoint.X && newPoint.Y <= previousPoint.Y) { strokeUp = true; } // otherwise, we fail the recognizer - else - { + else { base.State = UIGestureRecognizerState.Failed; } } } - Console.WriteLine(base.State.ToString()); + Console.WriteLine (base.State.ToString ()); } #endregion } diff --git a/ApplicationFundamentals/Touch_start/CustomGestureViewController.cs b/ApplicationFundamentals/Touch_start/CustomGestureViewController.cs index 67aa5da71..58608e223 100644 --- a/ApplicationFundamentals/Touch_start/CustomGestureViewController.cs +++ b/ApplicationFundamentals/Touch_start/CustomGestureViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace Touch -{ - partial class CustomGestureViewController : UIViewController - { +namespace Touch { + partial class CustomGestureViewController : UIViewController { #region Private Variables //private bool isChecked = false; //private CheckmarkGestureRecognizer checkmarkGesture; diff --git a/ApplicationFundamentals/Touch_start/GestureViewController.cs b/ApplicationFundamentals/Touch_start/GestureViewController.cs index 99832a5a5..4be2adb6f 100644 --- a/ApplicationFundamentals/Touch_start/GestureViewController.cs +++ b/ApplicationFundamentals/Touch_start/GestureViewController.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using CoreGraphics; -namespace Touch -{ - partial class GestureViewController : UIViewController - { +namespace Touch { + partial class GestureViewController : UIViewController { #region Private Variables //private bool imageHighlighted = false; //private RectangleF originalImageFrame = RectangleF.Empty; diff --git a/ApplicationFundamentals/Touch_start/Main.cs b/ApplicationFundamentals/Touch_start/Main.cs index 413f72f04..a394d9824 100644 --- a/ApplicationFundamentals/Touch_start/Main.cs +++ b/ApplicationFundamentals/Touch_start/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace Touch -{ - public class Application - { +namespace Touch { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ApplicationFundamentals/Touch_start/MasterViewController.cs b/ApplicationFundamentals/Touch_start/MasterViewController.cs index c1e88d43f..cbd9b5620 100644 --- a/ApplicationFundamentals/Touch_start/MasterViewController.cs +++ b/ApplicationFundamentals/Touch_start/MasterViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Touch -{ - public partial class MasterViewController : UITableViewController - { +namespace Touch { + public partial class MasterViewController : UITableViewController { DataSource dataSource; public MasterViewController (IntPtr handle) : base (handle) @@ -23,21 +21,21 @@ void AddNewItem (object sender, EventArgs args) dataSource.Objects.Insert (0, DateTime.Now); using (var indexPath = NSIndexPath.FromRowSection (0, 0)) - TableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. NavigationItem.LeftBarButtonItem = EditButtonItem; @@ -47,15 +45,14 @@ public override void ViewDidLoad () TableView.Source = dataSource = new DataSource (this); } - class DataSource : UITableViewSource - { + class DataSource : UITableViewSource { static readonly NSString CellIdentifier = new NSString ("Cell"); List objects = new List (); WeakReference _controller; public DataSource (MasterViewController controller) { - _controller = new WeakReference(controller); + _controller = new WeakReference (controller); } public IList Objects { @@ -76,7 +73,7 @@ public override nint RowsInSection (UITableView tableview, nint section) // Customize the appearance of table view cells. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (UITableViewCell)tableView.DequeueReusableCell (CellIdentifier, indexPath); + var cell = (UITableViewCell) tableView.DequeueReusableCell (CellIdentifier, indexPath); cell.TextLabel.Text = objects [indexPath.Row].ToString (); @@ -95,7 +92,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE // Delete the row from the data source. objects.RemoveAt (indexPath.Row); if (_controller.TryGetTarget (out var controller)) - controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); + controller.TableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); } else if (editingStyle == UITableViewCellEditingStyle.Insert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } diff --git a/ApplicationFundamentals/Touch_start/TouchViewController.cs b/ApplicationFundamentals/Touch_start/TouchViewController.cs index faec4ed1b..dae9f8525 100644 --- a/ApplicationFundamentals/Touch_start/TouchViewController.cs +++ b/ApplicationFundamentals/Touch_start/TouchViewController.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using CoreGraphics; -namespace Touch -{ - partial class TouchViewController : UIViewController - { +namespace Touch { + partial class TouchViewController : UIViewController { #region Private Variables //private bool imageHighlighted = false; //private bool touchStartedInside; diff --git a/AsyncDownloadImage/AsyncDownloadImage/AppDelegate.cs b/AsyncDownloadImage/AsyncDownloadImage/AppDelegate.cs index f9f448dc9..a91847dc1 100644 --- a/AsyncDownloadImage/AsyncDownloadImage/AppDelegate.cs +++ b/AsyncDownloadImage/AsyncDownloadImage/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace AsyncDownloadImage -{ +namespace AsyncDownloadImage { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; AsyncDownloadImageViewController viewController; diff --git a/AsyncDownloadImage/AsyncDownloadImage/AsyncDownloadImageViewController.cs b/AsyncDownloadImage/AsyncDownloadImage/AsyncDownloadImageViewController.cs index e1318d851..1575d2443 100644 --- a/AsyncDownloadImage/AsyncDownloadImage/AsyncDownloadImageViewController.cs +++ b/AsyncDownloadImage/AsyncDownloadImage/AsyncDownloadImageViewController.cs @@ -11,10 +11,8 @@ using Foundation; using UIKit; -namespace AsyncDownloadImage -{ - public partial class AsyncDownloadImageViewController : UIViewController - { +namespace AsyncDownloadImage { + public partial class AsyncDownloadImageViewController : UIViewController { int clickNumber = 0; WebClient webClient; public AsyncDownloadImageViewController () : base ("AsyncDownloadImageViewController", null) @@ -40,7 +38,7 @@ public override void ViewDidLoad () this.clickButton.SetTitleColor (UIColor.Blue, UIControlState.Normal); this.clickButton.TouchUpInside += (sender, e) => { clickNumber++; - this.clickButton.SetTitle( "Click Me:" + clickNumber, UIControlState.Normal); + this.clickButton.SetTitle ("Click Me:" + clickNumber, UIControlState.Normal); }; this.downloadButton.TouchUpInside += downloadAsync; @@ -58,49 +56,47 @@ public override UIStatusBarStyle PreferredStatusBarStyle () return UIStatusBarStyle.Default; } - async void downloadAsync(object sender, System.EventArgs ea) + async void downloadAsync (object sender, System.EventArgs ea) { webClient = new WebClient (); //An large image url var url = new Uri ("http://photojournal.jpl.nasa.gov/jpeg/PIA15416.jpg"); - byte[] bytes = null; + byte [] bytes = null; webClient.DownloadProgressChanged += HandleDownloadProgressChanged; - this.downloadButton.SetTitle ("Cancel",UIControlState.Normal); + this.downloadButton.SetTitle ("Cancel", UIControlState.Normal); this.downloadButton.TouchUpInside -= downloadAsync; this.downloadButton.TouchUpInside += cancelDownload; infoLabel.Text = "Downloading..."; //Start download data using DownloadDataTaskAsync - try{ - bytes = await webClient.DownloadDataTaskAsync(url); - } - catch(OperationCanceledException){ + try { + bytes = await webClient.DownloadDataTaskAsync (url); + } catch (OperationCanceledException) { Console.WriteLine ("Task Canceled!"); return; - } - catch(Exception e) { - Console.WriteLine (e.ToString()); + } catch (Exception e) { + Console.WriteLine (e.ToString ()); return; } string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); string localFilename = "downloaded.png"; - string localPath = Path.Combine (documentsPath, localFilename); + string localPath = Path.Combine (documentsPath, localFilename); infoLabel.Text = "Download Complete"; //Save the image using writeAsync FileStream fs = new FileStream (localPath, FileMode.OpenOrCreate); await fs.WriteAsync (bytes, 0, bytes.Length); - Console.WriteLine("localPath:"+localPath); + Console.WriteLine ("localPath:" + localPath); //Resizing image is time costing, using async to avoid blocking the UI thread UIImage image = null; CGSize imageViewSize = imageView.Frame.Size; infoLabel.Text = "Resizing Image..."; - await Task.Run( () => { image = UIImage.FromFile(localPath).Scale(imageViewSize); } ); + await Task.Run (() => { image = UIImage.FromFile (localPath).Scale (imageViewSize); }); Console.WriteLine ("Loaded!"); imageView.Image = image; @@ -118,10 +114,10 @@ void HandleDownloadProgressChanged (object sender, DownloadProgressChangedEventA this.downloadProgress.Progress = e.ProgressPercentage / 100.0f; } - void cancelDownload(object sender, System.EventArgs ea) + void cancelDownload (object sender, System.EventArgs ea) { Console.WriteLine ("Cancel clicked!"); - if(webClient!=null) + if (webClient != null) webClient.CancelAsync (); webClient.DownloadProgressChanged -= HandleDownloadProgressChanged; @@ -132,10 +128,10 @@ void cancelDownload(object sender, System.EventArgs ea) this.downloadProgress.Progress = 0.0f; new UIAlertView ("Canceled" - , "Download has been canceled." - , null - , "OK" - , null).Show(); + , "Download has been canceled." + , null + , "OK" + , null).Show (); infoLabel.Text = "Click Dowload button to download the image"; } diff --git a/AsyncDownloadImage/AsyncDownloadImage/Main.cs b/AsyncDownloadImage/AsyncDownloadImage/Main.cs index a844a617d..881dccb32 100644 --- a/AsyncDownloadImage/AsyncDownloadImage/Main.cs +++ b/AsyncDownloadImage/AsyncDownloadImage/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace AsyncDownloadImage -{ - public class Application - { +namespace AsyncDownloadImage { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AudioConverterFileConverter/AppDelegate.cs b/AudioConverterFileConverter/AppDelegate.cs index e66304be4..fdb842688 100644 --- a/AudioConverterFileConverter/AppDelegate.cs +++ b/AudioConverterFileConverter/AppDelegate.cs @@ -34,9 +34,8 @@ using Foundation; using UIKit; -namespace AudioConverterFileConverter -{ - /* +namespace AudioConverterFileConverter { + /* Since we perform conversion in a background thread, we must ensure that we handle interruptions appropriately. In this sample we're using a mutex protected variable tracking thread states. The background conversion threads state transistions from Done to Running to Done unless we've been interrupted in which case we are Paused blocking the conversion thread and preventing further calls @@ -45,169 +44,154 @@ namespace AudioConverterFileConverter Any errors returned from AudioConverterFillComplexBuffer must be handled appropriately. Additionally, if the Audio Converter cannot resume conversion after an interruption, you should not call AudioConverterFillComplexBuffer again. */ - public enum State - { - Running, - Paused, - Done - } - - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - static State State = State.Done; - static AutoResetEvent StateChanged = new AutoResetEvent(false); - static readonly object StateLock = new object(); - - private AVAudioSession session; - - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - // - // This method is invoked when the application has loaded and is ready to run. In this - // method you should instantiate the window, load the UI into it and then make the window - // visible. - // - // You have 17 seconds to return from this method, or iOS will terminate your application. - // - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - session = AVAudioSession.SharedInstance(); - session.BeginInterruption += delegate - { - Debug.WriteLine("Session interrupted"); - ThreadStateBeginInterruption(); - }; - session.EndInterruption += (object sender, EventArgs e) => - { - Debug.WriteLine("Session resumed"); - session.SetActive(true); - ThreadStateEndInterruption(); - }; - - int routes = (int)session.InputNumberOfChannels; - - // our default category -- we change this for conversion and playback appropriately - try - { - session.SetCategory (AVAudioSessionCategory.SoloAmbient); - } - catch - { - Debug.Print("ERROR: Cannot change audio session category"); - } - - session.InputAvailabilityChanged += (object sender, AVStatusEventArgs e) => - { - var sess = sender as AVAudioSession; - Debug.Print("Old route: {0}", routes); - Debug.Print("New route: {0}", sess.InputNumberOfChannels); - routes = (int)sess.InputNumberOfChannels; - }; - - session.SetActive(true); - return true; - } - - // This method is invoked when the application is about to move from active to inactive state. - // OpenGL applications should use this method to pause. - public override void OnResignActivation(UIApplication application) - { - ThreadStateBeginInterruption(); - session.SetActive(false); - Debug.Write("Audio Session Deactivated"); - } - - // This method should be used to release shared resources and it should store the application state. - // If your application supports background exection this method is called instead of WillTerminate - // when the user quits. - public override void DidEnterBackground(UIApplication application) - { - } - - /// This method is called as part of the transiton from background to active state. - public override void WillEnterForeground(UIApplication application) - { - } - - /// This method is called when the application is about to terminate. Save data, if needed. - public override void WillTerminate(UIApplication application) - { - } - - static void ThreadStateBeginInterruption() - { - Debug.Assert(NSThread.IsMain); - - lock (StateLock) - { - State = State.Paused; - } - } - - static void ThreadStateEndInterruption() - { - Debug.Assert(NSThread.IsMain); - - lock (StateLock) - { - if (State == State.Paused) - { - State = State.Running; - - StateChanged.Set(); - } - } - } - - public static void ThreadStateSetRunning() - { - lock (StateLock) - { - Debug.Assert(State == State.Done); - State = State.Running; - } - } - - // block for state change to State.Running - public static bool ThreadStatePausedCheck() - { - var wasInterrupted = false; - - lock (StateLock) - { - Debug.Assert(State != State.Done); - - while (State == State.Paused) - { - StateChanged.WaitOne(); - wasInterrupted = true; - } - - // we must be running or something bad has happened - Debug.Assert(State == State.Running); - } - - return wasInterrupted; - } - - public static void ThreadStateSetDone() - { - lock (StateLock) - { - Debug.Assert(State != State.Done); - State = State.Done; - } - } - } + public enum State { + Running, + Paused, + Done + } + + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + static State State = State.Done; + static AutoResetEvent StateChanged = new AutoResetEvent (false); + static readonly object StateLock = new object (); + + private AVAudioSession session; + + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + session = AVAudioSession.SharedInstance (); + session.BeginInterruption += delegate + { + Debug.WriteLine ("Session interrupted"); + ThreadStateBeginInterruption (); + }; + session.EndInterruption += (object sender, EventArgs e) => { + Debug.WriteLine ("Session resumed"); + session.SetActive (true); + ThreadStateEndInterruption (); + }; + + int routes = (int) session.InputNumberOfChannels; + + // our default category -- we change this for conversion and playback appropriately + try { + session.SetCategory (AVAudioSessionCategory.SoloAmbient); + } catch { + Debug.Print ("ERROR: Cannot change audio session category"); + } + + session.InputAvailabilityChanged += (object sender, AVStatusEventArgs e) => { + var sess = sender as AVAudioSession; + Debug.Print ("Old route: {0}", routes); + Debug.Print ("New route: {0}", sess.InputNumberOfChannels); + routes = (int) sess.InputNumberOfChannels; + }; + + session.SetActive (true); + return true; + } + + // This method is invoked when the application is about to move from active to inactive state. + // OpenGL applications should use this method to pause. + public override void OnResignActivation (UIApplication application) + { + ThreadStateBeginInterruption (); + session.SetActive (false); + Debug.Write ("Audio Session Deactivated"); + } + + // This method should be used to release shared resources and it should store the application state. + // If your application supports background exection this method is called instead of WillTerminate + // when the user quits. + public override void DidEnterBackground (UIApplication application) + { + } + + /// This method is called as part of the transiton from background to active state. + public override void WillEnterForeground (UIApplication application) + { + } + + /// This method is called when the application is about to terminate. Save data, if needed. + public override void WillTerminate (UIApplication application) + { + } + + static void ThreadStateBeginInterruption () + { + Debug.Assert (NSThread.IsMain); + + lock (StateLock) { + State = State.Paused; + } + } + + static void ThreadStateEndInterruption () + { + Debug.Assert (NSThread.IsMain); + + lock (StateLock) { + if (State == State.Paused) { + State = State.Running; + + StateChanged.Set (); + } + } + } + + public static void ThreadStateSetRunning () + { + lock (StateLock) { + Debug.Assert (State == State.Done); + State = State.Running; + } + } + + // block for state change to State.Running + public static bool ThreadStatePausedCheck () + { + var wasInterrupted = false; + + lock (StateLock) { + Debug.Assert (State != State.Done); + + while (State == State.Paused) { + StateChanged.WaitOne (); + wasInterrupted = true; + } + + // we must be running or something bad has happened + Debug.Assert (State == State.Running); + } + + return wasInterrupted; + } + + public static void ThreadStateSetDone () + { + lock (StateLock) { + Debug.Assert (State != State.Done); + State = State.Done; + } + } + } } diff --git a/AudioConverterFileConverter/AudioConverterFileConverterViewController.cs b/AudioConverterFileConverter/AudioConverterFileConverterViewController.cs index 4713e8f97..b3b1f06f6 100644 --- a/AudioConverterFileConverter/AudioConverterFileConverterViewController.cs +++ b/AudioConverterFileConverter/AudioConverterFileConverterViewController.cs @@ -38,670 +38,622 @@ using AVFoundation; using System.Runtime.InteropServices; -namespace AudioConverterFileConverter -{ - public partial class AudioConverterFileConverterViewController : UIViewController - { - class AudioFileIO - { - public AudioFileIO(int bufferSize) - { - this.SrcBufferSize = bufferSize; - this.SrcBuffer = Marshal.AllocHGlobal(bufferSize); - } - - ~AudioFileIO () - { - Marshal.FreeHGlobal(SrcBuffer); - } - - public AudioFile SourceFile { get; set; } - - public int SrcBufferSize { get; private set; } - - public IntPtr SrcBuffer { get; private set; } - - public int SrcFilePos { get; set; } - - public AudioStreamBasicDescription SrcFormat { get; set; } - - public int SrcSizePerPacket { get; set; } - - public int NumPacketsPerRead { get; set; } - - public AudioStreamPacketDescription[] PacketDescriptions { get; set; } - } - - AudioFormatType outputFormat; - double sampleRate; - CFUrl sourceURL; - NSUrl destinationURL; - string destinationFilePath; - AudioFileIO afio; - - public AudioConverterFileConverterViewController(IntPtr handle) : base(handle) - { - } - - public override void DidReceiveMemoryWarning() - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning(); - - // Release any cached data, images, etc that aren't in use. - } - - #region View lifecycle - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - UIImage greenImage = new UIImage("green_button.png").StretchableImage(12, 0); - UIImage redImage = new UIImage("red_button.png").StretchableImage(12, 0); - - startButton.SetBackgroundImage(greenImage, UIControlState.Normal); - startButton.SetBackgroundImage(redImage, UIControlState.Disabled); - - // default output format - // sample rate of 0 indicates source file sample rate - outputFormat = AudioFormatType.AppleLossless; - sampleRate = 0; - - // can we encode to AAC? - if (IsAACHardwareEncoderAvailable()) - { - outputFormatSelector.SetEnabled(true, 0); - } - else - { - // even though not enabled in IB, this segment will still be enabled - // if not specifically turned off here which we'll assume is a bug - outputFormatSelector.SetEnabled(false, 0); - } - - sourceURL = CFUrl.FromFile("sourcePCM.aif"); - var paths = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); - destinationFilePath = paths[0] + "/output.caf"; - destinationURL = NSUrl.FromFilename(destinationFilePath); - - UpdateFormatInfo(fileInfo, sourceURL); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - } - - public override void ViewWillDisappear(bool animated) - { - base.ViewWillDisappear(animated); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - } - - #endregion - - public override bool ShouldAutorotateToInterfaceOrientation(UIInterfaceOrientation toInterfaceOrientation) - { - // Return true for supported orientations - return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); - } - - partial void segmentedControllerValueChanged(UISegmentedControl sender) - { - switch (sender.Tag) - { - case 0: - switch (sender.SelectedSegment) - { - case 0: - outputFormat = AudioFormatType.MPEG4AAC; - outputSampleRateSelector.SetEnabled(true, 0); - outputSampleRateSelector.SetEnabled(true, 1); - outputSampleRateSelector.SetEnabled(true, 2); - outputSampleRateSelector.SetEnabled(true, 3); - break; - case 1: - outputFormat = AudioFormatType.AppleIMA4; - outputSampleRateSelector.SetEnabled(true, 0); - outputSampleRateSelector.SetEnabled(true, 1); - outputSampleRateSelector.SetEnabled(true, 2); - outputSampleRateSelector.SetEnabled(true, 3); - break; - case 2: +namespace AudioConverterFileConverter { + public partial class AudioConverterFileConverterViewController : UIViewController { + class AudioFileIO { + public AudioFileIO (int bufferSize) + { + this.SrcBufferSize = bufferSize; + this.SrcBuffer = Marshal.AllocHGlobal (bufferSize); + } + + ~AudioFileIO () + { + Marshal.FreeHGlobal (SrcBuffer); + } + + public AudioFile SourceFile { get; set; } + + public int SrcBufferSize { get; private set; } + + public IntPtr SrcBuffer { get; private set; } + + public int SrcFilePos { get; set; } + + public AudioStreamBasicDescription SrcFormat { get; set; } + + public int SrcSizePerPacket { get; set; } + + public int NumPacketsPerRead { get; set; } + + public AudioStreamPacketDescription [] PacketDescriptions { get; set; } + } + + AudioFormatType outputFormat; + double sampleRate; + CFUrl sourceURL; + NSUrl destinationURL; + string destinationFilePath; + AudioFileIO afio; + + public AudioConverterFileConverterViewController (IntPtr handle) : base (handle) + { + } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + #region View lifecycle + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + UIImage greenImage = new UIImage ("green_button.png").StretchableImage (12, 0); + UIImage redImage = new UIImage ("red_button.png").StretchableImage (12, 0); + + startButton.SetBackgroundImage (greenImage, UIControlState.Normal); + startButton.SetBackgroundImage (redImage, UIControlState.Disabled); + + // default output format + // sample rate of 0 indicates source file sample rate + outputFormat = AudioFormatType.AppleLossless; + sampleRate = 0; + + // can we encode to AAC? + if (IsAACHardwareEncoderAvailable ()) { + outputFormatSelector.SetEnabled (true, 0); + } else { + // even though not enabled in IB, this segment will still be enabled + // if not specifically turned off here which we'll assume is a bug + outputFormatSelector.SetEnabled (false, 0); + } + + sourceURL = CFUrl.FromFile ("sourcePCM.aif"); + var paths = NSSearchPath.GetDirectories (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User); + destinationFilePath = paths [0] + "/output.caf"; + destinationURL = NSUrl.FromFilename (destinationFilePath); + + UpdateFormatInfo (fileInfo, sourceURL); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + } + + #endregion + + public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) + { + // Return true for supported orientations + return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); + } + + partial void segmentedControllerValueChanged (UISegmentedControl sender) + { + switch (sender.Tag) { + case 0: + switch (sender.SelectedSegment) { + case 0: + outputFormat = AudioFormatType.MPEG4AAC; + outputSampleRateSelector.SetEnabled (true, 0); + outputSampleRateSelector.SetEnabled (true, 1); + outputSampleRateSelector.SetEnabled (true, 2); + outputSampleRateSelector.SetEnabled (true, 3); + break; + case 1: + outputFormat = AudioFormatType.AppleIMA4; + outputSampleRateSelector.SetEnabled (true, 0); + outputSampleRateSelector.SetEnabled (true, 1); + outputSampleRateSelector.SetEnabled (true, 2); + outputSampleRateSelector.SetEnabled (true, 3); + break; + case 2: // iLBC sample rate is 8K - outputFormat = AudioFormatType.iLBC; - sampleRate = 8000.0; - outputSampleRateSelector.SelectedSegment = 2; - outputSampleRateSelector.SetEnabled(false, 0); - outputSampleRateSelector.SetEnabled(false, 1); - outputSampleRateSelector.SetEnabled(true, 2); - outputSampleRateSelector.SetEnabled(false, 3); - break; - case 3: - outputFormat = AudioFormatType.AppleLossless; - outputSampleRateSelector.SetEnabled(true, 0); - outputSampleRateSelector.SetEnabled(true, 1); - outputSampleRateSelector.SetEnabled(true, 2); - outputSampleRateSelector.SetEnabled(true, 3); - break; - } - break; - case 1: - switch (sender.SelectedSegment) - { - case 0: - sampleRate = 44100.0; - break; - case 1: - sampleRate = 22050.0; - break; - case 2: - sampleRate = 8000.0; - break; - case 3: - sampleRate = 0; - break; - } - break; - } - } - - partial void convertButtonPressed(NSObject sender) - { - // use AudioSessionCategory::AudioProcessing category for offline conversion when not playing or recording audio at the same time - // if you are recording or playing audio at the same time you are encoding, use the same Audio Session category that you would normally - - try - { - AudioSession.Category = AudioSessionCategory.AudioProcessing; - } - catch - { - Debug.Print("Cannot set audio session category"); - } - - startButton.SetTitle("Converting...", UIControlState.Disabled); - startButton.Enabled = false; - - activityIndicator.StartAnimating(); - - // run audio file code in a background thread - InvokeInBackground(ConvertAudio); - } - - static bool IsAACHardwareEncoderAvailable() - { - AudioClassDescription[] encoders = AudioFormatAvailability.GetEncoders(AudioFormatType.MPEG4AAC); - return encoders.Any(l => l.SubType == AudioFormatType.MPEG4AAC); - } - - static void UpdateFormatInfo(UILabel label, NSUrl fileURL) - { - UpdateFormatInfo(label, AudioFile.Open(fileURL, AudioFilePermission.Read), System.IO.Path.GetFileName(fileURL.Path)); - } - - static void UpdateFormatInfo(UILabel label, CFUrl fileURL) - { - UpdateFormatInfo(label, AudioFile.Open(fileURL, AudioFilePermission.Read), fileURL.FileSystemPath); - } - - static void UpdateFormatInfo(UILabel label, AudioFile fileID, string fileName) - { - var asbd = fileID.DataFormat.Value; - label.Text = string.Format("{0} {1} {2} Hz ({3} ch.)", - fileName, asbd.Format, asbd.SampleRate, asbd.ChannelsPerFrame); - } - - void UpdateUI() - { - startButton.Enabled = true; - UpdateFormatInfo(fileInfo, sourceURL); - } - - void ConvertAudio() - { - var success = DoConvertFile(sourceURL, destinationURL, outputFormat, sampleRate); - - BeginInvokeOnMainThread(delegate - { - activityIndicator.StopAnimating(); - }); - - if (!success) - { - var fm = new NSFileManager(); - if (fm.FileExists(destinationFilePath)) - { - NSError error; - fm.Remove(destinationFilePath, out error); - } - BeginInvokeOnMainThread(UpdateUI); - } - else - { - BeginInvokeOnMainThread(playAudio); - } - } - - bool DoConvertFile(CFUrl sourceURL, NSUrl destinationURL, AudioFormatType outputFormatType, double outputSampleRate) - { - // in this sample we should never be on the main thread here - Debug.Assert(!NSThread.IsMain); - - // transition thread state to State::Running before continuing - AppDelegate.ThreadStateSetRunning(); - - Debug.WriteLine("DoConvertFile"); - - // get the source file - AudioFile sourceFile = AudioFile.Open(sourceURL, AudioFilePermission.Read); - - var srcFormat = (AudioStreamBasicDescription)sourceFile.DataFormat; - var dstFormat = new AudioStreamBasicDescription(); - - // setup the output file format - dstFormat.SampleRate = (outputSampleRate == 0 ? srcFormat.SampleRate : outputSampleRate); // set sample rate - if (outputFormatType == AudioFormatType.LinearPCM) - { - // if the output format is PCM create a 16-bit int PCM file format description as an example + outputFormat = AudioFormatType.iLBC; + sampleRate = 8000.0; + outputSampleRateSelector.SelectedSegment = 2; + outputSampleRateSelector.SetEnabled (false, 0); + outputSampleRateSelector.SetEnabled (false, 1); + outputSampleRateSelector.SetEnabled (true, 2); + outputSampleRateSelector.SetEnabled (false, 3); + break; + case 3: + outputFormat = AudioFormatType.AppleLossless; + outputSampleRateSelector.SetEnabled (true, 0); + outputSampleRateSelector.SetEnabled (true, 1); + outputSampleRateSelector.SetEnabled (true, 2); + outputSampleRateSelector.SetEnabled (true, 3); + break; + } + break; + case 1: + switch (sender.SelectedSegment) { + case 0: + sampleRate = 44100.0; + break; + case 1: + sampleRate = 22050.0; + break; + case 2: + sampleRate = 8000.0; + break; + case 3: + sampleRate = 0; + break; + } + break; + } + } + + partial void convertButtonPressed (NSObject sender) + { + // use AudioSessionCategory::AudioProcessing category for offline conversion when not playing or recording audio at the same time + // if you are recording or playing audio at the same time you are encoding, use the same Audio Session category that you would normally + + try { + AudioSession.Category = AudioSessionCategory.AudioProcessing; + } catch { + Debug.Print ("Cannot set audio session category"); + } + + startButton.SetTitle ("Converting...", UIControlState.Disabled); + startButton.Enabled = false; + + activityIndicator.StartAnimating (); + + // run audio file code in a background thread + InvokeInBackground (ConvertAudio); + } + + static bool IsAACHardwareEncoderAvailable () + { + AudioClassDescription [] encoders = AudioFormatAvailability.GetEncoders (AudioFormatType.MPEG4AAC); + return encoders.Any (l => l.SubType == AudioFormatType.MPEG4AAC); + } + + static void UpdateFormatInfo (UILabel label, NSUrl fileURL) + { + UpdateFormatInfo (label, AudioFile.Open (fileURL, AudioFilePermission.Read), System.IO.Path.GetFileName (fileURL.Path)); + } + + static void UpdateFormatInfo (UILabel label, CFUrl fileURL) + { + UpdateFormatInfo (label, AudioFile.Open (fileURL, AudioFilePermission.Read), fileURL.FileSystemPath); + } + + static void UpdateFormatInfo (UILabel label, AudioFile fileID, string fileName) + { + var asbd = fileID.DataFormat.Value; + label.Text = string.Format ("{0} {1} {2} Hz ({3} ch.)", + fileName, asbd.Format, asbd.SampleRate, asbd.ChannelsPerFrame); + } + + void UpdateUI () + { + startButton.Enabled = true; + UpdateFormatInfo (fileInfo, sourceURL); + } + + void ConvertAudio () + { + var success = DoConvertFile (sourceURL, destinationURL, outputFormat, sampleRate); + + BeginInvokeOnMainThread (delegate + { + activityIndicator.StopAnimating (); + }); + + if (!success) { + var fm = new NSFileManager (); + if (fm.FileExists (destinationFilePath)) { + NSError error; + fm.Remove (destinationFilePath, out error); + } + BeginInvokeOnMainThread (UpdateUI); + } else { + BeginInvokeOnMainThread (playAudio); + } + } + + bool DoConvertFile (CFUrl sourceURL, NSUrl destinationURL, AudioFormatType outputFormatType, double outputSampleRate) + { + // in this sample we should never be on the main thread here + Debug.Assert (!NSThread.IsMain); + + // transition thread state to State::Running before continuing + AppDelegate.ThreadStateSetRunning (); + + Debug.WriteLine ("DoConvertFile"); + + // get the source file + AudioFile sourceFile = AudioFile.Open (sourceURL, AudioFilePermission.Read); + + var srcFormat = (AudioStreamBasicDescription) sourceFile.DataFormat; + var dstFormat = new AudioStreamBasicDescription (); + + // setup the output file format + dstFormat.SampleRate = (outputSampleRate == 0 ? srcFormat.SampleRate : outputSampleRate); // set sample rate + if (outputFormatType == AudioFormatType.LinearPCM) { + // if the output format is PCM create a 16-bit int PCM file format description as an example dstFormat.Format = AudioFormatType.LinearPCM; - dstFormat.ChannelsPerFrame = srcFormat.ChannelsPerFrame; - dstFormat.BitsPerChannel = 16; - dstFormat.BytesPerPacket = dstFormat.BytesPerFrame = 2 * dstFormat.ChannelsPerFrame; - dstFormat.FramesPerPacket = 1; - dstFormat.FormatFlags = AudioFormatFlags.LinearPCMIsPacked | AudioFormatFlags.LinearPCMIsSignedInteger; - } - else - { - // compressed format - need to set at least format, sample rate and channel fields for kAudioFormatProperty_FormatInfo - dstFormat.Format = outputFormatType; - dstFormat.ChannelsPerFrame = (outputFormatType == AudioFormatType.iLBC ? 1 : srcFormat.ChannelsPerFrame); // for iLBC num channels must be 1 - - // use AudioFormat API to fill out the rest of the description - AudioFormatError afe = AudioStreamBasicDescription.GetFormatInfo(ref dstFormat); - if (afe != AudioFormatError.None) - { - Debug.Print("Cannot create destination format {0:x}", afe); - - AppDelegate.ThreadStateSetDone(); - return false; - } - } - - // create the AudioConverter - AudioConverterError ce; - var converter = AudioConverter.Create(srcFormat, dstFormat, out ce); - Debug.Assert(ce == AudioConverterError.None); - - converter.InputData += EncoderDataProc; - - // if the source has a cookie, get it and set it on the Audio Converter - ReadCookie(sourceFile, converter); - - // get the actual formats back from the Audio Converter - srcFormat = converter.CurrentInputStreamDescription; - dstFormat = converter.CurrentOutputStreamDescription; - - // if encoding to AAC set the bitrate to 192k which is a nice value for this demo - // kAudioConverterEncodeBitRate is a UInt32 value containing the number of bits per second to aim for when encoding data - if (dstFormat.Format == AudioFormatType.MPEG4AAC) - { - uint outputBitRate = 192000; // 192k - - // ignore errors as setting may be invalid depending on format specifics such as samplerate - try - { - converter.EncodeBitRate = outputBitRate; - } - catch - { - } - - // get it back and print it out - outputBitRate = converter.EncodeBitRate; - Debug.Print("AAC Encode Bitrate: {0}", outputBitRate); - } - - // can the Audio Converter resume conversion after an interruption? - // this property may be queried at any time after construction of the Audio Converter after setting its output format - // there's no clear reason to prefer construction time, interruption time, or potential resumption time but we prefer - // construction time since it means less code to execute during or after interruption time - bool canResumeFromInterruption; - try - { - canResumeFromInterruption = converter.CanResumeFromInterruption; - Debug.Print("Audio Converter {0} continue after interruption!", canResumeFromInterruption ? "CAN" : "CANNOT"); - } - catch (Exception e) - { - // if the property is unimplemented (kAudioConverterErr_PropertyNotSupported, or paramErr returned in the case of PCM), - // then the codec being used is not a hardware codec so we're not concerned about codec state - // we are always going to be able to resume conversion after an interruption - - canResumeFromInterruption = false; - Debug.Print("CanResumeFromInterruption: {0}", e.Message); - } - - // create the destination file - var destinationFile = AudioFile.Create(destinationURL, AudioFileType.CAF, dstFormat, AudioFileFlags.EraseFlags); - - // set up source buffers and data proc info struct - afio = new AudioFileIO(32 * 1024); // 32Kb - afio.SourceFile = sourceFile; - afio.SrcFormat = srcFormat; - - if (srcFormat.BytesPerPacket == 0) - { - // if the source format is VBR, we need to get the maximum packet size - // use kAudioFilePropertyPacketSizeUpperBound which returns the theoretical maximum packet size - // in the file (without actually scanning the whole file to find the largest packet, - // as may happen with kAudioFilePropertyMaximumPacketSize) - afio.SrcSizePerPacket = sourceFile.PacketSizeUpperBound; - - // how many packets can we read for our buffer size? - afio.NumPacketsPerRead = afio.SrcBufferSize / afio.SrcSizePerPacket; - - // allocate memory for the PacketDescription structures describing the layout of each packet - afio.PacketDescriptions = new AudioStreamPacketDescription [afio.NumPacketsPerRead]; - } - else - { - // CBR source format - afio.SrcSizePerPacket = srcFormat.BytesPerPacket; - afio.NumPacketsPerRead = afio.SrcBufferSize / afio.SrcSizePerPacket; - } - - // set up output buffers - int outputSizePerPacket = dstFormat.BytesPerPacket; // this will be non-zero if the format is CBR - const int theOutputBufSize = 32 * 1024; // 32Kb - var outputBuffer = Marshal.AllocHGlobal(theOutputBufSize); - AudioStreamPacketDescription[] outputPacketDescriptions = null; - - if (outputSizePerPacket == 0) - { - // if the destination format is VBR, we need to get max size per packet from the converter - outputSizePerPacket = (int)converter.MaximumOutputPacketSize; - - // allocate memory for the PacketDescription structures describing the layout of each packet - outputPacketDescriptions = new AudioStreamPacketDescription [theOutputBufSize / outputSizePerPacket]; - } - int numOutputPackets = theOutputBufSize / outputSizePerPacket; - - // if the destination format has a cookie, get it and set it on the output file - WriteCookie(converter, destinationFile); - - // write destination channel layout - if (srcFormat.ChannelsPerFrame > 2) - { - WriteDestinationChannelLayout(converter, sourceFile, destinationFile); - } - - long totalOutputFrames = 0; // used for debugging - long outputFilePos = 0; - AudioBuffers fillBufList = new AudioBuffers(1); - bool error = false; - - // loop to convert data - Debug.WriteLine("Converting..."); - while (true) - { - // set up output buffer list - fillBufList[0] = new AudioBuffer() - { - NumberChannels = dstFormat.ChannelsPerFrame, - DataByteSize = theOutputBufSize, - Data = outputBuffer - }; - - // this will block if we're interrupted - var wasInterrupted = AppDelegate.ThreadStatePausedCheck(); - - if (wasInterrupted && !canResumeFromInterruption) - { - // this is our interruption termination condition - // an interruption has occured but the Audio Converter cannot continue - Debug.WriteLine("Cannot resume from interruption"); - error = true; - break; - } - - // convert data - int ioOutputDataPackets = numOutputPackets; - var fe = converter.FillComplexBuffer(ref ioOutputDataPackets, fillBufList, outputPacketDescriptions); - // if interrupted in the process of the conversion call, we must handle the error appropriately - if (fe != AudioConverterError.None) - { - Debug.Print("FillComplexBuffer: {0}", fe); - error = true; - break; - } - - if (ioOutputDataPackets == 0) - { - // this is the EOF conditon - break; - } - - // write to output file - var inNumBytes = fillBufList[0].DataByteSize; - - var we = destinationFile.WritePackets(false, inNumBytes, outputPacketDescriptions, outputFilePos, ref ioOutputDataPackets, outputBuffer); - if (we != 0) - { - Debug.Print("WritePackets: {0}", we); - error = true; - break; - } - - // advance output file packet position - outputFilePos += ioOutputDataPackets; - - if (dstFormat.FramesPerPacket != 0) - { - // the format has constant frames per packet - totalOutputFrames += (ioOutputDataPackets * dstFormat.FramesPerPacket); - } - else - { - // variable frames per packet require doing this for each packet (adding up the number of sample frames of data in each packet) - for (var i = 0; i < ioOutputDataPackets; ++i) - totalOutputFrames += outputPacketDescriptions[i].VariableFramesInPacket; - } - - } - - Marshal.FreeHGlobal(outputBuffer); - - if (!error) - { - // write out any of the leading and trailing frames for compressed formats only - if (dstFormat.BitsPerChannel == 0) - { - // our output frame count should jive with - Debug.Print("Total number of output frames counted: {0}", totalOutputFrames); - WritePacketTableInfo(converter, destinationFile); - } - - // write the cookie again - sometimes codecs will update cookies at the end of a conversion - WriteCookie(converter, destinationFile); - } - - converter.Dispose(); - destinationFile.Dispose(); - sourceFile.Dispose(); - - // transition thread state to State.Done before continuing - AppDelegate.ThreadStateSetDone(); - - return !error; - } - - // Input data proc callback - AudioConverterError EncoderDataProc(ref int numberDataPackets, AudioBuffers data, ref AudioStreamPacketDescription[] dataPacketDescription) - { - // figure out how much to read - int maxPackets = afio.SrcBufferSize / afio.SrcSizePerPacket; - if (numberDataPackets > maxPackets) - numberDataPackets = maxPackets; - - // read from the file - int outNumBytes = 16384; - - // modified for iOS7 (ReadPackets depricated) - afio.PacketDescriptions = afio.SourceFile.ReadPacketData(false, afio.SrcFilePos, ref numberDataPackets, afio.SrcBuffer, ref outNumBytes); + dstFormat.ChannelsPerFrame = srcFormat.ChannelsPerFrame; + dstFormat.BitsPerChannel = 16; + dstFormat.BytesPerPacket = dstFormat.BytesPerFrame = 2 * dstFormat.ChannelsPerFrame; + dstFormat.FramesPerPacket = 1; + dstFormat.FormatFlags = AudioFormatFlags.LinearPCMIsPacked | AudioFormatFlags.LinearPCMIsSignedInteger; + } else { + // compressed format - need to set at least format, sample rate and channel fields for kAudioFormatProperty_FormatInfo + dstFormat.Format = outputFormatType; + dstFormat.ChannelsPerFrame = (outputFormatType == AudioFormatType.iLBC ? 1 : srcFormat.ChannelsPerFrame); // for iLBC num channels must be 1 + + // use AudioFormat API to fill out the rest of the description + AudioFormatError afe = AudioStreamBasicDescription.GetFormatInfo (ref dstFormat); + if (afe != AudioFormatError.None) { + Debug.Print ("Cannot create destination format {0:x}", afe); + + AppDelegate.ThreadStateSetDone (); + return false; + } + } + + // create the AudioConverter + AudioConverterError ce; + var converter = AudioConverter.Create (srcFormat, dstFormat, out ce); + Debug.Assert (ce == AudioConverterError.None); + + converter.InputData += EncoderDataProc; + + // if the source has a cookie, get it and set it on the Audio Converter + ReadCookie (sourceFile, converter); + + // get the actual formats back from the Audio Converter + srcFormat = converter.CurrentInputStreamDescription; + dstFormat = converter.CurrentOutputStreamDescription; + + // if encoding to AAC set the bitrate to 192k which is a nice value for this demo + // kAudioConverterEncodeBitRate is a UInt32 value containing the number of bits per second to aim for when encoding data + if (dstFormat.Format == AudioFormatType.MPEG4AAC) { + uint outputBitRate = 192000; // 192k + + // ignore errors as setting may be invalid depending on format specifics such as samplerate + try { + converter.EncodeBitRate = outputBitRate; + } catch { + } + + // get it back and print it out + outputBitRate = converter.EncodeBitRate; + Debug.Print ("AAC Encode Bitrate: {0}", outputBitRate); + } + + // can the Audio Converter resume conversion after an interruption? + // this property may be queried at any time after construction of the Audio Converter after setting its output format + // there's no clear reason to prefer construction time, interruption time, or potential resumption time but we prefer + // construction time since it means less code to execute during or after interruption time + bool canResumeFromInterruption; + try { + canResumeFromInterruption = converter.CanResumeFromInterruption; + Debug.Print ("Audio Converter {0} continue after interruption!", canResumeFromInterruption ? "CAN" : "CANNOT"); + } catch (Exception e) { + // if the property is unimplemented (kAudioConverterErr_PropertyNotSupported, or paramErr returned in the case of PCM), + // then the codec being used is not a hardware codec so we're not concerned about codec state + // we are always going to be able to resume conversion after an interruption + + canResumeFromInterruption = false; + Debug.Print ("CanResumeFromInterruption: {0}", e.Message); + } + + // create the destination file + var destinationFile = AudioFile.Create (destinationURL, AudioFileType.CAF, dstFormat, AudioFileFlags.EraseFlags); + + // set up source buffers and data proc info struct + afio = new AudioFileIO (32 * 1024); // 32Kb + afio.SourceFile = sourceFile; + afio.SrcFormat = srcFormat; + + if (srcFormat.BytesPerPacket == 0) { + // if the source format is VBR, we need to get the maximum packet size + // use kAudioFilePropertyPacketSizeUpperBound which returns the theoretical maximum packet size + // in the file (without actually scanning the whole file to find the largest packet, + // as may happen with kAudioFilePropertyMaximumPacketSize) + afio.SrcSizePerPacket = sourceFile.PacketSizeUpperBound; + + // how many packets can we read for our buffer size? + afio.NumPacketsPerRead = afio.SrcBufferSize / afio.SrcSizePerPacket; + + // allocate memory for the PacketDescription structures describing the layout of each packet + afio.PacketDescriptions = new AudioStreamPacketDescription [afio.NumPacketsPerRead]; + } else { + // CBR source format + afio.SrcSizePerPacket = srcFormat.BytesPerPacket; + afio.NumPacketsPerRead = afio.SrcBufferSize / afio.SrcSizePerPacket; + } + + // set up output buffers + int outputSizePerPacket = dstFormat.BytesPerPacket; // this will be non-zero if the format is CBR + const int theOutputBufSize = 32 * 1024; // 32Kb + var outputBuffer = Marshal.AllocHGlobal (theOutputBufSize); + AudioStreamPacketDescription [] outputPacketDescriptions = null; + + if (outputSizePerPacket == 0) { + // if the destination format is VBR, we need to get max size per packet from the converter + outputSizePerPacket = (int) converter.MaximumOutputPacketSize; + + // allocate memory for the PacketDescription structures describing the layout of each packet + outputPacketDescriptions = new AudioStreamPacketDescription [theOutputBufSize / outputSizePerPacket]; + } + int numOutputPackets = theOutputBufSize / outputSizePerPacket; + + // if the destination format has a cookie, get it and set it on the output file + WriteCookie (converter, destinationFile); + + // write destination channel layout + if (srcFormat.ChannelsPerFrame > 2) { + WriteDestinationChannelLayout (converter, sourceFile, destinationFile); + } + + long totalOutputFrames = 0; // used for debugging + long outputFilePos = 0; + AudioBuffers fillBufList = new AudioBuffers (1); + bool error = false; + + // loop to convert data + Debug.WriteLine ("Converting..."); + while (true) { + // set up output buffer list + fillBufList [0] = new AudioBuffer () { + NumberChannels = dstFormat.ChannelsPerFrame, + DataByteSize = theOutputBufSize, + Data = outputBuffer + }; + + // this will block if we're interrupted + var wasInterrupted = AppDelegate.ThreadStatePausedCheck (); + + if (wasInterrupted && !canResumeFromInterruption) { + // this is our interruption termination condition + // an interruption has occured but the Audio Converter cannot continue + Debug.WriteLine ("Cannot resume from interruption"); + error = true; + break; + } + + // convert data + int ioOutputDataPackets = numOutputPackets; + var fe = converter.FillComplexBuffer (ref ioOutputDataPackets, fillBufList, outputPacketDescriptions); + // if interrupted in the process of the conversion call, we must handle the error appropriately + if (fe != AudioConverterError.None) { + Debug.Print ("FillComplexBuffer: {0}", fe); + error = true; + break; + } + + if (ioOutputDataPackets == 0) { + // this is the EOF conditon + break; + } + + // write to output file + var inNumBytes = fillBufList [0].DataByteSize; + + var we = destinationFile.WritePackets (false, inNumBytes, outputPacketDescriptions, outputFilePos, ref ioOutputDataPackets, outputBuffer); + if (we != 0) { + Debug.Print ("WritePackets: {0}", we); + error = true; + break; + } + + // advance output file packet position + outputFilePos += ioOutputDataPackets; + + if (dstFormat.FramesPerPacket != 0) { + // the format has constant frames per packet + totalOutputFrames += (ioOutputDataPackets * dstFormat.FramesPerPacket); + } else { + // variable frames per packet require doing this for each packet (adding up the number of sample frames of data in each packet) + for (var i = 0; i < ioOutputDataPackets; ++i) + totalOutputFrames += outputPacketDescriptions [i].VariableFramesInPacket; + } + + } + + Marshal.FreeHGlobal (outputBuffer); + + if (!error) { + // write out any of the leading and trailing frames for compressed formats only + if (dstFormat.BitsPerChannel == 0) { + // our output frame count should jive with + Debug.Print ("Total number of output frames counted: {0}", totalOutputFrames); + WritePacketTableInfo (converter, destinationFile); + } + + // write the cookie again - sometimes codecs will update cookies at the end of a conversion + WriteCookie (converter, destinationFile); + } + + converter.Dispose (); + destinationFile.Dispose (); + sourceFile.Dispose (); + + // transition thread state to State.Done before continuing + AppDelegate.ThreadStateSetDone (); + + return !error; + } + + // Input data proc callback + AudioConverterError EncoderDataProc (ref int numberDataPackets, AudioBuffers data, ref AudioStreamPacketDescription [] dataPacketDescription) + { + // figure out how much to read + int maxPackets = afio.SrcBufferSize / afio.SrcSizePerPacket; + if (numberDataPackets > maxPackets) + numberDataPackets = maxPackets; + + // read from the file + int outNumBytes = 16384; + + // modified for iOS7 (ReadPackets depricated) + afio.PacketDescriptions = afio.SourceFile.ReadPacketData (false, afio.SrcFilePos, ref numberDataPackets, afio.SrcBuffer, ref outNumBytes); if (afio.PacketDescriptions.Length == 0 && numberDataPackets > 0) - throw new ApplicationException(afio.PacketDescriptions.ToString()); - - // advance input file packet position - afio.SrcFilePos += numberDataPackets; - - // put the data pointer into the buffer list - data.SetData(0, afio.SrcBuffer, outNumBytes); - - // don't forget the packet descriptions if required - if (dataPacketDescription != null) - dataPacketDescription = afio.PacketDescriptions; - - return AudioConverterError.None; - } - - // Some audio formats have a magic cookie associated with them which is required to decompress audio data - // When converting audio data you must check to see if the format of the data has a magic cookie - // If the audio data format has a magic cookie associated with it, you must add this information to anAudio Converter - // using AudioConverterSetProperty and kAudioConverterDecompressionMagicCookie to appropriately decompress the data - // http://developer.apple.com/mac/library/qa/qa2001/qa1318.html - static void ReadCookie(AudioFile sourceFile, AudioConverter converter) - { - // grab the cookie from the source file and set it on the converter - var cookie = sourceFile.MagicCookie; - - // if there is an error here, then the format doesn't have a cookie - this is perfectly fine as some formats do not - if (cookie != null && cookie.Length != 0) - { - converter.DecompressionMagicCookie = cookie; - } - } - - // Some audio formats have a magic cookie associated with them which is required to decompress audio data - // When converting audio, a magic cookie may be returned by the Audio Converter so that it may be stored along with - // the output data -- This is done so that it may then be passed back to the Audio Converter at a later time as required - static void WriteCookie(AudioConverter converter, AudioFile destinationFile) - { - var cookie = converter.CompressionMagicCookie; - if (cookie != null && cookie.Length != 0) - { - destinationFile.MagicCookie = cookie; - } - } - - // Write output channel layout to destination file - static void WriteDestinationChannelLayout(AudioConverter converter, AudioFile sourceFile, AudioFile destinationFile) - { - // if the Audio Converter doesn't have a layout see if the input file does - var layout = converter.OutputChannelLayout ?? sourceFile.ChannelLayout; - - if (layout != null) - { - // TODO: - throw new NotImplementedException(); - //destinationFile.ChannelLayout = layout; - } - } - - // Sets the packet table containing information about the number of valid frames in a file and where they begin and end - // for the file types that support this information. - // Calling this function makes sure we write out the priming and remainder details to the destination file - static void WritePacketTableInfo(AudioConverter converter, AudioFile destinationFile) - { - if (!destinationFile.IsPropertyWritable(AudioFileProperty.PacketTableInfo)) - return; - - // retrieve the leadingFrames and trailingFrames information from the converter, - AudioConverterPrimeInfo primeInfo = converter.PrimeInfo; - - // we have some priming information to write out to the destination file - // The total number of packets in the file times the frames per packet (or counting each packet's - // frames individually for a variable frames per packet format) minus mPrimingFrames, minus - // mRemainderFrames, should equal mNumberValidFrames. - - AudioFilePacketTableInfo? pti_n = destinationFile.PacketTableInfo; - if (pti_n == null) - return; - - AudioFilePacketTableInfo pti = pti_n.Value; - - // there's priming to write out to the file - // get the total number of frames from the output file - long totalFrames = pti.ValidFrames + pti.PrimingFrames + pti.RemainderFrames; - Debug.WriteLine("Total number of frames from output file: {0}", totalFrames); - - pti.PrimingFrames = primeInfo.LeadingFrames; - pti.RemainderFrames = primeInfo.TrailingFrames; - pti.ValidFrames = totalFrames - pti.PrimingFrames - pti.RemainderFrames; - - destinationFile.PacketTableInfo = pti; - } - - AVAudioPlayer player; - - void playAudio() - { - Debug.WriteLine("Playing converted audio..."); - - UpdateFormatInfo(fileInfo, destinationURL); - startButton.SetTitle("Playing Output File...", UIControlState.Disabled); - - // set category back to something that will allow us to play audio since kAudioSessionCategory_AudioProcessing will not - AudioSession.Category = AudioSessionCategory.MediaPlayback; - - // play the result - NSError error; - player = AVAudioPlayer.FromUrl(destinationURL, out error); - if (player == null) - { - Debug.Print("AVAudioPlayer failed: {0}", error); - UpdateUI(); - return; - } - - player.DecoderError += delegate - { - Debug.WriteLine("DecoderError"); - UpdateUI(); - }; - - player.BeginInterruption += delegate - { - Debug.WriteLine("BeginInterruption"); - player.Stop(); - UpdateUI(); - }; - - player.FinishedPlaying += delegate(object sender, AVStatusEventArgs e) - { - Debug.WriteLine("FinishedPlaying"); - UpdateUI(); - player = null; - }; - - if (!player.Play()) - { - Debug.WriteLine("ERROR: Cannot play the file"); - UpdateUI(); - player = null; - } - } - } + throw new ApplicationException (afio.PacketDescriptions.ToString ()); + + // advance input file packet position + afio.SrcFilePos += numberDataPackets; + + // put the data pointer into the buffer list + data.SetData (0, afio.SrcBuffer, outNumBytes); + + // don't forget the packet descriptions if required + if (dataPacketDescription != null) + dataPacketDescription = afio.PacketDescriptions; + + return AudioConverterError.None; + } + + // Some audio formats have a magic cookie associated with them which is required to decompress audio data + // When converting audio data you must check to see if the format of the data has a magic cookie + // If the audio data format has a magic cookie associated with it, you must add this information to anAudio Converter + // using AudioConverterSetProperty and kAudioConverterDecompressionMagicCookie to appropriately decompress the data + // http://developer.apple.com/mac/library/qa/qa2001/qa1318.html + static void ReadCookie (AudioFile sourceFile, AudioConverter converter) + { + // grab the cookie from the source file and set it on the converter + var cookie = sourceFile.MagicCookie; + + // if there is an error here, then the format doesn't have a cookie - this is perfectly fine as some formats do not + if (cookie != null && cookie.Length != 0) { + converter.DecompressionMagicCookie = cookie; + } + } + + // Some audio formats have a magic cookie associated with them which is required to decompress audio data + // When converting audio, a magic cookie may be returned by the Audio Converter so that it may be stored along with + // the output data -- This is done so that it may then be passed back to the Audio Converter at a later time as required + static void WriteCookie (AudioConverter converter, AudioFile destinationFile) + { + var cookie = converter.CompressionMagicCookie; + if (cookie != null && cookie.Length != 0) { + destinationFile.MagicCookie = cookie; + } + } + + // Write output channel layout to destination file + static void WriteDestinationChannelLayout (AudioConverter converter, AudioFile sourceFile, AudioFile destinationFile) + { + // if the Audio Converter doesn't have a layout see if the input file does + var layout = converter.OutputChannelLayout ?? sourceFile.ChannelLayout; + + if (layout != null) { + // TODO: + throw new NotImplementedException (); + //destinationFile.ChannelLayout = layout; + } + } + + // Sets the packet table containing information about the number of valid frames in a file and where they begin and end + // for the file types that support this information. + // Calling this function makes sure we write out the priming and remainder details to the destination file + static void WritePacketTableInfo (AudioConverter converter, AudioFile destinationFile) + { + if (!destinationFile.IsPropertyWritable (AudioFileProperty.PacketTableInfo)) + return; + + // retrieve the leadingFrames and trailingFrames information from the converter, + AudioConverterPrimeInfo primeInfo = converter.PrimeInfo; + + // we have some priming information to write out to the destination file + // The total number of packets in the file times the frames per packet (or counting each packet's + // frames individually for a variable frames per packet format) minus mPrimingFrames, minus + // mRemainderFrames, should equal mNumberValidFrames. + + AudioFilePacketTableInfo? pti_n = destinationFile.PacketTableInfo; + if (pti_n == null) + return; + + AudioFilePacketTableInfo pti = pti_n.Value; + + // there's priming to write out to the file + // get the total number of frames from the output file + long totalFrames = pti.ValidFrames + pti.PrimingFrames + pti.RemainderFrames; + Debug.WriteLine ("Total number of frames from output file: {0}", totalFrames); + + pti.PrimingFrames = primeInfo.LeadingFrames; + pti.RemainderFrames = primeInfo.TrailingFrames; + pti.ValidFrames = totalFrames - pti.PrimingFrames - pti.RemainderFrames; + + destinationFile.PacketTableInfo = pti; + } + + AVAudioPlayer player; + + void playAudio () + { + Debug.WriteLine ("Playing converted audio..."); + + UpdateFormatInfo (fileInfo, destinationURL); + startButton.SetTitle ("Playing Output File...", UIControlState.Disabled); + + // set category back to something that will allow us to play audio since kAudioSessionCategory_AudioProcessing will not + AudioSession.Category = AudioSessionCategory.MediaPlayback; + + // play the result + NSError error; + player = AVAudioPlayer.FromUrl (destinationURL, out error); + if (player == null) { + Debug.Print ("AVAudioPlayer failed: {0}", error); + UpdateUI (); + return; + } + + player.DecoderError += delegate + { + Debug.WriteLine ("DecoderError"); + UpdateUI (); + }; + + player.BeginInterruption += delegate + { + Debug.WriteLine ("BeginInterruption"); + player.Stop (); + UpdateUI (); + }; + + player.FinishedPlaying += delegate (object sender, AVStatusEventArgs e) + { + Debug.WriteLine ("FinishedPlaying"); + UpdateUI (); + player = null; + }; + + if (!player.Play ()) { + Debug.WriteLine ("ERROR: Cannot play the file"); + UpdateUI (); + player = null; + } + } + } } diff --git a/AudioConverterFileConverter/Main.cs b/AudioConverterFileConverter/Main.cs index 6bcf19837..c81162804 100644 --- a/AudioConverterFileConverter/Main.cs +++ b/AudioConverterFileConverter/Main.cs @@ -33,12 +33,10 @@ using Foundation; using UIKit; -namespace AudioConverterFileConverter -{ - public class Application - { +namespace AudioConverterFileConverter { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AudioGenerator/AppDelegate.cs b/AudioGenerator/AppDelegate.cs index 839732894..9b9a58bca 100644 --- a/AudioGenerator/AppDelegate.cs +++ b/AudioGenerator/AppDelegate.cs @@ -5,150 +5,140 @@ using AudioToolbox; using AVFoundation; -namespace tone -{ - [Register("AppDelegate")] - unsafe public partial class AppDelegate : UIApplicationDelegate - { - double sampleRate; - const int numBuffers = 3; - bool alternate = false; - NSError error; - - public override bool FinishedLaunching(UIApplication app, NSDictionary options) - { - // - // Setup audio system - // - var session = AVAudioSession.SharedInstance(); - session.SetCategory(new NSString("AVAudioSessionCategoryPlayback"), AVAudioSessionCategoryOptions.DefaultToSpeaker, out error); - if (error != null) - { +namespace tone { + [Register ("AppDelegate")] + unsafe public partial class AppDelegate : UIApplicationDelegate { + double sampleRate; + const int numBuffers = 3; + bool alternate = false; + NSError error; + + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + // + // Setup audio system + // + var session = AVAudioSession.SharedInstance (); + session.SetCategory (new NSString ("AVAudioSessionCategoryPlayback"), AVAudioSessionCategoryOptions.DefaultToSpeaker, out error); + if (error != null) { Console.WriteLine (error); } - // - // Format description, we generate LinearPCM as short integers - // - sampleRate = session.SampleRate; - var format = new AudioStreamBasicDescription - { - SampleRate = sampleRate, - Format = AudioFormatType.LinearPCM, - FormatFlags = AudioFormatFlags.LinearPCMIsSignedInteger | AudioFormatFlags.LinearPCMIsPacked, - BitsPerChannel = 16, - ChannelsPerFrame = 1, - BytesPerFrame = 2, - BytesPerPacket = 2, - FramesPerPacket = 1, - }; - - // - // Create an output queue - // - var queue = new OutputAudioQueue(format); - var bufferByteSize = (sampleRate > 16000) ? 2176 : 512; // 40.5 Hz : 31.25 Hz - - // - // Create three buffers, generate a tone, and output the tones - // - var buffers = new AudioQueueBuffer* [numBuffers]; - for (int i = 0; i < numBuffers; i++) - { - queue.AllocateBuffer(bufferByteSize, out buffers[i]); - GenerateTone(buffers[i]); - queue.EnqueueBuffer(buffers[i], null); - } - - // - // Output callback: invoked when the audio system is done with the - // buffer, this implementation merely recycles it. - // - queue.BufferCompleted += (object sender, BufferCompletedEventArgs e) => - { - if (alternate) - { - outputWaveForm += 1; - if (outputWaveForm > WaveForm.Square) - outputWaveForm = WaveForm.Sine; - GenerateTone(e.UnsafeBuffer); - } - queue.EnqueueBuffer(e.UnsafeBuffer, null); - }; - - queue.Start(); - return true; - } - - // Configuration options for the audio output - const float outputFrequency = 220; - - enum WaveForm - { - Sine, - Triangle, - Sawtooth, - Square - } - - WaveForm outputWaveForm; - - // - // Simple tone generator - // - void GenerateTone(AudioQueueBuffer*buffer) - { - // Make the buffer length a multiple of the wavelength for the output frequency. - uint sampleCount = buffer->AudioDataBytesCapacity / 2; - double bufferLength = sampleCount; - double wavelength = sampleRate / outputFrequency; - double repetitions = Math.Floor(bufferLength / wavelength); - if (repetitions > 0) - sampleCount = (uint)Math.Round(wavelength * repetitions); - - double x, y; - double sd = 1.0 / sampleRate; - double amp = 0.9; - double max16bit = Int16.MaxValue; - int i; - short* p = (short*)buffer->AudioData; - - for (i = 0; i < sampleCount; i++) - { - x = i * sd * outputFrequency; - switch (outputWaveForm) - { - case WaveForm.Sine: - y = Math.Sin(x * 2.0 * Math.PI); - break; - case WaveForm.Triangle: - x = x % 1.0; - if (x < 0.25) - y = x * 4.0; // up 0.0 to 1.0 - else if (x < 0.75) - y = (1.0 - x) * 4.0 - 2.0; // down 1.0 to -1.0 - else - y = (x - 1.0) * 4.0; // up -1.0 to 0.0 - break; - case WaveForm.Sawtooth: - y = 0.8 - (x % 1.0) * 1.8; - break; - case WaveForm.Square: - y = ((x % 1.0) < 0.5) ? 0.7 : -0.7; - break; - default: - y = 0; - break; - } - p[i] = (short)(y * max16bit * amp); - } - - buffer->AudioDataByteSize = sampleCount * 2; - } - - static void Main(string[] args) - { - UIApplication.Main(args, null, "AppDelegate"); - } - } + // + // Format description, we generate LinearPCM as short integers + // + sampleRate = session.SampleRate; + var format = new AudioStreamBasicDescription { + SampleRate = sampleRate, + Format = AudioFormatType.LinearPCM, + FormatFlags = AudioFormatFlags.LinearPCMIsSignedInteger | AudioFormatFlags.LinearPCMIsPacked, + BitsPerChannel = 16, + ChannelsPerFrame = 1, + BytesPerFrame = 2, + BytesPerPacket = 2, + FramesPerPacket = 1, + }; + + // + // Create an output queue + // + var queue = new OutputAudioQueue (format); + var bufferByteSize = (sampleRate > 16000) ? 2176 : 512; // 40.5 Hz : 31.25 Hz + + // + // Create three buffers, generate a tone, and output the tones + // + var buffers = new AudioQueueBuffer* [numBuffers]; + for (int i = 0; i < numBuffers; i++) { + queue.AllocateBuffer (bufferByteSize, out buffers [i]); + GenerateTone (buffers [i]); + queue.EnqueueBuffer (buffers [i], null); + } + + // + // Output callback: invoked when the audio system is done with the + // buffer, this implementation merely recycles it. + // + queue.BufferCompleted += (object sender, BufferCompletedEventArgs e) => { + if (alternate) { + outputWaveForm += 1; + if (outputWaveForm > WaveForm.Square) + outputWaveForm = WaveForm.Sine; + GenerateTone (e.UnsafeBuffer); + } + queue.EnqueueBuffer (e.UnsafeBuffer, null); + }; + + queue.Start (); + return true; + } + + // Configuration options for the audio output + const float outputFrequency = 220; + + enum WaveForm { + Sine, + Triangle, + Sawtooth, + Square + } + + WaveForm outputWaveForm; + + // + // Simple tone generator + // + void GenerateTone (AudioQueueBuffer* buffer) + { + // Make the buffer length a multiple of the wavelength for the output frequency. + uint sampleCount = buffer->AudioDataBytesCapacity / 2; + double bufferLength = sampleCount; + double wavelength = sampleRate / outputFrequency; + double repetitions = Math.Floor (bufferLength / wavelength); + if (repetitions > 0) + sampleCount = (uint) Math.Round (wavelength * repetitions); + + double x, y; + double sd = 1.0 / sampleRate; + double amp = 0.9; + double max16bit = Int16.MaxValue; + int i; + short* p = (short*) buffer->AudioData; + + for (i = 0; i < sampleCount; i++) { + x = i * sd * outputFrequency; + switch (outputWaveForm) { + case WaveForm.Sine: + y = Math.Sin (x * 2.0 * Math.PI); + break; + case WaveForm.Triangle: + x = x % 1.0; + if (x < 0.25) + y = x * 4.0; // up 0.0 to 1.0 + else if (x < 0.75) + y = (1.0 - x) * 4.0 - 2.0; // down 1.0 to -1.0 + else + y = (x - 1.0) * 4.0; // up -1.0 to 0.0 + break; + case WaveForm.Sawtooth: + y = 0.8 - (x % 1.0) * 1.8; + break; + case WaveForm.Square: + y = ((x % 1.0) < 0.5) ? 0.7 : -0.7; + break; + default: + y = 0; + break; + } + p [i] = (short) (y * max16bit * amp); + } + + buffer->AudioDataByteSize = sampleCount * 2; + } + + static void Main (string [] args) + { + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/AudioQueueOfflineRenderDemo/AppDelegate.cs b/AudioQueueOfflineRenderDemo/AppDelegate.cs index 3b5421de5..60276521b 100644 --- a/AudioQueueOfflineRenderDemo/AppDelegate.cs +++ b/AudioQueueOfflineRenderDemo/AppDelegate.cs @@ -15,11 +15,9 @@ using AudioFileID = System.IntPtr; -namespace AudioQueueOfflineRenderDemo -{ +namespace AudioQueueOfflineRenderDemo { [Register ("AppDelegate")] - public unsafe partial class AppDelegate : UIApplicationDelegate - { + public unsafe partial class AppDelegate : UIApplicationDelegate { UIWindow window; DialogViewController dvc; StyledStringElement element; @@ -96,7 +94,7 @@ static void CalculateBytesForTime (AudioStreamBasicDescription desc, int maxPack const int minBufferSize = 0x4000; if (desc.FramesPerPacket > 0) { - bufferSize = (int)(desc.SampleRate / desc.FramesPerPacket * seconds * maxPacketSize); + bufferSize = (int) (desc.SampleRate / desc.FramesPerPacket * seconds * maxPacketSize); } else { bufferSize = maxBufferSize > maxPacketSize ? maxBufferSize : maxPacketSize; } @@ -110,7 +108,7 @@ static void CalculateBytesForTime (AudioStreamBasicDescription desc, int maxPack packetCount = bufferSize / maxPacketSize; } - unsafe static void HandleOutput (AudioFile audioFile, AudioQueue queue, AudioQueueBuffer*audioQueueBuffer, ref int packetsToRead, ref long currentPacket, ref bool done, ref bool flushed, ref AudioStreamPacketDescription[] packetDescriptions) + unsafe static void HandleOutput (AudioFile audioFile, AudioQueue queue, AudioQueueBuffer* audioQueueBuffer, ref int packetsToRead, ref long currentPacket, ref bool done, ref bool flushed, ref AudioStreamPacketDescription [] packetDescriptions) { int bytes; int packets; @@ -119,12 +117,12 @@ unsafe static void HandleOutput (AudioFile audioFile, AudioQueue queue, AudioQue return; packets = packetsToRead; - bytes = (int)audioQueueBuffer->AudioDataBytesCapacity; + bytes = (int) audioQueueBuffer->AudioDataBytesCapacity; packetDescriptions = audioFile.ReadPacketData (false, currentPacket, ref packets, audioQueueBuffer->AudioData, ref bytes); if (packets > 0) { - audioQueueBuffer->AudioDataByteSize = (uint)bytes; + audioQueueBuffer->AudioDataByteSize = (uint) bytes; queue.EnqueueBuffer (audioQueueBuffer, packetDescriptions); currentPacket += packets; } else { @@ -144,12 +142,12 @@ unsafe static void RenderAudio (CFUrl sourceUrl, CFUrl destinationUrl) AudioQueueBuffer* buffer = null; long currentPacket = 0; int packetsToRead = 0; - AudioStreamPacketDescription[] packetDescs = null; + AudioStreamPacketDescription [] packetDescs = null; bool flushed = false; bool done = false; int bufferSize; - using (var audioFile = AudioFile.Open (sourceUrl, AudioFilePermission.Read, (AudioFileType)0)) { + using (var audioFile = AudioFile.Open (sourceUrl, AudioFilePermission.Read, (AudioFileType) 0)) { dataFormat = audioFile.StreamBasicDescription; using (var queue = new OutputAudioQueue (dataFormat, CFRunLoop.Current, CFRunLoop.ModeCommon)) { @@ -179,13 +177,13 @@ unsafe static void RenderAudio (CFUrl sourceUrl, CFUrl destinationUrl) queue.AllocateBuffer (bufferSize, out buffer); // prepare the capture format - var captureFormat = AudioStreamBasicDescription.CreateLinearPCM (dataFormat.SampleRate, (uint)dataFormat.ChannelsPerFrame, 32); + var captureFormat = AudioStreamBasicDescription.CreateLinearPCM (dataFormat.SampleRate, (uint) dataFormat.ChannelsPerFrame, 32); captureFormat.BytesPerFrame = captureFormat.BytesPerPacket = dataFormat.ChannelsPerFrame * 4; queue.SetOfflineRenderFormat (captureFormat, audioFile.ChannelLayout); // prepare the target format - var dstFormat = AudioStreamBasicDescription.CreateLinearPCM (dataFormat.SampleRate, (uint)dataFormat.ChannelsPerFrame); + var dstFormat = AudioStreamBasicDescription.CreateLinearPCM (dataFormat.SampleRate, (uint) dataFormat.ChannelsPerFrame); using (var captureFile = ExtAudioFile.CreateWithUrl (destinationUrl, AudioFileType.CAF, dstFormat, AudioFileFlags.EraseFlags)) { captureFile.ClientDataFormat = captureFormat; @@ -213,13 +211,13 @@ unsafe static void RenderAudio (CFUrl sourceUrl, CFUrl destinationUrl) queue.RenderOffline (ts, captureBuffer, reqFrames); - captureABL.SetData (0, captureBuffer->AudioData, (int)captureBuffer->AudioDataByteSize); + captureABL.SetData (0, captureBuffer->AudioData, (int) captureBuffer->AudioDataByteSize); var writeFrames = captureABL [0].DataByteSize / captureFormat.BytesPerFrame; // Console.WriteLine ("ts: {0} AudioQueueOfflineRender: req {1} frames / {2} bytes, got {3} frames / {4} bytes", // ts, reqFrames, captureBufferSize, writeFrames, captureABL.Buffers [0].DataByteSize); - captureFile.WriteAsync ((uint)writeFrames, captureABL); + captureFile.WriteAsync ((uint) writeFrames, captureABL); if (flushed) break; diff --git a/AudioQueueOfflineRenderDemo/Main.cs b/AudioQueueOfflineRenderDemo/Main.cs index b5a6b4af8..60d85b9bb 100644 --- a/AudioQueueOfflineRenderDemo/Main.cs +++ b/AudioQueueOfflineRenderDemo/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace AudioQueueOfflineRenderDemo -{ - public class Application - { +namespace AudioQueueOfflineRenderDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AudioTapProcessor/AudioTapProcessor/AVAudioTapProcessorContext.cs b/AudioTapProcessor/AudioTapProcessor/AVAudioTapProcessorContext.cs index 22d0d0ad7..8717ad213 100644 --- a/AudioTapProcessor/AudioTapProcessor/AVAudioTapProcessorContext.cs +++ b/AudioTapProcessor/AudioTapProcessor/AVAudioTapProcessorContext.cs @@ -5,10 +5,8 @@ using MediaToolbox; using AudioToolbox; -namespace AudioTapProcessor -{ - struct AVAudioTapProcessorContext - { +namespace AudioTapProcessor { + struct AVAudioTapProcessorContext { public bool SupportedTapProcessingFormat; public bool IsNonInterleaved; @@ -23,4 +21,4 @@ struct AVAudioTapProcessorContext public AudioUnit.AudioUnit AudioUnit; } -} \ No newline at end of file +} diff --git a/AudioTapProcessor/AudioTapProcessor/AppDelegate.cs b/AudioTapProcessor/AudioTapProcessor/AppDelegate.cs index d23c30703..2ce34c472 100644 --- a/AudioTapProcessor/AudioTapProcessor/AppDelegate.cs +++ b/AudioTapProcessor/AudioTapProcessor/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace AudioTapProcessor -{ +namespace AudioTapProcessor { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication app, NSDictionary options) diff --git a/AudioTapProcessor/AudioTapProcessor/AudioTapProcessor.cs b/AudioTapProcessor/AudioTapProcessor/AudioTapProcessor.cs index 038e9a192..fc36aa64d 100644 --- a/AudioTapProcessor/AudioTapProcessor/AudioTapProcessor.cs +++ b/AudioTapProcessor/AudioTapProcessor/AudioTapProcessor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; using Foundation; @@ -10,10 +10,8 @@ using CoreFoundation; -namespace AudioTapProcessor -{ - public class AudioTapProcessor : NSObject - { +namespace AudioTapProcessor { + public class AudioTapProcessor : NSObject { AVAssetTrack audioAssetTrack; MTAudioProcessingTap audioProcessingTap; AVAudioTapProcessorContext context; @@ -81,7 +79,7 @@ unsafe AVAudioMix CreateAudioMix () audioProcessingTap = new MTAudioProcessingTap (callbacks, MTAudioProcessingTapCreationFlags.PreEffects); audioMixInputParameters.AudioTapProcessor = audioProcessingTap; - audioMix.InputParameters = new AVAudioMixInputParameters[] { audioMixInputParameters }; + audioMix.InputParameters = new AVAudioMixInputParameters [] { audioMixInputParameters }; return audioMix; } @@ -93,7 +91,7 @@ unsafe AVAudioMix CreateAudioMix () unsafe void UpdateCenterFrequency (float frequency) { // Update center frequency of bandpass filter Audio Unit. - float newFrequency = CalcNewCenterFrequency ((float)context.SampleRate, frequency); + float newFrequency = CalcNewCenterFrequency ((float) context.SampleRate, frequency); SetCenterFrequency (newFrequency); } @@ -148,12 +146,12 @@ void SetBandwidth (float newBandwidth) #region MTAudioProcessingTap Callbacks unsafe void TapProcess (MTAudioProcessingTap tap, nint numberFrames, MTAudioProcessingTapFlags flags, - AudioBuffers bufferList, - out nint numberFramesOut, - out MTAudioProcessingTapFlags flagsOut) + AudioBuffers bufferList, + out nint numberFramesOut, + out MTAudioProcessingTapFlags flagsOut) { numberFramesOut = 0; - flagsOut = (MTAudioProcessingTapFlags)0; + flagsOut = (MTAudioProcessingTapFlags) 0; // Skip processing when format not supported. if (!context.SupportedTapProcessingFormat) { @@ -169,8 +167,8 @@ unsafe void TapProcess (MTAudioProcessingTap tap, nint numberFrames, MTAudioProc Flags = AudioTimeStamp.AtsFlags.SampleTimeValid }; - var f = (AudioUnitRenderActionFlags)0; - var status = context.AudioUnit.Render (ref f, audioTimeStamp, 0, (uint)numberFrames, bufferList); + var f = (AudioUnitRenderActionFlags) 0; + var status = context.AudioUnit.Render (ref f, audioTimeStamp, 0, (uint) numberFrames, bufferList); if (status != AudioUnitStatus.NoError) { Console.WriteLine ("AudioUnitRender(): {0}", status); return; @@ -207,7 +205,7 @@ unsafe void TapInitialization (MTAudioProcessingTap tap, out void* tapStorage) }; // We don't use tapStorage we store all data within context field - tapStorage = (void*)IntPtr.Zero; + tapStorage = (void*) IntPtr.Zero; } unsafe void Finalaze (MTAudioProcessingTap tap) @@ -246,10 +244,10 @@ unsafe void TapPrepare (MTAudioProcessingTap tap, nint maxFrames, ref AudioStrea error = audioUnit.SetRenderCallback (Render, AudioUnitScopeType.Input); if (error == AudioUnitStatus.NoError) - error = audioUnit.SetMaximumFramesPerSlice ((uint)maxFrames, AudioUnitScopeType.Global); + error = audioUnit.SetMaximumFramesPerSlice ((uint) maxFrames, AudioUnitScopeType.Global); if (error == AudioUnitStatus.NoError) - error = (AudioUnitStatus)audioUnit.Initialize (); + error = (AudioUnitStatus) audioUnit.Initialize (); if (error != AudioUnitStatus.NoError) { audioUnit.Dispose (); @@ -290,7 +288,7 @@ AudioUnitStatus Render (AudioUnitRenderActionFlags actionFlags, AudioTimeStamp t MTAudioProcessingTapFlags flags; CMTimeRange range; nint n; - var error = (AudioUnitStatus)(int)audioProcessingTap.GetSourceAudio ((nint)numberFrames, data, out flags, out range, out n); + var error = (AudioUnitStatus) (int) audioProcessingTap.GetSourceAudio ((nint) numberFrames, data, out flags, out range, out n); if (error != AudioUnitStatus.NoError) Console.WriteLine ("{0} audioProcessingTap.GetSourceAudio failed", error); return error; @@ -306,14 +304,14 @@ unsafe void UpdateVolumes (AudioBuffers bufferList, nint numberFrames) AudioBuffer pBuffer = bufferList [i]; long cSamples = numberFrames * (context.IsNonInterleaved ? 1 : pBuffer.NumberChannels); - float* pData = (float*)(void*)pBuffer.Data; + float* pData = (float*) (void*) pBuffer.Data; float rms = 0; for (int j = 0; j < cSamples; j++) rms += pData [j] * pData [j]; if (cSamples > 0) - rms = (float)Math.Sqrt (rms / cSamples); + rms = (float) Math.Sqrt (rms / cSamples); if (i == 0) context.LeftChannelVolume = rms; @@ -331,4 +329,4 @@ void UpdateVolumes (float leftVolume, float rightVolume) DispatchQueue.MainQueue.DispatchAsync (() => Controller.OnNewLeftRightChanelValue (this, leftVolume, rightVolume)); } } -} \ No newline at end of file +} diff --git a/AudioTapProcessor/AudioTapProcessor/Main.cs b/AudioTapProcessor/AudioTapProcessor/Main.cs index 454b5a30e..ecc435fb0 100644 --- a/AudioTapProcessor/AudioTapProcessor/Main.cs +++ b/AudioTapProcessor/AudioTapProcessor/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace AudioTapProcessor -{ - public class Application - { +namespace AudioTapProcessor { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/AudioTapProcessor/AudioTapProcessor/MainScreen/MainViewController.cs b/AudioTapProcessor/AudioTapProcessor/MainScreen/MainViewController.cs index 6f8ee0b7c..10114a678 100644 --- a/AudioTapProcessor/AudioTapProcessor/MainScreen/MainViewController.cs +++ b/AudioTapProcessor/AudioTapProcessor/MainScreen/MainViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -9,11 +9,9 @@ using CoreFoundation; using System.Threading; -namespace AudioTapProcessor -{ +namespace AudioTapProcessor { [Register ("MainViewController")] - public class MainViewController : UIViewController - { + public class MainViewController : UIViewController { static NSUrl movieUrl; NSObject playerTimeObserver; @@ -25,7 +23,7 @@ public AVPlayer Player { get { if (player == null && movieUrl != null) { - player = new AVPlayer(movieUrl); + player = new AVPlayer (movieUrl); } return player; @@ -122,8 +120,8 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) void SetupSettingsViewController (UIStoryboardSegue segue) { // Setup settings view controller before it is shown. - UIViewController topViewController = ((UINavigationController)segue.DestinationViewController).TopViewController; - var settingsViewController = (SettingsViewController)topViewController; + UIViewController topViewController = ((UINavigationController) segue.DestinationViewController).TopViewController; + var settingsViewController = (SettingsViewController) topViewController; settingsViewController.Controller = this; settingsViewController.EnabledSwitchValue = AudioTapProcessor.IsBandpassFilterEnabled; @@ -141,8 +139,8 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio AVPlayerStatus FetchStatus (NSDictionary change) { var ch = new NSObservedChange (change); - var newValue = (NSNumber)ch.NewValue; - return newValue == null ? AVPlayerStatus.Unknown : (AVPlayerStatus)newValue.Int32Value; + var newValue = (NSNumber) ch.NewValue; + return newValue == null ? AVPlayerStatus.Unknown : (AVPlayerStatus) newValue.Int32Value; } void OnReadyToPlay () @@ -173,7 +171,7 @@ void ResetUpdateTimeIndicators (CMTime duration) void UpdateTimeIndicators (CMTime time, CMTime duration) { ElapsedTimeLabel.Text = BuildTimeString (time); - CurrentTimeSlider.Value = (float)(time.Seconds / duration.Seconds); + CurrentTimeSlider.Value = (float) (time.Seconds / duration.Seconds); RemainingTimeLabel.Text = BuildTimeString (duration - time, "-"); } @@ -282,9 +280,9 @@ static NSUrl fetchMovieUrl () return; } - NSDate latest = NSDate.FromTimeIntervalSince1970(0); + NSDate latest = NSDate.FromTimeIntervalSince1970 (0); group.Enumerate ((ALAsset result, nint index, ref bool stopGroup) => { - if(result == null || result.AssetType != ALAssetType.Video) + if (result == null || result.AssetType != ALAssetType.Video) return; NSUrl url = result.DefaultRepresentation.Url; @@ -292,7 +290,7 @@ static NSUrl fetchMovieUrl () return; var diff = result.Date.SecondsSinceReferenceDate - latest.SecondsSinceReferenceDate; - if(diff > 0) { + if (diff > 0) { latest = result.Date; movieURL = url; } @@ -307,8 +305,8 @@ static NSUrl fetchMovieUrl () waitHandle.WaitOne (); if (movieURL == null) { - UIAlertView alertView = new UIAlertView(null, "Could not find any movies in assets library to use as sample content.", null, "OK", null); - alertView.Show(); + UIAlertView alertView = new UIAlertView (null, "Could not find any movies in assets library to use as sample content.", null, "OK", null); + alertView.Show (); } return movieURL; @@ -337,7 +335,7 @@ protected override void Dispose (bool disposing) static AVAssetTrack FetchFirstAudioTrack (AVPlayer player) { - AVAssetTrack[] tracks = player.CurrentItem.Asset.Tracks; + AVAssetTrack [] tracks = player.CurrentItem.Asset.Tracks; AVAssetTrack firstAudioTrack = tracks.FirstOrDefault (t => t.MediaType == AVMediaType.Audio); return firstAudioTrack; } @@ -347,13 +345,13 @@ static string BuildTimeString (CMTime time, string sign = null) sign = sign ?? string.Empty; var seconds = Math.Round (time.Seconds); - int hh = (int)Math.Floor (seconds / 3600); - int mm = (int)Math.Floor ((seconds - hh * 3600) / 60); - int ss = (int)seconds % 60; + int hh = (int) Math.Floor (seconds / 3600); + int mm = (int) Math.Floor ((seconds - hh * 3600) / 60); + int ss = (int) seconds % 60; return hh > 0 ? string.Format ("{0}{1:00}:{2:00}:{3:00}", sign, hh, mm, ss) : string.Format ("{0}{1:00}:{2:00}", sign, mm, ss); } } -} \ No newline at end of file +} diff --git a/AudioTapProcessor/AudioTapProcessor/SettingsViewController.cs b/AudioTapProcessor/AudioTapProcessor/SettingsViewController.cs index 4c6dc8482..61054cceb 100644 --- a/AudioTapProcessor/AudioTapProcessor/SettingsViewController.cs +++ b/AudioTapProcessor/AudioTapProcessor/SettingsViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace AudioTapProcessor -{ +namespace AudioTapProcessor { [Register ("SettingsViewController")] - public class SettingsViewController : UITableViewController - { + public class SettingsViewController : UITableViewController { [Outlet] UISwitch EnabledSwitch { get; set; } diff --git a/AudioTapProcessor/AudioTapProcessor/Views/GradientView.cs b/AudioTapProcessor/AudioTapProcessor/Views/GradientView.cs index 5c4103d95..6b0409f48 100644 --- a/AudioTapProcessor/AudioTapProcessor/Views/GradientView.cs +++ b/AudioTapProcessor/AudioTapProcessor/Views/GradientView.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using ObjCRuntime; @@ -6,35 +6,33 @@ using Foundation; using CoreGraphics; -namespace AudioTapProcessor -{ - [Register("GradientView")] - public class GradientView : UIView - { +namespace AudioTapProcessor { + [Register ("GradientView")] + public class GradientView : UIView { static Class LayerClass { - [Export("layerClass")] + [Export ("layerClass")] get { - return new Class (typeof(CAGradientLayer)); + return new Class (typeof (CAGradientLayer)); } } public GradientView (IntPtr handle) - : base(handle) + : base (handle) { SetupLayerTree (); } - void SetupLayerTree() + void SetupLayerTree () { // Setup gradient layer. - ((CAGradientLayer)Layer).Colors = new CGColor[] { + ((CAGradientLayer) Layer).Colors = new CGColor [] { UIColor.DarkGray.CGColor, UIColor.FromWhiteAlpha (0.125f, 1).CGColor, UIColor.Black.CGColor, UIColor.Black.CGColor, }; - ((CAGradientLayer)Layer).Locations = new NSNumber[] { + ((CAGradientLayer) Layer).Locations = new NSNumber [] { new NSNumber (0), new NSNumber (0.5), new NSNumber (0.5), @@ -42,4 +40,4 @@ void SetupLayerTree() }; } } -} \ No newline at end of file +} diff --git a/AudioTapProcessor/AudioTapProcessor/Views/PlayerView.cs b/AudioTapProcessor/AudioTapProcessor/Views/PlayerView.cs index 7093acc18..47a6a55f0 100644 --- a/AudioTapProcessor/AudioTapProcessor/Views/PlayerView.cs +++ b/AudioTapProcessor/AudioTapProcessor/Views/PlayerView.cs @@ -1,33 +1,31 @@ -using System; +using System; using UIKit; using AVFoundation; using ObjCRuntime; using Foundation; -namespace AudioTapProcessor -{ - [Register("PlayerView")] - public class PlayerView : UIView - { +namespace AudioTapProcessor { + [Register ("PlayerView")] + public class PlayerView : UIView { static Class LayerClass { - [Export("layerClass")] + [Export ("layerClass")] get { - return new Class (typeof(AVPlayerLayer)); + return new Class (typeof (AVPlayerLayer)); } } public AVPlayer Player { get { - return ((AVPlayerLayer)Layer).Player; + return ((AVPlayerLayer) Layer).Player; } set { - ((AVPlayerLayer)Layer).Player = value; + ((AVPlayerLayer) Layer).Player = value; } } public PlayerView (IntPtr handle) - : base(handle) + : base (handle) { } } diff --git a/AudioTapProcessor/AudioTapProcessor/Views/VolumeUnitMeterView.cs b/AudioTapProcessor/AudioTapProcessor/Views/VolumeUnitMeterView.cs index f9ce18d7e..f34a8f3bc 100644 --- a/AudioTapProcessor/AudioTapProcessor/Views/VolumeUnitMeterView.cs +++ b/AudioTapProcessor/AudioTapProcessor/Views/VolumeUnitMeterView.cs @@ -1,19 +1,17 @@ -using System; +using System; using UIKit; using Foundation; using CoreGraphics; using CoreAnimation; -namespace AudioTapProcessor -{ +namespace AudioTapProcessor { [Register ("VolumeUnitMeterView")] - public class VolumeUnitMeterView : UIView - { + public class VolumeUnitMeterView : UIView { // This is an arbitrary calibration to define 0 db in the VU meter. const float UnitMeterCalibration = 12; - static readonly float DegreeToRadian = (float)Math.PI / 180; + static readonly float DegreeToRadian = (float) Math.PI / 180; CALayer NeedleLayer { get; set; } @@ -30,7 +28,7 @@ public float Value { // Convert RMS amplitude into dB (using some arbitrary calibration values). var valueDB = (20.0f * Math.Log10 (value) + UnitMeterCalibration); - NeedleLayer.AffineTransform = CGAffineTransform.MakeRotation (ConvertValueToNeedleAngle ((float)valueDB)); + NeedleLayer.AffineTransform = CGAffineTransform.MakeRotation (ConvertValueToNeedleAngle ((float) valueDB)); } } @@ -110,4 +108,4 @@ static nfloat ConvertValueToNeedleAngle (nfloat value) return DegreeToRadian * degree; } } -} \ No newline at end of file +} diff --git a/BackgroundExecution/BackgroundExecution/AppDelegate.cs b/BackgroundExecution/BackgroundExecution/AppDelegate.cs index 4e916128b..eb81e7492 100644 --- a/BackgroundExecution/BackgroundExecution/AppDelegate.cs +++ b/BackgroundExecution/BackgroundExecution/AppDelegate.cs @@ -1,78 +1,74 @@ -using System; +using System; using System.Threading.Tasks; using Foundation; using UIKit; -namespace BackgroundExecution -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace BackgroundExecution { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - // how to check if multi-tasking is supported - if (UIDevice.CurrentDevice.IsMultitaskingSupported) - { - // code here to change your app's behavior - } + // how to check if multi-tasking is supported + if (UIDevice.CurrentDevice.IsMultitaskingSupported) { + // code here to change your app's behavior + } - return true; - } - - // Runs when the activation transitions from running in the background to being the foreground application. - public override void OnActivated(UIApplication application) - { - Console.WriteLine("App is becoming active"); - } - - public override void OnResignActivation(UIApplication application) - { - Console.WriteLine("App moving to inactive state."); - } - - public override void WillTerminate(UIApplication application) - { - Console.WriteLine("App is terminating."); - } - - public override void DidEnterBackground(UIApplication application) - { - Console.WriteLine("App entering background state."); - - nint taskID = 0; - // if you're creating a VOIP application, this is how you set the keep alive - //UIApplication.SharedApplication.SetKeepAliveTimout(600, () => { /* keep alive handler code*/ }); - - // register a long running task, and then start it on a new thread so that this method can return - taskID = UIApplication.SharedApplication.BeginBackgroundTask(() => - { - Console.WriteLine("Running out of time to complete you background task!"); - UIApplication.SharedApplication.EndBackgroundTask(taskID); - }); - - Task.Factory.StartNew(() => FinishLongRunningTask(taskID)); - } - - private void FinishLongRunningTask(nint taskID) - { - Console.WriteLine($"Starting task {taskID}"); - Console.WriteLine($"Background time remaining: {UIApplication.SharedApplication.BackgroundTimeRemaining}"); - - // sleep for 15 seconds to simulate a long running task - System.Threading.Thread.Sleep(15000); - - Console.WriteLine($"Task {taskID} finished"); - Console.WriteLine($"Background time remaining: {UIApplication.SharedApplication.BackgroundTimeRemaining}"); - - // call our end task - UIApplication.SharedApplication.EndBackgroundTask(taskID); - } - } -} \ No newline at end of file + return true; + } + + // Runs when the activation transitions from running in the background to being the foreground application. + public override void OnActivated (UIApplication application) + { + Console.WriteLine ("App is becoming active"); + } + + public override void OnResignActivation (UIApplication application) + { + Console.WriteLine ("App moving to inactive state."); + } + + public override void WillTerminate (UIApplication application) + { + Console.WriteLine ("App is terminating."); + } + + public override void DidEnterBackground (UIApplication application) + { + Console.WriteLine ("App entering background state."); + + nint taskID = 0; + // if you're creating a VOIP application, this is how you set the keep alive + //UIApplication.SharedApplication.SetKeepAliveTimout(600, () => { /* keep alive handler code*/ }); + + // register a long running task, and then start it on a new thread so that this method can return + taskID = UIApplication.SharedApplication.BeginBackgroundTask (() => { + Console.WriteLine ("Running out of time to complete you background task!"); + UIApplication.SharedApplication.EndBackgroundTask (taskID); + }); + + Task.Factory.StartNew (() => FinishLongRunningTask (taskID)); + } + + private void FinishLongRunningTask (nint taskID) + { + Console.WriteLine ($"Starting task {taskID}"); + Console.WriteLine ($"Background time remaining: {UIApplication.SharedApplication.BackgroundTimeRemaining}"); + + // sleep for 15 seconds to simulate a long running task + System.Threading.Thread.Sleep (15000); + + Console.WriteLine ($"Task {taskID} finished"); + Console.WriteLine ($"Background time remaining: {UIApplication.SharedApplication.BackgroundTimeRemaining}"); + + // call our end task + UIApplication.SharedApplication.EndBackgroundTask (taskID); + } + } +} diff --git a/BackgroundExecution/BackgroundExecution/Main.cs b/BackgroundExecution/BackgroundExecution/Main.cs index 4a69c58a8..c180bab9c 100644 --- a/BackgroundExecution/BackgroundExecution/Main.cs +++ b/BackgroundExecution/BackgroundExecution/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace BackgroundExecution -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace BackgroundExecution { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/BackgroundExecution/BackgroundExecution/ViewController.cs b/BackgroundExecution/BackgroundExecution/ViewController.cs index bdea09336..886fdf5a2 100644 --- a/BackgroundExecution/BackgroundExecution/ViewController.cs +++ b/BackgroundExecution/BackgroundExecution/ViewController.cs @@ -1,32 +1,29 @@ -using System; +using System; using UIKit; -namespace BackgroundExecution -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) { } +namespace BackgroundExecution { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { } - partial void StartLongRunningTask(UIButton sender) - { - nint taskId = 0; + partial void StartLongRunningTask (UIButton sender) + { + nint taskId = 0; - // register our background task - taskId = UIApplication.SharedApplication.BeginBackgroundTask(() => - { - Console.WriteLine("Running out of time to complete you background task!"); - UIApplication.SharedApplication.EndBackgroundTask(taskId); - }); + // register our background task + taskId = UIApplication.SharedApplication.BeginBackgroundTask (() => { + Console.WriteLine ("Running out of time to complete you background task!"); + UIApplication.SharedApplication.EndBackgroundTask (taskId); + }); - Console.WriteLine($"Starting background task {taskId}"); + Console.WriteLine ($"Starting background task {taskId}"); - // sleep for five seconds - System.Threading.Thread.Sleep(5000); + // sleep for five seconds + System.Threading.Thread.Sleep (5000); - Console.WriteLine($"Background task {taskId} completed."); + Console.WriteLine ($"Background task {taskId} completed."); - // mark our background task as complete - UIApplication.SharedApplication.EndBackgroundTask(taskId); - } - } -} \ No newline at end of file + // mark our background task as complete + UIApplication.SharedApplication.EndBackgroundTask (taskId); + } + } +} diff --git a/BindingSample/XMBindingLibrary/ApiDefinition.cs b/BindingSample/XMBindingLibrary/ApiDefinition.cs index c2525847d..3f72f68c9 100644 --- a/BindingSample/XMBindingLibrary/ApiDefinition.cs +++ b/BindingSample/XMBindingLibrary/ApiDefinition.cs @@ -1,17 +1,15 @@ -using System; +using System; using Foundation; using ObjCRuntime; using UIKit; -namespace XMBindingLibrary -{ +namespace XMBindingLibrary { // typedef void (^XMUtilityCallback) (NSString *message); - public delegate void XMUtilityCallback(NSString message); + public delegate void XMUtilityCallback (NSString message); // @interface XMUtilities : NSObject - [BaseType(typeof(NSObject))] - interface XMUtilities - { + [BaseType (typeof (NSObject))] + interface XMUtilities { // NOTE: // We DO NOT have to bind a constructor since the default/empty // constructor will be automatically generated. @@ -25,46 +23,46 @@ interface XMUtilities // // +(NSString *) echo:(NSString *)message; [Static] - [Export("echo:")] - string Echo(string message); + [Export ("echo:")] + string Echo (string message); // NOTE: // Methods without a parameter do not need the trailing colon (":"). // // -(NSString *) speak; - [Export("speak")] - string Speak(); + [Export ("speak")] + string Speak (); // -(NSString *) speak:(XMGreeting)greeting; - [Export("speak:")] - string Speak(XMGreeting greeting); + [Export ("speak:")] + string Speak (XMGreeting greeting); // NOTE: // Methods WITH a parameter must have a trailing colon (":"). // // -(NSString *) hello:(NSString *)name; - [Export("hello:")] - string Hello(string name); + [Export ("hello:")] + string Hello (string name); // NOTE: // Here we have two parameters, and the method name // and each argument are suffxed with a colon. // // -(NSInteger) add:(NSInteger)operandUn and:(NSInteger) operandDeux; - [Export("add:and:")] - nint Add(nint operandUn, nint operandDeux); + [Export ("add:and:")] + nint Add (nint operandUn, nint operandDeux); // -(NSInteger) multiply:(NSInteger)operandUn and:(NSInteger)operandDeux; - [Export("multiply:and:")] - nint Multiply(nint operandUn, nint operandDeux); + [Export ("multiply:and:")] + nint Multiply (nint operandUn, nint operandDeux); // -(void) setCallback:(XMUtilityCallback) callback; - [Export("setCallback:")] - void SetCallback(XMUtilityCallback callback); + [Export ("setCallback:")] + void SetCallback (XMUtilityCallback callback); // -(void) invokeCallback:(NSString *) message; - [Export("invokeCallback:")] - void InvokeCallback(string message); + [Export ("invokeCallback:")] + void InvokeCallback (string message); } // NOTE: @@ -74,17 +72,16 @@ interface IXMCustomViewDelegate { } // @protocol XMCustomViewDelegate [Protocol] - [Model(AutoGeneratedName = true)] - [BaseType(typeof(NSObject))] - interface XMCustomViewDelegate - { + [Model (AutoGeneratedName = true)] + [BaseType (typeof (NSObject))] + interface XMCustomViewDelegate { // NOTE: // The [Abstract] attribute is added since this is a required member. // // @required -(void)viewWasTouched:(UIView *)view; [Abstract] - [Export("viewWasTouched:")] - void ViewWasTouched(XMCustomView view); + [Export ("viewWasTouched:")] + void ViewWasTouched (XMCustomView view); } // NOTE: @@ -94,13 +91,12 @@ interface XMCustomViewDelegate // delegate. // // @interface XMCustomView : UIView - [BaseType(typeof(UIView), - Delegates = new[] { "Delegate" }, - Events = new[] { typeof(XMCustomViewDelegate) })] - interface XMCustomView - { + [BaseType (typeof (UIView), + Delegates = new [] { "Delegate" }, + Events = new [] { typeof (XMCustomViewDelegate) })] + interface XMCustomView { // @property (nonatomic, strong) NSString* name; - [Export("name")] + [Export ("name")] string Name { get; [NullAllowed] set; } // NOTE: @@ -108,7 +104,7 @@ interface XMCustomView // be more flexible. // // @property (nonatomic, assign) id delegate; - [Export("delegate", ArgumentSemantic.Assign)] + [Export ("delegate", ArgumentSemantic.Assign)] [NullAllowed] IXMCustomViewDelegate Delegate { get; set; } @@ -117,15 +113,15 @@ interface XMCustomView // because the attribute will be used to find it. // // -(void) customizeViewWithText:(NSString *)message; - [Export("customizeViewWithText:")] - void CustomizeView(string message); + [Export ("customizeViewWithText:")] + void CustomizeView (string message); // NOTE: // This method uses the dummy interface because it accepts a protocol // and not a concrete type. // // -(void) doTouch:(id)delegate; - [Export("doTouch:")] - void DoTouch(IXMCustomViewDelegate del); + [Export ("doTouch:")] + void DoTouch (IXMCustomViewDelegate del); } } diff --git a/BindingSample/XMBindingLibrary/Extras.cs b/BindingSample/XMBindingLibrary/Extras.cs index 991fd67e7..79e0e3acf 100755 --- a/BindingSample/XMBindingLibrary/Extras.cs +++ b/BindingSample/XMBindingLibrary/Extras.cs @@ -1,15 +1,13 @@ -using System; +using System; -namespace XMBindingLibrary -{ - partial class XMUtilities - { +namespace XMBindingLibrary { + partial class XMUtilities { // NOTE: // We can add additional members in this file that were never in the // original binding. - public nint Subtract(nint operandUn, nint operandDeux) + public nint Subtract (nint operandUn, nint operandDeux) { - return Add(operandUn, -operandDeux); + return Add (operandUn, -operandDeux); } } } diff --git a/BindingSample/XMBindingLibrary/Properties/AssemblyInfo.cs b/BindingSample/XMBindingLibrary/Properties/AssemblyInfo.cs index 364ba24e1..176388f5f 100644 --- a/BindingSample/XMBindingLibrary/Properties/AssemblyInfo.cs +++ b/BindingSample/XMBindingLibrary/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using Foundation; @@ -12,20 +12,20 @@ // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. -[assembly: AssemblyTitle("XMBindingLibrary")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("Copyright © Author 2018")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("XMBindingLibrary")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("")] +[assembly: AssemblyCopyright ("Copyright © Author 2018")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. diff --git a/BindingSample/XMBindingLibrary/Structs.cs b/BindingSample/XMBindingLibrary/Structs.cs index 89a7cc90f..932d89e43 100644 --- a/BindingSample/XMBindingLibrary/Structs.cs +++ b/BindingSample/XMBindingLibrary/Structs.cs @@ -1,7 +1,5 @@ -namespace XMBindingLibrary -{ - public enum XMGreeting - { +namespace XMBindingLibrary { + public enum XMGreeting { Hello, Goodbye, } diff --git a/BindingSample/XMBindingLibrarySample/AppDelegate.cs b/BindingSample/XMBindingLibrarySample/AppDelegate.cs index 1e5c6afb5..f7b72c870 100755 --- a/BindingSample/XMBindingLibrarySample/AppDelegate.cs +++ b/BindingSample/XMBindingLibrarySample/AppDelegate.cs @@ -1,23 +1,21 @@ using Foundation; using UIKit; -namespace XMBindingLibrarySample -{ - [Register(nameof(AppDelegate))] - public partial class AppDelegate : UIApplicationDelegate - { +namespace XMBindingLibrarySample { + [Register (nameof (AppDelegate))] + public partial class AppDelegate : UIApplicationDelegate { RootViewController rootViewController; public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { - Window = new UIWindow(UIScreen.MainScreen.Bounds); + Window = new UIWindow (UIScreen.MainScreen.Bounds); - rootViewController = new RootViewController(); + rootViewController = new RootViewController (); Window.RootViewController = rootViewController; - Window.MakeKeyAndVisible(); + Window.MakeKeyAndVisible (); return true; } diff --git a/BindingSample/XMBindingLibrarySample/Main.cs b/BindingSample/XMBindingLibrarySample/Main.cs index 6a975175b..da20532fd 100755 --- a/BindingSample/XMBindingLibrarySample/Main.cs +++ b/BindingSample/XMBindingLibrarySample/Main.cs @@ -1,13 +1,11 @@ using UIKit; -namespace XMBindingLibrarySample -{ - public class Application - { +namespace XMBindingLibrarySample { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { - UIApplication.Main(args, null, nameof(AppDelegate)); + UIApplication.Main (args, null, nameof (AppDelegate)); } } } diff --git a/BindingSample/XMBindingLibrarySample/ViewControllers/CustomViewController.cs b/BindingSample/XMBindingLibrarySample/ViewControllers/CustomViewController.cs index b0fdf9153..6e3e8f84a 100755 --- a/BindingSample/XMBindingLibrarySample/ViewControllers/CustomViewController.cs +++ b/BindingSample/XMBindingLibrarySample/ViewControllers/CustomViewController.cs @@ -6,28 +6,25 @@ using XMBindingLibrary; -namespace XMBindingLibrarySample -{ - public class CustomViewController : DialogViewController - { +namespace XMBindingLibrarySample { + public class CustomViewController : DialogViewController { XMCustomView customView; - public CustomViewController() - : base(new RootElement("XMCustomView Binding") { UnevenRows = true }, true) + public CustomViewController () + : base (new RootElement ("XMCustomView Binding") { UnevenRows = true }, true) { } - public override void LoadView() + public override void LoadView () { - base.LoadView(); + base.LoadView (); - customView = new XMCustomView - { + customView = new XMCustomView { // The XMCustomView Name Property Name = "Xamarin User", // The instance method uses a frame calculation. - Frame = new CGRect(10, 10, View.Bounds.Width - 40, 150), + Frame = new CGRect (10, 10, View.Bounds.Width - 40, 150), }; // This is the custom event we bound. @@ -39,9 +36,9 @@ public override void LoadView() // customView.Delegate = new CustomViewDelegate(); // The instance method we bound. - customView.CustomizeView($"Yo {customView.Name}, I heard you like bindings! Xamarin makes it super easy with binding projects. Try it out!"); + customView.CustomizeView ($"Yo {customView.Name}, I heard you like bindings! Xamarin makes it super easy with binding projects. Try it out!"); - Root.Add(new[] + Root.Add (new [] { new Section("Custom View") { @@ -57,15 +54,15 @@ public override void LoadView() }); } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); NavigationItem.HidesBackButton = false; - NavigationItem.BackBarButtonItem = new UIBarButtonItem("Utilities", UIBarButtonItemStyle.Plain, null); + NavigationItem.BackBarButtonItem = new UIBarButtonItem ("Utilities", UIBarButtonItemStyle.Plain, null); } - void Handle_UseEvent() + void Handle_UseEvent () { customView.Delegate = null; @@ -73,47 +70,44 @@ void Handle_UseEvent() customView.ViewWasTouched += Handle_CustomViewViewWasTouched; } - void Handle_UseDelegate() + void Handle_UseDelegate () { // set the delegate - customView.Delegate = new CustomViewDelegate(this); + customView.Delegate = new CustomViewDelegate (this); } - void Handle_DoTouchOperation() + void Handle_DoTouchOperation () { - using (var temp = new CustomViewDelegate(this)) - { - customView.DoTouch(temp); + using (var temp = new CustomViewDelegate (this)) { + customView.DoTouch (temp); } } - void Handle_CustomViewViewWasTouched(object sender, EventArgs e) + void Handle_CustomViewViewWasTouched (object sender, EventArgs e) { - Handle_ViewTouched("EVENT"); + Handle_ViewTouched ("EVENT"); } - void Handle_ViewTouched(string where) + void Handle_ViewTouched (string where) { - NSThread.Current.BeginInvokeOnMainThread(() => - { - var vc = UIAlertController.Create("Touched", $"Our bound XMCustomView was touched from the {where}!", UIAlertControllerStyle.Alert); - vc.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - PresentViewController(vc, true, null); + NSThread.Current.BeginInvokeOnMainThread (() => { + var vc = UIAlertController.Create ("Touched", $"Our bound XMCustomView was touched from the {where}!", UIAlertControllerStyle.Alert); + vc.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + PresentViewController (vc, true, null); }); } - class CustomViewDelegate : XMCustomViewDelegate - { + class CustomViewDelegate : XMCustomViewDelegate { CustomViewController viewController; - public CustomViewDelegate(CustomViewController viewController) + public CustomViewDelegate (CustomViewController viewController) { this.viewController = viewController; } - public override void ViewWasTouched(XMCustomView view) + public override void ViewWasTouched (XMCustomView view) { - viewController.Handle_ViewTouched("DELEGATE"); + viewController.Handle_ViewTouched ("DELEGATE"); } } } diff --git a/BindingSample/XMBindingLibrarySample/ViewControllers/RootViewController.cs b/BindingSample/XMBindingLibrarySample/ViewControllers/RootViewController.cs index a5c3f5758..374008719 100755 --- a/BindingSample/XMBindingLibrarySample/ViewControllers/RootViewController.cs +++ b/BindingSample/XMBindingLibrarySample/ViewControllers/RootViewController.cs @@ -1,23 +1,21 @@ using UIKit; -namespace XMBindingLibrarySample -{ - public class RootViewController : UINavigationController - { +namespace XMBindingLibrarySample { + public class RootViewController : UINavigationController { UtilitiesViewController utilViewController; - public override void LoadView() + public override void LoadView () { - base.LoadView(); + base.LoadView (); - utilViewController = new UtilitiesViewController(); + utilViewController = new UtilitiesViewController (); } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - PushViewController(utilViewController, true); + PushViewController (utilViewController, true); } } } diff --git a/BindingSample/XMBindingLibrarySample/ViewControllers/UtilitiesViewController.cs b/BindingSample/XMBindingLibrarySample/ViewControllers/UtilitiesViewController.cs index 9a8dccd5a..38b233d13 100755 --- a/BindingSample/XMBindingLibrarySample/ViewControllers/UtilitiesViewController.cs +++ b/BindingSample/XMBindingLibrarySample/ViewControllers/UtilitiesViewController.cs @@ -3,29 +3,26 @@ using XMBindingLibrary; -namespace XMBindingLibrarySample -{ - public class UtilitiesViewController : DialogViewController - { +namespace XMBindingLibrarySample { + public class UtilitiesViewController : DialogViewController { XMUtilities utility; - public UtilitiesViewController() - : base(new RootElement("XMUtilities Binding"), true) + public UtilitiesViewController () + : base (new RootElement ("XMUtilities Binding"), true) { } - public override void LoadView() + public override void LoadView () { - base.LoadView(); + base.LoadView (); - utility = new XMUtilities(); + utility = new XMUtilities (); - utility.SetCallback(new XMUtilityCallback(message => - { - SetResultElementValue("Callback: " + message); + utility.SetCallback (new XMUtilityCallback (message => { + SetResultElementValue ("Callback: " + message); })); - Root.Add(new[] + Root.Add (new [] { new Section("Operands") { @@ -62,75 +59,73 @@ public override void LoadView() }); } - void Handle_AddOperation() + void Handle_AddOperation () { - var one = Root[0][1] as EntryElement; - var two = Root[0][2] as EntryElement; + var one = Root [0] [1] as EntryElement; + var two = Root [0] [2] as EntryElement; - int.TryParse(one.Value, out var un); - int.TryParse(two.Value, out var deux); + int.TryParse (one.Value, out var un); + int.TryParse (two.Value, out var deux); - SetResultElementValue($"{utility.Add(un, deux)}"); + SetResultElementValue ($"{utility.Add (un, deux)}"); } - void Handle_SubtractOperation() + void Handle_SubtractOperation () { - var one = Root[0][1] as EntryElement; - var two = Root[0][2] as EntryElement; + var one = Root [0] [1] as EntryElement; + var two = Root [0] [2] as EntryElement; - int.TryParse(one.Value, out var un); - int.TryParse(two.Value, out var deux); + int.TryParse (one.Value, out var un); + int.TryParse (two.Value, out var deux); - SetResultElementValue($"{utility.Subtract(un, deux)}"); + SetResultElementValue ($"{utility.Subtract (un, deux)}"); } - void Handle_MultiplyOperation() + void Handle_MultiplyOperation () { - var one = Root[0][1] as EntryElement; - var two = Root[0][2] as EntryElement; + var one = Root [0] [1] as EntryElement; + var two = Root [0] [2] as EntryElement; - int.TryParse(one.Value, out var un); - int.TryParse(two.Value, out var deux); + int.TryParse (one.Value, out var un); + int.TryParse (two.Value, out var deux); - SetResultElementValue($"{utility.Multiply(un, deux)}"); + SetResultElementValue ($"{utility.Multiply (un, deux)}"); } - void Handle_EchoOperation() + void Handle_EchoOperation () { - var nameElement = Root[0][0] as EntryElement; - SetResultElementValue(XMUtilities.Echo(nameElement.Value)); + var nameElement = Root [0] [0] as EntryElement; + SetResultElementValue (XMUtilities.Echo (nameElement.Value)); } - void Handle_SpeakOperation() + void Handle_SpeakOperation () { - SetResultElementValue(utility.Speak()); + SetResultElementValue (utility.Speak ()); } - void Handle_SpeakGreetingOperation() + void Handle_SpeakGreetingOperation () { - SetResultElementValue(utility.Speak(XMGreeting.Goodbye)); + SetResultElementValue (utility.Speak (XMGreeting.Goodbye)); } - void Handle_HelloOperation() + void Handle_HelloOperation () { - var nameElement = Root[0][0] as EntryElement; - SetResultElementValue(utility.Hello(nameElement.Value)); + var nameElement = Root [0] [0] as EntryElement; + SetResultElementValue (utility.Hello (nameElement.Value)); } - void Handle_InvokeCallback() + void Handle_InvokeCallback () { - utility.InvokeCallback("Callback invoked!"); + utility.InvokeCallback ("Callback invoked!"); } - void SetResultElementValue(string value) + void SetResultElementValue (string value) { - NSThread.Current.BeginInvokeOnMainThread(() => - { - if (Root[1][0] is StringElement e) - { + NSThread.Current.BeginInvokeOnMainThread (() => { + if (Root [1] [0] is StringElement e) { e.Caption = value; - TableView.ReloadData(); + TableView.ReloadData (); } }); } diff --git a/BouncingGameCompleteiOS/BouncingGame.iOS/AppDelegate.cs b/BouncingGameCompleteiOS/BouncingGame.iOS/AppDelegate.cs index 74f5810e1..7b63f6dcb 100644 --- a/BouncingGameCompleteiOS/BouncingGame.iOS/AppDelegate.cs +++ b/BouncingGameCompleteiOS/BouncingGame.iOS/AppDelegate.cs @@ -6,11 +6,9 @@ using UIKit; using CocosSharp; -namespace BouncingGame.iOS -{ +namespace BouncingGame.iOS { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override void FinishedLaunching (UIApplication app) { var application = new CCApplication (); diff --git a/BouncingGameCompleteiOS/BouncingGame.iOS/GameContainer.cs b/BouncingGameCompleteiOS/BouncingGame.iOS/GameContainer.cs index dfa6c47ed..8d13317cd 100644 --- a/BouncingGameCompleteiOS/BouncingGame.iOS/GameContainer.cs +++ b/BouncingGameCompleteiOS/BouncingGame.iOS/GameContainer.cs @@ -1,10 +1,8 @@ -using System; +using System; using CocosSharp; -namespace BouncingGame.iOS -{ - public class GameContainer - { +namespace BouncingGame.iOS { + public class GameContainer { public GameContainer () { } diff --git a/BouncingGameCompleteiOS/BouncingGame.iOS/Main.cs b/BouncingGameCompleteiOS/BouncingGame.iOS/Main.cs index e8005d9d9..b70f119ef 100644 --- a/BouncingGameCompleteiOS/BouncingGame.iOS/Main.cs +++ b/BouncingGameCompleteiOS/BouncingGame.iOS/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace BouncingGame.iOS -{ - public class Application - { +namespace BouncingGame.iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/BouncingGameCompleteiOS/BouncingGame/GameAppDelegate.cs b/BouncingGameCompleteiOS/BouncingGame/GameAppDelegate.cs index 2317d3bfd..b431ae778 100644 --- a/BouncingGameCompleteiOS/BouncingGame/GameAppDelegate.cs +++ b/BouncingGameCompleteiOS/BouncingGame/GameAppDelegate.cs @@ -1,17 +1,15 @@ -using System; +using System; using CocosSharp; -namespace BouncingGame -{ - public class GameAppDelegate : CCApplicationDelegate - { +namespace BouncingGame { + public class GameAppDelegate : CCApplicationDelegate { public override void ApplicationDidFinishLaunching (CCApplication application, CCWindow mainWindow) { application.PreferMultiSampling = false; application.ContentRootDirectory = "Content"; var bounds = mainWindow.WindowSizeInPixels; - CCScene.SetDefaultDesignResolution(bounds.Width, bounds.Height, CCSceneResolutionPolicy.ShowAll); + CCScene.SetDefaultDesignResolution (bounds.Width, bounds.Height, CCSceneResolutionPolicy.ShowAll); GameScene gameScene = new GameScene (mainWindow); mainWindow.RunWithScene (gameScene); diff --git a/BouncingGameCompleteiOS/BouncingGame/GameScene.cs b/BouncingGameCompleteiOS/BouncingGame/GameScene.cs index 09a11e17c..e3fa1538a 100644 --- a/BouncingGameCompleteiOS/BouncingGame/GameScene.cs +++ b/BouncingGameCompleteiOS/BouncingGame/GameScene.cs @@ -1,10 +1,8 @@ -using System; +using System; using CocosSharp; -namespace BouncingGame -{ - public class GameScene : CCScene - { +namespace BouncingGame { + public class GameScene : CCScene { CCLayer mainLayer; CCSprite paddleSprite; CCSprite ballSprite; @@ -19,7 +17,7 @@ public class GameScene : CCScene int score; - public GameScene(CCWindow mainWindow) : base(mainWindow) + public GameScene (CCWindow mainWindow) : base (mainWindow) { mainLayer = new CCLayer (); AddChild (mainLayer); @@ -55,7 +53,7 @@ void HandleTouchesMoved (System.Collections.Generic.List touches, CCEve paddleSprite.PositionX = locationOnScreen.X; } - void RunGameLogic(float frameTimeInSeconds) + void RunGameLogic (float frameTimeInSeconds) { // This is a linear approximation of gravity, but it's good enough for this game ballYVelocity += frameTimeInSeconds * -gravity; @@ -63,15 +61,14 @@ void RunGameLogic(float frameTimeInSeconds) ballSprite.PositionX += ballXVelocity * frameTimeInSeconds; ballSprite.PositionY += ballYVelocity * frameTimeInSeconds; - //////////////////////////New Code Starts here:///////////////////////// + //////////////////////////New Code Starts here:///////////////////////// // Check if the two CCSprites overlap... - bool doesBallOverlapPaddle = ballSprite.BoundingBoxTransformedToParent.IntersectsRect( + bool doesBallOverlapPaddle = ballSprite.BoundingBoxTransformedToParent.IntersectsRect ( paddleSprite.BoundingBoxTransformedToParent); // ... and if the ball is moving downward. bool isMovingDownward = ballYVelocity < 0; - if (doesBallOverlapPaddle && isMovingDownward) - { + if (doesBallOverlapPaddle && isMovingDownward) { // First let's invert the velocity: ballYVelocity *= -1; // Then let's assign a random to the ball's x velocity: @@ -91,12 +88,11 @@ void RunGameLogic(float frameTimeInSeconds) float screenLeft = mainLayer.VisibleBoundsWorldspace.MinX; - bool shouldReflectXVelocity = + bool shouldReflectXVelocity = (ballRight > screenRight && ballXVelocity > 0) || (ballLeft < screenLeft && ballXVelocity < 0); - if (shouldReflectXVelocity) - { + if (shouldReflectXVelocity) { ballXVelocity *= -1; } diff --git a/BouncingGameCompleteiOS/BouncingGame/Properties/AssemblyInfo.cs b/BouncingGameCompleteiOS/BouncingGame/Properties/AssemblyInfo.cs index 884243f9d..b5cac7c2c 100644 --- a/BouncingGameCompleteiOS/BouncingGame/Properties/AssemblyInfo.cs +++ b/BouncingGameCompleteiOS/BouncingGame/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/BouncingGameEmptyiOS/BouncingGame.iOS/AppDelegate.cs b/BouncingGameEmptyiOS/BouncingGame.iOS/AppDelegate.cs index 74f5810e1..7b63f6dcb 100644 --- a/BouncingGameEmptyiOS/BouncingGame.iOS/AppDelegate.cs +++ b/BouncingGameEmptyiOS/BouncingGame.iOS/AppDelegate.cs @@ -6,11 +6,9 @@ using UIKit; using CocosSharp; -namespace BouncingGame.iOS -{ +namespace BouncingGame.iOS { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override void FinishedLaunching (UIApplication app) { var application = new CCApplication (); diff --git a/BouncingGameEmptyiOS/BouncingGame.iOS/GameContainer.cs b/BouncingGameEmptyiOS/BouncingGame.iOS/GameContainer.cs index dfa6c47ed..8d13317cd 100644 --- a/BouncingGameEmptyiOS/BouncingGame.iOS/GameContainer.cs +++ b/BouncingGameEmptyiOS/BouncingGame.iOS/GameContainer.cs @@ -1,10 +1,8 @@ -using System; +using System; using CocosSharp; -namespace BouncingGame.iOS -{ - public class GameContainer - { +namespace BouncingGame.iOS { + public class GameContainer { public GameContainer () { } diff --git a/BouncingGameEmptyiOS/BouncingGame.iOS/Main.cs b/BouncingGameEmptyiOS/BouncingGame.iOS/Main.cs index e8005d9d9..b70f119ef 100644 --- a/BouncingGameEmptyiOS/BouncingGame.iOS/Main.cs +++ b/BouncingGameEmptyiOS/BouncingGame.iOS/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace BouncingGame.iOS -{ - public class Application - { +namespace BouncingGame.iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/BouncingGameEmptyiOS/BouncingGame/GameAppDelegate.cs b/BouncingGameEmptyiOS/BouncingGame/GameAppDelegate.cs index ba13fbc4b..011ec7881 100644 --- a/BouncingGameEmptyiOS/BouncingGame/GameAppDelegate.cs +++ b/BouncingGameEmptyiOS/BouncingGame/GameAppDelegate.cs @@ -1,17 +1,15 @@ -using System; +using System; using CocosSharp; -namespace BouncingGame -{ - public class GameAppDelegate : CCApplicationDelegate - { +namespace BouncingGame { + public class GameAppDelegate : CCApplicationDelegate { public override void ApplicationDidFinishLaunching (CCApplication application, CCWindow mainWindow) { application.PreferMultiSampling = false; application.ContentRootDirectory = "Content"; var bounds = mainWindow.WindowSizeInPixels; - CCScene.SetDefaultDesignResolution(bounds.Width, bounds.Height, CCSceneResolutionPolicy.ShowAll); + CCScene.SetDefaultDesignResolution (bounds.Width, bounds.Height, CCSceneResolutionPolicy.ShowAll); // todo: Add our GameScene initialization here } diff --git a/BouncingGameEmptyiOS/BouncingGame/Properties/AssemblyInfo.cs b/BouncingGameEmptyiOS/BouncingGame/Properties/AssemblyInfo.cs index 884243f9d..b5cac7c2c 100644 --- a/BouncingGameEmptyiOS/BouncingGame/Properties/AssemblyInfo.cs +++ b/BouncingGameEmptyiOS/BouncingGame/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/ButtonEventDemo/AppDelegate.cs b/ButtonEventDemo/AppDelegate.cs index f94a05890..bdb16425b 100644 --- a/ButtonEventDemo/AppDelegate.cs +++ b/ButtonEventDemo/AppDelegate.cs @@ -4,35 +4,33 @@ using Foundation; using UIKit; -namespace ButtonEventDemo -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; - ButtonEventDemoViewController viewController; +namespace ButtonEventDemo { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; + ButtonEventDemoViewController viewController; - // - // This method is invoked when the application has loaded and is ready to run. In this - // method you should instantiate the window, load the UI into it and then make the window - // visible. - // - // You have 17 seconds to return from this method, or iOS will terminate your application. - // - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); - viewController = new ButtonEventDemoViewController ("ButtonEventDemoViewController", null); - window.RootViewController = viewController; - window.MakeKeyAndVisible (); + viewController = new ButtonEventDemoViewController ("ButtonEventDemoViewController", null); + window.RootViewController = viewController; + window.MakeKeyAndVisible (); - return true; - } + return true; + } - } + } } diff --git a/ButtonEventDemo/ButtonEventDemoViewController.cs b/ButtonEventDemo/ButtonEventDemoViewController.cs index 22a868944..f61a0bbc2 100644 --- a/ButtonEventDemo/ButtonEventDemoViewController.cs +++ b/ButtonEventDemo/ButtonEventDemoViewController.cs @@ -3,61 +3,59 @@ using System; using Foundation; -namespace ButtonEventDemo -{ - public partial class ButtonEventDemoViewController : UIViewController - { - public ButtonEventDemoViewController (string nibName, NSBundle bundle) : base (nibName, bundle) - { - } - - public override void DidReceiveMemoryWarning () - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning (); - - // Release any cached data, images, etc that aren't in use. - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - //Here we register for the TouchUpInside event using an outlet to - //the UIButton created in Interface Builder. Also see the target-action - //approach for accomplishing the same thing below. - aButton.TouchUpInside += (o,s) => { - Console.WriteLine ("button touched using a TouchUpInside event"); +namespace ButtonEventDemo { + public partial class ButtonEventDemoViewController : UIViewController { + public ButtonEventDemoViewController (string nibName, NSBundle bundle) : base (nibName, bundle) + { + } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + //Here we register for the TouchUpInside event using an outlet to + //the UIButton created in Interface Builder. Also see the target-action + //approach for accomplishing the same thing below. + aButton.TouchUpInside += (o, s) => { + Console.WriteLine ("button touched using a TouchUpInside event"); }; - //You could also use a C# 2.0 style anonymous function -// aButton.TouchUpInside += delegate { -// Console.WriteLine ("button touched"); -// }; + //You could also use a C# 2.0 style anonymous function + // aButton.TouchUpInside += delegate { + // Console.WriteLine ("button touched"); + // }; - } + } - public override void ViewDidUnload () - { - base.ViewDidUnload (); + public override void ViewDidUnload () + { + base.ViewDidUnload (); - aButton = null; - } + aButton = null; + } - public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) - { - // Return true for supported orientations - return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); - } + public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) + { + // Return true for supported orientations + return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); + } - //This is an action method connected to the TouchUpInside event - //of a UIButton. The action is connected via Interface Builder - //The same thing can be accomplished with a .NET event registered - //to the UIButton in code, as we do in the ViewDidLoad method above. + //This is an action method connected to the TouchUpInside event + //of a UIButton. The action is connected via Interface Builder + //The same thing can be accomplished with a .NET event registered + //to the UIButton in code, as we do in the ViewDidLoad method above. - partial void HandleButtonTouch (NSObject sender) - { + partial void HandleButtonTouch (NSObject sender) + { Console.WriteLine ("button touched using the action method"); - } - } + } + } } diff --git a/ButtonEventDemo/Main.cs b/ButtonEventDemo/Main.cs index fadd0273d..7386a90cf 100644 --- a/ButtonEventDemo/Main.cs +++ b/ButtonEventDemo/Main.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace ButtonEventDemo -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace ButtonEventDemo { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ButtonTapper3000/ButtonTapper3000/AppDelegate.cs b/ButtonTapper3000/ButtonTapper3000/AppDelegate.cs index 8b29eccda..a3bab614e 100644 --- a/ButtonTapper3000/ButtonTapper3000/AppDelegate.cs +++ b/ButtonTapper3000/ButtonTapper3000/AppDelegate.cs @@ -41,7 +41,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ButtonTapper3000/ButtonTapper3000/Model/GameInfo.cs b/ButtonTapper3000/ButtonTapper3000/Model/GameInfo.cs index 574d72d15..86b86f0f5 100644 --- a/ButtonTapper3000/ButtonTapper3000/Model/GameInfo.cs +++ b/ButtonTapper3000/ButtonTapper3000/Model/GameInfo.cs @@ -44,7 +44,7 @@ public static GameTime GameTime { public static GKChallenge Challenge; public static GKLeaderboardSet CurrentSet; public static GKLeaderboard CurrentLeaderBoard; - public static int[] GameTimes; + public static int [] GameTimes; public static int CurrentTicks; static GameInfo () @@ -53,12 +53,12 @@ static GameInfo () GameTimes = new [] { 15, 30, 45 }; GameTime = GameTime.Fifteen; CurrentTaps = 0; - CurrentTicks = GameTimes [(int)GameTime]; + CurrentTicks = GameTimes [(int) GameTime]; } public static int GameTimeInSeconds { get { - return GameTimes [(int)GameTime]; + return GameTimes [(int) GameTime]; } } @@ -66,7 +66,7 @@ public static void ResetGame () { CurrentTaps = 0; Challenge = null; - CurrentTicks = GameTimes [(int)GameTime]; + CurrentTicks = GameTimes [(int) GameTime]; } } } diff --git a/ButtonTapper3000/ButtonTapper3000/Scenes/BasicScene.cs b/ButtonTapper3000/ButtonTapper3000/Scenes/BasicScene.cs index 62a9b7993..a684b5547 100644 --- a/ButtonTapper3000/ButtonTapper3000/Scenes/BasicScene.cs +++ b/ButtonTapper3000/ButtonTapper3000/Scenes/BasicScene.cs @@ -29,8 +29,8 @@ public BasicScene (CGSize size) : base (size) ButtonColor = UIColor.FromRGBA (1f, 1f, 0f, 1f); InfoColor = UIColor.FromRGBA (1f, 1f, 1f, 1f); - FrameMidX = (float)Frame.GetMidX (); - FrameMidY = (float)Frame.GetMidY (); + FrameMidX = (float) Frame.GetMidX (); + FrameMidY = (float) Frame.GetMidY (); transition = SKTransition.MoveInWithDirection (SKTransitionDirection.Up, 0.5); } diff --git a/ButtonTapper3000/ButtonTapper3000/Scenes/GameSetupMenu.cs b/ButtonTapper3000/ButtonTapper3000/Scenes/GameSetupMenu.cs index f71550a7b..77a05f292 100644 --- a/ButtonTapper3000/ButtonTapper3000/Scenes/GameSetupMenu.cs +++ b/ButtonTapper3000/ButtonTapper3000/Scenes/GameSetupMenu.cs @@ -39,7 +39,7 @@ public GameSetupMenu (CGSize size) : base (size) FontColor = UnselectedColor, Position = new CGPoint (FrameMidX + 40, FrameMidY + 40) }; - timeLabels = new SKLabelNode[] { time15Button, time30Button, time45Button }; + timeLabels = new SKLabelNode [] { time15Button, time30Button, time45Button }; SKLabelNode modeLabel = new SKLabelNode ("GillSans-Bold") { Text = "Mode", @@ -73,8 +73,8 @@ public GameSetupMenu (CGSize size) : base (size) Position = new CGPoint (FrameMidX, FrameMidY - 200) }; - timeLabels [(int)GameInfo.GameTime].FontColor = SelectedColor; - modeLabels [(int)GameInfo.GameMode].FontColor = SelectedColor; + timeLabels [(int) GameInfo.GameTime].FontColor = SelectedColor; + modeLabels [(int) GameInfo.GameMode].FontColor = SelectedColor; GameInfo.ResetGame (); @@ -92,15 +92,15 @@ public GameSetupMenu (CGSize size) : base (size) void SelectTime (int time) { - timeLabels [(int)GameInfo.GameTime].FontColor = UnselectedColor; - GameInfo.GameTime = (GameTime)time; + timeLabels [(int) GameInfo.GameTime].FontColor = UnselectedColor; + GameInfo.GameTime = (GameTime) time; timeLabels [time].FontColor = SelectedColor; } void SelectMode (int mode) { - modeLabels [(int)GameInfo.GameMode].FontColor = UnselectedColor; - GameInfo.GameMode = (GameMode)mode; + modeLabels [(int) GameInfo.GameMode].FontColor = UnselectedColor; + GameInfo.GameMode = (GameMode) mode; modeLabels [mode].FontColor = SelectedColor; } @@ -109,14 +109,14 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) foreach (var touch in touches) { CGPoint location = (touch as UITouch).LocationInNode (this); - for (int i = 0; i < (int)GameTime.Max; i++) { + for (int i = 0; i < (int) GameTime.Max; i++) { if (timeLabels [i].ContainsPoint (location)) { SelectTime (i); break; } } - for (int i = 0; i < (int)GameMode.Max; i++) { + for (int i = 0; i < (int) GameMode.Max; i++) { if (modeLabels [i].ContainsPoint (location)) { SelectMode (i); break; diff --git a/ButtonTapper3000/ButtonTapper3000/Scenes/MainGame.cs b/ButtonTapper3000/ButtonTapper3000/Scenes/MainGame.cs index 2bf5e3823..d52b72531 100644 --- a/ButtonTapper3000/ButtonTapper3000/Scenes/MainGame.cs +++ b/ButtonTapper3000/ButtonTapper3000/Scenes/MainGame.cs @@ -34,13 +34,14 @@ public MainGame (CGSize size) : base (size) GameInfo.CurrentTaps = 0; gameTimer = NSTimer.CreateScheduledTimer (GameInfo.GameTimeInSeconds, async (t) => { - gameTimer.Dispose(); + gameTimer.Dispose (); gameTimer = null; await TimerDone (); }); - tickTimer = NSTimer.CreateRepeatingScheduledTimer (1.0, async delegate { - GameInfo.CurrentTicks --; + tickTimer = NSTimer.CreateRepeatingScheduledTimer (1.0, async delegate + { + GameInfo.CurrentTicks--; if (GameInfo.CurrentTicks < 0) { GameInfo.CurrentTicks = 0; await TimerDone (); @@ -77,7 +78,7 @@ public override async void TouchesBegan (NSSet touches, UIEvent evt) var location = (touch as UITouch).LocationInNode (this); if (button.ContainsPoint (location)) { - GameInfo.CurrentTaps ++; + GameInfo.CurrentTaps++; if (GameInfo.GameMode == GameMode.Hard) { int x = rand.Next (100) - 50; @@ -162,7 +163,7 @@ async Task ReportScore () int playedGameTypesBitField; using (NSUserDefaults defaults = NSUserDefaults.StandardUserDefaults) { - playedGameTypesBitField = (int)defaults.IntForKey ("playedGameTypes") | (int) gameType; + playedGameTypesBitField = (int) defaults.IntForKey ("playedGameTypes") | (int) gameType; defaults.SetInt (playedGameTypesBitField, "playedGameTypes"); defaults.Synchronize (); } @@ -195,17 +196,17 @@ async Task UpdateCurrentTapsLeaderboardAndTapAchievements () if (scores != null && scores.Length > 1) { currentScore = scores [0]; - int oldTaps = (int)currentScore.Context; - int oldTime = (int)currentScore.Value * oldTaps; + int oldTaps = (int) currentScore.Context; + int oldTime = (int) currentScore.Value * oldTaps; int newTime = oldTime + GameInfo.GameTimeInSeconds * 100; int newTaps = oldTaps + GameInfo.CurrentTaps; newScore.Value = newTime / newTaps; - newScore.Context = (ulong)newTaps; + newScore.Context = (ulong) newTaps; } else { newScore.Value = GameInfo.GameTimeInSeconds / Math.Max (GameInfo.CurrentTaps, 1) * 100; - newScore.Context = (ulong)GameInfo.CurrentTaps; + newScore.Context = (ulong) GameInfo.CurrentTaps; } GKAchievement playAHundred = new GKAchievement (Tap100Id, GKLocalPlayer.LocalPlayer.PlayerID) { diff --git a/ButtonTapper3000/ButtonTapper3000/Scenes/MainMenu.cs b/ButtonTapper3000/ButtonTapper3000/Scenes/MainMenu.cs index 9ebeb1df2..e52d952d5 100644 --- a/ButtonTapper3000/ButtonTapper3000/Scenes/MainMenu.cs +++ b/ButtonTapper3000/ButtonTapper3000/Scenes/MainMenu.cs @@ -99,7 +99,7 @@ async void SetupChallenge () void SelectChallenge (GKScoreChallenge challenge) { string leaderboardID = challenge.Score.LeaderboardIdentifier; - string[] substrings = leaderboardID.Split ('.'); + string [] substrings = leaderboardID.Split ('.'); string leaderboardSubstring = substrings [substrings.Length - 1]; string timeString = leaderboardSubstring.Substring (0, 9); string modeString = leaderboardSubstring.Substring (9); @@ -147,13 +147,14 @@ async void ChallengeFriends () GKScore score = new GKScore () { LeaderboardIdentifier = MainGame.Prefix + "15secondseasymode", - Context = (ulong)GameTypePlayed.Easy15, + Context = (ulong) GameTypePlayed.Easy15, Value = 10 }; UIViewController challengeController = score.ChallengeComposeController ( GKLocalPlayer.LocalPlayer.Friends, "Beat it!", - delegate (UIViewController composeController, bool didIssueChallenge, string[] sentPlayerIDs) { + delegate (UIViewController composeController, bool didIssueChallenge, string [] sentPlayerIDs) + { AppDelegate.Shared.ViewController.DismissViewController (true, null); } ); @@ -179,8 +180,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) } } - class PlayerListener : GKLocalPlayerListener - { + class PlayerListener : GKLocalPlayerListener { public Action DidReceiveChallengeAction; public override void DidReceiveChallenge (GKPlayer player, GKChallenge challenge) diff --git a/ButtonTapper3000/ButtonTapper3000/Scenes/StatsScreen.cs b/ButtonTapper3000/ButtonTapper3000/Scenes/StatsScreen.cs index 8f8c2f18a..2cdd60a71 100644 --- a/ButtonTapper3000/ButtonTapper3000/Scenes/StatsScreen.cs +++ b/ButtonTapper3000/ButtonTapper3000/Scenes/StatsScreen.cs @@ -54,7 +54,7 @@ public StatsScreen (CGSize size) : base (size) public override void TouchesBegan (NSSet touches, UIEvent evt) { - foreach (var touch in touches) { + foreach (var touch in touches) { var location = (touch as UITouch).LocationInNode (this); if (leaderboardsButton.ContainsPoint (location)) { @@ -108,12 +108,13 @@ public AchievementsScreen (CGSize size) : base (size) AddChild (backButton); } - void LoadAchievementInfo (GKAchievementDescription[] descriptions, NSError error) + void LoadAchievementInfo (GKAchievementDescription [] descriptions, NSError error) { if (descriptions == null) return; - GKAchievement.LoadAchievements (delegate (GKAchievement[] achievements, NSError err) { + GKAchievement.LoadAchievements (delegate (GKAchievement [] achievements, NSError err) + { int completeOffset = 0; int incompleteOffset = 0; @@ -134,7 +135,8 @@ void LoadAchievementInfo (GKAchievementDescription[] descriptions, NSError error }; AddChild (achievementLabel); - description.LoadImage (delegate (UIImage image, NSError imageError) { + description.LoadImage (delegate (UIImage image, NSError imageError) + { if (image == null) image = UIImage.FromFile ("Images/DefaultPlayerPhoto.png"); var sprite = SKSpriteNode.FromTexture (SKTexture.FromImage (image), new CGSize (32, 32)); @@ -162,7 +164,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) public class LeaderboardSetsScreen : BasicScene { SKLabelNode backButton; - GKLeaderboardSet[] leaderboardSets; + GKLeaderboardSet [] leaderboardSets; List leaderboardSetButtons; public LeaderboardSetsScreen (CGSize size) : base (size) @@ -189,7 +191,7 @@ public LeaderboardSetsScreen (CGSize size) : base (size) AddChild (backButton); } - void LoadLeaderboardSets (GKLeaderboardSet[] leaderboardSets, NSError error) + void LoadLeaderboardSets (GKLeaderboardSet [] leaderboardSets, NSError error) { this.leaderboardSets = leaderboardSets; if (leaderboardSets == null) @@ -262,7 +264,7 @@ public LeaderboardsScreen (CGSize size) : base (size) AddChild (backButton); } - void LoadLeaderboard (GKLeaderboard[] leaderboards, NSError error) + void LoadLeaderboard (GKLeaderboard [] leaderboards, NSError error) { this.leaderboards = leaderboards; int offset = 0; @@ -334,7 +336,7 @@ public LeaderboardScoresScreen (CGSize size) : base (size) void DisplayScore (GKScore score, int rank, GKPlayer player) { - CGPoint[] podiumPositions = new CGPoint[] { + CGPoint [] podiumPositions = new CGPoint [] { new CGPoint (0, 100), new CGPoint (-84, 75), new CGPoint (84, 50) @@ -348,7 +350,8 @@ void DisplayScore (GKScore score, int rank, GKPlayer player) Position = new CGPoint (FrameMidX + currentPoint.X, FrameMidY + currentPoint.Y - 32) }; - player.LoadPhoto (GKPhotoSize.Small, delegate (UIImage photo, NSError error) { + player.LoadPhoto (GKPhotoSize.Small, delegate (UIImage photo, NSError error) + { if (photo == null) photo = UIImage.FromFile ("Images/DefaultPlayerPhoto.png"); var image = SKSpriteNode.FromTexture (SKTexture.FromImage (photo), new CGSize (32, 32)); @@ -369,9 +372,10 @@ async void LoadLeaderboardScoresInfo (GKLeaderboard leaderboard) string [] identifiers = new string [scores.Length]; int n = 0; foreach (var score in scores) - identifiers [n++] = score.Player.ToString(); + identifiers [n++] = score.Player.ToString (); - GKPlayer.LoadPlayersForIdentifiers (identifiers, delegate (GKPlayer[] players, NSError error) { + GKPlayer.LoadPlayersForIdentifiers (identifiers, delegate (GKPlayer [] players, NSError error) + { for (int i = 0; i < scores.Length; i++) DisplayScore (scores [i], i, players [i]); }); diff --git a/Calendars/Calendars/AppDelegate.cs b/Calendars/Calendars/AppDelegate.cs index 794c17d0a..8f6094010 100644 --- a/Calendars/Calendars/AppDelegate.cs +++ b/Calendars/Calendars/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Calendars -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace Calendars { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/Calendars/Calendars/CalendarsViewController.cs b/Calendars/Calendars/CalendarsViewController.cs index 6bfe2ac2c..b825a374a 100644 --- a/Calendars/Calendars/CalendarsViewController.cs +++ b/Calendars/Calendars/CalendarsViewController.cs @@ -3,34 +3,32 @@ using System; using UIKit; -namespace Calendars -{ - public partial class CalendarsViewController : UITableViewController - { - private EKCalendar[] calendars; +namespace Calendars { + public partial class CalendarsViewController : UITableViewController { + private EKCalendar [] calendars; - public CalendarsViewController(IntPtr handle) : base(handle) { } + public CalendarsViewController (IntPtr handle) : base (handle) { } - public EKEntityType EntityType { get; set; } + public EKEntityType EntityType { get; set; } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - // get calendars of the particular type (either events or reminders) - this.calendars = MainViewController.EventStore.GetCalendars(this.EntityType); - } + // get calendars of the particular type (either events or reminders) + this.calendars = MainViewController.EventStore.GetCalendars (this.EntityType); + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.calendars.Length; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.calendars.Length; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("calendarCellIdentifier") ?? new UITableViewCell(); - cell.TextLabel.Text = this.calendars[indexPath.Row].Title; - return cell; - } - } -} \ No newline at end of file + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("calendarCellIdentifier") ?? new UITableViewCell (); + cell.TextLabel.Text = this.calendars [indexPath.Row].Title; + return cell; + } + } +} diff --git a/Calendars/Calendars/Delegates/CreateEventEditViewDelegate.cs b/Calendars/Calendars/Delegates/CreateEventEditViewDelegate.cs index 8a810329f..7cf70546d 100644 --- a/Calendars/Calendars/Delegates/CreateEventEditViewDelegate.cs +++ b/Calendars/Calendars/Delegates/CreateEventEditViewDelegate.cs @@ -1,39 +1,36 @@ -using UIKit; +using UIKit; -namespace Calendars.Delegates -{ - public class CreateEventEditViewDelegate : EventKitUI.EKEventEditViewDelegate - { - // we need to keep a reference to the controller so we can dismiss it - private readonly UIViewController eventController; +namespace Calendars.Delegates { + public class CreateEventEditViewDelegate : EventKitUI.EKEventEditViewDelegate { + // we need to keep a reference to the controller so we can dismiss it + private readonly UIViewController eventController; - public CreateEventEditViewDelegate(EventKitUI.EKEventEditViewController eventController) - { - // save our controller reference - this.eventController = eventController; - } + public CreateEventEditViewDelegate (EventKitUI.EKEventEditViewController eventController) + { + // save our controller reference + this.eventController = eventController; + } - // completed is called when a user eith - public override void Completed(EventKitUI.EKEventEditViewController controller, EventKitUI.EKEventEditViewAction action) - { - this.eventController.DismissViewController(true, null); + // completed is called when a user eith + public override void Completed (EventKitUI.EKEventEditViewController controller, EventKitUI.EKEventEditViewAction action) + { + this.eventController.DismissViewController (true, null); - // action tells you what the user did in the dialog, so you can optionally - // do things based on what their action was. additionally, you can get the - // Event from the controller.Event property, so for instance, you could - // modify the event and then resave if you'd like. - switch (action) - { - case EventKitUI.EKEventEditViewAction.Canceled: - break; - case EventKitUI.EKEventEditViewAction.Deleted: - break; - case EventKitUI.EKEventEditViewAction.Saved: - // if you wanted to modify the event you could do so here, and then - // save: - //App.Current.EventStore.SaveEvent ( controller.Event, ) - break; - } - } - } -} \ No newline at end of file + // action tells you what the user did in the dialog, so you can optionally + // do things based on what their action was. additionally, you can get the + // Event from the controller.Event property, so for instance, you could + // modify the event and then resave if you'd like. + switch (action) { + case EventKitUI.EKEventEditViewAction.Canceled: + break; + case EventKitUI.EKEventEditViewAction.Deleted: + break; + case EventKitUI.EKEventEditViewAction.Saved: + // if you wanted to modify the event you could do so here, and then + // save: + //App.Current.EventStore.SaveEvent ( controller.Event, ) + break; + } + } + } +} diff --git a/Calendars/Calendars/EventsController.cs b/Calendars/Calendars/EventsController.cs index 49f51a120..6c52c44af 100644 --- a/Calendars/Calendars/EventsController.cs +++ b/Calendars/Calendars/EventsController.cs @@ -3,41 +3,38 @@ using System; using UIKit; -namespace Calendars -{ - public partial class EventsController : UITableViewController - { - private EKEvent[] events; +namespace Calendars { + public partial class EventsController : UITableViewController { + private EKEvent [] events; - public EventsController(IntPtr handle) : base(handle) { } + public EventsController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - // create our NSPredicate which we'll use for the query - var startDate = (NSDate)DateTime.Now.AddDays(-7); - var endDate = (NSDate)DateTime.Now; - // the third parameter is calendars we want to look in, to use all calendars, we pass null - using (var query = MainViewController.EventStore.PredicateForEvents(startDate, endDate, null)) - { - // execute the query - this.events = MainViewController.EventStore.EventsMatching(query); - } + // create our NSPredicate which we'll use for the query + var startDate = (NSDate) DateTime.Now.AddDays (-7); + var endDate = (NSDate) DateTime.Now; + // the third parameter is calendars we want to look in, to use all calendars, we pass null + using (var query = MainViewController.EventStore.PredicateForEvents (startDate, endDate, null)) { + // execute the query + this.events = MainViewController.EventStore.EventsMatching (query); + } - this.TableView.ReloadData(); - } + this.TableView.ReloadData (); + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.events.Length; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.events.Length; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("eventCellIdentifier") ?? new UITableViewCell(); - cell.TextLabel.Text = this.events[indexPath.Row].Title; - return cell; - } - } -} \ No newline at end of file + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("eventCellIdentifier") ?? new UITableViewCell (); + cell.TextLabel.Text = this.events [indexPath.Row].Title; + return cell; + } + } +} diff --git a/Calendars/Calendars/Main.cs b/Calendars/Calendars/Main.cs index bb6409d98..a159d4d42 100644 --- a/Calendars/Calendars/Main.cs +++ b/Calendars/Calendars/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Calendars -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace Calendars { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/Calendars/Calendars/MainViewController.cs b/Calendars/Calendars/MainViewController.cs index bf021af45..252bfacd3 100644 --- a/Calendars/Calendars/MainViewController.cs +++ b/Calendars/Calendars/MainViewController.cs @@ -4,213 +4,190 @@ using System; using UIKit; -namespace Calendars -{ - public partial class MainViewController : UITableViewController - { - public static EKEventStore EventStore { get; } = new EKEventStore(); - - public MainViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.RequestAccess(); - } - - private void RequestAccess() - { - EventStore.RequestAccess(EKEntityType.Event, AccessCompletionHandler); - EventStore.RequestAccess(EKEntityType.Reminder, AccessCompletionHandler); - - void AccessCompletionHandler(bool granted, NSError error) - { - if (!granted) - { - base.InvokeOnMainThread(() => - { - var alert = UIAlertController.Create("Access Denied", "User Denied Access to Calendars/Reminders", UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - base.PresentViewController(alert, true, null); - }); - } - } - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "showCalendarsSegue" && - segue.DestinationViewController is CalendarsViewController calendarsViewController && - sender is NSNumber number) - { - calendarsViewController.EntityType = (EKEntityType)number.UInt64Value; - } - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var selectedCell = tableView.CellAt(indexPath); - if (selectedCell == this.newEventCell) - { - this.LaunchCreateNewEvent(); - } - else if (selectedCell == this.modifyEventCell) - { - this.LaunchModifyEvent(); - } - else if (selectedCell == this.saveEventsCell) - { - this.SaveAndRetrieveEvent(); - } - else if (selectedCell == this.createReminderCell) - { - this.CreateReminder(); - } - else if (selectedCell == this.calendarsCell) - { - base.PerformSegue("showCalendarsSegue", NSNumber.FromUInt64((ulong)EKEntityType.Event)); - } - else if (selectedCell == this.remindersCell) - { - base.PerformSegue("showCalendarsSegue", NSNumber.FromUInt64((ulong)EKEntityType.Reminder)); - } - - tableView.DeselectRow(indexPath, false); - } - - #region Events - - /// - /// Launchs the create new event controller. - /// - private void LaunchCreateNewEvent() - { - // create a new EKEventEditViewController. This controller is built in an allows - // the user to create a new, or edit an existing event. - var eventController = new EventKitUI.EKEventEditViewController - { - // set the controller's event store - it needs to know where/how to save the event - EventStore = EventStore - }; - - // wire up a delegate to handle events from the controller - eventController.EditViewDelegate = new CreateEventEditViewDelegate(eventController); - - // show the event controller - base.PresentViewController(eventController, true, null); - } - - /// - /// Launchs the create new event controller. - /// - private void LaunchModifyEvent() - { - // first we need to create an event it so we have one that we know exists - // in a real world scenario, we'd likely either a) be modifying an event that - // we found via a query, or 2) we'd do like this, in which we'd automatically - // populate the event data, like for say a dr. appt. reminder, or something - var newEvent = EKEvent.FromStore(EventStore); - // set the alarm for 10 minutes from now - newEvent.AddAlarm(EKAlarm.FromDate((NSDate)DateTime.Now.AddMinutes(10))); - // make the event start 20 minutes from now and last 30 minutes - newEvent.StartDate = (NSDate)DateTime.Now.AddMinutes(20); - newEvent.EndDate = (NSDate)DateTime.Now.AddMinutes(50); - newEvent.Title = "Get outside and do some exercise!"; - newEvent.Notes = "This is your motivational event to go and do 30 minutes of exercise. Super important. Do this."; - - // create a new EKEventEditViewController. This controller is built in an allows - // the user to create a new, or edit an existing event. - var eventController = new EventKitUI.EKEventEditViewController { EventStore = EventStore }; - eventController.Event = newEvent; - - // wire up a delegate to handle events from the controller - eventController.EditViewDelegate = new CreateEventEditViewDelegate(eventController); - - // show the event controller - base.PresentViewController(eventController, true, null); - } - - /// - /// This method illustrates how to save and retrieve events programmatically. - /// - private void SaveAndRetrieveEvent() - { - var newEvent = EKEvent.FromStore(EventStore); - // set the alarm for 5 minutes from now - newEvent.AddAlarm(EKAlarm.FromDate((NSDate)DateTime.Now.AddMinutes(5))); - // make the event start 10 minutes from now and last 30 minutes - newEvent.StartDate = (NSDate)DateTime.Now.AddMinutes(10); - newEvent.EndDate = (NSDate)DateTime.Now.AddMinutes(40); - newEvent.Title = "Appt. to do something Awesome!"; - newEvent.Notes = "Find a boulder, climb it. Find a river, swim it. Find an ocean, dive it."; - newEvent.Calendar = EventStore.DefaultCalendarForNewEvents; - - // save the event - EventStore.SaveEvent(newEvent, EKSpan.ThisEvent, out NSError error); - if (error != null) - { - var alert = UIAlertController.Create("Error", error.ToString(), UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - base.PresentViewController(alert, true, null); - } - else - { - var alert = UIAlertController.Create("Event Saved", $"Event ID: {newEvent.EventIdentifier}", UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - base.PresentViewController(alert, true, null); - - // to retrieve the event you can call - var savedEvent = EventStore.EventFromIdentifier(newEvent.EventIdentifier); - Console.WriteLine($"Retrieved Saved Event: {savedEvent.Title}"); - - // to delete, note that once you remove the event, the reference will be null, so - // if you try to access it you'll get a null reference error. - EventStore.RemoveEvent(savedEvent, EKSpan.ThisEvent, true, out error); - Console.WriteLine("Event Deleted."); - } - } - - #endregion - - #region Reminders - - /// - /// Creates and saves a reminder to the default reminder calendar - /// - private void CreateReminder() - { - // create a reminder using the EKReminder.Create method - var reminder = EKReminder.Create(EventStore); - reminder.Title = "Do something awesome!"; - reminder.Calendar = EventStore.DefaultCalendarForNewReminders; - - // save the reminder - EventStore.SaveReminder(reminder, true, out NSError error); - // if there was an error, show it - if (error != null) - { - var alert = UIAlertController.Create("Error", error.ToString(), UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - base.PresentViewController(alert, true, null); - } - else - { - var alert = UIAlertController.Create("Reminder saved", $"ID: {reminder.CalendarItemIdentifier}", UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - base.PresentViewController(alert, true, null); - - // to retrieve the reminder you can call GetCalendarItem - var myReminder = EventStore.GetCalendarItem(reminder.CalendarItemIdentifier); - Console.WriteLine($"Retrieved Saved Reminder: {myReminder.Title}"); - - // TODO: you can uncomment it to see how does removal work - // to delete, note that once you remove the event, the reference will be null, so - // if you try to access it you'll get a null reference error. - //EventStore.RemoveReminder(myReminder as EKReminder, true, out error); - //Console.WriteLine("Reminder Deleted."); - } - } - - #endregion - } -} \ No newline at end of file +namespace Calendars { + public partial class MainViewController : UITableViewController { + public static EKEventStore EventStore { get; } = new EKEventStore (); + + public MainViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.RequestAccess (); + } + + private void RequestAccess () + { + EventStore.RequestAccess (EKEntityType.Event, AccessCompletionHandler); + EventStore.RequestAccess (EKEntityType.Reminder, AccessCompletionHandler); + + void AccessCompletionHandler (bool granted, NSError error) + { + if (!granted) { + base.InvokeOnMainThread (() => { + var alert = UIAlertController.Create ("Access Denied", "User Denied Access to Calendars/Reminders", UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + base.PresentViewController (alert, true, null); + }); + } + } + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "showCalendarsSegue" && + segue.DestinationViewController is CalendarsViewController calendarsViewController && + sender is NSNumber number) { + calendarsViewController.EntityType = (EKEntityType) number.UInt64Value; + } + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var selectedCell = tableView.CellAt (indexPath); + if (selectedCell == this.newEventCell) { + this.LaunchCreateNewEvent (); + } else if (selectedCell == this.modifyEventCell) { + this.LaunchModifyEvent (); + } else if (selectedCell == this.saveEventsCell) { + this.SaveAndRetrieveEvent (); + } else if (selectedCell == this.createReminderCell) { + this.CreateReminder (); + } else if (selectedCell == this.calendarsCell) { + base.PerformSegue ("showCalendarsSegue", NSNumber.FromUInt64 ((ulong) EKEntityType.Event)); + } else if (selectedCell == this.remindersCell) { + base.PerformSegue ("showCalendarsSegue", NSNumber.FromUInt64 ((ulong) EKEntityType.Reminder)); + } + + tableView.DeselectRow (indexPath, false); + } + + #region Events + + /// + /// Launchs the create new event controller. + /// + private void LaunchCreateNewEvent () + { + // create a new EKEventEditViewController. This controller is built in an allows + // the user to create a new, or edit an existing event. + var eventController = new EventKitUI.EKEventEditViewController { + // set the controller's event store - it needs to know where/how to save the event + EventStore = EventStore + }; + + // wire up a delegate to handle events from the controller + eventController.EditViewDelegate = new CreateEventEditViewDelegate (eventController); + + // show the event controller + base.PresentViewController (eventController, true, null); + } + + /// + /// Launchs the create new event controller. + /// + private void LaunchModifyEvent () + { + // first we need to create an event it so we have one that we know exists + // in a real world scenario, we'd likely either a) be modifying an event that + // we found via a query, or 2) we'd do like this, in which we'd automatically + // populate the event data, like for say a dr. appt. reminder, or something + var newEvent = EKEvent.FromStore (EventStore); + // set the alarm for 10 minutes from now + newEvent.AddAlarm (EKAlarm.FromDate ((NSDate) DateTime.Now.AddMinutes (10))); + // make the event start 20 minutes from now and last 30 minutes + newEvent.StartDate = (NSDate) DateTime.Now.AddMinutes (20); + newEvent.EndDate = (NSDate) DateTime.Now.AddMinutes (50); + newEvent.Title = "Get outside and do some exercise!"; + newEvent.Notes = "This is your motivational event to go and do 30 minutes of exercise. Super important. Do this."; + + // create a new EKEventEditViewController. This controller is built in an allows + // the user to create a new, or edit an existing event. + var eventController = new EventKitUI.EKEventEditViewController { EventStore = EventStore }; + eventController.Event = newEvent; + + // wire up a delegate to handle events from the controller + eventController.EditViewDelegate = new CreateEventEditViewDelegate (eventController); + + // show the event controller + base.PresentViewController (eventController, true, null); + } + + /// + /// This method illustrates how to save and retrieve events programmatically. + /// + private void SaveAndRetrieveEvent () + { + var newEvent = EKEvent.FromStore (EventStore); + // set the alarm for 5 minutes from now + newEvent.AddAlarm (EKAlarm.FromDate ((NSDate) DateTime.Now.AddMinutes (5))); + // make the event start 10 minutes from now and last 30 minutes + newEvent.StartDate = (NSDate) DateTime.Now.AddMinutes (10); + newEvent.EndDate = (NSDate) DateTime.Now.AddMinutes (40); + newEvent.Title = "Appt. to do something Awesome!"; + newEvent.Notes = "Find a boulder, climb it. Find a river, swim it. Find an ocean, dive it."; + newEvent.Calendar = EventStore.DefaultCalendarForNewEvents; + + // save the event + EventStore.SaveEvent (newEvent, EKSpan.ThisEvent, out NSError error); + if (error != null) { + var alert = UIAlertController.Create ("Error", error.ToString (), UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + base.PresentViewController (alert, true, null); + } else { + var alert = UIAlertController.Create ("Event Saved", $"Event ID: {newEvent.EventIdentifier}", UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + base.PresentViewController (alert, true, null); + + // to retrieve the event you can call + var savedEvent = EventStore.EventFromIdentifier (newEvent.EventIdentifier); + Console.WriteLine ($"Retrieved Saved Event: {savedEvent.Title}"); + + // to delete, note that once you remove the event, the reference will be null, so + // if you try to access it you'll get a null reference error. + EventStore.RemoveEvent (savedEvent, EKSpan.ThisEvent, true, out error); + Console.WriteLine ("Event Deleted."); + } + } + + #endregion + + #region Reminders + + /// + /// Creates and saves a reminder to the default reminder calendar + /// + private void CreateReminder () + { + // create a reminder using the EKReminder.Create method + var reminder = EKReminder.Create (EventStore); + reminder.Title = "Do something awesome!"; + reminder.Calendar = EventStore.DefaultCalendarForNewReminders; + + // save the reminder + EventStore.SaveReminder (reminder, true, out NSError error); + // if there was an error, show it + if (error != null) { + var alert = UIAlertController.Create ("Error", error.ToString (), UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + base.PresentViewController (alert, true, null); + } else { + var alert = UIAlertController.Create ("Reminder saved", $"ID: {reminder.CalendarItemIdentifier}", UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + base.PresentViewController (alert, true, null); + + // to retrieve the reminder you can call GetCalendarItem + var myReminder = EventStore.GetCalendarItem (reminder.CalendarItemIdentifier); + Console.WriteLine ($"Retrieved Saved Reminder: {myReminder.Title}"); + + // TODO: you can uncomment it to see how does removal work + // to delete, note that once you remove the event, the reference will be null, so + // if you try to access it you'll get a null reference error. + //EventStore.RemoveReminder(myReminder as EKReminder, true, out error); + //Console.WriteLine("Reminder Deleted."); + } + } + + #endregion + } +} diff --git a/Calendars/Calendars/RemindersController.cs b/Calendars/Calendars/RemindersController.cs index 059eb4069..f46a40654 100644 --- a/Calendars/Calendars/RemindersController.cs +++ b/Calendars/Calendars/RemindersController.cs @@ -3,41 +3,37 @@ using System; using UIKit; -namespace Calendars -{ - public partial class RemindersController : UITableViewController - { - private EKReminder[] reminders; +namespace Calendars { + public partial class RemindersController : UITableViewController { + private EKReminder [] reminders; - public RemindersController(IntPtr handle) : base(handle) { } + public RemindersController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - // create our NSPredicate which we'll use for the query - using (var query = MainViewController.EventStore.PredicateForReminders(null)) - { - // execute the query - MainViewController.EventStore.FetchReminders(query, (collection) => - { - this.reminders = collection; - }); - } + // create our NSPredicate which we'll use for the query + using (var query = MainViewController.EventStore.PredicateForReminders (null)) { + // execute the query + MainViewController.EventStore.FetchReminders (query, (collection) => { + this.reminders = collection; + }); + } - this.TableView.ReloadData(); - } + this.TableView.ReloadData (); + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.reminders?.Length ?? 0; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.reminders?.Length ?? 0; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("eventCellIdentifier") ?? new UITableViewCell(); - cell.TextLabel.Text = this.reminders[indexPath.Row].Title; - return cell; - } - } -} \ No newline at end of file + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("eventCellIdentifier") ?? new UITableViewCell (); + cell.TextLabel.Text = this.reminders [indexPath.Row].Title; + return cell; + } + } +} diff --git a/Chat/Chat/AppDelegate.cs b/Chat/Chat/AppDelegate.cs index 54f5a8c29..65f196c3c 100644 --- a/Chat/Chat/AppDelegate.cs +++ b/Chat/Chat/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace Chat -{ +namespace Chat { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } -} \ No newline at end of file +} diff --git a/Chat/Chat/Cells/BubbleCell.cs b/Chat/Chat/Cells/BubbleCell.cs index 39dd4e8e7..e29d12c17 100644 --- a/Chat/Chat/Cells/BubbleCell.cs +++ b/Chat/Chat/Cells/BubbleCell.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using CoreGraphics; using Foundation; -namespace Chat -{ - public abstract class BubbleCell : UITableViewCell - { +namespace Chat { + public abstract class BubbleCell : UITableViewCell { public UIImageView BubbleImageView { get; private set; } public UILabel MessageLabel { get; private set; } public UIImage BubbleImage { get; set; } @@ -98,4 +96,4 @@ protected static UIImage CreateBubbleWithBorder (UIImage bubbleImg, UIColor bubb return result; } } -} \ No newline at end of file +} diff --git a/Chat/Chat/Cells/IncomingCell.cs b/Chat/Chat/Cells/IncomingCell.cs index 55edf9758..af854e3ab 100644 --- a/Chat/Chat/Cells/IncomingCell.cs +++ b/Chat/Chat/Cells/IncomingCell.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace Chat -{ +namespace Chat { [Register ("IncomingCell")] - public class IncomingCell : BubbleCell - { + public class IncomingCell : BubbleCell { static readonly UIImage normalBubbleImage; static readonly UIImage highlightedBubbleImage; @@ -55,7 +53,7 @@ void Initialize () BubbleImage = normalBubbleImage; ContentView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[bubble]", - 0, + 0, "bubble", BubbleImageView)); ContentView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-2-[bubble]-2-|", 0, diff --git a/Chat/Chat/Cells/OutgoingCell.cs b/Chat/Chat/Cells/OutgoingCell.cs index 442c11624..6d8166f57 100644 --- a/Chat/Chat/Cells/OutgoingCell.cs +++ b/Chat/Chat/Cells/OutgoingCell.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using Foundation; -namespace Chat -{ +namespace Chat { [Register ("OutgoingCell")] - public class OutgoingCell : BubbleCell - { + public class OutgoingCell : BubbleCell { static readonly UIImage normalBubbleImage; static readonly UIImage highlightedBubbleImage; @@ -55,7 +53,7 @@ void Initialize () BubbleImage = normalBubbleImage; ContentView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:[bubble]|", - 0, + 0, "bubble", BubbleImageView)); ContentView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-2-[bubble]-2-|", 0, @@ -81,4 +79,4 @@ void Initialize () MessageLabel.TextColor = UIColor.White; } } -} \ No newline at end of file +} diff --git a/Chat/Chat/ChatInput/ChatInputView.cs b/Chat/Chat/ChatInput/ChatInputView.cs index 35477292e..744462da9 100644 --- a/Chat/Chat/ChatInput/ChatInputView.cs +++ b/Chat/Chat/ChatInput/ChatInputView.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace Chat -{ - public class ChatInputView : UIView - { +namespace Chat { + public class ChatInputView : UIView { static readonly UIColor ButtonTextColorNormal = UIColor.FromRGB (1, 122, 255); static readonly UIColor ButtonTextColorDisabled = UIColor.FromRGB (142, 142, 147); static readonly UIFont ButtonFont = UIFont.BoldSystemFontOfSize (17f); @@ -63,4 +61,4 @@ public ChatInputView () AddConstraint (c2); } } -} \ No newline at end of file +} diff --git a/Chat/Chat/ChatSource.cs b/Chat/Chat/ChatSource.cs index 35b837a6c..874eb31e0 100644 --- a/Chat/Chat/ChatSource.cs +++ b/Chat/Chat/ChatSource.cs @@ -1,20 +1,18 @@ -using System; +using System; using System.Collections.Generic; using CoreGraphics; using Foundation; using UIKit; -namespace Chat -{ - public class ChatSource : UITableViewSource - { +namespace Chat { + public class ChatSource : UITableViewSource { static readonly NSString IncomingCellId = new NSString ("Incoming"); static readonly NSString OutgoingCellId = new NSString ("Outgoing"); IList messages; - readonly BubbleCell[] sizingCells; + readonly BubbleCell [] sizingCells; public ChatSource (IList messages) { @@ -22,7 +20,7 @@ public ChatSource (IList messages) throw new ArgumentNullException (nameof (messages)); this.messages = messages; - sizingCells = new BubbleCell[2]; + sizingCells = new BubbleCell [2]; } public override nint RowsInSection (UITableView tableview, nint section) @@ -35,7 +33,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde BubbleCell cell = null; Message msg = messages [indexPath.Row]; - cell = (BubbleCell)tableView.DequeueReusableCell (GetReuseId (msg.Type)); + cell = (BubbleCell) tableView.DequeueReusableCell (GetReuseId (msg.Type)); cell.Message = msg; return cell; @@ -55,12 +53,12 @@ public override nfloat EstimatedHeight (UITableView tableView, NSIndexPath index nfloat CalculateHeightFor (Message msg, UITableView tableView) { - var index = (int)msg.Type; + var index = (int) msg.Type; BubbleCell cell = sizingCells [index]; if (cell == null) - cell = sizingCells [index] = (BubbleCell)tableView.DequeueReusableCell (GetReuseId (msg.Type)); + cell = sizingCells [index] = (BubbleCell) tableView.DequeueReusableCell (GetReuseId (msg.Type)); - cell.Message = msg; + cell.Message = msg; cell.SetNeedsLayout (); cell.LayoutIfNeeded (); @@ -73,4 +71,4 @@ NSString GetReuseId (MessageType msgType) return msgType == MessageType.Incoming ? IncomingCellId : OutgoingCellId; } } -} \ No newline at end of file +} diff --git a/Chat/Chat/ChatViewController.cs b/Chat/Chat/ChatViewController.cs index d27bcef31..7760c3a1f 100644 --- a/Chat/Chat/ChatViewController.cs +++ b/Chat/Chat/ChatViewController.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using Foundation; using CoreGraphics; -namespace Chat -{ +namespace Chat { [Register ("ChatViewController")] - public class ChatViewController : UIViewController - { + public class ChatViewController : UIViewController { NSObject willShowToken; NSObject willHideToken; @@ -21,7 +19,7 @@ public class ChatViewController : UIViewController NSLayoutConstraint toolbarBottomConstraint; NSLayoutConstraint toolbarHeightConstraint; - int notifCount = 0; + int notifCount = 0; ChatInputView chatInputView; @@ -102,74 +100,66 @@ void SetUpTableView () AllowsSelection = false, SeparatorStyle = UITableViewCellSeparatorStyle.None }; - tableView.RegisterClassForCellReuse (typeof(IncomingCell), IncomingCell.CellId); - tableView.RegisterClassForCellReuse (typeof(OutgoingCell), OutgoingCell.CellId); + tableView.RegisterClassForCellReuse (typeof (IncomingCell), IncomingCell.CellId); + tableView.RegisterClassForCellReuse (typeof (OutgoingCell), OutgoingCell.CellId); View.AddSubview (tableView); - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { // iPhone X layout - var safeGuide = View.SafeAreaLayoutGuide; - tableView.TopAnchor.ConstraintEqualTo(safeGuide.TopAnchor).Active = true; - tableView.LeadingAnchor.ConstraintEqualTo(safeGuide.LeadingAnchor).Active = true; - tableView.TrailingAnchor.ConstraintEqualTo(safeGuide.TrailingAnchor).Active = true; - tableView.BottomAnchor.ConstraintEqualTo(safeGuide.BottomAnchor, -44).Active = true; - } - else - { - var pinLeft = NSLayoutConstraint.Create(tableView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 1f, 0f); - View.AddConstraint(pinLeft); - - var pinRight = NSLayoutConstraint.Create(tableView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1f, 0f); - View.AddConstraint(pinRight); - - var pinTop = NSLayoutConstraint.Create(tableView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, 0f); - View.AddConstraint(pinTop); - - var pinBottom = NSLayoutConstraint.Create(tableView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1f, 0f); - View.AddConstraint(pinBottom); - } + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { // iPhone X layout + var safeGuide = View.SafeAreaLayoutGuide; + tableView.TopAnchor.ConstraintEqualTo (safeGuide.TopAnchor).Active = true; + tableView.LeadingAnchor.ConstraintEqualTo (safeGuide.LeadingAnchor).Active = true; + tableView.TrailingAnchor.ConstraintEqualTo (safeGuide.TrailingAnchor).Active = true; + tableView.BottomAnchor.ConstraintEqualTo (safeGuide.BottomAnchor, -44).Active = true; + } else { + var pinLeft = NSLayoutConstraint.Create (tableView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 1f, 0f); + View.AddConstraint (pinLeft); + + var pinRight = NSLayoutConstraint.Create (tableView, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1f, 0f); + View.AddConstraint (pinRight); + + var pinTop = NSLayoutConstraint.Create (tableView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, 0f); + View.AddConstraint (pinTop); + + var pinBottom = NSLayoutConstraint.Create (tableView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1f, 0f); + View.AddConstraint (pinBottom); + } chatSource = new ChatSource (messages); tableView.Source = chatSource; } - void SetUpToolbar() - { - toolbar = new UIToolbar - { - TranslatesAutoresizingMaskIntoConstraints = false - }; - chatInputView = new ChatInputView - { - TranslatesAutoresizingMaskIntoConstraints = false - }; + void SetUpToolbar () + { + toolbar = new UIToolbar { + TranslatesAutoresizingMaskIntoConstraints = false + }; + chatInputView = new ChatInputView { + TranslatesAutoresizingMaskIntoConstraints = false + }; - toolbar.LayoutIfNeeded(); - View.AddSubview(toolbar); + toolbar.LayoutIfNeeded (); + View.AddSubview (toolbar); - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { // iPhone X layout + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { // iPhone X layout var safeGuide = View.SafeAreaLayoutGuide; - toolbar.HeightAnchor.ConstraintEqualTo(44).Active = true; - toolbar.LeadingAnchor.ConstraintEqualTo(safeGuide.LeadingAnchor).Active = true; - toolbar.TrailingAnchor.ConstraintEqualTo(safeGuide.TrailingAnchor).Active = true; - toolbarBottomConstraint = toolbar.BottomAnchor.ConstraintEqualTo(safeGuide.BottomAnchor); - toolbarBottomConstraint.Active = true; - } - else - { - var pinLeft = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 1f, 0f); - View.AddConstraint (pinLeft); - - var pinRight = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1f, 0f); - View.AddConstraint (pinRight); - - toolbarBottomConstraint = NSLayoutConstraint.Create (View, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, toolbar, NSLayoutAttribute.Bottom, 1f, 0f); - View.AddConstraint (toolbarBottomConstraint); - - toolbarHeightConstraint = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0f, 44f); - View.AddConstraint (toolbarHeightConstraint); - } + toolbar.HeightAnchor.ConstraintEqualTo (44).Active = true; + toolbar.LeadingAnchor.ConstraintEqualTo (safeGuide.LeadingAnchor).Active = true; + toolbar.TrailingAnchor.ConstraintEqualTo (safeGuide.TrailingAnchor).Active = true; + toolbarBottomConstraint = toolbar.BottomAnchor.ConstraintEqualTo (safeGuide.BottomAnchor); + toolbarBottomConstraint.Active = true; + } else { + var pinLeft = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, View, NSLayoutAttribute.Leading, 1f, 0f); + View.AddConstraint (pinLeft); + + var pinRight = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, View, NSLayoutAttribute.Trailing, 1f, 0f); + View.AddConstraint (pinRight); + + toolbarBottomConstraint = NSLayoutConstraint.Create (View, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, toolbar, NSLayoutAttribute.Bottom, 1f, 0f); + View.AddConstraint (toolbarBottomConstraint); + + toolbarHeightConstraint = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0f, 44f); + View.AddConstraint (toolbarHeightConstraint); + } toolbar.AddSubview (chatInputView); @@ -202,8 +192,8 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio void OnSizeChanged (NSObservedChange change) { - CGSize oldValue = ((NSValue)change.OldValue).CGSizeValue; - CGSize newValue = ((NSValue)change.NewValue).CGSizeValue; + CGSize oldValue = ((NSValue) change.OldValue).CGSizeValue; + CGSize newValue = ((NSValue) change.NewValue).CGSizeValue; var dy = newValue.Height - oldValue.Height; AdjustInputToolbarOnTextViewSizeChanged (dy); @@ -238,36 +228,31 @@ void AdjustInputToolbar (nfloat change) void KeyboardWillShowHandler (object sender, UIKeyboardEventArgs e) { - UpdateButtomLayoutConstraint (e); + UpdateButtomLayoutConstraint (e); } void KeyboardWillHideHandler (object sender, UIKeyboardEventArgs e) { - notifCount = 0; - SetToolbarContstraint(0); + notifCount = 0; + SetToolbarContstraint (0); } void UpdateButtomLayoutConstraint (UIKeyboardEventArgs e) { UIViewAnimationCurve curve = e.AnimationCurve; - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { - UIView.Animate(e.AnimationDuration, 0, ConvertToAnimationOptions(e.AnimationCurve), () => - { - nfloat offsetFromBottom = toolbar.Frame.GetMaxY() - e.FrameEnd.GetMinY(); - offsetFromBottom = NMath.Max(0, offsetFromBottom); - if (++notifCount >= 2) { SetToolbarContstraint(-offsetFromBottom); } + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { + UIView.Animate (e.AnimationDuration, 0, ConvertToAnimationOptions (e.AnimationCurve), () => { + nfloat offsetFromBottom = toolbar.Frame.GetMaxY () - e.FrameEnd.GetMinY (); + offsetFromBottom = NMath.Max (0, offsetFromBottom); + if (++notifCount >= 2) { SetToolbarContstraint (-offsetFromBottom); } }, null); - } - else - { - UIView.Animate(e.AnimationDuration, 0, ConvertToAnimationOptions(e.AnimationCurve), () => - { - nfloat offsetFromBottom = tableView.Frame.GetMaxY() - e.FrameEnd.GetMinY(); - offsetFromBottom = NMath.Max(0, offsetFromBottom); - SetToolbarContstraint(offsetFromBottom); - }, null); - } + } else { + UIView.Animate (e.AnimationDuration, 0, ConvertToAnimationOptions (e.AnimationCurve), () => { + nfloat offsetFromBottom = tableView.Frame.GetMaxY () - e.FrameEnd.GetMinY (); + offsetFromBottom = NMath.Max (0, offsetFromBottom); + SetToolbarContstraint (offsetFromBottom); + }, null); + } } void SetToolbarContstraint (nfloat constant) @@ -292,7 +277,7 @@ UIViewAnimationOptions ConvertToAnimationOptions (UIViewAnimationCurve curve) // Looks like a hack. But it is correct. // UIViewAnimationCurve and UIViewAnimationOptions are shifted by 16 bits // http://stackoverflow.com/questions/18870447/how-to-use-the-default-ios7-uianimation-curve/18873820#18873820 - return (UIViewAnimationOptions)((int)curve << 16); + return (UIViewAnimationOptions) ((int) curve << 16); } void OnSendClicked (object sender, EventArgs e) @@ -310,7 +295,7 @@ void OnSendClicked (object sender, EventArgs e) }; messages.Add (msg); - tableView.InsertRows (new NSIndexPath[] { NSIndexPath.FromRowSection (messages.Count - 1, 0) }, UITableViewRowAnimation.None); + tableView.InsertRows (new NSIndexPath [] { NSIndexPath.FromRowSection (messages.Count - 1, 0) }, UITableViewRowAnimation.None); ScrollToBottom (true); } @@ -342,11 +327,11 @@ void ScrollToBottom (bool animated) if (tableView.NumberOfSections () == 0) return; - var items = (int)tableView.NumberOfRowsInSection (0); + var items = (int) tableView.NumberOfRowsInSection (0); if (items == 0) return; - var finalRow = (int)NMath.Max (0, tableView.NumberOfRowsInSection (0) - 1); + var finalRow = (int) NMath.Max (0, tableView.NumberOfRowsInSection (0) - 1); NSIndexPath finalIndexPath = NSIndexPath.FromRowSection (finalRow, 0); tableView.ScrollToRow (finalIndexPath, UITableViewScrollPosition.Top, animated); } diff --git a/Chat/Chat/Main.cs b/Chat/Chat/Main.cs index 597cbcf2f..f9c199a61 100644 --- a/Chat/Chat/Main.cs +++ b/Chat/Chat/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace Chat -{ - public class Application - { +namespace Chat { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Chat/Chat/Model/Message.cs b/Chat/Chat/Model/Message.cs index 85ab6f3f7..004be18ec 100644 --- a/Chat/Chat/Model/Message.cs +++ b/Chat/Chat/Model/Message.cs @@ -1,7 +1,5 @@ -namespace Chat -{ - public class Message - { +namespace Chat { + public class Message { public MessageType Type { get; set; } public string Text { get; set; } } diff --git a/Chat/Chat/Model/MessageType.cs b/Chat/Chat/Model/MessageType.cs index 151966bf8..e512fbd01 100644 --- a/Chat/Chat/Model/MessageType.cs +++ b/Chat/Chat/Model/MessageType.cs @@ -1,7 +1,5 @@ -namespace Chat -{ - public enum MessageType - { +namespace Chat { + public enum MessageType { Incoming, Outgoing, } diff --git a/Chat/Chat/OutgoingCell.cs b/Chat/Chat/OutgoingCell.cs index 31dbb2c2b..109217500 100644 --- a/Chat/Chat/OutgoingCell.cs +++ b/Chat/Chat/OutgoingCell.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Chat -{ - public partial class OutgoingCell : UITableViewCell - { +namespace Chat { + public partial class OutgoingCell : UITableViewCell { public OutgoingCell (IntPtr handle) : base (handle) { } diff --git a/CircleLayout/AppDelegate.cs b/CircleLayout/AppDelegate.cs index 7aa46a8fd..ac67a9996 100755 --- a/CircleLayout/AppDelegate.cs +++ b/CircleLayout/AppDelegate.cs @@ -1,11 +1,9 @@ using Foundation; using UIKit; -namespace CircleLayout -{ +namespace CircleLayout { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) @@ -13,12 +11,12 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window = new UIWindow (UIScreen.MainScreen.Bounds); window.RootViewController = new ViewController (new CircleLayout ()); - window.MakeKeyAndVisible(); + window.MakeKeyAndVisible (); return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/CircleLayout/Cell.cs b/CircleLayout/Cell.cs index 82594fa92..6489fc9b3 100755 --- a/CircleLayout/Cell.cs +++ b/CircleLayout/Cell.cs @@ -2,10 +2,8 @@ using Foundation; using CoreGraphics; -namespace CircleLayout -{ - public class Cell : UICollectionViewCell - { +namespace CircleLayout { + public class Cell : UICollectionViewCell { [Export ("initWithFrame:")] public Cell (CGRect frame) : base (frame) { diff --git a/CircleLayout/CircleLayout.cs b/CircleLayout/CircleLayout.cs index bcbf0ebc3..9080e451c 100755 --- a/CircleLayout/CircleLayout.cs +++ b/CircleLayout/CircleLayout.cs @@ -5,10 +5,8 @@ using CoreAnimation; using UIKit; -namespace CircleLayout -{ - public class CircleLayout : UICollectionViewLayout - { +namespace CircleLayout { + public class CircleLayout : UICollectionViewLayout { const float ItemSize = 70.0f; int cellCount = 20; @@ -24,9 +22,9 @@ public override void PrepareLayout () base.PrepareLayout (); CGSize size = CollectionView.Frame.Size; - cellCount = (int)CollectionView.NumberOfItemsInSection (0); + cellCount = (int) CollectionView.NumberOfItemsInSection (0); center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f); - radius = (int)Math.Min (size.Width, size.Height) / 2.5f; + radius = (int) Math.Min (size.Width, size.Height) / 2.5f; } public override CGSize CollectionViewContentSize { @@ -40,11 +38,11 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSInde UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell (path); attributes.Size = new CGSize (ItemSize, ItemSize); attributes.Center = new CGPoint (center.X + radius * (float) Math.Cos (2 * path.Row * Math.PI / cellCount), - center.Y + radius * (float) Math.Sin (2 * path.Row * Math.PI / cellCount)); + center.Y + radius * (float) Math.Sin (2 * path.Row * Math.PI / cellCount)); return attributes; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { var attributes = new UICollectionViewLayoutAttributes [cellCount]; diff --git a/CircleLayout/ViewController.cs b/CircleLayout/ViewController.cs index 4c30a52a0..2fe6eb312 100755 --- a/CircleLayout/ViewController.cs +++ b/CircleLayout/ViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace CircleLayout -{ - public partial class ViewController : UICollectionViewController - { +namespace CircleLayout { + public partial class ViewController : UICollectionViewController { static NSString cellClass = new NSString ("Cell"); int cellCount = 20; @@ -19,7 +17,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - CollectionView.RegisterClassForCell (typeof(Cell), cellClass); + CollectionView.RegisterClassForCell (typeof (Cell), cellClass); CollectionView.AddGestureRecognizer (new UITapGestureRecognizer (HandleTapGesture)); CollectionView.ReloadData (); CollectionView.BackgroundColor = UIColor.DarkGray; @@ -52,17 +50,19 @@ void HandleTapGesture (UITapGestureRecognizer sender) if (tappedCellPath != null) { cellCount--; - CollectionView.PerformBatchUpdates (delegate { - CollectionView.DeleteItems (new NSIndexPath [] { tappedCellPath }); - }, null); + CollectionView.PerformBatchUpdates (delegate + { + CollectionView.DeleteItems (new NSIndexPath [] { tappedCellPath }); + }, null); } else { cellCount++; - CollectionView.PerformBatchUpdates (delegate { - CollectionView.InsertItems (new NSIndexPath[] { + CollectionView.PerformBatchUpdates (delegate + { + CollectionView.InsertItems (new NSIndexPath [] { NSIndexPath.FromItemSection (0, 0) }); - }, null); + }, null); } } } diff --git a/CollectionViewTransition/CollectionViewTransition/APLStackLayout.cs b/CollectionViewTransition/CollectionViewTransition/APLStackLayout.cs index c9c9b5f4f..daaff5afa 100644 --- a/CollectionViewTransition/CollectionViewTransition/APLStackLayout.cs +++ b/CollectionViewTransition/CollectionViewTransition/APLStackLayout.cs @@ -22,7 +22,7 @@ public override void PrepareLayout () CGSize size = CollectionView.Bounds.Size; CGPoint center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f); - int itemCount = (int)CollectionView.NumberOfItemsInSection (0); + int itemCount = (int) CollectionView.NumberOfItemsInSection (0); if (attributesArray == null) attributesArray = new List (itemCount); @@ -36,7 +36,7 @@ public override void PrepareLayout () angles.Add (0); for (int i = 1; i < stackCount * 10; i++) { int hash = (int) (i * 2654435761 % 2 ^ 32); - hash = (int)(hash * 2654435761 % 2 ^ 32); + hash = (int) (hash * 2654435761 % 2 ^ 32); float currentAngle = (float) ((hash % 1000) / 1000.0 * diff) + minAngle; angles.Add (currentAngle); @@ -72,10 +72,10 @@ public override CGSize CollectionViewContentSize { public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath indexPath) { - return attributesArray [(int)indexPath.Item]; + return attributesArray [(int) indexPath.Item]; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { return attributesArray.ToArray (); } diff --git a/CollectionViewTransition/CollectionViewTransition/APLTransitionController.cs b/CollectionViewTransition/CollectionViewTransition/APLTransitionController.cs index a6b6e9f33..93182d207 100644 --- a/CollectionViewTransition/CollectionViewTransition/APLTransitionController.cs +++ b/CollectionViewTransition/CollectionViewTransition/APLTransitionController.cs @@ -29,11 +29,11 @@ public APLTransitionController (UICollectionView view, UINavigationController co // the interactive portions of a view controller transition and start the animations void InteractionBegan (CGPoint point) { - UIViewController viewController = ((APLCollectionViewController)navigationController.TopViewController).NextViewControllerAtPoint (point); + UIViewController viewController = ((APLCollectionViewController) navigationController.TopViewController).NextViewControllerAtPoint (point); if (viewController != null) { navigationController.PushViewController (viewController, true); } else { - navigationController.PopViewController(true); + navigationController.PopViewController (true); } } @@ -53,13 +53,14 @@ public override void StartInteractiveTransition (IUIViewControllerContextTransit var fromVC = (UICollectionViewController) context.GetViewControllerForKey (UITransitionContext.FromViewControllerKey); var toVC = (UICollectionViewController) context.GetViewControllerForKey (UITransitionContext.ToViewControllerKey); transitionLayout = (APLTransitionLayout) fromVC.CollectionView.StartInteractiveTransition (toVC.Layout, - delegate (bool finished, bool completed) { - context.CompleteTransition (completed); - collectionView.WeakDelegate = completed ? toVC : fromVC; - transitionLayout = null; - context = null; - HasActiveInteraction = false; - }); + delegate (bool finished, bool completed) + { + context.CompleteTransition (completed); + collectionView.WeakDelegate = completed ? toVC : fromVC; + transitionLayout = null; + context = null; + HasActiveInteraction = false; + }); } void Update (float progress, UIOffset offset) @@ -105,8 +106,8 @@ public void HandlePinch (UIPinchGestureRecognizer sender) CGPoint point = sender.LocationInView (sender.View); // get the main touch point CGPoint point1 = sender.LocationOfTouch (0, sender.View); // return the locations of each gesture’s touches in the local coordinate system of a given view CGPoint point2 = sender.LocationOfTouch (1, sender.View); - float distance = (float)Math.Sqrt ((point1.X - point2.X) * (point1.X - point2.X) + - (point1.Y - point2.Y) * (point1.Y - point2.Y)); + float distance = (float) Math.Sqrt ((point1.X - point2.X) * (point1.X - point2.X) + + (point1.Y - point2.Y) * (point1.Y - point2.Y)); if (sender.State == UIGestureRecognizerState.Began) { // start the pinch in our out @@ -121,8 +122,8 @@ public void HandlePinch (UIPinchGestureRecognizer sender) if (HasActiveInteraction) { if (sender.State == UIGestureRecognizerState.Changed) { // update the progress of the transtition as the user continues to pinch - float offsetX = (float)point.X - (float)initialPinchPoint.X; - float offsetY = (float)point.Y - (float)initialPinchPoint.Y; + float offsetX = (float) point.X - (float) initialPinchPoint.X; + float offsetY = (float) point.Y - (float) initialPinchPoint.Y; float distanceDelta = distance - initialPinchDistance; @@ -130,8 +131,8 @@ public void HandlePinch (UIPinchGestureRecognizer sender) distanceDelta = -distanceDelta; CGSize size = collectionView.Bounds.Size; - float dimension = (float)Math.Sqrt (size.Width * size.Width + size.Height * size.Height); - float progress = (float)Math.Max (Math.Min (distanceDelta / dimension, 1.0), 0.0); + float dimension = (float) Math.Sqrt (size.Width * size.Width + size.Height * size.Height); + float progress = (float) Math.Max (Math.Min (distanceDelta / dimension, 1.0), 0.0); // tell our UICollectionViewTransitionLayout subclass (transitionLayout) // the progress state of the pinch gesture diff --git a/CollectionViewTransition/CollectionViewTransition/APLTransitionLayout.cs b/CollectionViewTransition/CollectionViewTransition/APLTransitionLayout.cs index 3931aceca..382ccb571 100644 --- a/CollectionViewTransition/CollectionViewTransition/APLTransitionLayout.cs +++ b/CollectionViewTransition/CollectionViewTransition/APLTransitionLayout.cs @@ -6,7 +6,7 @@ namespace CollectionViewTransition { public class APLTransitionLayout : UICollectionViewTransitionLayout { - public APLTransitionLayout(UICollectionViewLayout currentLayout, UICollectionViewLayout newLayout) : + public APLTransitionLayout (UICollectionViewLayout currentLayout, UICollectionViewLayout newLayout) : base (currentLayout, newLayout) { } @@ -16,8 +16,8 @@ public APLTransitionLayout(UICollectionViewLayout currentLayout, UICollectionVie public void SetTransitionProgress (float transitionProgress) { base.TransitionProgress = transitionProgress; - float offsetH = (float)GetValueForAnimatedKey ("offsetH"); - float offsetV = (float)GetValueForAnimatedKey ("offsetV"); + float offsetH = (float) GetValueForAnimatedKey ("offsetH"); + float offsetV = (float) GetValueForAnimatedKey ("offsetV"); Offset = new UIOffset (offsetH, offsetV); } @@ -28,9 +28,9 @@ public void SetOffset (UIOffset offset) Offset = offset; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { - UICollectionViewLayoutAttributes[] attributes = base.LayoutAttributesForElementsInRect (rect); + UICollectionViewLayoutAttributes [] attributes = base.LayoutAttributesForElementsInRect (rect); foreach (var attribute in attributes) { CGPoint center = attribute.Center; attribute.Center = new CGPoint (center.X + Offset.Horizontal, center.Y + Offset.Vertical); diff --git a/CollectionViewTransition/CollectionViewTransition/AppDelegate.cs b/CollectionViewTransition/CollectionViewTransition/AppDelegate.cs index 556ab57c2..4a0b1ca53 100644 --- a/CollectionViewTransition/CollectionViewTransition/AppDelegate.cs +++ b/CollectionViewTransition/CollectionViewTransition/AppDelegate.cs @@ -29,8 +29,7 @@ public override void FinishedLaunching (UIApplication application) Window.MakeKeyAndVisible (); } - public class NavigationControllerDelegate : UINavigationControllerDelegate - { + public class NavigationControllerDelegate : UINavigationControllerDelegate { APLTransitionController transitionController; public NavigationControllerDelegate (APLTransitionController controller) @@ -47,8 +46,8 @@ public override IUIViewControllerInteractiveTransitioning GetInteractionControll public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForOperation (UINavigationController navigationController, UINavigationControllerOperation operation, UIViewController fromViewController, UIViewController toViewController) { - if (!fromViewController.GetType ().IsSubclassOf (typeof(UICollectionViewController))) - return null; + if (!fromViewController.GetType ().IsSubclassOf (typeof (UICollectionViewController))) + return null; if (!toViewController.GetType ().IsSubclassOf (typeof (UICollectionViewController))) return null; if (!transitionController.HasActiveInteraction) @@ -59,7 +58,7 @@ public override IUIViewControllerAnimatedTransitioning GetAnimationControllerFor } } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Contacts/Contacts/AppDelegate.cs b/Contacts/Contacts/AppDelegate.cs index 171907443..ec4456f28 100644 --- a/Contacts/Contacts/AppDelegate.cs +++ b/Contacts/Contacts/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Contacts -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace Contacts { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/Contacts/Contacts/ContactPickerController.cs b/Contacts/Contacts/ContactPickerController.cs index 52023475a..870a61239 100644 --- a/Contacts/Contacts/ContactPickerController.cs +++ b/Contacts/Contacts/ContactPickerController.cs @@ -6,133 +6,128 @@ using System.Collections.Generic; using UIKit; -namespace Contacts -{ - public partial class ContactPickerController : UIViewController, IUITableViewDelegate, IUITableViewDataSource - { - private readonly List
sections = new List
(); - - private ICNContactPickerDelegate contactDelegate; - - public ContactPickerController(IntPtr handle) : base(handle) { } - - public PickerMode Mode { get; set; } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.tableView.Hidden = true; - this.headerLabel.Hidden = true; - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - switch (this.Mode) - { - case PickerMode.SingleContact: - this.headerLabel.Text = "Selected Contact:"; - this.descriptionLabel.Text = "This page allows you to select a single contact from the picker. Tap \"Show Picker\" to launch the view controller."; - break; - - case PickerMode.MultupleContacts: - this.headerLabel.Text = "Selected Contacts:"; - this.descriptionLabel.Text = "This page allows you to select multiple contacts from the picker. Tap \"Show Picker\" to launch the view controller."; - break; - - case PickerMode.SingleProperty: - this.headerLabel.Text = "Selected Property:"; - this.descriptionLabel.Text = "This page allows you to select a single property from the picker. Tap \"Show Picker\" to launch the view controller."; - break; - - case PickerMode.MultipleProperties: - this.headerLabel.Text = "Selected Properties:"; - this.descriptionLabel.Text = "This page allows you to select one or more e-mail properties. Tap \"Show Picker\" to launch the view controller."; - break; - } - } - - partial void ShowPicker(NSObject sender) - { - this.UpdateInterface(true); - switch (this.Mode) - { - case PickerMode.SingleContact: - this.contactDelegate = new SingleContactPickerDelegate(this.Update); - var picker = new CNContactPickerViewController { Delegate = this.contactDelegate }; - base.PresentViewController(picker, true, null); - break; - - case PickerMode.MultupleContacts: - this.contactDelegate = new MultipleContactPickerDelegate(this.Update); - var contactsPicker = new CNContactPickerViewController { Delegate = this.contactDelegate }; - base.PresentViewController(contactsPicker, true, null); - break; - - case PickerMode.SingleProperty: - this.contactDelegate = new SinglePropertyPickerDelegate(this.Update); - var propertyPicker = new CNContactPickerViewController { Delegate = this.contactDelegate }; - propertyPicker.DisplayedPropertyKeys = new NSString[] { CNContactKey.GivenName, - CNContactKey.FamilyName, - CNContactKey.EmailAddresses, - CNContactKey.PhoneNumbers, - CNContactKey.PostalAddresses }; - base.PresentViewController(propertyPicker, true, null); - break; - - case PickerMode.MultipleProperties: - this.contactDelegate = new MultiplePropertyPickerDelegate(this.Update); - var propertiesPicker = new CNContactPickerViewController { Delegate = this.contactDelegate }; - propertiesPicker.PredicateForSelectionOfProperty = NSPredicate.FromFormat("key == 'emailAddresses'"); - base.PresentViewController(propertiesPicker, true, null); - break; - } - } - - private void UpdateInterface(bool hide) - { - this.tableView.Hidden = hide; - this.headerLabel.Hidden = hide; - - if (!hide) - { - this.tableView.ReloadData(); - } - } - - #region IUITableViewDataSource - - [Export("numberOfSectionsInTableView:")] - public nint NumberOfSections(UITableView tableView) - { - return this.sections.Count; - } - - public nint RowsInSection(UITableView tableView, nint section) - { - return this.sections[(int)section].Items.Count; - } - - public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var item = this.sections[indexPath.Section].Items[indexPath.Row]; - var cell = tableView.DequeueReusableCell("cellID"); - cell.TextLabel.Text = item; - - return cell; - } - - #endregion - - private void Update(List
items) - { - this.sections.Clear(); - this.sections.AddRange(items); - - // Show and update the table view. - this.UpdateInterface(false); - } - } -} \ No newline at end of file +namespace Contacts { + public partial class ContactPickerController : UIViewController, IUITableViewDelegate, IUITableViewDataSource { + private readonly List
sections = new List
(); + + private ICNContactPickerDelegate contactDelegate; + + public ContactPickerController (IntPtr handle) : base (handle) { } + + public PickerMode Mode { get; set; } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.tableView.Hidden = true; + this.headerLabel.Hidden = true; + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + switch (this.Mode) { + case PickerMode.SingleContact: + this.headerLabel.Text = "Selected Contact:"; + this.descriptionLabel.Text = "This page allows you to select a single contact from the picker. Tap \"Show Picker\" to launch the view controller."; + break; + + case PickerMode.MultupleContacts: + this.headerLabel.Text = "Selected Contacts:"; + this.descriptionLabel.Text = "This page allows you to select multiple contacts from the picker. Tap \"Show Picker\" to launch the view controller."; + break; + + case PickerMode.SingleProperty: + this.headerLabel.Text = "Selected Property:"; + this.descriptionLabel.Text = "This page allows you to select a single property from the picker. Tap \"Show Picker\" to launch the view controller."; + break; + + case PickerMode.MultipleProperties: + this.headerLabel.Text = "Selected Properties:"; + this.descriptionLabel.Text = "This page allows you to select one or more e-mail properties. Tap \"Show Picker\" to launch the view controller."; + break; + } + } + + partial void ShowPicker (NSObject sender) + { + this.UpdateInterface (true); + switch (this.Mode) { + case PickerMode.SingleContact: + this.contactDelegate = new SingleContactPickerDelegate (this.Update); + var picker = new CNContactPickerViewController { Delegate = this.contactDelegate }; + base.PresentViewController (picker, true, null); + break; + + case PickerMode.MultupleContacts: + this.contactDelegate = new MultipleContactPickerDelegate (this.Update); + var contactsPicker = new CNContactPickerViewController { Delegate = this.contactDelegate }; + base.PresentViewController (contactsPicker, true, null); + break; + + case PickerMode.SingleProperty: + this.contactDelegate = new SinglePropertyPickerDelegate (this.Update); + var propertyPicker = new CNContactPickerViewController { Delegate = this.contactDelegate }; + propertyPicker.DisplayedPropertyKeys = new NSString [] { CNContactKey.GivenName, + CNContactKey.FamilyName, + CNContactKey.EmailAddresses, + CNContactKey.PhoneNumbers, + CNContactKey.PostalAddresses }; + base.PresentViewController (propertyPicker, true, null); + break; + + case PickerMode.MultipleProperties: + this.contactDelegate = new MultiplePropertyPickerDelegate (this.Update); + var propertiesPicker = new CNContactPickerViewController { Delegate = this.contactDelegate }; + propertiesPicker.PredicateForSelectionOfProperty = NSPredicate.FromFormat ("key == 'emailAddresses'"); + base.PresentViewController (propertiesPicker, true, null); + break; + } + } + + private void UpdateInterface (bool hide) + { + this.tableView.Hidden = hide; + this.headerLabel.Hidden = hide; + + if (!hide) { + this.tableView.ReloadData (); + } + } + + #region IUITableViewDataSource + + [Export ("numberOfSectionsInTableView:")] + public nint NumberOfSections (UITableView tableView) + { + return this.sections.Count; + } + + public nint RowsInSection (UITableView tableView, nint section) + { + return this.sections [(int) section].Items.Count; + } + + public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var item = this.sections [indexPath.Section].Items [indexPath.Row]; + var cell = tableView.DequeueReusableCell ("cellID"); + cell.TextLabel.Text = item; + + return cell; + } + + #endregion + + private void Update (List
items) + { + this.sections.Clear (); + this.sections.AddRange (items); + + // Show and update the table view. + this.UpdateInterface (false); + } + } +} diff --git a/Contacts/Contacts/Helpers/ContactExtensions.cs b/Contacts/Contacts/Helpers/ContactExtensions.cs index 04ed26b5d..db9d164a7 100644 --- a/Contacts/Contacts/Helpers/ContactExtensions.cs +++ b/Contacts/Contacts/Helpers/ContactExtensions.cs @@ -1,103 +1,93 @@ -using System; +using System; using System.Linq; using Foundation; -namespace Contacts.Helpers -{ - public static class ContactExtensions - { - /// - /// The formatted name of a contact if there is one and "No Name", otherwise. - /// - public static string GetFormattedName(this CNContact contact) - { - var name = contact != null ? CNContactFormatter.GetStringFrom(contact, CNContactFormatterStyle.FullName)?.Trim() : null; - return !string.IsNullOrEmpty(name) ? name : "No Name"; - } - } +namespace Contacts.Helpers { + public static class ContactExtensions { + /// + /// The formatted name of a contact if there is one and "No Name", otherwise. + /// + public static string GetFormattedName (this CNContact contact) + { + var name = contact != null ? CNContactFormatter.GetStringFrom (contact, CNContactFormatterStyle.FullName)?.Trim () : null; + return !string.IsNullOrEmpty (name) ? name : "No Name"; + } + } - public static class ContactPropertyExtensions - { - /// - /// The name matching the key of the property. - /// - public static string GetNameMatchingKey(this CNContactProperty property) - { - switch (property.Key) - { - case "emailAddresses": - return "Email address"; - case "phoneNumbers": - return "Phone numbers"; - case "postalAddresses": - return "Postal address"; - default: - return null; - } - } + public static class ContactPropertyExtensions { + /// + /// The name matching the key of the property. + /// + public static string GetNameMatchingKey (this CNContactProperty property) + { + switch (property.Key) { + case "emailAddresses": + return "Email address"; + case "phoneNumbers": + return "Phone numbers"; + case "postalAddresses": + return "Postal address"; + default: + return null; + } + } - /// - /// The name matching the value of the property. - /// - public static string GetNameMatchingValue(this CNContactProperty property) - { - switch (property.Key) - { - case "emailAddresses": - return property.Value as NSString; - case "phoneNumbers": - if (property.Value is CNPhoneNumber phoneNumber) - { - return phoneNumber.StringValue; - } - break; + /// + /// The name matching the value of the property. + /// + public static string GetNameMatchingValue (this CNContactProperty property) + { + switch (property.Key) { + case "emailAddresses": + return property.Value as NSString; + case "phoneNumbers": + if (property.Value is CNPhoneNumber phoneNumber) { + return phoneNumber.StringValue; + } + break; - case "postalAddresses": - if (property.Value is CNPostalAddress address) - { - return address.GetFormattedPostalAddress(); - } - break; - } + case "postalAddresses": + if (property.Value is CNPostalAddress address) { + return address.GetFormattedPostalAddress (); + } + break; + } - return null; - } + return null; + } - /// - /// The name matching the localized label of the property. - /// - public static string GetNameMatchingLocalizedLabel(this CNContactProperty property) - { - var label = property?.Label; - if (!string.IsNullOrEmpty(label)) - { - var nativeLabel = new NSString(label); - switch (property?.Label) - { - case "emailAddresses": - return CNLabeledValue.LocalizeLabel(nativeLabel); - case "phoneNumbers": - return CNLabeledValue.LocalizeLabel(nativeLabel); - case "postalAddresses": - return CNLabeledValue.LocalizeLabel(nativeLabel); - } - } + /// + /// The name matching the localized label of the property. + /// + public static string GetNameMatchingLocalizedLabel (this CNContactProperty property) + { + var label = property?.Label; + if (!string.IsNullOrEmpty (label)) { + var nativeLabel = new NSString (label); + switch (property?.Label) { + case "emailAddresses": + return CNLabeledValue.LocalizeLabel (nativeLabel); + case "phoneNumbers": + return CNLabeledValue.LocalizeLabel (nativeLabel); + case "postalAddresses": + return CNLabeledValue.LocalizeLabel (nativeLabel); + } + } - return null; - } - } + return null; + } + } - public static class PostalAddressExtensions - { - /// - /// The formatted postal address. - /// - public static string GetFormattedPostalAddress(this CNPostalAddress postalAddress) - { - string[] address = { postalAddress.Street, postalAddress.City, postalAddress.State, postalAddress.PostalCode, postalAddress.Country }; - var filteredArray = address.Where(item => !string.IsNullOrEmpty(item)).ToArray(); + public static class PostalAddressExtensions { + /// + /// The formatted postal address. + /// + public static string GetFormattedPostalAddress (this CNPostalAddress postalAddress) + { + string [] address = { postalAddress.Street, postalAddress.City, postalAddress.State, postalAddress.PostalCode, postalAddress.Country }; + var filteredArray = address.Where (item => !string.IsNullOrEmpty (item)).ToArray (); - return filteredArray.Any() ? string.Join(", ", filteredArray) : null; - } - } -} \ No newline at end of file + return filteredArray.Any () ? string.Join (", ", filteredArray) : null; + } + } +} diff --git a/Contacts/Contacts/Helpers/Helper.cs b/Contacts/Contacts/Helpers/Helper.cs index cf5a99bda..83c740327 100644 --- a/Contacts/Contacts/Helpers/Helper.cs +++ b/Contacts/Contacts/Helpers/Helper.cs @@ -1,17 +1,15 @@ -using UIKit; +using UIKit; -namespace Contacts.Helpers -{ - public static class Helper - { - /// - /// The formatted name of a contact if there is one and "No Name", otherwise. - /// - public static void ShowAlert(this UIViewController controller, string message) - { - var alert = UIAlertController.Create("Status", message, UIAlertControllerStyle.ActionSheet); - alert.AddAction(UIAlertAction.Create("Ok", UIAlertActionStyle.Default, null)); - controller.PresentViewController(alert, true, null); - } - } -} \ No newline at end of file +namespace Contacts.Helpers { + public static class Helper { + /// + /// The formatted name of a contact if there is one and "No Name", otherwise. + /// + public static void ShowAlert (this UIViewController controller, string message) + { + var alert = UIAlertController.Create ("Status", message, UIAlertControllerStyle.ActionSheet); + alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); + controller.PresentViewController (alert, true, null); + } + } +} diff --git a/Contacts/Contacts/Helpers/PickerMode.cs b/Contacts/Contacts/Helpers/PickerMode.cs index 250f1901d..b34cda378 100644 --- a/Contacts/Contacts/Helpers/PickerMode.cs +++ b/Contacts/Contacts/Helpers/PickerMode.cs @@ -1,12 +1,10 @@ - -namespace Contacts.Helpers -{ - public enum PickerMode - { - Default = 0, - SingleContact = 1, - SingleProperty = 2, - MultupleContacts = 3, - MultipleProperties = 4 - } -} \ No newline at end of file + +namespace Contacts.Helpers { + public enum PickerMode { + Default = 0, + SingleContact = 1, + SingleProperty = 2, + MultupleContacts = 3, + MultipleProperties = 4 + } +} diff --git a/Contacts/Contacts/Helpers/PredicatePickerMode.cs b/Contacts/Contacts/Helpers/PredicatePickerMode.cs index af82c75ff..f5167ce98 100644 --- a/Contacts/Contacts/Helpers/PredicatePickerMode.cs +++ b/Contacts/Contacts/Helpers/PredicatePickerMode.cs @@ -1,10 +1,8 @@ - -namespace Contacts.Helpers -{ - public enum PredicatePickerMode - { - Default = 0, - EnableContacts = 1, - SelectContacts = 2, - } -} \ No newline at end of file + +namespace Contacts.Helpers { + public enum PredicatePickerMode { + Default = 0, + EnableContacts = 1, + SelectContacts = 2, + } +} diff --git a/Contacts/Contacts/Helpers/Section.cs b/Contacts/Contacts/Helpers/Section.cs index c9ee47170..e961ea870 100644 --- a/Contacts/Contacts/Helpers/Section.cs +++ b/Contacts/Contacts/Helpers/Section.cs @@ -1,9 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; -namespace Contacts.Helpers -{ - public class Section - { - public List Items { get; set; } - } -} \ No newline at end of file +namespace Contacts.Helpers { + public class Section { + public List Items { get; set; } + } +} diff --git a/Contacts/Contacts/Main.cs b/Contacts/Contacts/Main.cs index 4f66bbb7d..514097a53 100644 --- a/Contacts/Contacts/Main.cs +++ b/Contacts/Contacts/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Contacts -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace Contacts { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/Contacts/Contacts/PickerDelegates/MultipleContactPickerDelegate.cs b/Contacts/Contacts/PickerDelegates/MultipleContactPickerDelegate.cs index f9dea2dce..de34aa2c5 100644 --- a/Contacts/Contacts/PickerDelegates/MultipleContactPickerDelegate.cs +++ b/Contacts/Contacts/PickerDelegates/MultipleContactPickerDelegate.cs @@ -1,32 +1,28 @@ -using Contacts.Helpers; +using Contacts.Helpers; using ContactsUI; using System; using System.Collections.Generic; using System.Linq; -namespace Contacts.PickerDelegates -{ - public class MultipleContactPickerDelegate : CNContactPickerDelegate - { - private readonly Action> callback; +namespace Contacts.PickerDelegates { + public class MultipleContactPickerDelegate : CNContactPickerDelegate { + private readonly Action> callback; - public MultipleContactPickerDelegate(Action> callback) - { - this.callback = callback; - } + public MultipleContactPickerDelegate (Action> callback) + { + this.callback = callback; + } - public override void DidSelectContacts(CNContactPickerViewController picker, CNContact[] contacts) - { - if(contacts != null && contacts.Any()) - { - var section = new Section { Items = new List() }; - foreach (var contact in contacts) - { - section.Items.Add(contact.GetFormattedName()); - } + public override void DidSelectContacts (CNContactPickerViewController picker, CNContact [] contacts) + { + if (contacts != null && contacts.Any ()) { + var section = new Section { Items = new List () }; + foreach (var contact in contacts) { + section.Items.Add (contact.GetFormattedName ()); + } - this.callback(new List
{ section }); - } - } - } -} \ No newline at end of file + this.callback (new List
{ section }); + } + } + } +} diff --git a/Contacts/Contacts/PickerDelegates/MultiplePropertyPickerDelegate.cs b/Contacts/Contacts/PickerDelegates/MultiplePropertyPickerDelegate.cs index f46f7354d..600b37522 100644 --- a/Contacts/Contacts/PickerDelegates/MultiplePropertyPickerDelegate.cs +++ b/Contacts/Contacts/PickerDelegates/MultiplePropertyPickerDelegate.cs @@ -1,55 +1,48 @@ -using Contacts.Helpers; +using Contacts.Helpers; using ContactsUI; using System; using System.Collections.Generic; using System.Linq; -namespace Contacts.PickerDelegates -{ - public class MultiplePropertyPickerDelegate : CNContactPickerDelegate - { - private readonly Action> callback; - - public MultiplePropertyPickerDelegate(Action> callback) - { - this.callback = callback; - } - - public override void DidSelectContactProperties(CNContactPickerViewController picker, CNContactProperty[] contactProperties) - { - if (contactProperties != null && contactProperties.Any()) - { - var sections = new List
(); - foreach (var contactProperty in contactProperties) - { - var section = new Section { Items = new List() }; - - var nameKey = contactProperty.GetNameMatchingKey(); - if (!string.IsNullOrEmpty(nameKey)) - { - section.Items.Add($"Contact: {contactProperty.Contact.GetFormattedName()}"); - section.Items.Add($"Key: {nameKey}"); - } - - // Attempt to fetch the localized label of the property. - var localizedLabel = contactProperty.GetNameMatchingLocalizedLabel(); - if (!string.IsNullOrEmpty(localizedLabel)) - { - section.Items.Add($"Label : {localizedLabel}"); - } - - // Attempt to fetch the value of the property. - var value = contactProperty.GetNameMatchingValue(); - if (!string.IsNullOrEmpty(value)) - { - section.Items.Add($"Value: {value}"); - } - - sections.Add(section); - } - - this.callback(sections); - } - } - } -} \ No newline at end of file +namespace Contacts.PickerDelegates { + public class MultiplePropertyPickerDelegate : CNContactPickerDelegate { + private readonly Action> callback; + + public MultiplePropertyPickerDelegate (Action> callback) + { + this.callback = callback; + } + + public override void DidSelectContactProperties (CNContactPickerViewController picker, CNContactProperty [] contactProperties) + { + if (contactProperties != null && contactProperties.Any ()) { + var sections = new List
(); + foreach (var contactProperty in contactProperties) { + var section = new Section { Items = new List () }; + + var nameKey = contactProperty.GetNameMatchingKey (); + if (!string.IsNullOrEmpty (nameKey)) { + section.Items.Add ($"Contact: {contactProperty.Contact.GetFormattedName ()}"); + section.Items.Add ($"Key: {nameKey}"); + } + + // Attempt to fetch the localized label of the property. + var localizedLabel = contactProperty.GetNameMatchingLocalizedLabel (); + if (!string.IsNullOrEmpty (localizedLabel)) { + section.Items.Add ($"Label : {localizedLabel}"); + } + + // Attempt to fetch the value of the property. + var value = contactProperty.GetNameMatchingValue (); + if (!string.IsNullOrEmpty (value)) { + section.Items.Add ($"Value: {value}"); + } + + sections.Add (section); + } + + this.callback (sections); + } + } + } +} diff --git a/Contacts/Contacts/PickerDelegates/SingleContactPickerDelegate.cs b/Contacts/Contacts/PickerDelegates/SingleContactPickerDelegate.cs index 038d815cc..21e8707cb 100644 --- a/Contacts/Contacts/PickerDelegates/SingleContactPickerDelegate.cs +++ b/Contacts/Contacts/PickerDelegates/SingleContactPickerDelegate.cs @@ -1,30 +1,27 @@ -using Contacts.Helpers; +using Contacts.Helpers; using ContactsUI; using System; using System.Collections.Generic; -namespace Contacts.PickerDelegates -{ - public class SingleContactPickerDelegate : CNContactPickerDelegate - { - private readonly Action> callback; +namespace Contacts.PickerDelegates { + public class SingleContactPickerDelegate : CNContactPickerDelegate { + private readonly Action> callback; - public SingleContactPickerDelegate(Action> callback) - { - this.callback = callback; - } + public SingleContactPickerDelegate (Action> callback) + { + this.callback = callback; + } - public override void DidSelectContact(CNContactPickerViewController picker, CNContact contact) - { - if (contact != null) - { - var sections = new List
- { - new Section { Items = new List { contact.GetFormattedName() } } - }; + public override void DidSelectContact (CNContactPickerViewController picker, CNContact contact) + { + if (contact != null) { + var sections = new List
+ { + new Section { Items = new List { contact.GetFormattedName() } } + }; - this.callback(sections); - } - } - } -} \ No newline at end of file + this.callback (sections); + } + } + } +} diff --git a/Contacts/Contacts/PickerDelegates/SinglePropertyPickerDelegate.cs b/Contacts/Contacts/PickerDelegates/SinglePropertyPickerDelegate.cs index cbded3fcb..118d47199 100644 --- a/Contacts/Contacts/PickerDelegates/SinglePropertyPickerDelegate.cs +++ b/Contacts/Contacts/PickerDelegates/SinglePropertyPickerDelegate.cs @@ -1,50 +1,44 @@ -using Contacts.Helpers; +using Contacts.Helpers; using ContactsUI; using System; using System.Collections.Generic; -namespace Contacts.PickerDelegates -{ - public class SinglePropertyPickerDelegate : CNContactPickerDelegate - { - private readonly Action> callback; +namespace Contacts.PickerDelegates { + public class SinglePropertyPickerDelegate : CNContactPickerDelegate { + private readonly Action> callback; - public SinglePropertyPickerDelegate(Action> callback) - { - this.callback = callback; - } + public SinglePropertyPickerDelegate (Action> callback) + { + this.callback = callback; + } - public override void DidSelectContactProperty(CNContactPickerViewController picker, CNContactProperty contactProperty) - { - if (contactProperty != null) - { - var sections = new List
(); - var section = new Section { Items = new List() }; + public override void DidSelectContactProperty (CNContactPickerViewController picker, CNContactProperty contactProperty) + { + if (contactProperty != null) { + var sections = new List
(); + var section = new Section { Items = new List () }; - var nameKey = contactProperty.GetNameMatchingKey(); - if (!string.IsNullOrEmpty(nameKey)) - { - section.Items.Add($"Contact: {contactProperty.Contact.GetFormattedName()}"); - section.Items.Add($"Key: {nameKey}"); - } + var nameKey = contactProperty.GetNameMatchingKey (); + if (!string.IsNullOrEmpty (nameKey)) { + section.Items.Add ($"Contact: {contactProperty.Contact.GetFormattedName ()}"); + section.Items.Add ($"Key: {nameKey}"); + } - // Attempt to fetch the localized label of the property. - var localizedLabel = contactProperty.GetNameMatchingLocalizedLabel(); - if (!string.IsNullOrEmpty(localizedLabel)) - { - section.Items.Add($"Label : {localizedLabel}"); - } + // Attempt to fetch the localized label of the property. + var localizedLabel = contactProperty.GetNameMatchingLocalizedLabel (); + if (!string.IsNullOrEmpty (localizedLabel)) { + section.Items.Add ($"Label : {localizedLabel}"); + } - // Attempt to fetch the value of the property. - var value = contactProperty.GetNameMatchingValue(); - if (!string.IsNullOrEmpty(value)) - { - section.Items.Add($"Value: {value}"); - } + // Attempt to fetch the value of the property. + var value = contactProperty.GetNameMatchingValue (); + if (!string.IsNullOrEmpty (value)) { + section.Items.Add ($"Value: {value}"); + } - sections.Add(section); - this.callback(sections); - } - } - } -} \ No newline at end of file + sections.Add (section); + this.callback (sections); + } + } + } +} diff --git a/Contacts/Contacts/PredicateContactViewController.cs b/Contacts/Contacts/PredicateContactViewController.cs index 361b73873..29ec47d1f 100644 --- a/Contacts/Contacts/PredicateContactViewController.cs +++ b/Contacts/Contacts/PredicateContactViewController.cs @@ -4,167 +4,155 @@ using System; using UIKit; -namespace Contacts -{ - public partial class PredicateContactViewController : UITableViewController, ICNContactPickerDelegate - { - private UITableViewCell previousSelectedCell; - - private string message; - - public PredicatePickerMode Mode { get; internal set; } - - public PredicateContactViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - var index = NSIndexPath.FromRowSection(0, 0); - base.TableView.SelectRow(index, false, UITableViewScrollPosition.Top); - this.previousSelectedCell = base.TableView.CellAt(index); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - if (!string.IsNullOrEmpty(this.message)) - { - base.NavigationController.ShowAlert(this.message); - this.message = null; - } - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - if (indexPath.Section == 0) - { - var selectedCell = tableView.CellAt(indexPath); - if (selectedCell != this.previousSelectedCell) - { - selectedCell.Accessory = UITableViewCellAccessory.Checkmark; - - if (this.previousSelectedCell != null) - { - this.previousSelectedCell.Accessory = UITableViewCellAccessory.None; - } - - this.previousSelectedCell = selectedCell; - } - } - else - { - // show picker - this.ShowPicker(); - } - - tableView.DeselectRow(indexPath, true); - } - - private void ShowPicker() - { - var index = base.TableView.IndexPathForCell(this.previousSelectedCell); - switch (index.Row) - { - case 0: - // Enable all contacts in the contacts picker view. - this.HandleAllContacts(); - break; - case 1: - // Only enable contacts with email addresses in the contacts picker view. - this.HandleContactsWithEmailAddresses(); - break; - case 2: - // Only enable contacts with postal addresses in the contacts picker view. - this.HandleContactsWithPostalAddresses(); - break; - case 3: - // Only enable contacts with 2 or more phone numbers in the contacts picker view. - this.HandleContactsWithPhoneNumbers(); - break; - case 4: - // Only enable contacts with a profile picture in the contacts picker view. - this.HandleContactsWithProfilePicture(); - break; - } - } - - private void HandleContactsWithProfilePicture() - { - var picker = this.CreatePicker(); - - // Only show contacts with email addresses. - picker.PredicateForEnablingContact = NSPredicate.FromFormat("imageDataAvailable == true"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleContactsWithPhoneNumbers() - { - var picker = this.CreatePicker(); - - // Only show contacts with email addresses. - picker.PredicateForEnablingContact = NSPredicate.FromFormat("phoneNumbers.@count > 1"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleContactsWithPostalAddresses() - { - var picker = this.CreatePicker(); - - // Only show contacts with email addresses. - picker.PredicateForEnablingContact = NSPredicate.FromFormat("postalAddresses.@count > 0"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleContactsWithEmailAddresses() - { - var picker = this.CreatePicker(); - - // Only show contacts with email addresses. - picker.PredicateForEnablingContact = NSPredicate.FromFormat("emailAddresses.@count > 0"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleAllContacts() - { - var picker = this.CreatePicker(); - base.NavigationController.PresentViewController(picker, true, null); - } - - private CNContactPickerViewController CreatePicker() - { - var controller = new CNContactPickerViewController(); - if (this.Mode == PredicatePickerMode.SelectContacts) - { - controller.Delegate = this; - } - - return controller; - } - - #region ICNContactPickerDelegate - - [Export("contactPicker:didSelectContact:")] - public void DidSelectContact(CNContactPickerViewController picker, CNContact contact) - { - var name = contact?.GetFormattedName(); - if (!string.IsNullOrEmpty(name)) - { - this.message = $"{name} was selected."; - } - } - - #endregion - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (this.previousSelectedCell != null) - { - this.previousSelectedCell.Dispose(); - this.previousSelectedCell = null; - } - } - } -} \ No newline at end of file +namespace Contacts { + public partial class PredicateContactViewController : UITableViewController, ICNContactPickerDelegate { + private UITableViewCell previousSelectedCell; + + private string message; + + public PredicatePickerMode Mode { get; internal set; } + + public PredicateContactViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var index = NSIndexPath.FromRowSection (0, 0); + base.TableView.SelectRow (index, false, UITableViewScrollPosition.Top); + this.previousSelectedCell = base.TableView.CellAt (index); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + if (!string.IsNullOrEmpty (this.message)) { + base.NavigationController.ShowAlert (this.message); + this.message = null; + } + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + if (indexPath.Section == 0) { + var selectedCell = tableView.CellAt (indexPath); + if (selectedCell != this.previousSelectedCell) { + selectedCell.Accessory = UITableViewCellAccessory.Checkmark; + + if (this.previousSelectedCell != null) { + this.previousSelectedCell.Accessory = UITableViewCellAccessory.None; + } + + this.previousSelectedCell = selectedCell; + } + } else { + // show picker + this.ShowPicker (); + } + + tableView.DeselectRow (indexPath, true); + } + + private void ShowPicker () + { + var index = base.TableView.IndexPathForCell (this.previousSelectedCell); + switch (index.Row) { + case 0: + // Enable all contacts in the contacts picker view. + this.HandleAllContacts (); + break; + case 1: + // Only enable contacts with email addresses in the contacts picker view. + this.HandleContactsWithEmailAddresses (); + break; + case 2: + // Only enable contacts with postal addresses in the contacts picker view. + this.HandleContactsWithPostalAddresses (); + break; + case 3: + // Only enable contacts with 2 or more phone numbers in the contacts picker view. + this.HandleContactsWithPhoneNumbers (); + break; + case 4: + // Only enable contacts with a profile picture in the contacts picker view. + this.HandleContactsWithProfilePicture (); + break; + } + } + + private void HandleContactsWithProfilePicture () + { + var picker = this.CreatePicker (); + + // Only show contacts with email addresses. + picker.PredicateForEnablingContact = NSPredicate.FromFormat ("imageDataAvailable == true"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleContactsWithPhoneNumbers () + { + var picker = this.CreatePicker (); + + // Only show contacts with email addresses. + picker.PredicateForEnablingContact = NSPredicate.FromFormat ("phoneNumbers.@count > 1"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleContactsWithPostalAddresses () + { + var picker = this.CreatePicker (); + + // Only show contacts with email addresses. + picker.PredicateForEnablingContact = NSPredicate.FromFormat ("postalAddresses.@count > 0"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleContactsWithEmailAddresses () + { + var picker = this.CreatePicker (); + + // Only show contacts with email addresses. + picker.PredicateForEnablingContact = NSPredicate.FromFormat ("emailAddresses.@count > 0"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleAllContacts () + { + var picker = this.CreatePicker (); + base.NavigationController.PresentViewController (picker, true, null); + } + + private CNContactPickerViewController CreatePicker () + { + var controller = new CNContactPickerViewController (); + if (this.Mode == PredicatePickerMode.SelectContacts) { + controller.Delegate = this; + } + + return controller; + } + + #region ICNContactPickerDelegate + + [Export ("contactPicker:didSelectContact:")] + public void DidSelectContact (CNContactPickerViewController picker, CNContact contact) + { + var name = contact?.GetFormattedName (); + if (!string.IsNullOrEmpty (name)) { + this.message = $"{name} was selected."; + } + } + + #endregion + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + if (this.previousSelectedCell != null) { + this.previousSelectedCell.Dispose (); + this.previousSelectedCell = null; + } + } + } +} diff --git a/Contacts/Contacts/PredicatePropertiesViewController.cs b/Contacts/Contacts/PredicatePropertiesViewController.cs index c29d9f4f9..d1ac496ee 100644 --- a/Contacts/Contacts/PredicatePropertiesViewController.cs +++ b/Contacts/Contacts/PredicatePropertiesViewController.cs @@ -4,160 +4,148 @@ using System; using UIKit; -namespace Contacts -{ - public partial class PredicatePropertiesViewController : UITableViewController, ICNContactPickerDelegate - { - private UITableViewCell previousSelectedCell; - - private string message; - - public PredicatePropertiesViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - var index = NSIndexPath.FromRowSection(0, 0); - base.TableView.SelectRow(index, false, UITableViewScrollPosition.Top); - this.previousSelectedCell = base.TableView.CellAt(index); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - if (!string.IsNullOrEmpty(this.message)) - { - base.NavigationController.ShowAlert(this.message); - this.message = null; - } - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - if (indexPath.Section == 0) - { - var selectedCell = tableView.CellAt(indexPath); - if (selectedCell != this.previousSelectedCell) - { - selectedCell.Accessory = UITableViewCellAccessory.Checkmark; - - if (this.previousSelectedCell != null) - { - this.previousSelectedCell.Accessory = UITableViewCellAccessory.None; - } - - this.previousSelectedCell = selectedCell; - } - } - else - { - // show picker - this.ShowPicker(); - } - - tableView.DeselectRow(indexPath, true); - } - - private void ShowPicker() - { - var index = base.TableView.IndexPathForCell(this.previousSelectedCell); - switch (index.Row) - { - case 0: - // Only show the given and family names, email addresses, phone numbers, and postal addresses of a contact. - this.HandleAllContacts(); - break; - case 1: - // When users select a contact's email address, it dismisses the view controller and returns the email address using - // CNContactPickerDelegate's contact​Picker(_:​did​Select:​). When users select other properties, it implements their default action. - this.HandleContactsWithEmailAddresses(); - break; - case 2: - // When users select a contact's postal address, it dismisses the view controller and returns the birthday using - // CNContactPickerDelegate's contact​Picker(_:​did​Select:​). When users select other properties, it implements their default action. - this.HandleContactsWithPostalAddresses(); - break; - case 3: - // When users select a contact's phone number, it dismisses the view controller and returns the phone number using - // CNContactPickerDelegate's contact​Picker(_:​did​Select:​). When users select other properties, it implements their default action. - this.HandleContactsWithPhoneNumbers(); - break; - } - } - - private void HandleContactsWithPhoneNumbers() - { - var picker = new CNContactPickerViewController { Delegate = this }; - - // Only show contacts with email addresses. - picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat("key == 'phoneNumbers'"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleContactsWithPostalAddresses() - { - var picker = new CNContactPickerViewController { Delegate = this }; - - // Only show contacts with email addresses. - picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat("key == 'postalAddresses'"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleContactsWithEmailAddresses() - { - var picker = new CNContactPickerViewController { Delegate = this }; - - // Only show contacts with email addresses. - picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat("(key == 'emailAddresses')"); - base.NavigationController.PresentViewController(picker, true, null); - } - - private void HandleAllContacts() - { - var picker = new CNContactPickerViewController { Delegate = this }; - /* +namespace Contacts { + public partial class PredicatePropertiesViewController : UITableViewController, ICNContactPickerDelegate { + private UITableViewCell previousSelectedCell; + + private string message; + + public PredicatePropertiesViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var index = NSIndexPath.FromRowSection (0, 0); + base.TableView.SelectRow (index, false, UITableViewScrollPosition.Top); + this.previousSelectedCell = base.TableView.CellAt (index); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + if (!string.IsNullOrEmpty (this.message)) { + base.NavigationController.ShowAlert (this.message); + this.message = null; + } + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + if (indexPath.Section == 0) { + var selectedCell = tableView.CellAt (indexPath); + if (selectedCell != this.previousSelectedCell) { + selectedCell.Accessory = UITableViewCellAccessory.Checkmark; + + if (this.previousSelectedCell != null) { + this.previousSelectedCell.Accessory = UITableViewCellAccessory.None; + } + + this.previousSelectedCell = selectedCell; + } + } else { + // show picker + this.ShowPicker (); + } + + tableView.DeselectRow (indexPath, true); + } + + private void ShowPicker () + { + var index = base.TableView.IndexPathForCell (this.previousSelectedCell); + switch (index.Row) { + case 0: + // Only show the given and family names, email addresses, phone numbers, and postal addresses of a contact. + this.HandleAllContacts (); + break; + case 1: + // When users select a contact's email address, it dismisses the view controller and returns the email address using + // CNContactPickerDelegate's contact​Picker(_:​did​Select:​). When users select other properties, it implements their default action. + this.HandleContactsWithEmailAddresses (); + break; + case 2: + // When users select a contact's postal address, it dismisses the view controller and returns the birthday using + // CNContactPickerDelegate's contact​Picker(_:​did​Select:​). When users select other properties, it implements their default action. + this.HandleContactsWithPostalAddresses (); + break; + case 3: + // When users select a contact's phone number, it dismisses the view controller and returns the phone number using + // CNContactPickerDelegate's contact​Picker(_:​did​Select:​). When users select other properties, it implements their default action. + this.HandleContactsWithPhoneNumbers (); + break; + } + } + + private void HandleContactsWithPhoneNumbers () + { + var picker = new CNContactPickerViewController { Delegate = this }; + + // Only show contacts with email addresses. + picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat ("key == 'phoneNumbers'"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleContactsWithPostalAddresses () + { + var picker = new CNContactPickerViewController { Delegate = this }; + + // Only show contacts with email addresses. + picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat ("key == 'postalAddresses'"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleContactsWithEmailAddresses () + { + var picker = new CNContactPickerViewController { Delegate = this }; + + // Only show contacts with email addresses. + picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat ("(key == 'emailAddresses')"); + base.NavigationController.PresentViewController (picker, true, null); + } + + private void HandleAllContacts () + { + var picker = new CNContactPickerViewController { Delegate = this }; + /* Only show the given and family names, email addresses, phone numbers, and postal addresses of a contact. */ - picker.DisplayedPropertyKeys = new NSString[] - { - CNContactKey.GivenName, - CNContactKey.FamilyName, - CNContactKey.EmailAddresses, - CNContactKey.PhoneNumbers, - CNContactKey.PostalAddresses - }; - base.NavigationController.PresentViewController(picker, true, null); - } - - #region ICNContactPickerDelegate - - [Export("contactPicker:didSelectContactProperty:")] - public void DidSelectContactProperty(CNContactPickerViewController picker, CNContactProperty contactProperty) - { - if (contactProperty != null) - { - var value = contactProperty.GetNameMatchingValue(); - var key = contactProperty.GetNameMatchingKey(); - if (!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(key)) - { - this.message = $"{contactProperty.Contact.GetFormattedName()}'s {key} ({value}) was selected."; - } - } - } - - #endregion - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (this.previousSelectedCell != null) - { - this.previousSelectedCell.Dispose(); - this.previousSelectedCell = null; - } - } - } -} \ No newline at end of file + picker.DisplayedPropertyKeys = new NSString [] + { + CNContactKey.GivenName, + CNContactKey.FamilyName, + CNContactKey.EmailAddresses, + CNContactKey.PhoneNumbers, + CNContactKey.PostalAddresses + }; + base.NavigationController.PresentViewController (picker, true, null); + } + + #region ICNContactPickerDelegate + + [Export ("contactPicker:didSelectContactProperty:")] + public void DidSelectContactProperty (CNContactPickerViewController picker, CNContactProperty contactProperty) + { + if (contactProperty != null) { + var value = contactProperty.GetNameMatchingValue (); + var key = contactProperty.GetNameMatchingKey (); + if (!string.IsNullOrEmpty (value) && !string.IsNullOrEmpty (key)) { + this.message = $"{contactProperty.Contact.GetFormattedName ()}'s {key} ({value}) was selected."; + } + } + } + + #endregion + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + if (this.previousSelectedCell != null) { + this.previousSelectedCell.Dispose (); + this.previousSelectedCell = null; + } + } + } +} diff --git a/Contacts/Contacts/RootViewController.cs b/Contacts/Contacts/RootViewController.cs index 1848b7c5b..eb9d91c47 100644 --- a/Contacts/Contacts/RootViewController.cs +++ b/Contacts/Contacts/RootViewController.cs @@ -6,227 +6,195 @@ using System.Linq; using UIKit; -namespace Contacts -{ - public partial class RootViewController : UITableViewController, ICNContactViewControllerDelegate - { - private readonly CNContactStore store = new CNContactStore(); - - public RootViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.CheckContactsAccess(); - } - - private void CheckContactsAccess() - { - var status = CNContactStore.GetAuthorizationStatus(CNEntityType.Contacts); - switch (status) - { - // Access was granted. Update the UI with the default navigation menu. - case CNAuthorizationStatus.Authorized: - Console.WriteLine("App is authorized"); - break; - - case CNAuthorizationStatus.NotDetermined: - this.store.RequestAccess(CNEntityType.Contacts, (granted, _) => - { - if (granted) - { - Console.WriteLine("App is authorized"); - } - }); - break; - - // Access was denied or restricted. - case CNAuthorizationStatus.Restricted: - case CNAuthorizationStatus.Denied: - Console.WriteLine("Access denied or restricted."); - break; - } - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "PickerSegue") - { - if (segue.DestinationViewController is ContactPickerController contactPickerController) - { - contactPickerController.Mode = (PickerMode)(sender as NSNumber).Int32Value; - } - } - else if (segue.Identifier == "PredicatePickerSegue") - { - if (segue.DestinationViewController is PredicateContactViewController predicateContactViewController) - { - predicateContactViewController.Mode = (PredicatePickerMode)(sender as NSNumber).Int32Value; - } - } - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var selectedCell = tableView.CellAt(indexPath); - - // regular contacts logic - if (indexPath.Section == 0) - { - this.PerformContactAction(selectedCell); - } - // picker logic - else if (indexPath.Section == 1) - { - this.PerformContactPickerAction(selectedCell); - } - // predicate picker logic - else if (indexPath.Section == 2) - { - this.PerformContactPredicatePickerAction(selectedCell); - } - - tableView.DeselectRow(indexPath, false); - } - - #region Contact predicate picker logic (3d section) - - private void PerformContactPredicatePickerAction(UITableViewCell selectedCell) - { - if (selectedCell == this.enableContactsPredicateCell) - { - base.PerformSegue("PredicatePickerSegue", new NSNumber((int)PredicatePickerMode.EnableContacts)); - } - else if (selectedCell == this.selectContactsPredicateCell) - { - base.PerformSegue("PredicatePickerSegue", new NSNumber((int)PredicatePickerMode.SelectContacts)); - } - } - - #endregion - - #region Contact picker logic (2st section) - - private void PerformContactPickerAction(UITableViewCell selectedCell) - { - var mode = default(PickerMode); - if (selectedCell == this.pickSingleContactCell) - { - mode = PickerMode.SingleContact; - } - else if (selectedCell == this.pickSinglePropertyCell) - { - mode = PickerMode.SingleProperty; - } - else if (selectedCell == this.pickMultipleContactsCell) - { - mode = PickerMode.MultupleContacts; - } - else if (selectedCell == this.pickMultiplePropertiesCell) - { - mode = PickerMode.MultipleProperties; - } - - base.PerformSegue("PickerSegue", new NSNumber((int)mode)); - } - - #endregion - - #region Regular contact logic (1st section) - - private void PerformContactAction(UITableViewCell selectedCell) - { - if (selectedCell == this.createNewContactCell) - { - // Create an empty contact view controller. - var contactViewController = CNContactViewController.FromNewContact(null); - // Set its delegate. - contactViewController.Delegate = this; - // Push it using the navigation controller. - base.NavigationController.PushViewController(contactViewController, true); - } - // Called when users tap "Create New Contact With Existing Data" in the UI. - // Create and launch a contacts view controller with pre - filled fields. - else if (selectedCell == this.createNewContactExistingData) - { - var contact = new CNMutableContact - { - // Given and family names. - FamilyName = Name.Family, - GivenName = Name.Given, - }; - - // Phone numbers. - contact.PhoneNumbers = new CNLabeledValue[] - { - new CNLabeledValue(PhoneNumber.IPhone, - new CNPhoneNumber(PhoneNumber.IPhone)), - new CNLabeledValue(PhoneNumber.Mobile, - new CNPhoneNumber(PhoneNumber.Mobile)) - }; - - // Postal address. - var homeAddress = new CNMutablePostalAddress - { - Street = Address.Street, - City = Address.City, - State = Address.State, - PostalCode = Address.PostalCode, - }; - - contact.PostalAddresses = new CNLabeledValue[] { new CNLabeledValue(CNLabelKey.Home, homeAddress) }; - - // Create a contact view controller with the above contact. - var contactViewController = CNContactViewController.FromNewContact(contact); - // Set its delegate. - contactViewController.Delegate = this; - // Push it using the navigation controller. - base.NavigationController.PushViewController(contactViewController, true); - } - // Called when users tap "Edit Unknown Contact" in the UI. - // The view controller displays some contact information that you can either add to an existing contact or use them to create a new contact. - else if (selectedCell == this.editContactCell) - { - var contact = new CNMutableContact(); - - // Phone number. - contact.PhoneNumbers = new CNLabeledValue[] { new CNLabeledValue(CNLabelPhoneNumberKey.iPhone, new CNPhoneNumber(PhoneNumber.Mobile)) }; - - // Postal address. - var homeAddress = new CNMutablePostalAddress() - { - Street = Address.Street, - City = Address.City, - State = Address.State, - PostalCode = Address.PostalCode, - }; - - contact.PostalAddresses = new CNLabeledValue[] { new CNLabeledValue(CNLabelKey.Home, homeAddress) }; - - // Create a view controller that allows editing. - var contactViewController = CNContactViewController.FromUnknownContact(contact); - contactViewController.AllowsEditing = true; - contactViewController.ContactStore = new CNContactStore(); - contactViewController.Delegate = this; - - // Push the unknown contact in the view controler. - base.NavigationController.PushViewController(contactViewController, true); - } - // Called when users tap "Display and Edit Contact" in the UI. - // Searches for the contact specified whose last name and first name are respectively specified by contact.family and contact.given - else if (selectedCell == this.displayEditCell) - { - var name = $"{Name.Given} {Name.Family}"; - this.FetchContact(name, (contacts) => - { - if (contacts.Any()) - { - var contactViewController = CNContactViewController.FromContact(contacts[0]); - contactViewController.AllowsEditing = true; - contactViewController.AllowsActions = true; - contactViewController.Delegate = this; - - /* +namespace Contacts { + public partial class RootViewController : UITableViewController, ICNContactViewControllerDelegate { + private readonly CNContactStore store = new CNContactStore (); + + public RootViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.CheckContactsAccess (); + } + + private void CheckContactsAccess () + { + var status = CNContactStore.GetAuthorizationStatus (CNEntityType.Contacts); + switch (status) { + // Access was granted. Update the UI with the default navigation menu. + case CNAuthorizationStatus.Authorized: + Console.WriteLine ("App is authorized"); + break; + + case CNAuthorizationStatus.NotDetermined: + this.store.RequestAccess (CNEntityType.Contacts, (granted, _) => { + if (granted) { + Console.WriteLine ("App is authorized"); + } + }); + break; + + // Access was denied or restricted. + case CNAuthorizationStatus.Restricted: + case CNAuthorizationStatus.Denied: + Console.WriteLine ("Access denied or restricted."); + break; + } + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "PickerSegue") { + if (segue.DestinationViewController is ContactPickerController contactPickerController) { + contactPickerController.Mode = (PickerMode) (sender as NSNumber).Int32Value; + } + } else if (segue.Identifier == "PredicatePickerSegue") { + if (segue.DestinationViewController is PredicateContactViewController predicateContactViewController) { + predicateContactViewController.Mode = (PredicatePickerMode) (sender as NSNumber).Int32Value; + } + } + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var selectedCell = tableView.CellAt (indexPath); + + // regular contacts logic + if (indexPath.Section == 0) { + this.PerformContactAction (selectedCell); + } + // picker logic + else if (indexPath.Section == 1) { + this.PerformContactPickerAction (selectedCell); + } + // predicate picker logic + else if (indexPath.Section == 2) { + this.PerformContactPredicatePickerAction (selectedCell); + } + + tableView.DeselectRow (indexPath, false); + } + + #region Contact predicate picker logic (3d section) + + private void PerformContactPredicatePickerAction (UITableViewCell selectedCell) + { + if (selectedCell == this.enableContactsPredicateCell) { + base.PerformSegue ("PredicatePickerSegue", new NSNumber ((int) PredicatePickerMode.EnableContacts)); + } else if (selectedCell == this.selectContactsPredicateCell) { + base.PerformSegue ("PredicatePickerSegue", new NSNumber ((int) PredicatePickerMode.SelectContacts)); + } + } + + #endregion + + #region Contact picker logic (2st section) + + private void PerformContactPickerAction (UITableViewCell selectedCell) + { + var mode = default (PickerMode); + if (selectedCell == this.pickSingleContactCell) { + mode = PickerMode.SingleContact; + } else if (selectedCell == this.pickSinglePropertyCell) { + mode = PickerMode.SingleProperty; + } else if (selectedCell == this.pickMultipleContactsCell) { + mode = PickerMode.MultupleContacts; + } else if (selectedCell == this.pickMultiplePropertiesCell) { + mode = PickerMode.MultipleProperties; + } + + base.PerformSegue ("PickerSegue", new NSNumber ((int) mode)); + } + + #endregion + + #region Regular contact logic (1st section) + + private void PerformContactAction (UITableViewCell selectedCell) + { + if (selectedCell == this.createNewContactCell) { + // Create an empty contact view controller. + var contactViewController = CNContactViewController.FromNewContact (null); + // Set its delegate. + contactViewController.Delegate = this; + // Push it using the navigation controller. + base.NavigationController.PushViewController (contactViewController, true); + } + // Called when users tap "Create New Contact With Existing Data" in the UI. + // Create and launch a contacts view controller with pre - filled fields. + else if (selectedCell == this.createNewContactExistingData) { + var contact = new CNMutableContact { + // Given and family names. + FamilyName = Name.Family, + GivenName = Name.Given, + }; + + // Phone numbers. + contact.PhoneNumbers = new CNLabeledValue [] + { + new CNLabeledValue(PhoneNumber.IPhone, + new CNPhoneNumber(PhoneNumber.IPhone)), + new CNLabeledValue(PhoneNumber.Mobile, + new CNPhoneNumber(PhoneNumber.Mobile)) + }; + + // Postal address. + var homeAddress = new CNMutablePostalAddress { + Street = Address.Street, + City = Address.City, + State = Address.State, + PostalCode = Address.PostalCode, + }; + + contact.PostalAddresses = new CNLabeledValue [] { new CNLabeledValue (CNLabelKey.Home, homeAddress) }; + + // Create a contact view controller with the above contact. + var contactViewController = CNContactViewController.FromNewContact (contact); + // Set its delegate. + contactViewController.Delegate = this; + // Push it using the navigation controller. + base.NavigationController.PushViewController (contactViewController, true); + } + // Called when users tap "Edit Unknown Contact" in the UI. + // The view controller displays some contact information that you can either add to an existing contact or use them to create a new contact. + else if (selectedCell == this.editContactCell) { + var contact = new CNMutableContact (); + + // Phone number. + contact.PhoneNumbers = new CNLabeledValue [] { new CNLabeledValue (CNLabelPhoneNumberKey.iPhone, new CNPhoneNumber (PhoneNumber.Mobile)) }; + + // Postal address. + var homeAddress = new CNMutablePostalAddress () { + Street = Address.Street, + City = Address.City, + State = Address.State, + PostalCode = Address.PostalCode, + }; + + contact.PostalAddresses = new CNLabeledValue [] { new CNLabeledValue (CNLabelKey.Home, homeAddress) }; + + // Create a view controller that allows editing. + var contactViewController = CNContactViewController.FromUnknownContact (contact); + contactViewController.AllowsEditing = true; + contactViewController.ContactStore = new CNContactStore (); + contactViewController.Delegate = this; + + // Push the unknown contact in the view controler. + base.NavigationController.PushViewController (contactViewController, true); + } + // Called when users tap "Display and Edit Contact" in the UI. + // Searches for the contact specified whose last name and first name are respectively specified by contact.family and contact.given + else if (selectedCell == this.displayEditCell) { + var name = $"{Name.Given} {Name.Family}"; + this.FetchContact (name, (contacts) => { + if (contacts.Any ()) { + var contactViewController = CNContactViewController.FromContact (contacts [0]); + contactViewController.AllowsEditing = true; + contactViewController.AllowsActions = true; + contactViewController.Delegate = this; + + /* Set the view controller's highlightProperty if highlightedPropertyIdentifier exists. Thus, ensuring that the contact's phone number specified by @@ -234,89 +202,79 @@ highlightedPropertyIdentifier will be highlighted in the UI. */ - var highlightedPropertyIdentifiers = contacts[0].PhoneNumbers.FirstOrDefault()?.Identifier; - if (!string.IsNullOrEmpty(highlightedPropertyIdentifiers)) - { - contactViewController.HighlightProperty(new NSString("phoneNumbers"), highlightedPropertyIdentifiers); - } - - // Show the view controller. - base.NavigationController.PushViewController(contactViewController, true); - } - else - { - this.ShowAlert($"Could not find {name} in Contacts."); - } - }); - } - } - - /// - /// Exising contacts matching the specified name. - /// - private void FetchContact(string name, Action completion) - { - var result = store.GetUnifiedContacts(CNContact.GetPredicateForContacts(name), - new ICNKeyDescriptor[] { CNContactViewController.DescriptorForRequiredKeys }, - out NSError error); - if (error != null) - { - Console.WriteLine($"Error: {error.LocalizedDescription}"); - } - else - { - DispatchQueue.MainQueue.DispatchAsync(() => completion(result)); - } - } - - #endregion - - #region ICNContactViewControllerDelegate - - /// - /// Setting it to false prevents users to perform default actions such as dialing a phone number, when they select a contact property. - /// - [Export("contactViewController:shouldPerformDefaultActionForContactProperty:")] - public bool ShouldPerformDefaultAction(CNContactViewController viewController, CNContactProperty property) - { - return false; - } - - /// - /// Used to dismiss the view controller when using init(for​New​Contact:​) to create a new contact. - /// - [Export("contactViewController:didCompleteWithContact:")] - public void DidComplete(CNContactViewController viewController, CNContact contact) - { - base.NavigationController.PopViewController(true); - if (contact != null) - { - base.NavigationController.ShowAlert($"{contact.GetFormattedName()} was successfully added."); - } - } - - #endregion - - /* helpers */ - - static class PhoneNumber - { - public static string IPhone { get; } = "(408) 555-0126"; - public static string Mobile { get; } = "(415) 123-4567"; - } - - static class Name - { - public static string Family { get; } = "Appleseed"; - public static string Given { get; } = "Jane"; - } - - static class Address - { - public static string Street { get; } = "1 Infinite Loop"; - public static string City { get; } = "Cupertino"; - public static string State { get; } = "CA"; - public static string PostalCode { get; } = "95014"; - } - } -} \ No newline at end of file + var highlightedPropertyIdentifiers = contacts [0].PhoneNumbers.FirstOrDefault ()?.Identifier; + if (!string.IsNullOrEmpty (highlightedPropertyIdentifiers)) { + contactViewController.HighlightProperty (new NSString ("phoneNumbers"), highlightedPropertyIdentifiers); + } + + // Show the view controller. + base.NavigationController.PushViewController (contactViewController, true); + } else { + this.ShowAlert ($"Could not find {name} in Contacts."); + } + }); + } + } + + /// + /// Exising contacts matching the specified name. + /// + private void FetchContact (string name, Action completion) + { + var result = store.GetUnifiedContacts (CNContact.GetPredicateForContacts (name), + new ICNKeyDescriptor [] { CNContactViewController.DescriptorForRequiredKeys }, + out NSError error); + if (error != null) { + Console.WriteLine ($"Error: {error.LocalizedDescription}"); + } else { + DispatchQueue.MainQueue.DispatchAsync (() => completion (result)); + } + } + + #endregion + + #region ICNContactViewControllerDelegate + + /// + /// Setting it to false prevents users to perform default actions such as dialing a phone number, when they select a contact property. + /// + [Export ("contactViewController:shouldPerformDefaultActionForContactProperty:")] + public bool ShouldPerformDefaultAction (CNContactViewController viewController, CNContactProperty property) + { + return false; + } + + /// + /// Used to dismiss the view controller when using init(for​New​Contact:​) to create a new contact. + /// + [Export ("contactViewController:didCompleteWithContact:")] + public void DidComplete (CNContactViewController viewController, CNContact contact) + { + base.NavigationController.PopViewController (true); + if (contact != null) { + base.NavigationController.ShowAlert ($"{contact.GetFormattedName ()} was successfully added."); + } + } + + #endregion + + /* helpers */ + + static class PhoneNumber { + public static string IPhone { get; } = "(408) 555-0126"; + public static string Mobile { get; } = "(415) 123-4567"; + } + + static class Name { + public static string Family { get; } = "Appleseed"; + public static string Given { get; } = "Jane"; + } + + static class Address { + public static string Street { get; } = "1 Infinite Loop"; + public static string City { get; } = "Cupertino"; + public static string State { get; } = "CA"; + public static string PostalCode { get; } = "95014"; + } + } +} diff --git a/Controls/Controls/AppDelegate.cs b/Controls/Controls/AppDelegate.cs index e108fb88e..3f0164ca3 100644 --- a/Controls/Controls/AppDelegate.cs +++ b/Controls/Controls/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace Controls -{ +namespace Controls { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/Controls/Controls/ControlsViewController.cs b/Controls/Controls/ControlsViewController.cs index 60a7f9ad0..ec9d329b6 100644 --- a/Controls/Controls/ControlsViewController.cs +++ b/Controls/Controls/ControlsViewController.cs @@ -4,10 +4,8 @@ using UIKit; using System.Threading.Tasks; -namespace Controls -{ - public partial class ControlsViewController : UIViewController - { +namespace Controls { + public partial class ControlsViewController : UIViewController { public ControlsViewController (IntPtr handle) : base (handle) { } @@ -26,14 +24,14 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - label1.Text = "New Label"; - View.Add (label1); + label1.Text = "New Label"; + View.Add (label1); -// new System.Threading.Thread (new System.Threading.ThreadStart (() => { -// InvokeOnMainThread (() => { -// label1.Text = "updated in thread"; -// }); -// })).Start (); + // new System.Threading.Thread (new System.Threading.ThreadStart (() => { + // InvokeOnMainThread (() => { + // label1.Text = "updated in thread"; + // }); + // })).Start (); Button1.TouchUpInside += (sender, e) => { label1.Text = "button1 clicked"; @@ -59,7 +57,8 @@ public override void ViewDidLoad () alert.AddButton ("custom button 1"); alert.AddButton ("Cancel"); // last button added is the 'cancel' button (index of '2') - alert.Clicked += delegate(object a, UIButtonEventArgs b) { + alert.Clicked += delegate (object a, UIButtonEventArgs b) + { Console.WriteLine ("Button " + b.ButtonIndex.ToString () + " clicked"); }; alert.Show (); @@ -68,21 +67,21 @@ public override void ViewDidLoad () textview1.ResignFirstResponder (); }; - // SLIDER - slider1.MinValue = -1; - slider1.MaxValue = 2; - slider1.Value = 0.5f; + // SLIDER + slider1.MinValue = -1; + slider1.MaxValue = 2; + slider1.Value = 0.5f; - // customize - // slider1.MinimumTrackTintColor = UIColor.Gray; - // slider1.MaximumTrackTintColor = UIColor.Green; + // customize + // slider1.MinimumTrackTintColor = UIColor.Gray; + // slider1.MaximumTrackTintColor = UIColor.Green; - // BOOLEAN - switch1.On = true; + // BOOLEAN + switch1.On = true; //DISMISS KEYBOARD ON RETURN BUTTON PRESS. this.textfield1.ShouldReturn += (textField) => { - textField.ResignFirstResponder(); + textField.ResignFirstResponder (); return true; }; @@ -93,17 +92,17 @@ public override void ViewDidLoad () partial void slider1_valueChanged (UISlider sender) { - sliderLabel.Text = ((UISlider)sender).Value.ToString (); + sliderLabel.Text = ((UISlider) sender).Value.ToString (); } partial void button2_TouchUpInside (UIButton sender) { textfield1.ResignFirstResponder (); - textview1.ResignFirstResponder(); + textview1.ResignFirstResponder (); - new UIAlertView("Button2 touched", "This method was declared as an event, which creates an [Action] in the designer.cs file", + new UIAlertView ("Button2 touched", "This method was declared as an event, which creates an [Action] in the designer.cs file", null, "Cancel", null) - .Show(); + .Show (); } // @@ -112,40 +111,40 @@ partial void button2_TouchUpInside (UIButton sender) async partial void button3_TouchUpInside (UIButton sender) { textfield1.ResignFirstResponder (); - textview1.ResignFirstResponder(); + textview1.ResignFirstResponder (); label1.Text = "async method started"; - await Task.Delay(1000); + await Task.Delay (1000); label1.Text = "1 second passed"; - await Task.Delay(2000); + await Task.Delay (2000); label1.Text = "2 more seconds passed"; - await Task.Delay(1000); + await Task.Delay (1000); - new UIAlertView("Async method complete", "This method contained async awaits", + new UIAlertView ("Async method complete", "This method contained async awaits", null, "Cancel", null) - .Show(); + .Show (); label1.Text = "async method completed"; } - partial void button4_TouchUpInside(UIButton sender) + partial void button4_TouchUpInside (UIButton sender) { //One Button Alert UIAlertView alert = new UIAlertView ("Title", "The message", null, "OK", null); - alert.Show(); + alert.Show (); //Two button Alert -// UIAlertView alert = new UIAlertView ("Alert Title", "Choose from two buttons", null, "OK", new string[] {"Cancel"}); -// alert.Clicked += (s, b) => { -// label1.Text = "Button " + b.ButtonIndex.ToString () + " clicked"; -// Console.WriteLine ("Button " + b.ButtonIndex.ToString () + " clicked"); -// }; -// alert.Show(); + // UIAlertView alert = new UIAlertView ("Alert Title", "Choose from two buttons", null, "OK", new string[] {"Cancel"}); + // alert.Clicked += (s, b) => { + // label1.Text = "Button " + b.ButtonIndex.ToString () + " clicked"; + // Console.WriteLine ("Button " + b.ButtonIndex.ToString () + " clicked"); + // }; + // alert.Show(); } public override void ViewWillAppear (bool animated) diff --git a/Controls/Controls/Main.cs b/Controls/Controls/Main.cs index 7fb2050cd..ed83ded04 100644 --- a/Controls/Controls/Main.cs +++ b/Controls/Controls/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace Controls -{ - public class Application - { +namespace Controls { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/CoreAnimation/AppDelegate.cs b/CoreAnimation/AppDelegate.cs index 9580681ed..9251fecdf 100644 --- a/CoreAnimation/AppDelegate.cs +++ b/CoreAnimation/AppDelegate.cs @@ -2,11 +2,9 @@ using UIKit; using Foundation; -namespace CoreAnimationExample -{ +namespace CoreAnimationExample { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { UIWindow window; MainSplitView splitView; diff --git a/CoreAnimation/Application.cs b/CoreAnimation/Application.cs index 015c7d28a..b803262ae 100644 --- a/CoreAnimation/Application.cs +++ b/CoreAnimation/Application.cs @@ -1,11 +1,9 @@ using System; using UIKit; -namespace CoreAnimationExample -{ - public class Application - { - public static void Main (string[] args) +namespace CoreAnimationExample { + public class Application { + public static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/CoreAnimation/Code/NavigationTable/NavItem.cs b/CoreAnimation/Code/NavigationTable/NavItem.cs index bfc3acc94..d82299cd2 100644 --- a/CoreAnimation/Code/NavigationTable/NavItem.cs +++ b/CoreAnimation/Code/NavigationTable/NavItem.cs @@ -1,10 +1,8 @@ using System; using UIKit; -namespace CoreAnimationExample -{ - public class NavItem - { +namespace CoreAnimationExample { + public class NavItem { #region declarations @@ -57,14 +55,14 @@ public Type ControllerType { /// a list of the constructor args (if neccesary) for the controller. use this in /// conjunction with ControllerType if lazy-creating controllers. /// - object[] controllerConstructorArgs = new object[] { }; + object [] controllerConstructorArgs = new object [] { }; - public object[] ControllerConstructorArgs { + public object [] ControllerConstructorArgs { get { return controllerConstructorArgs; } set { controllerConstructorArgs = value; - controllerConstructorTypes = new Type[controllerConstructorArgs.Length]; + controllerConstructorTypes = new Type [controllerConstructorArgs.Length]; for (int i = 0; i < controllerConstructorArgs.Length; i++) { controllerConstructorTypes [i] = controllerConstructorArgs [i].GetType (); } @@ -74,10 +72,10 @@ public object[] ControllerConstructorArgs { /// /// The types of constructor args. /// - Type[] controllerConstructorTypes = Type.EmptyTypes; + Type [] controllerConstructorTypes = Type.EmptyTypes; - public Type[] ControllerConstructorTypes { - get { return controllerConstructorTypes; } + public Type [] ControllerConstructorTypes { + get { return controllerConstructorTypes; } } #endregion @@ -103,7 +101,7 @@ public NavItem (string name, Type controllerType) : this (name) this.controllerType = controllerType; } - public NavItem (string name, Type controllerType, object[] controllerConstructorArgs) : this (name, controllerType) + public NavItem (string name, Type controllerType, object [] controllerConstructorArgs) : this (name, controllerType) { this.ControllerConstructorArgs = controllerConstructorArgs; } @@ -118,7 +116,7 @@ public NavItem (string name, string imagePath, Type controllerType) : this (name this.imagePath = imagePath; } - public NavItem (string name, string imagePath, Type controllerType, object[] controllerConstructorArgs) : this (name, controllerType, controllerConstructorArgs) + public NavItem (string name, string imagePath, Type controllerType, object [] controllerConstructorArgs) : this (name, controllerType, controllerConstructorArgs) { this.imagePath = imagePath; } diff --git a/CoreAnimation/Code/NavigationTable/NavItemGroup.cs b/CoreAnimation/Code/NavigationTable/NavItemGroup.cs index 59ceda3e6..22212fa29 100644 --- a/CoreAnimation/Code/NavigationTable/NavItemGroup.cs +++ b/CoreAnimation/Code/NavigationTable/NavItemGroup.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; -namespace CoreAnimationExample -{ +namespace CoreAnimationExample { /// /// A group that contains table items /// - public class NavItemGroup - { + public class NavItemGroup { List items = new List (); public string Name { get; set; } @@ -15,7 +13,7 @@ public class NavItemGroup public string Footer { get; set; } public List Items { - get { return items; } + get { return items; } set { items = value; } } diff --git a/CoreAnimation/Code/NavigationTable/NavItemTableSource.cs b/CoreAnimation/Code/NavigationTable/NavItemTableSource.cs index fc8e19cd2..7d0f2b31c 100644 --- a/CoreAnimation/Code/NavigationTable/NavItemTableSource.cs +++ b/CoreAnimation/Code/NavigationTable/NavItemTableSource.cs @@ -4,14 +4,12 @@ using Foundation; using System.Reflection; -namespace CoreAnimationExample -{ +namespace CoreAnimationExample { /// /// Combined DataSource and Delegate for our UITableView /// - public class NavItemTableSource : UITableViewSource - { - static readonly NSString cellIdentifier = (NSString)"NavTableCellView"; + public class NavItemTableSource : UITableViewSource { + static readonly NSString cellIdentifier = (NSString) "NavTableCellView"; public event EventHandler RowClicked; @@ -35,7 +33,7 @@ public override nint NumberOfSections (UITableView tableView) /// public override nint RowsInSection (UITableView tableview, nint section) { - return navItems [(int)section].Items.Count; + return navItems [(int) section].Items.Count; } /// @@ -43,7 +41,7 @@ public override nint RowsInSection (UITableView tableview, nint section) /// public override string TitleForHeader (UITableView tableView, nint section) { - return navItems [(int)section].Name; + return navItems [(int) section].Name; } /// @@ -51,7 +49,7 @@ public override string TitleForHeader (UITableView tableView, nint section) /// public override string TitleForFooter (UITableView tableView, nint section) { - return navItems [(int)section].Footer; + return navItems [(int) section].Footer; } /// diff --git a/CoreAnimation/Code/NavigationTable/RowClickedEventArgs.cs b/CoreAnimation/Code/NavigationTable/RowClickedEventArgs.cs index b44652973..0d4f5e558 100644 --- a/CoreAnimation/Code/NavigationTable/RowClickedEventArgs.cs +++ b/CoreAnimation/Code/NavigationTable/RowClickedEventArgs.cs @@ -1,9 +1,7 @@ using System; -namespace CoreAnimationExample -{ - public class RowClickedEventArgs : EventArgs - { +namespace CoreAnimationExample { + public class RowClickedEventArgs : EventArgs { public NavItem Item { get; set; } public RowClickedEventArgs (NavItem item) : base () diff --git a/CoreAnimation/Screens/iPad/BasicUIViewAnimation/BasicUIViewAnimationScreen.xib.cs b/CoreAnimation/Screens/iPad/BasicUIViewAnimation/BasicUIViewAnimationScreen.xib.cs index 756d7c230..ef88ab7bf 100644 --- a/CoreAnimation/Screens/iPad/BasicUIViewAnimation/BasicUIViewAnimationScreen.xib.cs +++ b/CoreAnimation/Screens/iPad/BasicUIViewAnimation/BasicUIViewAnimationScreen.xib.cs @@ -5,10 +5,8 @@ using UIKit; using CoreGraphics; -namespace CoreAnimationExample -{ - public partial class BasicUIViewAnimationScreen : UIViewController, IDetailView - { +namespace CoreAnimationExample { + public partial class BasicUIViewAnimationScreen : UIViewController, IDetailView { public event EventHandler ContentsButtonClicked; public override void ViewDidLoad () diff --git a/CoreAnimation/Screens/iPad/CustomizableAnimationViewer/CustomizableAnimationViewerScreen.xib.cs b/CoreAnimation/Screens/iPad/CustomizableAnimationViewer/CustomizableAnimationViewerScreen.xib.cs index 80d772a29..b9f81277f 100644 --- a/CoreAnimation/Screens/iPad/CustomizableAnimationViewer/CustomizableAnimationViewerScreen.xib.cs +++ b/CoreAnimation/Screens/iPad/CustomizableAnimationViewer/CustomizableAnimationViewerScreen.xib.cs @@ -6,10 +6,8 @@ using ObjCRuntime; using CoreGraphics; -namespace CoreAnimationExample -{ - public partial class CustomizableAnimationViewerScreen : UIViewController, IDetailView - { +namespace CoreAnimationExample { + public partial class CustomizableAnimationViewerScreen : UIViewController, IDetailView { public event EventHandler ContentsButtonClicked; public override void ViewDidLoad () @@ -30,26 +28,26 @@ public override void ViewDidLoad () UIView.SetAnimationDelegate (this); //NOTE: you need this for the selector b.s. // animation delay - UIView.SetAnimationDelay ((double)sldrDelay.Value); + UIView.SetAnimationDelay ((double) sldrDelay.Value); // animation duration - UIView.SetAnimationDuration ((double)sldrDuration.Value); + UIView.SetAnimationDuration ((double) sldrDuration.Value); // animation curve UIViewAnimationCurve curve = UIViewAnimationCurve.EaseInOut; switch (sgmtCurves.SelectedSegment) { - case 0: - curve = UIViewAnimationCurve.EaseInOut; - break; - case 1: - curve = UIViewAnimationCurve.EaseIn; - break; - case 2: - curve = UIViewAnimationCurve.EaseOut; - break; - case 3: - curve = UIViewAnimationCurve.Linear; - break; + case 0: + curve = UIViewAnimationCurve.EaseInOut; + break; + case 1: + curve = UIViewAnimationCurve.EaseIn; + break; + case 2: + curve = UIViewAnimationCurve.EaseOut; + break; + case 3: + curve = UIViewAnimationCurve.Linear; + break; } UIView.SetAnimationCurve (curve); diff --git a/CoreAnimation/Screens/iPad/Home/MainSplitView.cs b/CoreAnimation/Screens/iPad/Home/MainSplitView.cs index fc457d2d5..19426c055 100644 --- a/CoreAnimation/Screens/iPad/Home/MainSplitView.cs +++ b/CoreAnimation/Screens/iPad/Home/MainSplitView.cs @@ -4,10 +4,8 @@ using ObjCRuntime; using Foundation; -namespace CoreAnimationExample -{ - public class MainSplitView : UISplitViewController - { +namespace CoreAnimationExample { + public class MainSplitView : UISplitViewController { MasterNavTableViewController masterViewController; UIViewController detailViewController; Selector toggleMasterVisible; @@ -24,7 +22,7 @@ public MainSplitView () : base () // create an array of controllers from them and then assign it to the // controllers property - ViewControllers = new UIViewController[] { masterViewController, detailViewController }; + ViewControllers = new UIViewController [] { masterViewController, detailViewController }; // in this example, i expose an event on the master view called RowClicked, and i listen // for it in here, and then call a method on the detail view to update. this class thereby @@ -73,7 +71,7 @@ void HandleRowClicked (RowClickedEventArgs e) if (e.Item.Controller != null) { UIView.BeginAnimations ("DetailViewPush"); detailViewController = e.Item.Controller; - ViewControllers = new UIViewController[] { masterViewController, detailViewController }; + ViewControllers = new UIViewController [] { masterViewController, detailViewController }; UIView.SetAnimationTransition (UIViewAnimationTransition.FlipFromRight, ViewControllers [1].View, false); UIView.CommitAnimations (); } else { @@ -108,7 +106,7 @@ void HandleRowClicked (RowClickedEventArgs e) // push the view controller onto the stack UIView.BeginAnimations ("DetailViewPush"); detailViewController = e.Item.Controller; - ViewControllers = new UIViewController[] { masterViewController, detailViewController }; + ViewControllers = new UIViewController [] { masterViewController, detailViewController }; UIView.SetAnimationTransition (UIViewAnimationTransition.FlipFromRight, ViewControllers [1].View, false); UIView.CommitAnimations (); } else diff --git a/CoreAnimation/Screens/iPad/IDetailView.cs b/CoreAnimation/Screens/iPad/IDetailView.cs index 6ec69760f..6bc26289c 100644 --- a/CoreAnimation/Screens/iPad/IDetailView.cs +++ b/CoreAnimation/Screens/iPad/IDetailView.cs @@ -1,10 +1,8 @@ using System; using UIKit; -namespace CoreAnimationExample -{ - public interface IDetailView - { +namespace CoreAnimationExample { + public interface IDetailView { event EventHandler ContentsButtonClicked; } } diff --git a/CoreAnimation/Screens/iPad/LayerAnimation/ImplicitAnimationScreen.xib.cs b/CoreAnimation/Screens/iPad/LayerAnimation/ImplicitAnimationScreen.xib.cs index ef31903bb..9a8533f30 100644 --- a/CoreAnimation/Screens/iPad/LayerAnimation/ImplicitAnimationScreen.xib.cs +++ b/CoreAnimation/Screens/iPad/LayerAnimation/ImplicitAnimationScreen.xib.cs @@ -6,10 +6,8 @@ using CoreAnimation; using CoreGraphics; -namespace CoreAnimationExample -{ - public partial class ImplicitAnimationScreen : UIViewController, IDetailView - { +namespace CoreAnimationExample { + public partial class ImplicitAnimationScreen : UIViewController, IDetailView { public event EventHandler ContentsButtonClicked; CALayer imgLayer; @@ -86,16 +84,14 @@ CALayer CreateLayerWithDelegate () return layer; } - public class LayerDelegate : CALayerDelegate - { + public class LayerDelegate : CALayerDelegate { public override void DrawLayer (CALayer layer, CGContext context) { // implement your drawing } } // Method 3: Create a custom CALayer and override the appropriate methods - public class MyCustomLayer : CALayer - { + public class MyCustomLayer : CALayer { public override void DrawInContext (CGContext ctx) { base.DrawInContext (ctx); diff --git a/CoreAnimation/Screens/iPad/LayerAnimation/LayerAnimationScreen.xib.cs b/CoreAnimation/Screens/iPad/LayerAnimation/LayerAnimationScreen.xib.cs index 651943041..ff4ee8133 100644 --- a/CoreAnimation/Screens/iPad/LayerAnimation/LayerAnimationScreen.xib.cs +++ b/CoreAnimation/Screens/iPad/LayerAnimation/LayerAnimationScreen.xib.cs @@ -7,10 +7,8 @@ using CoreAnimation; using CoreGraphics; -namespace CoreAnimationExample -{ - public partial class LayerAnimationScreen : UIViewController, IDetailView - { +namespace CoreAnimationExample { + public partial class LayerAnimationScreen : UIViewController, IDetailView { public event EventHandler ContentsButtonClicked; CGPath animationPath; @@ -34,7 +32,7 @@ public override void ViewDidLoad () btnAnimate.TouchUpInside += (s, e) => { // create a keyframe animation - var keyFrameAnimation = (CAKeyFrameAnimation)CAKeyFrameAnimation.GetFromKeyPath ("position"); + var keyFrameAnimation = (CAKeyFrameAnimation) CAKeyFrameAnimation.GetFromKeyPath ("position"); keyFrameAnimation.Path = animationPath; keyFrameAnimation.Duration = 3; @@ -75,10 +73,10 @@ void DrawPathAsBackground () // create our offscreen bitmap context var bitmapSize = new CGSize (View.Frame.Size); using (var context = new CGBitmapContext ( - IntPtr.Zero, - (int)bitmapSize.Width, (int)bitmapSize.Height, 8, - (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), - CGImageAlphaInfo.PremultipliedFirst)) { + IntPtr.Zero, + (int) bitmapSize.Width, (int) bitmapSize.Height, 8, + (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), + CGImageAlphaInfo.PremultipliedFirst)) { // convert to View space var affineTransform = CGAffineTransform.MakeIdentity (); diff --git a/CoreAnimation/Screens/iPad/NavTable/MasterNavTableViewController.cs b/CoreAnimation/Screens/iPad/NavTable/MasterNavTableViewController.cs index 0e71fafc7..586396820 100644 --- a/CoreAnimation/Screens/iPad/NavTable/MasterNavTableViewController.cs +++ b/CoreAnimation/Screens/iPad/NavTable/MasterNavTableViewController.cs @@ -3,10 +3,8 @@ using UIKit; -namespace CoreAnimationExample -{ - public class MasterNavTableViewController : UITableViewController - { +namespace CoreAnimationExample { + public class MasterNavTableViewController : UITableViewController { public event EventHandler RowClicked; List navItems; diff --git a/CoreAnimation/Screens/iPad/ViewTransitions/BackTransitionViewController.xib.cs b/CoreAnimation/Screens/iPad/ViewTransitions/BackTransitionViewController.xib.cs index fd68a8638..b8356189e 100644 --- a/CoreAnimation/Screens/iPad/ViewTransitions/BackTransitionViewController.xib.cs +++ b/CoreAnimation/Screens/iPad/ViewTransitions/BackTransitionViewController.xib.cs @@ -5,10 +5,8 @@ using UIKit; using Foundation; -namespace CoreAnimationExample -{ - public partial class BackTransitionViewController : UIViewController - { +namespace CoreAnimationExample { + public partial class BackTransitionViewController : UIViewController { public event EventHandler BackClicked; public override void ViewDidLoad () diff --git a/CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs b/CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs index 5a1003962..3afeaaa50 100644 --- a/CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs +++ b/CoreAnimation/Screens/iPad/ViewTransitions/Controller.cs @@ -3,10 +3,8 @@ using CoreFoundation; using UIKit; -namespace CoreAnimationExample -{ - public class Controller : UIViewController, IDetailView - { +namespace CoreAnimationExample { + public class Controller : UIViewController, IDetailView { public event EventHandler ContentsButtonClicked; TransitionViewController transitionViewController; diff --git a/CoreAnimation/Screens/iPad/ViewTransitions/TransitionViewController.xib.cs b/CoreAnimation/Screens/iPad/ViewTransitions/TransitionViewController.xib.cs index 03c33093c..a270d743f 100644 --- a/CoreAnimation/Screens/iPad/ViewTransitions/TransitionViewController.xib.cs +++ b/CoreAnimation/Screens/iPad/ViewTransitions/TransitionViewController.xib.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace CoreAnimationExample -{ - public partial class TransitionViewController : UIViewController - { +namespace CoreAnimationExample { + public partial class TransitionViewController : UIViewController { public Action ContentsClicked; public event EventHandler TransitionClicked; @@ -15,16 +13,16 @@ public partial class TransitionViewController : UIViewController public UIViewAnimationOptions SelectedTransition { get { switch (sgmntTransitionType.SelectedSegment) { - case 0: - return UIViewAnimationOptions.TransitionCurlDown; - case 1: - return UIViewAnimationOptions.TransitionCurlUp; - case 2: - return UIViewAnimationOptions.TransitionFlipFromLeft; - case 3: - return UIViewAnimationOptions.TransitionFlipFromRight; - default: - return UIViewAnimationOptions.TransitionCurlDown; + case 0: + return UIViewAnimationOptions.TransitionCurlDown; + case 1: + return UIViewAnimationOptions.TransitionCurlUp; + case 2: + return UIViewAnimationOptions.TransitionFlipFromLeft; + case 3: + return UIViewAnimationOptions.TransitionFlipFromRight; + default: + return UIViewAnimationOptions.TransitionCurlDown; } } } diff --git a/CoreImage/AppDelegate.cs b/CoreImage/AppDelegate.cs index 859c23d58..4019461da 100644 --- a/CoreImage/AppDelegate.cs +++ b/CoreImage/AppDelegate.cs @@ -13,11 +13,9 @@ using System.IO; using System.Threading.Tasks; -namespace coreimage -{ +namespace coreimage { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { /// /// "Flower" © 2012 Milica Sekulic, used under a Creative Commons Attribution-ShareAlike license: http://creativecommons.org/licenses/by-sa/3.0/ /// @@ -57,7 +55,7 @@ void AddVersionRoot (Section byIOSSection, string versionString, byte majorVersi var catSection = new Section (section); iOSRoot.Add (catSection); - var elementList = query.Select (fi => (Element)new RootElement (fi.Name, (x) => { + var elementList = query.Select (fi => (Element) new RootElement (fi.Name, (x) => { var viewCtrl = Demo (fi.Callback); viewCtrl.Title = fi.Name; return viewCtrl; @@ -93,7 +91,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) var catSection = new Section (); catRoot.Add (catSection); - var elementList = query.Select (fi => (Element)new RootElement (fi.Name, (x) => { + var elementList = query.Select (fi => (Element) new RootElement (fi.Name, (x) => { var viewCtrl = Demo (fi.Callback); viewCtrl.Title = fi.Name; return viewCtrl; @@ -117,7 +115,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) #endregion - string[] sectionList = new [] { + string [] sectionList = new [] { "Blur", "Color Adjustment", "Color Effect", @@ -132,7 +130,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) "Tile Effect", "Transition", }; - FilterHolder[] masterList; + FilterHolder [] masterList; void InitList () { @@ -517,7 +515,7 @@ public CIImage VignetteEffect () Image = flower, Center = new CIVector (flower.Extent.Width * .3f, flower.Extent.Width * .35f), Intensity = .6f, - Radius = (float)flower.Extent.Width * .20f, + Radius = (float) flower.Extent.Width * .20f, }; return vignette_effect.OutputImage; @@ -566,9 +564,9 @@ public CIImage ColorCrossPolynomial () { var color_cross_polynomial = new CIColorCrossPolynomial () { Image = flower, - RedCoefficients = new CIVector (new nfloat []{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }), - GreenCoefficients = new CIVector (new nfloat []{ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }), - BlueCoefficients = new CIVector (new nfloat []{ 1, 0, 1, 0, -20, 0, 0, 0, 0, 0 }), + RedCoefficients = new CIVector (new nfloat [] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }), + GreenCoefficients = new CIVector (new nfloat [] { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 }), + BlueCoefficients = new CIVector (new nfloat [] { 1, 0, 1, 0, -20, 0, 0, 0, 0, 0 }), }; return color_cross_polynomial.OutputImage; } @@ -581,7 +579,7 @@ public CIImage ColorCrossPolynomial () /// public unsafe CIImage ColorCube () { - float[] color_cube_data = { + float [] color_cube_data = { 0, 0, 0, 1, .1f, 0, 1, 1, 0, 1, 0, 1, @@ -592,7 +590,7 @@ public unsafe CIImage ColorCube () 1, 1, 1, 1 }; - var byteArray = new byte[color_cube_data.Length * 4]; + var byteArray = new byte [color_cube_data.Length * 4]; Buffer.BlockCopy (color_cube_data, 0, byteArray, 0, byteArray.Length); var data = NSData.FromArray (byteArray); @@ -611,7 +609,7 @@ public unsafe CIImage ColorCube () /// The altered image. public CIImage ColorCubeWithColorSpace () { - float[] color_cube_data = { + float [] color_cube_data = { 0, 0, 0, 1, .1f, 0, 1, 1, 0, 1, 0, 1, @@ -622,7 +620,7 @@ public CIImage ColorCubeWithColorSpace () 1, 1, 1, 1 }; - var byteArray = new byte[color_cube_data.Length * 4]; + var byteArray = new byte [color_cube_data.Length * 4]; Buffer.BlockCopy (color_cube_data, 0, byteArray, 0, byteArray.Length); var data = NSData.FromArray (byteArray); @@ -1547,7 +1545,7 @@ CIImage BumpDistortion () var bump_distortion = new CIBumpDistortion () { Image = xamarinCheck, Center = new CIVector (width / 2f, height / 2f), - Radius = .4f * (float)height, + Radius = .4f * (float) height, Scale = .5f }; @@ -1566,9 +1564,9 @@ CIImage BumpDistortionLinear () var bump_distortion_linear = new CIBumpDistortionLinear () { Image = xamarinCheck, Center = new CIVector (width * .5f, height * .5f), - Radius = .4f * (float)height, + Radius = .4f * (float) height, Scale = .5f, - Angle = (float)Math.PI * .5f + Angle = (float) Math.PI * .5f }; return bump_distortion_linear.OutputImage; @@ -1671,7 +1669,7 @@ public CIImage CheckerboardGenerator () var checker = new CICheckerboardGenerator () { Color0 = c0, Color1 = c1, - Center = new CIVector (new nfloat[] { 10, 10 }), // Default [80 80] + Center = new CIVector (new nfloat [] { 10, 10 }), // Default [80 80] Sharpness = 1F // Default 1 }; diff --git a/CoreImage/FilterAttribute.cs b/CoreImage/FilterAttribute.cs index e0b3f3b7f..2fab1e80c 100644 --- a/CoreImage/FilterAttribute.cs +++ b/CoreImage/FilterAttribute.cs @@ -1,9 +1,7 @@ using System; -namespace coreimage -{ - public class FilterAttribute : Attribute - { +namespace coreimage { + public class FilterAttribute : Attribute { public FilterAttribute () { } diff --git a/CoreImage/FilterHolder.cs b/CoreImage/FilterHolder.cs index 64010aa46..ed1d0f14b 100644 --- a/CoreImage/FilterHolder.cs +++ b/CoreImage/FilterHolder.cs @@ -3,17 +3,15 @@ using ObjCRuntime; using System.Reflection; -namespace coreimage -{ - class FilterHolder - { +namespace coreimage { + class FilterHolder { public string Name { get; private set; } public string SectionName { get; private set; } public byte MajorVersion { get; private set; } - public Func Callback { get; private set; } + public Func Callback { get; private set; } public FilterHolder (string name, string sectionName, byte version, Type filterType, Func callback) { diff --git a/CoreImage/FlipsideViewController.cs b/CoreImage/FlipsideViewController.cs index 5137e4570..6a8f95086 100644 --- a/CoreImage/FlipsideViewController.cs +++ b/CoreImage/FlipsideViewController.cs @@ -4,10 +4,8 @@ using MonoTouch.Foundation; using MonoTouch.UIKit; -namespace coreimage -{ - public partial class FlipsideViewController : UIViewController - { +namespace coreimage { + public partial class FlipsideViewController : UIViewController { public FlipsideViewController () : base ("FlipsideViewController", null) { } diff --git a/CoreImage/Main.cs b/CoreImage/Main.cs index e42269b06..563b11924 100644 --- a/CoreImage/Main.cs +++ b/CoreImage/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace coreimage -{ - public class Application - { +namespace coreimage { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - Console.WriteLine(System.IO.Directory.GetCurrentDirectory()); + Console.WriteLine (System.IO.Directory.GetCurrentDirectory ()); UIApplication.Main (args, null, "AppDelegate"); } } diff --git a/CoreImage/MainViewController.cs b/CoreImage/MainViewController.cs index 81821c230..1fd05c300 100644 --- a/CoreImage/MainViewController.cs +++ b/CoreImage/MainViewController.cs @@ -3,10 +3,8 @@ using MonoTouch.Foundation; using MonoTouch.UIKit; -namespace coreimage -{ - public partial class MainViewController : UIViewController - { +namespace coreimage { + public partial class MainViewController : UIViewController { public MainViewController () : base ("MainViewController", null) { // Custom initialization @@ -51,7 +49,8 @@ partial void showInfo (NSObject sender) ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal, }; - controller.Done += delegate { + controller.Done += delegate + { DismissModalViewControllerAnimated (true); }; diff --git a/CoreImage/VisitFilterViewController.cs b/CoreImage/VisitFilterViewController.cs index e4169282d..4b088ffd0 100644 --- a/CoreImage/VisitFilterViewController.cs +++ b/CoreImage/VisitFilterViewController.cs @@ -7,10 +7,8 @@ using ObjCRuntime; using System.Threading.Tasks; -namespace coreimage -{ - class VisitFilterViewController : UIViewController - { +namespace coreimage { + class VisitFilterViewController : UIViewController { protected UIImageView ImageView { get; set; } protected UIBarButtonItem BarButton { get; set; } @@ -19,7 +17,7 @@ class VisitFilterViewController : UIViewController protected bool ShouldStop { get; set; } - public VisitFilterViewController (FilterHolder[] filterList) + public VisitFilterViewController (FilterHolder [] filterList) { FilterList = filterList; ShouldStop = false; diff --git a/CoreLocation/CoreLocation/AppDelegate.cs b/CoreLocation/CoreLocation/AppDelegate.cs index a7e49f7e0..f6e948ead 100644 --- a/CoreLocation/CoreLocation/AppDelegate.cs +++ b/CoreLocation/CoreLocation/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace CoreLocation -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace CoreLocation { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } + return true; + } + } } diff --git a/CoreLocation/CoreLocation/Main.cs b/CoreLocation/CoreLocation/Main.cs index aff359911..c35db2321 100644 --- a/CoreLocation/CoreLocation/Main.cs +++ b/CoreLocation/CoreLocation/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace CoreLocation -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace CoreLocation { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/CoreLocation/CoreLocation/ViewController.cs b/CoreLocation/CoreLocation/ViewController.cs index 401de16c6..05e3c4df9 100644 --- a/CoreLocation/CoreLocation/ViewController.cs +++ b/CoreLocation/CoreLocation/ViewController.cs @@ -1,69 +1,64 @@ -using Foundation; +using Foundation; using System; using System.Linq; using UIKit; -namespace CoreLocation -{ - public partial class ViewController : UIViewController, ICLLocationManagerDelegate - { - private readonly CLLocationManager locationManager = new CLLocationManager(); +namespace CoreLocation { + public partial class ViewController : UIViewController, ICLLocationManagerDelegate { + private readonly CLLocationManager locationManager = new CLLocationManager (); - protected ViewController(IntPtr handle) : base(handle) { } + protected ViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - // you can set the update threshold and accuracy if you want: - //locationManager.DistanceFilter = 10d; // move ten meters before updating - //locationManager.HeadingFilter = 3d; // move 3 degrees before updating + // you can set the update threshold and accuracy if you want: + //locationManager.DistanceFilter = 10d; // move ten meters before updating + //locationManager.HeadingFilter = 3d; // move 3 degrees before updating - // you can also set the desired accuracy: - locationManager.DesiredAccuracy = 1000; // 1000 meters/1 kilometer - // you can also use presets, which simply evalute to a double value: - //locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; + // you can also set the desired accuracy: + locationManager.DesiredAccuracy = 1000; // 1000 meters/1 kilometer + // you can also use presets, which simply evalute to a double value: + //locationManager.DesiredAccuracy = CLLocation.AccuracyNearestTenMeters; - locationManager.Delegate = this; - locationManager.RequestWhenInUseAuthorization(); + locationManager.Delegate = this; + locationManager.RequestWhenInUseAuthorization (); - if (CLLocationManager.LocationServicesEnabled) - { - locationManager.StartUpdatingLocation(); - } + if (CLLocationManager.LocationServicesEnabled) { + locationManager.StartUpdatingLocation (); + } - if (CLLocationManager.HeadingAvailable) - { - locationManager.StartUpdatingHeading(); - } - } + if (CLLocationManager.HeadingAvailable) { + locationManager.StartUpdatingHeading (); + } + } - #region ICLLocationManagerDelegate + #region ICLLocationManagerDelegate - [Export("locationManager:didUpdateHeading:")] - public void UpdatedHeading(CLLocationManager manager, CLHeading newHeading) - { - trueHeadingLabel.Text = $"{newHeading.TrueHeading}º"; - magneticHeadingLabel.Text = $"{newHeading.MagneticHeading}º"; - } + [Export ("locationManager:didUpdateHeading:")] + public void UpdatedHeading (CLLocationManager manager, CLHeading newHeading) + { + trueHeadingLabel.Text = $"{newHeading.TrueHeading}º"; + magneticHeadingLabel.Text = $"{newHeading.MagneticHeading}º"; + } - [Export("locationManager:didUpdateLocations:")] - public void LocationsUpdated(CLLocationManager manager, CLLocation[] locations) - { - var location = locations.LastOrDefault(); - if (location != null) - { - altitudeLabel.Text = $"{location.Altitude} meters"; - longitudeLabel.Text = $"{location.Coordinate.Longitude}º"; - latitudeLabel.Text = $"{location.Coordinate.Latitude}º"; - courseLabel.Text = $"{location.Course}º"; - speedLabel.Text = $"{location.Speed} meters/s"; + [Export ("locationManager:didUpdateLocations:")] + public void LocationsUpdated (CLLocationManager manager, CLLocation [] locations) + { + var location = locations.LastOrDefault (); + if (location != null) { + altitudeLabel.Text = $"{location.Altitude} meters"; + longitudeLabel.Text = $"{location.Coordinate.Longitude}º"; + latitudeLabel.Text = $"{location.Coordinate.Latitude}º"; + courseLabel.Text = $"{location.Course}º"; + speedLabel.Text = $"{location.Speed} meters/s"; - // get the distance from here to paris - distanceLabel.Text = $"{location.DistanceFrom(new CLLocation(48.857, 2.351)) / 1000} km"; - } - } + // get the distance from here to paris + distanceLabel.Text = $"{location.DistanceFrom (new CLLocation (48.857, 2.351)) / 1000} km"; + } + } - #endregion - } -} \ No newline at end of file + #endregion + } +} diff --git a/CoreMidiSample/AppDelegate.cs b/CoreMidiSample/AppDelegate.cs index 1abc7706a..bdf6e7058 100644 --- a/CoreMidiSample/AppDelegate.cs +++ b/CoreMidiSample/AppDelegate.cs @@ -8,11 +8,9 @@ using MonoTouch.Dialog; using System.Threading; -namespace CoreMidiSample -{ +namespace CoreMidiSample { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { DialogViewController dvc; UIWindow window; MidiClient client; @@ -58,20 +56,20 @@ RootElement MakeRoot () RootElement MakeHardware () { - int sources = (int)Midi.SourceCount; - int destinations = (int)Midi.DestinationCount; + int sources = (int) Midi.SourceCount; + int destinations = (int) Midi.DestinationCount; var sourcesSection = new Section ("Sources"); sourcesSection.AddAll ( from x in Enumerable.Range (0, sources) let source = MidiEndpoint.GetSource (x) - select (Element)new StringElement (source.DisplayName, source.IsNetworkSession ? "Network" : "Local") + select (Element) new StringElement (source.DisplayName, source.IsNetworkSession ? "Network" : "Local") ); var targetsSection = new Section ("Targets"); targetsSection.AddAll ( from x in Enumerable.Range (0, destinations) let target = MidiEndpoint.GetDestination (x) - select (Element)new StringElement (target.DisplayName, target.IsNetworkSession ? "Network" : "Local") + select (Element) new StringElement (target.DisplayName, target.IsNetworkSession ? "Network" : "Local") ); return new RootElement ("Endpoints (" + sources + ", " + destinations + ")") { sourcesSection, @@ -83,17 +81,17 @@ RootElement MakeDevices () { var internalDevices = new Section ("Internal Devices"); internalDevices.AddAll ( - from x in Enumerable.Range (0, (int)Midi.DeviceCount) + from x in Enumerable.Range (0, (int) Midi.DeviceCount) let dev = Midi.GetDevice (x) where dev.EntityCount > 0 select MakeDevice (dev) ); var externalDevices = new Section ("External Devices"); externalDevices.AddAll ( - from x in Enumerable.Range (0, (int)Midi.ExternalDeviceCount) + from x in Enumerable.Range (0, (int) Midi.ExternalDeviceCount) let dev = Midi.GetExternalDevice (x) where dev.EntityCount > 0 - select (Element)MakeDevice (dev) + select (Element) MakeDevice (dev) ); return new RootElement ("Devices (" + Midi.DeviceCount + ", " + Midi.ExternalDeviceCount + ")") { internalDevices, @@ -104,21 +102,21 @@ where dev.EntityCount > 0 Element MakeDevice (MidiDevice dev) { var entities = new Section ("Entities"); - foreach (var ex in Enumerable.Range(0, (int)dev.EntityCount)) { + foreach (var ex in Enumerable.Range (0, (int) dev.EntityCount)) { var entity = dev.GetEntity (ex); var sourceSection = new Section ("Sources"); sourceSection.AddAll ( - from sx in Enumerable.Range (0, (int)entity.Sources) + from sx in Enumerable.Range (0, (int) entity.Sources) let endpoint = entity.GetSource (sx) select MakeEndpoint (endpoint) ); var destinationSection = new Section ("Destinations"); destinationSection.AddAll ( - from sx in Enumerable.Range (0, (int)entity.Destinations) + from sx in Enumerable.Range (0, (int) entity.Destinations) let endpoint = entity.GetDestination (sx) select MakeEndpoint (endpoint) ); - entities.Add(new RootElement (entity.Name) { + entities.Add (new RootElement (entity.Name) { sourceSection, destinationSection }); @@ -157,11 +155,12 @@ Element MakeEndpoint (MidiEndpoint endpoint) void ReloadDevices () { - BeginInvokeOnMainThread (delegate { + BeginInvokeOnMainThread (delegate + { hardwareSection.Remove (0); hardwareSection.Remove (0); - hardwareSection.Add ((Element)MakeHardware ()); - hardwareSection.Add ((Element)MakeDevices ()); + hardwareSection.Add ((Element) MakeHardware ()); + hardwareSection.Add ((Element) MakeDevices ()); }); } @@ -172,7 +171,7 @@ void SendNote () for (int i = 0; i < Midi.DestinationCount; i++) { var endpoint = MidiEndpoint.GetDestination (i); - var note = (byte)(rand.Next () % 127); + var note = (byte) (rand.Next () % 127); // play note outputPort.Send (endpoint, new MidiPacket [] { new MidiPacket (0, new byte [] { 0x90, note, 127 }) }); @@ -189,28 +188,35 @@ void SendNote () void SetupMidi () { client = new MidiClient ("CoreMidiSample MIDI CLient"); - client.ObjectAdded += delegate(object sender, ObjectAddedOrRemovedEventArgs e) { + client.ObjectAdded += delegate (object sender, ObjectAddedOrRemovedEventArgs e) + { }; - client.ObjectAdded += delegate { + client.ObjectAdded += delegate + { ReloadDevices (); }; - client.ObjectRemoved += delegate { + client.ObjectRemoved += delegate + { ReloadDevices (); }; - client.PropertyChanged += delegate(object sender, ObjectPropertyChangedEventArgs e) { + client.PropertyChanged += delegate (object sender, ObjectPropertyChangedEventArgs e) + { Console.WriteLine ("Changed"); }; - client.ThruConnectionsChanged += delegate { + client.ThruConnectionsChanged += delegate + { Console.WriteLine ("Thru connections changed"); }; - client.SerialPortOwnerChanged += delegate { + client.SerialPortOwnerChanged += delegate + { Console.WriteLine ("Serial port changed"); }; outputPort = client.CreateOutputPort ("CoreMidiSample Output Port"); inputPort = client.CreateInputPort ("CoreMidiSample Input Port"); - inputPort.MessageReceived += delegate(object sender, MidiPacketsEventArgs e) { + inputPort.MessageReceived += delegate (object sender, MidiPacketsEventArgs e) + { Console.WriteLine ("Got {0} packets", e.Packets.Length); }; ConnectExistingDevices (); @@ -231,7 +237,7 @@ void ConnectExistingDevices () } } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/CoreTelephonyDemo/AppDelegate.cs b/CoreTelephonyDemo/AppDelegate.cs index c9b77fa74..f9078c152 100644 --- a/CoreTelephonyDemo/AppDelegate.cs +++ b/CoreTelephonyDemo/AppDelegate.cs @@ -1,14 +1,12 @@ using Foundation; using UIKit; -namespace CoreTelephonyDemo -{ +namespace CoreTelephonyDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { CoreTelephonyDemoViewController viewController; UIWindow window; UINavigationController navigationController; diff --git a/CoreTelephonyDemo/CoreTelephonyDemoViewController.cs b/CoreTelephonyDemo/CoreTelephonyDemoViewController.cs index d66c1ee0b..9d1965350 100644 --- a/CoreTelephonyDemo/CoreTelephonyDemoViewController.cs +++ b/CoreTelephonyDemo/CoreTelephonyDemoViewController.cs @@ -5,14 +5,12 @@ using Foundation; using CoreTelephony; -namespace CoreTelephonyDemo -{ - public partial class CoreTelephonyDemoViewController : UITableViewController - { +namespace CoreTelephonyDemo { + public partial class CoreTelephonyDemoViewController : UITableViewController { CTTelephonyNetworkInfo networkInfo; CTCallCenter callCenter; string carrierName; - CTCall[] calls = new CTCall [0]; + CTCall [] calls = new CTCall [0]; public CoreTelephonyDemoViewController () : base ("CoreTelephonyDemoViewController", null) @@ -36,8 +34,7 @@ public override void ViewDidLoad () private void ProviderUpdatedEvent (CTCarrier carrier) { - CoreFoundation.DispatchQueue.MainQueue.DispatchSync (() => - { + CoreFoundation.DispatchQueue.MainQueue.DispatchSync (() => { carrierName = carrier == null ? null : carrier.CarrierName; TableView.ReloadData (); }); @@ -45,8 +42,7 @@ private void ProviderUpdatedEvent (CTCarrier carrier) private void CallEvent (CTCall inCTCall) { - CoreFoundation.DispatchQueue.MainQueue.DispatchSync (() => - { + CoreFoundation.DispatchQueue.MainQueue.DispatchSync (() => { NSSet calls = callCenter.CurrentCalls; calls = callCenter.CurrentCalls; if (calls == null) { @@ -54,8 +50,7 @@ private void CallEvent (CTCall inCTCall) } else { this.calls = calls.ToArray (); } - Array.Sort (this.calls, (CTCall a, CTCall b) => - { + Array.Sort (this.calls, (CTCall a, CTCall b) => { return string.Compare (a.CallID, b.CallID); }); TableView.ReloadData (); @@ -103,7 +98,7 @@ public TableViewDataSource (CoreTelephonyDemoViewController controller) #region implemented abstract members of MonoTouch.UIKit.UITableViewDataSource public override nint RowsInSection (UITableView tableView, nint section) { - switch ((SectionIndex) (int)section) { + switch ((SectionIndex) (int) section) { case SectionIndex.CurrentCall: var controller = wcontroller.Target as CoreTelephonyDemoViewController; return Math.Max (controller.calls.Length, 1); @@ -182,7 +177,7 @@ public override nint NumberOfSections (UITableView tableView) public override string TitleForHeader (UITableView tableView, nint section) { - switch ((SectionIndex) (int)section) { + switch ((SectionIndex) (int) section) { case SectionIndex.CurrentCall: return "Current call"; case SectionIndex.CallCenter: diff --git a/CoreTelephonyDemo/Main.cs b/CoreTelephonyDemo/Main.cs index 2e40ded8a..1f5b004a1 100644 --- a/CoreTelephonyDemo/Main.cs +++ b/CoreTelephonyDemo/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace CoreTelephonyDemo -{ - public class Application - { +namespace CoreTelephonyDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/AppDelegate.cs b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/AppDelegate.cs index 3151c74de..d282709d9 100644 --- a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/AppDelegate.cs +++ b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace InitalScreenDemo -{ +namespace InitalScreenDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { @@ -21,9 +19,9 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary // If not required for your application you can safely delete this method // Code to start the Xamarin Test Cloud Agent - #if ENABLE_TEST_CLOUD +#if ENABLE_TEST_CLOUD Xamarin.Calabash.Start(); - #endif +#endif return true; } diff --git a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/Main.cs b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/Main.cs index b7924f519..bb1945f70 100644 --- a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/Main.cs +++ b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace InitalScreenDemo -{ - public class Application - { +namespace InitalScreenDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController1.cs b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController1.cs index 3d544b9ba..0c1f07f0a 100644 --- a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController1.cs +++ b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController1.cs @@ -3,22 +3,20 @@ using System.CodeDom.Compiler; using UIKit; -namespace InitalScreenDemo -{ - partial class ViewController1 : UIViewController - { +namespace InitalScreenDemo { + partial class ViewController1 : UIViewController { public ViewController1 (IntPtr handle) : base (handle) { } partial void InitialActionCompleted (UIButton sender) { - aButton.Hidden = true; + aButton.Hidden = true; } public override void ViewDidLoad () { - if (ParentViewController != null){ + if (ParentViewController != null) { aButton.Hidden = true; } diff --git a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController2.cs b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController2.cs index 74ae30e5d..4d9630de3 100644 --- a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController2.cs +++ b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController2.cs @@ -3,10 +3,8 @@ using System.CodeDom.Compiler; using UIKit; -namespace InitalScreenDemo -{ - partial class ViewController2 : UIViewController - { +namespace InitalScreenDemo { + partial class ViewController2 : UIViewController { public ViewController2 (IntPtr handle) : base (handle) { } diff --git a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController3.cs b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController3.cs index 625b205dc..3f9f46b9b 100644 --- a/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController3.cs +++ b/CreatingTabbedApplications/InitalScreenDemo/InitalScreenDemo/ViewController3.cs @@ -3,10 +3,8 @@ using System.CodeDom.Compiler; using UIKit; -namespace InitalScreenDemo -{ - partial class ViewController3 : UIViewController - { +namespace InitalScreenDemo { + partial class ViewController3 : UIViewController { public ViewController3 (IntPtr handle) : base (handle) { } diff --git a/CreatingTabbedApplications/TabbedApplication/TabbedApplication/AppDelegate.cs b/CreatingTabbedApplications/TabbedApplication/TabbedApplication/AppDelegate.cs index bace4e0f6..94e3a1378 100644 --- a/CreatingTabbedApplications/TabbedApplication/TabbedApplication/AppDelegate.cs +++ b/CreatingTabbedApplications/TabbedApplication/TabbedApplication/AppDelegate.cs @@ -5,11 +5,9 @@ using Foundation; using UIKit; -namespace TabbedApplication -{ +namespace TabbedApplication { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; TabController tabController; @@ -21,7 +19,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.RootViewController = tabController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/CreatingTabbedApplications/TabbedApplication/TabbedApplication/Main.cs b/CreatingTabbedApplications/TabbedApplication/TabbedApplication/Main.cs index 2edca629d..07856e648 100644 --- a/CreatingTabbedApplications/TabbedApplication/TabbedApplication/Main.cs +++ b/CreatingTabbedApplications/TabbedApplication/TabbedApplication/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace TabbedApplication -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace TabbedApplication { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/CreatingTabbedApplications/TabbedApplication/TabbedApplication/TabController.cs b/CreatingTabbedApplications/TabbedApplication/TabbedApplication/TabController.cs index 747bf5721..c1b6cdf23 100644 --- a/CreatingTabbedApplications/TabbedApplication/TabbedApplication/TabController.cs +++ b/CreatingTabbedApplications/TabbedApplication/TabbedApplication/TabController.cs @@ -1,38 +1,36 @@ using System; using UIKit; -namespace TabbedApplication -{ - public class TabController : UITabBarController - { - +namespace TabbedApplication { + public class TabController : UITabBarController { + UIViewController tab1, tab2, tab3; - + public TabController () { tab1 = new UIViewController (); -// tab1.Title = "Green"; + // tab1.Title = "Green"; tab1.TabBarItem = new UITabBarItem (UITabBarSystemItem.Favorites, 0); tab1.View.BackgroundColor = UIColor.Green; - + tab2 = new UIViewController (); -// tab2.Title = "Orange"; + // tab2.Title = "Orange"; tab2.TabBarItem = new UITabBarItem (); tab2.TabBarItem.Image = UIImage.FromFile ("second.png"); tab2.TabBarItem.Title = "Second"; tab2.View.BackgroundColor = UIColor.Orange; - + tab3 = new UIViewController (); - tab3.Title = "Red"; + tab3.Title = "Red"; tab3.View.BackgroundColor = UIColor.Red; - tab3.TabBarItem.BadgeValue = "Hi"; - - var tabs = new UIViewController[] { - tab1, tab2, tab3 - }; - + tab3.TabBarItem.BadgeValue = "Hi"; + + var tabs = new UIViewController [] { + tab1, tab2, tab3 + }; + ViewControllers = tabs; - } + } } } diff --git a/CustomCollectionViewLayoutAttributes/Animals.cs b/CustomCollectionViewLayoutAttributes/Animals.cs index 9436ccf63..cbb7e5f5b 100644 --- a/CustomCollectionViewLayoutAttributes/Animals.cs +++ b/CustomCollectionViewLayoutAttributes/Animals.cs @@ -1,22 +1,19 @@ using System; using UIKit; -namespace SimpleCollectionView -{ - public interface IAnimal - { +namespace SimpleCollectionView { + public interface IAnimal { string Name { get; } UIImage Image { get; } } - public class Monkey : IAnimal - { + public class Monkey : IAnimal { public string Name { get { return "Monkey"; } } public UIImage Image { get { return UIImage.FromBundle ("monkey.png"); } } } public class Tamarin : IAnimal { - public string Name { get { return "Tamarin"; } } + public string Name { get { return "Tamarin"; } } public UIImage Image { get { return UIImage.FromBundle ("placeholder.png"); } } } } diff --git a/CustomCollectionViewLayoutAttributes/AppDelegate.cs b/CustomCollectionViewLayoutAttributes/AppDelegate.cs index 5139f568a..f021dc20b 100644 --- a/CustomCollectionViewLayoutAttributes/AppDelegate.cs +++ b/CustomCollectionViewLayoutAttributes/AppDelegate.cs @@ -6,32 +6,30 @@ using UIKit; using CoreGraphics; -namespace SimpleCollectionView -{ - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - UIWindow window; - UICollectionViewController simpleCollectionViewController; - CircleLayout circleLayout; - - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); +namespace SimpleCollectionView { + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + UIWindow window; + UICollectionViewController simpleCollectionViewController; + CircleLayout circleLayout; + + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); - circleLayout = new CircleLayout (); - simpleCollectionViewController = new SimpleCollectionViewController (circleLayout); + circleLayout = new CircleLayout (); + simpleCollectionViewController = new SimpleCollectionViewController (circleLayout); - window.RootViewController = simpleCollectionViewController; - window.MakeKeyAndVisible (); + window.RootViewController = simpleCollectionViewController; + window.MakeKeyAndVisible (); - return true; - } + return true; + } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } - } + } } diff --git a/CustomCollectionViewLayoutAttributes/CircleLayout.cs b/CustomCollectionViewLayoutAttributes/CircleLayout.cs index 21d592c54..8a8386164 100644 --- a/CustomCollectionViewLayoutAttributes/CircleLayout.cs +++ b/CustomCollectionViewLayoutAttributes/CircleLayout.cs @@ -6,8 +6,7 @@ using UIKit; using ObjCRuntime; -namespace SimpleCollectionView -{ +namespace SimpleCollectionView { public class CircleData { public int CellCount = 20; public float Radius; @@ -15,12 +14,11 @@ public class CircleData { public CGPoint Center; } - public class CircleLayout : UICollectionViewLayout - { + public class CircleLayout : UICollectionViewLayout { Random random = new Random (); CircleData data = new CircleData (); - [Export("layoutAttributesClass")] + [Export ("layoutAttributesClass")] public static new Class LayoutAttributesClass { get { return new Class (typeof (CustomCollectionViewLayoutAttributes)); @@ -33,9 +31,9 @@ public override void PrepareLayout () CGSize size = CollectionView.Frame.Size; - data.CellCount = (int)CollectionView.NumberOfItemsInSection (0); + data.CellCount = (int) CollectionView.NumberOfItemsInSection (0); data.Center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f); - data.Radius = (int)Math.Min (size.Width, size.Height) / 2.5f; + data.Radius = (int) Math.Min (size.Width, size.Height) / 2.5f; } public override CGSize CollectionViewContentSize { @@ -44,10 +42,10 @@ public override CGSize CollectionViewContentSize { } } - public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) - { - return true; - } + public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) + { + return true; + } public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath path) { @@ -65,7 +63,7 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSInde return attributes; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { var attributes = new UICollectionViewLayoutAttributes [data.CellCount]; @@ -78,8 +76,7 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn } } - public class CustomCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes - { + public class CustomCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes { public int Row { get; set; } public CircleData Data { get; set; } // "distance from center" multiplier. diff --git a/CustomCollectionViewLayoutAttributes/SimpleCollectionViewController.cs b/CustomCollectionViewLayoutAttributes/SimpleCollectionViewController.cs index 598cc864e..d4fb4eba9 100644 --- a/CustomCollectionViewLayoutAttributes/SimpleCollectionViewController.cs +++ b/CustomCollectionViewLayoutAttributes/SimpleCollectionViewController.cs @@ -5,43 +5,41 @@ using Foundation; using CoreGraphics; -namespace SimpleCollectionView -{ - public class SimpleCollectionViewController : UICollectionViewController - { - static NSString animalCellId = new NSString ("AnimalCell"); - List animals; - UIGestureRecognizer tapRecognizer; - - public SimpleCollectionViewController (UICollectionViewLayout layout) : base (layout) - { - animals = new List (); - for (int i = 0; i < 20; i++) { +namespace SimpleCollectionView { + public class SimpleCollectionViewController : UICollectionViewController { + static NSString animalCellId = new NSString ("AnimalCell"); + List animals; + UIGestureRecognizer tapRecognizer; + + public SimpleCollectionViewController (UICollectionViewLayout layout) : base (layout) + { + animals = new List (); + for (int i = 0; i < 20; i++) { animals.Add (i % 2 == 0 ? (IAnimal) new Monkey () : (IAnimal) new Tamarin ()); - } - } + } + } - public override void ViewDidLoad () - { - base.ViewDidLoad (); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - tapRecognizer = new UITapGestureRecognizer (Tapped); - CollectionView.AddGestureRecognizer (tapRecognizer); - CollectionView.RegisterClassForCell (typeof (AnimalCell), animalCellId); + tapRecognizer = new UITapGestureRecognizer (Tapped); + CollectionView.AddGestureRecognizer (tapRecognizer); + CollectionView.RegisterClassForCell (typeof (AnimalCell), animalCellId); CollectionView.BackgroundColor = UIColor.LightGray; - } + } - void Tapped () - { - if (tapRecognizer.State == UIGestureRecognizerState.Ended) { - var pinchPoint = tapRecognizer.LocationInView (CollectionView); + void Tapped () + { + if (tapRecognizer.State == UIGestureRecognizerState.Ended) { + var pinchPoint = tapRecognizer.LocationInView (CollectionView); var tappedCellPath = GetIndexPathsForVisibleItems (pinchPoint); - if (tappedCellPath != null) { + if (tappedCellPath != null) { animals.RemoveAt (tappedCellPath.Row); - CollectionView.DeleteItems (new NSIndexPath[] { tappedCellPath }); - } - } - } + CollectionView.DeleteItems (new NSIndexPath [] { tappedCellPath }); + } + } + } public NSIndexPath GetIndexPathsForVisibleItems (CGPoint touchPoint) { @@ -53,50 +51,49 @@ public NSIndexPath GetIndexPathsForVisibleItems (CGPoint touchPoint) return null; } - public override nint GetItemsCount (UICollectionView collectionView, nint section) - { - return animals.Count; - } + public override nint GetItemsCount (UICollectionView collectionView, nint section) + { + return animals.Count; + } - public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) - { - var animalCell = (AnimalCell) collectionView.DequeueReusableCell (animalCellId, indexPath); + public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) + { + var animalCell = (AnimalCell) collectionView.DequeueReusableCell (animalCellId, indexPath); - var animal = animals [indexPath.Row]; - animalCell.Image = animal.Image; + var animal = animals [indexPath.Row]; + animalCell.Image = animal.Image; - return animalCell; - } - } + return animalCell; + } + } - public class AnimalCell : UICollectionViewCell - { - UIImageView imageView; + public class AnimalCell : UICollectionViewCell { + UIImageView imageView; - [Export ("initWithFrame:")] - public AnimalCell (CGRect frame) : base (frame) - { - BackgroundView = new UIView { BackgroundColor = UIColor.Orange }; + [Export ("initWithFrame:")] + public AnimalCell (CGRect frame) : base (frame) + { + BackgroundView = new UIView { BackgroundColor = UIColor.Orange }; - SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Green }; + SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Green }; - ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; - ContentView.Layer.BorderWidth = 2.0f; - ContentView.BackgroundColor = UIColor.White; - ContentView.Transform = CGAffineTransform.MakeScale (0.8f, 0.8f); + ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; + ContentView.Layer.BorderWidth = 2.0f; + ContentView.BackgroundColor = UIColor.White; + ContentView.Transform = CGAffineTransform.MakeScale (0.8f, 0.8f); - imageView = new UIImageView (UIImage.FromBundle ("placeholder.png")); - imageView.Center = ContentView.Center; - imageView.Transform = CGAffineTransform.MakeScale (0.7f, 0.7f); + imageView = new UIImageView (UIImage.FromBundle ("placeholder.png")); + imageView.Center = ContentView.Center; + imageView.Transform = CGAffineTransform.MakeScale (0.7f, 0.7f); - ContentView.AddSubview (imageView); - } + ContentView.AddSubview (imageView); + } - public UIImage Image { - set { - imageView.Image = value; - } - } + public UIImage Image { + set { + imageView.Image = value; + } + } public override void ApplyLayoutAttributes (UICollectionViewLayoutAttributes layoutAttributes) { @@ -104,15 +101,15 @@ public override void ApplyLayoutAttributes (UICollectionViewLayoutAttributes lay if (attributes != null) { var data = attributes.Data; attributes.Center = new CGPoint (data.Center.X + data.Radius * attributes.Distance * (float) Math.Cos (2 * attributes.Row * Math.PI / data.CellCount), - data.Center.Y + data.Radius * attributes.Distance * (float) Math.Sin (2 * attributes.Row * Math.PI / data.CellCount)); + data.Center.Y + data.Radius * attributes.Distance * (float) Math.Sin (2 * attributes.Row * Math.PI / data.CellCount)); - if (!float.IsNaN ((float)attributes.Center.X) && !float.IsNaN ((float)attributes.Center.Y) && - UIDevice.CurrentDevice.CheckSystemVersion(7, 0)) + if (!float.IsNaN ((float) attributes.Center.X) && !float.IsNaN ((float) attributes.Center.Y) && + UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) Center = attributes.Center; } base.ApplyLayoutAttributes (layoutAttributes); } - } + } } diff --git a/CustomInputStream/AppDelegate.cs b/CustomInputStream/AppDelegate.cs index e286f998b..eb34f33b5 100644 --- a/CustomInputStream/AppDelegate.cs +++ b/CustomInputStream/AppDelegate.cs @@ -8,11 +8,9 @@ using MonoTouch.Dialog; -namespace InputStreamTest -{ +namespace InputStreamTest { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; DialogViewController dvc; NativeUploader uploader; @@ -48,17 +46,14 @@ void Upload () Console.WriteLine ("Listening on: {0}", listener.LocalEndpoint); uploader = new NativeUploader (); - uploader.UploadStream ("http://127.0.0.1:" + ((IPEndPoint) listener.LocalEndpoint).Port.ToString (), 1000, () => - { + uploader.UploadStream ("http://127.0.0.1:" + ((IPEndPoint) listener.LocalEndpoint).Port.ToString (), 1000, () => { Console.WriteLine ("Upload completed."); }); - listener.BeginAcceptSocket ((IAsyncResult res) => - { - ThreadPool.QueueUserWorkItem ((v) => - { + listener.BeginAcceptSocket ((IAsyncResult res) => { + ThreadPool.QueueUserWorkItem ((v) => { using (var socket = listener.EndAcceptSocket (res)) { - byte [] buffer = new byte[1024]; + byte [] buffer = new byte [1024]; int read; // receive headers @@ -83,7 +78,7 @@ void Upload () }, null); } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/CustomInputStream/NativeUploader.cs b/CustomInputStream/NativeUploader.cs index 454e7e38b..3fe0e5f45 100644 --- a/CustomInputStream/NativeUploader.cs +++ b/CustomInputStream/NativeUploader.cs @@ -3,14 +3,12 @@ using System.Collections.Generic; using Foundation; -namespace InputStreamTest -{ - public class NativeUploader : NSObject - { +namespace InputStreamTest { + public class NativeUploader : NSObject { NSMutableUrlRequest request; NSUrlConnection url_connection; ZInputStream random_input_stream; - Dictionary headers; + Dictionary headers; protected override void Dispose (bool disposing) { @@ -20,7 +18,7 @@ protected override void Dispose (bool disposing) } if (request != null) { - if(request.BodyStream!=null) + if (request.BodyStream != null) request.BodyStream = null; request.Dispose (); request = null; @@ -51,7 +49,8 @@ public void UploadStream (string url, long content_length, Action completed) AddHeader ("Content-Type", "application/octet-stream"); AddHeader ("Content-Length", content_length.ToString ()); - InvokeOnMainThread (delegate { + InvokeOnMainThread (delegate + { try { request = CreateNativePostRequest (url, content_length); } catch (Exception e) { @@ -104,7 +103,7 @@ public NativeUrlDelegate (Action success, Action failure) { success_callback = success; failure_callback = failure; - data = new NSMutableData(); + data = new NSMutableData (); } public override void ReceivedData (NSUrlConnection connection, NSData d) @@ -121,7 +120,7 @@ public override void ReceivedResponse (NSUrlConnection connection, NSUrlResponse return; } - status_code = (int)http_response.StatusCode; + status_code = (int) http_response.StatusCode; Console.WriteLine ("Status code of result: '{0}'", status_code); } diff --git a/CustomInputStream/ZInputStream.cs b/CustomInputStream/ZInputStream.cs index e5d05ec37..efa721610 100644 --- a/CustomInputStream/ZInputStream.cs +++ b/CustomInputStream/ZInputStream.cs @@ -4,11 +4,9 @@ using CoreFoundation; using Foundation; -namespace InputStreamTest -{ +namespace InputStreamTest { [Preserve (AllMembers = true)] - public class ZInputStream : NSInputStream - { + public class ZInputStream : NSInputStream { NSStreamStatus status; long read_length; long total_length; @@ -61,15 +59,15 @@ public override nint Read (IntPtr buffer, nuint len) protected override bool GetBuffer (out IntPtr buffer, out nuint len) { - // Just call the base implemention (which will return false) + // Just call the base implemention (which will return false) return base.GetBuffer (out buffer, out len); } - /* protected override bool GetBuffer(out IntPtr buffer, out uint len) - { - // Just call the base implemention (which will return false) - return base.GetBuffer (out buffer, out len); - }*/ + /* protected override bool GetBuffer(out IntPtr buffer, out uint len) + { + // Just call the base implemention (which will return false) + return base.GetBuffer (out buffer, out len); + }*/ protected override bool SetCFClientFlags (CFStreamEventType inFlags, IntPtr inCallback, IntPtr inContextPtr) { diff --git a/CustomPropertyAnimation/AppDelegate.cs b/CustomPropertyAnimation/AppDelegate.cs index ff2f68d8e..71c3ea7fb 100644 --- a/CustomPropertyAnimation/AppDelegate.cs +++ b/CustomPropertyAnimation/AppDelegate.cs @@ -5,11 +5,9 @@ using Foundation; using UIKit; -namespace CustomPropertyAnimation -{ +namespace CustomPropertyAnimation { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UIViewController vc; CircleLayer testLayer; @@ -25,15 +23,15 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) vc = new UIViewControllerRotation (); vc.View.BackgroundColor = UIColor.Black; - testLayer = new CircleLayer(); + testLayer = new CircleLayer (); testLayer.Color = UIColor.Green.CGColor; testLayer.Thickness = 19f; testLayer.Radius = 60f; testLayer.Frame = vc.View.Layer.Bounds; - vc.View.Layer.AddSublayer(testLayer); + vc.View.Layer.AddSublayer (testLayer); - testLayer.SetNeedsDisplay(); + testLayer.SetNeedsDisplay (); radiusAnimation = CABasicAnimation.FromKeyPath ("radius"); radiusAnimation.Duration = 3; @@ -62,7 +60,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) } // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. @@ -70,24 +68,21 @@ static void Main (string[] args) } } - public class UIViewControllerRotation : UIViewController - { + public class UIViewControllerRotation : UIViewController { public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrientation, double duration) { base.WillAnimateRotation (toInterfaceOrientation, duration); // call our helper method to position the controls - CALayer[] layers = this.View.Layer.Sublayers; - foreach (CALayer layer in layers) - { + CALayer [] layers = this.View.Layer.Sublayers; + foreach (CALayer layer in layers) { layer.Frame = this.View.Layer.Bounds; } } } - public class CircleLayer : CALayer - { + public class CircleLayer : CALayer { public CircleLayer () { } @@ -142,19 +137,19 @@ public override void DrawInContext (CGContext context) // Outer circle context.AddEllipseInRect (new CGRect (centerPoint.X - (float) Radius, - centerPoint.Y - (float) Radius, - (float) Radius * 2, - (float) Radius * 2)); + centerPoint.Y - (float) Radius, + (float) Radius * 2, + (float) Radius * 2)); // Inner circle context.AddEllipseInRect (new CGRect (centerPoint.X - (float) innerRadius, - centerPoint.Y - (float) innerRadius, - (float) innerRadius * 2, - (float) innerRadius * 2)); + centerPoint.Y - (float) innerRadius, + (float) innerRadius * 2, + (float) innerRadius * 2)); // Fill in circle context.SetFillColor (Color); context.SetShadow (CGSize.Empty, 10.0f, glowColor); - context.EOFillPath(); + context.EOFillPath (); } } } diff --git a/CustomTransitions/CustomTransitions/AdaptivePresentation/APFirstViewController.cs b/CustomTransitions/CustomTransitions/AdaptivePresentation/APFirstViewController.cs index 463bf19b5..122b519c5 100644 --- a/CustomTransitions/CustomTransitions/AdaptivePresentation/APFirstViewController.cs +++ b/CustomTransitions/CustomTransitions/AdaptivePresentation/APFirstViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; diff --git a/CustomTransitions/CustomTransitions/AdaptivePresentation/APSecondViewController.cs b/CustomTransitions/CustomTransitions/AdaptivePresentation/APSecondViewController.cs index c8dea3eb8..71163a05c 100644 --- a/CustomTransitions/CustomTransitions/AdaptivePresentation/APSecondViewController.cs +++ b/CustomTransitions/CustomTransitions/AdaptivePresentation/APSecondViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; diff --git a/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationController.cs b/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationController.cs index febe4c416..ead3c684a 100644 --- a/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationController.cs +++ b/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationController.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; using Foundation; using CoreGraphics; @@ -34,7 +34,7 @@ public override void PresentationTransitionWillBegin () var dismissButtonAux = new UIButton (UIButtonType.Custom) { Frame = new CGRect (0f, 0f, 26f, 26f) }; - dismissButtonAux.SetImage (new UIImage("CloseButton"), UIControlState.Normal); + dismissButtonAux.SetImage (new UIImage ("CloseButton"), UIControlState.Normal); dismissButtonAux.AddTarget ((object sender, System.EventArgs e) => DismissButtonTapped (dismissButtonAux), UIControlEvent.TouchUpInside); dismissButton = dismissButtonAux; @@ -54,7 +54,7 @@ public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerT presentationWrappingView.Layer.ShadowOpacity = .0f; presentationWrappingView.Layer.ShadowRadius = .0f; - coordinator.AnimateAlongsideTransition ((obj) => {}, (obj) => { + coordinator.AnimateAlongsideTransition ((obj) => { }, (obj) => { presentationWrappingView.ClipsToBounds = false; presentationWrappingView.Layer.ShadowOpacity = .63f; presentationWrappingView.Layer.ShadowRadius = 17f; @@ -69,14 +69,14 @@ public override CGSize GetSizeForChildContentContainer (IUIContentContainer cont return base.GetSizeForChildContentContainer (contentContainer, parentContainerSize); } - public override CGRect FrameOfPresentedViewInContainerView{ + public override CGRect FrameOfPresentedViewInContainerView { get { CGRect containerViewBounds = ContainerView.Bounds; var presentedViewContentSize = GetSizeForChildContentContainer (PresentedViewController, containerViewBounds.Size); - var frame = new CGRect (containerViewBounds.GetMidX () - (presentedViewContentSize.Width / 2f), - containerViewBounds.GetMidY () - (presentedViewContentSize.Height / 2f), - presentedViewContentSize.Width, presentedViewContentSize.Height); + var frame = new CGRect (containerViewBounds.GetMidX () - (presentedViewContentSize.Width / 2f), + containerViewBounds.GetMidY () - (presentedViewContentSize.Height / 2f), + presentedViewContentSize.Width, presentedViewContentSize.Height); return frame.Inset (-20f, -20f); } @@ -91,7 +91,7 @@ public override void ContainerViewWillLayoutSubviews () dismissButton.Center = new CGPoint (PresentedViewController.View.Frame.GetMinX (), PresentedViewController.View.Frame.GetMinY ()); } - public double TransitionDuration(IUIViewControllerContextTransitioning transitionContext) + public double TransitionDuration (IUIViewControllerContextTransitioning transitionContext) { return transitionContext.IsAnimated ? 0 : 0.35; } @@ -114,26 +114,25 @@ public void AnimateTransition (IUIViewControllerContextTransitioning transitionC toView.Alpha = 0f; if (fromView != null) - fromView.Frame = transitionContext.GetFinalFrameForViewController(fromViewController); + fromView.Frame = transitionContext.GetFinalFrameForViewController (fromViewController); - toView.Frame = transitionContext.GetFinalFrameForViewController(toViewController); - } - else if (toView != null) { + toView.Frame = transitionContext.GetFinalFrameForViewController (toViewController); + } else if (toView != null) { toView.Frame = transitionContext.GetFinalFrameForViewController (toViewController); } double transitionDuration = TransitionDuration (transitionContext); - UIView.Animate(transitionDuration, 0, UIViewAnimationOptions.TransitionNone, () => { - if (toView != null) - toView.Alpha = isPresenting ? 1f : 0f; - }, () => { - bool wasCancelled = transitionContext.TransitionWasCancelled; - transitionContext.CompleteTransition (!wasCancelled); + UIView.Animate (transitionDuration, 0, UIViewAnimationOptions.TransitionNone, () => { + if (toView != null) + toView.Alpha = isPresenting ? 1f : 0f; + }, () => { + bool wasCancelled = transitionContext.TransitionWasCancelled; + transitionContext.CompleteTransition (!wasCancelled); - if (isPresenting == false) - fromView.Alpha = 1f; - } + if (isPresenting == false) + fromView.Alpha = 1f; + } ); } diff --git a/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationSegue.cs b/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationSegue.cs index b0020945b..832093e3b 100644 --- a/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationSegue.cs +++ b/CustomTransitions/CustomTransitions/AdaptivePresentation/AdaptivePresentationSegue.cs @@ -14,8 +14,8 @@ public AdaptivePresentationSegue (IntPtr handle) : base (handle) public override void Perform () { - var sourceViewController = (APSecondViewController)DestinationViewController; - var destinationViewController = (APSecondViewController)DestinationViewController; + var sourceViewController = (APSecondViewController) DestinationViewController; + var destinationViewController = (APSecondViewController) DestinationViewController; var presentationController = new AdaptivePresentationController (destinationViewController, sourceViewController); diff --git a/CustomTransitions/CustomTransitions/AppDelegate.cs b/CustomTransitions/CustomTransitions/AppDelegate.cs index 7579ae22b..ecd899460 100644 --- a/CustomTransitions/CustomTransitions/AppDelegate.cs +++ b/CustomTransitions/CustomTransitions/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace CustomTransitions { diff --git a/CustomTransitions/CustomTransitions/Checkboard/CheckboardFirstViewController.cs b/CustomTransitions/CustomTransitions/Checkboard/CheckboardFirstViewController.cs index 18c958292..3c2c179df 100644 --- a/CustomTransitions/CustomTransitions/Checkboard/CheckboardFirstViewController.cs +++ b/CustomTransitions/CustomTransitions/Checkboard/CheckboardFirstViewController.cs @@ -1,11 +1,11 @@ -using System; +using System; using Foundation; using UIKit; namespace CustomTransitions { public partial class CheckboardFirstViewController : UIViewController, IUINavigationControllerDelegate { - partial void unwindToMenuViewController(UIBarButtonItem sender) + partial void unwindToMenuViewController (UIBarButtonItem sender) { DismissViewController (true, null); } diff --git a/CustomTransitions/CustomTransitions/Checkboard/CheckboardTransitionAnimator.cs b/CustomTransitions/CustomTransitions/Checkboard/CheckboardTransitionAnimator.cs index 0290b069c..ada3a9ecb 100644 --- a/CustomTransitions/CustomTransitions/Checkboard/CheckboardTransitionAnimator.cs +++ b/CustomTransitions/CustomTransitions/Checkboard/CheckboardTransitionAnimator.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreAnimation; using CoreGraphics; @@ -27,14 +27,14 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr // TODO UIImage fromViewSnapshot; - var toViewSnapshot = new UIImage(); + var toViewSnapshot = new UIImage (); UIGraphics.BeginImageContextWithOptions (containerView.Bounds.Size, true, containerView.Window.Screen.Scale); fromView.DrawViewHierarchy (containerView.Bounds, false); fromViewSnapshot = UIGraphics.GetImageFromCurrentImageContext (); UIGraphics.EndImageContext (); - CoreFoundation.DispatchQueue.MainQueue.DispatchAsync (() => { + CoreFoundation.DispatchQueue.MainQueue.DispatchAsync (() => { UIGraphics.BeginImageContextWithOptions (containerView.Bounds.Size, true, containerView.Window.Screen.Scale); toView.DrawViewHierarchy (containerView.Bounds, false); toViewSnapshot = UIGraphics.GetImageFromCurrentImageContext (); @@ -63,15 +63,15 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr var transitionDuration = TransitionDuration (transitionContext); nfloat dx = isPush ? transitionContainer.Bounds.GetMaxY () - transitionContainer.Bounds.GetMinX () - : transitionContainer.Bounds.GetMinX () - transitionContainer.Bounds.GetMaxX (); + : transitionContainer.Bounds.GetMinX () - transitionContainer.Bounds.GetMaxX (); nfloat dy = isPush ? transitionContainer.Bounds.GetMaxY () - transitionContainer.Bounds.GetMinY () : - transitionContainer.Bounds.GetMinY () - transitionContainer.Bounds.GetMaxY (); + transitionContainer.Bounds.GetMinY () - transitionContainer.Bounds.GetMaxY (); var transitionVector = new CGVector (dx, dy); - var transitionVectorLength = (nfloat)Math.Sqrt (transitionVector.dx * transitionVector.dx + transitionVector.dy * transitionVector.dy); - var transitionUnitVector = new CGVector (transitionVector.dx / transitionVectorLength, transitionVector.dy / new nfloat(transitionVectorLength)); + var transitionVectorLength = (nfloat) Math.Sqrt (transitionVector.dx * transitionVector.dx + transitionVector.dy * transitionVector.dy); + var transitionUnitVector = new CGVector (transitionVector.dx / transitionVectorLength, transitionVector.dy / new nfloat (transitionVectorLength)); for (int y = 0; y < verticalSlices; y++) { for (int x = 0; x < horizontalSileces; x++) { @@ -102,7 +102,7 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr toCheckboardSquareView.Layer.MasksToBounds = true; toCheckboardSquareView.Layer.DoubleSided = false; toCheckboardSquareView.Layer.Transform = CATransform3D.MakeRotation (NMath.PI, 0f, 1f, 0f); - toCheckboardSquareView.Layer.AddSublayer(toContentLayer); + toCheckboardSquareView.Layer.AddSublayer (toContentLayer); var fromCheckboardSquareView = new UIView { Frame = new CGRect (x * sliceSize, y * sliceSize, sliceSize, sliceSize), @@ -124,10 +124,10 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr for (int y = 0; y < verticalSlices; y++) { for (int x = 0; x < horizontalSileces; x++) { double toIndex = y * horizontalSileces * 2f + (x * 2); - UIView toCheckboardSquareView = transitionContainer.Subviews[(int)toIndex]; + UIView toCheckboardSquareView = transitionContainer.Subviews [(int) toIndex]; double fromIndex = y * horizontalSileces * 2f + (x * 2 + 1); - UIView fromCheckboardSquareView = transitionContainer.Subviews[(int)fromIndex]; + UIView fromCheckboardSquareView = transitionContainer.Subviews [(int) fromIndex]; CGVector sliceOriginVector; @@ -148,16 +148,16 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr sliceAnimationsPending++; - UIView.Animate(duration, startTime, UIViewAnimationOptions.TransitionNone, () => { - toCheckboardSquareView.Layer.Transform = CATransform3D.Identity; - fromCheckboardSquareView.Layer.Transform = CATransform3D.MakeRotation (NMath.PI, 0f, 1f, 0f); - }, () => { - if (--sliceAnimationsPending == 0) { - bool wasCancelled = transitionContext.TransitionWasCancelled; - transitionContainer.RemoveFromSuperview (); - transitionContext.CompleteTransition (!wasCancelled); - } + UIView.Animate (duration, startTime, UIViewAnimationOptions.TransitionNone, () => { + toCheckboardSquareView.Layer.Transform = CATransform3D.Identity; + fromCheckboardSquareView.Layer.Transform = CATransform3D.MakeRotation (NMath.PI, 0f, 1f, 0f); + }, () => { + if (--sliceAnimationsPending == 0) { + bool wasCancelled = transitionContext.TransitionWasCancelled; + transitionContainer.RemoveFromSuperview (); + transitionContext.CompleteTransition (!wasCancelled); } + } ); } } diff --git a/CustomTransitions/CustomTransitions/CrossDissolve/CDFirstViewController.cs b/CustomTransitions/CustomTransitions/CrossDissolve/CDFirstViewController.cs index dcd1fe94a..ce991548c 100644 --- a/CustomTransitions/CustomTransitions/CrossDissolve/CDFirstViewController.cs +++ b/CustomTransitions/CustomTransitions/CrossDissolve/CDFirstViewController.cs @@ -1,15 +1,15 @@ -using System; +using System; using Foundation; using UIKit; namespace CustomTransitions { - public partial class CDFirstViewController : UIViewController, IUIViewControllerTransitioningDelegate { + public partial class CDFirstViewController : UIViewController, IUIViewControllerTransitioningDelegate { public CDFirstViewController (IntPtr handle) : base (handle) { } - partial void PresentWithCustomTransitionAction(UIButton sender) + partial void PresentWithCustomTransitionAction (UIButton sender) { UIViewController secondViewController = Storyboard.InstantiateViewController ("SecondViewController"); secondViewController.ModalPresentationStyle = UIModalPresentationStyle.FullScreen; diff --git a/CustomTransitions/CustomTransitions/CrossDissolve/CDSecondViewController.cs b/CustomTransitions/CustomTransitions/CrossDissolve/CDSecondViewController.cs index d99497167..ed680911f 100644 --- a/CustomTransitions/CustomTransitions/CrossDissolve/CDSecondViewController.cs +++ b/CustomTransitions/CustomTransitions/CrossDissolve/CDSecondViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; @@ -8,7 +8,7 @@ public CDSecondViewController (IntPtr handle) : base (handle) { } - partial void DismissAction(UIButton sender) + partial void DismissAction (UIButton sender) { DismissViewController (true, null); } diff --git a/CustomTransitions/CustomTransitions/CrossDissolve/CrossDissolveTransitionAnimator.cs b/CustomTransitions/CustomTransitions/CrossDissolve/CrossDissolveTransitionAnimator.cs index 7875fb59d..ac405e651 100644 --- a/CustomTransitions/CustomTransitions/CrossDissolve/CrossDissolveTransitionAnimator.cs +++ b/CustomTransitions/CustomTransitions/CrossDissolve/CrossDissolveTransitionAnimator.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace CustomTransitions { public class CrossDissolveTransitionAnimator : UIViewControllerAnimatedTransitioning { @@ -10,13 +10,13 @@ public override double TransitionDuration (IUIViewControllerContextTransitioning public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext) { - var fromViewController = transitionContext.GetViewControllerForKey(UITransitionContext.FromViewControllerKey); - var toViewController = transitionContext.GetViewControllerForKey(UITransitionContext.ToViewControllerKey); + var fromViewController = transitionContext.GetViewControllerForKey (UITransitionContext.FromViewControllerKey); + var toViewController = transitionContext.GetViewControllerForKey (UITransitionContext.ToViewControllerKey); UIView containerView = transitionContext.ContainerView; - var fromView = transitionContext.GetViewFor(UITransitionContext.FromViewKey); - var toView = transitionContext.GetViewFor(UITransitionContext.ToViewKey); + var fromView = transitionContext.GetViewFor (UITransitionContext.FromViewKey); + var toView = transitionContext.GetViewFor (UITransitionContext.ToViewKey); fromView.Frame = transitionContext.GetInitialFrameForViewController (fromViewController); toView.Frame = transitionContext.GetFinalFrameForViewController (toViewController); @@ -28,12 +28,12 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr var transitionDuration = TransitionDuration (transitionContext); UIView.Animate (transitionDuration, 0, UIViewAnimationOptions.TransitionNone, () => { - fromView.Alpha = 0f; - toView.Alpha = 1f; - }, () => { - bool wasCancel = transitionContext.TransitionWasCancelled; - transitionContext.CompleteTransition (!wasCancel); - } + fromView.Alpha = 0f; + toView.Alpha = 1f; + }, () => { + bool wasCancel = transitionContext.TransitionWasCancelled; + transitionContext.CompleteTransition (!wasCancel); + } ); } } diff --git a/CustomTransitions/CustomTransitions/CustomPresentation/CPFirstViewController.cs b/CustomTransitions/CustomTransitions/CustomPresentation/CPFirstViewController.cs index 4915c98f9..2ebad003c 100644 --- a/CustomTransitions/CustomTransitions/CustomPresentation/CPFirstViewController.cs +++ b/CustomTransitions/CustomTransitions/CustomPresentation/CPFirstViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; diff --git a/CustomTransitions/CustomTransitions/CustomPresentation/CPSecondViewController.cs b/CustomTransitions/CustomTransitions/CustomPresentation/CPSecondViewController.cs index 62a0b294f..f5b3a6f7a 100644 --- a/CustomTransitions/CustomTransitions/CustomPresentation/CPSecondViewController.cs +++ b/CustomTransitions/CustomTransitions/CustomPresentation/CPSecondViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; @@ -25,7 +25,7 @@ public void UpdatePreferredContentSizeWithTraitCollection (UITraitCollection tra float sizeHeigt = traitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact ? 270f : 420f; PreferredContentSize = new CoreGraphics.CGSize (View.Bounds.Width, sizeHeigt); - slider.MaxValue = (float)PreferredContentSize.Height; + slider.MaxValue = (float) PreferredContentSize.Height; slider.MinValue = 220f; slider.Value = slider.MaxValue; } diff --git a/CustomTransitions/CustomTransitions/CustomPresentation/CustomPresentationController.cs b/CustomTransitions/CustomTransitions/CustomPresentation/CustomPresentationController.cs index 7d8c7c6ac..ecda52140 100644 --- a/CustomTransitions/CustomTransitions/CustomPresentation/CustomPresentationController.cs +++ b/CustomTransitions/CustomTransitions/CustomPresentation/CustomPresentationController.cs @@ -1,4 +1,4 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; using UIKit; @@ -59,10 +59,10 @@ public override void PresentationTransitionWillBegin () ContainerView.AddSubview (dimmingView); - var transitionCoordinator = PresentingViewController.GetTransitionCoordinator(); + var transitionCoordinator = PresentingViewController.GetTransitionCoordinator (); dimmingView.Alpha = 0f; - transitionCoordinator.AnimateAlongsideTransition ((obj) => dimmingView.Alpha = .5f, (obj) => {}); + transitionCoordinator.AnimateAlongsideTransition ((obj) => dimmingView.Alpha = .5f, (obj) => { }); } CGRect UIEdgeInsetsInsetRect (CGRect rect, UIEdgeInsets insets) @@ -123,7 +123,7 @@ public override CGRect FrameOfPresentedViewInContainerView { CGRect presentedViewControllerFrame = containerViewBounds; presentedViewControllerFrame.Height = presentedViewContentSize.Height; - presentedViewControllerFrame.Y = containerViewBounds.GetMaxY() - presentedViewContentSize.Height; + presentedViewControllerFrame.Y = containerViewBounds.GetMaxY () - presentedViewContentSize.Height; return presentedViewControllerFrame; } @@ -148,9 +148,9 @@ public double TransitionDuration (IUIViewControllerContextTransitioning transiti } public void AnimateTransition (IUIViewControllerContextTransitioning transitionContext) - { - var fromViewController = transitionContext.GetViewControllerForKey(UITransitionContext.FromViewControllerKey); - var toViewController = transitionContext.GetViewControllerForKey(UITransitionContext.ToViewControllerKey); + { + var fromViewController = transitionContext.GetViewControllerForKey (UITransitionContext.FromViewControllerKey); + var toViewController = transitionContext.GetViewControllerForKey (UITransitionContext.ToViewControllerKey); UIView containerView = transitionContext.ContainerView; @@ -158,10 +158,10 @@ public void AnimateTransition (IUIViewControllerContextTransitioning transitionC var fromView = transitionContext.GetViewFor (UITransitionContext.FromViewKey); bool isPresenting = (fromViewController == PresentingViewController); - var fromViewFinalFrame = transitionContext.GetFinalFrameForViewController(fromViewController); - var toViewInitialFrame = transitionContext.GetInitialFrameForViewController(toViewController); + var fromViewFinalFrame = transitionContext.GetFinalFrameForViewController (fromViewController); + var toViewInitialFrame = transitionContext.GetInitialFrameForViewController (toViewController); - var toViewFinalFrame = transitionContext.GetFinalFrameForViewController(toViewController); + var toViewFinalFrame = transitionContext.GetFinalFrameForViewController (toViewController); if (toView != null) containerView.AddSubview (toView); @@ -180,14 +180,14 @@ public void AnimateTransition (IUIViewControllerContextTransitioning transitionC double transitionDuration = TransitionDuration (transitionContext); UIView.Animate (transitionDuration, 0, UIViewAnimationOptions.TransitionNone, () => { - if (isPresenting) - toView.Frame = toViewFinalFrame; - else - fromView.Frame = fromViewFinalFrame; - }, () => { - bool wasCancelled = transitionContext.TransitionWasCancelled; - transitionContext.CompleteTransition(!wasCancelled); - } + if (isPresenting) + toView.Frame = toViewFinalFrame; + else + fromView.Frame = fromViewFinalFrame; + }, () => { + bool wasCancelled = transitionContext.TransitionWasCancelled; + transitionContext.CompleteTransition (!wasCancelled); + } ); } diff --git a/CustomTransitions/CustomTransitions/Main.cs b/CustomTransitions/CustomTransitions/Main.cs index 8101f58d0..f4872e115 100644 --- a/CustomTransitions/CustomTransitions/Main.cs +++ b/CustomTransitions/CustomTransitions/Main.cs @@ -1,8 +1,8 @@ -using UIKit; +using UIKit; namespace CustomTransitions { public class Application { - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/CustomTransitions/CustomTransitions/MainMenu/MenuViewController.cs b/CustomTransitions/CustomTransitions/MainMenu/MenuViewController.cs index ef257c604..9b2977608 100644 --- a/CustomTransitions/CustomTransitions/MainMenu/MenuViewController.cs +++ b/CustomTransitions/CustomTransitions/MainMenu/MenuViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; diff --git a/CustomTransitions/CustomTransitions/Slide/SlideTransitionAnimator.cs b/CustomTransitions/CustomTransitions/Slide/SlideTransitionAnimator.cs index 7ed26fefa..7bfb80bba 100644 --- a/CustomTransitions/CustomTransitions/Slide/SlideTransitionAnimator.cs +++ b/CustomTransitions/CustomTransitions/Slide/SlideTransitionAnimator.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; using CoreGraphics; namespace CustomTransitions { @@ -11,7 +11,7 @@ public SlideTransitionAnimator (UIRectEdge edge) } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext) - { + { var fromViewController = transitionContext.GetViewControllerForKey (UITransitionContext.FromViewControllerKey); var toViewController = transitionContext.GetViewControllerForKey (UITransitionContext.ToViewControllerKey); @@ -41,14 +41,14 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr var duration = TransitionDuration (transitionContext); UIView.Animate (duration, 0, UIViewAnimationOptions.TransitionNone, () => { - var fromFrameAux = fromFrame; - fromFrameAux.Offset (fromFrame.Width * offset.dx, fromFrame.Height * offset.dy); - fromView.Frame = fromFrameAux; - - toView.Frame = toFrame; - }, () => { - transitionContext.CompleteTransition (!transitionContext.TransitionWasCancelled); - } + var fromFrameAux = fromFrame; + fromFrameAux.Offset (fromFrame.Width * offset.dx, fromFrame.Height * offset.dy); + fromView.Frame = fromFrameAux; + + toView.Frame = toFrame; + }, () => { + transitionContext.CompleteTransition (!transitionContext.TransitionWasCancelled); + } ); } diff --git a/CustomTransitions/CustomTransitions/Slide/SlideTransitionDelegate.cs b/CustomTransitions/CustomTransitions/Slide/SlideTransitionDelegate.cs index 6217404d9..d211552b4 100644 --- a/CustomTransitions/CustomTransitions/Slide/SlideTransitionDelegate.cs +++ b/CustomTransitions/CustomTransitions/Slide/SlideTransitionDelegate.cs @@ -3,20 +3,17 @@ using Foundation; using UIKit; -namespace CustomTransitions -{ +namespace CustomTransitions { [Register ("SlideTransitionDelegate")] - public class SlideTransitionDelegate : NSObject, IUITabBarControllerDelegate - { - public SlideTransitionDelegate (IntPtr handle) : base(handle) + public class SlideTransitionDelegate : NSObject, IUITabBarControllerDelegate { + public SlideTransitionDelegate (IntPtr handle) : base (handle) { } UITabBarController tabBarController; [Outlet] - public UITabBarController TabBarController - { + public UITabBarController TabBarController { get { return tabBarController; } @@ -47,7 +44,8 @@ UIPanGestureRecognizer PanGestureRecognizer { get { panGestureRecognizer = panGestureRecognizer ?? new UIPanGestureRecognizer (() => PanGestureRecognizerDidPan (panGestureRecognizer)); return panGestureRecognizer; - } set { + } + set { panGestureRecognizer = value; } } @@ -66,9 +64,9 @@ void BeginInteractiveTransitionIfPossible (UIPanGestureRecognizer sender) var translation = sender.TranslationInView (tabBarController.View); if (translation.X > 0f && tabBarController.SelectedIndex > 0) { - tabBarController.SelectedIndex --; + tabBarController.SelectedIndex--; } else if (translation.X < 0f && (tabBarController.SelectedIndex + 1) < tabBarController.ViewControllers.Length) { - tabBarController.SelectedIndex ++; + tabBarController.SelectedIndex++; } else if (!(Math.Abs (translation.X) < nfloat.Epsilon && Math.Abs (translation.Y) < nfloat.Epsilon)) { sender.Enabled = false; sender.Enabled = true; @@ -89,7 +87,7 @@ void BeginInteractiveTransitionIfPossible (UIPanGestureRecognizer sender) [Export ("tabBarController:animationControllerForTransitionFromViewController:toViewController:")] public IUIViewControllerAnimatedTransitioning GetAnimationControllerForTransition (UITabBarController tabBarController, UIViewController fromViewController, UIViewController toViewController) { - UIViewController[] viewControllers = tabBarController.ViewControllers; + UIViewController [] viewControllers = tabBarController.ViewControllers; if (Array.IndexOf (viewControllers, toViewController) > Array.IndexOf (viewControllers, fromViewController)) return new SlideTransitionAnimator (UIRectEdge.Left); @@ -100,7 +98,7 @@ public IUIViewControllerAnimatedTransitioning GetAnimationControllerForTransitio [Export ("tabBarController:interactionControllerForAnimationController:")] public IUIViewControllerInteractiveTransitioning GetInteractionControllerForAnimationController (UITabBarController tabBarController, IUIViewControllerAnimatedTransitioning animationController) { - UIViewController[] viewControllers = tabBarController.ViewControllers; + UIViewController [] viewControllers = tabBarController.ViewControllers; if (PanGestureRecognizer.State == UIGestureRecognizerState.Began || PanGestureRecognizer.State == UIGestureRecognizerState.Changed) return new SlideTransitionInteractionController (PanGestureRecognizer); @@ -108,4 +106,4 @@ public IUIViewControllerInteractiveTransitioning GetInteractionControllerForAnim return null; } } -} \ No newline at end of file +} diff --git a/CustomTransitions/CustomTransitions/Slide/SlideTransitionInteractionController.cs b/CustomTransitions/CustomTransitions/Slide/SlideTransitionInteractionController.cs index ca1f76171..ea070c8d4 100644 --- a/CustomTransitions/CustomTransitions/Slide/SlideTransitionInteractionController.cs +++ b/CustomTransitions/CustomTransitions/Slide/SlideTransitionInteractionController.cs @@ -1,10 +1,10 @@ -using System; +using System; using CoreGraphics; using UIKit; namespace CustomTransitions { - public class SlideTransitionInteractionController : UIPercentDrivenInteractiveTransition { + public class SlideTransitionInteractionController : UIPercentDrivenInteractiveTransition { readonly UIPanGestureRecognizer gestureRecognizer; @@ -22,7 +22,7 @@ public override void StartInteractiveTransition (IUIViewControllerContextTransit { TransitionContext = transitionContext; initialTranslationInContainerView = gestureRecognizer.TranslationInView (transitionContext.ContainerView); - base.StartInteractiveTransition(transitionContext); + base.StartInteractiveTransition (transitionContext); } nfloat PercentForGesture (UIPanGestureRecognizer gesture) @@ -42,24 +42,24 @@ nfloat PercentForGesture (UIPanGestureRecognizer gesture) } void GestureRecognizeDidUpdate (UIPanGestureRecognizer sender) - { + { switch (sender.State) { - case UIGestureRecognizerState.Changed: - if (PercentForGesture(sender) < 0f) - CancelInteractiveTransition (); - else - UpdateInteractiveTransition (PercentForGesture (sender)); - break; - case UIGestureRecognizerState.Ended: - if (PercentForGesture(gestureRecognizer) >= .4f) { - FinishInteractiveTransition (); - } else { - CancelInteractiveTransition (); - } - break; - default: + case UIGestureRecognizerState.Changed: + if (PercentForGesture (sender) < 0f) + CancelInteractiveTransition (); + else + UpdateInteractiveTransition (PercentForGesture (sender)); + break; + case UIGestureRecognizerState.Ended: + if (PercentForGesture (gestureRecognizer) >= .4f) { + FinishInteractiveTransition (); + } else { CancelInteractiveTransition (); - break; + } + break; + default: + CancelInteractiveTransition (); + break; } } } diff --git a/CustomTransitions/CustomTransitions/Swipe/SwipeFirstViewController.cs b/CustomTransitions/CustomTransitions/Swipe/SwipeFirstViewController.cs index d98285a65..18e0bd2b3 100644 --- a/CustomTransitions/CustomTransitions/Swipe/SwipeFirstViewController.cs +++ b/CustomTransitions/CustomTransitions/Swipe/SwipeFirstViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; @@ -15,7 +15,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); var interactiveTransitionRecognizer = new UIScreenEdgePanGestureRecognizer (); - interactiveTransitionRecognizer.AddTarget (() => InteractiveTransitionRecognizerAction(interactiveTransitionRecognizer)); + interactiveTransitionRecognizer.AddTarget (() => InteractiveTransitionRecognizerAction (interactiveTransitionRecognizer)); interactiveTransitionRecognizer.Edges = UIRectEdge.Right; View.AddGestureRecognizer (interactiveTransitionRecognizer); } diff --git a/CustomTransitions/CustomTransitions/Swipe/SwipeSecondViewController.cs b/CustomTransitions/CustomTransitions/Swipe/SwipeSecondViewController.cs index 24d55e038..3f037aee6 100644 --- a/CustomTransitions/CustomTransitions/Swipe/SwipeSecondViewController.cs +++ b/CustomTransitions/CustomTransitions/Swipe/SwipeSecondViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; @@ -29,10 +29,10 @@ public override void PrepareForSegue (UIStoryboardSegue segue, Foundation.NSObje { if (segue.Identifier == "BackToFirstViewController") { if (TransitioningDelegate is SwipeTransitionDelegate) { - var transitionDelegate = (SwipeTransitionDelegate)TransitioningDelegate; + var transitionDelegate = (SwipeTransitionDelegate) TransitioningDelegate; if (sender is UIScreenEdgePanGestureRecognizer) - transitionDelegate.GestureRecognizer = (UIScreenEdgePanGestureRecognizer)sender; + transitionDelegate.GestureRecognizer = (UIScreenEdgePanGestureRecognizer) sender; else transitionDelegate.GestureRecognizer = null; diff --git a/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionAnimator.cs b/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionAnimator.cs index 7c4185783..0c6eeae7f 100644 --- a/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionAnimator.cs +++ b/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionAnimator.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; using CoreGraphics; namespace CustomTransitions { @@ -17,7 +17,7 @@ public override double TransitionDuration (IUIViewControllerContextTransitioning } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext) - { + { var fromViewController = transitionContext.GetViewControllerForKey (UITransitionContext.FromViewControllerKey); var toViewController = transitionContext.GetViewControllerForKey (UITransitionContext.ToViewControllerKey); @@ -33,22 +33,22 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr var offset = new CGVector (0f, 0f); switch (targetEdge) { - case UIRectEdge.Top: - offset = new CGVector (0f, 1f); - break; - case UIRectEdge.Bottom: - offset = new CGVector (0f, -1f); - break; - case UIRectEdge.Left: - offset = new CGVector (1f, 0f); - break; - case UIRectEdge.Right: - offset = new CGVector (-1, 0); - break; - default: - offset = new CGVector (0f, 0f); - // TODO: error - break; + case UIRectEdge.Top: + offset = new CGVector (0f, 1f); + break; + case UIRectEdge.Bottom: + offset = new CGVector (0f, -1f); + break; + case UIRectEdge.Left: + offset = new CGVector (1f, 0f); + break; + case UIRectEdge.Right: + offset = new CGVector (-1, 0); + break; + default: + offset = new CGVector (0f, 0f); + // TODO: error + break; } if (isPresenting) { @@ -67,7 +67,7 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr var duration = TransitionDuration (transitionContext); - UIView.Animate(duration, 0, UIViewAnimationOptions.TransitionNone, () => { + UIView.Animate (duration, 0, UIViewAnimationOptions.TransitionNone, () => { toView.Frame = isPresenting ? toFrame : new CGRect (fromFrame.X + (fromFrame.Size.Width * offset.dx), fromFrame.Y + (fromFrame.Size.Height * offset.dy), fromFrame.Size.Width, fromFrame.Size.Height); }, () => { diff --git a/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionDelegate.cs b/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionDelegate.cs index 2aa595e82..135650ecd 100644 --- a/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionDelegate.cs +++ b/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionDelegate.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; using Foundation; namespace CustomTransitions { @@ -38,4 +38,4 @@ public IUIViewControllerInteractiveTransitioning GetInteractionControllerForDism return null; } } -} \ No newline at end of file +} diff --git a/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionInteractionController.cs b/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionInteractionController.cs index 13224ba54..25941829a 100644 --- a/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionInteractionController.cs +++ b/CustomTransitions/CustomTransitions/Swipe/SwipeTransitionInteractionController.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; using System; namespace CustomTransitions { @@ -8,7 +8,7 @@ public class SwipeTransitionInteractionController : UIPercentDrivenInteractiveTr UIScreenEdgePanGestureRecognizer GestureRecognizer { get; set; } - UIRectEdge Edge { get ; set; } + UIRectEdge Edge { get; set; } public SwipeTransitionInteractionController (UIScreenEdgePanGestureRecognizer gestureRecognizer, UIRectEdge edge) { @@ -58,18 +58,18 @@ nfloat PercentForGesture (UIScreenEdgePanGestureRecognizer gesture) void GestureRecognizeDidUpdate (UIScreenEdgePanGestureRecognizer sender) { switch (sender.State) { - case UIGestureRecognizerState.Changed: - UpdateInteractiveTransition (PercentForGesture (sender)); - break; - case UIGestureRecognizerState.Ended: - if (PercentForGesture (sender) >= 0.5) - FinishInteractiveTransition (); - else - CancelInteractiveTransition (); - break; - default: + case UIGestureRecognizerState.Changed: + UpdateInteractiveTransition (PercentForGesture (sender)); + break; + case UIGestureRecognizerState.Ended: + if (PercentForGesture (sender) >= 0.5) + FinishInteractiveTransition (); + else CancelInteractiveTransition (); - break; + break; + default: + CancelInteractiveTransition (); + break; } } } diff --git a/Data/AppDelegate.cs b/Data/AppDelegate.cs index 57afe4fd9..4d5badc04 100644 --- a/Data/AppDelegate.cs +++ b/Data/AppDelegate.cs @@ -4,11 +4,9 @@ using UIKit; using Foundation; -namespace Xamarin -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace Xamarin { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected UINavigationController navController; protected Screens.NavTable.HomeNavController navTable; diff --git a/Data/Application.cs b/Data/Application.cs index 98275ea49..14494b735 100644 --- a/Data/Application.cs +++ b/Data/Application.cs @@ -1,16 +1,13 @@ using System; using UIKit; -namespace Xamarin -{ - public class Application - { - public static void Main (string[] args) +namespace Xamarin { + public class Application { + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); - } - catch (Exception e) { + } catch (Exception e) { Console.WriteLine (e.ToString ()); } } diff --git a/Data/Code/NavItem.cs b/Data/Code/NavItem.cs index 3ec717e89..2fdae0dcd 100644 --- a/Data/Code/NavItem.cs +++ b/Data/Code/NavItem.cs @@ -1,15 +1,12 @@ using System; using UIKit; -namespace Xamarin.Code -{ - public class NavItem - { +namespace Xamarin.Code { + public class NavItem { /// /// The name of the nav item, shows up as the label /// - public string Name - { + public string Name { get { return name; } set { name = value; } } @@ -21,8 +18,7 @@ public string Name /// otherwise just set the Type property and it will lazy-instantiate when the /// nav item is clicked on. /// - public UIViewController Controller - { + public UIViewController Controller { get { return controller; } set { controller = value; } } @@ -31,8 +27,7 @@ public UIViewController Controller /// /// Path to the image to show in the nav item /// - public string ImagePath - { + public string ImagePath { get { return imagePath; } set { imagePath = value; } } @@ -43,8 +38,7 @@ public string ImagePath /// property empty to lazy-instantiate the ViewController when the nav item is /// clicked. /// - public Type ControllerType - { + public Type ControllerType { get { return controllerType; } set { controllerType = value; } } @@ -54,35 +48,32 @@ public Type ControllerType /// a list of the constructor args (if neccesary) for the controller. use this in /// conjunction with ControllerType if lazy-creating controllers. /// - public object[] ControllerConstructorArgs - { + public object [] ControllerConstructorArgs { get { return controllerConstructorArgs; } - set - { + set { controllerConstructorArgs = value; - controllerConstructorTypes = new Type[controllerConstructorArgs.Length]; + controllerConstructorTypes = new Type [controllerConstructorArgs.Length]; for (int i = 0; i < controllerConstructorArgs.Length; i++) { - controllerConstructorTypes[i] = controllerConstructorArgs[i].GetType (); + controllerConstructorTypes [i] = controllerConstructorArgs [i].GetType (); } } } - protected object[] controllerConstructorArgs = new object[] {}; + protected object [] controllerConstructorArgs = new object [] { }; /// /// The types of constructor args. /// - public Type[] ControllerConstructorTypes - { + public Type [] ControllerConstructorTypes { get { return controllerConstructorTypes; } } - protected Type[] controllerConstructorTypes = Type.EmptyTypes; + protected Type [] controllerConstructorTypes = Type.EmptyTypes; public NavItem () { } - public NavItem (string name) : this() + public NavItem (string name) : this () { this.name = name; } @@ -97,7 +88,7 @@ public NavItem (string name, Type controllerType) : this (name) this.controllerType = controllerType; } - public NavItem (string name, Type controllerType, object[] controllerConstructorArgs) : this (name, controllerType) + public NavItem (string name, Type controllerType, object [] controllerConstructorArgs) : this (name, controllerType) { this.ControllerConstructorArgs = controllerConstructorArgs; } @@ -112,7 +103,7 @@ public NavItem (string name, string imagePath, Type controllerType) : this (name this.imagePath = imagePath; } - public NavItem (string name, string imagePath, Type controllerType, object[] controllerConstructorArgs) : this (name, controllerType, controllerConstructorArgs) + public NavItem (string name, string imagePath, Type controllerType, object [] controllerConstructorArgs) : this (name, controllerType, controllerConstructorArgs) { this.imagePath = imagePath; } diff --git a/Data/Code/NavItemGroup.cs b/Data/Code/NavItemGroup.cs index 31680a6da..291139e09 100644 --- a/Data/Code/NavItemGroup.cs +++ b/Data/Code/NavItemGroup.cs @@ -1,19 +1,16 @@ using System; using System.Collections.Generic; -namespace Xamarin.Code -{ +namespace Xamarin.Code { /// /// A group that contains table items /// - public class NavItemGroup - { + public class NavItemGroup { public string Name { get; set; } public string Footer { get; set; } - public List Items - { + public List Items { get { return items; } set { items = value; } } diff --git a/Data/Code/NavItemTableSource.cs b/Data/Code/NavItemTableSource.cs index 901a39731..4d168c6d9 100644 --- a/Data/Code/NavItemTableSource.cs +++ b/Data/Code/NavItemTableSource.cs @@ -4,14 +4,12 @@ using Foundation; using System.Reflection; -namespace Xamarin.Code -{ +namespace Xamarin.Code { /// /// Combined DataSource and Delegate for our UITableView /// - public class NavItemTableSource : UITableViewSource - { + public class NavItemTableSource : UITableViewSource { protected List navItems; string cellIdentifier = "NavTableCellView"; UINavigationController navigationController; @@ -35,7 +33,7 @@ public override nint NumberOfSections (UITableView tableView) /// public override nint RowsInSection (UITableView tableview, nint section) { - return navItems[(int)section].Items.Count; + return navItems [(int) section].Items.Count; } /// @@ -43,7 +41,7 @@ public override nint RowsInSection (UITableView tableview, nint section) /// public override string TitleForHeader (UITableView tableView, nint section) { - return navItems[(int)section].Name; + return navItems [(int) section].Name; } /// @@ -51,7 +49,7 @@ public override string TitleForHeader (UITableView tableView, nint section) /// public override string TitleForFooter (UITableView tableView, nint section) { - return navItems[(int)section].Footer; + return navItems [(int) section].Footer; } /// @@ -60,7 +58,7 @@ public override string TitleForFooter (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { // declare vars - NavItem navItem = navItems[indexPath.Section].Items[indexPath.Row]; + NavItem navItem = navItems [indexPath.Section].Items [indexPath.Row]; var cell = tableView.DequeueReusableCell (this.cellIdentifier); if (cell == null) { @@ -69,7 +67,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde } // set the cell properties - cell.TextLabel.Text = navItems[indexPath.Section].Items[indexPath.Row].Name; + cell.TextLabel.Text = navItems [indexPath.Section].Items [indexPath.Row].Name; cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; // return the cell @@ -82,7 +80,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { // get a reference to the nav item - NavItem navItem = navItems[indexPath.Section].Items[indexPath.Row]; + NavItem navItem = navItems [indexPath.Section].Items [indexPath.Row]; // if the nav item has a proper controller, push it on to the NavigationController // NOTE: we could also raise an event here, to loosely couple this, but isn't neccessary, @@ -91,9 +89,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) navigationController.PushViewController (navItem.Controller, true); // show the nav bar (we don't show it on the home page) navigationController.NavigationBarHidden = false; - } - else - { + } else { if (navItem.ControllerType != null) { // ConstructorInfo ctor = null; @@ -102,23 +98,20 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) if (navItem.ControllerConstructorArgs.Length > 0) { // look for the constructor ctor = navItem.ControllerType.GetConstructor (navItem.ControllerConstructorTypes); - } - else { + } else { // search for the default constructor ctor = navItem.ControllerType.GetConstructor (System.Type.EmptyTypes); } // if we found the constructor - if (ctor != null) - { + if (ctor != null) { // UIViewController instance = null; if (navItem.ControllerConstructorArgs.Length > 0) { // instance the view controller instance = ctor.Invoke (navItem.ControllerConstructorArgs) as UIViewController; - } - else { + } else { // instance the view controller instance = ctor.Invoke (null) as UIViewController; } @@ -129,13 +122,10 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) // push the view controller onto the stack navigationController.PushViewController (navItem.Controller, true); - } - else { + } else { Console.WriteLine ("instance of view controller not created"); } - } - else - { + } else { Console.WriteLine ("constructor not found"); } } diff --git a/Data/Code/SQLiteNet/SQLite.cs b/Data/Code/SQLiteNet/SQLite.cs index 1bcdc63f3..2dd429127 100644 --- a/Data/Code/SQLiteNet/SQLite.cs +++ b/Data/Code/SQLiteNet/SQLite.cs @@ -26,13 +26,11 @@ using System.Linq; using System.Linq.Expressions; -namespace SQLite -{ - public class SQLiteException : System.Exception - { +namespace SQLite { + public class SQLiteException : System.Exception { public SQLite3.Result Result { get; private set; } - protected SQLiteException (SQLite3.Result r,string message) : base(message) + protected SQLiteException (SQLite3.Result r, string message) : base (message) { Result = r; } @@ -46,8 +44,7 @@ public static SQLiteException New (SQLite3.Result r, string message) /// /// Represents an open connection to a SQLite database. /// - public class SQLiteConnection : IDisposable - { + public class SQLiteConnection : IDisposable { private bool _open; private TimeSpan _busyTimeout; private Dictionary _mappings = null; @@ -106,7 +103,7 @@ public TimeSpan BusyTimeout { set { _busyTimeout = value; if (Handle != IntPtr.Zero) { - SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds); + SQLite3.BusyTimeout (Handle, (int) _busyTimeout.TotalMilliseconds); } } } @@ -159,7 +156,7 @@ public TableMapping GetMapping (Type type) /// public int CreateTable () { - var ty = typeof(T); + var ty = typeof (T); if (_tables == null) { _tables = new Dictionary (); @@ -181,8 +178,7 @@ public int CreateTable () try { Execute (query); count = 1; - } - catch (SQLiteException) { + } catch (SQLiteException) { } if (count == 0) { @@ -199,8 +195,7 @@ public int CreateTable () return count; } - class TableInfo - { + class TableInfo { public int cid { get; set; } public string name { get; set; } @@ -253,7 +248,7 @@ void MigrateTable (TableMapping map) /// /// A /// - public SQLiteCommand CreateCommand (string cmdText, params object[] ps) + public SQLiteCommand CreateCommand (string cmdText, params object [] ps) { if (!_open) { throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database"); @@ -284,7 +279,7 @@ public SQLiteCommand CreateCommand (string cmdText, params object[] ps) /// /// The number of rows modified in the database as a result of this execution. /// - public int Execute (string query, params object[] args) + public int Execute (string query, params object [] args) { var cmd = CreateCommand (query, args); @@ -322,7 +317,7 @@ public int Execute (string query, params object[] args) /// /// An enumerable with one result for each row returned by the query. /// - public List Query (string query, params object[] args) where T : new() + public List Query (string query, params object [] args) where T : new() { var cmd = CreateCommand (query, args); return cmd.ExecuteQuery (); @@ -348,7 +343,7 @@ public int Execute (string query, params object[] args) /// /// An enumerable with one result for each row returned by the query. /// - public List Query (TableMapping map, string query, params object[] args) + public List Query (TableMapping map, string query, params object [] args) { var cmd = CreateCommand (query, args); return cmd.ExecuteQuery (map); @@ -380,7 +375,7 @@ public List Query (TableMapping map, string query, params object[] args) /// public T Get (object pk) where T : new() { - var map = GetMapping (typeof(T)); + var map = GetMapping (typeof (T)); string query = string.Format ("select * from \"{0}\" where \"{1}\" = ?", map.TableName, map.PK.Name); return Query (query, pk).First (); } @@ -520,7 +515,7 @@ public int Insert (object obj, string extra, Type objType) var map = GetMapping (objType); var cols = map.InsertColumns; - var vals = new object[cols.Length]; + var vals = new object [cols.Length]; for (var i = 0; i < vals.Length; i++) { vals [i] = cols [i].GetValue (obj); } @@ -570,14 +565,14 @@ public int Update (object obj, Type objType) } var cols = from p in map.Columns - where p != pk - select p; + where p != pk + select p; var vals = from c in cols - select c.GetValue (obj); + select c.GetValue (obj); var ps = new List (vals); ps.Add (pk.GetValue (obj)); var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols - select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); + select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); return Execute (q, ps.ToArray ()); } @@ -616,24 +611,19 @@ public void Close () } } - public class PrimaryKeyAttribute : Attribute - { + public class PrimaryKeyAttribute : Attribute { } - public class AutoIncrementAttribute : Attribute - { + public class AutoIncrementAttribute : Attribute { } - public class IndexedAttribute : Attribute - { + public class IndexedAttribute : Attribute { } - public class IgnoreAttribute : Attribute - { + public class IgnoreAttribute : Attribute { } - public class MaxLengthAttribute : Attribute - { + public class MaxLengthAttribute : Attribute { public int Value { get; private set; } public MaxLengthAttribute (int length) @@ -642,8 +632,7 @@ public MaxLengthAttribute (int length) } } - public class CollationAttribute: Attribute - { + public class CollationAttribute : Attribute { public string Value { get; private set; } public CollationAttribute (string collation) @@ -652,18 +641,17 @@ public CollationAttribute (string collation) } } - public class TableMapping - { + public class TableMapping { public Type MappedType { get; private set; } public string TableName { get; private set; } - public Column[] Columns { get; private set; } + public Column [] Columns { get; private set; } public Column PK { get; private set; } Column _autoPk = null; - Column[] _insertColumns = null; + Column [] _insertColumns = null; string _insertSql = null; public TableMapping (Type type) @@ -673,7 +661,7 @@ public TableMapping (Type type) var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); var cols = new List (); foreach (var p in props) { - var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0; + var ignore = p.GetCustomAttributes (typeof (IgnoreAttribute), true).Length > 0; if (p.CanWrite && !ignore) { cols.Add (new PropColumn (p)); } @@ -700,7 +688,7 @@ public void SetAutoIncPK (object obj, long id) } } - public Column[] InsertColumns { + public Column [] InsertColumns { get { if (_insertColumns == null) { _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray (); @@ -720,8 +708,8 @@ public string InsertSql (string extra) if (_insertSql == null) { var cols = InsertColumns; _insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", TableName, string.Join (",", (from c in cols - select "\"" + c.Name + "\"").ToArray ()), string.Join (",", (from c in cols - select "?").ToArray ()), extra); + select "\"" + c.Name + "\"").ToArray ()), string.Join (",", (from c in cols + select "?").ToArray ()), extra); } return _insertSql; } @@ -740,8 +728,7 @@ public PreparedSqlLiteInsertCommand GetInsertCommand (SQLiteConnection conn, str return _insertCommand; } - public abstract class Column - { + public abstract class Column { public string Name { get; protected set; } public Type ColumnType { get; protected set; } @@ -763,8 +750,7 @@ public abstract class Column public abstract object GetValue (object obj); } - public class PropColumn : Column - { + public class PropColumn : Column { PropertyInfo _prop; public PropColumn (PropertyInfo prop) @@ -772,7 +758,7 @@ public PropColumn (PropertyInfo prop) _prop = prop; Name = prop.Name; //If this type is Nullable then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the the actual type instead - ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; + ColumnType = Nullable.GetUnderlyingType (prop.PropertyType) ?? prop.PropertyType; Collation = Orm.Collation (prop); IsAutoInc = Orm.IsAutoInc (prop); IsPK = Orm.IsPK (prop); @@ -793,8 +779,7 @@ public override object GetValue (object obj) } } - public static class Orm - { + public static class Orm { public const int DefaultMaxStringLength = 140; public static string SqlDecl (TableMapping.Column p) @@ -820,20 +805,20 @@ public static string SqlDecl (TableMapping.Column p) public static string SqlType (TableMapping.Column p) { var clrType = p.ColumnType; - if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) { + if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32)) { return "integer"; - } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) { + } else if (clrType == typeof (UInt32) || clrType == typeof (Int64)) { return "bigint"; - } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) { + } else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) { return "float"; - } else if (clrType == typeof(String)) { + } else if (clrType == typeof (String)) { int len = p.MaxStringLength; return "varchar(" + len + ")"; - } else if (clrType == typeof(DateTime)) { + } else if (clrType == typeof (DateTime)) { return "datetime"; } else if (clrType.IsEnum) { return "integer"; - } else if (clrType == typeof(byte[])) { + } else if (clrType == typeof (byte [])) { return "blob"; } else { throw new NotSupportedException ("Don't know about " + clrType); @@ -842,15 +827,15 @@ public static string SqlType (TableMapping.Column p) public static bool IsPK (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true); + var attrs = p.GetCustomAttributes (typeof (PrimaryKeyAttribute), true); return attrs.Length > 0; } public static string Collation (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(CollationAttribute), true); + var attrs = p.GetCustomAttributes (typeof (CollationAttribute), true); if (attrs.Length > 0) { - return ((CollationAttribute)attrs [0]).Value; + return ((CollationAttribute) attrs [0]).Value; } else { return string.Empty; } @@ -858,29 +843,28 @@ public static string Collation (MemberInfo p) public static bool IsAutoInc (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true); + var attrs = p.GetCustomAttributes (typeof (AutoIncrementAttribute), true); return attrs.Length > 0; } public static bool IsIndexed (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(IndexedAttribute), true); + var attrs = p.GetCustomAttributes (typeof (IndexedAttribute), true); return attrs.Length > 0; } public static int MaxStringLength (PropertyInfo p) { - var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true); + var attrs = p.GetCustomAttributes (typeof (MaxLengthAttribute), true); if (attrs.Length > 0) { - return ((MaxLengthAttribute)attrs [0]).Value; + return ((MaxLengthAttribute) attrs [0]).Value; } else { return DefaultMaxStringLength; } } } - public class SQLiteCommand - { + public class SQLiteCommand { SQLiteConnection _conn; private List _bindings; @@ -916,7 +900,7 @@ public int ExecuteNonQuery () public List ExecuteQuery () where T : new() { - return ExecuteQuery (_conn.GetMapping (typeof(T))); + return ExecuteQuery (_conn.GetMapping (typeof (T))); } public List ExecuteQuery (TableMapping map) @@ -929,7 +913,7 @@ public List ExecuteQuery (TableMapping map) var stmt = Prepare (); - var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)]; + var cols = new TableMapping.Column [SQLite3.ColumnCount (stmt)]; for (int i = 0; i < cols.Length; i++) { var name = Marshal.PtrToStringUni (SQLite3.ColumnName16 (stmt, i)); @@ -945,7 +929,7 @@ public List ExecuteQuery (TableMapping map) var val = ReadCol (stmt, i, colType, cols [i].ColumnType); cols [i].SetValue (obj, val); } - r.Add ((T)obj); + r.Add ((T) obj); } Finalize (stmt); @@ -958,12 +942,12 @@ public T ExecuteScalar () Console.WriteLine ("Executing Query: " + this); } - T val = default(T); + T val = default (T); var stmt = Prepare (); if (SQLite3.Step (stmt) == SQLite3.Result.Row) { var colType = SQLite3.ColumnType (stmt, 0); - val = (T)ReadCol (stmt, 0, colType, typeof(T)); + val = (T) ReadCol (stmt, 0, colType, typeof (T)); } Finalize (stmt); @@ -985,7 +969,7 @@ public void Bind (object val) public override string ToString () { - var parts = new string[1 + _bindings.Count]; + var parts = new string [1 + _bindings.Count]; parts [0] = CommandText; var i = 1; foreach (var b in _bindings) { @@ -1030,31 +1014,30 @@ internal static void BindParameter (IntPtr stmt, int index, object value) SQLite3.BindNull (stmt, index); } else { if (value is Int32) { - SQLite3.BindInt (stmt, index, (int)value); + SQLite3.BindInt (stmt, index, (int) value); } else if (value is String) { - SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer); + SQLite3.BindText (stmt, index, (string) value, -1, NegativePointer); } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); } else if (value is Boolean) { - SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0); + SQLite3.BindInt (stmt, index, (bool) value ? 1 : 0); } else if (value is UInt32 || value is Int64) { SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value)); } else if (value is Single || value is Double || value is Decimal) { SQLite3.BindDouble (stmt, index, Convert.ToDouble (value)); } else if (value is DateTime) { - SQLite3.BindText (stmt, index, ((DateTime)value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); + SQLite3.BindText (stmt, index, ((DateTime) value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); } else if (value.GetType ().IsEnum) { SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is byte[]) { - SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer); + } else if (value is byte []) { + SQLite3.BindBlob (stmt, index, (byte []) value, ((byte []) value).Length, NegativePointer); } else { throw new NotSupportedException ("Cannot store type: " + value.GetType ()); } } } - class Binding - { + class Binding { public string Name { get; set; } public object Value { get; set; } @@ -1067,36 +1050,36 @@ object ReadCol (IntPtr stmt, int index, SQLite3.ColType type, Type clrType) if (type == SQLite3.ColType.Null) { return null; } else { - if (clrType == typeof(String)) { + if (clrType == typeof (String)) { return SQLite3.ColumnString (stmt, index); - } else if (clrType == typeof(Int32)) { - return (int)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Boolean)) { + } else if (clrType == typeof (Int32)) { + return (int) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (Boolean)) { return SQLite3.ColumnInt (stmt, index) == 1; - } else if (clrType == typeof(double)) { + } else if (clrType == typeof (double)) { return SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(float)) { - return (float)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(DateTime)) { + } else if (clrType == typeof (float)) { + return (float) SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof (DateTime)) { var text = SQLite3.ColumnString (stmt, index); return DateTime.Parse (text); } else if (clrType.IsEnum) { return SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int64)) { + } else if (clrType == typeof (Int64)) { return SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(UInt32)) { - return (uint)SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(decimal)) { - return (decimal)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(Byte)) { - return (byte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(UInt16)) { - return (ushort)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int16)) { - return (short)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(sbyte)) { - return (sbyte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(byte[])) { + } else if (clrType == typeof (UInt32)) { + return (uint) SQLite3.ColumnInt64 (stmt, index); + } else if (clrType == typeof (decimal)) { + return (decimal) SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof (Byte)) { + return (byte) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (UInt16)) { + return (ushort) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (Int16)) { + return (short) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (sbyte)) { + return (sbyte) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (byte [])) { return SQLite3.ColumnByteArray (stmt, index); } else { throw new NotSupportedException ("Don't know how to read " + clrType); @@ -1108,8 +1091,7 @@ object ReadCol (IntPtr stmt, int index, SQLite3.ColType type, Type clrType) /// /// Since the insert never changed, we only need to prepare once. /// - public class PreparedSqlLiteInsertCommand : IDisposable - { + public class PreparedSqlLiteInsertCommand : IDisposable { public bool Initialized { get; set; } protected SQLiteConnection Connection { get; set; } @@ -1123,7 +1105,7 @@ internal PreparedSqlLiteInsertCommand (SQLiteConnection conn) Connection = conn; } - public int ExecuteNonQuery (object[] source) + public int ExecuteNonQuery (object [] source) { if (Connection.Trace) { Console.WriteLine ("Executing: " + CommandText); @@ -1188,8 +1170,7 @@ private void Dispose (bool disposing) } } - public class TableQuery : IEnumerable where T : new() - { + public class TableQuery : IEnumerable where T : new() { public SQLiteConnection Connection { get; private set; } public TableMapping Table { get; private set; } @@ -1199,8 +1180,7 @@ private void Dispose (bool disposing) int? _limit; int? _offset; - class Ordering - { + class Ordering { public string ColumnName { get; set; } public bool Ascending { get; set; } @@ -1215,7 +1195,7 @@ class Ordering public TableQuery (SQLiteConnection conn) { Connection = conn; - Table = Connection.GetMapping (typeof(T)); + Table = Connection.GetMapping (typeof (T)); } public TableQuery Clone () @@ -1233,7 +1213,7 @@ public TableQuery Clone () public TableQuery Where (Expression> predExpr) { if (predExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)predExpr; + var lambda = (LambdaExpression) predExpr; var pred = lambda.Body; var q = Clone (); q.AddWhere (pred); @@ -1270,7 +1250,7 @@ public TableQuery OrderByDescending (Expression> orderExpr) private TableQuery AddOrderBy (Expression> orderExpr, bool asc) { if (orderExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)orderExpr; + var lambda = (LambdaExpression) orderExpr; var mem = lambda.Body as MemberExpression; if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { var q = Clone (); @@ -1323,8 +1303,7 @@ private SQLiteCommand GenerateCommand (string selectionList) return Connection.CreateCommand (cmdText, args.ToArray ()); } - class CompileResult - { + class CompileResult { public string CommandText { get; set; } public object Value { get; set; } @@ -1335,7 +1314,7 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) if (expr == null) { throw new NotSupportedException ("Expression is NULL"); } else if (expr is BinaryExpression) { - var bin = (BinaryExpression)expr; + var bin = (BinaryExpression) expr; var leftr = CompileExpr (bin.Left, queryArgs); var rightr = CompileExpr (bin.Right, queryArgs); @@ -1343,16 +1322,16 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") string text; if (leftr.CommandText == "?" && leftr.Value == null) - text = CompileNullBinaryExpression(bin, rightr); + text = CompileNullBinaryExpression (bin, rightr); else if (rightr.CommandText == "?" && rightr.Value == null) - text = CompileNullBinaryExpression(bin, leftr); + text = CompileNullBinaryExpression (bin, leftr); else - text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")"; + text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")"; return new CompileResult { CommandText = text }; } else if (expr.NodeType == ExpressionType.Call) { - var call = (MethodCallExpression)expr; - var args = new CompileResult[call.Arguments.Count]; + var call = (MethodCallExpression) expr; + var args = new CompileResult [call.Arguments.Count]; for (var i = 0; i < args.Length; i++) { args [i] = CompileExpr (call.Arguments [i], queryArgs); @@ -1370,14 +1349,14 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) return new CompileResult { CommandText = sqlCall }; } else if (expr.NodeType == ExpressionType.Constant) { - var c = (ConstantExpression)expr; + var c = (ConstantExpression) expr; queryArgs.Add (c.Value); return new CompileResult { CommandText = "?", Value = c.Value }; } else if (expr.NodeType == ExpressionType.Convert) { - var u = (UnaryExpression)expr; + var u = (UnaryExpression) expr; var ty = u.Type; var valr = CompileExpr (u.Operand, queryArgs); return new CompileResult { @@ -1385,7 +1364,7 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) Value = valr.Value != null ? Convert.ChangeType (valr.Value, ty) : null }; } else if (expr.NodeType == ExpressionType.MemberAccess) { - var mem = (MemberExpression)expr; + var mem = (MemberExpression) expr; if (mem.Expression.NodeType == ExpressionType.Parameter) { // @@ -1411,10 +1390,10 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) object val = null; if (mem.Member.MemberType == MemberTypes.Property) { - var m = (PropertyInfo)mem.Member; + var m = (PropertyInfo) mem.Member; val = m.GetValue (obj, null); } else if (mem.Member.MemberType == MemberTypes.Field) { - var m = (FieldInfo)mem.Member; + var m = (FieldInfo) mem.Member; val = m.GetValue (obj); } else { throw new NotSupportedException ("MemberExpr: " + mem.Member.MemberType.ToString ()); @@ -1424,22 +1403,21 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) // Work special magic for enumerables // if (val != null && val is System.Collections.IEnumerable && !(val is string)) { - var sb = new System.Text.StringBuilder(); - sb.Append("("); + var sb = new System.Text.StringBuilder (); + sb.Append ("("); var head = ""; - foreach (var a in (System.Collections.IEnumerable)val) { - queryArgs.Add(a); - sb.Append(head); - sb.Append("?"); + foreach (var a in (System.Collections.IEnumerable) val) { + queryArgs.Add (a); + sb.Append (head); + sb.Append ("?"); head = ","; } - sb.Append(")"); + sb.Append (")"); return new CompileResult { - CommandText = sb.ToString(), + CommandText = sb.ToString (), Value = val }; - } - else { + } else { queryArgs.Add (val); return new CompileResult { CommandText = "?", @@ -1455,21 +1433,22 @@ private CompileResult CompileExpr (Expression expr, List queryArgs) /// Compiles a BinaryExpression where one of the parameters is null. /// /// The non-null parameter - private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) + private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter) { if (expression.NodeType == ExpressionType.Equal) return "(" + parameter.CommandText + " is ?)"; else if (expression.NodeType == ExpressionType.NotEqual) return "(" + parameter.CommandText + " is not ?)"; else - throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString()); + throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ()); } string GetSqlName (Expression expr) { var n = expr.NodeType; if (n == ExpressionType.GreaterThan) - return ">"; else if (n == ExpressionType.GreaterThanOrEqual) { + return ">"; + else if (n == ExpressionType.GreaterThanOrEqual) { return ">="; } else if (n == ExpressionType.LessThan) { return "<"; @@ -1494,7 +1473,7 @@ string GetSqlName (Expression expr) public int Count () { - return GenerateCommand("count(*)").ExecuteScalar (); + return GenerateCommand ("count(*)").ExecuteScalar (); } public IEnumerator GetEnumerator () @@ -1508,10 +1487,8 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () } } - public static class SQLite3 - { - public enum Result : int - { + public static class SQLite3 { + public enum Result : int { OK = 0, Error = 1, Internal = 2, @@ -1531,29 +1508,28 @@ public enum Result : int Done = 101 } - public enum ConfigOption : int - { + public enum ConfigOption : int { SingleThread = 1, MultiThread = 2, Serialized = 3 } - [DllImport("sqlite3", EntryPoint = "sqlite3_open")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_open")] public static extern Result Open (string filename, out IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_close")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_close")] public static extern Result Close (IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_config")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_config")] public static extern Result Config (ConfigOption option); - [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_busy_timeout")] public static extern Result BusyTimeout (IntPtr db, int milliseconds); - [DllImport("sqlite3", EntryPoint = "sqlite3_changes")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_changes")] public static extern int Changes (IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_prepare_v2")] public static extern Result Prepare2 (IntPtr db, string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); public static IntPtr Prepare2 (IntPtr db, string query) @@ -1566,19 +1542,19 @@ public static IntPtr Prepare2 (IntPtr db, string query) return stmt; } - [DllImport("sqlite3", EntryPoint = "sqlite3_step")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_step")] public static extern Result Step (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_reset")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_reset")] public static extern Result Reset (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_finalize")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_finalize")] public static extern Result Finalize (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_last_insert_rowid")] public static extern long LastInsertRowid (IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_errmsg16")] public static extern IntPtr Errmsg (IntPtr db); public static string GetErrmsg (IntPtr db) @@ -1586,58 +1562,58 @@ public static string GetErrmsg (IntPtr db) return Marshal.PtrToStringUni (Errmsg (db)); } - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_parameter_index")] public static extern int BindParameterIndex (IntPtr stmt, string name); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_null")] public static extern int BindNull (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_int")] public static extern int BindInt (IntPtr stmt, int index, int val); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_int64")] public static extern int BindInt64 (IntPtr stmt, int index, long val); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_double")] public static extern int BindDouble (IntPtr stmt, int index, double val); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_text")] public static extern int BindText (IntPtr stmt, int index, string val, int n, IntPtr free); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob")] - public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free); + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_blob")] + public static extern int BindBlob (IntPtr stmt, int index, byte [] val, int n, IntPtr free); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_count")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_count")] public static extern int ColumnCount (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_name")] public static extern IntPtr ColumnName (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_name16")] public static extern IntPtr ColumnName16 (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_type")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_type")] public static extern ColType ColumnType (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_int")] public static extern int ColumnInt (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_int64")] public static extern long ColumnInt64 (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_double")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_double")] public static extern double ColumnDouble (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_text")] public static extern IntPtr ColumnText (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_text16")] public static extern IntPtr ColumnText16 (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_blob")] public static extern IntPtr ColumnBlob (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_bytes")] public static extern int ColumnBytes (IntPtr stmt, int index); public static string ColumnString (IntPtr stmt, int index) @@ -1645,17 +1621,16 @@ public static string ColumnString (IntPtr stmt, int index) return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index)); } - public static byte[] ColumnByteArray (IntPtr stmt, int index) + public static byte [] ColumnByteArray (IntPtr stmt, int index) { int length = ColumnBytes (stmt, index); - byte[] result = new byte[length]; + byte [] result = new byte [length]; if (length > 0) Marshal.Copy (ColumnBlob (stmt, index), result, 0, length); return result; } - public enum ColType : int - { + public enum ColType : int { Integer = 1, Float = 2, Text = 3, diff --git a/Data/Screens/ADONET/BasicOperations.cs b/Data/Screens/ADONET/BasicOperations.cs index 5ca0c9db3..2db74ee05 100644 --- a/Data/Screens/ADONET/BasicOperations.cs +++ b/Data/Screens/ADONET/BasicOperations.cs @@ -8,11 +8,9 @@ using System.IO; using Mono.Data.Sqlite; -namespace Xamarin.Screens.ADONET -{ - public partial class BasicOperations : UITableViewController - { - protected List people = new List(); +namespace Xamarin.Screens.ADONET { + public partial class BasicOperations : UITableViewController { + protected List people = new List (); protected TableSource tableSource; #region Constructors @@ -20,7 +18,7 @@ public partial class BasicOperations : UITableViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code public BasicOperations (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] + [Export ("initWithCoder:")] public BasicOperations (NSCoder coder) : base (coder) { Initialize (); } public BasicOperations () : base ("DataSample", null) { Initialize (); } @@ -29,18 +27,17 @@ protected void Initialize () this.Title = "ADO.NET"; // performance timing - System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); + System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch (); stopwatch.Start (); // create a connection to the database, if the db doesn't exist, it'll get created - var connection = GetConnection ("db_adonet.db3"); + var connection = GetConnection ("db_adonet.db3"); // performance timing - Console.WriteLine("database creation: " + stopwatch.ElapsedMilliseconds.ToString()); + Console.WriteLine ("database creation: " + stopwatch.ElapsedMilliseconds.ToString ()); // create a command - using (var cmd = connection.CreateCommand ()) - { + using (var cmd = connection.CreateCommand ()) { // open the connection connection.Open (); // create a select statement @@ -48,12 +45,12 @@ protected void Initialize () using (var reader = cmd.ExecuteReader ()) { // loop through each record and add the name to our collection while (reader.Read ()) { - people.Add (reader[1] + " " + reader[2]); + people.Add (reader [1] + " " + reader [2]); } } // performance timing - Console.WriteLine("database query: " + stopwatch.ElapsedMilliseconds.ToString ()); + Console.WriteLine ("database query: " + stopwatch.ElapsedMilliseconds.ToString ()); // close the connection connection.Close (); @@ -71,8 +68,8 @@ protected void Initialize () // Creates a connection to a database. if the database doesn't exist, it // creates it. - protected SqliteConnection GetConnection(string dbName) - { + protected SqliteConnection GetConnection (string dbName) + { // declare vars bool needToCreate; @@ -91,22 +88,22 @@ protected SqliteConnection GetConnection(string dbName) SqliteConnection.CreateFile (db); // create a new connection object, from the path to the database - var conn = new SqliteConnection("Data Source=" + db); + var conn = new SqliteConnection ("Data Source=" + db); // now that we have a connnection to the database, let's actually create our table structure - if (needToCreate) - CreateDBSchema(conn); + if (needToCreate) + CreateDBSchema (conn); - return conn; - } + return conn; + } /// /// Creates a People table and inserts some data /// - protected void CreateDBSchema(SqliteConnection connection) + protected void CreateDBSchema (SqliteConnection connection) { // create a an array of commands - var commands = new[] + var commands = new [] { "CREATE TABLE People (PersonID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName ntext, LastName ntext)", "INSERT INTO People (FirstName, LastName) VALUES ('Peter', 'Gabriel')", @@ -117,7 +114,7 @@ protected void CreateDBSchema(SqliteConnection connection) // execute each command, using standard ADO.NET calls foreach (var cmd in commands) { - using (var c = connection.CreateCommand()) { + using (var c = connection.CreateCommand ()) { c.CommandText = cmd; c.CommandType = CommandType.Text; connection.Open (); @@ -131,11 +128,10 @@ protected void CreateDBSchema(SqliteConnection connection) /// /// A simple data source for our table /// - protected class TableSource : UITableViewSource - { + protected class TableSource : UITableViewSource { List items; - public TableSource(List items) : base() { this.items = items; } + public TableSource (List items) : base () { this.items = items; } public override nint NumberOfSections (UITableView tableView) { return 1; } @@ -144,10 +140,10 @@ protected class TableSource : UITableViewSource public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell; - cell = tableView.DequeueReusableCell("item"); - if(cell == null) - cell = new UITableViewCell(UITableViewCellStyle.Default, "item"); - cell.TextLabel.Text = this.items[indexPath.Row]; + cell = tableView.DequeueReusableCell ("item"); + if (cell == null) + cell = new UITableViewCell (UITableViewCellStyle.Default, "item"); + cell.TextLabel.Text = this.items [indexPath.Row]; return cell; } diff --git a/Data/Screens/NavTable/HomeTableViewController.cs b/Data/Screens/NavTable/HomeTableViewController.cs index b5eeb6717..d0e5d603d 100644 --- a/Data/Screens/NavTable/HomeTableViewController.cs +++ b/Data/Screens/NavTable/HomeTableViewController.cs @@ -5,15 +5,13 @@ using System.Collections.Generic; using Xamarin.Code; -namespace Xamarin.Screens.NavTable -{ - public class HomeNavController : UITableViewController - { +namespace Xamarin.Screens.NavTable { + public class HomeNavController : UITableViewController { // declare vars - protected List navItems = new List(); + protected List navItems = new List (); protected NavItemTableSource tableSource; - public HomeNavController () : base(UITableViewStyle.Grouped) + public HomeNavController () : base (UITableViewStyle.Grouped) { } @@ -39,15 +37,15 @@ public override void ViewDidLoad () // create the navigation items navGroup = new NavItemGroup ("ADO.NET"); navItems.Add (navGroup); - navGroup.Items.Add (new NavItem ("Basic ADO.NET", "", typeof(ADONET.BasicOperations))); + navGroup.Items.Add (new NavItem ("Basic ADO.NET", "", typeof (ADONET.BasicOperations))); navGroup = new NavItemGroup ("SQLite-Net"); navItems.Add (navGroup); - navGroup.Items.Add (new NavItem ("Basic SQLite-Net", "", typeof(SQLiteNet.BasicOperations))); + navGroup.Items.Add (new NavItem ("Basic SQLite-Net", "", typeof (SQLiteNet.BasicOperations))); navGroup = new NavItemGroup ("Vici CoolStorage"); navItems.Add (navGroup); - navGroup.Items.Add (new NavItem ("Basic Vici CoolStorage", "", typeof(ViciCoolStorage.BasicOperations))); + navGroup.Items.Add (new NavItem ("Basic Vici CoolStorage", "", typeof (ViciCoolStorage.BasicOperations))); // create a table source from our nav items tableSource = new NavItemTableSource (NavigationController, navItems); diff --git a/Data/Screens/SQLiteNet/BasicOperations.cs b/Data/Screens/SQLiteNet/BasicOperations.cs index 1a1e70d07..3a680a1d9 100644 --- a/Data/Screens/SQLiteNet/BasicOperations.cs +++ b/Data/Screens/SQLiteNet/BasicOperations.cs @@ -7,19 +7,17 @@ using System.IO; using SQLite; -namespace Xamarin.Screens.SQLiteNet -{ - public partial class BasicOperations : UITableViewController - { +namespace Xamarin.Screens.SQLiteNet { + public partial class BasicOperations : UITableViewController { protected List people = new List (); protected TableSource tableSource; #region Constructors - public BasicOperations (IntPtr handle) : base(handle) { Initialize (); } - [Export("initWithCoder:")] - public BasicOperations (NSCoder coder) : base(coder) { Initialize (); } - public BasicOperations () : base("DataSample", null) { Initialize (); } + public BasicOperations (IntPtr handle) : base (handle) { Initialize (); } + [Export ("initWithCoder:")] + public BasicOperations (NSCoder coder) : base (coder) { Initialize (); } + public BasicOperations () : base ("DataSample", null) { Initialize (); } protected void Initialize () { @@ -74,13 +72,12 @@ protected void CheckAndCreateDatabase (string dbName) { // create a connection object. if the database doesn't exist, it will create // a blank database - using(SQLiteConnection db = new SQLiteConnection (GetDBPath (dbName))) - { + using (SQLiteConnection db = new SQLiteConnection (GetDBPath (dbName))) { // create the tables db.CreateTable (); // skip inserting data if it already exists - if(db.Table().Count() > 0) + if (db.Table ().Count () > 0) return; // declare vars @@ -107,11 +104,10 @@ protected void CheckAndCreateDatabase (string dbName) } // A simple data source for our table - protected class TableSource : UITableViewSource - { + protected class TableSource : UITableViewSource { List items; - public TableSource (List items) : base() { this.items = items; } + public TableSource (List items) : base () { this.items = items; } public override nint NumberOfSections (UITableView tableView) { return 1; } @@ -121,9 +117,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde { UITableViewCell cell; cell = tableView.DequeueReusableCell ("item"); - if(cell == null) - cell = new UITableViewCell(UITableViewCellStyle.Default, "item"); - cell.TextLabel.Text = this.items[indexPath.Row].FirstName + " " + this.items[indexPath.Row].LastName; + if (cell == null) + cell = new UITableViewCell (UITableViewCellStyle.Default, "item"); + cell.TextLabel.Text = this.items [indexPath.Row].FirstName + " " + this.items [indexPath.Row].LastName; return cell; } diff --git a/Data/Screens/SQLiteNet/PeopleDatabase.cs b/Data/Screens/SQLiteNet/PeopleDatabase.cs index 03080017f..e71cb0e8f 100644 --- a/Data/Screens/SQLiteNet/PeopleDatabase.cs +++ b/Data/Screens/SQLiteNet/PeopleDatabase.cs @@ -3,13 +3,11 @@ using System.Linq; using SQLite; -namespace Xamarin.Screens.SQLiteNet -{ +namespace Xamarin.Screens.SQLiteNet { // If you're looking for a more encapsulated way to work with SQLite-Net, // i recommend creating a database object that inherits from SQLiteConnection // and handles it's own creation, as well as data access methods. - public class PeopleDatabase : SQLiteConnection - { + public class PeopleDatabase : SQLiteConnection { // Creates a new PeopelDatabase. if the database doesn't exist, it will // create the database and all the tables @@ -27,8 +25,8 @@ public IEnumerable GetPeople () public Person GetPerson (int id) { return (from i in Table () - where i.ID == id - select i).FirstOrDefault (); + where i.ID == id + select i).FirstOrDefault (); } public int AddPerson (Person item) diff --git a/Data/Screens/SQLiteNet/Person.cs b/Data/Screens/SQLiteNet/Person.cs index c7700b2b6..31184d115 100644 --- a/Data/Screens/SQLiteNet/Person.cs +++ b/Data/Screens/SQLiteNet/Person.cs @@ -1,13 +1,11 @@ using System; using SQLite; -namespace Xamarin.Screens.SQLiteNet -{ +namespace Xamarin.Screens.SQLiteNet { /// /// A simple person class to illustrate SQLite-Net mapping /// - public class Person - { + public class Person { public Person () { } [PrimaryKey, AutoIncrement] public int ID { get; set; } diff --git a/Data/Screens/ViciCoolStorage/BasicOperations.cs b/Data/Screens/ViciCoolStorage/BasicOperations.cs index 4317afed0..412b8c20d 100644 --- a/Data/Screens/ViciCoolStorage/BasicOperations.cs +++ b/Data/Screens/ViciCoolStorage/BasicOperations.cs @@ -7,17 +7,15 @@ using System.IO; using Vici.CoolStorage; -namespace Xamarin.Screens.ViciCoolStorage -{ - public partial class BasicOperations : UITableViewController - { +namespace Xamarin.Screens.ViciCoolStorage { + public partial class BasicOperations : UITableViewController { protected CSList people; protected TableSource tableSource; #region Constructors public BasicOperations (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] + [Export ("initWithCoder:")] public BasicOperations (NSCoder coder) : base (coder) { Initialize (); } public BasicOperations () : base ("DataSample", null) { Initialize (); } @@ -38,7 +36,7 @@ protected void Initialize () Console.WriteLine ("database creation: " + stopwatch.ElapsedMilliseconds.ToString ()); // query a list of people from the db - people = Person.List(); + people = Person.List (); // performance timing Console.WriteLine ("database query: " + stopwatch.ElapsedMilliseconds.ToString ()); @@ -47,7 +45,7 @@ protected void Initialize () tableSource = new BasicOperations.TableSource (people); // initialize the table view and set the source - this.TableView = new UITableView (){ + this.TableView = new UITableView () { Source = tableSource }; @@ -102,11 +100,10 @@ protected void CheckAndCreateDatabase (string dbName) } // A simple data source for our table - protected class TableSource : UITableViewSource - { + protected class TableSource : UITableViewSource { CSList items; - public TableSource (CSList items) : base() { this.items = items; } + public TableSource (CSList items) : base () { this.items = items; } public override nint NumberOfSections (UITableView tableView) { return 1; } @@ -118,7 +115,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde cell = tableView.DequeueReusableCell ("item"); if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Default, "item"); - cell.TextLabel.Text = this.items[indexPath.Row].FirstName + " " + this.items[indexPath.Row].LastName; + cell.TextLabel.Text = this.items [indexPath.Row].FirstName + " " + this.items [indexPath.Row].LastName; return cell; } diff --git a/Data/Screens/ViciCoolStorage/Person.cs b/Data/Screens/ViciCoolStorage/Person.cs index 4c9dbd48a..5408c3aeb 100644 --- a/Data/Screens/ViciCoolStorage/Person.cs +++ b/Data/Screens/ViciCoolStorage/Person.cs @@ -1,19 +1,17 @@ using System; using Vici.CoolStorage; -namespace Xamarin.Screens.ViciCoolStorage -{ +namespace Xamarin.Screens.ViciCoolStorage { /// /// A simple person class to illustrate Vici.CoolStorage mapping /// - [MapTo("People")] - public class Person : CSObject - { + [MapTo ("People")] + public class Person : CSObject { public Person () { } - public int ID { get { return (int)GetField ("PersonID"); } } - public string FirstName { get { return (string)GetField ("FirstName"); } set { SetField ("FirstName",value); } } - public string LastName { get { return (string)GetField ("LastName"); } set { SetField ("LastName",value); } } + public int ID { get { return (int) GetField ("PersonID"); } } + public string FirstName { get { return (string) GetField ("FirstName"); } set { SetField ("FirstName", value); } } + public string LastName { get { return (string) GetField ("LastName"); } set { SetField ("LastName", value); } } } } diff --git a/DesignerWalkthrough/DesignerWalkthrough/AppDelegate.cs b/DesignerWalkthrough/DesignerWalkthrough/AppDelegate.cs index 46c4efe84..700a3128d 100644 --- a/DesignerWalkthrough/DesignerWalkthrough/AppDelegate.cs +++ b/DesignerWalkthrough/DesignerWalkthrough/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace DesignerWalkthrough -{ +namespace DesignerWalkthrough { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/DesignerWalkthrough/DesignerWalkthrough/FlipsideViewController.cs b/DesignerWalkthrough/DesignerWalkthrough/FlipsideViewController.cs index 1dbf9b1d4..7e13a6677 100644 --- a/DesignerWalkthrough/DesignerWalkthrough/FlipsideViewController.cs +++ b/DesignerWalkthrough/DesignerWalkthrough/FlipsideViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace DesignerWalkthrough -{ - public partial class FlipsideViewController : UIViewController - { +namespace DesignerWalkthrough { + public partial class FlipsideViewController : UIViewController { public event EventHandler Done; public FlipsideViewController (IntPtr handle) : base (handle) diff --git a/DesignerWalkthrough/DesignerWalkthrough/Main.cs b/DesignerWalkthrough/DesignerWalkthrough/Main.cs index 48f0cfeeb..60ca364a1 100644 --- a/DesignerWalkthrough/DesignerWalkthrough/Main.cs +++ b/DesignerWalkthrough/DesignerWalkthrough/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace DesignerWalkthrough -{ - public class Application - { +namespace DesignerWalkthrough { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/DesignerWalkthrough/DesignerWalkthrough/MainViewController.cs b/DesignerWalkthrough/DesignerWalkthrough/MainViewController.cs index 8c3d1a955..27a83b641 100644 --- a/DesignerWalkthrough/DesignerWalkthrough/MainViewController.cs +++ b/DesignerWalkthrough/DesignerWalkthrough/MainViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace DesignerWalkthrough -{ - public partial class MainViewController : UIViewController - { +namespace DesignerWalkthrough { + public partial class MainViewController : UIViewController { public MainViewController (IntPtr handle) : base (handle) { } diff --git a/DesignerWalkthrough/DesignerWalkthrough/MonkeyController.cs b/DesignerWalkthrough/DesignerWalkthrough/MonkeyController.cs index 4c3b250d8..e29964e37 100644 --- a/DesignerWalkthrough/DesignerWalkthrough/MonkeyController.cs +++ b/DesignerWalkthrough/DesignerWalkthrough/MonkeyController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace DesignerWalkthrough -{ - partial class MonkeyController : UIViewController - { +namespace DesignerWalkthrough { + partial class MonkeyController : UIViewController { public MonkeyController (IntPtr handle) : base (handle) { } diff --git a/DispatchSourceExamples/DispatchSourceExamples/AppDelegate.cs b/DispatchSourceExamples/DispatchSourceExamples/AppDelegate.cs index 750ed873b..727306da9 100644 --- a/DispatchSourceExamples/DispatchSourceExamples/AppDelegate.cs +++ b/DispatchSourceExamples/DispatchSourceExamples/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace DispatchSourceExamples -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace DispatchSourceExamples { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/DispatchSourceExamples/DispatchSourceExamples/DetailsViewController.cs b/DispatchSourceExamples/DispatchSourceExamples/DetailsViewController.cs index 728c40503..5713aaf86 100644 --- a/DispatchSourceExamples/DispatchSourceExamples/DetailsViewController.cs +++ b/DispatchSourceExamples/DispatchSourceExamples/DetailsViewController.cs @@ -6,304 +6,274 @@ using System.Linq; using UIKit; -namespace DispatchSourceExamples -{ - public partial class DetailsViewController : UIViewController - { - private const long NanosecondsInSecond = 1000000000; - - private DispatchSource dispatchSource; - - private NSUrl testFileUrl; - - private bool isActive; - - public DetailsViewController(IntPtr handle) : base(handle) { } - - public DispatchSourceItem DispatchItem { get; internal set; } - - protected NSUrl TestFileUrl - { - get - { - if (testFileUrl == null) - { - var fileUrl = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).FirstOrDefault(); - if (fileUrl != null) - { - using (fileUrl) - { - testFileUrl = fileUrl.Append("test.txt", false); - } - } - } - - return testFileUrl; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - Title = DispatchItem.Title; - UpdateButton(); - } - - partial void Execute(UIButton sender) - { - isActive = !isActive; - UpdateButton(); - - switch (DispatchItem.Type) - { - case DispatchSourceType.Timer: - if (isActive) - { - StartTimer(); - } - else - { - CancelDispatchSource(); - } - break; - - case DispatchSourceType.Vnode: - if (isActive) - { - StartVnodeMonitor(); - } - else - { - TestVnodeMonitor(); - } - break; - - case DispatchSourceType.MemoryPressure: - if (isActive) - { - StartMemoryMonitor(); - } - else - { - TestMemoryMonitor(); - } - break; - - case DispatchSourceType.ReadMonitor: - TestReadMonitor(); - break; - - case DispatchSourceType.WriteMonitor: - StartWriteMonitor(); - break; - } - } - - private void UpdateButton() - { - var title = string.Empty; - switch (DispatchItem.Type) - { - case DispatchSourceType.Timer: - title = isActive ? "Stop Timer" : "Start Timer"; - break; - case DispatchSourceType.Vnode: - title = isActive ? "Test Vnode Monitor" : "Start Vnode Monitor"; - break; - case DispatchSourceType.MemoryPressure: - title = isActive ? "Test Memory Monitor" : "Start Memory Monitor"; - break; - case DispatchSourceType.ReadMonitor: - title = "Test Read Monitor"; - break; - case DispatchSourceType.WriteMonitor: - title = "Test Write Monitor"; - break; - } - - actionButton.SetTitle(title, UIControlState.Normal); - } - - #region Actions - - #region Timer - - private void StartTimer() - { - var dispatchSourceTimer = new DispatchSource.Timer(DispatchQueue.MainQueue); - - var delay = 2 * NanosecondsInSecond; - var leeway = 5 * NanosecondsInSecond; - - dispatchSourceTimer.SetTimer(DispatchTime.Now, delay, leeway); - dispatchSourceTimer.SetRegistrationHandler(() => PrintResult("Timer registered")); - dispatchSourceTimer.SetEventHandler(() => PrintResult("Timer tick")); - dispatchSourceTimer.SetCancelHandler(() => PrintResult("Timer stopped")); - - dispatchSource = dispatchSourceTimer; - dispatchSource.Resume(); - } - - #endregion - - #region Vnode - - private void StartVnodeMonitor() - { - var fileUrl = TestFileUrl; - - var testFileStream = File.Create(fileUrl.Path); - int fileDescriptor = GetFileDescriptor(testFileStream); - - var dispatchSourceMonitor = new DispatchSource.VnodeMonitor(fileDescriptor, - VnodeMonitorKind.Delete | VnodeMonitorKind.Extend | VnodeMonitorKind.Write, - DispatchQueue.MainQueue); - - dispatchSourceMonitor.SetRegistrationHandler(() => PrintResult("Vnode monitor registered")); - dispatchSourceMonitor.SetEventHandler(() => - { - var observedEvents = dispatchSourceMonitor.ObservedEvents; - var message = $"Vnode monitor event for {fileUrl.LastPathComponent}: {observedEvents}"; - PrintResult(message); - - CancelDispatchSource(); - testFileStream.Close(); - }); - - dispatchSourceMonitor.SetCancelHandler(() => PrintResult("Vnode monitor cancelled")); - - dispatchSource = dispatchSourceMonitor; - dispatchSource.Resume(); - } - - private void TestVnodeMonitor() - { - File.Delete(TestFileUrl.Path); - } - - #endregion - - #region Memory Monitor - - private void StartMemoryMonitor() - { - var dispatchSourcePressure = new DispatchSource.MemoryPressure(MemoryPressureFlags.Critical | MemoryPressureFlags.Warn | MemoryPressureFlags.Normal, - DispatchQueue.MainQueue); - - dispatchSourcePressure.SetRegistrationHandler(() => PrintResult("Memory monitor registered")); - dispatchSourcePressure.SetEventHandler(() => - { - var pressureLevel = dispatchSourcePressure.PressureFlags; - PrintResult($"Memory worning of level: {pressureLevel}"); - CancelDispatchSource(); - }); - - dispatchSourcePressure.SetCancelHandler(() => PrintResult("Memory monitor cancelled")); - - dispatchSource = dispatchSourcePressure; - dispatchSource.Resume(); - } - - private void TestMemoryMonitor() - { - if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR) - { - PrintResult("Press: Debug -> Simulate Memory Warning"); - } - else - { - PrintResult("This test available on simulator only"); - CancelDispatchSource(); - } - } - - #endregion - - private void TestReadMonitor() - { - var fileUrl = TestFileUrl; - int fileDescriptor = 0; - - using (var stream = new FileStream(fileUrl.Path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)) - { - fileDescriptor = GetFileDescriptor(stream); - } - - dispatchSource = new DispatchSource.ReadMonitor(fileDescriptor, DispatchQueue.MainQueue); - dispatchSource.SetRegistrationHandler(() => PrintResult("Read monitor registered")); - dispatchSource.SetEventHandler(() => - { - PrintResult($"Read monitor: {fileUrl.LastPathComponent} was opened in read mode"); - CancelDispatchSource(); - }); - - dispatchSource.SetCancelHandler(() => PrintResult("Read monitor cancelled")); - dispatchSource.Resume(); - } - - private void StartWriteMonitor() - { - var fileUrl = TestFileUrl; - var stream = new FileStream(fileUrl.Path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); - int fileDescriptor = GetFileDescriptor(stream); - - dispatchSource = new DispatchSource.WriteMonitor(fileDescriptor, DispatchQueue.MainQueue); - dispatchSource.SetRegistrationHandler(() => PrintResult("Write monitor registered")); - dispatchSource.SetEventHandler(() => - { - PrintResult($"Write monitor: {fileUrl.LastPathComponent} was opened in write mode"); - CancelDispatchSource(); - - stream.Dispose(); - stream = null; - }); - - dispatchSource.SetCancelHandler(() => PrintResult("Write monitor cancelled")); - dispatchSource.Resume(); - } - - private void PrintResult(string message) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - textView.Text = $"{textView.Text}\n{message}"; - textView.ScrollRangeToVisible(new NSRange(0, textView.Text.Length)); - }); - } - - private int GetFileDescriptor(FileStream stream) - { - var safeHandle = stream.SafeFileHandle; - return safeHandle.DangerousGetHandle().ToInt32(); - } - - private void CancelDispatchSource() - { - if (dispatchSource != null) - { - dispatchSource.Cancel(); - dispatchSource.Dispose(); - dispatchSource = null; - } - } - - #endregion - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (testFileUrl != null) - { - testFileUrl.Dispose(); - testFileUrl = null; - } - - if (dispatchSource != null) - { - dispatchSource.Dispose(); - dispatchSource = null; - } - } - } -} \ No newline at end of file +namespace DispatchSourceExamples { + public partial class DetailsViewController : UIViewController { + private const long NanosecondsInSecond = 1000000000; + + private DispatchSource dispatchSource; + + private NSUrl testFileUrl; + + private bool isActive; + + public DetailsViewController (IntPtr handle) : base (handle) { } + + public DispatchSourceItem DispatchItem { get; internal set; } + + protected NSUrl TestFileUrl { + get { + if (testFileUrl == null) { + var fileUrl = NSFileManager.DefaultManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).FirstOrDefault (); + if (fileUrl != null) { + using (fileUrl) { + testFileUrl = fileUrl.Append ("test.txt", false); + } + } + } + + return testFileUrl; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + Title = DispatchItem.Title; + UpdateButton (); + } + + partial void Execute (UIButton sender) + { + isActive = !isActive; + UpdateButton (); + + switch (DispatchItem.Type) { + case DispatchSourceType.Timer: + if (isActive) { + StartTimer (); + } else { + CancelDispatchSource (); + } + break; + + case DispatchSourceType.Vnode: + if (isActive) { + StartVnodeMonitor (); + } else { + TestVnodeMonitor (); + } + break; + + case DispatchSourceType.MemoryPressure: + if (isActive) { + StartMemoryMonitor (); + } else { + TestMemoryMonitor (); + } + break; + + case DispatchSourceType.ReadMonitor: + TestReadMonitor (); + break; + + case DispatchSourceType.WriteMonitor: + StartWriteMonitor (); + break; + } + } + + private void UpdateButton () + { + var title = string.Empty; + switch (DispatchItem.Type) { + case DispatchSourceType.Timer: + title = isActive ? "Stop Timer" : "Start Timer"; + break; + case DispatchSourceType.Vnode: + title = isActive ? "Test Vnode Monitor" : "Start Vnode Monitor"; + break; + case DispatchSourceType.MemoryPressure: + title = isActive ? "Test Memory Monitor" : "Start Memory Monitor"; + break; + case DispatchSourceType.ReadMonitor: + title = "Test Read Monitor"; + break; + case DispatchSourceType.WriteMonitor: + title = "Test Write Monitor"; + break; + } + + actionButton.SetTitle (title, UIControlState.Normal); + } + + #region Actions + + #region Timer + + private void StartTimer () + { + var dispatchSourceTimer = new DispatchSource.Timer (DispatchQueue.MainQueue); + + var delay = 2 * NanosecondsInSecond; + var leeway = 5 * NanosecondsInSecond; + + dispatchSourceTimer.SetTimer (DispatchTime.Now, delay, leeway); + dispatchSourceTimer.SetRegistrationHandler (() => PrintResult ("Timer registered")); + dispatchSourceTimer.SetEventHandler (() => PrintResult ("Timer tick")); + dispatchSourceTimer.SetCancelHandler (() => PrintResult ("Timer stopped")); + + dispatchSource = dispatchSourceTimer; + dispatchSource.Resume (); + } + + #endregion + + #region Vnode + + private void StartVnodeMonitor () + { + var fileUrl = TestFileUrl; + + var testFileStream = File.Create (fileUrl.Path); + int fileDescriptor = GetFileDescriptor (testFileStream); + + var dispatchSourceMonitor = new DispatchSource.VnodeMonitor (fileDescriptor, + VnodeMonitorKind.Delete | VnodeMonitorKind.Extend | VnodeMonitorKind.Write, + DispatchQueue.MainQueue); + + dispatchSourceMonitor.SetRegistrationHandler (() => PrintResult ("Vnode monitor registered")); + dispatchSourceMonitor.SetEventHandler (() => { + var observedEvents = dispatchSourceMonitor.ObservedEvents; + var message = $"Vnode monitor event for {fileUrl.LastPathComponent}: {observedEvents}"; + PrintResult (message); + + CancelDispatchSource (); + testFileStream.Close (); + }); + + dispatchSourceMonitor.SetCancelHandler (() => PrintResult ("Vnode monitor cancelled")); + + dispatchSource = dispatchSourceMonitor; + dispatchSource.Resume (); + } + + private void TestVnodeMonitor () + { + File.Delete (TestFileUrl.Path); + } + + #endregion + + #region Memory Monitor + + private void StartMemoryMonitor () + { + var dispatchSourcePressure = new DispatchSource.MemoryPressure (MemoryPressureFlags.Critical | MemoryPressureFlags.Warn | MemoryPressureFlags.Normal, + DispatchQueue.MainQueue); + + dispatchSourcePressure.SetRegistrationHandler (() => PrintResult ("Memory monitor registered")); + dispatchSourcePressure.SetEventHandler (() => { + var pressureLevel = dispatchSourcePressure.PressureFlags; + PrintResult ($"Memory worning of level: {pressureLevel}"); + CancelDispatchSource (); + }); + + dispatchSourcePressure.SetCancelHandler (() => PrintResult ("Memory monitor cancelled")); + + dispatchSource = dispatchSourcePressure; + dispatchSource.Resume (); + } + + private void TestMemoryMonitor () + { + if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR) { + PrintResult ("Press: Debug -> Simulate Memory Warning"); + } else { + PrintResult ("This test available on simulator only"); + CancelDispatchSource (); + } + } + + #endregion + + private void TestReadMonitor () + { + var fileUrl = TestFileUrl; + int fileDescriptor = 0; + + using (var stream = new FileStream (fileUrl.Path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None)) { + fileDescriptor = GetFileDescriptor (stream); + } + + dispatchSource = new DispatchSource.ReadMonitor (fileDescriptor, DispatchQueue.MainQueue); + dispatchSource.SetRegistrationHandler (() => PrintResult ("Read monitor registered")); + dispatchSource.SetEventHandler (() => { + PrintResult ($"Read monitor: {fileUrl.LastPathComponent} was opened in read mode"); + CancelDispatchSource (); + }); + + dispatchSource.SetCancelHandler (() => PrintResult ("Read monitor cancelled")); + dispatchSource.Resume (); + } + + private void StartWriteMonitor () + { + var fileUrl = TestFileUrl; + var stream = new FileStream (fileUrl.Path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); + int fileDescriptor = GetFileDescriptor (stream); + + dispatchSource = new DispatchSource.WriteMonitor (fileDescriptor, DispatchQueue.MainQueue); + dispatchSource.SetRegistrationHandler (() => PrintResult ("Write monitor registered")); + dispatchSource.SetEventHandler (() => { + PrintResult ($"Write monitor: {fileUrl.LastPathComponent} was opened in write mode"); + CancelDispatchSource (); + + stream.Dispose (); + stream = null; + }); + + dispatchSource.SetCancelHandler (() => PrintResult ("Write monitor cancelled")); + dispatchSource.Resume (); + } + + private void PrintResult (string message) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + textView.Text = $"{textView.Text}\n{message}"; + textView.ScrollRangeToVisible (new NSRange (0, textView.Text.Length)); + }); + } + + private int GetFileDescriptor (FileStream stream) + { + var safeHandle = stream.SafeFileHandle; + return safeHandle.DangerousGetHandle ().ToInt32 (); + } + + private void CancelDispatchSource () + { + if (dispatchSource != null) { + dispatchSource.Cancel (); + dispatchSource.Dispose (); + dispatchSource = null; + } + } + + #endregion + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (testFileUrl != null) { + testFileUrl.Dispose (); + testFileUrl = null; + } + + if (dispatchSource != null) { + dispatchSource.Dispose (); + dispatchSource = null; + } + } + } +} diff --git a/DispatchSourceExamples/DispatchSourceExamples/Main.cs b/DispatchSourceExamples/DispatchSourceExamples/Main.cs index 5d03f0f23..5a034d290 100644 --- a/DispatchSourceExamples/DispatchSourceExamples/Main.cs +++ b/DispatchSourceExamples/DispatchSourceExamples/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace DispatchSourceExamples -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace DispatchSourceExamples { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/DispatchSourceExamples/DispatchSourceExamples/MainViewController.cs b/DispatchSourceExamples/DispatchSourceExamples/MainViewController.cs index 52684c2d5..4cf3456c6 100644 --- a/DispatchSourceExamples/DispatchSourceExamples/MainViewController.cs +++ b/DispatchSourceExamples/DispatchSourceExamples/MainViewController.cs @@ -4,59 +4,55 @@ using System.Collections.Generic; using UIKit; -namespace DispatchSourceExamples -{ - public partial class MainViewController : UITableViewController - { - private const string OpenDetailsSegueIndentifier = "openDetailsSegue"; - private const string CellIdentifier = "sourceCellIdentifier"; - - private readonly List items = new List - { - new DispatchSourceItem { Type = DispatchSourceType.Timer, Title = "Timer", Subtitle = "Submit the event to the target queue"}, - new DispatchSourceItem { Type = DispatchSourceType.Vnode, Title = "Vnode", Subtitle = "Monitor the file system nodes for changes"}, - new DispatchSourceItem { Type = DispatchSourceType.MemoryPressure, Title = "Memory Pressure", Subtitle = "Monitor the system memory pressure"}, - new DispatchSourceItem { Type = DispatchSourceType.ReadMonitor, Title = "Read Monitor", Subtitle = "Monitor file descriptors for pending data"}, - new DispatchSourceItem { Type = DispatchSourceType.WriteMonitor, Title = "Write Monitor", Subtitle = "Monitor file descriptors for write buffer space"} - }; - - private DispatchSourceItem selectedItem; - - public MainViewController(IntPtr handle) : base(handle) { } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if(!string.IsNullOrEmpty(segue?.Identifier) && - segue.Identifier == OpenDetailsSegueIndentifier) - { - if(segue.DestinationViewController is DetailsViewController controller) - { - controller.DispatchItem = selectedItem; - selectedItem = null; - } - } - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return items.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var item = items[indexPath.Row]; - - var cell = tableView.DequeueReusableCell(CellIdentifier, indexPath); - cell.TextLabel.Text = item.Title; - cell.DetailTextLabel.Text = item.Subtitle; - - return cell; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - selectedItem = items[indexPath.Row]; - PerformSegue(OpenDetailsSegueIndentifier, this); - } - } -} \ No newline at end of file +namespace DispatchSourceExamples { + public partial class MainViewController : UITableViewController { + private const string OpenDetailsSegueIndentifier = "openDetailsSegue"; + private const string CellIdentifier = "sourceCellIdentifier"; + + private readonly List items = new List + { + new DispatchSourceItem { Type = DispatchSourceType.Timer, Title = "Timer", Subtitle = "Submit the event to the target queue"}, + new DispatchSourceItem { Type = DispatchSourceType.Vnode, Title = "Vnode", Subtitle = "Monitor the file system nodes for changes"}, + new DispatchSourceItem { Type = DispatchSourceType.MemoryPressure, Title = "Memory Pressure", Subtitle = "Monitor the system memory pressure"}, + new DispatchSourceItem { Type = DispatchSourceType.ReadMonitor, Title = "Read Monitor", Subtitle = "Monitor file descriptors for pending data"}, + new DispatchSourceItem { Type = DispatchSourceType.WriteMonitor, Title = "Write Monitor", Subtitle = "Monitor file descriptors for write buffer space"} + }; + + private DispatchSourceItem selectedItem; + + public MainViewController (IntPtr handle) : base (handle) { } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (!string.IsNullOrEmpty (segue?.Identifier) && + segue.Identifier == OpenDetailsSegueIndentifier) { + if (segue.DestinationViewController is DetailsViewController controller) { + controller.DispatchItem = selectedItem; + selectedItem = null; + } + } + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return items.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var item = items [indexPath.Row]; + + var cell = tableView.DequeueReusableCell (CellIdentifier, indexPath); + cell.TextLabel.Text = item.Title; + cell.DetailTextLabel.Text = item.Subtitle; + + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + selectedItem = items [indexPath.Row]; + PerformSegue (OpenDetailsSegueIndentifier, this); + } + } +} diff --git a/DispatchSourceExamples/DispatchSourceExamples/Models/DispatchSourceItem.cs b/DispatchSourceExamples/DispatchSourceExamples/Models/DispatchSourceItem.cs index 3785ff76e..1b648be4c 100644 --- a/DispatchSourceExamples/DispatchSourceExamples/Models/DispatchSourceItem.cs +++ b/DispatchSourceExamples/DispatchSourceExamples/Models/DispatchSourceItem.cs @@ -1,21 +1,18 @@ - -namespace DispatchSourceExamples.Models -{ - public class DispatchSourceItem - { - public string Title { get; set; } - public string Subtitle { get; set; } +namespace DispatchSourceExamples.Models { + public class DispatchSourceItem { + public string Title { get; set; } - public DispatchSourceType Type { get; set; } - } + public string Subtitle { get; set; } - public enum DispatchSourceType - { - Timer, - Vnode, - MemoryPressure, - ReadMonitor, - WriteMonitor - } -} \ No newline at end of file + public DispatchSourceType Type { get; set; } + } + + public enum DispatchSourceType { + Timer, + Vnode, + MemoryPressure, + ReadMonitor, + WriteMonitor + } +} diff --git a/Drawing/AppDelegate.cs b/Drawing/AppDelegate.cs index fad6ec8a9..12e3a24e7 100644 --- a/Drawing/AppDelegate.cs +++ b/Drawing/AppDelegate.cs @@ -2,11 +2,9 @@ using UIKit; using Foundation; -namespace Example_Drawing -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace Example_Drawing { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { #region -= declarations and properties =- protected UIWindow window; diff --git a/Drawing/Application.cs b/Drawing/Application.cs index 6813d3338..a384066a2 100644 --- a/Drawing/Application.cs +++ b/Drawing/Application.cs @@ -1,18 +1,14 @@ using System; using UIKit; -namespace Example_Drawing -{ +namespace Example_Drawing { public class Application// : UIApplication { - public static void Main (string[] args) + public static void Main (string [] args) { - try - { + try { UIApplication.Main (args, null, "AppDelegate"); - } - catch (Exception e) - { + } catch (Exception e) { Console.WriteLine (e.ToString ()); } } diff --git a/Drawing/Screens/iPad/ColorPattern/Controller.cs b/Drawing/Screens/iPad/ColorPattern/Controller.cs index e2b5ea6c2..ba7183269 100644 --- a/Drawing/Screens/iPad/ColorPattern/Controller.cs +++ b/Drawing/Screens/iPad/ColorPattern/Controller.cs @@ -2,15 +2,13 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.ColorPattern -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.ColorPattern { + public class Controller : UIViewController { UIImageView imageView; #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion @@ -31,9 +29,9 @@ public override void ViewDidLoad () // size CGSize bitmapSize = new CGSize (View.Frame.Size); using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, - (int)bitmapSize.Width, (int)bitmapSize.Height, 8, - (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), - CGImageAlphaInfo.PremultipliedFirst)) { + (int) bitmapSize.Width, (int) bitmapSize.Height, 8, + (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), + CGImageAlphaInfo.PremultipliedFirst)) { // declare vars CGRect patternRect = new CGRect (0, 0, 16, 16); @@ -47,7 +45,7 @@ public override void ViewDidLoad () true, DrawPolkaDotPattern); // set our fill as our pattern, color doesn't matter because the pattern handles it - context.SetFillPattern (pattern, new nfloat[] { 1 }); + context.SetFillPattern (pattern, new nfloat [] { 1 }); // fill the entire view with that pattern context.FillRect (imageView.Frame); @@ -73,7 +71,7 @@ protected void DrawStarPattern (CGContext context) // declare vars float starDiameter = 16; // 144º - float theta = 2 * (float)Math.PI * (2f / 5f); + float theta = 2 * (float) Math.PI * (2f / 5f); float radius = starDiameter / 2; // move up and over @@ -81,7 +79,7 @@ protected void DrawStarPattern (CGContext context) context.MoveTo (0, radius); for (int i = 1; i < 5; i++) { - context.AddLineToPoint (radius * (float)Math.Sin (i * theta), radius * (float)Math.Cos (i * theta)); + context.AddLineToPoint (radius * (float) Math.Sin (i * theta), radius * (float) Math.Cos (i * theta)); } // fill our star as dark gray context.SetFillColor (.3f, .3f, .3f, 1); diff --git a/Drawing/Screens/iPad/CoordinatesOffScreen/Controller.cs b/Drawing/Screens/iPad/CoordinatesOffScreen/Controller.cs index 13574e4d5..34e3e016b 100644 --- a/Drawing/Screens/iPad/CoordinatesOffScreen/Controller.cs +++ b/Drawing/Screens/iPad/CoordinatesOffScreen/Controller.cs @@ -2,15 +2,13 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.CoordinatesOffScreen -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.CoordinatesOffScreen { + public class Controller : UIViewController { UIImageView imageView; #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion @@ -31,11 +29,10 @@ public override void ViewDidLoad () // size CGSize bitmapSize = new CGSize (View.Frame.Size); using (CGBitmapContext context = new CGBitmapContext ( - IntPtr.Zero, - (int)bitmapSize.Width, (int)bitmapSize.Height, 8, - (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), - CGImageAlphaInfo.PremultipliedFirst)) - { + IntPtr.Zero, + (int) bitmapSize.Width, (int) bitmapSize.Height, 8, + (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), + CGImageAlphaInfo.PremultipliedFirst)) { // declare vars int remainder; int textHeight = 20; @@ -58,7 +55,7 @@ public override void ViewDidLoad () // starting at 40, draw the coordinate text nearly to the top if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points - Math.DivRem ( (int)yPos, (int)80, out remainder); + Math.DivRem ((int) yPos, (int) 80, out remainder); if (remainder == 0) ShowTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight); } @@ -86,7 +83,7 @@ public override void ViewDidLoad () // starting at 100, draw the coordinate text nearly to the top if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points - Math.DivRem ((int)xPos, (int)80, out remainder); + Math.DivRem ((int) xPos, (int) 80, out remainder); if (remainder == 0) ShowCenteredTextAtPoint (context, xPos, 30, xPos.ToString (), textHeight); } diff --git a/Drawing/Screens/iPad/CoordinatesOnScreen/Controller.cs b/Drawing/Screens/iPad/CoordinatesOnScreen/Controller.cs index 6ce351697..e4d69d779 100644 --- a/Drawing/Screens/iPad/CoordinatesOnScreen/Controller.cs +++ b/Drawing/Screens/iPad/CoordinatesOnScreen/Controller.cs @@ -1,14 +1,12 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.CoordinatesOnScreen -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.CoordinatesOnScreen { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() + public Controller () : base () { } diff --git a/Drawing/Screens/iPad/CoordinatesOnScreen/View.cs b/Drawing/Screens/iPad/CoordinatesOnScreen/View.cs index 8f5119e80..c0c9f1719 100644 --- a/Drawing/Screens/iPad/CoordinatesOnScreen/View.cs +++ b/Drawing/Screens/iPad/CoordinatesOnScreen/View.cs @@ -2,13 +2,11 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.CoordinatesOnScreen -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.CoordinatesOnScreen { + public class View : UIView { #region -= constructors =- - public View () : base() + public View () : base () { } @@ -39,7 +37,7 @@ public override void Draw (CGRect rect) // draw a vertical tick every 20 pixels float yPos = 20; - int numberOfVerticalTicks = (((int)Frame.Height / 20) - 1); + int numberOfVerticalTicks = (((int) Frame.Height / 20) - 1); for (int i = 0; i < numberOfVerticalTicks; i++) { // draw the layer @@ -49,7 +47,7 @@ public override void Draw (CGRect rect) if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points - Math.DivRem ((int)yPos, (int)80, out remainder); + Math.DivRem ((int) yPos, (int) 80, out remainder); if (remainder == 0) ShowTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight); } @@ -69,14 +67,14 @@ public override void Draw (CGRect rect) // draw a horizontal tick every 20 pixels float xPos = 20; - int numberOfHorizontalTicks = (((int)Frame.Width / 20) - 1); + int numberOfHorizontalTicks = (((int) Frame.Width / 20) - 1); for (int i = 0; i < numberOfHorizontalTicks; i++) { context.DrawLayer (horizontalTickLayer, new CGPoint (xPos, 0)); // starting at 100, draw the coordinate text nearly to the top if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points - Math.DivRem ((int)xPos, (int)80, out remainder); + Math.DivRem ((int) xPos, (int) 80, out remainder); if (remainder == 0) { ShowCenteredTextAtPoint (context, xPos, 40, xPos.ToString (), textHeight); } diff --git a/Drawing/Screens/iPad/DrawOffScreenUsingCGBitmapContext/Controller.cs b/Drawing/Screens/iPad/DrawOffScreenUsingCGBitmapContext/Controller.cs index 372fc32e7..20405f3ce 100644 --- a/Drawing/Screens/iPad/DrawOffScreenUsingCGBitmapContext/Controller.cs +++ b/Drawing/Screens/iPad/DrawOffScreenUsingCGBitmapContext/Controller.cs @@ -2,13 +2,11 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.DrawOffScreenUsingCGBitmapContext -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.DrawOffScreenUsingCGBitmapContext { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() + public Controller () : base () { } @@ -26,14 +24,14 @@ public override void ViewDidLoad () // 32bit RGB (8bits * 4components (aRGB) = 32bit) int bitsPerComponent = 8; // 4bytes for each pixel (32 bits = 4bytes) - int bytesPerRow = (int)(4 * bitmapSize.Width); + int bytesPerRow = (int) (4 * bitmapSize.Width); // no special color space CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB (); // aRGB CGImageAlphaInfo alphaType = CGImageAlphaInfo.PremultipliedFirst; using (CGBitmapContext context = new CGBitmapContext (data - , (int)bitmapSize.Width, (int)bitmapSize.Height, bitsPerComponent + , (int) bitmapSize.Width, (int) bitmapSize.Height, bitsPerComponent , bytesPerRow, colorSpace, alphaType)) { // draw whatever here. diff --git a/Drawing/Screens/iPad/DrawRectVsPath/Controller.cs b/Drawing/Screens/iPad/DrawRectVsPath/Controller.cs index f4d081718..0dbb8b3da 100644 --- a/Drawing/Screens/iPad/DrawRectVsPath/Controller.cs +++ b/Drawing/Screens/iPad/DrawRectVsPath/Controller.cs @@ -1,13 +1,11 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.DrawRectVsPath -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.DrawRectVsPath { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion diff --git a/Drawing/Screens/iPad/DrawRectVsPath/View.cs b/Drawing/Screens/iPad/DrawRectVsPath/View.cs index e7f5d98fb..b24c99b1b 100644 --- a/Drawing/Screens/iPad/DrawRectVsPath/View.cs +++ b/Drawing/Screens/iPad/DrawRectVsPath/View.cs @@ -2,13 +2,11 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.DrawRectVsPath -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.DrawRectVsPath { + public class View : UIView { #region -= constructors =- - public View () : base() { } + public View () : base () { } #endregion diff --git a/Drawing/Screens/iPad/FlagOffScreen/Controller.cs b/Drawing/Screens/iPad/FlagOffScreen/Controller.cs index 5067ff887..a7503f567 100644 --- a/Drawing/Screens/iPad/FlagOffScreen/Controller.cs +++ b/Drawing/Screens/iPad/FlagOffScreen/Controller.cs @@ -2,15 +2,13 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.FlagOffScreen -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.FlagOffScreen { + public class Controller : UIViewController { UIImageView imageView; #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion @@ -31,9 +29,9 @@ public override void ViewDidLoad () // size CGSize bitmapSize = new CGSize (imageView.Frame.Size); using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, - (int)bitmapSize.Width, (int)bitmapSize.Height, 8, - (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), - CGImageAlphaInfo.PremultipliedFirst)) { + (int) bitmapSize.Width, (int) bitmapSize.Height, 8, + (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), + CGImageAlphaInfo.PremultipliedFirst)) { // draw our coordinates for reference DrawCoordinateSpace (context); @@ -55,8 +53,8 @@ protected void DrawFlag (CGContext context) int i, j; // general sizes - float flagWidth = (float)imageView.Frame.Width * .8f; - float flagHeight = (float)(flagWidth / 1.9); + float flagWidth = (float) imageView.Frame.Width * .8f; + float flagHeight = (float) (flagWidth / 1.9); CGPoint flagOrigin = new CGPoint (imageView.Frame.Width * .1f, imageView.Frame.Height / 3); // stripe @@ -136,7 +134,7 @@ protected void DrawFlag (CGContext context) context.TranslateCTM (starHorizontalCenterSpacing, 0f); } // move the row down, and then back left - context.TranslateCTM ( (-i * starHorizontalCenterSpacing), -starVerticalCenterSpacing); + context.TranslateCTM ((-i * starHorizontalCenterSpacing), -starVerticalCenterSpacing); } context.RestoreState (); @@ -152,7 +150,7 @@ protected void DrawFlag (CGContext context) context.DrawLayer (starLayer, new CGPoint (0f, 0f)); context.TranslateCTM (starHorizontalCenterSpacing, 0); } - context.TranslateCTM ( (-i * starHorizontalCenterSpacing), -starVerticalCenterSpacing); + context.TranslateCTM ((-i * starHorizontalCenterSpacing), -starVerticalCenterSpacing); } context.RestoreState (); } @@ -183,7 +181,7 @@ protected void DrawStar (CGContext context, float starDiameter) { // declare vars // 144º - float theta = 2 * (float)Math.PI * (2f / 5f); + float theta = 2 * (float) Math.PI * (2f / 5f); float radius = starDiameter / 2; // move up and over @@ -191,7 +189,7 @@ protected void DrawStar (CGContext context, float starDiameter) context.MoveTo (0, radius); for (int i = 1; i < 5; i++) { - context.AddLineToPoint (radius * (float)Math.Sin (i * theta), radius * (float)Math.Cos (i * theta)); + context.AddLineToPoint (radius * (float) Math.Sin (i * theta), radius * (float) Math.Cos (i * theta)); } context.SetFillColor (1, 1, 1, 1); context.ClosePath (); @@ -208,8 +206,7 @@ protected void DrawCoordinateSpace (CGBitmapContext context) #region -= vertical ticks =- // create our vertical tick lines - using (CGLayer verticalTickLayer = CGLayer.Create (context, new CGSize (20, 3))) - { + using (CGLayer verticalTickLayer = CGLayer.Create (context, new CGSize (20, 3))) { // draw a single tick verticalTickLayer.Context.FillRect (new CGRect (0, 1, 20, 2)); @@ -225,7 +222,7 @@ protected void DrawCoordinateSpace (CGBitmapContext context) if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points - Math.DivRem ((int)yPos, (int)80, out remainder); + Math.DivRem ((int) yPos, (int) 80, out remainder); if (remainder == 0) DrawTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight); } @@ -240,8 +237,7 @@ protected void DrawCoordinateSpace (CGBitmapContext context) #region -= horizontal ticks =- // create our horizontal tick lines - using (CGLayer horizontalTickLayer = CGLayer.Create (context, new CGSize (3, 20))) - { + using (CGLayer horizontalTickLayer = CGLayer.Create (context, new CGSize (3, 20))) { horizontalTickLayer.Context.FillRect (new CGRect (1, 0, 2, 20)); // draw a horizontal tick every 20 pixels @@ -255,7 +251,7 @@ protected void DrawCoordinateSpace (CGBitmapContext context) if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points - Math.DivRem ((int)xPos, (int)80, out remainder); + Math.DivRem ((int) xPos, (int) 80, out remainder); if (remainder == 0) DrawCenteredTextAtPoint (context, xPos, 30, xPos.ToString (), textHeight); } diff --git a/Drawing/Screens/iPad/FlagOnScreen/Controller.cs b/Drawing/Screens/iPad/FlagOnScreen/Controller.cs index 7b4b2603d..07e1e478a 100644 --- a/Drawing/Screens/iPad/FlagOnScreen/Controller.cs +++ b/Drawing/Screens/iPad/FlagOnScreen/Controller.cs @@ -1,14 +1,12 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.FlagOnScreen -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.FlagOnScreen { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() + public Controller () : base () { } diff --git a/Drawing/Screens/iPad/FlagOnScreen/View.cs b/Drawing/Screens/iPad/FlagOnScreen/View.cs index 5b4e1f515..e8f7e84c4 100644 --- a/Drawing/Screens/iPad/FlagOnScreen/View.cs +++ b/Drawing/Screens/iPad/FlagOnScreen/View.cs @@ -2,13 +2,11 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.FlagOnScreen -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.FlagOnScreen { + public class View : UIView { #region -= constructors =- - public View () : base() { } + public View () : base () { } #endregion @@ -47,8 +45,8 @@ protected void DrawFlag (CGContext context) int i, j; // general sizes - float flagWidth = (float)Frame.Width * .8f; - float flagHeight = (float)(flagWidth / 1.9); + float flagWidth = (float) Frame.Width * .8f; + float flagHeight = (float) (flagWidth / 1.9); CGPoint flagOrigin = new CGPoint (Frame.Width * .1f, Frame.Height / 3); // stripe @@ -176,7 +174,7 @@ protected void DrawStar (CGContext context, float starDiameter) { // declare vars // 144º - float theta = 2 * (float)Math.PI * (2f / 5f); + float theta = 2 * (float) Math.PI * (2f / 5f); float radius = starDiameter / 2; // move up and over @@ -184,7 +182,7 @@ protected void DrawStar (CGContext context, float starDiameter) context.MoveTo (0, radius); for (int i = 1; i < 5; i++) { - context.AddLineToPoint (radius * (float)Math.Sin (i * theta), radius * (float)Math.Cos (i * theta)); + context.AddLineToPoint (radius * (float) Math.Sin (i * theta), radius * (float) Math.Cos (i * theta)); } context.SetFillColor (1, 1, 1, 1); context.ClosePath (); @@ -210,7 +208,7 @@ protected void DrawCoordinateSpace (CGContext context) // draw a vertical tick every 20 pixels float yPos = 20; - int numberOfVerticalTicks = ((int)(Frame.Height / 20) - 1); + int numberOfVerticalTicks = ((int) (Frame.Height / 20) - 1); for (int i = 0; i < numberOfVerticalTicks; i++) { // draw the layer @@ -220,7 +218,7 @@ protected void DrawCoordinateSpace (CGContext context) if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points - Math.DivRem ((int)yPos, (int)80, out remainder); + Math.DivRem ((int) yPos, (int) 80, out remainder); if (remainder == 0) DrawTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight); } @@ -241,7 +239,7 @@ protected void DrawCoordinateSpace (CGContext context) // draw a horizontal tick every 20 pixels float xPos = 20; - int numberOfHorizontalTicks = ((int)(Frame.Width / 20) - 1); + int numberOfHorizontalTicks = ((int) (Frame.Width / 20) - 1); for (int i = 0; i < numberOfHorizontalTicks; i++) { context.DrawLayer (horizontalTickLayer, new CGPoint (xPos, 0)); @@ -250,7 +248,7 @@ protected void DrawCoordinateSpace (CGContext context) if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points - Math.DivRem ((int)xPos, (int)80, out remainder); + Math.DivRem ((int) xPos, (int) 80, out remainder); if (remainder == 0) DrawCenteredTextAtPoint (context, xPos, 30, xPos.ToString (), textHeight); } diff --git a/Drawing/Screens/iPad/HitTesting/Controller.cs b/Drawing/Screens/iPad/HitTesting/Controller.cs index 762849369..769a30f91 100644 --- a/Drawing/Screens/iPad/HitTesting/Controller.cs +++ b/Drawing/Screens/iPad/HitTesting/Controller.cs @@ -1,13 +1,11 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.HitTesting -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.HitTesting { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion diff --git a/Drawing/Screens/iPad/HitTesting/View.cs b/Drawing/Screens/iPad/HitTesting/View.cs index 7ee822632..447059b0c 100644 --- a/Drawing/Screens/iPad/HitTesting/View.cs +++ b/Drawing/Screens/iPad/HitTesting/View.cs @@ -3,16 +3,14 @@ using CoreGraphics; using Foundation; -namespace Example_Drawing.Screens.iPad.HitTesting -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.HitTesting { + public class View : UIView { CGPath myRectangleButtonPath; bool touchStartedInPath; #region -= constructors =- - public View () : base() { } + public View () : base () { } #endregion diff --git a/Drawing/Screens/iPad/Home/HomeScreen.xib.cs b/Drawing/Screens/iPad/Home/HomeScreen.xib.cs index ae0820c0a..703ff7e74 100644 --- a/Drawing/Screens/iPad/Home/HomeScreen.xib.cs +++ b/Drawing/Screens/iPad/Home/HomeScreen.xib.cs @@ -5,21 +5,19 @@ using Foundation; using UIKit; -namespace Example_Drawing.Screens.iPad.Home -{ - public partial class HomeScreen : UIViewController - { +namespace Example_Drawing.Screens.iPad.Home { + public partial class HomeScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public HomeScreen (IntPtr handle) : base(handle) { } + public HomeScreen (IntPtr handle) : base (handle) { } - [Export("initWithCoder:")] - public HomeScreen (NSCoder coder) : base(coder) { } + [Export ("initWithCoder:")] + public HomeScreen (NSCoder coder) : base (coder) { } - public HomeScreen () : base("HomeScreen", null) { } + public HomeScreen () : base ("HomeScreen", null) { } #endregion @@ -27,49 +25,64 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - btnDrawRectVsPath.TouchUpInside += delegate { + btnDrawRectVsPath.TouchUpInside += delegate + { NavigationController.PushViewController (new DrawRectVsPath.Controller (), true); }; - btnDrawUsingCGBitmapContext.TouchUpInside += delegate { + btnDrawUsingCGBitmapContext.TouchUpInside += delegate + { NavigationController.PushViewController (new DrawOffScreenUsingCGBitmapContext.Controller (), true); }; - btnDrawUsingLayers.TouchUpInside += delegate { + btnDrawUsingLayers.TouchUpInside += delegate + { NavigationController.PushViewController (new Layers.Controller (), true); }; - btnOnScreenCoords.TouchUpInside += delegate { + btnOnScreenCoords.TouchUpInside += delegate + { NavigationController.PushViewController (new CoordinatesOnScreen.Controller (), true); }; - btnOffScreenCoords.TouchUpInside += delegate { + btnOffScreenCoords.TouchUpInside += delegate + { NavigationController.PushViewController (new CoordinatesOffScreen.Controller (), true); }; - btnOnScreenUncorrectedText.TouchUpInside += delegate { + btnOnScreenUncorrectedText.TouchUpInside += delegate + { NavigationController.PushViewController (new OnScreenUncorrectedTextRotation.Controller (), true); }; - btnImage.TouchUpInside += delegate { + btnImage.TouchUpInside += delegate + { NavigationController.PushViewController (new Images.Controller (), true); }; - btnOffScreenFlag.TouchUpInside += delegate { + btnOffScreenFlag.TouchUpInside += delegate + { NavigationController.PushViewController (new FlagOffScreen.Controller (), true); }; - btnOnScreenFlag.TouchUpInside += delegate { + btnOnScreenFlag.TouchUpInside += delegate + { NavigationController.PushViewController (new FlagOnScreen.Controller (), true); }; - btnPatterns.TouchUpInside += delegate { + btnPatterns.TouchUpInside += delegate + { NavigationController.PushViewController (new ColorPattern.Controller (), true); }; - btnStencilPattern.TouchUpInside += delegate { + btnStencilPattern.TouchUpInside += delegate + { NavigationController.PushViewController (new StencilPattern.Controller (), true); }; - btnShadows.TouchUpInside += delegate { + btnShadows.TouchUpInside += delegate + { NavigationController.PushViewController (new Shadows.Controller (), true); }; - btnHitTesting.TouchUpInside += delegate { + btnHitTesting.TouchUpInside += delegate + { NavigationController.PushViewController (new HitTesting.Controller (), true); }; - btnTouchDrawing.TouchUpInside += delegate { + btnTouchDrawing.TouchUpInside += delegate + { NavigationController.PushViewController (new TouchDrawing.Controller (), true); }; - btnTransformations.TouchUpInside += delegate { + btnTransformations.TouchUpInside += delegate + { NavigationController.PushViewController (new Transformations.Controller (), true); }; diff --git a/Drawing/Screens/iPad/Images/Controller.cs b/Drawing/Screens/iPad/Images/Controller.cs index 4b60eb5f3..b06afdd6b 100644 --- a/Drawing/Screens/iPad/Images/Controller.cs +++ b/Drawing/Screens/iPad/Images/Controller.cs @@ -2,15 +2,13 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.Images -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.Images { + public class Controller : UIViewController { UIImageView imageView; #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion @@ -31,9 +29,9 @@ public override void ViewDidLoad () // size CGSize bitmapSize = new CGSize (View.Frame.Size); using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, - (int)bitmapSize.Width, (int)bitmapSize.Height, 8, - (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), - CGImageAlphaInfo.PremultipliedFirst)) { + (int) bitmapSize.Width, (int) bitmapSize.Height, 8, + (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), + CGImageAlphaInfo.PremultipliedFirst)) { // declare vars UIImage apressImage = UIImage.FromFile ("icon-114.png"); diff --git a/Drawing/Screens/iPad/Layers/Controller.cs b/Drawing/Screens/iPad/Layers/Controller.cs index 235440804..7379d90d8 100644 --- a/Drawing/Screens/iPad/Layers/Controller.cs +++ b/Drawing/Screens/iPad/Layers/Controller.cs @@ -1,13 +1,11 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.Layers -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.Layers { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion diff --git a/Drawing/Screens/iPad/Layers/View.cs b/Drawing/Screens/iPad/Layers/View.cs index 4eabc2038..ae1ae7680 100644 --- a/Drawing/Screens/iPad/Layers/View.cs +++ b/Drawing/Screens/iPad/Layers/View.cs @@ -2,13 +2,11 @@ using CoreGraphics; using UIKit; -namespace Example_Drawing.Screens.iPad.Layers -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.Layers { + public class View : UIView { #region -= constructors =- - public View () : base() { } + public View () : base () { } #endregion @@ -32,7 +30,7 @@ public override void Draw (CGRect rect) // paint context.FillRect (rect); - CGPoint[] myStarPoints = { new CGPoint (5f, 5f) + CGPoint [] myStarPoints = { new CGPoint (5f, 5f) , new CGPoint (10f, 15f), new CGPoint (10f, 15f) , new CGPoint (15f, 5f), new CGPoint (15f, 5f) , new CGPoint (12f, 5f), new CGPoint (15f, 5f) diff --git a/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/Controller.cs b/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/Controller.cs index af61a116d..5a62466cf 100644 --- a/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/Controller.cs +++ b/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/Controller.cs @@ -1,14 +1,12 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.OnScreenUncorrectedTextRotation -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.OnScreenUncorrectedTextRotation { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion diff --git a/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/View.cs b/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/View.cs index 0bf888ab0..b21401448 100644 --- a/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/View.cs +++ b/Drawing/Screens/iPad/OnScreenUncorrectedTextRotation/View.cs @@ -2,13 +2,11 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.OnScreenUncorrectedTextRotation -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.OnScreenUncorrectedTextRotation { + public class View : UIView { #region -= constructors =- - public View () : base() { } + public View () : base () { } #endregion diff --git a/Drawing/Screens/iPad/Shadows/Controller.cs b/Drawing/Screens/iPad/Shadows/Controller.cs index 324d37f15..5d5840545 100644 --- a/Drawing/Screens/iPad/Shadows/Controller.cs +++ b/Drawing/Screens/iPad/Shadows/Controller.cs @@ -2,15 +2,13 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.Shadows -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.Shadows { + public class Controller : UIViewController { UIImageView imageView; #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion @@ -30,7 +28,7 @@ public override void ViewDidLoad () // create our offscreen bitmap context // size CGSize bitmapSize = new CGSize (View.Frame.Size); - using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int)bitmapSize.Width, (int)bitmapSize.Height, 8, (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { + using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int) bitmapSize.Width, (int) bitmapSize.Height, 8, (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { //==== create a grayscale shadow // 1) save graphics state diff --git a/Drawing/Screens/iPad/StencilPattern/Controller.cs b/Drawing/Screens/iPad/StencilPattern/Controller.cs index 14175351b..380ea6716 100644 --- a/Drawing/Screens/iPad/StencilPattern/Controller.cs +++ b/Drawing/Screens/iPad/StencilPattern/Controller.cs @@ -2,15 +2,13 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.StencilPattern -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.StencilPattern { + public class Controller : UIViewController { UIImageView imageView; #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion @@ -30,20 +28,20 @@ public override void ViewDidLoad () // create our offscreen bitmap context // size CGSize bitmapSize = new CGSize (View.Frame.Size); - using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int)bitmapSize.Width, (int)bitmapSize.Height, 8, (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { + using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int) bitmapSize.Width, (int) bitmapSize.Height, 8, (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { // declare vars CGRect patternRect = new CGRect (0, 0, 16, 16); // set the color space of our fill to be the patter colorspace - context.SetFillColorSpace (CGColorSpace.CreatePattern (CGColorSpace.CreateDeviceRGB())); + context.SetFillColorSpace (CGColorSpace.CreatePattern (CGColorSpace.CreateDeviceRGB ())); // create a new pattern CGPattern pattern = new CGPattern (patternRect, CGAffineTransform.MakeRotation (.3f) , 16, 16, CGPatternTiling.NoDistortion, false, DrawPolkaDotPattern); // set our fill as our pattern, color doesn't matter because the pattern handles it - context.SetFillPattern (pattern, new nfloat[] { 1, 0, 0, 1 }); + context.SetFillPattern (pattern, new nfloat [] { 1, 0, 0, 1 }); // fill the entire view with that pattern context.FillRect (imageView.Frame); @@ -72,7 +70,7 @@ protected void DrawStarPattern (CGContext context) // declare vars float starDiameter = 16; // 144º - float theta = 2 * (float)Math.PI * (2f / 5f); + float theta = 2 * (float) Math.PI * (2f / 5f); float radius = starDiameter / 2; // move up and over @@ -80,7 +78,7 @@ protected void DrawStarPattern (CGContext context) context.MoveTo (0, radius); for (int i = 1; i < 5; i++) { - context.AddLineToPoint (radius * (float)Math.Sin (i * theta), radius * (float)Math.Cos (i * theta)); + context.AddLineToPoint (radius * (float) Math.Sin (i * theta), radius * (float) Math.Cos (i * theta)); } // fill our star as dark gray context.ClosePath (); diff --git a/Drawing/Screens/iPad/TouchDrawing/Controller.cs b/Drawing/Screens/iPad/TouchDrawing/Controller.cs index ba7e60061..bf64d12c0 100644 --- a/Drawing/Screens/iPad/TouchDrawing/Controller.cs +++ b/Drawing/Screens/iPad/TouchDrawing/Controller.cs @@ -1,13 +1,11 @@ using System; using UIKit; -namespace Example_Drawing.Screens.iPad.TouchDrawing -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.TouchDrawing { + public class Controller : UIViewController { #region -= constructors =- - public Controller () : base() { } + public Controller () : base () { } #endregion diff --git a/Drawing/Screens/iPad/TouchDrawing/View.cs b/Drawing/Screens/iPad/TouchDrawing/View.cs index 5a61f7bb1..d1bf1fbe1 100644 --- a/Drawing/Screens/iPad/TouchDrawing/View.cs +++ b/Drawing/Screens/iPad/TouchDrawing/View.cs @@ -4,16 +4,14 @@ using System.Collections.Generic; using Foundation; -namespace Example_Drawing.Screens.iPad.TouchDrawing -{ - public class View : UIView - { +namespace Example_Drawing.Screens.iPad.TouchDrawing { + public class View : UIView { List touchSpots = new List (); - CGSize spotSize = new CGSize(15,15); + CGSize spotSize = new CGSize (15, 15); #region -= constructors =- - public View () : base() { } + public View () : base () { } #endregion @@ -64,21 +62,20 @@ protected void AddSpot (UITouch touch) SetNeedsDisplay (); } - protected class Spot - { + protected class Spot { public CGPoint Point { get; set; } public float Red { get; set; } public float Green { get; set; } public float Blue { get; set; } public float Alpha { get; set; } - public static Spot CreateNewRandomColor(CGPoint point) + public static Spot CreateNewRandomColor (CGPoint point) { Random rdm = new Random (Environment.TickCount); Spot spot = new View.Spot () { - Red = (float)rdm.NextDouble (), - Green = (float)rdm.NextDouble (), - Blue = (float)rdm.NextDouble (), + Red = (float) rdm.NextDouble (), + Green = (float) rdm.NextDouble (), + Blue = (float) rdm.NextDouble (), Alpha = 1 }; spot.Point = point; diff --git a/Drawing/Screens/iPad/Transformations/Controller.cs b/Drawing/Screens/iPad/Transformations/Controller.cs index 92cc79f50..fff762cad 100644 --- a/Drawing/Screens/iPad/Transformations/Controller.cs +++ b/Drawing/Screens/iPad/Transformations/Controller.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace Example_Drawing.Screens.iPad.Transformations -{ - public class Controller : UIViewController - { +namespace Example_Drawing.Screens.iPad.Transformations { + public class Controller : UIViewController { UIImageView imageView; UIButton btnUp; @@ -19,15 +17,15 @@ public class Controller : UIViewController UIButton btnScaleDown; float currentScale, initialScale = 1.0f; - CGPoint currentLocation, initialLocation = new CGPoint(380, 500); - float currentRotation , initialRotation = 0; + CGPoint currentLocation, initialLocation = new CGPoint (380, 500); + float currentRotation, initialRotation = 0; float movementIncrement = 20; - float rotationIncrement = (float)(Math.PI * 2 / 16); + float rotationIncrement = (float) (Math.PI * 2 / 16); float scaleIncrement = 1.5f; #region -= constructors =- - public Controller () : base() + public Controller () : base () { currentScale = initialScale; currentLocation = initialLocation; @@ -61,7 +59,7 @@ protected void DrawScreen () // create our offscreen bitmap context // size CGSize bitmapSize = new CGSize (imageView.Frame.Size); - using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int)bitmapSize.Width, (int)bitmapSize.Height, 8, (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { + using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int) bitmapSize.Width, (int) bitmapSize.Height, 8, (int) (4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { // save the state of the context while we change the CTM context.SaveState (); @@ -105,42 +103,51 @@ protected void InitializeButtons () InitButton (ref btnScaleDown, new CGPoint (635, 180), 75, "-"); View.AddSubview (btnScaleDown); - btnReset.TouchUpInside += delegate { + btnReset.TouchUpInside += delegate + { currentScale = initialScale; currentLocation = initialLocation; currentRotation = initialRotation; - DrawScreen(); + DrawScreen (); }; - btnUp.TouchUpInside += delegate { + btnUp.TouchUpInside += delegate + { currentLocation.Y += movementIncrement; DrawScreen (); }; - btnDown.TouchUpInside += delegate { + btnDown.TouchUpInside += delegate + { currentLocation.Y -= movementIncrement; DrawScreen (); }; - btnLeft.TouchUpInside += delegate { + btnLeft.TouchUpInside += delegate + { currentLocation.X -= movementIncrement; DrawScreen (); }; - btnRight.TouchUpInside += delegate { + btnRight.TouchUpInside += delegate + { currentLocation.X += movementIncrement; DrawScreen (); }; - btnScaleUp.TouchUpInside += delegate { + btnScaleUp.TouchUpInside += delegate + { currentScale = currentScale * scaleIncrement; DrawScreen (); }; - btnScaleDown.TouchUpInside += delegate { + btnScaleDown.TouchUpInside += delegate + { currentScale = currentScale / scaleIncrement; DrawScreen (); }; - btnRotateLeft.TouchUpInside += delegate { + btnRotateLeft.TouchUpInside += delegate + { currentRotation += rotationIncrement; DrawScreen (); }; - btnRotateRight.TouchUpInside += delegate { + btnRotateRight.TouchUpInside += delegate + { currentRotation -= rotationIncrement; DrawScreen (); }; @@ -207,7 +214,7 @@ protected void DrawCoordinateSpace (CGBitmapContext context) if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points - Math.DivRem ((int)yPos, (int)80, out remainder); + Math.DivRem ((int) yPos, (int) 80, out remainder); if (remainder == 0) DrawTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight); } @@ -237,7 +244,7 @@ protected void DrawCoordinateSpace (CGBitmapContext context) if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points - Math.DivRem ((int)xPos, (int)80, out remainder); + Math.DivRem ((int) xPos, (int) 80, out remainder); if (remainder == 0) DrawCenteredTextAtPoint (context, xPos, 30, xPos.ToString (), textHeight); } diff --git a/DynamicsCatalog/DynamicsCatalog/AppDelegate.cs b/DynamicsCatalog/DynamicsCatalog/AppDelegate.cs index 1fdd26246..3fa751f51 100644 --- a/DynamicsCatalog/DynamicsCatalog/AppDelegate.cs +++ b/DynamicsCatalog/DynamicsCatalog/AppDelegate.cs @@ -5,8 +5,7 @@ namespace DynamicsCatalog { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } } diff --git a/DynamicsCatalog/DynamicsCatalog/CollisionGravitySpringViewController.cs b/DynamicsCatalog/DynamicsCatalog/CollisionGravitySpringViewController.cs index 07cf6fe9e..ebcae723a 100644 --- a/DynamicsCatalog/DynamicsCatalog/CollisionGravitySpringViewController.cs +++ b/DynamicsCatalog/DynamicsCatalog/CollisionGravitySpringViewController.cs @@ -22,10 +22,10 @@ public override void ViewDidLoad () TranslatesReferenceBoundsIntoBoundary = true }; collisionBehavior.BeganBoundaryContact += (sender, e) => { - ((UIView)e.DynamicItem).BackgroundColor = UIColor.LightGray; + ((UIView) e.DynamicItem).BackgroundColor = UIColor.LightGray; }; collisionBehavior.EndedBoundaryContact += (sender, e) => { - ((UIView)e.DynamicItem).BackgroundColor = UIColor.Gray; + ((UIView) e.DynamicItem).BackgroundColor = UIColor.Gray; }; var squareCenterPoint = new CGPoint (square.Center.X, square.Center.Y - 100); diff --git a/DynamicsCatalog/DynamicsCatalog/CollisionGravityViewController.cs b/DynamicsCatalog/DynamicsCatalog/CollisionGravityViewController.cs index 5dcfd17be..cb2cfefd5 100644 --- a/DynamicsCatalog/DynamicsCatalog/CollisionGravityViewController.cs +++ b/DynamicsCatalog/DynamicsCatalog/CollisionGravityViewController.cs @@ -21,10 +21,10 @@ public override void ViewDidLoad () TranslatesReferenceBoundsIntoBoundary = true }; collisionBehavior.BeganBoundaryContact += (sender, e) => { - ((UIView)e.DynamicItem).BackgroundColor = UIColor.LightGray; + ((UIView) e.DynamicItem).BackgroundColor = UIColor.LightGray; }; collisionBehavior.EndedBoundaryContact += (sender, e) => { - ((UIView)e.DynamicItem).BackgroundColor = UIColor.Gray; + ((UIView) e.DynamicItem).BackgroundColor = UIColor.Gray; }; // Another style of creating the UIDynamicAnimator diff --git a/DynamicsCatalog/DynamicsCatalog/InstantaneousPushViewController.cs b/DynamicsCatalog/DynamicsCatalog/InstantaneousPushViewController.cs index 0ab904951..11097fa6e 100644 --- a/DynamicsCatalog/DynamicsCatalog/InstantaneousPushViewController.cs +++ b/DynamicsCatalog/DynamicsCatalog/InstantaneousPushViewController.cs @@ -17,7 +17,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); var collisionBehavior = new UICollisionBehavior (square) { - TranslatesReferenceBoundsIntoBoundary = true + TranslatesReferenceBoundsIntoBoundary = true }; var pushBehavior = new UIPushBehavior (UIPushBehaviorMode.Instantaneous, square) { @@ -39,8 +39,8 @@ the angle and magnitude of this vector is briefly drawn. */ CGPoint p = gesture.LocationInView (View); CGPoint o = new CGPoint (View.Bounds.GetMidX (), View.Bounds.GetMidY ()); - float distance = (float)Math.Sqrt ((p.X - o.X) * (p.X - o.X) + (p.Y - o.Y) * (p.Y - o.Y)); - float angle = (float)Math.Atan2 (p.Y - o.Y, p.X - o.X); + float distance = (float) Math.Sqrt ((p.X - o.X) * (p.X - o.X) + (p.Y - o.Y) * (p.Y - o.Y)); + float angle = (float) Math.Atan2 (p.Y - o.Y, p.X - o.X); distance = Math.Min (distance, 100.0f); redSquare.Bounds = new CGRect (0.0f, 0.0f, distance, 5.0f); diff --git a/DynamicsCatalog/DynamicsCatalog/ItemPropertiesViewController.cs b/DynamicsCatalog/DynamicsCatalog/ItemPropertiesViewController.cs index 98a121b1e..7df2e626f 100644 --- a/DynamicsCatalog/DynamicsCatalog/ItemPropertiesViewController.cs +++ b/DynamicsCatalog/DynamicsCatalog/ItemPropertiesViewController.cs @@ -26,10 +26,10 @@ these views. TranslatesReferenceBoundsIntoBoundary = true }; collisionBehavior.BeganBoundaryContact += (sender, e) => { - ((UIView)e.DynamicItem).BackgroundColor = UIColor.LightGray; + ((UIView) e.DynamicItem).BackgroundColor = UIColor.LightGray; }; collisionBehavior.EndedBoundaryContact += (sender, e) => { - ((UIView)e.DynamicItem).BackgroundColor = UIColor.Gray; + ((UIView) e.DynamicItem).BackgroundColor = UIColor.Gray; }; var propertiesBehavior = new UIDynamicItemBehavior (square2) { diff --git a/DynamicsCatalog/DynamicsCatalog/Main.cs b/DynamicsCatalog/DynamicsCatalog/Main.cs index d0c46a0a9..557bb7980 100644 --- a/DynamicsCatalog/DynamicsCatalog/Main.cs +++ b/DynamicsCatalog/DynamicsCatalog/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace DynamicsCatalog -{ - public class Application - { +namespace DynamicsCatalog { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/FileSystemSampleCode/FileSystem/AppDelegate.cs b/FileSystemSampleCode/FileSystem/AppDelegate.cs index 83b514bb7..ec1cc4e95 100644 --- a/FileSystemSampleCode/FileSystem/AppDelegate.cs +++ b/FileSystemSampleCode/FileSystem/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace FileSystem -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace FileSystem { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/FileSystemSampleCode/FileSystem/DataManager.cs b/FileSystemSampleCode/FileSystem/DataManager.cs index 31a8fff0e..0798d09e6 100644 --- a/FileSystemSampleCode/FileSystem/DataManager.cs +++ b/FileSystemSampleCode/FileSystem/DataManager.cs @@ -5,109 +5,103 @@ using System.Text; using System.Xml.Serialization; -namespace FileSystem -{ - /// - /// This class contains the code shown in the article "Working with the File System" - /// - public static class DataManager - { - public static string ReadText() - { - var text = File.ReadAllText("TestData/ReadMe.txt"); - Console.WriteLine(text); - - return text; - } - - public static string ReadDirectories() - { - var result = new StringBuilder(); - - var directories = Directory.EnumerateDirectories("./"); - foreach (var directory in directories) - { - result.AppendLine(directory); - Console.WriteLine(directory); - } - - return result.ToString(); - } - - public static string ReadAll() - { - var result = new StringBuilder(); - - var fileOrDirectory = Directory.EnumerateFileSystemEntries("./"); - foreach (var entry in fileOrDirectory) - { - result.AppendLine(entry); - Console.WriteLine(entry); - } - - return result.ToString(); - } - - public static string ReadXml() - { - var result = string.Empty; - - using (TextReader reader = new StreamReader("TestData/Test.xml")) - { - var serializer = new XmlSerializer(typeof(TestXml)); - var xml = serializer.Deserialize(reader) as TestXml; - - result = "XML was deserialized." + Environment.NewLine - + "-----------------" + Environment.NewLine + Environment.NewLine - + "Title: " + xml.Title + Environment.NewLine - + "Description: " + xml.Description; - } - - return result; - } - - public static string WriteFile() - { - var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - var filename = Path.Combine(documents, "Write.txt"); - File.WriteAllText(filename, "Write this text into a file!"); - - return "Text was written to a file." + Environment.NewLine - + "-----------------" + Environment.NewLine - + File.ReadAllText(filename); - } - - public static string WriteJson() - { - // Create a new record - var account = new Account() - { - Email = "monkey@xamarin.com", - Active = true, - CreatedDate = new DateTime(2015, 5, 27, 0, 0, 0, DateTimeKind.Utc), - Roles = new List { "User", "Admin" } - }; - - // Serialize object - var json = JsonConvert.SerializeObject(account, Formatting.Indented); - - // Save to file - var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - var filename = Path.Combine(documents, "account.json"); - File.WriteAllText(filename, json); - - return json; - } - - public static string CreateDirectory() - { - var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); - var directoryName = Path.Combine(documents, "NewDirectory"); - Directory.CreateDirectory(directoryName); - - return "A directory was created." + Environment.NewLine - + "-----------------" + Environment.NewLine - + directoryName; - } - } -} \ No newline at end of file +namespace FileSystem { + /// + /// This class contains the code shown in the article "Working with the File System" + /// + public static class DataManager { + public static string ReadText () + { + var text = File.ReadAllText ("TestData/ReadMe.txt"); + Console.WriteLine (text); + + return text; + } + + public static string ReadDirectories () + { + var result = new StringBuilder (); + + var directories = Directory.EnumerateDirectories ("./"); + foreach (var directory in directories) { + result.AppendLine (directory); + Console.WriteLine (directory); + } + + return result.ToString (); + } + + public static string ReadAll () + { + var result = new StringBuilder (); + + var fileOrDirectory = Directory.EnumerateFileSystemEntries ("./"); + foreach (var entry in fileOrDirectory) { + result.AppendLine (entry); + Console.WriteLine (entry); + } + + return result.ToString (); + } + + public static string ReadXml () + { + var result = string.Empty; + + using (TextReader reader = new StreamReader ("TestData/Test.xml")) { + var serializer = new XmlSerializer (typeof (TestXml)); + var xml = serializer.Deserialize (reader) as TestXml; + + result = "XML was deserialized." + Environment.NewLine + + "-----------------" + Environment.NewLine + Environment.NewLine + + "Title: " + xml.Title + Environment.NewLine + + "Description: " + xml.Description; + } + + return result; + } + + public static string WriteFile () + { + var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); + var filename = Path.Combine (documents, "Write.txt"); + File.WriteAllText (filename, "Write this text into a file!"); + + return "Text was written to a file." + Environment.NewLine + + "-----------------" + Environment.NewLine + + File.ReadAllText (filename); + } + + public static string WriteJson () + { + // Create a new record + var account = new Account () { + Email = "monkey@xamarin.com", + Active = true, + CreatedDate = new DateTime (2015, 5, 27, 0, 0, 0, DateTimeKind.Utc), + Roles = new List { "User", "Admin" } + }; + + // Serialize object + var json = JsonConvert.SerializeObject (account, Formatting.Indented); + + // Save to file + var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); + var filename = Path.Combine (documents, "account.json"); + File.WriteAllText (filename, json); + + return json; + } + + public static string CreateDirectory () + { + var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); + var directoryName = Path.Combine (documents, "NewDirectory"); + Directory.CreateDirectory (directoryName); + + return "A directory was created." + Environment.NewLine + + "-----------------" + Environment.NewLine + + directoryName; + } + } +} diff --git a/FileSystemSampleCode/FileSystem/Main.cs b/FileSystemSampleCode/FileSystem/Main.cs index 4b0184f1e..308fca092 100644 --- a/FileSystemSampleCode/FileSystem/Main.cs +++ b/FileSystemSampleCode/FileSystem/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace FileSystem -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace FileSystem { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/FileSystemSampleCode/FileSystem/Models.cs b/FileSystemSampleCode/FileSystem/Models.cs index 93019d666..2da9fbc2a 100644 --- a/FileSystemSampleCode/FileSystem/Models.cs +++ b/FileSystemSampleCode/FileSystem/Models.cs @@ -1,30 +1,27 @@ -using Foundation; +using Foundation; using System; using System.Collections.Generic; -namespace FileSystem -{ - [Preserve] - public class TestXml - { - public string Title { get; set; } +namespace FileSystem { + [Preserve] + public class TestXml { + public string Title { get; set; } - public string Description { get; set; } - } + public string Description { get; set; } + } - // We use the Preserve attribute to ensure that all the properties of the object - // are preserve even when the linker is ran on the assembly. The reasoning - // for this pattern is to ensure that libraries, such as Newsoft.Json, that use - // reflection can find properties that could be removed by the linker. - [Preserve] - public class Account - { - public string Email { get; set; } + // We use the Preserve attribute to ensure that all the properties of the object + // are preserve even when the linker is ran on the assembly. The reasoning + // for this pattern is to ensure that libraries, such as Newsoft.Json, that use + // reflection can find properties that could be removed by the linker. + [Preserve] + public class Account { + public string Email { get; set; } - public bool Active { get; set; } + public bool Active { get; set; } - public DateTime CreatedDate { get; set; } + public DateTime CreatedDate { get; set; } - public List Roles { get; set; } - } -} \ No newline at end of file + public List Roles { get; set; } + } +} diff --git a/FileSystemSampleCode/FileSystem/ViewController.cs b/FileSystemSampleCode/FileSystem/ViewController.cs index 0c46505ab..54b5a2e3f 100644 --- a/FileSystemSampleCode/FileSystem/ViewController.cs +++ b/FileSystemSampleCode/FileSystem/ViewController.cs @@ -1,52 +1,47 @@ -using System; +using System; using UIKit; -namespace FileSystem -{ - public partial class ViewController : UIViewController - { - private bool writeJson = true; - - protected ViewController(IntPtr handle) : base(handle) { } - - partial void OpenReadMe(UIButton sender) - { - textView.Text = DataManager.ReadText(); - } - - partial void OpenTestFile(UIButton sender) - { - textView.Text = DataManager.ReadXml(); - } - - partial void ListDirectories(UIButton sender) - { - textView.Text = DataManager.ReadDirectories(); - } - - partial void ListAll(UIButton sender) - { - textView.Text = DataManager.ReadAll(); - } - - partial void WriteFile(UIButton sender) - { - var text = string.Empty; - if (writeJson) - { - text = DataManager.WriteJson(); - } - else - { - text = DataManager.WriteFile(); - } - - textView.Text = text; - } - - partial void CreateDirectory(UIButton sender) - { - textView.Text = DataManager.CreateDirectory(); - } - } -} \ No newline at end of file +namespace FileSystem { + public partial class ViewController : UIViewController { + private bool writeJson = true; + + protected ViewController (IntPtr handle) : base (handle) { } + + partial void OpenReadMe (UIButton sender) + { + textView.Text = DataManager.ReadText (); + } + + partial void OpenTestFile (UIButton sender) + { + textView.Text = DataManager.ReadXml (); + } + + partial void ListDirectories (UIButton sender) + { + textView.Text = DataManager.ReadDirectories (); + } + + partial void ListAll (UIButton sender) + { + textView.Text = DataManager.ReadAll (); + } + + partial void WriteFile (UIButton sender) + { + var text = string.Empty; + if (writeJson) { + text = DataManager.WriteJson (); + } else { + text = DataManager.WriteFile (); + } + + textView.Text = text; + } + + partial void CreateDirectory (UIButton sender) + { + textView.Text = DataManager.CreateDirectory (); + } + } +} diff --git a/FontList/FontList/AppDelegate.cs b/FontList/FontList/AppDelegate.cs index 72e13f987..e13ca50c2 100644 --- a/FontList/FontList/AppDelegate.cs +++ b/FontList/FontList/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace FontList -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace FontList { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/FontList/FontList/FontDetailsViewController.cs b/FontList/FontList/FontDetailsViewController.cs index 044730c83..8b7596c6d 100644 --- a/FontList/FontList/FontDetailsViewController.cs +++ b/FontList/FontList/FontDetailsViewController.cs @@ -2,20 +2,18 @@ using System; using UIKit; -namespace FontList -{ - public partial class FontDetailsViewController : UIViewController - { - public FontDetailsViewController(IntPtr handle) : base(handle) { } +namespace FontList { + public partial class FontDetailsViewController : UIViewController { + public FontDetailsViewController (IntPtr handle) : base (handle) { } - public FontItem FontItem { get; internal set; } + public FontItem FontItem { get; internal set; } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - Title = FontItem.Name; - textView.Font = FontItem.Font; - } - } -} \ No newline at end of file + Title = FontItem.Name; + textView.Font = FontItem.Font; + } + } +} diff --git a/FontList/FontList/FontsViewController.cs b/FontList/FontList/FontsViewController.cs index 6fb4499f2..a15926a4b 100644 --- a/FontList/FontList/FontsViewController.cs +++ b/FontList/FontList/FontsViewController.cs @@ -5,96 +5,86 @@ using System.Linq; using UIKit; -namespace FontList -{ - public partial class FontsViewController : UITableViewController - { - private const string CellIdentifier = "FontCellView"; - private const string FontDetailsSegueIdentifier = "fontDetailsSegue"; - - private readonly List items = new List(); - - private FontItem selectedItem; - - public FontsViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - foreach (var fontFamily in UIFont.FamilyNames) - { - // create a nav group - var group = new FontFamilyItem(fontFamily); - - var fontNames = UIFont.FontNamesForFamilyName(fontFamily); - if (fontNames.Any()) - { - foreach (var fontName in fontNames) - { - var font = UIFont.FromName(fontName, UIFont.LabelFontSize); - if (font != null) - { - group.Items.Add(new FontItem { Name = fontName, Font = font }); - } - } - } - else - { - var font = UIFont.FromName(fontFamily, UIFont.LabelFontSize); - group.Items.Add(new FontItem { Name = fontFamily, Font = font }); - } - - items.Add(group); - } - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (!string.IsNullOrEmpty(segue?.Identifier) && segue.Identifier == FontDetailsSegueIdentifier) - { - if (segue.DestinationViewController is FontDetailsViewController controller) - { - controller.FontItem = selectedItem; - selectedItem = null; - } - } - } - - #region table delegate - - public override nint NumberOfSections(UITableView tableView) - { - return items.Count; - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return items[(int)section].Items.Count; - } - - public override string TitleForHeader(UITableView tableView, nint section) - { - return items[(int)section].Name; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var item = items[indexPath.Section].Items[indexPath.Row]; - - var cell = tableView.DequeueReusableCell(CellIdentifier); - cell.TextLabel.Text = item.Name; - cell.TextLabel.Font = item.Font; - - return cell; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - selectedItem = items[indexPath.Section].Items[indexPath.Row]; - PerformSegue(FontDetailsSegueIdentifier, this); - } - - #endregion - } -} \ No newline at end of file +namespace FontList { + public partial class FontsViewController : UITableViewController { + private const string CellIdentifier = "FontCellView"; + private const string FontDetailsSegueIdentifier = "fontDetailsSegue"; + + private readonly List items = new List (); + + private FontItem selectedItem; + + public FontsViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + foreach (var fontFamily in UIFont.FamilyNames) { + // create a nav group + var group = new FontFamilyItem (fontFamily); + + var fontNames = UIFont.FontNamesForFamilyName (fontFamily); + if (fontNames.Any ()) { + foreach (var fontName in fontNames) { + var font = UIFont.FromName (fontName, UIFont.LabelFontSize); + if (font != null) { + group.Items.Add (new FontItem { Name = fontName, Font = font }); + } + } + } else { + var font = UIFont.FromName (fontFamily, UIFont.LabelFontSize); + group.Items.Add (new FontItem { Name = fontFamily, Font = font }); + } + + items.Add (group); + } + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (!string.IsNullOrEmpty (segue?.Identifier) && segue.Identifier == FontDetailsSegueIdentifier) { + if (segue.DestinationViewController is FontDetailsViewController controller) { + controller.FontItem = selectedItem; + selectedItem = null; + } + } + } + + #region table delegate + + public override nint NumberOfSections (UITableView tableView) + { + return items.Count; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return items [(int) section].Items.Count; + } + + public override string TitleForHeader (UITableView tableView, nint section) + { + return items [(int) section].Name; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var item = items [indexPath.Section].Items [indexPath.Row]; + + var cell = tableView.DequeueReusableCell (CellIdentifier); + cell.TextLabel.Text = item.Name; + cell.TextLabel.Font = item.Font; + + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + selectedItem = items [indexPath.Section].Items [indexPath.Row]; + PerformSegue (FontDetailsSegueIdentifier, this); + } + + #endregion + } +} diff --git a/FontList/FontList/Main.cs b/FontList/FontList/Main.cs index b858266ec..605329071 100644 --- a/FontList/FontList/Main.cs +++ b/FontList/FontList/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace FontList -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace FontList { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/FontList/FontList/Models/FontFamilyItem.cs b/FontList/FontList/Models/FontFamilyItem.cs index c388befaa..00346dd12 100644 --- a/FontList/FontList/Models/FontFamilyItem.cs +++ b/FontList/FontList/Models/FontFamilyItem.cs @@ -1,24 +1,22 @@ using System.Collections.Generic; -namespace FontList.Models -{ - /// - /// A group that contains table items - /// - public class FontFamilyItem - { - public string Name { get; set; } +namespace FontList.Models { + /// + /// A group that contains table items + /// + public class FontFamilyItem { + public string Name { get; set; } - public List Items { get; set; } + public List Items { get; set; } - public FontFamilyItem() - { - Items = new List(); - } + public FontFamilyItem () + { + Items = new List (); + } - public FontFamilyItem(string name) : this() - { - Name = name; - } - } -} \ No newline at end of file + public FontFamilyItem (string name) : this () + { + Name = name; + } + } +} diff --git a/FontList/FontList/Models/FontItem.cs b/FontList/FontList/Models/FontItem.cs index 7c6446f1f..84f6cdf8e 100644 --- a/FontList/FontList/Models/FontItem.cs +++ b/FontList/FontList/Models/FontItem.cs @@ -1,17 +1,15 @@ using UIKit; -namespace FontList.Models -{ - public class FontItem - { - /// - /// The name of the nav item, shows up as the label - /// - public string Name { get; set; } +namespace FontList.Models { + public class FontItem { + /// + /// The name of the nav item, shows up as the label + /// + public string Name { get; set; } - /// - /// The font used to display the item. - /// - public UIFont Font { get; set; } - } -} \ No newline at end of file + /// + /// The font used to display the item. + /// + public UIFont Font { get; set; } + } +} diff --git a/FrogScroller/FrogScroller/AppDelegate.cs b/FrogScroller/FrogScroller/AppDelegate.cs index c7b0f9c64..3a57721e6 100644 --- a/FrogScroller/FrogScroller/AppDelegate.cs +++ b/FrogScroller/FrogScroller/AppDelegate.cs @@ -3,15 +3,13 @@ using Foundation; using UIKit; -namespace FrogScroller -{ +namespace FrogScroller { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UIPageViewController viewController; - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } @@ -26,7 +24,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // kick things off by making the first page ImageViewController pageZero = ImageViewController.ImageViewControllerForPageIndex (0); - viewController.SetViewControllers (new UIViewController[] { pageZero }, + viewController.SetViewControllers (new UIViewController [] { pageZero }, UIPageViewControllerNavigationDirection.Forward, false, null); viewController.DataSource = new MyDataSource (); @@ -38,20 +36,19 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) } //DataSource PageIndexing - class MyDataSource : UIPageViewControllerDataSource - { + class MyDataSource : UIPageViewControllerDataSource { public override UIViewController GetPreviousViewController (UIPageViewController pageViewController, - UIViewController referenceViewController) + UIViewController referenceViewController) { - int index = ((ImageViewController)referenceViewController).PageIndex; - return (ImageViewController)ImageViewController.ImageViewControllerForPageIndex (index - 1); + int index = ((ImageViewController) referenceViewController).PageIndex; + return (ImageViewController) ImageViewController.ImageViewControllerForPageIndex (index - 1); } public override UIViewController GetNextViewController (UIPageViewController pageViewController, - UIViewController referenceViewController) + UIViewController referenceViewController) { - int index = ((ImageViewController)referenceViewController).PageIndex; - return (ImageViewController)ImageViewController.ImageViewControllerForPageIndex (index + 1); + int index = ((ImageViewController) referenceViewController).PageIndex; + return (ImageViewController) ImageViewController.ImageViewControllerForPageIndex (index + 1); } } } diff --git a/FrogScroller/FrogScroller/ImageDetails.cs b/FrogScroller/FrogScroller/ImageDetails.cs index fb61a0625..a51d981fb 100644 --- a/FrogScroller/FrogScroller/ImageDetails.cs +++ b/FrogScroller/FrogScroller/ImageDetails.cs @@ -1,13 +1,11 @@ -using System; +using System; using CoreGraphics; -namespace FrogScroller -{ +namespace FrogScroller { /// /// Class to hold FrogImage properties /// - public class ImageDetails - { + public class ImageDetails { public float Height { get; set; } public string Name { get; set; } diff --git a/FrogScroller/FrogScroller/ImageScrollView.cs b/FrogScroller/FrogScroller/ImageScrollView.cs index f5b7ace7d..394b0db21 100644 --- a/FrogScroller/FrogScroller/ImageScrollView.cs +++ b/FrogScroller/FrogScroller/ImageScrollView.cs @@ -8,10 +8,8 @@ using Foundation; using UIKit; -namespace FrogScroller -{ - public class ImageScrollView : UIScrollView - { +namespace FrogScroller { + public class ImageScrollView : UIScrollView { // turn on to use tiled images, if off, we use whole images bool TileImagesMode = true; @@ -61,7 +59,7 @@ public int Index { set { _index = value; - if(TileImagesMode) + if (TileImagesMode) DisplayTiledImageNamed (ImageNameAtIndex (_index), ImageSizeAtIndex (_index)); else DisplayImage (ImageAtIndex (_index)); @@ -162,7 +160,7 @@ public void SetMaxMinZoomScalesForCurrentBounds () //fill width if the image and phone are both portrait or both landscape; otherwise take smaller scale bool imagePortrait = _imageSize.Height > _imageSize.Width; bool phonePortrait = boundsSize.Height > boundsSize.Width; - var minScale = (nfloat)(imagePortrait == phonePortrait ? xScale : NMath.Min (xScale, yScale)); + var minScale = (nfloat) (imagePortrait == phonePortrait ? xScale : NMath.Min (xScale, yScale)); //on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the maximum zoom scale to 0.5 nfloat maxScale = 1 / UIScreen.MainScreen.Scale; @@ -180,7 +178,7 @@ public void SetMaxMinZoomScalesForCurrentBounds () // Rotation support public void PrepareToResize () { - var boundsCenter = new CGPoint (Bounds.GetMidX(), Bounds.GetMidY()); + var boundsCenter = new CGPoint (Bounds.GetMidX (), Bounds.GetMidY ()); _pointToCenterAfterResize = ConvertPointToView (boundsCenter, zoomView); _scaleToRestoreAfterResize = ZoomScale; // If we're at the minimum zoom scale, preserve that by returning 0, which will be converted to the minimum @@ -258,8 +256,8 @@ static List FetchImageData () try { using (TextReader reader = new StreamReader (path)) { - XmlSerializer serializer = new XmlSerializer (typeof(List)); - result = (List)serializer.Deserialize (reader); + XmlSerializer serializer = new XmlSerializer (typeof (List)); + result = (List) serializer.Deserialize (reader); } } catch (XmlException e) { Console.WriteLine (e); diff --git a/FrogScroller/FrogScroller/ImageViewController.cs b/FrogScroller/FrogScroller/ImageViewController.cs index e182a5579..4df6d4e3e 100644 --- a/FrogScroller/FrogScroller/ImageViewController.cs +++ b/FrogScroller/FrogScroller/ImageViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace FrogScroller -{ - public partial class ImageViewController : UIViewController - { +namespace FrogScroller { + public partial class ImageViewController : UIViewController { public ImageViewController (int pageIndex) { PageIndex = pageIndex; diff --git a/FrogScroller/FrogScroller/TilingView.cs b/FrogScroller/FrogScroller/TilingView.cs index 1c9782616..cae7ce1a6 100644 --- a/FrogScroller/FrogScroller/TilingView.cs +++ b/FrogScroller/FrogScroller/TilingView.cs @@ -6,14 +6,12 @@ using UIKit; using System.IO; -namespace FrogScroller -{ - public class TilingView : UIView - { +namespace FrogScroller { + public class TilingView : UIView { [Export ("layerClass")] public static Class LayerClass () { - return new Class (typeof(CATiledLayer)); + return new Class (typeof (CATiledLayer)); } string ImageName { get; set; } @@ -22,7 +20,7 @@ public TilingView (string name, CGSize size) : base (new CGRect (CGPoint.Empty, size)) { ImageName = name; - var tiledLayer = (CATiledLayer)this.Layer; + var tiledLayer = (CATiledLayer) this.Layer; tiledLayer.LevelsOfDetail = 4; } // to handle the interaction between CATiledLayer and high resolution screens, we need to always keep the @@ -43,7 +41,7 @@ public override void Draw (CGRect rect) // its "a" component, which is one of the two scale components. We could also ask for "d". // This assumes (safely) that the view is being scaled equally in both dimensions. var scale = context.GetCTM ().xx; - CATiledLayer tiledLayer = (CATiledLayer)this.Layer; + CATiledLayer tiledLayer = (CATiledLayer) this.Layer; var tileSize = tiledLayer.TileSize; // Even at scales lower than 100%, we are drawing into a rect in the coordinate system of the full @@ -58,15 +56,15 @@ public override void Draw (CGRect rect) tileSize.Height /= scale; // calculate the rows and columns of tiles that intersect the rect we have been asked to draw - int firstCol = (int)Math.Floor (rect.GetMinX () / tileSize.Width); - int lastCol = (int)Math.Floor ((rect.GetMaxX () - 1) / tileSize.Width); - int firstRow = (int)Math.Floor (rect.GetMinY () / tileSize.Height); - int lastRow = (int)Math.Floor ((rect.GetMaxY () - 1) / tileSize.Height); + int firstCol = (int) Math.Floor (rect.GetMinX () / tileSize.Width); + int lastCol = (int) Math.Floor ((rect.GetMaxX () - 1) / tileSize.Width); + int firstRow = (int) Math.Floor (rect.GetMinY () / tileSize.Height); + int lastRow = (int) Math.Floor ((rect.GetMaxY () - 1) / tileSize.Height); for (int row = firstRow; row <= lastRow; row++) { for (int col = firstCol; col <= lastCol; col++) { - UIImage tile = TileForScale ((float)scale, row, col); + UIImage tile = TileForScale ((float) scale, row, col); var tileRect = new CGRect (tileSize.Width * col, tileSize.Height * row, tileSize.Width, tileSize.Height); // if the tile would stick outside of our bounds, we need to truncate it so as to avoid // stretching out the partial tiles at the right and bottom edges @@ -80,7 +78,7 @@ public override void Draw (CGRect rect) public UIImage TileForScale (float scale, int row, int col) { // we use "FromFile" instead of "FromBundle" here because we don't want UIImage to cache our tiles - string tileNameWithExt = string.Format ("{0}_{1}_{2}_{3}.png", ImageName, (int)(scale * 1000), col, row); + string tileNameWithExt = string.Format ("{0}_{1}_{2}_{3}.png", ImageName, (int) (scale * 1000), col, row); string tilePath = Path.Combine ("Image", "ImageTiles", tileNameWithExt); UIImage img = UIImage.FromFile (tilePath); diff --git a/GLCameraRipple/GLCameraRipple/AppDelegate.cs b/GLCameraRipple/GLCameraRipple/AppDelegate.cs index f83814706..9f1e8c1e3 100644 --- a/GLCameraRipple/GLCameraRipple/AppDelegate.cs +++ b/GLCameraRipple/GLCameraRipple/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace GLCameraRipple -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace GLCameraRipple { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/GLCameraRipple/GLCameraRipple/Helpers/DataOutputDelegate.cs b/GLCameraRipple/GLCameraRipple/Helpers/DataOutputDelegate.cs index be62473a2..cdd67a66a 100644 --- a/GLCameraRipple/GLCameraRipple/Helpers/DataOutputDelegate.cs +++ b/GLCameraRipple/GLCameraRipple/Helpers/DataOutputDelegate.cs @@ -1,99 +1,86 @@ -using AVFoundation; +using AVFoundation; using CoreMedia; using CoreVideo; using OpenTK.Graphics.ES20; using System; -namespace GLCameraRipple.Helpers -{ - class DataOutputDelegate : AVCaptureVideoDataOutputSampleBufferDelegate - { - private WeakReference viewControllerReference; +namespace GLCameraRipple.Helpers { + class DataOutputDelegate : AVCaptureVideoDataOutputSampleBufferDelegate { + private WeakReference viewControllerReference; - private CVOpenGLESTexture lumaTexture, chromaTexture; + private CVOpenGLESTexture lumaTexture, chromaTexture; - private int textureWidth, textureHeight; + private int textureWidth, textureHeight; - public DataOutputDelegate(ViewController container) - { - this.viewControllerReference = new WeakReference(container); - } + public DataOutputDelegate (ViewController container) + { + this.viewControllerReference = new WeakReference (container); + } - public override void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) - { - try - { - using (var pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer) - { - int width = (int)pixelBuffer.Width; - int height = (int)pixelBuffer.Height; + public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + { + try { + using (var pixelBuffer = sampleBuffer.GetImageBuffer () as CVPixelBuffer) { + int width = (int) pixelBuffer.Width; + int height = (int) pixelBuffer.Height; - if (this.viewControllerReference.TryGetTarget(out var container)) - { - if (container.Ripple == null || width != this.textureWidth || height != this.textureHeight) - { - this.textureWidth = width; - this.textureHeight = height; - container.SetupRipple(this.textureWidth, this.textureHeight); - } + if (this.viewControllerReference.TryGetTarget (out var container)) { + if (container.Ripple == null || width != this.textureWidth || height != this.textureHeight) { + this.textureWidth = width; + this.textureHeight = height; + container.SetupRipple (this.textureWidth, this.textureHeight); + } - this.CleanupTextures(); + this.CleanupTextures (); - // Y-plane - GL.ActiveTexture(TextureUnit.Texture0); - All re = (All)0x1903; // GL_RED_EXT, RED component from ARB OpenGL extension + // Y-plane + GL.ActiveTexture (TextureUnit.Texture0); + All re = (All) 0x1903; // GL_RED_EXT, RED component from ARB OpenGL extension - this.lumaTexture = container.VideoTextureCache.TextureFromImage(pixelBuffer, true, re, this.textureWidth, this.textureHeight, re, DataType.UnsignedByte, 0, out CVReturn status); - if (this.lumaTexture == null) - { - Console.WriteLine("Error creating luma texture: {0}", status); - return; - } + this.lumaTexture = container.VideoTextureCache.TextureFromImage (pixelBuffer, true, re, this.textureWidth, this.textureHeight, re, DataType.UnsignedByte, 0, out CVReturn status); + if (this.lumaTexture == null) { + Console.WriteLine ("Error creating luma texture: {0}", status); + return; + } - GL.BindTexture(this.lumaTexture.Target, this.lumaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); + GL.BindTexture (this.lumaTexture.Target, this.lumaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); - // UV Plane - GL.ActiveTexture(TextureUnit.Texture1); - re = (All)0x8227; // GL_RG_EXT, RED GREEN component from ARB OpenGL extension - this.chromaTexture = container.VideoTextureCache.TextureFromImage(pixelBuffer, true, re, this.textureWidth / 2, this.textureHeight / 2, re, DataType.UnsignedByte, 1, out status); - if (this.chromaTexture == null) - { - Console.WriteLine("Error creating chroma texture: {0}", status); - return; - } + // UV Plane + GL.ActiveTexture (TextureUnit.Texture1); + re = (All) 0x8227; // GL_RG_EXT, RED GREEN component from ARB OpenGL extension + this.chromaTexture = container.VideoTextureCache.TextureFromImage (pixelBuffer, true, re, this.textureWidth / 2, this.textureHeight / 2, re, DataType.UnsignedByte, 1, out status); + if (this.chromaTexture == null) { + Console.WriteLine ("Error creating chroma texture: {0}", status); + return; + } - GL.BindTexture(this.chromaTexture.Target, this.chromaTexture.Name); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - } - } - } - finally - { - sampleBuffer.Dispose(); - } - } + GL.BindTexture (this.chromaTexture.Target, this.chromaTexture.Name); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + } + } + } finally { + sampleBuffer.Dispose (); + } + } - private void CleanupTextures() - { - if (this.lumaTexture != null) - { - this.lumaTexture.Dispose(); - this.lumaTexture = null; - } + private void CleanupTextures () + { + if (this.lumaTexture != null) { + this.lumaTexture.Dispose (); + this.lumaTexture = null; + } - if (this.chromaTexture != null) - { - this.chromaTexture.Dispose(); - this.chromaTexture = null; - } + if (this.chromaTexture != null) { + this.chromaTexture.Dispose (); + this.chromaTexture = null; + } - if (this.viewControllerReference.TryGetTarget(out var container)) - { - container.VideoTextureCache.Flush(CVOptionFlags.None); - } - } - } -} \ No newline at end of file + if (this.viewControllerReference.TryGetTarget (out var container)) { + container.VideoTextureCache.Flush (CVOptionFlags.None); + } + } + } +} diff --git a/GLCameraRipple/GLCameraRipple/Helpers/Ripple.cs b/GLCameraRipple/GLCameraRipple/Helpers/Ripple.cs index 26662f925..e23c346a1 100644 --- a/GLCameraRipple/GLCameraRipple/Helpers/Ripple.cs +++ b/GLCameraRipple/GLCameraRipple/Helpers/Ripple.cs @@ -2,272 +2,237 @@ using System; using System.Runtime.InteropServices; -namespace GLCameraRipple -{ - public class RippleModel - { - private readonly CGSize screenSize; - private readonly int poolHeight, poolWidth; - private readonly int touchRadius; - - private readonly float texCoordFactorS; - private readonly float texCoordOffsetS; - private readonly float texCoordFactorT; - private readonly float texCoordOffsetT; - - // ripple coefficients - private readonly float[,] rippleCoeff; - - // ripple simulation buffers - private float[,] rippleSource; - private float[,] rippleDest; - - // data passed to GL - private unsafe float* rippleVertices; - private unsafe float* rippleTexCoords; - private unsafe ushort* rippleIndicies; - - public RippleModel(CGSize screenSize, int meshFactor, int touchRadius, CGSize textureSize) - { - Console.WriteLine("New 'Ripple Model'"); - - this.screenSize = screenSize; - this.touchRadius = touchRadius; - this.poolWidth = (int)this.screenSize.Width / meshFactor; - this.poolHeight = (int)this.screenSize.Height / meshFactor; - - if ((float)this.screenSize.Height / this.screenSize.Width < (float)textureSize.Width / textureSize.Height) - { - this.texCoordFactorS = (float)((textureSize.Height * this.screenSize.Height) / (this.screenSize.Width * textureSize.Width)); - this.texCoordOffsetS = (1 - this.texCoordFactorS) / 2f; - - this.texCoordFactorT = 1; - this.texCoordOffsetT = 0; - } - else - { - this.texCoordFactorS = 1; - this.texCoordOffsetS = 0; - - this.texCoordFactorT = (float)((this.screenSize.Width * textureSize.Width) / (textureSize.Height * this.screenSize.Height)); - this.texCoordOffsetT = (1 - this.texCoordFactorT) / 2f; - } - - this.rippleCoeff = new float[touchRadius * 2 + 1, touchRadius * 2 + 1]; - - // +2 for padding the border - this.rippleSource = new float[this.poolWidth + 2, this.poolHeight + 2]; - this.rippleDest = new float[this.poolWidth + 2, this.poolHeight + 2]; - - unsafe - { - int poolsize2 = this.poolWidth * this.poolHeight * 2; - rippleVertices = (float*)Marshal.AllocHGlobal(poolsize2 * sizeof(float)); - rippleTexCoords = (float*)Marshal.AllocHGlobal(poolsize2 * sizeof(float)); - rippleIndicies = (ushort*)Marshal.AllocHGlobal((this.poolHeight - 1) * (this.poolWidth * 2 + 2) * sizeof(ushort)); - } - - this.InitRippleCoef(); - this.InitMesh(); - } - - private void InitRippleCoef() - { - for (int y = 0; y <= 2 * this.touchRadius; y++) - { - for (int x = 0; x <= 2 * this.touchRadius; x++) - { - float distance = (float)Math.Sqrt((x - this.touchRadius) * (x - this.touchRadius) + (y - this.touchRadius) * (y - this.touchRadius)); - - if (distance <= this.touchRadius) - { - var factor = (distance / this.touchRadius); - - // goes from -512 -> 0 - this.rippleCoeff[x, y] = -((float)Math.Cos(factor * Math.PI) + 1f) * 256f; - } - else - { - this.rippleCoeff[x, y] = 0f; - } - } - } - } - - private unsafe void InitMesh() - { - for (int i = 0; i < this.poolHeight; i++) - { - for (int j = 0; j < this.poolWidth; j++) - { - this.rippleVertices[(i * this.poolWidth + j) * 2 + 0] = -1f + j * (2f / (this.poolWidth - 1)); - this.rippleVertices[(i * this.poolWidth + j) * 2 + 1] = 1f - i * (2f / (this.poolHeight - 1)); - - this.rippleTexCoords[(i * this.poolWidth + j) * 2 + 0] = (float)i / (this.poolHeight - 1) * this.texCoordFactorS + this.texCoordOffsetS; - this.rippleTexCoords[(i * this.poolWidth + j) * 2 + 1] = (1f - (float)j / (this.poolWidth - 1)) * this.texCoordFactorT + this.texCoordFactorT; - } - } - - uint index = 0; - for (int i = 0; i < this.poolHeight - 1; i++) - { - for (int j = 0; j < this.poolWidth; j++) - { - if (i % 2 == 0) - { - // emit extra index to create degenerate triangle - if (j == 0) - { - this.rippleIndicies[index] = (ushort)(i * this.poolWidth + j); - index++; - } - - this.rippleIndicies[index] = (ushort)(i * this.poolWidth + j); - index++; - this.rippleIndicies[index] = (ushort)((i + 1) * this.poolWidth + j); - index++; - - // emit extra index to create degenerate triangle - if (j == (this.poolWidth - 1)) - { - this.rippleIndicies[index] = (ushort)((i + 1) * this.poolWidth + j); - index++; - } - } - else - { - // emit extra index to create degenerate triangle - if (j == 0) - { - this.rippleIndicies[index] = (ushort)((i + 1) * this.poolWidth + j); - index++; - } - - this.rippleIndicies[index] = (ushort)((i + 1) * this.poolWidth + j); - index++; - this.rippleIndicies[index] = (ushort)(i * this.poolWidth + j); - index++; - - // emit extra index to create degenerate triangle - if (j == (this.poolWidth - 1)) - { - this.rippleIndicies[index] = (ushort)(i * this.poolWidth + j); - index++; - } - } - } - } - } - - public IntPtr Vertices - { - get { unsafe { return (IntPtr)this.rippleVertices; } } - } - - public IntPtr TexCoords - { - get { unsafe { return (IntPtr)this.rippleTexCoords; } } - } - - public IntPtr Indices - { - get { unsafe { return (IntPtr)this.rippleIndicies; } } - } - - public int VertexSize - { - get { return this.poolWidth * this.poolHeight * 2 * sizeof(float); } - } - - public int IndexSize - { - get { return (this.poolHeight - 1) * (this.poolWidth * 2 + 2) * sizeof(ushort); } - } - - public int IndexCount - { - get { return this.IndexSize / sizeof(ushort); } - } - - public unsafe void RunSimulation() - { - for (int y = 0; y < this.poolHeight; y++) - { - for (int x = 0; x < this.poolWidth; x++) - { - // * - denotes current pixel - // - // a - // c * d - // b - - // +1 to both x/y values because the border is padded - float a = this.rippleSource[x + 1, y]; - float b = this.rippleSource[x + 1, y + 2]; - float c = this.rippleSource[x, y + 1]; - float d = this.rippleSource[x + 2, y + 1]; - - float result = (a + b + c + d) / 2f - this.rippleDest[x + 1, y + 1]; - result -= result / 32f; - - this.rippleDest[x + 1, y + 1] = result; - } - } - - for (int y = 0; y < this.poolHeight; y++) - { - for (int x = 0; x < this.poolWidth; x++) - { - // * - denotes current pixel - // - // a - // c * d - // b - - // +1 to both x/y values because the border is padded - float a = this.rippleDest[x + 1, y]; - float b = this.rippleDest[x + 1, y + 2]; - float c = this.rippleDest[x, y + 1]; - float d = this.rippleDest[x + 2, y + 1]; - - float s_offset = ((b - a) / 2048f); - float t_offset = ((c - d) / 2048f); - - // clamp - s_offset = (s_offset < -0.5f) ? -0.5f : s_offset; - t_offset = (t_offset < -0.5f) ? -0.5f : t_offset; - s_offset = (s_offset > 0.5f) ? 0.5f : s_offset; - t_offset = (t_offset > 0.5f) ? 0.5f : t_offset; - - float s_tc = (float)y / (poolHeight - 1) * this.texCoordFactorS + this.texCoordOffsetS; - float t_tc = (1f - (float)x / (poolWidth - 1)) * this.texCoordFactorT + this.texCoordOffsetT; - - this.rippleTexCoords[(y * this.poolWidth + x) * 2 + 0] = s_tc + s_offset; - this.rippleTexCoords[(y * this.poolWidth + x) * 2 + 1] = t_tc + t_offset; - } - } - - var tmp = this.rippleSource; - this.rippleSource = this.rippleDest; - this.rippleDest = tmp; - } - - public void InitiateRippleAtLocation(CGPoint location) - { - int xIndex = (int)(location.X / this.screenSize.Width * this.poolWidth); - int yIndex = (int)(location.Y / this.screenSize.Height * this.poolHeight); - - for (int y = yIndex - this.touchRadius; y <= yIndex + this.touchRadius; y++) - { - for (int x = xIndex - this.touchRadius; x <= xIndex + this.touchRadius; x++) - { - if (x >= 0 && x < this.poolWidth && y >= 0 && y < this.poolHeight) - { - // +1 to both x/y values because the border is padded - this.rippleSource[x + 1, y + 1] += this.rippleCoeff[y - (yIndex - this.touchRadius), x - (xIndex - this.touchRadius)]; - } - } - } - } - } -} \ No newline at end of file +namespace GLCameraRipple { + public class RippleModel { + private readonly CGSize screenSize; + private readonly int poolHeight, poolWidth; + private readonly int touchRadius; + + private readonly float texCoordFactorS; + private readonly float texCoordOffsetS; + private readonly float texCoordFactorT; + private readonly float texCoordOffsetT; + + // ripple coefficients + private readonly float [,] rippleCoeff; + + // ripple simulation buffers + private float [,] rippleSource; + private float [,] rippleDest; + + // data passed to GL + private unsafe float* rippleVertices; + private unsafe float* rippleTexCoords; + private unsafe ushort* rippleIndicies; + + public RippleModel (CGSize screenSize, int meshFactor, int touchRadius, CGSize textureSize) + { + Console.WriteLine ("New 'Ripple Model'"); + + this.screenSize = screenSize; + this.touchRadius = touchRadius; + this.poolWidth = (int) this.screenSize.Width / meshFactor; + this.poolHeight = (int) this.screenSize.Height / meshFactor; + + if ((float) this.screenSize.Height / this.screenSize.Width < (float) textureSize.Width / textureSize.Height) { + this.texCoordFactorS = (float) ((textureSize.Height * this.screenSize.Height) / (this.screenSize.Width * textureSize.Width)); + this.texCoordOffsetS = (1 - this.texCoordFactorS) / 2f; + + this.texCoordFactorT = 1; + this.texCoordOffsetT = 0; + } else { + this.texCoordFactorS = 1; + this.texCoordOffsetS = 0; + + this.texCoordFactorT = (float) ((this.screenSize.Width * textureSize.Width) / (textureSize.Height * this.screenSize.Height)); + this.texCoordOffsetT = (1 - this.texCoordFactorT) / 2f; + } + + this.rippleCoeff = new float [touchRadius * 2 + 1, touchRadius * 2 + 1]; + + // +2 for padding the border + this.rippleSource = new float [this.poolWidth + 2, this.poolHeight + 2]; + this.rippleDest = new float [this.poolWidth + 2, this.poolHeight + 2]; + + unsafe { + int poolsize2 = this.poolWidth * this.poolHeight * 2; + rippleVertices = (float*) Marshal.AllocHGlobal (poolsize2 * sizeof (float)); + rippleTexCoords = (float*) Marshal.AllocHGlobal (poolsize2 * sizeof (float)); + rippleIndicies = (ushort*) Marshal.AllocHGlobal ((this.poolHeight - 1) * (this.poolWidth * 2 + 2) * sizeof (ushort)); + } + + this.InitRippleCoef (); + this.InitMesh (); + } + + private void InitRippleCoef () + { + for (int y = 0; y <= 2 * this.touchRadius; y++) { + for (int x = 0; x <= 2 * this.touchRadius; x++) { + float distance = (float) Math.Sqrt ((x - this.touchRadius) * (x - this.touchRadius) + (y - this.touchRadius) * (y - this.touchRadius)); + + if (distance <= this.touchRadius) { + var factor = (distance / this.touchRadius); + + // goes from -512 -> 0 + this.rippleCoeff [x, y] = -((float) Math.Cos (factor * Math.PI) + 1f) * 256f; + } else { + this.rippleCoeff [x, y] = 0f; + } + } + } + } + + private unsafe void InitMesh () + { + for (int i = 0; i < this.poolHeight; i++) { + for (int j = 0; j < this.poolWidth; j++) { + this.rippleVertices [(i * this.poolWidth + j) * 2 + 0] = -1f + j * (2f / (this.poolWidth - 1)); + this.rippleVertices [(i * this.poolWidth + j) * 2 + 1] = 1f - i * (2f / (this.poolHeight - 1)); + + this.rippleTexCoords [(i * this.poolWidth + j) * 2 + 0] = (float) i / (this.poolHeight - 1) * this.texCoordFactorS + this.texCoordOffsetS; + this.rippleTexCoords [(i * this.poolWidth + j) * 2 + 1] = (1f - (float) j / (this.poolWidth - 1)) * this.texCoordFactorT + this.texCoordFactorT; + } + } + + uint index = 0; + for (int i = 0; i < this.poolHeight - 1; i++) { + for (int j = 0; j < this.poolWidth; j++) { + if (i % 2 == 0) { + // emit extra index to create degenerate triangle + if (j == 0) { + this.rippleIndicies [index] = (ushort) (i * this.poolWidth + j); + index++; + } + + this.rippleIndicies [index] = (ushort) (i * this.poolWidth + j); + index++; + this.rippleIndicies [index] = (ushort) ((i + 1) * this.poolWidth + j); + index++; + + // emit extra index to create degenerate triangle + if (j == (this.poolWidth - 1)) { + this.rippleIndicies [index] = (ushort) ((i + 1) * this.poolWidth + j); + index++; + } + } else { + // emit extra index to create degenerate triangle + if (j == 0) { + this.rippleIndicies [index] = (ushort) ((i + 1) * this.poolWidth + j); + index++; + } + + this.rippleIndicies [index] = (ushort) ((i + 1) * this.poolWidth + j); + index++; + this.rippleIndicies [index] = (ushort) (i * this.poolWidth + j); + index++; + + // emit extra index to create degenerate triangle + if (j == (this.poolWidth - 1)) { + this.rippleIndicies [index] = (ushort) (i * this.poolWidth + j); + index++; + } + } + } + } + } + + public IntPtr Vertices { + get { unsafe { return (IntPtr) this.rippleVertices; } } + } + + public IntPtr TexCoords { + get { unsafe { return (IntPtr) this.rippleTexCoords; } } + } + + public IntPtr Indices { + get { unsafe { return (IntPtr) this.rippleIndicies; } } + } + + public int VertexSize { + get { return this.poolWidth * this.poolHeight * 2 * sizeof (float); } + } + + public int IndexSize { + get { return (this.poolHeight - 1) * (this.poolWidth * 2 + 2) * sizeof (ushort); } + } + + public int IndexCount { + get { return this.IndexSize / sizeof (ushort); } + } + + public unsafe void RunSimulation () + { + for (int y = 0; y < this.poolHeight; y++) { + for (int x = 0; x < this.poolWidth; x++) { + // * - denotes current pixel + // + // a + // c * d + // b + + // +1 to both x/y values because the border is padded + float a = this.rippleSource [x + 1, y]; + float b = this.rippleSource [x + 1, y + 2]; + float c = this.rippleSource [x, y + 1]; + float d = this.rippleSource [x + 2, y + 1]; + + float result = (a + b + c + d) / 2f - this.rippleDest [x + 1, y + 1]; + result -= result / 32f; + + this.rippleDest [x + 1, y + 1] = result; + } + } + + for (int y = 0; y < this.poolHeight; y++) { + for (int x = 0; x < this.poolWidth; x++) { + // * - denotes current pixel + // + // a + // c * d + // b + + // +1 to both x/y values because the border is padded + float a = this.rippleDest [x + 1, y]; + float b = this.rippleDest [x + 1, y + 2]; + float c = this.rippleDest [x, y + 1]; + float d = this.rippleDest [x + 2, y + 1]; + + float s_offset = ((b - a) / 2048f); + float t_offset = ((c - d) / 2048f); + + // clamp + s_offset = (s_offset < -0.5f) ? -0.5f : s_offset; + t_offset = (t_offset < -0.5f) ? -0.5f : t_offset; + s_offset = (s_offset > 0.5f) ? 0.5f : s_offset; + t_offset = (t_offset > 0.5f) ? 0.5f : t_offset; + + float s_tc = (float) y / (poolHeight - 1) * this.texCoordFactorS + this.texCoordOffsetS; + float t_tc = (1f - (float) x / (poolWidth - 1)) * this.texCoordFactorT + this.texCoordOffsetT; + + this.rippleTexCoords [(y * this.poolWidth + x) * 2 + 0] = s_tc + s_offset; + this.rippleTexCoords [(y * this.poolWidth + x) * 2 + 1] = t_tc + t_offset; + } + } + + var tmp = this.rippleSource; + this.rippleSource = this.rippleDest; + this.rippleDest = tmp; + } + + public void InitiateRippleAtLocation (CGPoint location) + { + int xIndex = (int) (location.X / this.screenSize.Width * this.poolWidth); + int yIndex = (int) (location.Y / this.screenSize.Height * this.poolHeight); + + for (int y = yIndex - this.touchRadius; y <= yIndex + this.touchRadius; y++) { + for (int x = xIndex - this.touchRadius; x <= xIndex + this.touchRadius; x++) { + if (x >= 0 && x < this.poolWidth && y >= 0 && y < this.poolHeight) { + // +1 to both x/y values because the border is padded + this.rippleSource [x + 1, y + 1] += this.rippleCoeff [y - (yIndex - this.touchRadius), x - (xIndex - this.touchRadius)]; + } + } + } + } + } +} diff --git a/GLCameraRipple/GLCameraRipple/Main.cs b/GLCameraRipple/GLCameraRipple/Main.cs index c4325c819..e96e86ba5 100644 --- a/GLCameraRipple/GLCameraRipple/Main.cs +++ b/GLCameraRipple/GLCameraRipple/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace GLCameraRipple -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace GLCameraRipple { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/GLCameraRipple/GLCameraRipple/ViewController.cs b/GLCameraRipple/GLCameraRipple/ViewController.cs index 7a79aee81..8b9c05ea4 100644 --- a/GLCameraRipple/GLCameraRipple/ViewController.cs +++ b/GLCameraRipple/GLCameraRipple/ViewController.cs @@ -1,4 +1,4 @@ -using AVFoundation; +using AVFoundation; using CoreFoundation; using CoreGraphics; using CoreVideo; @@ -10,281 +10,259 @@ using System; using UIKit; -namespace GLCameraRipple -{ - public partial class ViewController : GLKViewController - { - // OpenGL components - private const int UNIFORM_Y = 0; - private const int UNIFORM_UV = 1; - private const int ATTRIB_VERTEX = 0; - private const int ATTRIB_TEXCOORD = 1; - - private int indexVbo, positionVbo, texcoordVbo; - private int[] uniforms = new int[2]; - private int program; - - private EAGLContext context; - private CGSize size; - private int meshFactor; - - private AVCaptureSession session; - - private DataOutputDelegate dataOutputDelegate; - - protected ViewController(IntPtr handle) : base(handle) { } - - public RippleModel Ripple { get; private set; } - - public CVOpenGLESTextureCache VideoTextureCache { get; private set; } - - public override UIStatusBarStyle PreferredStatusBarStyle() - { - return UIStatusBarStyle.LightContent; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - context = new EAGLContext(EAGLRenderingAPI.OpenGLES2); - var glkView = View as GLKView; - glkView.Context = context; - glkView.MultipleTouchEnabled = true; - - PreferredFramesPerSecond = 60; - size = UIScreen.MainScreen.Bounds.Size.ToRoundedCGSize(); - View.ContentScaleFactor = UIScreen.MainScreen.Scale; - - var isPad = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad; - meshFactor = isPad ? 8 : 4; - SetupGL(); - SetupAVCapture(isPad ? AVCaptureSession.PresetiFrame1280x720 : AVCaptureSession.Preset640x480); - } - - public override void Update() - { - if (this.Ripple != null) - { - this.Ripple.RunSimulation(); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)this.Ripple.VertexSize, this.Ripple.TexCoords, BufferUsage.DynamicDraw); - } - } - - public override void DrawInRect(GLKView view, CGRect rect) - { - GL.Clear(ClearBufferMask.ColorBufferBit); - if (this.Ripple != null) - { - GL.DrawElements(BeginMode.TriangleStrip, this.Ripple.IndexCount, DrawElementsType.UnsignedShort, IntPtr.Zero); - } - } - - #region touches - - public override void TouchesBegan(NSSet touches, UIEvent evt) - { - this.ProcessTouches(touches); - } - - public override void TouchesMoved(NSSet touches, UIEvent evt) - { - this.ProcessTouches(touches); - } - - private void ProcessTouches(NSSet touches) - { - if (this.Ripple != null) - { - foreach (UITouch touch in touches.ToArray()) - { - this.Ripple.InitiateRippleAtLocation(touch.LocationInView(touch.View)); - } - } - } - - #endregion - - #region setup - - private void SetupGL() - { - EAGLContext.SetCurrentContext(this.context); - if (this.LoadShaders()) - { - GL.UseProgram(this.program); - GL.Uniform1(this.uniforms[UNIFORM_Y], 0); - GL.Uniform1(this.uniforms[UNIFORM_UV], 1); - } - } - - private void SetupAVCapture(NSString sessionPreset) - { - if ((this.VideoTextureCache = CVOpenGLESTextureCache.FromEAGLContext(this.context)) == null) - { - Console.WriteLine("Could not create the CoreVideo TextureCache"); - return; - } - - this.session = new AVCaptureSession(); - this.session.BeginConfiguration(); - - // Preset size - this.session.SessionPreset = sessionPreset; - - // Input device - var videoDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); - if (videoDevice == null) - { - Console.WriteLine("No video device"); - return; - } - - var input = new AVCaptureDeviceInput(videoDevice, out NSError error); - if (error != null) - { - Console.WriteLine("Error creating video capture device"); - return; - } - - this.session.AddInput(input); - - // Create the output device - using (var dataOutput = new AVCaptureVideoDataOutput()) - { - dataOutput.AlwaysDiscardsLateVideoFrames = true; - - // YUV 420, use "BiPlanar" to split the Y and UV planes in two separate blocks of - // memory, then we can index 0 to get the Y and 1 for the UV planes in the frame decoding - //VideoSettings = new AVVideoSettings (CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange) - - this.dataOutputDelegate = new DataOutputDelegate(this); - - // - // This dispatches the video frames into the main thread, because the OpenGL - // code is accessing the data synchronously. - // - dataOutput.SetSampleBufferDelegateQueue(this.dataOutputDelegate, DispatchQueue.MainQueue); - this.session.AddOutput(dataOutput); - } - - this.session.CommitConfiguration(); - this.session.StartRunning(); - } - - private bool LoadShaders() - { - this.program = GL.CreateProgram(); - if (this.CompileShader(out int vertShader, ShaderType.VertexShader, "Shaders/Shader.vsh")) - { - if (this.CompileShader(out int fragShader, ShaderType.FragmentShader, "Shaders/Shader.fsh")) - { - // Attach shaders - GL.AttachShader(this.program, vertShader); - GL.AttachShader(this.program, fragShader); - - // Bind attribtue locations - GL.BindAttribLocation(this.program, ATTRIB_VERTEX, "position"); - GL.BindAttribLocation(this.program, ATTRIB_TEXCOORD, "texCoord"); - - if (this.LinkProgram(this.program)) - { - // Get uniform locations - this.uniforms[UNIFORM_Y] = GL.GetUniformLocation(this.program, "SamplerY"); - this.uniforms[UNIFORM_UV] = GL.GetUniformLocation(this.program, "SamplerUV"); - - // Delete these ones, we do not need them anymore - GL.DeleteShader(vertShader); - GL.DeleteShader(fragShader); - return true; - } - else - { - Console.WriteLine("Failed to link the shader programs"); - GL.DeleteProgram(this.program); - this.program = 0; - } - } - else - { - Console.WriteLine("Failed to compile fragment shader"); - } - - GL.DeleteShader(vertShader); - } - else - { - Console.WriteLine("Failed to compile vertex shader"); - } - - GL.DeleteProgram(this.program); - return false; - } - - private bool CompileShader(out int shader, ShaderType type, string path) - { - var shaderProgram = System.IO.File.ReadAllText(path); - var length = shaderProgram.Length; - shader = GL.CreateShader(type); - - GL.ShaderSource(shader, 1, new string[] { shaderProgram }, ref length); - GL.CompileShader(shader); - GL.GetShader(shader, ShaderParameter.CompileStatus, out int status); - if (status == 0) - { - GL.DeleteShader(shader); - return false; - } - return true; - } - - private bool LinkProgram(int program) - { - GL.LinkProgram(program); - GL.GetProgram(program, ProgramParameter.LinkStatus, out int status); - if (status == 0) - { - GL.GetProgram(program, ProgramParameter.InfoLogLength, out int length); - var stringBuilder = new System.Text.StringBuilder(length); - GL.GetProgramInfoLog(program, length, out length, stringBuilder); - - Console.WriteLine($"Link error: {stringBuilder}"); - } - - return status != 0; - } - - private unsafe void SetupBuffers() - { - GL.GenBuffers(1, out indexVbo); - GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexVbo); - GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)this.Ripple.IndexSize, this.Ripple.Indices, BufferUsage.StaticDraw); - - GL.GenBuffers(1, out positionVbo); - GL.BindBuffer(BufferTarget.ArrayBuffer, positionVbo); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)this.Ripple.VertexSize, this.Ripple.Vertices, BufferUsage.StaticDraw); - - GL.EnableVertexAttribArray(ATTRIB_VERTEX); - - GL.VertexAttribPointer(ATTRIB_VERTEX, 2, VertexAttribPointerType.Float, false, 2 * sizeof(float), IntPtr.Zero); - GL.GenBuffers(1, out texcoordVbo); - GL.BindBuffer(BufferTarget.ArrayBuffer, texcoordVbo); - GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)this.Ripple.VertexSize, this.Ripple.TexCoords, BufferUsage.DynamicDraw); - - GL.EnableVertexAttribArray(ATTRIB_TEXCOORD); - GL.VertexAttribPointer(ATTRIB_TEXCOORD, 2, VertexAttribPointerType.Float, false, 2 * sizeof(float), IntPtr.Zero); - } - - public void SetupRipple(int width, int height) - { - this.Ripple = new RippleModel(this.size, this.meshFactor, 5, new CGSize(width, height)); - this.SetupBuffers(); - } - - #endregion - - private void TeardownAVCapture() { } - - private void TeardownGL() { } - } -} \ No newline at end of file +namespace GLCameraRipple { + public partial class ViewController : GLKViewController { + // OpenGL components + private const int UNIFORM_Y = 0; + private const int UNIFORM_UV = 1; + private const int ATTRIB_VERTEX = 0; + private const int ATTRIB_TEXCOORD = 1; + + private int indexVbo, positionVbo, texcoordVbo; + private int [] uniforms = new int [2]; + private int program; + + private EAGLContext context; + private CGSize size; + private int meshFactor; + + private AVCaptureSession session; + + private DataOutputDelegate dataOutputDelegate; + + protected ViewController (IntPtr handle) : base (handle) { } + + public RippleModel Ripple { get; private set; } + + public CVOpenGLESTextureCache VideoTextureCache { get; private set; } + + public override UIStatusBarStyle PreferredStatusBarStyle () + { + return UIStatusBarStyle.LightContent; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + context = new EAGLContext (EAGLRenderingAPI.OpenGLES2); + var glkView = View as GLKView; + glkView.Context = context; + glkView.MultipleTouchEnabled = true; + + PreferredFramesPerSecond = 60; + size = UIScreen.MainScreen.Bounds.Size.ToRoundedCGSize (); + View.ContentScaleFactor = UIScreen.MainScreen.Scale; + + var isPad = UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad; + meshFactor = isPad ? 8 : 4; + SetupGL (); + SetupAVCapture (isPad ? AVCaptureSession.PresetiFrame1280x720 : AVCaptureSession.Preset640x480); + } + + public override void Update () + { + if (this.Ripple != null) { + this.Ripple.RunSimulation (); + GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr) this.Ripple.VertexSize, this.Ripple.TexCoords, BufferUsage.DynamicDraw); + } + } + + public override void DrawInRect (GLKView view, CGRect rect) + { + GL.Clear (ClearBufferMask.ColorBufferBit); + if (this.Ripple != null) { + GL.DrawElements (BeginMode.TriangleStrip, this.Ripple.IndexCount, DrawElementsType.UnsignedShort, IntPtr.Zero); + } + } + + #region touches + + public override void TouchesBegan (NSSet touches, UIEvent evt) + { + this.ProcessTouches (touches); + } + + public override void TouchesMoved (NSSet touches, UIEvent evt) + { + this.ProcessTouches (touches); + } + + private void ProcessTouches (NSSet touches) + { + if (this.Ripple != null) { + foreach (UITouch touch in touches.ToArray ()) { + this.Ripple.InitiateRippleAtLocation (touch.LocationInView (touch.View)); + } + } + } + + #endregion + + #region setup + + private void SetupGL () + { + EAGLContext.SetCurrentContext (this.context); + if (this.LoadShaders ()) { + GL.UseProgram (this.program); + GL.Uniform1 (this.uniforms [UNIFORM_Y], 0); + GL.Uniform1 (this.uniforms [UNIFORM_UV], 1); + } + } + + private void SetupAVCapture (NSString sessionPreset) + { + if ((this.VideoTextureCache = CVOpenGLESTextureCache.FromEAGLContext (this.context)) == null) { + Console.WriteLine ("Could not create the CoreVideo TextureCache"); + return; + } + + this.session = new AVCaptureSession (); + this.session.BeginConfiguration (); + + // Preset size + this.session.SessionPreset = sessionPreset; + + // Input device + var videoDevice = AVCaptureDevice.GetDefaultDevice (AVMediaType.Video); + if (videoDevice == null) { + Console.WriteLine ("No video device"); + return; + } + + var input = new AVCaptureDeviceInput (videoDevice, out NSError error); + if (error != null) { + Console.WriteLine ("Error creating video capture device"); + return; + } + + this.session.AddInput (input); + + // Create the output device + using (var dataOutput = new AVCaptureVideoDataOutput ()) { + dataOutput.AlwaysDiscardsLateVideoFrames = true; + + // YUV 420, use "BiPlanar" to split the Y and UV planes in two separate blocks of + // memory, then we can index 0 to get the Y and 1 for the UV planes in the frame decoding + //VideoSettings = new AVVideoSettings (CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange) + + this.dataOutputDelegate = new DataOutputDelegate (this); + + // + // This dispatches the video frames into the main thread, because the OpenGL + // code is accessing the data synchronously. + // + dataOutput.SetSampleBufferDelegateQueue (this.dataOutputDelegate, DispatchQueue.MainQueue); + this.session.AddOutput (dataOutput); + } + + this.session.CommitConfiguration (); + this.session.StartRunning (); + } + + private bool LoadShaders () + { + this.program = GL.CreateProgram (); + if (this.CompileShader (out int vertShader, ShaderType.VertexShader, "Shaders/Shader.vsh")) { + if (this.CompileShader (out int fragShader, ShaderType.FragmentShader, "Shaders/Shader.fsh")) { + // Attach shaders + GL.AttachShader (this.program, vertShader); + GL.AttachShader (this.program, fragShader); + + // Bind attribtue locations + GL.BindAttribLocation (this.program, ATTRIB_VERTEX, "position"); + GL.BindAttribLocation (this.program, ATTRIB_TEXCOORD, "texCoord"); + + if (this.LinkProgram (this.program)) { + // Get uniform locations + this.uniforms [UNIFORM_Y] = GL.GetUniformLocation (this.program, "SamplerY"); + this.uniforms [UNIFORM_UV] = GL.GetUniformLocation (this.program, "SamplerUV"); + + // Delete these ones, we do not need them anymore + GL.DeleteShader (vertShader); + GL.DeleteShader (fragShader); + return true; + } else { + Console.WriteLine ("Failed to link the shader programs"); + GL.DeleteProgram (this.program); + this.program = 0; + } + } else { + Console.WriteLine ("Failed to compile fragment shader"); + } + + GL.DeleteShader (vertShader); + } else { + Console.WriteLine ("Failed to compile vertex shader"); + } + + GL.DeleteProgram (this.program); + return false; + } + + private bool CompileShader (out int shader, ShaderType type, string path) + { + var shaderProgram = System.IO.File.ReadAllText (path); + var length = shaderProgram.Length; + shader = GL.CreateShader (type); + + GL.ShaderSource (shader, 1, new string [] { shaderProgram }, ref length); + GL.CompileShader (shader); + GL.GetShader (shader, ShaderParameter.CompileStatus, out int status); + if (status == 0) { + GL.DeleteShader (shader); + return false; + } + return true; + } + + private bool LinkProgram (int program) + { + GL.LinkProgram (program); + GL.GetProgram (program, ProgramParameter.LinkStatus, out int status); + if (status == 0) { + GL.GetProgram (program, ProgramParameter.InfoLogLength, out int length); + var stringBuilder = new System.Text.StringBuilder (length); + GL.GetProgramInfoLog (program, length, out length, stringBuilder); + + Console.WriteLine ($"Link error: {stringBuilder}"); + } + + return status != 0; + } + + private unsafe void SetupBuffers () + { + GL.GenBuffers (1, out indexVbo); + GL.BindBuffer (BufferTarget.ElementArrayBuffer, indexVbo); + GL.BufferData (BufferTarget.ElementArrayBuffer, (IntPtr) this.Ripple.IndexSize, this.Ripple.Indices, BufferUsage.StaticDraw); + + GL.GenBuffers (1, out positionVbo); + GL.BindBuffer (BufferTarget.ArrayBuffer, positionVbo); + GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr) this.Ripple.VertexSize, this.Ripple.Vertices, BufferUsage.StaticDraw); + + GL.EnableVertexAttribArray (ATTRIB_VERTEX); + + GL.VertexAttribPointer (ATTRIB_VERTEX, 2, VertexAttribPointerType.Float, false, 2 * sizeof (float), IntPtr.Zero); + GL.GenBuffers (1, out texcoordVbo); + GL.BindBuffer (BufferTarget.ArrayBuffer, texcoordVbo); + GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr) this.Ripple.VertexSize, this.Ripple.TexCoords, BufferUsage.DynamicDraw); + + GL.EnableVertexAttribArray (ATTRIB_TEXCOORD); + GL.VertexAttribPointer (ATTRIB_TEXCOORD, 2, VertexAttribPointerType.Float, false, 2 * sizeof (float), IntPtr.Zero); + } + + public void SetupRipple (int width, int height) + { + this.Ripple = new RippleModel (this.size, this.meshFactor, 5, new CGSize (width, height)); + this.SetupBuffers (); + } + + #endregion + + private void TeardownAVCapture () { } + + private void TeardownGL () { } + } +} diff --git a/GLPaint-GameView/Main.cs b/GLPaint-GameView/Main.cs index 2cc43e00a..e36722f13 100644 --- a/GLPaint-GameView/Main.cs +++ b/GLPaint-GameView/Main.cs @@ -7,19 +7,16 @@ using CoreGraphics; using OpenTK.Graphics.ES11; -namespace GLPaintGameView -{ - public class Application - { - static void Main (string[] args) +namespace GLPaintGameView { + public class Application { + static void Main (string [] args) { UIApplication.Main (args); } } // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { const int PaletteHeight = 30; const int PaletteSize = 5; const int AccelerometerFrequency = 25; @@ -32,9 +29,9 @@ public partial class AppDelegate : UIApplicationDelegate const float TopMarginPadding = 10.0f; const float RightMarginPadding = 10.0f; - double[] myAccelerometer = new double [3]; + double [] myAccelerometer = new double [3]; SoundEffect erasingSound = new SoundEffect (NSBundle.MainBundle.PathForResource ("Erase", "caf")); - SoundEffect selectSound = new SoundEffect (NSBundle.MainBundle.PathForResource ("Select", "caf")); + SoundEffect selectSound = new SoundEffect (NSBundle.MainBundle.PathForResource ("Select", "caf")); DateTime lastTime; PaintingView drawingView; @@ -54,7 +51,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.RootViewController = viewController; // Create a segmented control so that the user can choose the brush color. - var images = new[] { + var images = new [] { UIImage.FromFile ("Images/Red.png"), UIImage.FromFile ("Images/Yellow.png"), UIImage.FromFile ("Images/Green.png"), @@ -131,7 +128,7 @@ static void HslToRgb (float h, float s, float l, out float r, out float g, out f float temp1 = 2.0f * l - temp2; // Compute intermediate values based on hue - float[] temp = { + float [] temp = { h + 1.0f / 3.0f, h, h - 1.0f / 3.0f, @@ -174,8 +171,8 @@ private void ChangeBrushColor (object sender, EventArgs e) private void OnAccelerated (object sender, UIAccelerometerEventArgs e) { #if LINQ - myAccelerometer = new[]{e.Acceleration.X, e.Acceleration.Y, e.Acceleration.Z} - .Select((v, i) => v * FilteringFactor + myAccelerometer [i] * (1.0f - FilteringFactor)) + myAccelerometer = new [] { e.Acceleration.X, e.Acceleration.Y, e.Acceleration.Z } + .Select ((v, i) => v * FilteringFactor + myAccelerometer [i] * (1.0f - FilteringFactor)) .ToArray (); #else myAccelerometer [0] = e.Acceleration.X * FilteringFactor + myAccelerometer [0] * (1.0 - FilteringFactor); diff --git a/GLPaint-GameView/PaintingView.cs b/GLPaint-GameView/PaintingView.cs index d777831e7..00523dc86 100644 --- a/GLPaint-GameView/PaintingView.cs +++ b/GLPaint-GameView/PaintingView.cs @@ -9,10 +9,8 @@ using System.Runtime.InteropServices; using CoreGraphics; -namespace GLPaintGameView -{ - public class PaintingView : iPhoneOSGameView - { +namespace GLPaintGameView { + public class PaintingView : iPhoneOSGameView { public const float BrushOpacity = 1.0f / 3.0f; public const int BrushPixelStep = 3; @@ -45,36 +43,36 @@ public PaintingView (CGRect frame) var width = brushImage.Width; var height = brushImage.Height; if (brushImage != null) { - IntPtr brushData = Marshal.AllocHGlobal ((int)(width * height * 4)); + IntPtr brushData = Marshal.AllocHGlobal ((int) (width * height * 4)); if (brushData == IntPtr.Zero) throw new OutOfMemoryException (); try { using (var brushContext = new CGBitmapContext (brushData, - width, width, 8, width * 4, brushImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) { - brushContext.DrawImage (new CGRect (0.0f, 0.0f, (float)width, (float)height), brushImage); + width, width, 8, width * 4, brushImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) { + brushContext.DrawImage (new CGRect (0.0f, 0.0f, (float) width, (float) height), brushImage); } GL.GenTextures (1, out brushTexture); GL.BindTexture (All.Texture2D, brushTexture); - GL.TexImage2D (All.Texture2D, 0, (int)All.Rgba, (int)width, (int)height, 0, All.Rgba, All.UnsignedByte, brushData); + GL.TexImage2D (All.Texture2D, 0, (int) All.Rgba, (int) width, (int) height, 0, All.Rgba, All.UnsignedByte, brushData); } finally { Marshal.FreeHGlobal (brushData); } - GL.TexParameter (All.Texture2D, All.TextureMinFilter, (int)All.Linear); + GL.TexParameter (All.Texture2D, All.TextureMinFilter, (int) All.Linear); GL.Enable (All.Texture2D); GL.BlendFunc (All.SrcAlpha, All.One); GL.Enable (All.Blend); } GL.Disable (All.Dither); GL.MatrixMode (All.Projection); - GL.Ortho (0, (int)frame.Width, 0, (int)frame.Height, -1, 1); + GL.Ortho (0, (int) frame.Width, 0, (int) frame.Height, -1, 1); GL.MatrixMode (All.Modelview); GL.Enable (All.Texture2D); GL.EnableClientState (All.VertexArray); GL.Enable (All.Blend); GL.BlendFunc (All.SrcAlpha, All.One); GL.Enable (All.PointSpriteOes); - GL.TexEnv (All.PointSpriteOes, All.CoordReplaceOes, (float)All.True); + GL.TexEnv (All.PointSpriteOes, All.CoordReplaceOes, (float) All.True); GL.PointSize (width / BrushScale); Erase (); @@ -95,7 +93,7 @@ public void Erase () SwapBuffers (); } - float[] vertexBuffer; + float [] vertexBuffer; int vertexMax = 64; private void RenderLineFromPoint (CGPoint start, CGPoint end) @@ -105,14 +103,14 @@ private void RenderLineFromPoint (CGPoint start, CGPoint end) vertexBuffer = new float [vertexMax * 2]; } var count = Math.Max (Math.Ceiling (Math.Sqrt ((end.X - start.X) * (end.X - start.X) + (end.Y - start.Y) * (end.Y - start.Y)) / BrushPixelStep), - 1); + 1); for (int i = 0; i < count; ++i, ++vertexCount) { if (vertexCount == vertexMax) { vertexMax *= 2; Array.Resize (ref vertexBuffer, vertexMax * 2); } - vertexBuffer [2 * vertexCount + 0] = (float)(start.X + (end.X - start.X) * (float)i / (float)count); - vertexBuffer [2 * vertexCount + 1] = (float)(start.Y + (end.Y - start.Y) * (float)i / (float)count); + vertexBuffer [2 * vertexCount + 0] = (float) (start.X + (end.X - start.X) * (float) i / (float) count); + vertexBuffer [2 * vertexCount + 1] = (float) (start.Y + (end.Y - start.Y) * (float) i / (float) count); } GL.VertexPointer (2, All.Float, 0, vertexBuffer); GL.DrawArrays (All.Points, 0, vertexCount); @@ -125,7 +123,7 @@ private void RenderLineFromPoint (CGPoint start, CGPoint end) [Export ("playback")] void Playback () { - CGPoint[] points = ShakeMe.Data [dataofs]; + CGPoint [] points = ShakeMe.Data [dataofs]; for (int i = 0; i < points.Length - 1; i++) RenderLineFromPoint (points [i], points [i + 1]); @@ -139,7 +137,7 @@ void Playback () public override void TouchesBegan (NSSet touches, UIEvent e) { var bounds = Bounds; - var touch = (UITouch)e.TouchesForView (this).AnyObject; + var touch = (UITouch) e.TouchesForView (this).AnyObject; firstTouch = true; Location = touch.LocationInView (this); Location.Y = bounds.Height - Location.Y; @@ -148,7 +146,7 @@ public override void TouchesBegan (NSSet touches, UIEvent e) public override void TouchesMoved (NSSet touches, UIEvent e) { var bounds = Bounds; - var touch = (UITouch)e.TouchesForView (this).AnyObject; + var touch = (UITouch) e.TouchesForView (this).AnyObject; if (firstTouch) { firstTouch = false; @@ -166,7 +164,7 @@ public override void TouchesMoved (NSSet touches, UIEvent e) public override void TouchesEnded (NSSet touches, UIEvent e) { var bounds = Bounds; - var touch = (UITouch)e.TouchesForView (this).AnyObject; + var touch = (UITouch) e.TouchesForView (this).AnyObject; if (firstTouch) { firstTouch = false; PreviousLocation = touch.PreviousLocationInView (this); diff --git a/GLPaint-GameView/ShakeMe.cs b/GLPaint-GameView/ShakeMe.cs index 8567cbab6..1e133fe5f 100644 --- a/GLPaint-GameView/ShakeMe.cs +++ b/GLPaint-GameView/ShakeMe.cs @@ -3,7 +3,7 @@ namespace GLPaintGameView { public class ShakeMe { - public static List Data = new List () { + public static List Data = new List () { new CGPoint [] { new CGPoint (62.000000f, 366.000000f), new CGPoint (52.000000f, 363.000000f), diff --git a/GLPaint-GameView/SoundEffect.cs b/GLPaint-GameView/SoundEffect.cs index 7ba792fcf..ba56bb0db 100644 --- a/GLPaint-GameView/SoundEffect.cs +++ b/GLPaint-GameView/SoundEffect.cs @@ -2,10 +2,8 @@ using Foundation; using AudioToolbox; -namespace GLPaintGameView -{ - public class SoundEffect : NSObject - { +namespace GLPaintGameView { + public class SoundEffect : NSObject { SystemSound sound; public SoundEffect (string path) diff --git a/GameCenterSample/GameCenterSample/AppDelegate.cs b/GameCenterSample/GameCenterSample/AppDelegate.cs index 6900bf900..981b9c79c 100644 --- a/GameCenterSample/GameCenterSample/AppDelegate.cs +++ b/GameCenterSample/GameCenterSample/AppDelegate.cs @@ -5,14 +5,12 @@ using UIKit; using GameKit; -namespace GameCenterSample -{ +namespace GameCenterSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; MainViewController viewController; @@ -27,9 +25,8 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - if (!isGameCenterAPIAvailable ()) - { - new UIAlertView ("Error", "Game Center is not supported on this device", null, "OK", null).Show(); + if (!isGameCenterAPIAvailable ()) { + new UIAlertView ("Error", "Game Center is not supported on this device", null, "OK", null).Show (); return true; } viewController = new MainViewController (); @@ -45,7 +42,7 @@ public override void DidEnterBackground (UIApplication application) { } - private bool isGameCenterAPIAvailable() + private bool isGameCenterAPIAvailable () { return UIDevice.CurrentDevice.CheckSystemVersion (4, 1); } diff --git a/GameCenterSample/GameCenterSample/Main.cs b/GameCenterSample/GameCenterSample/Main.cs index 524ce45f6..441b08b0b 100644 --- a/GameCenterSample/GameCenterSample/Main.cs +++ b/GameCenterSample/GameCenterSample/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace GameCenterSample -{ - public class Application - { +namespace GameCenterSample { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/GameCenterSample/GameCenterSample/MainViewController.cs b/GameCenterSample/GameCenterSample/MainViewController.cs index 655f380ce..2be2c2516 100644 --- a/GameCenterSample/GameCenterSample/MainViewController.cs +++ b/GameCenterSample/GameCenterSample/MainViewController.cs @@ -4,10 +4,8 @@ using UIKit; using GameKit; -namespace GameCenterSample -{ - public partial class MainViewController : UIViewController - { +namespace GameCenterSample { + public partial class MainViewController : UIViewController { public Action authenticatedHandler; public PlayerModel player; @@ -19,16 +17,16 @@ public MainViewController () : base ("MainViewController", null) authenticatedHandler = new Action ((error) => { if (GKLocalPlayer.LocalPlayer.Authenticated) { //Switching Users - if(currentPlayerID != null || currentPlayerID != GKLocalPlayer.LocalPlayer.PlayerID) - { + if (currentPlayerID != null || currentPlayerID != GKLocalPlayer.LocalPlayer.PlayerID) { currentPlayerID = GKLocalPlayer.LocalPlayer.PlayerID; - player = new PlayerModel(); - player.loadStoredScores(); - player.loadSotredAchievements(); + player = new PlayerModel (); + player.loadStoredScores (); + player.loadSotredAchievements (); } } else { var alert = new UIAlertView ("Game Center Account Required", "Need login the game center!", null, "Retry", null); - alert.Clicked += delegate { + alert.Clicked += delegate + { GKLocalPlayer.LocalPlayer.Authenticate (authenticatedHandler); }; alert.Show (); @@ -48,7 +46,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); this.scoreTextField.EditingDidEndOnExit += (object sender, EventArgs e) => { - this.scoreTextField.EndEditing(true); + this.scoreTextField.EndEditing (true); }; //Add event handler for our buttons @@ -73,7 +71,7 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat void resetAchievementsButtonHandleTouchUpInside (object sender, EventArgs e) { if (!GKLocalPlayer.LocalPlayer.Authenticated) { - new UIAlertView ("Error", "Need sign in Game Center to reset the achievement", null, "OK", null).Show(); + new UIAlertView ("Error", "Need sign in Game Center to reset the achievement", null, "OK", null).Show (); GKLocalPlayer.LocalPlayer.Authenticate (authenticatedHandler); return; } @@ -83,7 +81,7 @@ void resetAchievementsButtonHandleTouchUpInside (object sender, EventArgs e) void submitAchievementHandleTouchUpInside (object sender, EventArgs e) { if (!GKLocalPlayer.LocalPlayer.Authenticated) { - new UIAlertView ("Error", "Need sign in Game Center to submit the achievement", null, "OK", null).Show(); + new UIAlertView ("Error", "Need sign in Game Center to submit the achievement", null, "OK", null).Show (); GKLocalPlayer.LocalPlayer.Authenticate (authenticatedHandler); return; } @@ -100,18 +98,17 @@ void submitAchievementHandleTouchUpInside (object sender, EventArgs e) void submitScoreHandleTouchUpInside (object sender, EventArgs e) { if (!GKLocalPlayer.LocalPlayer.Authenticated) { - new UIAlertView ("Error", "Need sign in Game Center to submit the score", null, "OK", null).Show(); + new UIAlertView ("Error", "Need sign in Game Center to submit the score", null, "OK", null).Show (); GKLocalPlayer.LocalPlayer.Authenticate (authenticatedHandler); return; } GKScore submitScore = new GKScore ("leaderboard"); submitScore.Init (); - try{ - submitScore.Value = Convert.ToInt64(this.scoreTextField.Text); - } - catch{ - new UIAlertView ("Error", "Score should be a number", null, "OK", null).Show(); + try { + submitScore.Value = Convert.ToInt64 (this.scoreTextField.Text); + } catch { + new UIAlertView ("Error", "Score should be a number", null, "OK", null).Show (); return; } @@ -125,12 +122,12 @@ void leaderBoardButtonTouchUpInsideHander (object sender, EventArgs e) showLeaderboard (); } - void showLeaderboard() + void showLeaderboard () { GKLeaderboardViewController leaderboardViewController = new GKLeaderboardViewController (); leaderboardViewController.Category = "Leaderboard"; leaderboardViewController.DidFinish += (object sender, EventArgs e) => { - leaderboardViewController.DismissViewController(true, null); + leaderboardViewController.DismissViewController (true, null); }; this.PresentViewController (leaderboardViewController, true, null); } @@ -141,13 +138,13 @@ void showAchievementsHandleTouchUpInside (object sender, EventArgs e) showAchievements (); } - void showAchievements() + void showAchievements () { GKAchievementViewController achievementViewController = new GKAchievementViewController (); achievementViewController.DidFinish += (object sender, EventArgs e) => { - achievementViewController.DismissViewController(true, null); + achievementViewController.DismissViewController (true, null); }; - this.PresentViewController(achievementViewController, true, null); + this.PresentViewController (achievementViewController, true, null); } } diff --git a/GameCenterSample/GameCenterSample/PlayerModel.cs b/GameCenterSample/GameCenterSample/PlayerModel.cs index c5229a8be..81a924ab0 100644 --- a/GameCenterSample/GameCenterSample/PlayerModel.cs +++ b/GameCenterSample/GameCenterSample/PlayerModel.cs @@ -5,10 +5,8 @@ using GameKit; using UIKit; -namespace GameCenterSample -{ - public class PlayerModel - { +namespace GameCenterSample { + public class PlayerModel { string storedScoresFilename; string storedAchievementsFilename; @@ -57,7 +55,7 @@ public void resubmitSotredScores () new UIAlertView ("Score Stored", "Score Stored ", null, "OK", null).Show (); } })); - storedScores.RemoveObject ((nint)index); + storedScores.RemoveObject ((nint) index); index--; } } @@ -76,9 +74,9 @@ public void writeStoredScore () // Load stored scores from disk public void loadStoredScores () { - NSArray unarchivedObj = (NSArray)NSKeyedUnarchiver.UnarchiveFile (this.storedScoresFilename); + NSArray unarchivedObj = (NSArray) NSKeyedUnarchiver.UnarchiveFile (this.storedScoresFilename); if (unarchivedObj != null) { - storedScores = (NSMutableArray)unarchivedObj; + storedScores = (NSMutableArray) unarchivedObj; this.resubmitSotredScores (); } else { storedScores = new NSMutableArray (); @@ -113,7 +111,7 @@ public void submitScore (GKScore score) // Create an entry for an achievement that hasn't been submitted to the server void storeAchievement (GKAchievement achievement) { - GKAchievement currentStorage = (GKAchievement)storedAchievements.ValueForKey (new NSString (achievement.Identifier)); + GKAchievement currentStorage = (GKAchievement) storedAchievements.ValueForKey (new NSString (achievement.Identifier)); if (currentStorage == null) { storedAchievements.Add (new NSString (achievement.Identifier), achievement); @@ -157,7 +155,7 @@ public void loadSotredAchievements () { if (storedAchievements == null) { - NSMutableDictionary unarchivedObj = (NSMutableDictionary)NSKeyedUnarchiver.UnarchiveFile (this.storedAchievementsFilename); + NSMutableDictionary unarchivedObj = (NSMutableDictionary) NSKeyedUnarchiver.UnarchiveFile (this.storedAchievementsFilename); if (unarchivedObj != null) { this.resubmitStoredAchievements (); } else { @@ -171,7 +169,7 @@ public void resubmitStoredAchievements () { if (storedAchievements != null) { foreach (NSString key in storedAchievements.Keys) { - GKAchievement achievement = (GKAchievement)storedAchievements.ObjectForKey (key); + GKAchievement achievement = (GKAchievement) storedAchievements.ObjectForKey (key); this.submitAchievement (achievement); } } @@ -180,7 +178,8 @@ public void resubmitStoredAchievements () // Reset all the achievements for local player public void resetAchievements () { - GKAchievement.ResetAchivements (new Action (delegate(NSError error) { + GKAchievement.ResetAchivements (new Action (delegate (NSError error) + { if (error == null) new UIAlertView ("Achievement reset", "Achievement reset successfully", null, "OK", null).Show (); else diff --git a/GoogleAdMobAds/binding/admobads.cs b/GoogleAdMobAds/binding/admobads.cs index 0a4350210..0edf8e86b 100644 --- a/GoogleAdMobAds/binding/admobads.cs +++ b/GoogleAdMobAds/binding/admobads.cs @@ -5,11 +5,9 @@ using MonoTouch.UIKit; using MonoTouch.CoreGraphics; -namespace GoogleAdMobAds -{ - [BaseType (typeof(UIView))] - interface GADBannerView - { +namespace GoogleAdMobAds { + [BaseType (typeof (UIView))] + interface GADBannerView { //@property (nonatomic, copy) NSString *adUnitID; [Export ("adUnitID", ArgumentSemantic.Copy)] string AdUnitID { get; set; } @@ -39,10 +37,9 @@ interface GADBannerView } //@protocol GADBannerViewDelegate - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [Model] - interface GADBannerViewDelegate - { + interface GADBannerViewDelegate { //- (void)adViewDidReceiveAd:(GADBannerView *)view; [Export ("adViewDidReceiveAd:")] void AdViewDidReceiveAd (GADBannerView view); @@ -69,9 +66,8 @@ interface GADBannerViewDelegate } //@interface GADInterstitial : NSObject - [BaseType (typeof(NSObject))] - interface GADInterstitial - { + [BaseType (typeof (NSObject))] + interface GADInterstitial { //@property (nonatomic, copy) NSString *adUnitID; [Export ("adUnitID", ArgumentSemantic.Copy)] string AdUnitID { get; set; } @@ -102,10 +98,9 @@ interface GADInterstitial } //@protocol GADInterstitialDelegate - [BaseType (typeof(NSObject))] + [BaseType (typeof (NSObject))] [Model] - interface GADInterstitialDelegate - { + interface GADInterstitialDelegate { //- (void)interstitialDidReceiveAd:(GADInterstitial *)ad; [Export ("interstitialDidReceiveAd:")] void interstitialDidReceiveAd (GADInterstitial ad); @@ -132,9 +127,8 @@ interface GADInterstitialDelegate } //@interface GADRequest : NSObject - [BaseType (typeof(NSObject))] - interface GADRequest - { + [BaseType (typeof (NSObject))] + interface GADRequest { //+ (GADRequest *)request; [Static, Export ("request")] GADRequest Request (); @@ -185,9 +179,8 @@ interface GADRequest bool Testing { [Bind ("isTesting")] get; set; } } - [BaseType (typeof(NSError))] - interface GADRequestError - { + [BaseType (typeof (NSError))] + interface GADRequestError { } } diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/AppDelegate.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/AppDelegate.cs index 8ac7f4492..517553a44 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/AppDelegate.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace AnimationSamples -{ +namespace AnimationSamples { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/DemoViewTransition.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/DemoViewTransition.cs index dd856586c..f4c2a28e0 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/DemoViewTransition.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/DemoViewTransition.cs @@ -1,16 +1,14 @@ -using System; +using System; using UIKit; -namespace AnimationSamples -{ - public class DemoViewTransition : UIViewController - { - static readonly UIStoryboard MainStoryboard = UIStoryboard.FromName ("Main", null); +namespace AnimationSamples { + public class DemoViewTransition : UIViewController { + static readonly UIStoryboard MainStoryboard = UIStoryboard.FromName ("Main", null); UIView fromView; UIView toView; - public override void ViewDidLoad() + public override void ViewDidLoad () { base.ViewDidLoad (); View.BackgroundColor = UIColor.White; @@ -33,10 +31,10 @@ public override void ViewDidLoad() fromView.AddGestureRecognizer (new UITapGestureRecognizer (() => UIView.Transition (fromView, toView, 2, options, () => Console.WriteLine ("transition complete")))); toView.AddGestureRecognizer (new UITapGestureRecognizer (() => { - var initalViewController = (ViewController)MainStoryboard.InstantiateViewController("InitalViewController"); + var initalViewController = (ViewController) MainStoryboard.InstantiateViewController ("InitalViewController"); initalViewController.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve; - PresentViewController(initalViewController, true, null); + PresentViewController (initalViewController, true, null); })); } } -} \ No newline at end of file +} diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ExplicitLayerAnimation.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ExplicitLayerAnimation.cs index c042b1b62..9b96cc579 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ExplicitLayerAnimation.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ExplicitLayerAnimation.cs @@ -1,11 +1,9 @@ -using CoreGraphics; +using CoreGraphics; using CoreAnimation; using UIKit; -namespace AnimationSamples -{ - public class ExplicitLayerAnimation : UIViewController - { +namespace AnimationSamples { + public class ExplicitLayerAnimation : UIViewController { static UIStoryboard MainStoryboard = UIStoryboard.FromName ("Main", null); CALayer layer; @@ -28,9 +26,9 @@ public override void ViewDidLoad () View.Layer.AddSublayer (layer); View.AddGestureRecognizer (new UITapGestureRecognizer (() => { - var initalViewController = (ViewController)MainStoryboard.InstantiateViewController("InitalViewController"); + var initalViewController = (ViewController) MainStoryboard.InstantiateViewController ("InitalViewController"); initalViewController.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal; - PresentViewController(initalViewController, true, null); + PresentViewController (initalViewController, true, null); })); } @@ -48,7 +46,7 @@ after the animation completes */ //Create a path for the animation to follow var path = new CGPath (); - path.AddLines (new []{ fromPt, new CGPoint (50, 300), new CGPoint (200, 50), new CGPoint (200, 300) }); + path.AddLines (new [] { fromPt, new CGPoint (50, 300), new CGPoint (200, 50), new CGPoint (200, 300) }); // create a keyframe animation for the position using the path CAKeyFrameAnimation animPosition = CAKeyFrameAnimation.FromKeyPath ("position"); @@ -61,4 +59,4 @@ when the layer positino is set above*/ layer.AddAnimation (animPosition, "position"); } } -} \ No newline at end of file +} diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ImplicitLayerAnimation.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ImplicitLayerAnimation.cs index b005d7a07..27a802436 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ImplicitLayerAnimation.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ImplicitLayerAnimation.cs @@ -1,11 +1,9 @@ -using CoreAnimation; +using CoreAnimation; using CoreGraphics; using UIKit; -namespace AnimationSamples -{ - public class ImplicitLayerAnimation : UIViewController - { +namespace AnimationSamples { + public class ImplicitLayerAnimation : UIViewController { static UIStoryboard MainStoryboard = UIStoryboard.FromName ("Main", null); CALayer layer; @@ -28,9 +26,9 @@ public override void ViewDidLoad () View.Layer.AddSublayer (layer); View.AddGestureRecognizer (new UITapGestureRecognizer (() => { - var initalViewController = (ViewController)MainStoryboard.InstantiateViewController("InitalViewController"); + var initalViewController = (ViewController) MainStoryboard.InstantiateViewController ("InitalViewController"); initalViewController.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal; - PresentViewController(initalViewController, true, null); + PresentViewController (initalViewController, true, null); })); } @@ -38,7 +36,7 @@ public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); - CATransaction.Begin(); + CATransaction.Begin (); CATransaction.AnimationDuration = 10; layer.Position = new CGPoint (150, 550); layer.BorderWidth = 5.0f; @@ -46,4 +44,4 @@ public override void ViewDidAppear (bool animated) CATransaction.Commit (); } } -} \ No newline at end of file +} diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/Main.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/Main.cs index 887cfb155..20768ba78 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/Main.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace AnimationSamples -{ - public class Application - { +namespace AnimationSamples { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/SecondViewController.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/SecondViewController.cs index 725c71262..8c0201f12 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/SecondViewController.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/SecondViewController.cs @@ -1,10 +1,8 @@ using System; using UIKit; -namespace AnimationSamples -{ - partial class SecondViewController : UIViewController - { +namespace AnimationSamples { + partial class SecondViewController : UIViewController { public SecondViewController (IntPtr handle) : base (handle) { } diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewController.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewController.cs index 2fb295c91..421a03d3a 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewController.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewController.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace AnimationSamples -{ - public partial class ViewController : UIViewController - { +namespace AnimationSamples { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } @@ -15,7 +13,7 @@ public override void ViewDidLoad () // Perform any additional setup after loading the view, typically from a nib. TransitionButton.TouchUpInside += (sender, e) => { - var vc2 = (SecondViewController)Storyboard.InstantiateViewController ("SecondViewController"); + var vc2 = (SecondViewController) Storyboard.InstantiateViewController ("SecondViewController"); vc2.ModalTransitionStyle = UIModalTransitionStyle.PartialCurl; PresentViewController (vc2, true, null); }; @@ -41,4 +39,4 @@ public override void ViewDidLoad () }; } } -} \ No newline at end of file +} diff --git a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewPropertyAnimation.cs b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewPropertyAnimation.cs index 7d7fe6b9b..e23811c45 100644 --- a/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewPropertyAnimation.cs +++ b/GraphicsAndAnimation/CoreAnimation/AnimationSamples/ViewPropertyAnimation.cs @@ -1,10 +1,8 @@ -using UIKit; +using UIKit; using CoreGraphics; -namespace AnimationSamples -{ - public class ViewPropertyAnimation : UIViewController - { +namespace AnimationSamples { + public class ViewPropertyAnimation : UIViewController { readonly UIStoryboard MainStoryboard = UIStoryboard.FromName ("Main", null); CGPoint pt; @@ -44,10 +42,10 @@ public override void ViewDidLoad () }); View.AddGestureRecognizer (new UITapGestureRecognizer (() => { - var initalViewController = (ViewController)MainStoryboard.InstantiateViewController("InitalViewController"); + var initalViewController = (ViewController) MainStoryboard.InstantiateViewController ("InitalViewController"); initalViewController.ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve; - PresentViewController(initalViewController, true, null); + PresentViewController (initalViewController, true, null); })); } } -} \ No newline at end of file +} diff --git a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/AppDelegate.cs b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/AppDelegate.cs index 4263c7684..7ae863b63 100644 --- a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/AppDelegate.cs +++ b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/AppDelegate.cs @@ -4,35 +4,33 @@ using Foundation; using UIKit; -namespace CoreGraphicsSamples -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; - CoreGraphicsSamplesViewController viewController; +namespace CoreGraphicsSamples { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; + CoreGraphicsSamplesViewController viewController; - // - // This method is invoked when the application has loaded and is ready to run. In this - // method you should instantiate the window, load the UI into it and then make the window - // visible. - // - // You have 17 seconds to return from this method, or iOS will terminate your application. - // - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); - - viewController = new CoreGraphicsSamplesViewController (); - window.RootViewController = viewController; - window.MakeKeyAndVisible (); - - return true; - } - } + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); + + viewController = new CoreGraphicsSamplesViewController (); + window.RootViewController = viewController; + window.MakeKeyAndVisible (); + + return true; + } + } } diff --git a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/CoreGraphicsSamplesViewController.cs b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/CoreGraphicsSamplesViewController.cs index d32b57518..1af620d7c 100644 --- a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/CoreGraphicsSamplesViewController.cs +++ b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/CoreGraphicsSamplesViewController.cs @@ -3,30 +3,28 @@ using System; using Foundation; -namespace CoreGraphicsSamples -{ - public partial class CoreGraphicsSamplesViewController : UIViewController - { -// TriangleView triangleView; +namespace CoreGraphicsSamples { + public partial class CoreGraphicsSamplesViewController : UIViewController { + // TriangleView triangleView; DrawnImageView drawnImageView; -// PDFView pdfView; - + // PDFView pdfView; + public CoreGraphicsSamplesViewController () { } - + public override void ViewDidLoad () { base.ViewDidLoad (); -// triangleView = new TriangleView (){Frame = UIScreen.MainScreen.Bounds}; -// View.AddSubview (triangleView); + // triangleView = new TriangleView (){Frame = UIScreen.MainScreen.Bounds}; + // View.AddSubview (triangleView); - drawnImageView = new DrawnImageView (){Frame = UIScreen.MainScreen.Bounds}; - View.AddSubview(drawnImageView); + drawnImageView = new DrawnImageView () { Frame = UIScreen.MainScreen.Bounds }; + View.AddSubview (drawnImageView); -// pdfView = new PDFView (){Frame = UIScreen.MainScreen.Bounds}; -// View.AddSubview(pdfView); + // pdfView = new PDFView (){Frame = UIScreen.MainScreen.Bounds}; + // View.AddSubview(pdfView); } } } diff --git a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/DrawnImageView.cs b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/DrawnImageView.cs index 53298bfbc..873aa3b72 100644 --- a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/DrawnImageView.cs +++ b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/DrawnImageView.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace CoreGraphicsSamples -{ - public class DrawnImageView : UIView - { +namespace CoreGraphicsSamples { + public class DrawnImageView : UIView { public DrawnImageView () { BackgroundColor = UIColor.White; @@ -14,14 +12,14 @@ public DrawnImageView () public override void Draw (CGRect rect) { base.Draw (rect); - + using (CGContext g = UIGraphics.GetCurrentContext ()) { // scale and translate the CTM so the image appears upright g.ScaleCTM (1, -1); g.TranslateCTM (0, -Bounds.Height); g.DrawImage (rect, UIImage.FromFile ("MyImage.png").CGImage); - + // translate the CTM by the font size so it displays on screen float fontSize = 35f; g.TranslateCTM (0, fontSize); @@ -31,7 +29,7 @@ public override void Draw (CGRect rect) g.SetStrokeColor (UIColor.Yellow.CGColor); g.SetFillColor (UIColor.Red.CGColor); g.SetShadow (new CGSize (5, 5), 0, UIColor.Blue.CGColor); - + // set text specific graphics state g.SetTextDrawingMode (CGTextDrawingMode.FillStroke); g.SelectFont ("Helvetica", fontSize, CGTextEncoding.MacRoman); diff --git a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/Main.cs b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/Main.cs index f602ef6b9..e31aaec75 100644 --- a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/Main.cs +++ b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/Main.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace CoreGraphicsSamples -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace CoreGraphicsSamples { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/PDFView.cs b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/PDFView.cs index 0dd8dbf62..0dcc2ecb2 100644 --- a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/PDFView.cs +++ b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/PDFView.cs @@ -3,12 +3,10 @@ using CoreGraphics; using Foundation; -namespace CoreGraphicsSamples -{ - public class PDFView : UIView - { +namespace CoreGraphicsSamples { + public class PDFView : UIView { CGPDFDocument pdfDoc; - + public PDFView () { BackgroundColor = UIColor.White; @@ -20,15 +18,15 @@ public PDFView () public override void Draw (CGRect rect) { base.Draw (rect); - + //flip the CTM so the PDF will be drawn upright using (CGContext g = UIGraphics.GetCurrentContext ()) { g.TranslateCTM (0, Bounds.Height); g.ScaleCTM (1, -1); - + // render the first page of the PDF using (CGPDFPage pdfPage = pdfDoc.GetPage (1)) { - + //get the affine transform that defines where the PDF is drawn CGAffineTransform t = pdfPage.GetDrawingTransform (CGPDFBox.Crop, rect, 0, true); //concatenate the pdf transform with the CTM for display in the view @@ -46,10 +44,10 @@ void DrawPDFInMemory () //create a PDF with empty rectangle, which will configure it for 8.5x11 inches UIGraphics.BeginPDFContext (data, CGRect.Empty, null); //start a PDF page - UIGraphics.BeginPDFPage (); + UIGraphics.BeginPDFPage (); using (CGContext g = UIGraphics.GetCurrentContext ()) { g.ScaleCTM (1, -1); - g.TranslateCTM (0, -25); + g.TranslateCTM (0, -25); g.SelectFont ("Helvetica", 25, CGTextEncoding.MacRoman); g.ShowText ("Hello Core Graphics"); } diff --git a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/TriangleView.cs b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/TriangleView.cs index 486d95321..d9382af76 100644 --- a/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/TriangleView.cs +++ b/GraphicsAndAnimation/CoreGraphics/CoreGraphicsSamples/TriangleView.cs @@ -2,10 +2,8 @@ using CoreGraphics; using UIKit; -namespace CoreGraphicsSamples -{ - public class TriangleView : UIView - { +namespace CoreGraphicsSamples { + public class TriangleView : UIView { public TriangleView () { BackgroundColor = UIColor.White; @@ -14,50 +12,50 @@ public TriangleView () public override void Draw (CGRect rect) { base.Draw (rect); - + //get graphics context using (CGContext g = UIGraphics.GetCurrentContext ()) { - + //set up drawing attributes g.SetLineWidth (10); UIColor.Blue.SetFill (); UIColor.Red.SetStroke (); - + //create geometry var path = new CGPath (); - - path.AddLines (new CGPoint[]{ + + path.AddLines (new CGPoint []{ new CGPoint (100, 200), - new CGPoint (160, 100), + new CGPoint (160, 100), new CGPoint (220, 200)}); - + path.CloseSubpath (); - + //use a dashed line - g.SetLineDash (0, new nfloat[] { 10, 4 * (nfloat)Math.PI }); + g.SetLineDash (0, new nfloat [] { 10, 4 * (nfloat) Math.PI }); + - //add geometry to graphics context and draw it - g.AddPath (path); + g.AddPath (path); g.DrawPath (CGPathDrawingMode.FillStroke); - + // add the path back to the graphics context so that it is the current path g.AddPath (path); // set the current path to be the clipping path g.Clip (); - + // the color space determines how Core Graphics interprets color information - using (CGColorSpace rgb = CGColorSpace.CreateDeviceRGB()) { - CGGradient gradient = new CGGradient (rgb, new CGColor[] { + using (CGColorSpace rgb = CGColorSpace.CreateDeviceRGB ()) { + CGGradient gradient = new CGGradient (rgb, new CGColor [] { UIColor.Blue.CGColor, UIColor.Yellow.CGColor }); - + // draw a linear gradient g.DrawLinearGradient ( - gradient, - new CGPoint (path.BoundingBox.Left, path.BoundingBox.Top), - new CGPoint (path.BoundingBox.Right, path.BoundingBox.Bottom), + gradient, + new CGPoint (path.BoundingBox.Left, path.BoundingBox.Top), + new CGPoint (path.BoundingBox.Right, path.BoundingBox.Bottom), CGGradientDrawingOptions.DrawsBeforeStartLocation); } @@ -66,17 +64,17 @@ public override void Draw (CGRect rect) } -// UITableViewCell cellView as new; -// var anyView; -// -// UIGraphics.BeginImageContext (cellView.Frame.Size); -// -// //render the view's layer in the current context -// anyView.Layer.RenderInContext (UIGraphics.GetCurrentContext ()); -// -// //get a UIImage from the context -// UIImage anyViewImage = UIGraphics.GetImageFromCurrentImageContext (); -// UIGraphics.EndImageContext (); + // UITableViewCell cellView as new; + // var anyView; + // + // UIGraphics.BeginImageContext (cellView.Frame.Size); + // + // //render the view's layer in the current context + // anyView.Layer.RenderInContext (UIGraphics.GetCurrentContext ()); + // + // //get a UIImage from the context + // UIImage anyViewImage = UIGraphics.GetImageFromCurrentImageContext (); + // UIGraphics.EndImageContext (); } } } diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/AppDelegate.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/AppDelegate.cs index d4762c7e6..6130c9944 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/AppDelegate.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/AppDelegate.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace GraphicsDemo -{ +namespace GraphicsDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; GraphicsDemoViewController viewController; @@ -27,11 +25,11 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - + viewController = new GraphicsDemoViewController (); window.RootViewController = viewController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/DemoView.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/DemoView.cs index 9fb8f509d..ae4524a61 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/DemoView.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/DemoView.cs @@ -4,10 +4,8 @@ using CoreAnimation; using Foundation; -namespace GraphicsDemo -{ - public class DemoView : UIView - { +namespace GraphicsDemo { + public class DemoView : UIView { CGPath path; CGPoint initialPoint; CGPoint latestPoint; @@ -66,7 +64,7 @@ public override void TouchesEnded (NSSet touches, UIEvent evt) // create a keyframe animation for the position using the path layer.Position = latestPoint; - CAKeyFrameAnimation animPosition = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath ("position"); + CAKeyFrameAnimation animPosition = (CAKeyFrameAnimation) CAKeyFrameAnimation.FromKeyPath ("position"); animPosition.Path = path; animPosition.Duration = 3; layer.AddAnimation (animPosition, "position"); @@ -79,7 +77,7 @@ public override void Draw (CGRect rect) if (!initialPoint.IsEmpty) { //get graphics context - using(CGContext g = UIGraphics.GetCurrentContext ()){ + using (CGContext g = UIGraphics.GetCurrentContext ()) { //set up drawing attributes g.SetLineWidth (2); @@ -87,19 +85,19 @@ public override void Draw (CGRect rect) //add lines to the touch points if (path.IsEmpty) { - path.AddLines (new CGPoint[]{initialPoint, latestPoint}); + path.AddLines (new CGPoint [] { initialPoint, latestPoint }); } else { path.AddLineToPoint (latestPoint); } //use a dashed line - g.SetLineDash (0, new nfloat[] { 5, 2 * (nfloat)Math.PI }); + g.SetLineDash (0, new nfloat [] { 5, 2 * (nfloat) Math.PI }); //add geometry to graphics context and draw it - g.AddPath (path); + g.AddPath (path); g.DrawPath (CGPathDrawingMode.Stroke); } } - } + } } } diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/GraphicsDemoViewController.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/GraphicsDemoViewController.cs index 25bf97452..eee3debb5 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/GraphicsDemoViewController.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/GraphicsDemoViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace GraphicsDemo -{ - public partial class GraphicsDemoViewController : UIViewController - { +namespace GraphicsDemo { + public partial class GraphicsDemoViewController : UIViewController { DemoView demo; public GraphicsDemoViewController () @@ -18,10 +16,10 @@ public override void LoadView () { base.LoadView (); - demo = new DemoView{Frame = UIScreen.MainScreen.Bounds}; + demo = new DemoView { Frame = UIScreen.MainScreen.Bounds }; View = demo; } - + public override void ViewDidLoad () { base.ViewDidLoad (); diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/Main.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/Main.cs index c32b2f225..13cdef2f0 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/Main.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_Finished/GraphicsDemo/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace GraphicsDemo -{ - public class Application - { +namespace GraphicsDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/AppDelegate.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/AppDelegate.cs index d4762c7e6..6130c9944 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/AppDelegate.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/AppDelegate.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace GraphicsDemo -{ +namespace GraphicsDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; GraphicsDemoViewController viewController; @@ -27,11 +25,11 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - + viewController = new GraphicsDemoViewController (); window.RootViewController = viewController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/DemoView.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/DemoView.cs index 44894591f..e91b2fc26 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/DemoView.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/DemoView.cs @@ -4,102 +4,100 @@ //using CoreAnimation; //using Foundation; -namespace GraphicsDemo -{ - public class DemoView : UIView - { -// CGPath path; -// CGPoint initialPoint; -// CGPoint latestPoint; -// -// CALayer layer; +namespace GraphicsDemo { + public class DemoView : UIView { + // CGPath path; + // CGPoint initialPoint; + // CGPoint latestPoint; + // + // CALayer layer; public DemoView () { BackgroundColor = UIColor.White; -// path = new CGPath (); + // path = new CGPath (); -// //create layer -// layer = new CALayer (); -// layer.Bounds = new CGRect (0, 0, 50, 50); -// layer.Position = new CGPoint (50, 50); -// layer.Contents = UIImage.FromFile ("monkey.png").CGImage; -// layer.ContentsGravity = CALayer.GravityResizeAspect; -// layer.BorderWidth = 1.5f; -// layer.CornerRadius = 5; -// layer.BorderColor = UIColor.Blue.CGColor; -// layer.BackgroundColor = UIColor.Purple.CGColor; + // //create layer + // layer = new CALayer (); + // layer.Bounds = new CGRect (0, 0, 50, 50); + // layer.Position = new CGPoint (50, 50); + // layer.Contents = UIImage.FromFile ("monkey.png").CGImage; + // layer.ContentsGravity = CALayer.GravityResizeAspect; + // layer.BorderWidth = 1.5f; + // layer.CornerRadius = 5; + // layer.BorderColor = UIColor.Blue.CGColor; + // layer.BackgroundColor = UIColor.Purple.CGColor; } -// public override void TouchesBegan (NSSet touches, UIEvent evt) -// { -// base.TouchesBegan (touches, evt); -// -// UITouch touch = touches.AnyObject as UITouch; -// -// if (touch != null) { -// initialPoint = touch.LocationInView (this); -// } -// } -// -// public override void TouchesMoved (NSSet touches, UIEvent evt) -// { -// base.TouchesMoved (touches, evt); -// -// UITouch touch = touches.AnyObject as UITouch; -// -// if (touch != null) { -// latestPoint = touch.LocationInView (this); -// SetNeedsDisplay (); -// } -// } -// -// public override void TouchesEnded (NSSet touches, UIEvent evt) -// { -// base.TouchesEnded (touches, evt); -// -// //add layer with image and animate along path -// -// if (layer.SuperLayer == null) -// Layer.AddSublayer (layer); -// -// // create a keyframe animation for the position using the path -// layer.Position = latestPoint; -// CAKeyFrameAnimation animPosition = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath ("position"); -// animPosition.Path = path; -// animPosition.Duration = 3; -// layer.AddAnimation (animPosition, "position"); -// } -// -// public override void Draw (CGRect rect) -// { -// base.Draw (rect); -// -// if (!initialPoint.IsEmpty) { -// -// //get graphics context -// using(CGContext g = UIGraphics.GetCurrentContext ()){ -// -// //set up drawing attributes -// g.SetLineWidth (2); -// UIColor.Red.SetStroke (); -// -// //add lines to the touch points -// if (path.IsEmpty) { -// path.AddLines (new CGPoint[]{initialPoint, latestPoint}); -// } else { -// path.AddLineToPoint (latestPoint); -// } -// -// //use a dashed line -// g.SetLineDash (0, new nfloat[] { 5, 2 * (nfloat)Math.PI }); -// -// //add geometry to graphics context and draw it -// g.AddPath (path); -// g.DrawPath (CGPathDrawingMode.Stroke); -// } -// } -// } + // public override void TouchesBegan (NSSet touches, UIEvent evt) + // { + // base.TouchesBegan (touches, evt); + // + // UITouch touch = touches.AnyObject as UITouch; + // + // if (touch != null) { + // initialPoint = touch.LocationInView (this); + // } + // } + // + // public override void TouchesMoved (NSSet touches, UIEvent evt) + // { + // base.TouchesMoved (touches, evt); + // + // UITouch touch = touches.AnyObject as UITouch; + // + // if (touch != null) { + // latestPoint = touch.LocationInView (this); + // SetNeedsDisplay (); + // } + // } + // + // public override void TouchesEnded (NSSet touches, UIEvent evt) + // { + // base.TouchesEnded (touches, evt); + // + // //add layer with image and animate along path + // + // if (layer.SuperLayer == null) + // Layer.AddSublayer (layer); + // + // // create a keyframe animation for the position using the path + // layer.Position = latestPoint; + // CAKeyFrameAnimation animPosition = (CAKeyFrameAnimation)CAKeyFrameAnimation.FromKeyPath ("position"); + // animPosition.Path = path; + // animPosition.Duration = 3; + // layer.AddAnimation (animPosition, "position"); + // } + // + // public override void Draw (CGRect rect) + // { + // base.Draw (rect); + // + // if (!initialPoint.IsEmpty) { + // + // //get graphics context + // using(CGContext g = UIGraphics.GetCurrentContext ()){ + // + // //set up drawing attributes + // g.SetLineWidth (2); + // UIColor.Red.SetStroke (); + // + // //add lines to the touch points + // if (path.IsEmpty) { + // path.AddLines (new CGPoint[]{initialPoint, latestPoint}); + // } else { + // path.AddLineToPoint (latestPoint); + // } + // + // //use a dashed line + // g.SetLineDash (0, new nfloat[] { 5, 2 * (nfloat)Math.PI }); + // + // //add geometry to graphics context and draw it + // g.AddPath (path); + // g.DrawPath (CGPathDrawingMode.Stroke); + // } + // } + // } } } diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/GraphicsDemoViewController.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/GraphicsDemoViewController.cs index 25bf97452..eee3debb5 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/GraphicsDemoViewController.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/GraphicsDemoViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace GraphicsDemo -{ - public partial class GraphicsDemoViewController : UIViewController - { +namespace GraphicsDemo { + public partial class GraphicsDemoViewController : UIViewController { DemoView demo; public GraphicsDemoViewController () @@ -18,10 +16,10 @@ public override void LoadView () { base.LoadView (); - demo = new DemoView{Frame = UIScreen.MainScreen.Bounds}; + demo = new DemoView { Frame = UIScreen.MainScreen.Bounds }; View = demo; } - + public override void ViewDidLoad () { base.ViewDidLoad (); diff --git a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/Main.cs b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/Main.cs index c32b2f225..13cdef2f0 100644 --- a/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/Main.cs +++ b/GraphicsAndAnimation/GraphicsWalkthrough/GraphicsDemo_starter/GraphicsDemo/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace GraphicsDemo -{ - public class Application - { +namespace GraphicsDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/GrowRowTable/GrowRowTable/AppDelegate.cs b/GrowRowTable/GrowRowTable/AppDelegate.cs index a9f56420c..dacad3f74 100644 --- a/GrowRowTable/GrowRowTable/AppDelegate.cs +++ b/GrowRowTable/GrowRowTable/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace GrowRowTable -{ +namespace GrowRowTable { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/GrowRowTable/GrowRowTable/Classes/GrowItem.cs b/GrowRowTable/GrowRowTable/Classes/GrowItem.cs index 1efbce729..8be7d51c5 100644 --- a/GrowRowTable/GrowRowTable/Classes/GrowItem.cs +++ b/GrowRowTable/GrowRowTable/Classes/GrowItem.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace GrowRowTable -{ - public class GrowItem - { +namespace GrowRowTable { + public class GrowItem { public string ImageName { get; set; } = ""; public string Title { get; set; } = ""; public string Description { get; set; } = ""; diff --git a/GrowRowTable/GrowRowTable/Classes/GrowRowTableDataSource.cs b/GrowRowTable/GrowRowTable/Classes/GrowRowTableDataSource.cs index b25121cea..059b10549 100644 --- a/GrowRowTable/GrowRowTable/Classes/GrowRowTableDataSource.cs +++ b/GrowRowTable/GrowRowTable/Classes/GrowRowTableDataSource.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Collections.Generic; using UIKit; -namespace GrowRowTable -{ - public class GrowRowTableDataSource : UITableViewDataSource - { - public List Items = new List(); +namespace GrowRowTable { + public class GrowRowTableDataSource : UITableViewDataSource { + public List Items = new List (); public string CellID { get { return "GrowCell"; } @@ -15,25 +13,26 @@ public string CellID { public GrowRowTableDataSource () { // Initialize - Initialize(); + Initialize (); } - private void Initialize() { + private void Initialize () + { // Populate database - Items.Add(new GrowItem("Macintosh_128k.png","Macintosh 128K","The Macintosh 128K, originally released as the Apple Macintosh, is the original Apple Macintosh personal computer. Its beige case consisted of a 9 in (23 cm) CRT monitor and came with a keyboard and mouse. A handle built into the top of the case made it easier for the computer to be lifted and carried. It had an initial selling price of $2,495 (equivalent to $5,683 in 2015).")); - Items.Add(new GrowItem("Macintosh_512K.png","Macintosh 512K","The Macintosh 512K Personal Computer is the second of a long line of Apple Macintosh computers, and was the first update to the original Macintosh 128K. It was virtually identical to the previous Mac, differing primarily in the amount of built-in memory (RAM).")); - Items.Add(new GrowItem("Macintosh_Plus.jpg","Macintosh Plus","The Macintosh Plus computer is the third model in the Macintosh line, introduced on January 16, 1986, two years after the original Macintosh and a little more than a year after the Macintosh 512K, with a price tag of US$2599. As an evolutionary improvement over the 512K, it shipped with 1 MB of RAM standard, expandable to 4 MB, and an external SCSI peripheral bus, among smaller improvements.")); - Items.Add(new GrowItem("Macintosh_SE.jpg","Macintosh SE","The Macintosh SE is a personal computer manufactured by Apple between March 1987 and October 1990. This computer marked a significant improvement on the Macintosh Plus design and was introduced by Apple at the same time as the Macintosh II. It had a similar case to the original Macintosh computer, but with slight differences in color and styling.")); - Items.Add(new GrowItem("MacII.jpg","Macintosh II","The Apple Macintosh II is the first personal computer model of the Macintosh II series in the Apple Macintosh line and the first Macintosh to support a color display. A basic system with 20 MB drive and monitor cost about $5500, A complete color-capable system could cost as much as $10,000 once the cost of the color monitor, video card, hard disk, keyboard and RAM were added. ")); - Items.Add(new GrowItem("SE30.jpg","Macintosh SE/30","The Macintosh SE/30 is a personal computer that was designed, manufactured and sold by Apple Computer, Inc. from 1989 until 1991. It was the fastest of the original black-and-white compact Macintosh series.")); - Items.Add(new GrowItem("Macintosh_Portable.jpg","Macintosh Portable","The Macintosh Portable was Apple Inc.'s first battery-powered portable Macintosh personal computer. Released on September 20, 1989, it was received with excitement from most critics but consumer sales were quite low. It featured a fast, sharp, and expensive black and white active matrix LCD screen in a hinged design that covered the keyboard when the machine was not in use.")); - Items.Add(new GrowItem("Macintosh_Classic.jpg","Macintosh Classic","The Macintosh Classic is a personal computer manufactured by Apple Inc. Introduced on October 15, 1990, it was the first Apple Macintosh to sell for less than US$1,000. Production of the Classic was prompted by the success of the Macintosh Plus and the Macintosh SE. The system specifications of the Classic were very similar to its predecessors, with the same 9-inch (23 cm) monochrome CRT display, 512×342 pixel resolution, and 4 megabyte (MB) memory limit of the older Macintosh computers.")); - Items.Add(new GrowItem("Macintosh_LC.jpg","Macintosh LC","The Macintosh LC (meaning low-cost color) is Apple Computer's product family of low-end consumer Macintosh personal computers in the early 1990s. The original Macintosh LC was released in October 1990 and was the first affordable color-capable Macintosh. Due to its affordability and Apple II compatibility the LC was adopted primarily in the education and home markets.")); - Items.Add(new GrowItem("Powerbook_150.jpg","Powerbook","The PowerBook (known as Macintosh PowerBook before 1997) is a line of Macintosh laptop computers that was designed, manufactured and sold by Apple Computer, Inc. from 1991 to 2006. During its lifetime, the PowerBook went through several major revisions and redesigns, often being the first to incorporate features that would later become standard in competing laptops.")); - Items.Add(new GrowItem("Macintosh_Classic_2.jpg","Macintosh Classic II","The Apple Macintosh Classic II (also known as the Performa 200) replaced the Macintosh SE/30 in the compact Macintosh line in 1991. Like the SE/30, the Classic II was powered by a 16 MHz Motorola 68030 CPU and 40 or 80 MB hard disk, but in contrast to its predecessor, it was limited by a 16-bit data bus (the SE/30 had a 32-bit data bus) and a 10 MB memory ceiling.")); - Items.Add(new GrowItem("Macintosh_Color_Classic.jpg","Macintosh Color Classic","The Macintosh Color Classic, released on February 10, 1993, is the first color compact Apple Macintosh computer. It has an integrated 10″ Sony Trinitron color display with the same 512×384 pixel resolution as the Macintosh 12″ RGB monitor. It can display 256 colors(Can upgrade to 4096 colors). ")); - Items.Add(new GrowItem("Power_Macintosh.jpg","Power Macintosh","Power Macintosh, later Power Mac, is a line of Apple Macintosh workstation-class personal computers based on various models of PowerPC microprocessors that were developed, marketed, and supported by Apple Inc. from March 1994 until August 2006. ")); + Items.Add (new GrowItem ("Macintosh_128k.png", "Macintosh 128K", "The Macintosh 128K, originally released as the Apple Macintosh, is the original Apple Macintosh personal computer. Its beige case consisted of a 9 in (23 cm) CRT monitor and came with a keyboard and mouse. A handle built into the top of the case made it easier for the computer to be lifted and carried. It had an initial selling price of $2,495 (equivalent to $5,683 in 2015).")); + Items.Add (new GrowItem ("Macintosh_512K.png", "Macintosh 512K", "The Macintosh 512K Personal Computer is the second of a long line of Apple Macintosh computers, and was the first update to the original Macintosh 128K. It was virtually identical to the previous Mac, differing primarily in the amount of built-in memory (RAM).")); + Items.Add (new GrowItem ("Macintosh_Plus.jpg", "Macintosh Plus", "The Macintosh Plus computer is the third model in the Macintosh line, introduced on January 16, 1986, two years after the original Macintosh and a little more than a year after the Macintosh 512K, with a price tag of US$2599. As an evolutionary improvement over the 512K, it shipped with 1 MB of RAM standard, expandable to 4 MB, and an external SCSI peripheral bus, among smaller improvements.")); + Items.Add (new GrowItem ("Macintosh_SE.jpg", "Macintosh SE", "The Macintosh SE is a personal computer manufactured by Apple between March 1987 and October 1990. This computer marked a significant improvement on the Macintosh Plus design and was introduced by Apple at the same time as the Macintosh II. It had a similar case to the original Macintosh computer, but with slight differences in color and styling.")); + Items.Add (new GrowItem ("MacII.jpg", "Macintosh II", "The Apple Macintosh II is the first personal computer model of the Macintosh II series in the Apple Macintosh line and the first Macintosh to support a color display. A basic system with 20 MB drive and monitor cost about $5500, A complete color-capable system could cost as much as $10,000 once the cost of the color monitor, video card, hard disk, keyboard and RAM were added. ")); + Items.Add (new GrowItem ("SE30.jpg", "Macintosh SE/30", "The Macintosh SE/30 is a personal computer that was designed, manufactured and sold by Apple Computer, Inc. from 1989 until 1991. It was the fastest of the original black-and-white compact Macintosh series.")); + Items.Add (new GrowItem ("Macintosh_Portable.jpg", "Macintosh Portable", "The Macintosh Portable was Apple Inc.'s first battery-powered portable Macintosh personal computer. Released on September 20, 1989, it was received with excitement from most critics but consumer sales were quite low. It featured a fast, sharp, and expensive black and white active matrix LCD screen in a hinged design that covered the keyboard when the machine was not in use.")); + Items.Add (new GrowItem ("Macintosh_Classic.jpg", "Macintosh Classic", "The Macintosh Classic is a personal computer manufactured by Apple Inc. Introduced on October 15, 1990, it was the first Apple Macintosh to sell for less than US$1,000. Production of the Classic was prompted by the success of the Macintosh Plus and the Macintosh SE. The system specifications of the Classic were very similar to its predecessors, with the same 9-inch (23 cm) monochrome CRT display, 512×342 pixel resolution, and 4 megabyte (MB) memory limit of the older Macintosh computers.")); + Items.Add (new GrowItem ("Macintosh_LC.jpg", "Macintosh LC", "The Macintosh LC (meaning low-cost color) is Apple Computer's product family of low-end consumer Macintosh personal computers in the early 1990s. The original Macintosh LC was released in October 1990 and was the first affordable color-capable Macintosh. Due to its affordability and Apple II compatibility the LC was adopted primarily in the education and home markets.")); + Items.Add (new GrowItem ("Powerbook_150.jpg", "Powerbook", "The PowerBook (known as Macintosh PowerBook before 1997) is a line of Macintosh laptop computers that was designed, manufactured and sold by Apple Computer, Inc. from 1991 to 2006. During its lifetime, the PowerBook went through several major revisions and redesigns, often being the first to incorporate features that would later become standard in competing laptops.")); + Items.Add (new GrowItem ("Macintosh_Classic_2.jpg", "Macintosh Classic II", "The Apple Macintosh Classic II (also known as the Performa 200) replaced the Macintosh SE/30 in the compact Macintosh line in 1991. Like the SE/30, the Classic II was powered by a 16 MHz Motorola 68030 CPU and 40 or 80 MB hard disk, but in contrast to its predecessor, it was limited by a 16-bit data bus (the SE/30 had a 32-bit data bus) and a 10 MB memory ceiling.")); + Items.Add (new GrowItem ("Macintosh_Color_Classic.jpg", "Macintosh Color Classic", "The Macintosh Color Classic, released on February 10, 1993, is the first color compact Apple Macintosh computer. It has an integrated 10″ Sony Trinitron color display with the same 512×384 pixel resolution as the Macintosh 12″ RGB monitor. It can display 256 colors(Can upgrade to 4096 colors). ")); + Items.Add (new GrowItem ("Power_Macintosh.jpg", "Power Macintosh", "Power Macintosh, later Power Mac, is a line of Apple Macintosh workstation-class personal computers based on various models of PowerPC microprocessors that were developed, marketed, and supported by Apple Inc. from March 1994 until August 2006. ")); } public override nint NumberOfSections (UITableView tableView) @@ -53,7 +52,7 @@ public override UITableViewCell GetCell (UITableView tableView, Foundation.NSInd var item = Items [indexPath.Row]; // Setup - cell.Image = UIImage.FromFile(item.ImageName); + cell.Image = UIImage.FromFile (item.ImageName); cell.Title = item.Title; cell.Description = item.Description; diff --git a/GrowRowTable/GrowRowTable/Classes/GrowRowTableDelegate.cs b/GrowRowTable/GrowRowTable/Classes/GrowRowTableDelegate.cs index 36ea47006..0a9f3aff7 100644 --- a/GrowRowTable/GrowRowTable/Classes/GrowRowTableDelegate.cs +++ b/GrowRowTable/GrowRowTable/Classes/GrowRowTableDelegate.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace GrowRowTable -{ - public class GrowRowTableDelegate : UITableViewDelegate - { +namespace GrowRowTable { + public class GrowRowTableDelegate : UITableViewDelegate { public GrowRowTableDelegate () { } @@ -12,7 +10,7 @@ public GrowRowTableDelegate () public override void RowSelected (UITableView tableView, Foundation.NSIndexPath indexPath) { // Output selected row - Console.WriteLine("Row selected: {0}",indexPath.Row); + Console.WriteLine ("Row selected: {0}", indexPath.Row); } } } diff --git a/GrowRowTable/GrowRowTable/GrowRowTableCell.cs b/GrowRowTable/GrowRowTable/GrowRowTableCell.cs index ab45d305a..2d32e63ec 100644 --- a/GrowRowTable/GrowRowTable/GrowRowTableCell.cs +++ b/GrowRowTable/GrowRowTable/GrowRowTableCell.cs @@ -3,11 +3,9 @@ using System.CodeDom.Compiler; using UIKit; -namespace GrowRowTable -{ - partial class GrowRowTableCell : UITableViewCell - { - +namespace GrowRowTable { + partial class GrowRowTableCell : UITableViewCell { + #region Computed Properties public UIImage Image { get { return CellImage.Image; } diff --git a/GrowRowTable/GrowRowTable/GrowRowTableView.cs b/GrowRowTable/GrowRowTable/GrowRowTableView.cs index b0f719932..a891266f9 100644 --- a/GrowRowTable/GrowRowTable/GrowRowTableView.cs +++ b/GrowRowTable/GrowRowTable/GrowRowTableView.cs @@ -3,13 +3,11 @@ using System.CodeDom.Compiler; using UIKit; -namespace GrowRowTable -{ - partial class GrowRowTableView : UITableView - { +namespace GrowRowTable { + partial class GrowRowTableView : UITableView { public GrowRowTableView (IntPtr handle) : base (handle) { - + } } } diff --git a/GrowRowTable/GrowRowTable/GrowRowTableViewController.cs b/GrowRowTable/GrowRowTable/GrowRowTableViewController.cs index 337686e7a..e92483ae6 100644 --- a/GrowRowTable/GrowRowTable/GrowRowTableViewController.cs +++ b/GrowRowTable/GrowRowTable/GrowRowTableViewController.cs @@ -3,10 +3,8 @@ using System.CodeDom.Compiler; using UIKit; -namespace GrowRowTable -{ - public partial class GrowRowTableViewController : UITableViewController - { +namespace GrowRowTable { + public partial class GrowRowTableViewController : UITableViewController { public GrowRowTableDataSource DataSource { get { return TableView.DataSource as GrowRowTableDataSource; } } @@ -30,13 +28,13 @@ public override void ViewWillAppear (bool animated) base.ViewWillAppear (animated); // Initialize table - TableView.DataSource = new GrowRowTableDataSource(); + TableView.DataSource = new GrowRowTableDataSource (); TableView.Delegate = new GrowRowTableDelegate (); TableView.RowHeight = UITableView.AutomaticDimension; TableView.EstimatedRowHeight = 40f; TableView.ReloadData (); } - + } } diff --git a/GrowRowTable/GrowRowTable/Main.cs b/GrowRowTable/GrowRowTable/Main.cs index 6feb0eddf..b3c18d689 100644 --- a/GrowRowTable/GrowRowTable/Main.cs +++ b/GrowRowTable/GrowRowTable/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace GrowRowTable -{ - public class Application - { +namespace GrowRowTable { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/HelloWorld_iPhone/AppDelegate.cs b/HelloWorld_iPhone/AppDelegate.cs index 7ce11a284..ac904de7e 100644 --- a/HelloWorld_iPhone/AppDelegate.cs +++ b/HelloWorld_iPhone/AppDelegate.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace HelloWorld_iPhone -{ +namespace HelloWorld_iPhone { /// /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; HelloWorld_iPhoneViewController viewController; diff --git a/HelloWorld_iPhone/HelloWorld_iPhoneViewController.cs b/HelloWorld_iPhone/HelloWorld_iPhoneViewController.cs index 41e28fe89..45a73f747 100644 --- a/HelloWorld_iPhone/HelloWorld_iPhoneViewController.cs +++ b/HelloWorld_iPhone/HelloWorld_iPhoneViewController.cs @@ -3,10 +3,8 @@ using System; using Foundation; -namespace HelloWorld_iPhone -{ - public partial class HelloWorld_iPhoneViewController : UIViewController - { +namespace HelloWorld_iPhone { + public partial class HelloWorld_iPhoneViewController : UIViewController { /// /// a class-level variable that tracks the number of times the button has been clicked. /// @@ -33,7 +31,7 @@ public override void ViewDidLoad () //---- wire up our click me button this.btnClickMe.TouchUpInside += (sender, e) => { this._numberOfTimesClicked++; - this.lblOutput.Text = "Clicked [" + this._numberOfTimesClicked.ToString() + "] times!"; + this.lblOutput.Text = "Clicked [" + this._numberOfTimesClicked.ToString () + "] times!"; }; } @@ -43,7 +41,7 @@ public override void ViewDidLoad () /// partial void actnButtonClick (Foundation.NSObject sender) { - this.lblOutput.Text = "Action button " + ((UIButton)sender).CurrentTitle + " clicked."; + this.lblOutput.Text = "Action button " + ((UIButton) sender).CurrentTitle + " clicked."; } } diff --git a/HelloWorld_iPhone/Main.cs b/HelloWorld_iPhone/Main.cs index 7709b495a..725c29311 100644 --- a/HelloWorld_iPhone/Main.cs +++ b/HelloWorld_iPhone/Main.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace HelloWorld_iPhone -{ - public class Application - { - static void Main (string[] args) +namespace HelloWorld_iPhone { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Hello_ComplexUniversal/AppDelegate.cs b/Hello_ComplexUniversal/AppDelegate.cs index ec898ba7d..0412ab6be 100644 --- a/Hello_ComplexUniversal/AppDelegate.cs +++ b/Hello_ComplexUniversal/AppDelegate.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace Hello_ComplexUniversal -{ +namespace Hello_ComplexUniversal { /// /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; UIViewController homeScreen; @@ -38,9 +36,9 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // // in this sample, we load a completely different controller, depending on the device: if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { - homeScreen = new Screens.HomeScreen_iPhone(); + homeScreen = new Screens.HomeScreen_iPhone (); } else { - homeScreen = new Screens.HomeScreen_iPad(); + homeScreen = new Screens.HomeScreen_iPad (); } window.RootViewController = homeScreen; window.MakeKeyAndVisible (); diff --git a/Hello_ComplexUniversal/Main.cs b/Hello_ComplexUniversal/Main.cs index b10a9496d..787618d89 100644 --- a/Hello_ComplexUniversal/Main.cs +++ b/Hello_ComplexUniversal/Main.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace Hello_ComplexUniversal -{ - public class Application - { +namespace Hello_ComplexUniversal { + public class Application { /// /// This is the main entry point of the application. /// - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Hello_ComplexUniversal/Screens/HomeScreen_iPad.cs b/Hello_ComplexUniversal/Screens/HomeScreen_iPad.cs index 454f6f0cd..74d79a5e8 100644 --- a/Hello_ComplexUniversal/Screens/HomeScreen_iPad.cs +++ b/Hello_ComplexUniversal/Screens/HomeScreen_iPad.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace Hello_ComplexUniversal.Screens -{ - public partial class HomeScreen_iPad : UIViewController - { +namespace Hello_ComplexUniversal.Screens { + public partial class HomeScreen_iPad : UIViewController { //loads the HomeScreen_iPad.xib file and connects it to this object public HomeScreen_iPad () : base ("HomeScreen_iPad", null) { diff --git a/Hello_ComplexUniversal/Screens/HomeScreen_iPhoneController.cs b/Hello_ComplexUniversal/Screens/HomeScreen_iPhoneController.cs index 65720ef33..9ff868535 100644 --- a/Hello_ComplexUniversal/Screens/HomeScreen_iPhoneController.cs +++ b/Hello_ComplexUniversal/Screens/HomeScreen_iPhoneController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace Hello_ComplexUniversal.Screens -{ - public partial class HomeScreen_iPhone : UIViewController - { +namespace Hello_ComplexUniversal.Screens { + public partial class HomeScreen_iPhone : UIViewController { //loads the HomeScreen_iPhone.xib file and connects it to this object public HomeScreen_iPhone () : base ("HomeScreen_iPhone", null) { diff --git a/Hello_MultiScreen_iPhone/AppDelegate.cs b/Hello_MultiScreen_iPhone/AppDelegate.cs index 0e6ffb396..54a196bf1 100644 --- a/Hello_MultiScreen_iPhone/AppDelegate.cs +++ b/Hello_MultiScreen_iPhone/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace Hello_MultiScreen_iPhone -{ +namespace Hello_MultiScreen_iPhone { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { //---- declarations UIWindow window; @@ -18,11 +16,11 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) this.window = new UIWindow (UIScreen.MainScreen.Bounds); //---- instantiate a new navigation controller - var rootNavigationController = new UINavigationController(); + var rootNavigationController = new UINavigationController (); //---- instantiate a new home screen - HomeScreen homeScreen = new HomeScreen(); + HomeScreen homeScreen = new HomeScreen (); //---- add the home screen to the navigation controller (it'll be the top most screen) - rootNavigationController.PushViewController(homeScreen, false); + rootNavigationController.PushViewController (homeScreen, false); //---- set the root view controller on the window. the nav controller will handle the rest this.window.RootViewController = rootNavigationController; diff --git a/Hello_MultiScreen_iPhone/Main.cs b/Hello_MultiScreen_iPhone/Main.cs index 797a9a41c..2bec0d3f1 100644 --- a/Hello_MultiScreen_iPhone/Main.cs +++ b/Hello_MultiScreen_iPhone/Main.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace Hello_MultiScreen_iPhone -{ - public class Application - { - static void Main (string[] args) +namespace Hello_MultiScreen_iPhone { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Hello_MultiScreen_iPhone/Screens/HelloUniverseScreen.cs b/Hello_MultiScreen_iPhone/Screens/HelloUniverseScreen.cs index effb65722..d4a036955 100644 --- a/Hello_MultiScreen_iPhone/Screens/HelloUniverseScreen.cs +++ b/Hello_MultiScreen_iPhone/Screens/HelloUniverseScreen.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace Hello_MultiScreen_iPhone -{ - public partial class HelloUniverseScreen : UIViewController - { +namespace Hello_MultiScreen_iPhone { + public partial class HelloUniverseScreen : UIViewController { //loads the HelloUniverseScreen.xib file and connects it to this object public HelloUniverseScreen () : base ("HelloUniverseScreen", null) { diff --git a/Hello_MultiScreen_iPhone/Screens/HelloWorldScreen.cs b/Hello_MultiScreen_iPhone/Screens/HelloWorldScreen.cs index 13632bbb5..370d0ed93 100644 --- a/Hello_MultiScreen_iPhone/Screens/HelloWorldScreen.cs +++ b/Hello_MultiScreen_iPhone/Screens/HelloWorldScreen.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace Hello_MultiScreen_iPhone -{ - public partial class HelloWorldScreen : UIViewController - { +namespace Hello_MultiScreen_iPhone { + public partial class HelloWorldScreen : UIViewController { //loads the HelloWorldScreen.xib file and connects it to this object public HelloWorldScreen () : base ("HelloWorldScreen", null) { diff --git a/Hello_MultiScreen_iPhone/Screens/HomeScreen.cs b/Hello_MultiScreen_iPhone/Screens/HomeScreen.cs index c75dc5fb6..7db5ee08a 100644 --- a/Hello_MultiScreen_iPhone/Screens/HomeScreen.cs +++ b/Hello_MultiScreen_iPhone/Screens/HomeScreen.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace Hello_MultiScreen_iPhone -{ - public partial class HomeScreen : UIViewController - { +namespace Hello_MultiScreen_iPhone { + public partial class HomeScreen : UIViewController { HelloWorldScreen helloWorldScreen; HelloUniverseScreen helloUniverseScreen; @@ -24,15 +22,15 @@ public override void ViewDidLoad () this.btnHelloWorld.TouchUpInside += (sender, e) => { //---- instantiate a new hello world screen, if it's null (it may not be null if they've navigated // backwards from it - if(this.helloWorldScreen == null) { this.helloWorldScreen = new HelloWorldScreen(); } + if (this.helloWorldScreen == null) { this.helloWorldScreen = new HelloWorldScreen (); } //---- push our hello world screen onto the navigation controller and pass a true so it navigates - this.NavigationController.PushViewController(this.helloWorldScreen, true); + this.NavigationController.PushViewController (this.helloWorldScreen, true); }; //---- same thing, but for the hello universe screen this.btnHelloUniverse.TouchUpInside += (sender, e) => { - if(this.helloUniverseScreen == null) { this.helloUniverseScreen = new HelloUniverseScreen(); } - this.NavigationController.PushViewController(this.helloUniverseScreen, true); + if (this.helloUniverseScreen == null) { this.helloUniverseScreen = new HelloUniverseScreen (); } + this.NavigationController.PushViewController (this.helloUniverseScreen, true); }; } diff --git a/Hello_Universal/AppDelegate.cs b/Hello_Universal/AppDelegate.cs index d2a4c5df9..4e3c035a6 100644 --- a/Hello_Universal/AppDelegate.cs +++ b/Hello_Universal/AppDelegate.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace Hello_Universal -{ +namespace Hello_Universal { /// /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; Hello_UniversalViewController viewController; diff --git a/Hello_Universal/Hello_UniversalViewController.cs b/Hello_Universal/Hello_UniversalViewController.cs index f7da87185..0b55cd65d 100644 --- a/Hello_Universal/Hello_UniversalViewController.cs +++ b/Hello_Universal/Hello_UniversalViewController.cs @@ -3,10 +3,8 @@ using System; using Foundation; -namespace Hello_Universal -{ - public partial class Hello_UniversalViewController : UIViewController - { +namespace Hello_Universal { + public partial class Hello_UniversalViewController : UIViewController { public Hello_UniversalViewController (string nibName, NSBundle bundle) : base (nibName, bundle) { } @@ -24,7 +22,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); this.btnClickMe.TouchUpInside += (sender, e) => { - this.lblOutput.Text = "Clicked @ " + DateTime.Now.ToShortTimeString(); + this.lblOutput.Text = "Clicked @ " + DateTime.Now.ToShortTimeString (); }; } diff --git a/Hello_Universal/Main.cs b/Hello_Universal/Main.cs index 25315d100..be4126ba5 100644 --- a/Hello_Universal/Main.cs +++ b/Hello_Universal/Main.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace Hello_Universal -{ - public class Application - { +namespace Hello_Universal { + public class Application { /// /// This is the main entry point of the application. /// - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Hello_iOS/Hello.iOS/Phoneword_iOS/AppDelegate.cs b/Hello_iOS/Hello.iOS/Phoneword_iOS/AppDelegate.cs index e4ce78169..7131f4110 100644 --- a/Hello_iOS/Hello.iOS/Phoneword_iOS/AppDelegate.cs +++ b/Hello_iOS/Hello.iOS/Phoneword_iOS/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace Phoneword_iOS -{ +namespace Phoneword_iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/Hello_iOS/Hello.iOS/Phoneword_iOS/Main.cs b/Hello_iOS/Hello.iOS/Phoneword_iOS/Main.cs index 74f6ffd87..953cc2eb5 100644 --- a/Hello_iOS/Hello.iOS/Phoneword_iOS/Main.cs +++ b/Hello_iOS/Hello.iOS/Phoneword_iOS/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace Phoneword_iOS -{ - public class Application - { +namespace Phoneword_iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Hello_iOS/Hello.iOS/Phoneword_iOS/PhoneTranslator.cs b/Hello_iOS/Hello.iOS/Phoneword_iOS/PhoneTranslator.cs index 725dc8bff..4eca97101 100644 --- a/Hello_iOS/Hello.iOS/Phoneword_iOS/PhoneTranslator.cs +++ b/Hello_iOS/Hello.iOS/Phoneword_iOS/PhoneTranslator.cs @@ -1,10 +1,8 @@ -using System.Text; +using System.Text; using System; -namespace Phoneword_iOS -{ - public static class PhoneTranslator - { +namespace Phoneword_iOS { + public static class PhoneTranslator { public static string ToNumber (string raw) { if (string.IsNullOrWhiteSpace (raw)) diff --git a/Hello_iOS/Hello.iOS/Phoneword_iOS/ViewController.cs b/Hello_iOS/Hello.iOS/Phoneword_iOS/ViewController.cs index 93854ccdb..ff5ccc0ba 100644 --- a/Hello_iOS/Hello.iOS/Phoneword_iOS/ViewController.cs +++ b/Hello_iOS/Hello.iOS/Phoneword_iOS/ViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace Phoneword_iOS -{ - public partial class ViewController : UIViewController - { +namespace Phoneword_iOS { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } diff --git a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/AppDelegate.cs b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/AppDelegate.cs index e4ce78169..7131f4110 100644 --- a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/AppDelegate.cs +++ b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace Phoneword_iOS -{ +namespace Phoneword_iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/CallHistoryController.cs b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/CallHistoryController.cs index b396e500d..2a4a6d2a9 100644 --- a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/CallHistoryController.cs +++ b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/CallHistoryController.cs @@ -4,23 +4,20 @@ using UIKit; using System.Collections.Generic; -namespace Phoneword_iOS -{ - partial class CallHistoryController : UITableViewController - { +namespace Phoneword_iOS { + partial class CallHistoryController : UITableViewController { public List PhoneNumbers { get; set; } static NSString callHistoryCellId = new NSString ("CallHistoryCell"); public CallHistoryController (IntPtr handle) : base (handle) { - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), callHistoryCellId); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), callHistoryCellId); TableView.Source = new CallHistoryDataSource (this); PhoneNumbers = new List (); } - class CallHistoryDataSource : UITableViewSource - { + class CallHistoryDataSource : UITableViewSource { CallHistoryController controller; public CallHistoryDataSource (CallHistoryController controller) diff --git a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/Main.cs b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/Main.cs index 74f6ffd87..953cc2eb5 100644 --- a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/Main.cs +++ b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace Phoneword_iOS -{ - public class Application - { +namespace Phoneword_iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/PhoneTranslator.cs b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/PhoneTranslator.cs index cee0abf91..fa41a87e8 100644 --- a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/PhoneTranslator.cs +++ b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/PhoneTranslator.cs @@ -1,54 +1,51 @@ -using System.Text; +using System.Text; using System; -namespace Phoneword_iOS -{ - public static class PhonewordTranslator - { - public static string ToNumber(string raw) +namespace Phoneword_iOS { + public static class PhonewordTranslator { + public static string ToNumber (string raw) { - if (string.IsNullOrWhiteSpace(raw)) + if (string.IsNullOrWhiteSpace (raw)) return ""; else - raw = raw.ToUpperInvariant(); + raw = raw.ToUpperInvariant (); - var newNumber = new StringBuilder(); - foreach (var c in raw) - { - if (" -0123456789".Contains(c)) - newNumber.Append(c); + var newNumber = new StringBuilder (); + foreach (var c in raw) { + if (" -0123456789".Contains (c)) + newNumber.Append (c); else { - var result = TranslateToNumber(c); + var result = TranslateToNumber (c); if (result != null) - newNumber.Append(result); - } + newNumber.Append (result); + } // otherwise we've skipped a non-numeric char } - return newNumber.ToString(); + return newNumber.ToString (); } static bool Contains (this string keyString, char c) { - return keyString.IndexOf(c) >= 0; + return keyString.IndexOf (c) >= 0; } - static int? TranslateToNumber(char c) + static int? TranslateToNumber (char c) { - if ("ABC".Contains(c)) + if ("ABC".Contains (c)) return 2; - else if ("DEF".Contains(c)) + else if ("DEF".Contains (c)) return 3; - else if ("GHI".Contains(c)) + else if ("GHI".Contains (c)) return 4; - else if ("JKL".Contains(c)) + else if ("JKL".Contains (c)) return 5; - else if ("MNO".Contains(c)) + else if ("MNO".Contains (c)) return 6; - else if ("PQRS".Contains(c)) + else if ("PQRS".Contains (c)) return 7; - else if ("TUV".Contains(c)) + else if ("TUV".Contains (c)) return 8; - else if ("WXYZ".Contains(c)) + else if ("WXYZ".Contains (c)) return 9; return null; } diff --git a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/ViewController.cs b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/ViewController.cs index 496ea6224..6f36a5e72 100644 --- a/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/ViewController.cs +++ b/Hello_iOS/Hello.iOS_MultiScreen/Phoneword_iOS/ViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using Foundation; -namespace Phoneword_iOS -{ - public partial class ViewController : UIViewController - { +namespace Phoneword_iOS { + public partial class ViewController : UIViewController { // translatedNumber was moved here from ViewDidLoad () string translatedNumber = ""; @@ -25,9 +23,9 @@ public override void ViewDidLoad () TranslateButton.TouchUpInside += (object sender, EventArgs e) => { // Convert the phone number with text to a number // using PhoneTranslator.cs - translatedNumber = PhonewordTranslator.ToNumber( - PhoneNumberText.Text); - + translatedNumber = PhonewordTranslator.ToNumber ( + PhoneNumberText.Text); + // Dismiss the keyboard if text field was tapped PhoneNumberText.ResignFirstResponder (); @@ -35,7 +33,7 @@ public override void ViewDidLoad () CallButton.SetTitle ("Call ", UIControlState.Normal); CallButton.Enabled = false; } else { - CallButton.SetTitle ("Call " + translatedNumber, + CallButton.SetTitle ("Call " + translatedNumber, UIControlState.Normal); CallButton.Enabled = true; } @@ -62,14 +60,14 @@ public override void ViewDidLoad () // Nativation without Segues // - if the segue was deleted from the storyboard, this code would enable the button to open the second view controller // -// CallHistoryButton.TouchUpInside += (object sender, EventArgs e) => { -// // Launches a new instance of CallHistoryController -// CallHistoryController callHistory = this.Storyboard.InstantiateViewController ("CallHistoryController") as CallHistoryController; -// if (callHistory != null) { -// callHistory.PhoneNumbers = PhoneNumbers; -// this.NavigationController.PushViewController (callHistory, true); -// } -// }; + // CallHistoryButton.TouchUpInside += (object sender, EventArgs e) => { + // // Launches a new instance of CallHistoryController + // CallHistoryController callHistory = this.Storyboard.InstantiateViewController ("CallHistoryController") as CallHistoryController; + // if (callHistory != null) { + // callHistory.PhoneNumbers = PhoneNumbers; + // this.NavigationController.PushViewController (callHistory, true); + // } + // }; } // diff --git a/Hello_iPad/AppDelegate.cs b/Hello_iPad/AppDelegate.cs index 6d096d540..6d12e2b11 100644 --- a/Hello_iPad/AppDelegate.cs +++ b/Hello_iPad/AppDelegate.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace Hello_iPad -{ +namespace Hello_iPad { /// /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; Hello_iPadViewController viewController; diff --git a/Hello_iPad/Hello_iPadViewController.cs b/Hello_iPad/Hello_iPadViewController.cs index 4fd83b87f..5c23419db 100644 --- a/Hello_iPad/Hello_iPadViewController.cs +++ b/Hello_iPad/Hello_iPadViewController.cs @@ -3,10 +3,8 @@ using System; using Foundation; -namespace Hello_iPad -{ - public partial class Hello_iPadViewController : UIViewController - { +namespace Hello_iPad { + public partial class Hello_iPadViewController : UIViewController { public Hello_iPadViewController (string nibName, NSBundle bundle) : base (nibName, bundle) { } diff --git a/Hello_iPad/Main.cs b/Hello_iPad/Main.cs index 26927b6c9..38237e607 100644 --- a/Hello_iPad/Main.cs +++ b/Hello_iPad/Main.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace Hello_iPad -{ - public class Application - { +namespace Hello_iPad { + public class Application { /// /// This is the main entry point of the application. /// - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryCell.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryCell.cs index 89ddfbb60..96d4db7bc 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryCell.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryCell.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class AccessoryCell : UITableViewCell - { +namespace HomeKitIntro { + public partial class AccessoryCell : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("AccessoryCell"); #endregion @@ -19,7 +17,8 @@ public AccessoryCell (IntPtr handle) : base (handle) #endregion #region Public Methods - public void DisplayAccessory(HMAccessory accessory) { + public void DisplayAccessory (HMAccessory accessory) + { // Update the UI AccessoryName.Text = accessory.Name; @@ -29,7 +28,8 @@ public void DisplayAccessory(HMAccessory accessory) { AccessoryImage.Image = UIImage.FromFile ("61-brightness.png"); } else if (accessory.Name.Contains ("Garage")) { AccessoryImage.Image = UIImage.FromFile ("24-circle-north.png"); - } if (accessory.Name.Contains ("Thermostat")) { + } + if (accessory.Name.Contains ("Thermostat")) { AccessoryImage.Image = UIImage.FromFile ("81-dashboard.png"); } else if (accessory.Name.Contains ("Switch")) { AccessoryImage.Image = UIImage.FromFile ("51-power.png"); diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableSource.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableSource.cs index 6c6b04154..01151eb23 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableSource.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableSource.cs @@ -4,16 +4,14 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ +namespace HomeKitIntro { /// /// Accessory table source. /// - public class AccessoryTableSource : UITableViewSource - { + public class AccessoryTableSource : UITableViewSource { #region Private Variables private AccessoryTableViewController _controller; - #endregion + #endregion #region Computed Properties /// @@ -21,7 +19,7 @@ public class AccessoryTableSource : UITableViewSource /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableViewController.cs index 0168d2231..8c6dadf20 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AccessoryTableViewController.cs @@ -3,17 +3,15 @@ using UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - public partial class AccessoryTableViewController : UITableViewController - { +namespace HomeKitIntro { + public partial class AccessoryTableViewController : UITableViewController { #region Computed Properties /// /// Returns the delegate of the current running application /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// @@ -21,7 +19,7 @@ public AppDelegate ThisApp { /// /// The data source. public AccessoryTableSource DataSource { - get { return (AccessoryTableSource)TableView.Source; } + get { return (AccessoryTableSource) TableView.Source; } } /// @@ -45,7 +43,8 @@ public AccessoryTableViewController (IntPtr handle) : base (handle) /// /// Reloads the data. /// - public void ReloadData() { + public void ReloadData () + { // Ask the table to redisplay its information TableView.ReloadData (); @@ -56,7 +55,8 @@ public void ReloadData() { /// /// Sets the name of the home. /// - private void SetHomeName() { + private void SetHomeName () + { // Was a primary home found? if (ThisApp.HomeManager.PrimaryHome == null) { // No, @@ -68,12 +68,12 @@ private void SetHomeName() { // Wireup home view ThisApp.HomeManager.PrimaryHome.DidAddAccessory += (sender, e) => { // Update list - ReloadData(); + ReloadData (); }; ThisApp.HomeManager.PrimaryHome.DidRemoveAccessory += (sender, e) => { // Update list - ReloadData(); + ReloadData (); }; } } @@ -94,25 +94,25 @@ public override void ViewDidLoad () // Wireup events ThisApp.HomeManager.DidUpdateHomes += (sender, e) => { // Update title and reload data - SetHomeName(); - ReloadData(); + SetHomeName (); + ReloadData (); }; ThisApp.HomeManager.DidUpdatePrimaryHome += (sender, e) => { // Update title and reload data - SetHomeName(); - ReloadData(); + SetHomeName (); + ReloadData (); }; ThisApp.HomeManager.DidRemoveHome += (sender, e) => { // Update title and reload data - SetHomeName(); - ReloadData(); + SetHomeName (); + ReloadData (); }; ThisApp.UpdateGUI += () => { // Update list of items - ReloadData(); + ReloadData (); }; } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AddHomeViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AddHomeViewController.cs index 27786e205..10c6a246e 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AddHomeViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AddHomeViewController.cs @@ -4,17 +4,15 @@ using UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - partial class AddHomeViewController : UIViewController - { +namespace HomeKitIntro { + partial class AddHomeViewController : UIViewController { #region Computed Properties /// /// Returns the delegate of the current running application /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -30,42 +28,44 @@ public AddHomeViewController (IntPtr handle) : base (handle) /// /// The x coordinate. /// The y coordinate. - private void MoveTo (float x, float y){ + private void MoveTo (float x, float y) + { View.Frame = new CGRect (0, y, View.Frame.Width, View.Frame.Height); } /// /// Adds the home. /// - private void AddNewHome() { + private void AddNewHome () + { // Has a name been entered? - if (HomeName.Text=="" ) { + if (HomeName.Text == "") { // No, inform the user that they must create a home first - AlertView.PresentOKAlert("Home Name Error","You must enter a name for the home before it can be created.",this); + AlertView.PresentOKAlert ("Home Name Error", "You must enter a name for the home before it can be created.", this); return; } // Add new home to HomeKit - ThisApp.HomeManager.AddHome(HomeName.Text,(home,error) =>{ + ThisApp.HomeManager.AddHome (HomeName.Text, (home, error) => { // Did an error occur - if (error!=null) { + if (error != null) { // Yes, inform user - AlertView.PresentOKAlert("Add Home Error",string.Format("Error adding {0}: {1}",HomeName.Text,error.LocalizedDescription),this); + AlertView.PresentOKAlert ("Add Home Error", string.Format ("Error adding {0}: {1}", HomeName.Text, error.LocalizedDescription), this); return; } // Make the primary house - ThisApp.HomeManager.UpdatePrimaryHome(home,(err) => { + ThisApp.HomeManager.UpdatePrimaryHome (home, (err) => { // Error? - if (err!=null) { + if (err != null) { // Inform user of error - AlertView.PresentOKAlert("Add Home Error",string.Format("Unable to make this the primary home: {0}",err.LocalizedDescription),this); - return ; + AlertView.PresentOKAlert ("Add Home Error", string.Format ("Unable to make this the primary home: {0}", err.LocalizedDescription), this); + return; } }); // Close the window when the home is created - DismissViewController(true,null); + DismissViewController (true, null); }); } #endregion @@ -75,36 +75,39 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - HomeName.ShouldBeginEditing= delegate(UITextField field){ + HomeName.ShouldBeginEditing = delegate (UITextField field) + { //Placeholder - UIView.BeginAnimations("keyboard"); - UIView.SetAnimationDuration(0.3f); - this.MoveTo(0,-170); - UIView.CommitAnimations(); + UIView.BeginAnimations ("keyboard"); + UIView.SetAnimationDuration (0.3f); + this.MoveTo (0, -170); + UIView.CommitAnimations (); return true; }; - HomeName.ShouldReturn = delegate (UITextField field){ + HomeName.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); - UIView.BeginAnimations("keyboard"); - UIView.SetAnimationDuration(0.3f); - this.MoveTo(0,0); - UIView.CommitAnimations(); + UIView.BeginAnimations ("keyboard"); + UIView.SetAnimationDuration (0.3f); + this.MoveTo (0, 0); + UIView.CommitAnimations (); return true; }; - HomeName.ShouldEndEditing= delegate (UITextField field){ - UIView.BeginAnimations("keyboard"); - UIView.SetAnimationDuration(0.3f); - this.MoveTo(0,0); - UIView.CommitAnimations(); - AddNewHome(); + HomeName.ShouldEndEditing = delegate (UITextField field) + { + UIView.BeginAnimations ("keyboard"); + UIView.SetAnimationDuration (0.3f); + this.MoveTo (0, 0); + UIView.CommitAnimations (); + AddNewHome (); return true; }; // Wireup buttons AddHome.TouchUpInside += (sender, e) => { // Add the new home - AddNewHome(); + AddNewHome (); }; } #endregion diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AppDelegate.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AppDelegate.cs index e4f202824..2a9aea8ea 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AppDelegate.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,20 +6,18 @@ using UIKit; using HomeKit; -namespace HomeKitIntro -{ +namespace HomeKitIntro { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { #region Computed Properties /// /// Gets or sets the window. /// /// The window. - public override UIWindow Window {get; set;} + public override UIWindow Window { get; set; } /// /// Gets or sets the home manager. @@ -39,21 +37,21 @@ public override void FinishedLaunching (UIApplication application) { // Attach to the Home Manager HomeManager = new HMHomeManager (); - Console.WriteLine ("{0} Home(s) defined in the Home Manager", HomeManager.Homes.Count()); + Console.WriteLine ("{0} Home(s) defined in the Home Manager", HomeManager.Homes.Count ()); // Wire-up Home Manager Events HomeManager.DidAddHome += (sender, e) => { - Console.WriteLine("Manager Added Home: {0}",e.Home); + Console.WriteLine ("Manager Added Home: {0}", e.Home); }; HomeManager.DidRemoveHome += (sender, e) => { - Console.WriteLine("Manager Removed Home: {0}",e.Home); + Console.WriteLine ("Manager Removed Home: {0}", e.Home); }; HomeManager.DidUpdateHomes += (sender, e) => { - Console.WriteLine("Manager Updated Homes"); + Console.WriteLine ("Manager Updated Homes"); }; HomeManager.DidUpdatePrimaryHome += (sender, e) => { - Console.WriteLine("Manager Updated Primary Home"); + Console.WriteLine ("Manager Updated Primary Home"); }; } @@ -63,19 +61,19 @@ public override void FinishedLaunching (UIApplication application) public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { @@ -86,13 +84,14 @@ public override void WillTerminate (UIApplication application) /// /// Update GUI delegate. /// - public delegate void UpdateGUIDelegate(); + public delegate void UpdateGUIDelegate (); public event UpdateGUIDelegate UpdateGUI; /// /// Raises the update GUI event /// - internal void RaiseUpdateGUI() { + internal void RaiseUpdateGUI () + { // Inform caller if (this.UpdateGUI != null) this.UpdateGUI (); diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableCell.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableCell.cs index 281c9127a..ce63f82b4 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableCell.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableCell.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class AvailableCell : UITableViewCell - { +namespace HomeKitIntro { + public partial class AvailableCell : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("AvailableCell"); #endregion @@ -19,7 +17,8 @@ public AvailableCell (IntPtr handle) : base (handle) #endregion #region Public Methods - public void DisplayAccessory(HMAccessory accessory) { + public void DisplayAccessory (HMAccessory accessory) + { // Update the UI AvailableName.Text = accessory.Name; @@ -29,7 +28,8 @@ public void DisplayAccessory(HMAccessory accessory) { AvailableImage.Image = UIImage.FromFile ("61-brightness.png"); } else if (accessory.Name.Contains ("Garage")) { AvailableImage.Image = UIImage.FromFile ("24-circle-north.png"); - } if (accessory.Name.Contains ("Thermostat")) { + } + if (accessory.Name.Contains ("Thermostat")) { AvailableImage.Image = UIImage.FromFile ("81-dashboard.png"); } else if (accessory.Name.Contains ("Switch")) { AvailableImage.Image = UIImage.FromFile ("51-power.png"); diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableSource.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableSource.cs index b359ba0c4..4d8d2f4b7 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableSource.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableSource.cs @@ -4,16 +4,14 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ +namespace HomeKitIntro { /// /// Accessory table source. /// - public class AvailableTableSource : UITableViewSource - { + public class AvailableTableSource : UITableViewSource { #region Private Variables private AvailableTableViewController _controller; - #endregion + #endregion #region Computed Properties /// @@ -21,7 +19,7 @@ public class AvailableTableSource : UITableViewSource /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -147,9 +145,9 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) // Add the requested accessory to the home ThisApp.HomeManager.PrimaryHome.AddAccessory (_controller.AccessoryBrowser.DiscoveredAccessories [indexPath.Row], (err) => { // Did an error occur - if (err !=null) { + if (err != null) { // Inform user of error - AlertView.PresentOKAlert("Add Accessory Error",err.LocalizedDescription,_controller); + AlertView.PresentOKAlert ("Add Accessory Error", err.LocalizedDescription, _controller); } }); } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableViewController.cs index f835324dd..3b679622d 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableTableViewController.cs @@ -4,17 +4,15 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class AvailableTableViewController : UITableViewController - { +namespace HomeKitIntro { + public partial class AvailableTableViewController : UITableViewController { #region Computed Properties /// /// Returns the delegate of the current running application /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// @@ -22,7 +20,7 @@ public AppDelegate ThisApp { /// /// The data source. public AvailableTableSource DataSource { - get { return (AvailableTableSource)TableView.Source; } + get { return (AvailableTableSource) TableView.Source; } } /// @@ -48,7 +46,8 @@ public AvailableTableViewController (IntPtr handle) : base (handle) /// /// Reloads the data. /// - public void ReloadData() { + public void ReloadData () + { // Ask the table to redisplay its information TableView.ReloadData (); @@ -70,15 +69,15 @@ public override void AwakeFromNib () // Wireup changes AccessoryBrowser.DidFindNewAccessory += (sender, e) => { // Update display - ReloadData(); + ReloadData (); }; AccessoryBrowser.DidRemoveNewAccessory += (sender, e) => { // Update display - ReloadData(); + ReloadData (); // Inform the rest of the UI that it needs to refresh - ThisApp.RaiseUpdateGUI(); + ThisApp.RaiseUpdateGUI (); }; } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableViewController.cs index d061475b1..b45f52d92 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/AvailableViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/AvailableViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - partial class AvailableViewController : UINavigationController - { +namespace HomeKitIntro { + partial class AvailableViewController : UINavigationController { public AvailableViewController (IntPtr handle) : base (handle) { } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellInfo.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellInfo.cs index 8e9e8468c..5145489cf 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellInfo.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellInfo.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class CharacteristicCellInfo : UITableViewCell - { +namespace HomeKitIntro { + public partial class CharacteristicCellInfo : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("CharacteristicCellInfo"); #endregion @@ -19,7 +17,8 @@ public CharacteristicCellInfo (IntPtr handle) : base (handle) #endregion #region Public Methods - public void DisplayInfo(string title, string value) { + public void DisplayInfo (string title, string value) + { // Update UI Title.Text = title; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSlider.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSlider.cs index bd37cb262..c0975391d 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSlider.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSlider.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class CharacteristicCellSlider : UITableViewCell - { +namespace HomeKitIntro { + public partial class CharacteristicCellSlider : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("CharacteristicCellSlider"); #endregion @@ -28,7 +26,7 @@ public partial class CharacteristicCellSlider : UITableViewCell /// /// The controller. public CharacteristicTableViewController Controller { get; set; } - #endregion + #endregion #region Constructors public CharacteristicCellSlider (IntPtr handle) : base (handle) @@ -37,7 +35,8 @@ public CharacteristicCellSlider (IntPtr handle) : base (handle) #endregion #region Public Methods - public void DisplayInfo(string title, float value, float min, float max, bool enabled) { + public void DisplayInfo (string title, float value, float min, float max, bool enabled) + { // Update UI Title.Text = title; @@ -58,7 +57,8 @@ public void DisplayInfo(string title, float value, float min, float max, bool en /// /// Wireups the events. /// - private void WireupEvents () { + private void WireupEvents () + { // Already wired up? if (_wiredup) @@ -66,22 +66,22 @@ private void WireupEvents () { // Display the new value Slider.ValueChanged += (sender, e) => { - var value = Math.Round(Slider.Value,0); - SubTItle.Text = value.ToString(); + var value = Math.Round (Slider.Value, 0); + SubTItle.Text = value.ToString (); }; // Send change of value on end of change Slider.TouchUpInside += (sender, e) => { // Is a characteristic attached? - if (Characteristic==null) return; + if (Characteristic == null) return; // Set updated value to the characteristic - var value = Math.Round(Slider.Value,0); - Characteristic.WriteValue(NSObject.FromObject(value),(err) =>{ + var value = Math.Round (Slider.Value, 0); + Characteristic.WriteValue (NSObject.FromObject (value), (err) => { // Was there an error? - if (err!=null) { + if (err != null) { // Yes, inform user - AlertView.PresentOKAlert("Update Error",err.LocalizedDescription,Controller); + AlertView.PresentOKAlert ("Update Error", err.LocalizedDescription, Controller); } }); }; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellStepper.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellStepper.cs index aa6bfe343..506a35a4f 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellStepper.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellStepper.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class CharacteristicCellStepper : UITableViewCell - { +namespace HomeKitIntro { + public partial class CharacteristicCellStepper : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("CharacteristicCellStepper"); #endregion @@ -28,16 +26,17 @@ public partial class CharacteristicCellStepper : UITableViewCell /// /// The controller. public CharacteristicTableViewController Controller { get; set; } - #endregion + #endregion #region Constructors public CharacteristicCellStepper (IntPtr handle) : base (handle) { } - #endregion + #endregion #region Public Methods - public void DisplayInfo(string title, float value, float min, float max, bool enabled) { + public void DisplayInfo (string title, float value, float min, float max, bool enabled) + { // Update UI Title.Text = title; @@ -58,7 +57,8 @@ public void DisplayInfo(string title, float value, float min, float max, bool en /// /// Wireups the events. /// - private void WireupEvents () { + private void WireupEvents () + { // Already wired up? if (_wiredup) @@ -66,14 +66,14 @@ private void WireupEvents () { // Display the new value Stepper.ValueChanged += (sender, e) => { - SubTitle.Text = Stepper.Value.ToString(); + SubTitle.Text = Stepper.Value.ToString (); // Set updated value to the characteristic - Characteristic.WriteValue(NSObject.FromObject(Stepper.Value),(err) =>{ + Characteristic.WriteValue (NSObject.FromObject (Stepper.Value), (err) => { // Was there an error? - if (err!=null) { + if (err != null) { // Yes, inform user - AlertView.PresentOKAlert("Update Error",err.LocalizedDescription,Controller); + AlertView.PresentOKAlert ("Update Error", err.LocalizedDescription, Controller); } }); }; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSwitch.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSwitch.cs index 80b84518d..94f7ad67f 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSwitch.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellSwitch.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class CharacteristicCellSwitch : UITableViewCell - { +namespace HomeKitIntro { + public partial class CharacteristicCellSwitch : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("CharacteristicCellSwitch"); @@ -29,7 +27,7 @@ public partial class CharacteristicCellSwitch : UITableViewCell /// /// The controller. public CharacteristicTableViewController Controller { get; set; } - #endregion + #endregion #region Constructors public CharacteristicCellSwitch (IntPtr handle) : base (handle) @@ -38,7 +36,8 @@ public CharacteristicCellSwitch (IntPtr handle) : base (handle) #endregion #region Public Methods - public void DisplayInfo(string title, bool value, bool enabled) { + public void DisplayInfo (string title, bool value, bool enabled) + { // Update UI Title.Text = title; @@ -57,7 +56,8 @@ public void DisplayInfo(string title, bool value, bool enabled) { /// /// Wireups the events. /// - private void WireupEvents () { + private void WireupEvents () + { // Already wired up? if (_wiredup) @@ -65,14 +65,14 @@ private void WireupEvents () { // Display the new value Switch.ValueChanged += (sender, e) => { - SubTitle.Text = Switch.On.ToString(); + SubTitle.Text = Switch.On.ToString (); // Set updated value to the characteristic - Characteristic.WriteValue(NSObject.FromObject(Switch.On),(err) =>{ + Characteristic.WriteValue (NSObject.FromObject (Switch.On), (err) => { // Was there an error? - if (err!=null) { + if (err != null) { // Yes, inform user - AlertView.PresentOKAlert("Update Error",err.LocalizedDescription,Controller); + AlertView.PresentOKAlert ("Update Error", err.LocalizedDescription, Controller); } }); }; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellText.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellText.cs index 036dffce7..2c8c7df98 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellText.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicCellText.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class CharacteristicCellText : UITableViewCell - { +namespace HomeKitIntro { + public partial class CharacteristicCellText : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("CharacteristicCellText"); #endregion @@ -28,7 +26,7 @@ public partial class CharacteristicCellText : UITableViewCell /// /// The controller. public CharacteristicTableViewController Controller { get; set; } - #endregion + #endregion #region Constructors public CharacteristicCellText (IntPtr handle) : base (handle) @@ -37,7 +35,8 @@ public CharacteristicCellText (IntPtr handle) : base (handle) #endregion #region Public Methods - public void DisplayInfo(string title, string value, bool enabled) { + public void DisplayInfo (string title, string value, bool enabled) + { // Update UI TItle.Text = title; @@ -56,7 +55,8 @@ public void DisplayInfo(string title, string value, bool enabled) { /// /// Wireups the events. /// - private void WireupEvents () { + private void WireupEvents () + { // Already wired up? if (_wiredup) @@ -64,14 +64,14 @@ private void WireupEvents () { // Wire text field Text.ShouldReturn += (UITextField field) => { - field.ResignFirstResponder(); + field.ResignFirstResponder (); // Set updated value to the characteristic - Characteristic.WriteValue(NSObject.FromObject(Text.Text),(err) =>{ + Characteristic.WriteValue (NSObject.FromObject (Text.Text), (err) => { // Was there an error? - if (err!=null) { + if (err != null) { // Yes, inform user - AlertView.PresentOKAlert("Update Error",err.LocalizedDescription,Controller); + AlertView.PresentOKAlert ("Update Error", err.LocalizedDescription, Controller); } }); @@ -79,14 +79,14 @@ private void WireupEvents () { }; Text.ShouldEndEditing += (UITextField field) => { - field.ResignFirstResponder(); + field.ResignFirstResponder (); // Set updated value to the characteristic - Characteristic.WriteValue(NSObject.FromObject(Text.Text),(err) =>{ + Characteristic.WriteValue (NSObject.FromObject (Text.Text), (err) => { // Was there an error? - if (err!=null) { + if (err != null) { // Yes, inform user - AlertView.PresentOKAlert("Update Error",err.LocalizedDescription,Controller); + AlertView.PresentOKAlert ("Update Error", err.LocalizedDescription, Controller); } }); diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableSource.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableSource.cs index f2163a4d5..f79b4a7ca 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableSource.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableSource.cs @@ -1,15 +1,13 @@ -using System; +using System; using Foundation; using UIKit; using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public class CharacteristicTableSource : UITableViewSource - { +namespace HomeKitIntro { + public class CharacteristicTableSource : UITableViewSource { #region Private Variables private CharacteristicTableViewController _controller; - #endregion + #endregion #region Computed Properties /// @@ -17,7 +15,7 @@ public class CharacteristicTableSource : UITableViewSource /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -218,7 +216,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde break; default: // Just display as info it the type is unknown - fieldName = characteristic.CharacteristicType.ToString(); + fieldName = characteristic.CharacteristicType.ToString (); display = CharacteristicDisplayType.Info; editable = false; break; @@ -227,8 +225,8 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde // Update the current value of the field characteristic.ReadValue ((err) => { // Report errors to console - if (err!=null) { - Console.WriteLine("Error Updating {0}: {1}",fieldName,err.LocalizedDescription); + if (err != null) { + Console.WriteLine ("Error Updating {0}: {1}", fieldName, err.LocalizedDescription); } }); @@ -239,7 +237,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var InfoCell = tableView.DequeueReusableCell (CharacteristicCellInfo.Key) as CharacteristicCellInfo; // Populate the cell - InfoCell.DisplayInfo (fieldName, characteristic.Value.ToString()); + InfoCell.DisplayInfo (fieldName, characteristic.Value.ToString ()); // Return cell return InfoCell; @@ -248,7 +246,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var SliderCell = tableView.DequeueReusableCell (CharacteristicCellSlider.Key) as CharacteristicCellSlider; // Populate the cell - SliderCell.DisplayInfo (fieldName, NSObjectConverter.ToFloat (characteristic.Value), (float)characteristic.Metadata.MinimumValue, (float)characteristic.Metadata.MaximumValue, editable); + SliderCell.DisplayInfo (fieldName, NSObjectConverter.ToFloat (characteristic.Value), (float) characteristic.Metadata.MinimumValue, (float) characteristic.Metadata.MaximumValue, editable); SliderCell.Characteristic = characteristic; SliderCell.Controller = _controller; @@ -259,7 +257,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var StepperCell = tableView.DequeueReusableCell (CharacteristicCellStepper.Key) as CharacteristicCellStepper; // Populate the cell - StepperCell.DisplayInfo (fieldName, NSObjectConverter.ToFloat (characteristic.Value), (float)characteristic.Metadata.MinimumValue, (float)characteristic.Metadata.MaximumValue, editable); + StepperCell.DisplayInfo (fieldName, NSObjectConverter.ToFloat (characteristic.Value), (float) characteristic.Metadata.MinimumValue, (float) characteristic.Metadata.MaximumValue, editable); StepperCell.Characteristic = characteristic; StepperCell.Controller = _controller; @@ -271,7 +269,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var SwitchCell = tableView.DequeueReusableCell (CharacteristicCellSwitch.Key) as CharacteristicCellSwitch; // Populate the cell - SwitchCell.DisplayInfo (fieldName, NSObjectConverter.ToBool(characteristic.Value), editable); + SwitchCell.DisplayInfo (fieldName, NSObjectConverter.ToBool (characteristic.Value), editable); SwitchCell.Characteristic = characteristic; SwitchCell.Controller = _controller; @@ -282,7 +280,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var TextCell = tableView.DequeueReusableCell (CharacteristicCellText.Key) as CharacteristicCellText; // Populate the cell - TextCell.DisplayInfo (fieldName, NSObjectConverter.ToString(characteristic.Value), editable); + TextCell.DisplayInfo (fieldName, NSObjectConverter.ToString (characteristic.Value), editable); TextCell.Characteristic = characteristic; TextCell.Controller = _controller; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableViewController.cs index e187504bd..7d3aba90d 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/CharacteristicTableViewController.cs @@ -4,17 +4,15 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class CharacteristicTableViewController : UITableViewController - { +namespace HomeKitIntro { + public partial class CharacteristicTableViewController : UITableViewController { #region Computed Properties /// /// Returns the delegate of the current running application /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// @@ -22,7 +20,7 @@ public AppDelegate ThisApp { /// /// The data source. public CharacteristicTableSource DataSource { - get { return (CharacteristicTableSource)TableView.Source; } + get { return (CharacteristicTableSource) TableView.Source; } } /// @@ -46,7 +44,8 @@ public CharacteristicTableViewController (IntPtr handle) : base (handle) /// /// Reloads the data. /// - public void ReloadData() { + public void ReloadData () + { // Ask the table to redisplay its information TableView.ReloadData (); diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/Classes/AlertView.cs b/HomeKit/HomeKitIntro/HomeKitIntro/Classes/AlertView.cs index c9effe3ce..4046bc406 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/Classes/AlertView.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/Classes/AlertView.cs @@ -3,20 +3,19 @@ using UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - public class AlertView - { +namespace HomeKitIntro { + public class AlertView { #region Static Methods - public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) { + public static UIAlertController PresentOKAlert (string title, string description, UIViewController controller) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Configure the alert - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {})); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (action) => { })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/Classes/CharacteristicDisplayType.cs b/HomeKit/HomeKitIntro/HomeKitIntro/Classes/CharacteristicDisplayType.cs index 13c7100b4..20ae7afb5 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/Classes/CharacteristicDisplayType.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/Classes/CharacteristicDisplayType.cs @@ -1,12 +1,10 @@ using System; -namespace HomeKitIntro -{ +namespace HomeKitIntro { /// /// Defines the type of cell used to display a Characteristic type. /// - public enum CharacteristicDisplayType - { + public enum CharacteristicDisplayType { Info, Slider, Stepper, diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/Classes/NSObjectConverter.cs b/HomeKit/HomeKitIntro/HomeKitIntro/Classes/NSObjectConverter.cs index 112118952..4d0c942ef 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/Classes/NSObjectConverter.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/Classes/NSObjectConverter.cs @@ -3,14 +3,12 @@ using System.Globalization; using CoreGraphics; -namespace HomeKitIntro -{ +namespace HomeKitIntro { /// /// NS object converter is a helper class that helps to convert NSObjects into /// C# objects /// - public static class NSObjectConverter - { + public static class NSObjectConverter { #region Static Methods /// /// Converts to an object. @@ -25,8 +23,8 @@ public static Object ToObject (NSObject nsO, Type targetType) } if (nsO is NSDate) { - var nsDate = (NSDate)nsO; - return DateTime.SpecifyKind ((DateTime)nsDate, DateTimeKind.Unspecified); + var nsDate = (NSDate) nsO; + return DateTime.SpecifyKind ((DateTime) nsDate, DateTimeKind.Unspecified); } if (nsO is NSDecimalNumber) { @@ -34,7 +32,7 @@ public static Object ToObject (NSObject nsO, Type targetType) } if (nsO is NSNumber) { - var x = (NSNumber)nsO; + var x = (NSNumber) nsO; switch (Type.GetTypeCode (targetType)) { case TypeCode.Boolean: @@ -65,23 +63,23 @@ public static Object ToObject (NSObject nsO, Type targetType) } if (nsO is NSValue) { - var v = (NSValue)nsO; + var v = (NSValue) nsO; - if (targetType == typeof(IntPtr)) { + if (targetType == typeof (IntPtr)) { return v.PointerValue; } - if (targetType == typeof(CGSize)) { + if (targetType == typeof (CGSize)) { return v.SizeFValue; } - if (targetType == typeof(CGRect)) { + if (targetType == typeof (CGRect)) { return v.RectangleFValue; } - if (targetType == typeof(CGPoint)) { + if (targetType == typeof (CGPoint)) { return v.PointFValue; - } + } } return nsO; @@ -92,8 +90,9 @@ public static Object ToObject (NSObject nsO, Type targetType) /// /// The string. /// Ns o. - public static string ToString(NSObject nsO) { - return (string)ToObject (nsO, typeof(string)); + public static string ToString (NSObject nsO) + { + return (string) ToObject (nsO, typeof (string)); } /// @@ -101,8 +100,9 @@ public static string ToString(NSObject nsO) { /// /// The date time. /// Ns o. - public static DateTime ToDateTime(NSObject nsO){ - return (DateTime)ToObject (nsO, typeof(DateTime)); + public static DateTime ToDateTime (NSObject nsO) + { + return (DateTime) ToObject (nsO, typeof (DateTime)); } /// @@ -110,8 +110,9 @@ public static DateTime ToDateTime(NSObject nsO){ /// /// The decimal. /// Ns o. - public static decimal ToDecimal(NSObject nsO){ - return (decimal)ToObject (nsO, typeof(decimal)); + public static decimal ToDecimal (NSObject nsO) + { + return (decimal) ToObject (nsO, typeof (decimal)); } /// @@ -119,8 +120,9 @@ public static decimal ToDecimal(NSObject nsO){ /// /// true, if bool was toed, false otherwise. /// Ns o. - public static bool ToBool(NSObject nsO){ - return (bool)ToObject (nsO, typeof(bool)); + public static bool ToBool (NSObject nsO) + { + return (bool) ToObject (nsO, typeof (bool)); } /// @@ -128,8 +130,9 @@ public static bool ToBool(NSObject nsO){ /// /// The char. /// Ns o. - public static char ToChar(NSObject nsO){ - return (char)ToObject (nsO, typeof(char)); + public static char ToChar (NSObject nsO) + { + return (char) ToObject (nsO, typeof (char)); } /// @@ -137,8 +140,9 @@ public static char ToChar(NSObject nsO){ /// /// The int. /// Ns o. - public static int ToInt(NSObject nsO){ - return (int)ToObject (nsO, typeof(int)); + public static int ToInt (NSObject nsO) + { + return (int) ToObject (nsO, typeof (int)); } /// @@ -146,8 +150,9 @@ public static int ToInt(NSObject nsO){ /// /// The float. /// Ns o. - public static float ToFloat(NSObject nsO){ - return (float)ToObject (nsO, typeof(float)); + public static float ToFloat (NSObject nsO) + { + return (float) ToObject (nsO, typeof (float)); } /// @@ -155,8 +160,9 @@ public static float ToFloat(NSObject nsO){ /// /// The double. /// Ns o. - public static double ToDouble(NSObject nsO){ - return (double)ToObject (nsO, typeof(double)); + public static double ToDouble (NSObject nsO) + { + return (double) ToObject (nsO, typeof (double)); } #endregion } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/HomeKitIntroViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/HomeKitIntroViewController.cs index 7d3b750f7..b7413e7b3 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/HomeKitIntroViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/HomeKitIntroViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; -namespace HomeKitIntro -{ - public partial class HomeKitIntroViewController : UIViewController - { +namespace HomeKitIntro { + public partial class HomeKitIntroViewController : UIViewController { public HomeKitIntroViewController (IntPtr handle) : base (handle) { } @@ -16,7 +14,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -25,7 +23,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/Main.cs b/HomeKit/HomeKitIntro/HomeKitIntro/Main.cs index 984b1125a..ad3ad218a 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/Main.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace HomeKitIntro -{ - public class Application - { +namespace HomeKitIntro { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/MasterTabViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/MasterTabViewController.cs index 88f467f20..cf02fc5de 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/MasterTabViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/MasterTabViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - partial class MasterTabViewController : UITabBarController - { +namespace HomeKitIntro { + partial class MasterTabViewController : UITabBarController { #region Constructors public MasterTabViewController (IntPtr handle) : base (handle) { diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/MasterViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/MasterViewController.cs index b978958d1..0c8c568a7 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/MasterViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/MasterViewController.cs @@ -3,17 +3,15 @@ using UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - partial class MasterViewController : UINavigationController - { +namespace HomeKitIntro { + partial class MasterViewController : UINavigationController { #region Computed Properties /// /// Returns the delegate of the current running application /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -34,12 +32,12 @@ public override void ViewDidAppear (bool animated) // Was a primary home found? if (ThisApp.HomeManager.PrimaryHome == null) { // Ask user to add a home - PerformSegue("AddHomeSegue",this); + PerformSegue ("AddHomeSegue", this); } else { } }; - + } #endregion } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/RoomTableViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/RoomTableViewController.cs index 05e2cf744..fd948dd8e 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/RoomTableViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/RoomTableViewController.cs @@ -3,10 +3,8 @@ using MonoTouch.UIKit; using System.CodeDom.Compiler; -namespace HomeKitIntro -{ - partial class RoomTableViewController : UITableViewController - { +namespace HomeKitIntro { + partial class RoomTableViewController : UITableViewController { public RoomTableViewController (IntPtr handle) : base (handle) { } diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableCell.cs b/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableCell.cs index 5053d6010..aa3831d03 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableCell.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableCell.cs @@ -4,10 +4,8 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class ServiceTableCell : UITableViewCell - { +namespace HomeKitIntro { + public partial class ServiceTableCell : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("ServiceTableCell"); #endregion @@ -28,7 +26,8 @@ public ServiceTableCell (IntPtr handle) : base (handle) /// /// Title. /// Subtitle. - public void DisplayInformation(string title, string subtitle) { + public void DisplayInformation (string title, string subtitle) + { // Update GUI Title.Text = title; @@ -41,7 +40,8 @@ public void DisplayInformation(string title, string subtitle) { /// /// Name. /// Type. - public void DisplayService(string name, HMServiceType type) { + public void DisplayService (string name, HMServiceType type) + { // Update GUI Title.Text = name; diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableSource.cs b/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableSource.cs index 680090cc4..7dbaf1c8b 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableSource.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableSource.cs @@ -4,13 +4,11 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public class ServiceTableSource : UITableViewSource - { +namespace HomeKitIntro { + public class ServiceTableSource : UITableViewSource { #region Private Variables private ServiceTableViewController _controller; - #endregion + #endregion #region Computed Properties /// @@ -18,7 +16,7 @@ public class ServiceTableSource : UITableViewSource /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -154,7 +152,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde switch (indexPath.Section) { case 0: // Display Accessory Details - accessoryCell.DisplayInformation (string.Format ("{0} Reachable", _controller.Accessory.Name), _controller.Accessory.Reachable.ToString()); + accessoryCell.DisplayInformation (string.Format ("{0} Reachable", _controller.Accessory.Name), _controller.Accessory.Reachable.ToString ()); accessoryCell.Accessory = UITableViewCellAccessory.None; break; case 1: diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableViewController.cs b/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableViewController.cs index 25f281c8a..ffd3321c5 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableViewController.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/ServiceTableViewController.cs @@ -4,17 +4,15 @@ using System.CodeDom.Compiler; using HomeKit; -namespace HomeKitIntro -{ - public partial class ServiceTableViewController : UITableViewController - { +namespace HomeKitIntro { + public partial class ServiceTableViewController : UITableViewController { #region Computed Properties /// /// Returns the delegate of the current running application /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// @@ -22,7 +20,7 @@ public AppDelegate ThisApp { /// /// The data source. public ServiceTableSource DataSource { - get { return (ServiceTableSource)TableView.Source; } + get { return (ServiceTableSource) TableView.Source; } } /// @@ -48,7 +46,8 @@ public ServiceTableViewController (IntPtr handle) : base (handle) /// /// Reloads the data. /// - public void ReloadData() { + public void ReloadData () + { // Ask the table to redisplay its information TableView.ReloadData (); diff --git a/HomeKit/HomeKitIntro/HomeKitIntro/Temp.cs b/HomeKit/HomeKitIntro/HomeKitIntro/Temp.cs index 32734e573..d1fca367e 100644 --- a/HomeKit/HomeKitIntro/HomeKitIntro/Temp.cs +++ b/HomeKit/HomeKitIntro/HomeKitIntro/Temp.cs @@ -1,4 +1,4 @@ -PowerState +PowerState Hue Saturation Brightness @@ -68,4 +68,4 @@ TargetSecuritySystemState TargetHorizontalTilt TargetPosition -TargetVerticalTilt \ No newline at end of file +TargetVerticalTilt diff --git a/HttpClient/HttpClient/AppDelegate.cs b/HttpClient/HttpClient/AppDelegate.cs index 690de81d4..4f76c2774 100644 --- a/HttpClient/HttpClient/AppDelegate.cs +++ b/HttpClient/HttpClient/AppDelegate.cs @@ -1,23 +1,21 @@ -using Foundation; +using Foundation; using UIKit; -namespace HttpClient -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace HttpClient { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window { get; set; } + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/HttpClient/HttpClient/Core/CocoaProvider.cs b/HttpClient/HttpClient/Core/CocoaProvider.cs index 5f7c5ebf8..d9c6d14bb 100644 --- a/HttpClient/HttpClient/Core/CocoaProvider.cs +++ b/HttpClient/HttpClient/Core/CocoaProvider.cs @@ -12,63 +12,59 @@ using System.Threading.Tasks; using Foundation; -namespace HttpClient.Core -{ - public class CocoaProvider : NetworkProvider - { - public override async Task ExecuteAsync() - { - Busy(); +namespace HttpClient.Core { + public class CocoaProvider : NetworkProvider { + public override async Task ExecuteAsync () + { + Busy (); - Stream result = null; - using (var cocoa = new Cocoa()) - { - result = await cocoa.ExecuteAsync(); - } + Stream result = null; + using (var cocoa = new Cocoa ()) { + result = await cocoa.ExecuteAsync (); + } - Done(); + Done (); - return result; - } - } + return result; + } + } - public class Cocoa : NSUrlConnectionDataDelegate - { - private TaskCompletionSource taskCompletionSource; + public class Cocoa : NSUrlConnectionDataDelegate { + private TaskCompletionSource taskCompletionSource; - private byte[] result; + private byte [] result; - public Cocoa() - { - result = new byte[0]; - } + public Cocoa () + { + result = new byte [0]; + } - public async Task ExecuteAsync() - { - taskCompletionSource = new TaskCompletionSource(); + public async Task ExecuteAsync () + { + taskCompletionSource = new TaskCompletionSource (); - var req = new NSUrlRequest(new NSUrl(NetworkProvider.WisdomUrl), NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 10); - NSUrlConnection.FromRequest(req, this); + var req = new NSUrlRequest (new NSUrl (NetworkProvider.WisdomUrl), NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 10); + NSUrlConnection.FromRequest (req, this); - return await taskCompletionSource.Task; - } + return await taskCompletionSource.Task; + } - public override void ReceivedData(NSUrlConnection connection, NSData data) - { - var nb = new byte[result.Length + (int)data.Length]; - result.CopyTo(nb, 0); - Marshal.Copy(data.Bytes, nb, result.Length, (int)data.Length); - result = nb; - } + public override void ReceivedData (NSUrlConnection connection, NSData data) + { + var nb = new byte [result.Length + (int) data.Length]; + result.CopyTo (nb, 0); + Marshal.Copy (data.Bytes, nb, result.Length, (int) data.Length); + result = nb; + } - public override void FinishedLoading(NSUrlConnection connection) - { - taskCompletionSource.TrySetResult(new MemoryStream(result)); - } + public override void FinishedLoading (NSUrlConnection connection) + { + taskCompletionSource.TrySetResult (new MemoryStream (result)); + } - public override void FailedWithError(NSUrlConnection connection, NSError error) - { - taskCompletionSource.TrySetResult(null); - } - } -} \ No newline at end of file + public override void FailedWithError (NSUrlConnection connection, NSError error) + { + taskCompletionSource.TrySetResult (null); + } + } +} diff --git a/HttpClient/HttpClient/Core/DotNetProvider.cs b/HttpClient/HttpClient/Core/DotNetProvider.cs index 8548393a9..c317e0535 100644 --- a/HttpClient/HttpClient/Core/DotNetProvider.cs +++ b/HttpClient/HttpClient/Core/DotNetProvider.cs @@ -11,87 +11,76 @@ using System.Net; using System.Threading.Tasks; -namespace HttpClient.Core -{ - public class DotNetProvider : NetworkProvider - { - private TaskCompletionSource taskCompletionSource; +namespace HttpClient.Core { + public class DotNetProvider : NetworkProvider { + private TaskCompletionSource taskCompletionSource; - private readonly bool secure; + private readonly bool secure; - public DotNetProvider(bool secure) - { - this.secure = secure; - } + public DotNetProvider (bool secure) + { + this.secure = secure; + } - public override async Task ExecuteAsync() - { - Busy(); - taskCompletionSource = new TaskCompletionSource(); + public override async Task ExecuteAsync () + { + Busy (); + taskCompletionSource = new TaskCompletionSource (); - if (!secure) - { - // http - var request = WebRequest.Create(WisdomUrl); - request.BeginGetResponse(FeedDownloaded, request); - } - else - { - // https - var request = (HttpWebRequest)WebRequest.Create("https://gmail.com"); + if (!secure) { + // http + var request = WebRequest.Create (WisdomUrl); + request.BeginGetResponse (FeedDownloaded, request); + } else { + // https + var request = (HttpWebRequest) WebRequest.Create ("https://gmail.com"); - // - // To not depend on the root certficates, we will - // accept any certificates: - // - ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, ssl) => true; + // + // To not depend on the root certficates, we will + // accept any certificates: + // + ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, ssl) => true; - request.BeginGetResponse(GmailDownloaded, request); - } + request.BeginGetResponse (GmailDownloaded, request); + } - return await taskCompletionSource.Task; - } + return await taskCompletionSource.Task; + } - /// - /// Invoked when we get the stream back from the twitter feed - /// We parse the RSS feed and push the data into a table. - /// - private void FeedDownloaded(IAsyncResult result) - { - Done(); - var request = result.AsyncState as HttpWebRequest; + /// + /// Invoked when we get the stream back from the twitter feed + /// We parse the RSS feed and push the data into a table. + /// + private void FeedDownloaded (IAsyncResult result) + { + Done (); + var request = result.AsyncState as HttpWebRequest; - try - { - var response = request.EndGetResponse(result); - taskCompletionSource.TrySetResult(response.GetResponseStream()); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine(ex); - taskCompletionSource.TrySetResult(null); - } - } + try { + var response = request.EndGetResponse (result); + taskCompletionSource.TrySetResult (response.GetResponseStream ()); + } catch (Exception ex) { + System.Diagnostics.Debug.WriteLine (ex); + taskCompletionSource.TrySetResult (null); + } + } - /// - /// This sample just gets the result from calling https://gmail.com, an HTTPS secure connection, - /// we do not attempt to parse the output, but merely dump it as text - /// - private void GmailDownloaded(IAsyncResult result) - { - Done(); - var request = result.AsyncState as HttpWebRequest; + /// + /// This sample just gets the result from calling https://gmail.com, an HTTPS secure connection, + /// we do not attempt to parse the output, but merely dump it as text + /// + private void GmailDownloaded (IAsyncResult result) + { + Done (); + var request = result.AsyncState as HttpWebRequest; - try - { - var response = request.EndGetResponse(result); - taskCompletionSource.TrySetResult(response.GetResponseStream()); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine(ex); - taskCompletionSource.TrySetResult(null); - } - } - } -} \ No newline at end of file + try { + var response = request.EndGetResponse (result); + taskCompletionSource.TrySetResult (response.GetResponseStream ()); + } catch (Exception ex) { + System.Diagnostics.Debug.WriteLine (ex); + taskCompletionSource.TrySetResult (null); + } + } + } +} diff --git a/HttpClient/HttpClient/Core/NetHttpProvider.cs b/HttpClient/HttpClient/Core/NetHttpProvider.cs index 63ecaa3bc..a16b5a21b 100644 --- a/HttpClient/HttpClient/Core/NetHttpProvider.cs +++ b/HttpClient/HttpClient/Core/NetHttpProvider.cs @@ -7,37 +7,34 @@ using System.IO; using System.Threading.Tasks; -namespace HttpClient.Core -{ - public class NetHttpProvider : NetworkProvider - { - private readonly bool secure; - - public NetHttpProvider(bool secure) - { - this.secure = secure; - } - - public override async Task ExecuteAsync() - { - Busy(); - - var client = new System.Net.Http.HttpClient(); - var stream = await client.GetStreamAsync(secure ? "https://www.xamarin.com" : WisdomUrl); - - Done(); - return stream; - } - - public static Type GetHandlerType() - { - Type result = null; - using (var client = new System.Net.Http.HttpClient()) - { - result = typeof(System.Net.Http.HttpMessageInvoker).GetField("handler", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(client).GetType(); - } - - return result; - } - } -} \ No newline at end of file +namespace HttpClient.Core { + public class NetHttpProvider : NetworkProvider { + private readonly bool secure; + + public NetHttpProvider (bool secure) + { + this.secure = secure; + } + + public override async Task ExecuteAsync () + { + Busy (); + + var client = new System.Net.Http.HttpClient (); + var stream = await client.GetStreamAsync (secure ? "https://www.xamarin.com" : WisdomUrl); + + Done (); + return stream; + } + + public static Type GetHandlerType () + { + Type result = null; + using (var client = new System.Net.Http.HttpClient ()) { + result = typeof (System.Net.Http.HttpMessageInvoker).GetField ("handler", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue (client).GetType (); + } + + return result; + } + } +} diff --git a/HttpClient/HttpClient/Core/NetworkProvider.cs b/HttpClient/HttpClient/Core/NetworkProvider.cs index 8c3c3a1c3..56e7af69e 100644 --- a/HttpClient/HttpClient/Core/NetworkProvider.cs +++ b/HttpClient/HttpClient/Core/NetworkProvider.cs @@ -1,24 +1,22 @@ -using System.IO; -using System.Threading.Tasks; +using System.IO; +using System.Threading.Tasks; using UIKit; -namespace HttpClient.Core -{ - public abstract class NetworkProvider - { - // URL where we fetch the wisdom from - public const string WisdomUrl = "http://httpbin.org/ip"; +namespace HttpClient.Core { + public abstract class NetworkProvider { + // URL where we fetch the wisdom from + public const string WisdomUrl = "http://httpbin.org/ip"; - protected void Busy() - { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - } + protected void Busy () + { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; + } - protected void Done() - { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - } - - public abstract Task ExecuteAsync(); - } -} \ No newline at end of file + protected void Done () + { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + } + + public abstract Task ExecuteAsync (); + } +} diff --git a/HttpClient/HttpClient/Main.cs b/HttpClient/HttpClient/Main.cs index 21082c30f..236b9bef2 100644 --- a/HttpClient/HttpClient/Main.cs +++ b/HttpClient/HttpClient/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace HttpClient -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace HttpClient { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/HttpClient/HttpClient/ResponseViewController.cs b/HttpClient/HttpClient/ResponseViewController.cs index 0df1456a2..afc153ee4 100644 --- a/HttpClient/HttpClient/ResponseViewController.cs +++ b/HttpClient/HttpClient/ResponseViewController.cs @@ -1,34 +1,29 @@ using HttpClient.Core; -using System; +using System; using System.IO; -using UIKit; - -namespace HttpClient -{ - public partial class ResponseViewController : UIViewController - { - public ResponseViewController (IntPtr handle) : base (handle) { } +using UIKit; - public NetworkProvider Provider { get; set; } - - public override async void ViewDidLoad() - { - base.ViewDidLoad(); - - if(Provider.GetType() == typeof(NetHttpProvider)) - { - TitleLabel.Text = $"HttpClient is using {NetHttpProvider.GetHandlerType().Name}"; - TitleLabel.Hidden = false; - } - - // execute request - using (var stream = await Provider.ExecuteAsync()) - { - using (var streamReader = new StreamReader(stream)) - { - ResponseTextView.Text = await streamReader.ReadToEndAsync(); - } - } - } - } -} \ No newline at end of file +namespace HttpClient { + public partial class ResponseViewController : UIViewController { + public ResponseViewController (IntPtr handle) : base (handle) { } + + public NetworkProvider Provider { get; set; } + + public override async void ViewDidLoad () + { + base.ViewDidLoad (); + + if (Provider.GetType () == typeof (NetHttpProvider)) { + TitleLabel.Text = $"HttpClient is using {NetHttpProvider.GetHandlerType ().Name}"; + TitleLabel.Hidden = false; + } + + // execute request + using (var stream = await Provider.ExecuteAsync ()) { + using (var streamReader = new StreamReader (stream)) { + ResponseTextView.Text = await streamReader.ReadToEndAsync (); + } + } + } + } +} diff --git a/HttpClient/HttpClient/ViewController.cs b/HttpClient/HttpClient/ViewController.cs index 155ecc062..ac7a8cdbe 100644 --- a/HttpClient/HttpClient/ViewController.cs +++ b/HttpClient/HttpClient/ViewController.cs @@ -1,102 +1,94 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using HttpClient.Core; using UIKit; -namespace HttpClient -{ - public partial class ViewController : UITableViewController - { - private const string SegueIdentidfier = "showRequestDetails"; - private const string CellIdentidfier = "cell_identifier"; +namespace HttpClient { + public partial class ViewController : UITableViewController { + private const string SegueIdentidfier = "showRequestDetails"; + private const string CellIdentidfier = "cell_identifier"; - private readonly List configurations = new List - { - new RequestConfiguration { Type = RequestType.WebRequestHttp, Title = "WebRequest (http)" }, - new RequestConfiguration { Type = RequestType.WebRequestHttps, Title = "WebRequest (https)" }, - new RequestConfiguration { Type = RequestType.NSUrlConnectionHttp, Title = "NSUrlConnection (http)" }, - new RequestConfiguration { Type = RequestType.HttpClientHttp, Title = "HttpClient (http)" }, - new RequestConfiguration { Type = RequestType.HttpClientHttps, Title = "HttpClient (https)" }, - }; + private readonly List configurations = new List + { + new RequestConfiguration { Type = RequestType.WebRequestHttp, Title = "WebRequest (http)" }, + new RequestConfiguration { Type = RequestType.WebRequestHttps, Title = "WebRequest (https)" }, + new RequestConfiguration { Type = RequestType.NSUrlConnectionHttp, Title = "NSUrlConnection (http)" }, + new RequestConfiguration { Type = RequestType.HttpClientHttp, Title = "HttpClient (http)" }, + new RequestConfiguration { Type = RequestType.HttpClientHttps, Title = "HttpClient (https)" }, + }; - protected ViewController(IntPtr handle) : base(handle) { } + protected ViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - TableView.SelectRow(NSIndexPath.FromRowSection(0, 0), false, UITableViewScrollPosition.Top); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + TableView.SelectRow (NSIndexPath.FromRowSection (0, 0), false, UITableViewScrollPosition.Top); + } - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if(!string.IsNullOrEmpty(segue?.Identifier) && segue.Identifier == SegueIdentidfier) - { - if (segue.DestinationViewController is ResponseViewController responseViewController) - { - NetworkProvider provider = null; - var selectedConfiguration = configurations[TableView.IndexPathForSelectedRow.Row]; - switch (selectedConfiguration.Type) - { - case RequestType.WebRequestHttp: - provider = new DotNetProvider(false); - break; - case RequestType.WebRequestHttps: - provider = new DotNetProvider(true); - break; - case RequestType.NSUrlConnectionHttp: - provider = new CocoaProvider(); - break; - case RequestType.HttpClientHttp: - provider = new NetHttpProvider(false); - break; - case RequestType.HttpClientHttps: - provider = new NetHttpProvider(true); - break; - } + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (!string.IsNullOrEmpty (segue?.Identifier) && segue.Identifier == SegueIdentidfier) { + if (segue.DestinationViewController is ResponseViewController responseViewController) { + NetworkProvider provider = null; + var selectedConfiguration = configurations [TableView.IndexPathForSelectedRow.Row]; + switch (selectedConfiguration.Type) { + case RequestType.WebRequestHttp: + provider = new DotNetProvider (false); + break; + case RequestType.WebRequestHttps: + provider = new DotNetProvider (true); + break; + case RequestType.NSUrlConnectionHttp: + provider = new CocoaProvider (); + break; + case RequestType.HttpClientHttp: + provider = new NetHttpProvider (false); + break; + case RequestType.HttpClientHttps: + provider = new NetHttpProvider (true); + break; + } - responseViewController.Provider = provider; - } - } - } + responseViewController.Provider = provider; + } + } + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return configurations.Count; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return configurations.Count; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(CellIdentidfier, indexPath); + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (CellIdentidfier, indexPath); - var configuration = configurations[indexPath.Row]; - cell.TextLabel.Text = configuration.Title; + var configuration = configurations [indexPath.Row]; + cell.TextLabel.Text = configuration.Title; - return cell; - } + return cell; + } - partial void RunHttpRequest(UIButton sender) - { - if(TableView.IndexPathForSelectedRow != null) - { - this.PerformSegue(SegueIdentidfier, this); - } - } - } + partial void RunHttpRequest (UIButton sender) + { + if (TableView.IndexPathForSelectedRow != null) { + this.PerformSegue (SegueIdentidfier, this); + } + } + } - class RequestConfiguration - { - public string Title { get; set; } + class RequestConfiguration { + public string Title { get; set; } - public RequestType Type { get; set; } - } + public RequestType Type { get; set; } + } - enum RequestType - { - WebRequestHttp, - WebRequestHttps, - NSUrlConnectionHttp, - HttpClientHttp, - HttpClientHttps, - } -} \ No newline at end of file + enum RequestType { + WebRequestHttp, + WebRequestHttps, + NSUrlConnectionHttp, + HttpClientHttp, + HttpClientHttps, + } +} diff --git a/ImageProtocol/AppDelegate.cs b/ImageProtocol/AppDelegate.cs index b1033afa2..ebcf5cf88 100644 --- a/ImageProtocol/AppDelegate.cs +++ b/ImageProtocol/AppDelegate.cs @@ -31,11 +31,9 @@ using Foundation; using UIKit; -namespace ImageProtocol -{ +namespace ImageProtocol { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UIWebView web; UIViewController controller; @@ -54,8 +52,8 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary }; if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) web.Frame = new CGRect (0, 20, - UIScreen.MainScreen.Bounds.Width, - UIScreen.MainScreen.Bounds.Height - 20); + UIScreen.MainScreen.Bounds.Width, + UIScreen.MainScreen.Bounds.Height - 20); else web.Frame = UIScreen.MainScreen.Bounds; controller.NavigationItem.Title = "Test case"; diff --git a/ImageProtocol/ImageProtocol.cs b/ImageProtocol/ImageProtocol.cs index 0e702103d..c876ccdd3 100644 --- a/ImageProtocol/ImageProtocol.cs +++ b/ImageProtocol/ImageProtocol.cs @@ -31,10 +31,8 @@ using Foundation; using UIKit; -namespace ImageProtocol -{ - public class ImageProtocol : NSUrlProtocol - { +namespace ImageProtocol { + public class ImageProtocol : NSUrlProtocol { [Export ("canInitWithRequest:")] public static bool canInitWithRequest (NSUrlRequest request) { @@ -59,7 +57,8 @@ public override void StartLoading () using (var image = Render (value)) { using (var response = new NSUrlResponse (Request.Url, "image/jpeg", -1, null)) { Client.ReceivedResponse (this, response, NSUrlCacheStoragePolicy.NotAllowed); - this.InvokeOnMainThread (delegate { + this.InvokeOnMainThread (delegate + { using (var data = image.AsJPEG ()) { Client.DataLoaded (this, data); } diff --git a/ImageProtocol/Main.cs b/ImageProtocol/Main.cs index 48172117e..70ce6e77d 100644 --- a/ImageProtocol/Main.cs +++ b/ImageProtocol/Main.cs @@ -30,11 +30,9 @@ using Foundation; using UIKit; -namespace ImageProtocol -{ - public class Application - { - static void Main (string[] args) +namespace ImageProtocol { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/ApiDefinition.cs b/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/ApiDefinition.cs index ac2cacd3c..af164c750 100644 --- a/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/ApiDefinition.cs +++ b/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/ApiDefinition.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using ObjCRuntime; @@ -67,7 +67,7 @@ interface InfColorPickerController { } // @protocol InfColorPickerControllerDelegate - [BaseType(typeof(NSObject))] + [BaseType (typeof (NSObject))] [Model] interface InfColorPickerControllerDelegate { diff --git a/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/StructsAndEnums.cs b/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/StructsAndEnums.cs index 8116e41fb..028bf145d 100644 --- a/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/StructsAndEnums.cs +++ b/InfColorPicker/InfColorPickerBinding/InfColorPickerBinding/StructsAndEnums.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace InfColorPicker { diff --git a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/AppDelegate.cs b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/AppDelegate.cs index 733436cde..eeb212163 100644 --- a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/AppDelegate.cs +++ b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/AppDelegate.cs @@ -1,43 +1,41 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace InfColorPickerSample -{ +namespace InfColorPickerSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/ColorSelectedDelegate.cs b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/ColorSelectedDelegate.cs index c588eceea..79944ce8e 100644 --- a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/ColorSelectedDelegate.cs +++ b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/ColorSelectedDelegate.cs @@ -1,11 +1,9 @@ -using System; +using System; using InfColorPicker; using UIKit; -namespace InfColorPickerSample -{ - public class ColorSelectedDelegate:InfColorPickerControllerDelegate - { +namespace InfColorPickerSample { + public class ColorSelectedDelegate : InfColorPickerControllerDelegate { private UIViewController _parent; public ColorSelectedDelegate (UIViewController parent) { diff --git a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/InfColorPickerSampleViewController.cs b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/InfColorPickerSampleViewController.cs index 61ebd03ed..200dc5502 100644 --- a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/InfColorPickerSampleViewController.cs +++ b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/InfColorPickerSampleViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; using InfColorPicker; -namespace InfColorPickerSample -{ - public partial class InfColorPickerSampleViewController : UIViewController - { +namespace InfColorPickerSample { + public partial class InfColorPickerSampleViewController : UIViewController { #region Private Variables private ColorSelectedDelegate _selector; #endregion @@ -22,14 +20,14 @@ public InfColorPickerSampleViewController (IntPtr handle) : base (handle) #region Private Methods private void HandleTouchUpInsideWithStrongDelegate (object sender, EventArgs e) { - InfColorPickerController picker = InfColorPickerController.ColorPickerViewController(); + InfColorPickerController picker = InfColorPickerController.ColorPickerViewController (); picker.Delegate = _selector; picker.PresentModallyOverViewController (this); } private void HandleTouchUpInsideWithWeakDelegate (object sender, EventArgs e) { - InfColorPickerController picker = InfColorPickerController.ColorPickerViewController(); + InfColorPickerController picker = InfColorPickerController.ColorPickerViewController (); picker.WeakDelegate = this; picker.SourceColor = this.View.BackgroundColor; picker.PresentModallyOverViewController (this); @@ -37,7 +35,7 @@ private void HandleTouchUpInsideWithWeakDelegate (object sender, EventArgs e) #endregion #region Public Methods - [Export("colorPickerControllerDidFinish:")] + [Export ("colorPickerControllerDidFinish:")] public void ColorPickerControllerDidFinish (InfColorPickerController controller) { View.BackgroundColor = controller.ResultColor; diff --git a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/Main.cs b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/Main.cs index 5fb06f3e0..93f66fa18 100644 --- a/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/Main.cs +++ b/InfColorPicker/InfColorPickerBinding/InfColorPickerSample/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace InfColorPickerSample -{ - public class Application - { +namespace InfColorPickerSample { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/AppDelegate.cs b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/AppDelegate.cs index a6ed55303..34d877743 100644 --- a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/AppDelegate.cs +++ b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace ExclusionPathDemo -{ +namespace ExclusionPathDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; ExclusionPathDemoViewController viewController; @@ -25,11 +23,11 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - + viewController = new ExclusionPathDemoViewController (); window.RootViewController = viewController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathDemoViewController.cs b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathDemoViewController.cs index d7a572b1d..1bcab049a 100644 --- a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathDemoViewController.cs +++ b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathDemoViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace ExclusionPathDemo -{ - public class ExclusionPathDemoViewController : UIViewController - { +namespace ExclusionPathDemo { + public class ExclusionPathDemoViewController : UIViewController { ExclusionPathView textView; public ExclusionPathDemoViewController () @@ -22,8 +20,8 @@ public override void ViewDidLoad () textView = new ExclusionPathView (text) { Frame = UIScreen.MainScreen.Bounds }; textView.TextStorage.BeginEditing (); - textView.TextStorage.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Green, new NSRange(200, 400)); - textView.TextStorage.AddAttribute(UIStringAttributeKey.BackgroundColor, UIColor.Black, new NSRange(210, 300)); + textView.TextStorage.AddAttribute (UIStringAttributeKey.ForegroundColor, UIColor.Green, new NSRange (200, 400)); + textView.TextStorage.AddAttribute (UIStringAttributeKey.BackgroundColor, UIColor.Black, new NSRange (210, 300)); textView.TextStorage.EndEditing (); View.AddSubview (textView); diff --git a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathView.cs b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathView.cs index c25c2ff30..411aab4b5 100644 --- a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathView.cs +++ b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/ExclusionPathView.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace ExclusionPathDemo -{ - public class ExclusionPathView : UITextView - { - CGPath exclusionPath; +namespace ExclusionPathDemo { + public class ExclusionPathView : UITextView { + CGPath exclusionPath; CGPoint initialPoint; CGPoint latestPoint; UIBezierPath bezierPath; @@ -51,7 +49,7 @@ public override void TouchesEnded (NSSet touches, UIEvent evt) base.TouchesEnded (touches, evt); bezierPath.CGPath = exclusionPath; - TextContainer.ExclusionPaths = new UIBezierPath[] { bezierPath }; + TextContainer.ExclusionPaths = new UIBezierPath [] { bezierPath }; } public override void Draw (CGRect rect) @@ -66,7 +64,7 @@ public override void Draw (CGRect rect) UIColor.Blue.SetStroke (); if (exclusionPath.IsEmpty) { - exclusionPath.AddLines (new CGPoint[] { initialPoint, latestPoint }); + exclusionPath.AddLines (new CGPoint [] { initialPoint, latestPoint }); } else { exclusionPath.AddLineToPoint (latestPoint); } diff --git a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/Main.cs b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/Main.cs index 4235b3d6a..6d62cdbb4 100644 --- a/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/Main.cs +++ b/IntroToiOS7/ExclusionPathDemo/ExclusionPathDemo/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace ExclusionPathDemo -{ - public class Application - { +namespace ExclusionPathDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/AppDelegate.cs b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/AppDelegate.cs index f458d673a..33c8465a9 100644 --- a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/AppDelegate.cs +++ b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/AppDelegate.cs @@ -2,24 +2,22 @@ using Foundation; using UIKit; -namespace CustomTransitionDemo -{ +namespace CustomTransitionDemo { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; ControllerOne controllerOne; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - + controllerOne = new ControllerOne (); window.RootViewController = controllerOne; window.MakeKeyAndVisible (); - + return true; } } -} \ No newline at end of file +} diff --git a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerOne.cs b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerOne.cs index 4b6f178fd..47aadc56e 100644 --- a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerOne.cs +++ b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerOne.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace CustomTransitionDemo -{ - public partial class ControllerOne : UIViewController - { +namespace CustomTransitionDemo { + public partial class ControllerOne : UIViewController { UIButton showTwo; ControllerTwo controllerTwo; TransitioningDelegate transitioningDelegate; @@ -20,7 +18,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); View.BackgroundColor = UIColor.White; - + showTwo = UIButton.FromType (UIButtonType.System); showTwo.Frame = new CGRect (View.Frame.Width / 2 - 100, View.Frame.Height / 2 - 25, 200, 50); showTwo.SetTitle ("Show Controller Two", UIControlState.Normal); diff --git a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerTwo.cs b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerTwo.cs index b01d52945..b2e86e115 100644 --- a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerTwo.cs +++ b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/ControllerTwo.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace CustomTransitionDemo -{ - public partial class ControllerTwo : UIViewController - { +namespace CustomTransitionDemo { + public partial class ControllerTwo : UIViewController { UIButton showOne; public ControllerTwo () diff --git a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/CustomTransitionAnimator.cs b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/CustomTransitionAnimator.cs index 95f9c0839..a8076ef30 100644 --- a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/CustomTransitionAnimator.cs +++ b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/CustomTransitionAnimator.cs @@ -2,10 +2,8 @@ using CoreGraphics; using UIKit; -namespace CustomTransitionDemo -{ - public class CustomTransitionAnimator : UIViewControllerAnimatedTransitioning - { +namespace CustomTransitionDemo { + public class CustomTransitionAnimator : UIViewControllerAnimatedTransitioning { public CustomTransitionAnimator () { } @@ -34,8 +32,7 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr } } - public class TransitioningDelegate : UIViewControllerTransitioningDelegate - { + public class TransitioningDelegate : UIViewControllerTransitioningDelegate { CustomTransitionAnimator animator; public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForPresentedController (UIViewController presented, UIViewController presenting, UIViewController source) diff --git a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/Main.cs b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/Main.cs index ecedb5bae..fdad5e16b 100644 --- a/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/Main.cs +++ b/IntroToiOS7/TransitionDemos/CustomTransitionDemo/CustomTransitionDemo/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace CustomTransitionDemo -{ - public class Application - { +namespace CustomTransitionDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/AppDelegate.cs b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/AppDelegate.cs index bb4f4767b..91acac929 100644 --- a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/AppDelegate.cs +++ b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/AppDelegate.cs @@ -6,14 +6,12 @@ using UIKit; using CoreGraphics; -namespace InteractiveTransitionLayout -{ +namespace InteractiveTransitionLayout { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; ImagesCollectionViewController imagesController; UICollectionViewFlowLayout flowLayout; @@ -28,17 +26,17 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window = new UIWindow (UIScreen.MainScreen.Bounds); // create and initialize a UICollectionViewFlowLayout - flowLayout = new UICollectionViewFlowLayout (){ - SectionInset = new UIEdgeInsets (25,5,10,5), + flowLayout = new UICollectionViewFlowLayout () { + SectionInset = new UIEdgeInsets (25, 5, 10, 5), MinimumInteritemSpacing = 5, MinimumLineSpacing = 5, ItemSize = new CGSize (100, 100) }; - circleLayout = new CircleLayout (Monkeys.Instance.Count){ + circleLayout = new CircleLayout (Monkeys.Instance.Count) { ItemSize = new CGSize (100, 100) }; - + imagesController = new ImagesCollectionViewController (flowLayout); nfloat sf = 0.4f; @@ -47,25 +45,25 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) pinch = new UIPinchGestureRecognizer (g => { - var progress = Math.Abs(1.0f - g.Scale)/sf; + var progress = Math.Abs (1.0f - g.Scale) / sf; - if(trLayout == null){ - if(imagesController.CollectionView.CollectionViewLayout is CircleLayout) + if (trLayout == null) { + if (imagesController.CollectionView.CollectionViewLayout is CircleLayout) nextLayout = flowLayout; else nextLayout = circleLayout; - trLayout = imagesController.CollectionView.StartInteractiveTransition (nextLayout, (completed, finished) => { + trLayout = imagesController.CollectionView.StartInteractiveTransition (nextLayout, (completed, finished) => { Console.WriteLine ("transition completed"); trLayout = null; }); } - trLayout.TransitionProgress = (nfloat)progress; + trLayout.TransitionProgress = (nfloat) progress; imagesController.CollectionView.CollectionViewLayout.InvalidateLayout (); - if(g.State == UIGestureRecognizerState.Ended){ + if (g.State == UIGestureRecognizerState.Ended) { if (trLayout.TransitionProgress > 0.5f) imagesController.CollectionView.FinishInteractiveTransition (); else @@ -78,7 +76,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.RootViewController = imagesController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/CircleLayout.cs b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/CircleLayout.cs index f8290b19f..e0c9d0ad2 100644 --- a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/CircleLayout.cs +++ b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/CircleLayout.cs @@ -5,11 +5,9 @@ using CoreAnimation; using UIKit; -namespace InteractiveTransitionLayout -{ +namespace InteractiveTransitionLayout { // this class creates a circular layout - public class CircleLayout : UICollectionViewLayout - { + public class CircleLayout : UICollectionViewLayout { nint count; double radius; CGPoint center; @@ -29,11 +27,11 @@ public CircleLayout (int itemCount) public override void PrepareLayout () { base.PrepareLayout (); - + CGSize size = CollectionView.Frame.Size; count = CollectionView.NumberOfItemsInSection (0); center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f); - radius = Math.Min (size.Width, size.Height) / 2.5f; + radius = Math.Min (size.Width, size.Height) / 2.5f; } // return the overall content size for the collection view @@ -55,22 +53,22 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSInde { UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell (path); attributes.Size = ItemSize; - attributes.Center = new CGPoint (center.X + radius * (float)Math.Cos (2 * path.Row * Math.PI / count), - center.Y + radius * (float)Math.Sin (2 * path.Row * Math.PI / count)); + attributes.Center = new CGPoint (center.X + radius * (float) Math.Cos (2 * path.Row * Math.PI / count), + center.Y + radius * (float) Math.Sin (2 * path.Row * Math.PI / count)); attributes.Transform3D = CATransform3D.MakeScale (0.5f, 0.5f, 1.0f); return attributes; } // return layout attributes for all the items in a given rectangle - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { - UICollectionViewLayoutAttributes[] attributes = new UICollectionViewLayoutAttributes [count]; - + UICollectionViewLayoutAttributes [] attributes = new UICollectionViewLayoutAttributes [count]; + for (int i = 0; i < count; i++) { NSIndexPath indexPath = NSIndexPath.FromItemSection (i, 0); attributes [i] = LayoutAttributesForItem (indexPath); } - + return attributes; } } diff --git a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/ImagesCollectionViewController.cs b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/ImagesCollectionViewController.cs index 844c372cf..ba466d005 100644 --- a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/ImagesCollectionViewController.cs +++ b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/ImagesCollectionViewController.cs @@ -6,10 +6,8 @@ using System.Threading; using MonoTouch.Dialog.Utilities; -namespace InteractiveTransitionLayout -{ - public class ImagesCollectionViewController : UICollectionViewController - { +namespace InteractiveTransitionLayout { + public class ImagesCollectionViewController : UICollectionViewController { static readonly NSString cellId = new NSString ("ImageCell"); Monkeys monkeys; @@ -25,9 +23,9 @@ public ImagesCollectionViewController (UICollectionViewLayout layout) : base (la public override void ViewDidLoad () { base.ViewDidLoad (); - + // register the ImageCell so it can be created from a DequeueReusableCell call - CollectionView.RegisterClassForCell (typeof(ImageCell), cellId); + CollectionView.RegisterClassForCell (typeof (ImageCell), cellId); } public override nint GetItemsCount (UICollectionView collectionView, nint section) @@ -38,24 +36,23 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { // get an ImageCell from the pool. DequeueReusableCell will create one if necessary - ImageCell imageCell = (ImageCell)collectionView.DequeueReusableCell (cellId, indexPath); + ImageCell imageCell = (ImageCell) collectionView.DequeueReusableCell (cellId, indexPath); // update the image for the speaker imageCell.UpdateImage (monkeys [indexPath.Row].ImageFile); - + return imageCell; } // class to use for cell - class ImageCell : UICollectionViewCell - { + class ImageCell : UICollectionViewCell { UIImageView imageView; [Export ("initWithFrame:")] ImageCell (CGRect frame) : base (frame) { // create an image view to use in the cell - imageView = new UIImageView (new CGRect (0, 0, 100, 100)); + imageView = new UIImageView (new CGRect (0, 0, 100, 100)); imageView.ContentMode = UIViewContentMode.ScaleAspectFit; // populate the content view diff --git a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Main.cs b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Main.cs index 366755e8c..4312ff181 100644 --- a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Main.cs +++ b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace InteractiveTransitionLayout -{ - public class Application - { +namespace InteractiveTransitionLayout { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Monkeys.cs b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Monkeys.cs index 242d93344..5bf6d8188 100644 --- a/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Monkeys.cs +++ b/IntroToiOS7/TransitionDemos/InteractiveTransitionLayout/InteractiveTransitionLayout/Monkeys.cs @@ -5,33 +5,30 @@ using System.Text.RegularExpressions; using Foundation; -namespace InteractiveTransitionLayout -{ +namespace InteractiveTransitionLayout { // Loads a collection of monkeys containing file paths of monkey images - public class Monkeys : List - { + public class Monkeys : List { static readonly Monkeys monkeys = new Monkeys (); - Monkeys () + Monkeys () { Regex pattern = new Regex (@"^.*\.(jpg|jpeg|png)$", RegexOptions.IgnoreCase); string path = Path.Combine (NSBundle.MainBundle.BundlePath, "Images"); Directory.GetFiles (path).Where (f => pattern.IsMatch (f)).ToList ().ForEach (p => { - Monkey s = new Monkey{ImageFile = "Images/" + Path.GetFileName(p)}; + Monkey s = new Monkey { ImageFile = "Images/" + Path.GetFileName (p) }; this.Add (s); }); } public static Monkeys Instance { - get{ + get { return monkeys; } } - public class Monkey - { + public class Monkey { public string ImageFile { get; set; } } } -} \ No newline at end of file +} diff --git a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/AppDelegate.cs b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/AppDelegate.cs index 850388293..8b4f2273e 100644 --- a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/AppDelegate.cs +++ b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/AppDelegate.cs @@ -6,14 +6,12 @@ using UIKit; using CoreGraphics; -namespace LayoutWithNavController -{ +namespace LayoutWithNavController { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; ImagesCollectionViewController viewController; UICollectionViewFlowLayout layout; @@ -27,8 +25,8 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window = new UIWindow (UIScreen.MainScreen.Bounds); // create and initialize a UICollectionViewFlowLayout - layout = new UICollectionViewFlowLayout (){ - SectionInset = new UIEdgeInsets (10,5,10,5), + layout = new UICollectionViewFlowLayout () { + SectionInset = new UIEdgeInsets (10, 5, 10, 5), MinimumInteritemSpacing = 5, MinimumLineSpacing = 5, ItemSize = new CGSize (100, 100) @@ -41,7 +39,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.RootViewController = navController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/CircleLayout.cs b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/CircleLayout.cs index 314733828..65c04e253 100644 --- a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/CircleLayout.cs +++ b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/CircleLayout.cs @@ -5,11 +5,9 @@ using CoreAnimation; using UIKit; -namespace LayoutWithNavController -{ +namespace LayoutWithNavController { // this class creates a circular layout - public class CircleLayout : UICollectionViewLayout - { + public class CircleLayout : UICollectionViewLayout { nint count; double radius; CGPoint center; @@ -29,11 +27,11 @@ public CircleLayout (int itemCount) public override void PrepareLayout () { base.PrepareLayout (); - + CGSize size = CollectionView.Frame.Size; count = CollectionView.NumberOfItemsInSection (0); center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f); - radius = Math.Min (size.Width, size.Height) / 2.5f; + radius = Math.Min (size.Width, size.Height) / 2.5f; } // return the overall content size for the collection view @@ -55,22 +53,22 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSInde { UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell (path); attributes.Size = ItemSize; - attributes.Center = new CGPoint (center.X + radius * (float)Math.Cos (2 * path.Row * Math.PI / count), - center.Y + radius * (float)Math.Sin (2 * path.Row * Math.PI / count)); + attributes.Center = new CGPoint (center.X + radius * (float) Math.Cos (2 * path.Row * Math.PI / count), + center.Y + radius * (float) Math.Sin (2 * path.Row * Math.PI / count)); attributes.Transform3D = CATransform3D.MakeScale (0.5f, 0.5f, 1.0f); return attributes; } // return layout attributes for all the items in a given rectangle - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { - UICollectionViewLayoutAttributes[] attributes = new UICollectionViewLayoutAttributes [count]; - + UICollectionViewLayoutAttributes [] attributes = new UICollectionViewLayoutAttributes [count]; + for (int i = 0; i < count; i++) { NSIndexPath indexPath = NSIndexPath.FromItemSection (i, 0); attributes [i] = LayoutAttributesForItem (indexPath); } - + return attributes; } } diff --git a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/ImagesCollectionViewController.cs b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/ImagesCollectionViewController.cs index 5cea720d1..766edf643 100644 --- a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/ImagesCollectionViewController.cs +++ b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/ImagesCollectionViewController.cs @@ -6,10 +6,8 @@ using System.Threading; using MonoTouch.Dialog.Utilities; -namespace LayoutWithNavController -{ - public class ImagesCollectionViewController : UICollectionViewController - { +namespace LayoutWithNavController { + public class ImagesCollectionViewController : UICollectionViewController { static readonly NSString cellId = new NSString ("ImageCell"); // for use with UseLayoutToLayoutNavigationTransitions @@ -31,9 +29,9 @@ public ImagesCollectionViewController (UICollectionViewLayout layout) : base (la public override void ViewDidLoad () { base.ViewDidLoad (); - + // register the ImageCell so it can be created from a DequeueReusableCell call - CollectionView.RegisterClassForCell (typeof(ImageCell), cellId); + CollectionView.RegisterClassForCell (typeof (ImageCell), cellId); } public override nint GetItemsCount (UICollectionView collectionView, nint section) @@ -44,11 +42,11 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { // get an ImageCell from the pool. DequeueReusableCell will create one if necessary - ImageCell imageCell = (ImageCell)collectionView.DequeueReusableCell (cellId, indexPath); + ImageCell imageCell = (ImageCell) collectionView.DequeueReusableCell (cellId, indexPath); // update the image for the speaker imageCell.UpdateImage (monkeys [indexPath.Row].ImageFile); - + return imageCell; } @@ -68,15 +66,14 @@ public override void ItemSelected (UICollectionView collectionView, NSIndexPath NavigationController.PushViewController (controller2, true); } // class to use for cell - class ImageCell : UICollectionViewCell - { + class ImageCell : UICollectionViewCell { UIImageView imageView; [Export ("initWithFrame:")] ImageCell (CGRect frame) : base (frame) { // create an image view to use in the cell - imageView = new UIImageView (new CGRect (0, 0, 100, 100)); + imageView = new UIImageView (new CGRect (0, 0, 100, 100)); imageView.ContentMode = UIViewContentMode.ScaleAspectFit; // populate the content view diff --git a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Main.cs b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Main.cs index 3ce9cb75b..7c030efdf 100644 --- a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Main.cs +++ b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace LayoutWithNavController -{ - public class Application - { +namespace LayoutWithNavController { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Monkeys.cs b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Monkeys.cs index 480be6576..b610384d6 100644 --- a/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Monkeys.cs +++ b/IntroToiOS7/TransitionDemos/NavigationControllerTransitions/LayoutWithNavController/Monkeys.cs @@ -5,11 +5,9 @@ using System.Text.RegularExpressions; using Foundation; -namespace LayoutWithNavController -{ +namespace LayoutWithNavController { // Loads a collection of monkeys containing file paths of monkey images - public class Monkeys : List - { + public class Monkeys : List { static readonly Monkeys monkeys = new Monkeys (); Monkeys () @@ -18,20 +16,19 @@ public class Monkeys : List string path = Path.Combine (NSBundle.MainBundle.BundlePath, "Images"); Directory.GetFiles (path).Where (f => pattern.IsMatch (f)).ToList ().ForEach (p => { - Monkey s = new Monkey{ImageFile = "Images/" + Path.GetFileName(p)}; + Monkey s = new Monkey { ImageFile = "Images/" + Path.GetFileName (p) }; this.Add (s); }); } public static Monkeys Instance { - get{ + get { return monkeys; } } - public class Monkey - { + public class Monkey { public string ImageFile { get; set; } } } -} \ No newline at end of file +} diff --git a/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/AppDelegate.cs b/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/AppDelegate.cs index 776f30d5e..689c86430 100644 --- a/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/AppDelegate.cs +++ b/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace UIKitDynamicsDemo -{ +namespace UIKitDynamicsDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; UIKitDynamicsDemoViewController viewController; @@ -25,11 +23,11 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - + viewController = new UIKitDynamicsDemoViewController (); window.RootViewController = viewController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/Main.cs b/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/Main.cs index 9660e7fb0..fc27ca0d0 100644 --- a/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/Main.cs +++ b/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace UIKitDynamicsDemo -{ - public class Application - { +namespace UIKitDynamicsDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/UIKitDynamicsDemoViewController.cs b/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/UIKitDynamicsDemoViewController.cs index e59c6da04..04e78f0a5 100644 --- a/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/UIKitDynamicsDemoViewController.cs +++ b/IntroToiOS7/UIKitDynamicsDemo/UIKitDynamicsDemo/UIKitDynamicsDemoViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace UIKitDynamicsDemo -{ - public partial class UIKitDynamicsDemoViewController : UIViewController - { +namespace UIKitDynamicsDemo { + public partial class UIKitDynamicsDemoViewController : UIViewController { UIImageView imageView; UIImage image; UIDynamicAnimator dynAnimator; @@ -19,11 +17,11 @@ public UIKitDynamicsDemoViewController () public override void ViewDidLoad () { base.ViewDidLoad (); - + using (image = UIImage.FromFile ("monkeys.jpg")) { imageView = new UIImageView (new CGRect (new CGPoint (View.Center.X - image.Size.Width / 2, 0), image.Size)) { - Image = image + Image = image }; View.AddSubview (imageView); @@ -32,7 +30,7 @@ public override void ViewDidLoad () dynAnimator = new UIDynamicAnimator (this.View); // 2. create behavior(s) - var dynItems = new IUIDynamicItem[] { imageView }; + var dynItems = new IUIDynamicItem [] { imageView }; var gravity = new UIGravityBehavior (dynItems); var collision = new UICollisionBehavior (dynItems) { TranslatesReferenceBoundsIntoBoundary = true @@ -48,4 +46,4 @@ public override void ViewDidLoad () } } } -} \ No newline at end of file +} diff --git a/IntroToiOS7/ViewAnimations/ViewAnimations/AppDelegate.cs b/IntroToiOS7/ViewAnimations/ViewAnimations/AppDelegate.cs index cccfe01b4..1f597e5af 100644 --- a/IntroToiOS7/ViewAnimations/ViewAnimations/AppDelegate.cs +++ b/IntroToiOS7/ViewAnimations/ViewAnimations/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace ViewAnimations -{ +namespace ViewAnimations { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; ViewAnimationsViewController viewController; @@ -25,11 +23,11 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - + viewController = new ViewAnimationsViewController (); window.RootViewController = viewController; window.MakeKeyAndVisible (); - + return true; } } diff --git a/IntroToiOS7/ViewAnimations/ViewAnimations/Main.cs b/IntroToiOS7/ViewAnimations/ViewAnimations/Main.cs index 9d8772ab3..ac7a858ed 100644 --- a/IntroToiOS7/ViewAnimations/ViewAnimations/Main.cs +++ b/IntroToiOS7/ViewAnimations/ViewAnimations/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace ViewAnimations -{ - public class Application - { +namespace ViewAnimations { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/IntroToiOS7/ViewAnimations/ViewAnimations/ViewAnimationsViewController.cs b/IntroToiOS7/ViewAnimations/ViewAnimations/ViewAnimationsViewController.cs index 4d80f53e4..613b1e6c4 100644 --- a/IntroToiOS7/ViewAnimations/ViewAnimations/ViewAnimationsViewController.cs +++ b/IntroToiOS7/ViewAnimations/ViewAnimations/ViewAnimationsViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace ViewAnimations -{ - public partial class ViewAnimationsViewController : UIViewController - { +namespace ViewAnimations { + public partial class ViewAnimationsViewController : UIViewController { UIImageView imageView; UIImage image; @@ -21,7 +19,7 @@ public override void ViewDidLoad () image = UIImage.FromFile ("monkeys.jpg"); imageView = new UIImageView (new CGRect (new CGPoint (0, 0), image.Size)) { - Image = image + Image = image }; View.AddSubview (imageView); @@ -37,12 +35,12 @@ void AnimateViewWithKeyframes () // can now use keyframes directly on UIView without needing to drop directly into Core Animation UIView.AnimateKeyframes (2.0, 0, UIViewKeyframeAnimationOptions.Autoreverse, () => { - UIView.AddKeyframeWithRelativeStartTime (0.0, 0.5, () => { + UIView.AddKeyframeWithRelativeStartTime (0.0, 0.5, () => { imageView.Center = new CGPoint (200, 200); }); - UIView.AddKeyframeWithRelativeStartTime (0.5, 0.5, () => { - imageView.Transform = CGAffineTransform.MakeRotation ((float)Math.PI / 2); + UIView.AddKeyframeWithRelativeStartTime (0.5, 0.5, () => { + imageView.Transform = CGAffineTransform.MakeRotation ((float) Math.PI / 2); }); }, (finished) => { imageView.Center = initialCeneter; @@ -53,14 +51,14 @@ void AnimateViewWithKeyframes () } void AnimateWithSpring () - { + { float springDampingRatio = 0.25f; float initialSpringVelocity = 1.0f; UIView.AnimateNotify (3.0, 0.0, springDampingRatio, initialSpringVelocity, 0, () => { - imageView.Center = new CGPoint (imageView.Center.X, 400); - + imageView.Center = new CGPoint (imageView.Center.X, 400); + }, null); } } diff --git a/IntroductionToiCloud/iCloudKeyValue/AppDelegate.cs b/IntroductionToiCloud/iCloudKeyValue/AppDelegate.cs index b46aaec70..76376c26f 100644 --- a/IntroductionToiCloud/iCloudKeyValue/AppDelegate.cs +++ b/IntroductionToiCloud/iCloudKeyValue/AppDelegate.cs @@ -22,4 +22,4 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } } -} \ No newline at end of file +} diff --git a/IntroductionToiCloud/iCloudKeyValue/KeyValueViewController.cs b/IntroductionToiCloud/iCloudKeyValue/KeyValueViewController.cs index 966a0617e..ef2baa794 100644 --- a/IntroductionToiCloud/iCloudKeyValue/KeyValueViewController.cs +++ b/IntroductionToiCloud/iCloudKeyValue/KeyValueViewController.cs @@ -14,13 +14,13 @@ public class KeyValueViewController : UIViewController { UIButton saveButton, reloadButton, clearButton; UITextView localText, testText, outputText; UILabel localLabel, testLabel, keyLabel, valueLabel; - + const string sharedKeyName = "Shared"; public override void ViewDidLoad () - { + { base.ViewDidLoad (); - + #region UI Layout // Create the buttons and TextView to run the sample code saveButton = UIButton.FromType (UIButtonType.RoundedRect); @@ -30,11 +30,11 @@ public override void ViewDidLoad () reloadButton = UIButton.FromType (UIButtonType.RoundedRect); reloadButton.Frame = new CGRect (110.0, 120.0, 90.0, 50.0); reloadButton.SetTitle ("Reload", UIControlState.Normal); - + clearButton = UIButton.FromType (UIButtonType.RoundedRect); clearButton.Frame = new CGRect (210.0, 120.0, 90.0, 50.0); clearButton.SetTitle ("Clear", UIControlState.Normal); - + outputText = new UITextView (new CGRect (10.0, 180.0, 300.0, 270.0)) { Editable = false, ScrollEnabled = true @@ -77,15 +77,15 @@ public override void ViewDidLoad () Add (keyLabel); Add (valueLabel); #endregion - + // Wire up the buttons to the SamplCode class methods saveButton.TouchUpInside += Save; reloadButton.TouchUpInside += Reload; - + clearButton.TouchUpInside += Clear; } - + // saves the inputs to iCloud keys void Save (object sender, EventArgs ea) { @@ -103,8 +103,8 @@ void Save (object sender, EventArgs ea) void Reload (object sender, EventArgs ea) { var store = NSUbiquitousKeyValueStore.DefaultStore; - var synchronized = store.Synchronize (); - + var synchronized = store.Synchronize (); + testText.Text = store.GetString (sharedKeyName); localText.Text = store.GetString (UIDevice.CurrentDevice.Name); @@ -127,45 +127,45 @@ void Clear (object sender, EventArgs e) localText.ResignFirstResponder (); testText.ResignFirstResponder (); } - + // notification when Key-Value changes are triggered by server NSObject keyValueNotification; - + // register for the notification when iCloud keys are changed public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); - + Reload (null, null); - keyValueNotification = + keyValueNotification = NSNotificationCenter.DefaultCenter.AddObserver ( NSUbiquitousKeyValueStore.DidChangeExternallyNotification, notification => { - Console.WriteLine ("Cloud notification received"); - NSDictionary userInfo = notification.UserInfo; - - var reasonNumber = (NSNumber)userInfo.ObjectForKey (NSUbiquitousKeyValueStore.ChangeReasonKey); - nint reason = reasonNumber.NIntValue; - - var changedKeys = (NSArray)userInfo.ObjectForKey (NSUbiquitousKeyValueStore.ChangedKeysKey); - var changedKeysList = new List (); - for (uint i = 0; i < changedKeys.Count; i++) { - var key = changedKeys.GetItem (i); // resolve key to a string - changedKeysList.Add (key); - } - - var store = NSUbiquitousKeyValueStore.DefaultStore; - store.Synchronize (); - // now do something with the list... - InvokeOnMainThread (() => { - outputText.Text += "\n--- Cloud Notification \uE049\uE049\uE049 ---"; - foreach (var k in changedKeysList) - outputText.Text += String.Format ("\n{0}: {1}", k, store.GetString (k)); - - testText.Text = store.GetString (sharedKeyName); - localText.Text = store.GetString (UIDevice.CurrentDevice.Name); + Console.WriteLine ("Cloud notification received"); + NSDictionary userInfo = notification.UserInfo; + + var reasonNumber = (NSNumber) userInfo.ObjectForKey (NSUbiquitousKeyValueStore.ChangeReasonKey); + nint reason = reasonNumber.NIntValue; + + var changedKeys = (NSArray) userInfo.ObjectForKey (NSUbiquitousKeyValueStore.ChangedKeysKey); + var changedKeysList = new List (); + for (uint i = 0; i < changedKeys.Count; i++) { + var key = changedKeys.GetItem (i); // resolve key to a string + changedKeysList.Add (key); + } + + var store = NSUbiquitousKeyValueStore.DefaultStore; + store.Synchronize (); + // now do something with the list... + InvokeOnMainThread (() => { + outputText.Text += "\n--- Cloud Notification \uE049\uE049\uE049 ---"; + foreach (var k in changedKeysList) + outputText.Text += String.Format ("\n{0}: {1}", k, store.GetString (k)); + + testText.Text = store.GetString (sharedKeyName); + localText.Text = store.GetString (UIDevice.CurrentDevice.Name); + }); }); - }); } // remove notification observer @@ -176,4 +176,4 @@ public override void ViewWillDisappear (bool animated) NSNotificationCenter.DefaultCenter.RemoveObserver (keyValueNotification); } } -} \ No newline at end of file +} diff --git a/IntroductionToiCloud/iCloudKeyValue/Main.cs b/IntroductionToiCloud/iCloudKeyValue/Main.cs index bf42028db..46d7e44d0 100644 --- a/IntroductionToiCloud/iCloudKeyValue/Main.cs +++ b/IntroductionToiCloud/iCloudKeyValue/Main.cs @@ -2,7 +2,7 @@ namespace Cloud { public class Application { - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/IntroductionToiCloud/iCloudUIDoc/AppDelegate.cs b/IntroductionToiCloud/iCloudUIDoc/AppDelegate.cs index 083855ef0..3293f5731 100644 --- a/IntroductionToiCloud/iCloudUIDoc/AppDelegate.cs +++ b/IntroductionToiCloud/iCloudUIDoc/AppDelegate.cs @@ -76,7 +76,7 @@ void FindDocument () SearchScopes = new NSObject [] { NSMetadataQuery.UbiquitousDocumentsScope } }; - var pred = NSPredicate.FromFormat ("%K == %@", new NSObject[] { + var pred = NSPredicate.FromFormat ("%K == %@", new NSObject [] { NSMetadataQuery.ItemFSNameKey, new NSString (MonkeyDocFilename) }); @@ -89,7 +89,7 @@ void FindDocument () NSMetadataQuery.DidFinishGatheringNotification, query ); - + query.StartQuery (); } @@ -97,7 +97,7 @@ void FindDocument () void DidFinishGathering (NSNotification notification) { Console.WriteLine ("DidFinishGathering"); - var metadataQuery = (NSMetadataQuery)notification.Object; + var metadataQuery = (NSMetadataQuery) notification.Object; metadataQuery.DisableUpdates (); metadataQuery.StopQuery (); @@ -107,13 +107,13 @@ void DidFinishGathering (NSNotification notification) void LoadDocument (NSMetadataQuery metadataQuery) { - Console.WriteLine ("LoadDocument"); + Console.WriteLine ("LoadDocument"); if (metadataQuery.ResultCount == 1) { - var item = (NSMetadataItem)metadataQuery.ResultAtIndex (0); - var url = (NSUrl)item.ValueForAttribute (NSMetadataQuery.ItemURLKey); + var item = (NSMetadataItem) metadataQuery.ResultAtIndex (0); + var url = (NSUrl) item.ValueForAttribute (NSMetadataQuery.ItemURLKey); doc = new MonkeyDocument (url); - + doc.Open (success => { if (success) { Console.WriteLine ("iCloud document opened"); @@ -141,15 +141,15 @@ void LoadDocument (NSMetadataQuery metadataQuery) Console.WriteLine ("Save completion:" + saveSuccess); if (saveSuccess) { monkeyDoc.Open (openSuccess => { - Console.WriteLine ("Open completion:" + openSuccess); - if (openSuccess) { - Console.WriteLine ("new document for iCloud"); - Console.WriteLine (" == " + monkeyDoc.DocumentString); - viewController.DisplayDocument (monkeyDoc); - } else { - Console.WriteLine ("couldn't open"); - } - }); + Console.WriteLine ("Open completion:" + openSuccess); + if (openSuccess) { + Console.WriteLine ("new document for iCloud"); + Console.WriteLine (" == " + monkeyDoc.DocumentString); + viewController.DisplayDocument (monkeyDoc); + } else { + Console.WriteLine ("couldn't open"); + } + }); } else { Console.WriteLine ("couldn't save"); } diff --git a/IntroductionToiCloud/iCloudUIDoc/Main.cs b/IntroductionToiCloud/iCloudUIDoc/Main.cs index 6215579c1..4e1d3f8e3 100644 --- a/IntroductionToiCloud/iCloudUIDoc/Main.cs +++ b/IntroductionToiCloud/iCloudUIDoc/Main.cs @@ -3,7 +3,7 @@ namespace Cloud { public class Application { - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/IntroductionToiCloud/iCloudUIDoc/MonkeyDocument.cs b/IntroductionToiCloud/iCloudUIDoc/MonkeyDocument.cs index d91d75294..214f7a4a3 100644 --- a/IntroductionToiCloud/iCloudUIDoc/MonkeyDocument.cs +++ b/IntroductionToiCloud/iCloudUIDoc/MonkeyDocument.cs @@ -34,7 +34,7 @@ public override bool LoadFromContents (NSObject contents, string typeName, out N Console.WriteLine ("LoadFromContents({0})", typeName); if (contents != null) - dataModel = NSString.FromData ((NSData)contents, NSStringEncoding.UTF8); + dataModel = NSString.FromData ((NSData) contents, NSStringEncoding.UTF8); // LoadFromContents called when an update occurs NSNotificationCenter.DefaultCenter.PostNotificationName ("monkeyDocumentModified", this); @@ -47,10 +47,10 @@ public override NSObject ContentsForType (string typeName, out NSError outError) outError = null; Console.WriteLine ("ContentsForType({0})", typeName); - Console.WriteLine ("DocumentText:{0}",dataModel); + Console.WriteLine ("DocumentText:{0}", dataModel); NSData docData = dataModel.Encode (NSStringEncoding.UTF8); return docData; } } -} \ No newline at end of file +} diff --git a/IntroductionToiCloud/iCloudUIDoc/MonkeyDocumentViewController.cs b/IntroductionToiCloud/iCloudUIDoc/MonkeyDocumentViewController.cs index e555804e2..46f74acb7 100644 --- a/IntroductionToiCloud/iCloudUIDoc/MonkeyDocumentViewController.cs +++ b/IntroductionToiCloud/iCloudUIDoc/MonkeyDocumentViewController.cs @@ -13,7 +13,7 @@ public class MonkeyDocumentViewController : UIViewController { UITextView docText, alertText; public override void ViewDidLoad () - { + { base.ViewDidLoad (); #region UI controls, you could do this in a XIB if you wanted @@ -21,7 +21,7 @@ public override void ViewDidLoad () saveButton.Frame = new CGRect (10.0, 10.0, 160.0, 50.0); saveButton.SetTitle ("UpdateChangeCount", UIControlState.Normal); saveButton.Enabled = false; - + alertText = new UITextView (new CGRect (175.0, 10.0, 140.0, 50.0)) { TextColor = UIColor.Red, Editable = false @@ -32,7 +32,7 @@ public override void ViewDidLoad () ScrollEnabled = true, BackgroundColor = UIColor.FromRGB (224, 255, 255) }; - + // Add the controls to the view Add (saveButton); Add (docText); @@ -47,7 +47,7 @@ public override void ViewDidLoad () doc.UpdateChangeCount (UIDocumentChangeKind.Done); docText.ResignFirstResponder (); }; - + // listen for notifications that the document was modified via the server NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("dataReloaded:"), @@ -59,7 +59,7 @@ public override void ViewDidLoad () [Export ("dataReloaded:")] void DataReloaded (NSNotification notification) { - doc = (MonkeyDocument)notification.Object; + doc = (MonkeyDocument) notification.Object; alertText.Text = string.Format ("{0} dataReloaded: notification", DateTime.Now.ToString ("H:mm:ss")); // we just overwrite whatever was being typed, no conflict resolution for now docText.Text = doc.DocumentString; @@ -73,4 +73,4 @@ public void DisplayDocument (MonkeyDocument monkeyDoc) saveButton.Enabled = true; } } -} \ No newline at end of file +} diff --git a/KeyValueObserving/AppDelegate.cs b/KeyValueObserving/AppDelegate.cs index 487855f5e..90488da19 100644 --- a/KeyValueObserving/AppDelegate.cs +++ b/KeyValueObserving/AppDelegate.cs @@ -7,11 +7,9 @@ using Foundation; using UIKit; -namespace kvo -{ +namespace kvo { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UINavigationController topController; UIWindow window; UILabel label; @@ -45,9 +43,9 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // the "ObserveValue" method. // topController.View.Layer.AddObserver (observer: this, - keyPath: new NSString ("bounds"), - options: NSKeyValueObservingOptions.New, - context: IntPtr.Zero); + keyPath: new NSString ("bounds"), + options: NSKeyValueObservingOptions.New, + context: IntPtr.Zero); return true; } @@ -71,7 +69,7 @@ CGRect ComputeLabelRect () return rect; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Keychain/Main.cs b/Keychain/Main.cs index 2e84d7ee9..3def32a6c 100644 --- a/Keychain/Main.cs +++ b/Keychain/Main.cs @@ -5,7 +5,8 @@ namespace Keychain { public class Application { - static void Main (string[] args) { + static void Main (string [] args) + { UIApplication.Main (args); } } @@ -17,9 +18,11 @@ public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { - ThreadPool.QueueUserWorkItem (delegate { - window.BeginInvokeOnMainThread (delegate { - var rec = new SecRecord (SecKind.GenericPassword){ + ThreadPool.QueueUserWorkItem (delegate + { + window.BeginInvokeOnMainThread (delegate + { + var rec = new SecRecord (SecKind.GenericPassword) { Generic = NSData.FromString ("foo") }; @@ -54,7 +57,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } - static void DisplayMessage (AppDelegate instance, string message, params object[] format) + static void DisplayMessage (AppDelegate instance, string message, params object [] format) { new UIAlertView ("Keychain", string.Format (message, format), null, "OK", null).Show (); } diff --git a/LazyTableImages/AppDelegate.cs b/LazyTableImages/AppDelegate.cs index 9c2b9a8b8..06fb55e85 100644 --- a/LazyTableImages/AppDelegate.cs +++ b/LazyTableImages/AppDelegate.cs @@ -32,98 +32,89 @@ using System.Net; using System.Collections.ObjectModel; -namespace LazyTableImages -{ - /// - /// The UIApplicationDelegate for the application. This class is responsible for launching the - /// User Interface of the application, as well as listening (and optionally responding) to - /// application events from iOS. - /// - - [Register("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - - /// - /// Choose a feed from https://rss.itunes.apple.com/ - /// - static readonly Uri RssFeedUrl = new Uri("https://rss.itunes.apple.com/api/v1/us/ios-apps/top-free/all/50/non-explicit.atom"); - - - UINavigationController NavigationController { get; set; } - - RootViewController RootController { get; set; } - - public override UIWindow Window { get; set; } - - /// - /// This method is invoked when the application has loaded and is ready to run. In this - /// method you should instantiate the window, load the UI into it and then make the window - /// visible. - /// - /// - /// You have 5 seconds to return from this method, or iOS will terminate your application. - /// - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - Window = new UIWindow(UIScreen.MainScreen.Bounds); - RootController = new RootViewController("RootViewController", null); - NavigationController = new UINavigationController(RootController); - Window.RootViewController = NavigationController; - - // make the window visible - Window.MakeKeyAndVisible(); - - BeginDownloading(); - return true; - } - - void BeginDownloading() - { - // Show the user that data is about to be downloaded - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - - // Retrieve the rss feed from the server - var downloader = new GzipWebClient(); - downloader.DownloadStringCompleted += DownloadCompleted; - downloader.DownloadStringAsync(RssFeedUrl); - } - - void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e) - { - // The WebClient will invoke the DownloadStringCompleted event on a - // background thread. We want to do UI updates with the result, so process - // the result on the main thread. - UIApplication.SharedApplication.BeginInvokeOnMainThread(() => - { - // First disable the download indicator - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - - // Now handle the result from the WebClient - if (e.Error != null) - { - DisplayError("Warning", "The rss feed could not be downloaded: " + e.Error.Message); - } - else - { - try - { - RootController.Apps.Clear(); - foreach (var v in RssParser.Parse(e.Result)) - RootController.Apps.Add(v); - } - catch - { - DisplayError("Warning", "Malformed Xml was found in the Rss Feed."); - } - } - }); - } - - void DisplayError(string title, string errorMessage, params object[] formatting) - { - var alert = new UIAlertView(title, string.Format(errorMessage, formatting), null, "ok", null); - alert.Show(); - } - } +namespace LazyTableImages { + /// + /// The UIApplicationDelegate for the application. This class is responsible for launching the + /// User Interface of the application, as well as listening (and optionally responding) to + /// application events from iOS. + /// + + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + + /// + /// Choose a feed from https://rss.itunes.apple.com/ + /// + static readonly Uri RssFeedUrl = new Uri ("https://rss.itunes.apple.com/api/v1/us/ios-apps/top-free/all/50/non-explicit.atom"); + + + UINavigationController NavigationController { get; set; } + + RootViewController RootController { get; set; } + + public override UIWindow Window { get; set; } + + /// + /// This method is invoked when the application has loaded and is ready to run. In this + /// method you should instantiate the window, load the UI into it and then make the window + /// visible. + /// + /// + /// You have 5 seconds to return from this method, or iOS will terminate your application. + /// + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + Window = new UIWindow (UIScreen.MainScreen.Bounds); + RootController = new RootViewController ("RootViewController", null); + NavigationController = new UINavigationController (RootController); + Window.RootViewController = NavigationController; + + // make the window visible + Window.MakeKeyAndVisible (); + + BeginDownloading (); + return true; + } + + void BeginDownloading () + { + // Show the user that data is about to be downloaded + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; + + // Retrieve the rss feed from the server + var downloader = new GzipWebClient (); + downloader.DownloadStringCompleted += DownloadCompleted; + downloader.DownloadStringAsync (RssFeedUrl); + } + + void DownloadCompleted (object sender, DownloadStringCompletedEventArgs e) + { + // The WebClient will invoke the DownloadStringCompleted event on a + // background thread. We want to do UI updates with the result, so process + // the result on the main thread. + UIApplication.SharedApplication.BeginInvokeOnMainThread (() => { + // First disable the download indicator + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + + // Now handle the result from the WebClient + if (e.Error != null) { + DisplayError ("Warning", "The rss feed could not be downloaded: " + e.Error.Message); + } else { + try { + RootController.Apps.Clear (); + foreach (var v in RssParser.Parse (e.Result)) + RootController.Apps.Add (v); + } catch { + DisplayError ("Warning", "Malformed Xml was found in the Rss Feed."); + } + } + }); + } + + void DisplayError (string title, string errorMessage, params object [] formatting) + { + var alert = new UIAlertView (title, string.Format (errorMessage, formatting), null, "ok", null); + alert.Show (); + } + } } diff --git a/LazyTableImages/GzipWebClient.cs b/LazyTableImages/GzipWebClient.cs index 049decc64..92f7b0220 100644 --- a/LazyTableImages/GzipWebClient.cs +++ b/LazyTableImages/GzipWebClient.cs @@ -1,10 +1,8 @@ using System; using System.Net; -namespace LazyTableImages -{ - public class GzipWebClient : WebClient - { +namespace LazyTableImages { + public class GzipWebClient : WebClient { protected override WebRequest GetWebRequest (Uri address) { var request = base.GetWebRequest (address); diff --git a/LazyTableImages/Main.cs b/LazyTableImages/Main.cs index 5306afc5b..56ee8883d 100644 --- a/LazyTableImages/Main.cs +++ b/LazyTableImages/Main.cs @@ -10,7 +10,7 @@ public class Application { /// /// This is the main entry point of the application. /// - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/LazyTableImages/RootViewController.cs b/LazyTableImages/RootViewController.cs index 90d794d44..7a6b59280 100644 --- a/LazyTableImages/RootViewController.cs +++ b/LazyTableImages/RootViewController.cs @@ -84,7 +84,8 @@ public DataSource (RootViewController controller) PlaceholderImage = UIImage.FromFile ("Images/Placeholder.png"); // If either a download fails or the image we download is corrupt, ignore the problem. - TaskScheduler.UnobservedTaskException += delegate(object sender, UnobservedTaskExceptionEventArgs e) { + TaskScheduler.UnobservedTaskException += delegate (object sender, UnobservedTaskExceptionEventArgs e) + { e.SetObserved (); }; } @@ -150,7 +151,7 @@ void BeginDownloadingImage (App app, NSIndexPath path) { // Queue the image to be downloaded. This task will execute // as soon as the existing ones have finished. - byte[] data = null; + byte [] data = null; DownloadTask = DownloadTask.ContinueWith (prevTask => { try { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; diff --git a/LazyTableImages/RssParser.cs b/LazyTableImages/RssParser.cs index 20985af9c..61555fd19 100644 --- a/LazyTableImages/RssParser.cs +++ b/LazyTableImages/RssParser.cs @@ -29,51 +29,48 @@ using System.Xml.Linq; using System.Collections.Generic; -namespace LazyTableImages -{ +namespace LazyTableImages { - public static class RssParser - { + public static class RssParser { - // These are used to select the correct nodes and attributes from the Rss feed - static readonly XName FeedElement = XName.Get("feed", "http://www.w3.org/2005/Atom"); - static readonly XName EntryElement = XName.Get("entry", "http://www.w3.org/2005/Atom"); - static readonly XName AppUrlElement = XName.Get("id", "http://www.w3.org/2005/Atom"); + // These are used to select the correct nodes and attributes from the Rss feed + static readonly XName FeedElement = XName.Get ("feed", "http://www.w3.org/2005/Atom"); + static readonly XName EntryElement = XName.Get ("entry", "http://www.w3.org/2005/Atom"); + static readonly XName AppUrlElement = XName.Get ("id", "http://www.w3.org/2005/Atom"); - static readonly XName AppNameElement = XName.Get("name", "https://rss.itunes.apple.com"); - static readonly XName ArtistElement = XName.Get("artist", "https://rss.itunes.apple.com"); - static readonly XName ImageUrlElement = XName.Get("image", "https://rss.itunes.apple.com"); + static readonly XName AppNameElement = XName.Get ("name", "https://rss.itunes.apple.com"); + static readonly XName ArtistElement = XName.Get ("artist", "https://rss.itunes.apple.com"); + static readonly XName ImageUrlElement = XName.Get ("image", "https://rss.itunes.apple.com"); - static readonly XName HeightAttribute = XName.Get("height", ""); + static readonly XName HeightAttribute = XName.Get ("height", ""); - public static List Parse(string xml) - { - // Open the xml - var doc = XDocument.Parse(xml); + public static List Parse (string xml) + { + // Open the xml + var doc = XDocument.Parse (xml); - // We want to convert all the raw Xml nodes called 'entry' which - // are in that namespace into instances of the 'App' class so they - // can be displayed easily in the table. - return doc.Element(FeedElement) // Select the 'feed' node. - .Elements(EntryElement) // Select all children with the name 'entry'. - .Select(XmlElementToApp) // Convert the 'entry' nodes to instances of the App class. - .ToList(); // Return as a List. - } + // We want to convert all the raw Xml nodes called 'entry' which + // are in that namespace into instances of the 'App' class so they + // can be displayed easily in the table. + return doc.Element (FeedElement) // Select the 'feed' node. + .Elements (EntryElement) // Select all children with the name 'entry'. + .Select (XmlElementToApp) // Convert the 'entry' nodes to instances of the App class. + .ToList (); // Return as a List. + } - static App XmlElementToApp(XElement entry) - { - // Select an image node - var imageUrlNode = entry.Elements(ImageUrlElement).FirstOrDefault(); + static App XmlElementToApp (XElement entry) + { + // Select an image node + var imageUrlNode = entry.Elements (ImageUrlElement).FirstOrDefault (); - // Parse the rest of the apps information from the XElement and - // return the App instance. - return new App - { - Name = entry.Element(AppNameElement).Value, - Url = new Uri(entry.Element(AppUrlElement).Value), - Artist = entry.Element(ArtistElement).Value, - ImageUrl = new Uri(imageUrlNode.Value) - }; - } - } + // Parse the rest of the apps information from the XElement and + // return the App instance. + return new App { + Name = entry.Element (AppNameElement).Value, + Url = new Uri (entry.Element (AppUrlElement).Value), + Artist = entry.Element (ArtistElement).Value, + ImageUrl = new Uri (imageUrlNode.Value) + }; + } + } } diff --git a/LazyTableImagesAsync/AppDelegate.cs b/LazyTableImagesAsync/AppDelegate.cs index a322024ae..ce44274ac 100644 --- a/LazyTableImagesAsync/AppDelegate.cs +++ b/LazyTableImagesAsync/AppDelegate.cs @@ -32,97 +32,88 @@ using System.Net; using System.Collections.ObjectModel; -namespace LazyTableImages -{ - /// - /// The UIApplicationDelegate for the application. This class is responsible for launching the - /// User Interface of the application, as well as listening (and optionally responding) to - /// application events from iOS. - /// +namespace LazyTableImages { + /// + /// The UIApplicationDelegate for the application. This class is responsible for launching the + /// User Interface of the application, as well as listening (and optionally responding) to + /// application events from iOS. + /// - [Register("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { - /// - /// Choose a feed from https://rss.itunes.apple.com/ - /// - static readonly Uri RssFeedUrl = new Uri("https://rss.itunes.apple.com/api/v1/us/ios-apps/top-free/all/50/non-explicit.atom"); + /// + /// Choose a feed from https://rss.itunes.apple.com/ + /// + static readonly Uri RssFeedUrl = new Uri ("https://rss.itunes.apple.com/api/v1/us/ios-apps/top-free/all/50/non-explicit.atom"); - UINavigationController NavigationController { get; set; } + UINavigationController NavigationController { get; set; } - RootViewController RootController { get; set; } + RootViewController RootController { get; set; } - public override UIWindow Window { get; set; } + public override UIWindow Window { get; set; } - /// - /// This method is invoked when the application has loaded and is ready to run. In this - /// method you should instantiate the window, load the UI into it and then make the window - /// visible. - /// - /// - /// You have 5 seconds to return from this method, or iOS will terminate your application. - /// - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - Window = new UIWindow(UIScreen.MainScreen.Bounds); - RootController = new RootViewController("RootViewController", null); - NavigationController = new UINavigationController(RootController); - Window.RootViewController = NavigationController; + /// + /// This method is invoked when the application has loaded and is ready to run. In this + /// method you should instantiate the window, load the UI into it and then make the window + /// visible. + /// + /// + /// You have 5 seconds to return from this method, or iOS will terminate your application. + /// + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + Window = new UIWindow (UIScreen.MainScreen.Bounds); + RootController = new RootViewController ("RootViewController", null); + NavigationController = new UINavigationController (RootController); + Window.RootViewController = NavigationController; - // make the window visible - Window.MakeKeyAndVisible(); + // make the window visible + Window.MakeKeyAndVisible (); - BeginDownloading(); - return true; - } + BeginDownloading (); + return true; + } - void BeginDownloading() - { - // Show the user that data is about to be downloaded - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; + void BeginDownloading () + { + // Show the user that data is about to be downloaded + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - // Retrieve the rss feed from the server - var downloader = new GzipWebClient(); - downloader.DownloadStringCompleted += DownloadCompleted; - downloader.DownloadStringAsync(RssFeedUrl); - } + // Retrieve the rss feed from the server + var downloader = new GzipWebClient (); + downloader.DownloadStringCompleted += DownloadCompleted; + downloader.DownloadStringAsync (RssFeedUrl); + } - void DownloadCompleted(object sender, DownloadStringCompletedEventArgs e) - { - // The WebClient will invoke the DownloadStringCompleted event on a - // background thread. We want to do UI updates with the result, so process - // the result on the main thread. - UIApplication.SharedApplication.BeginInvokeOnMainThread(() => - { - // First disable the download indicator - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + void DownloadCompleted (object sender, DownloadStringCompletedEventArgs e) + { + // The WebClient will invoke the DownloadStringCompleted event on a + // background thread. We want to do UI updates with the result, so process + // the result on the main thread. + UIApplication.SharedApplication.BeginInvokeOnMainThread (() => { + // First disable the download indicator + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - // Now handle the result from the WebClient - if (e.Error != null) - { - DisplayError("Warning", "The rss feed could not be downloaded: " + e.Error.Message); - } - else - { - try - { - RootController.Apps.Clear(); - foreach (var v in RssParser.Parse(e.Result)) - RootController.Apps.Add(v); - } - catch - { - DisplayError("Warning", "Malformed Xml was found in the Rss Feed."); - } - } - }); - } + // Now handle the result from the WebClient + if (e.Error != null) { + DisplayError ("Warning", "The rss feed could not be downloaded: " + e.Error.Message); + } else { + try { + RootController.Apps.Clear (); + foreach (var v in RssParser.Parse (e.Result)) + RootController.Apps.Add (v); + } catch { + DisplayError ("Warning", "Malformed Xml was found in the Rss Feed."); + } + } + }); + } - void DisplayError(string title, string errorMessage, params object[] formatting) - { - var alert = new UIAlertView(title, string.Format(errorMessage, formatting), null, "ok", null); - alert.Show(); - } - } + void DisplayError (string title, string errorMessage, params object [] formatting) + { + var alert = new UIAlertView (title, string.Format (errorMessage, formatting), null, "ok", null); + alert.Show (); + } + } } diff --git a/LazyTableImagesAsync/GzipWebClient.cs b/LazyTableImagesAsync/GzipWebClient.cs index 049decc64..92f7b0220 100644 --- a/LazyTableImagesAsync/GzipWebClient.cs +++ b/LazyTableImagesAsync/GzipWebClient.cs @@ -1,10 +1,8 @@ using System; using System.Net; -namespace LazyTableImages -{ - public class GzipWebClient : WebClient - { +namespace LazyTableImages { + public class GzipWebClient : WebClient { protected override WebRequest GetWebRequest (Uri address) { var request = base.GetWebRequest (address); diff --git a/LazyTableImagesAsync/Main.cs b/LazyTableImagesAsync/Main.cs index 5306afc5b..56ee8883d 100644 --- a/LazyTableImagesAsync/Main.cs +++ b/LazyTableImagesAsync/Main.cs @@ -10,7 +10,7 @@ public class Application { /// /// This is the main entry point of the application. /// - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/LazyTableImagesAsync/RootViewController.cs b/LazyTableImagesAsync/RootViewController.cs index d59030d86..8dbf3b432 100644 --- a/LazyTableImagesAsync/RootViewController.cs +++ b/LazyTableImagesAsync/RootViewController.cs @@ -81,7 +81,8 @@ public DataSource (RootViewController controller) PlaceholderImage = UIImage.FromFile ("Images/Placeholder.png"); // If either a download fails or the image we download is corrupt, ignore the problem. - TaskScheduler.UnobservedTaskException += delegate(object sender, UnobservedTaskExceptionEventArgs e) { + TaskScheduler.UnobservedTaskException += delegate (object sender, UnobservedTaskExceptionEventArgs e) + { e.SetObserved (); }; } @@ -147,7 +148,7 @@ async void BeginDownloadingImage (App app, NSIndexPath path) { // Queue the image to be downloaded. This task will execute // as soon as the existing ones have finished. - byte[] data = null; + byte [] data = null; data = await GetImageData (app); app.Image = UIImage.LoadFromData (NSData.FromArray (data)); @@ -159,9 +160,9 @@ async void BeginDownloadingImage (App app, NSIndexPath path) }); } - async Task GetImageData(App app) + async Task GetImageData (App app) { - byte[] data = null; + byte [] data = null; try { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; using (var c = new GzipWebClient ()) diff --git a/LazyTableImagesAsync/RssParser.cs b/LazyTableImagesAsync/RssParser.cs index 55be41fe7..90d79a0ef 100644 --- a/LazyTableImagesAsync/RssParser.cs +++ b/LazyTableImagesAsync/RssParser.cs @@ -29,52 +29,49 @@ using System.Xml.Linq; using System.Collections.Generic; -namespace LazyTableImages -{ +namespace LazyTableImages { - public static class RssParser - { + public static class RssParser { - // These are used to select the correct nodes and attributes from the Rss feed - static readonly XName FeedElement = XName.Get("feed", "http://www.w3.org/2005/Atom"); - static readonly XName EntryElement = XName.Get("entry", "http://www.w3.org/2005/Atom"); - static readonly XName AppUrlElement = XName.Get("id", "http://www.w3.org/2005/Atom"); + // These are used to select the correct nodes and attributes from the Rss feed + static readonly XName FeedElement = XName.Get ("feed", "http://www.w3.org/2005/Atom"); + static readonly XName EntryElement = XName.Get ("entry", "http://www.w3.org/2005/Atom"); + static readonly XName AppUrlElement = XName.Get ("id", "http://www.w3.org/2005/Atom"); - static readonly XName AppNameElement = XName.Get("name", "https://rss.itunes.apple.com"); - static readonly XName ArtistElement = XName.Get("artist", "https://rss.itunes.apple.com"); - static readonly XName ImageUrlElement = XName.Get("image", "https://rss.itunes.apple.com"); + static readonly XName AppNameElement = XName.Get ("name", "https://rss.itunes.apple.com"); + static readonly XName ArtistElement = XName.Get ("artist", "https://rss.itunes.apple.com"); + static readonly XName ImageUrlElement = XName.Get ("image", "https://rss.itunes.apple.com"); - static readonly XName HeightAttribute = XName.Get("height", ""); + static readonly XName HeightAttribute = XName.Get ("height", ""); - public static List Parse(string xml) - { - // Open the xml - var doc = XDocument.Parse(xml); + public static List Parse (string xml) + { + // Open the xml + var doc = XDocument.Parse (xml); - // We want to convert all the raw Xml nodes called 'entry' which - // are in that namespace into instances of the 'App' class so they - // can be displayed easily in the table. - return doc.Element(FeedElement) // Select the 'feed' node. - .Elements(EntryElement) // Select all children with the name 'entry'. - .Select(XmlElementToApp) // Convert the 'entry' nodes to instances of the App class. - .ToList(); // Return as a List. - } + // We want to convert all the raw Xml nodes called 'entry' which + // are in that namespace into instances of the 'App' class so they + // can be displayed easily in the table. + return doc.Element (FeedElement) // Select the 'feed' node. + .Elements (EntryElement) // Select all children with the name 'entry'. + .Select (XmlElementToApp) // Convert the 'entry' nodes to instances of the App class. + .ToList (); // Return as a List. + } - static App XmlElementToApp(XElement entry) - { - // The document may contain many image nodes. Select the one with - // the largest resolution. - var imageUrlNode = entry.Elements(ImageUrlElement).FirstOrDefault(); + static App XmlElementToApp (XElement entry) + { + // The document may contain many image nodes. Select the one with + // the largest resolution. + var imageUrlNode = entry.Elements (ImageUrlElement).FirstOrDefault (); - // Parse the rest of the apps information from the XElement and - // return the App instance. - return new App - { - Name = entry.Element(AppNameElement).Value, - Url = new Uri(entry.Element(AppUrlElement).Value), - Artist = entry.Element(ArtistElement).Value, - ImageUrl = new Uri(imageUrlNode.Value) - }; - } - } + // Parse the rest of the apps information from the XElement and + // return the App instance. + return new App { + Name = entry.Element (AppNameElement).Value, + Url = new Uri (entry.Element (AppUrlElement).Value), + Artist = entry.Element (ArtistElement).Value, + ImageUrl = new Uri (imageUrlNode.Value) + }; + } + } } diff --git a/LifecycleDemo/LifecycleDemo/AppDelegate.cs b/LifecycleDemo/LifecycleDemo/AppDelegate.cs index f794c5b89..afbc00f4c 100644 --- a/LifecycleDemo/LifecycleDemo/AppDelegate.cs +++ b/LifecycleDemo/LifecycleDemo/AppDelegate.cs @@ -5,54 +5,52 @@ using Foundation; using UIKit; -namespace Lifecycle.iOS -{ - [Register("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { +namespace Lifecycle.iOS { + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { //Recall that AppDelegate subscribes to events from the system (subscribes to iOS events) UIWindow window; AppLifecycleViewController viewController; - - public override bool FinishedLaunching(UIApplication app, NSDictionary options) + + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { - window = new UIWindow(UIScreen.MainScreen.Bounds); - - viewController = new AppLifecycleViewController(); + window = new UIWindow (UIScreen.MainScreen.Bounds); + + viewController = new AppLifecycleViewController (); window.RootViewController = viewController; - - window.MakeKeyAndVisible(); - + + window.MakeKeyAndVisible (); + return true; } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { - Console.WriteLine("OnActivated called, App is active."); + Console.WriteLine ("OnActivated called, App is active."); } - - public override void WillEnterForeground(UIApplication application) + + public override void WillEnterForeground (UIApplication application) { - Console.WriteLine("App will enter foreground"); + Console.WriteLine ("App will enter foreground"); } - - public override void OnResignActivation(UIApplication application) + + public override void OnResignActivation (UIApplication application) { - Console.WriteLine("OnResignActivation called, App moving to inactive state."); + Console.WriteLine ("OnResignActivation called, App moving to inactive state."); } - - public override void DidEnterBackground(UIApplication application) + + public override void DidEnterBackground (UIApplication application) { - Console.WriteLine("App entering background state."); + Console.WriteLine ("App entering background state."); } - + // [not guaranteed that this will run] - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { - Console.WriteLine("App is terminating."); + Console.WriteLine ("App is terminating."); } - + } } diff --git a/LifecycleDemo/LifecycleDemo/AppLifecycleViewController.cs b/LifecycleDemo/LifecycleDemo/AppLifecycleViewController.cs index 17145eb0e..9c9a409a7 100755 --- a/LifecycleDemo/LifecycleDemo/AppLifecycleViewController.cs +++ b/LifecycleDemo/LifecycleDemo/AppLifecycleViewController.cs @@ -2,36 +2,34 @@ using UIKit; using CoreGraphics; -namespace Lifecycle.iOS -{ - public class AppLifecycleViewController : UIViewController - { +namespace Lifecycle.iOS { + public class AppLifecycleViewController : UIViewController { UILabel label; - nfloat labelWidth = 300; - nfloat labelHeight = 200; + nfloat labelWidth = 300; + nfloat labelHeight = 200; - public AppLifecycleViewController() - { - } + public AppLifecycleViewController () + { + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - View.Frame = UIScreen.MainScreen.Bounds; - View.BackgroundColor = UIColor.White; - View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; + View.Frame = UIScreen.MainScreen.Bounds; + View.BackgroundColor = UIColor.White; + View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; - var frame = new CGRect( - View.Frame.Width / 2 - labelWidth / 2, - View.Frame.Height / 2 - labelHeight / 2, - labelWidth, - labelHeight); + var frame = new CGRect ( + View.Frame.Width / 2 - labelWidth / 2, + View.Frame.Height / 2 - labelHeight / 2, + labelWidth, + labelHeight); - label = new UILabel(frame); + label = new UILabel (frame); label.Text = "App Lifecycle Demo"; - label.Font = UIFont.FromName("Helvetica-Bold", 50f); + label.Font = UIFont.FromName ("Helvetica-Bold", 50f); label.AdjustsFontSizeToFitWidth = true; // here we can use a notification to let us know when the app has entered the foreground @@ -42,9 +40,9 @@ public override void ViewDidLoad() }); - View.AddSubview(label); - } + View.AddSubview (label); + } - } + } } diff --git a/LifecycleDemo/LifecycleDemo/Main.cs b/LifecycleDemo/LifecycleDemo/Main.cs index 0fecfd86d..05577d8cf 100644 --- a/LifecycleDemo/LifecycleDemo/Main.cs +++ b/LifecycleDemo/LifecycleDemo/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace Lifecycle.iOS -{ - public class Application - { +namespace Lifecycle.iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/LineLayout/LineLayout/AppDelegate.cs b/LineLayout/LineLayout/AppDelegate.cs index 7d05e4a38..77418cfe6 100644 --- a/LineLayout/LineLayout/AppDelegate.cs +++ b/LineLayout/LineLayout/AppDelegate.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace LineLayout -{ +namespace LineLayout { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) @@ -19,7 +17,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/LineLayout/LineLayout/Cell.cs b/LineLayout/LineLayout/Cell.cs index b040d5243..7dd4222a6 100644 --- a/LineLayout/LineLayout/Cell.cs +++ b/LineLayout/LineLayout/Cell.cs @@ -4,17 +4,15 @@ using Foundation; using UIKit; -namespace LineLayout -{ - public partial class Cell : UICollectionViewCell - { +namespace LineLayout { + public partial class Cell : UICollectionViewCell { public UILabel Label { get; private set; } - [Export("initWithFrame:")] + [Export ("initWithFrame:")] public Cell (CGRect frame) : base (frame) { Label = new UILabel (new CGRect (CGPoint.Empty, frame.Size)) { - AutoresizingMask = UIViewAutoresizing.FlexibleHeight|UIViewAutoresizing.FlexibleWidth, + AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth, TextAlignment = UITextAlignment.Center, Font = UIFont.BoldSystemFontOfSize (50f), BackgroundColor = UIColor.UnderPageBackgroundColor, diff --git a/LineLayout/LineLayout/LineLayout.cs b/LineLayout/LineLayout/LineLayout.cs index 00ca522c1..dc2e16e2e 100644 --- a/LineLayout/LineLayout/LineLayout.cs +++ b/LineLayout/LineLayout/LineLayout.cs @@ -4,10 +4,8 @@ using CoreGraphics; using CoreAnimation; -namespace LineLayout -{ - public partial class LineLayout : UICollectionViewFlowLayout - { +namespace LineLayout { + public partial class LineLayout : UICollectionViewFlowLayout { public const float ITEM_SIZE = 200.0f; public const int ACTIVE_DISTANCE = 200; public const float ZOOM_FACTOR = 0.3f; @@ -25,14 +23,14 @@ public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) return true; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { var array = base.LayoutAttributesForElementsInRect (rect); var visibleRect = new CGRect (CollectionView.ContentOffset, CollectionView.Bounds.Size); foreach (var attributes in array) { if (attributes.Frame.IntersectsWith (rect)) { - float distance = (float)visibleRect.GetMidX () - (float)attributes.Center.X; + float distance = (float) visibleRect.GetMidX () - (float) attributes.Center.X; float normalizedDistance = distance / ACTIVE_DISTANCE; if (Math.Abs (distance) < ACTIVE_DISTANCE) { float zoom = 1 + ZOOM_FACTOR * (1 - Math.Abs (normalizedDistance)); @@ -47,11 +45,11 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn public override CGPoint TargetContentOffset (CGPoint proposedContentOffset, CGPoint scrollingVelocity) { float offSetAdjustment = float.MaxValue; - float horizontalCenter = (float)(proposedContentOffset.X + (this.CollectionView.Bounds.Size.Width / 2.0)); + float horizontalCenter = (float) (proposedContentOffset.X + (this.CollectionView.Bounds.Size.Width / 2.0)); CGRect targetRect = new CGRect (proposedContentOffset.X, 0.0f, this.CollectionView.Bounds.Size.Width, this.CollectionView.Bounds.Size.Height); var array = base.LayoutAttributesForElementsInRect (targetRect); foreach (var layoutAttributes in array) { - float itemHorizontalCenter = (float)layoutAttributes.Center.X; + float itemHorizontalCenter = (float) layoutAttributes.Center.X; if (Math.Abs (itemHorizontalCenter - horizontalCenter) < Math.Abs (offSetAdjustment)) { offSetAdjustment = itemHorizontalCenter - horizontalCenter; } diff --git a/LineLayout/LineLayout/LineLayoutViewController.cs b/LineLayout/LineLayout/LineLayoutViewController.cs index 8c010b061..ad8c62e00 100644 --- a/LineLayout/LineLayout/LineLayoutViewController.cs +++ b/LineLayout/LineLayout/LineLayoutViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace LineLayout -{ - public partial class LineLayoutViewController : UICollectionViewController - { +namespace LineLayout { + public partial class LineLayoutViewController : UICollectionViewController { static readonly NSString cellToken = new NSString ("MY_CELL"); public LineLayoutViewController (UICollectionViewFlowLayout layout) : base (layout) @@ -15,7 +13,7 @@ public LineLayoutViewController (UICollectionViewFlowLayout layout) : base (layo public override void ViewDidLoad () { - CollectionView.RegisterClassForCell (typeof(Cell), cellToken); + CollectionView.RegisterClassForCell (typeof (Cell), cellToken); } public override nint GetItemsCount (UICollectionView collectionView, nint section) diff --git a/LocalNotifications/LocalNotifications/AppDelegate.cs b/LocalNotifications/LocalNotifications/AppDelegate.cs index 5c34ec9db..836267bb2 100644 --- a/LocalNotifications/LocalNotifications/AppDelegate.cs +++ b/LocalNotifications/LocalNotifications/AppDelegate.cs @@ -1,97 +1,90 @@ -using Foundation; +using Foundation; using UIKit; -namespace LocalNotifications -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) - { - var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes( - UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null - ); - - - application.RegisterUserNotificationSettings(notificationSettings); - } - - // check for a notification - if (launchOptions != null) - { - // check for a local notification - if (launchOptions.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey)) - { - var localNotification = launchOptions[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; - if (localNotification != null) - { - UIAlertController okayAlertController = UIAlertController.Create(localNotification.AlertAction, localNotification.AlertBody, UIAlertControllerStyle.Alert); - okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - - Window.RootViewController.PresentViewController(okayAlertController, true, null); - - // reset our badge - UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; - } - } - } - return true; - } - - public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification) - { - // show an alert - UIAlertController okayAlertController = UIAlertController.Create(notification.AlertAction, notification.AlertBody, UIAlertControllerStyle.Alert); - okayAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - - Window.RootViewController.PresentViewController(okayAlertController, true, null); - - // reset our badge - UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } -} \ No newline at end of file +namespace LocalNotifications { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) { + var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes ( + UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null + ); + + + application.RegisterUserNotificationSettings (notificationSettings); + } + + // check for a notification + if (launchOptions != null) { + // check for a local notification + if (launchOptions.ContainsKey (UIApplication.LaunchOptionsLocalNotificationKey)) { + var localNotification = launchOptions [UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; + if (localNotification != null) { + UIAlertController okayAlertController = UIAlertController.Create (localNotification.AlertAction, localNotification.AlertBody, UIAlertControllerStyle.Alert); + okayAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + + Window.RootViewController.PresentViewController (okayAlertController, true, null); + + // reset our badge + UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; + } + } + } + return true; + } + + public override void ReceivedLocalNotification (UIApplication application, UILocalNotification notification) + { + // show an alert + UIAlertController okayAlertController = UIAlertController.Create (notification.AlertAction, notification.AlertBody, UIAlertControllerStyle.Alert); + okayAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + + Window.RootViewController.PresentViewController (okayAlertController, true, null); + + // reset our badge + UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } +} diff --git a/LocalNotifications/LocalNotifications/Main.cs b/LocalNotifications/LocalNotifications/Main.cs index c590e2b0f..48e576bcc 100644 --- a/LocalNotifications/LocalNotifications/Main.cs +++ b/LocalNotifications/LocalNotifications/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace LocalNotifications -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace LocalNotifications { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/LocalNotifications/LocalNotifications/ViewController.cs b/LocalNotifications/LocalNotifications/ViewController.cs index 0d0697111..d2968ffe7 100644 --- a/LocalNotifications/LocalNotifications/ViewController.cs +++ b/LocalNotifications/LocalNotifications/ViewController.cs @@ -1,39 +1,33 @@ -using Foundation; +using Foundation; using System; using UIKit; using UserNotifications; -namespace LocalNotifications -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) { } +namespace LocalNotifications { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { } - partial void SendNotification(UIButton sender) - { - var content = new UNMutableNotificationContent(); - content.Title = "View Alert"; - content.Body = "Your 10 second alert has fired!"; - content.Sound = UNNotificationSound.Default; - content.Badge = 1; + partial void SendNotification (UIButton sender) + { + var content = new UNMutableNotificationContent (); + content.Title = "View Alert"; + content.Body = "Your 10 second alert has fired!"; + content.Sound = UNNotificationSound.Default; + content.Badge = 1; - var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(10, false); + var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (10, false); - var requestID = "sampleRequest"; - var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger); + var requestID = "sampleRequest"; + var request = UNNotificationRequest.FromIdentifier (requestID, content, trigger); - // schedule it - UNUserNotificationCenter.Current.AddNotificationRequest(request, (error) => - { - if (error != null) - { - Console.WriteLine($"Error: {error.LocalizedDescription ?? ""}"); - } - else - { - Console.WriteLine("Scheduled..."); - } - }); - } - } -} \ No newline at end of file + // schedule it + UNUserNotificationCenter.Current.AddNotificationRequest (request, (error) => { + if (error != null) { + Console.WriteLine ($"Error: {error.LocalizedDescription ?? ""}"); + } else { + Console.WriteLine ("Scheduled..."); + } + }); + } + } +} diff --git a/Location/Location/AppDelegate.cs b/Location/Location/AppDelegate.cs index e9b35efa6..ec9d842eb 100644 --- a/Location/Location/AppDelegate.cs +++ b/Location/Location/AppDelegate.cs @@ -1,14 +1,12 @@ -using Foundation; +using Foundation; using UIKit; using System; -namespace Location -{ +namespace Location { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/Location/Location/LocationManager.cs b/Location/Location/LocationManager.cs index ac350c74e..d55a62e66 100644 --- a/Location/Location/LocationManager.cs +++ b/Location/Location/LocationManager.cs @@ -1,11 +1,9 @@ -using System; +using System; using CoreLocation; using UIKit; -namespace Location -{ - public class LocationManager - { +namespace Location { + public class LocationManager { protected CLLocationManager locMgr; @@ -19,7 +17,7 @@ public LocationManager () // iOS 8 has additional permissions requirements if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) { locMgr.RequestAlwaysAuthorization (); // works in background - //locMgr.RequestWhenInUseAuthorization (); // only in foreground + //locMgr.RequestWhenInUseAuthorization (); // only in foreground } // iOS 9 requires the following for background location updates @@ -58,7 +56,7 @@ public void StartLocationUpdates () //This will keep going in the background and the foreground public void PrintLocation (object sender, LocationUpdatedEventArgs e) { - + CLLocation location = e.Location; Console.WriteLine ("Altitude: " + location.Altitude + " meters"); Console.WriteLine ("Longitude: " + location.Coordinate.Longitude); diff --git a/Location/Location/LocationUpdateEventArgs.cs b/Location/Location/LocationUpdateEventArgs.cs index a7101e816..7f4c018ea 100644 --- a/Location/Location/LocationUpdateEventArgs.cs +++ b/Location/Location/LocationUpdateEventArgs.cs @@ -1,19 +1,16 @@ -using System; +using System; using CoreLocation; -namespace Location -{ - public class LocationUpdatedEventArgs : EventArgs - { +namespace Location { + public class LocationUpdatedEventArgs : EventArgs { CLLocation location; - public LocationUpdatedEventArgs(CLLocation location) + public LocationUpdatedEventArgs (CLLocation location) { this.location = location; } - public CLLocation Location - { + public CLLocation Location { get { return location; } } } diff --git a/Location/Location/Main.cs b/Location/Location/Main.cs index 8f597190f..e9cb241f0 100644 --- a/Location/Location/Main.cs +++ b/Location/Location/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace Location -{ - public class Application - { +namespace Location { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Location/Location/ViewController.cs b/Location/Location/ViewController.cs index b407a961f..8b7cc5abf 100644 --- a/Location/Location/ViewController.cs +++ b/Location/Location/ViewController.cs @@ -1,26 +1,24 @@ -using System; +using System; using UIKit; using CoreLocation; -namespace Location -{ - public partial class ViewController : UIViewController - { +namespace Location { + public partial class ViewController : UIViewController { #region Computed Properties public static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } - public static LocationManager Manager { get; set;} + public static LocationManager Manager { get; set; } #endregion #region Constructors public ViewController (IntPtr handle) : base (handle) { // As soon as the app is done launching, begin generating location updates in the location manager - Manager = new LocationManager(); - Manager.StartLocationUpdates(); + Manager = new LocationManager (); + Manager.StartLocationUpdates (); } #endregion diff --git a/LowLevelGLPaint/EAGLView.cs b/LowLevelGLPaint/EAGLView.cs index ecd86d060..01e1dc7f8 100644 --- a/LowLevelGLPaint/EAGLView.cs +++ b/LowLevelGLPaint/EAGLView.cs @@ -9,8 +9,7 @@ using Foundation; using OpenGLES; -namespace LowLevelGLPaint -{ +namespace LowLevelGLPaint { public class EAGLView : UIView { All _depthFormat; bool _autoResize; @@ -54,7 +53,7 @@ public EAGLView (CGRect frame, All format, All depth, bool retained) : base (fra protected override void Dispose (bool disposing) { DestroySurface (); - _context.Dispose(); + _context.Dispose (); _context = null; } @@ -62,17 +61,17 @@ void CreateSurface () { CAEAGLLayer eaglLayer = (CAEAGLLayer) Layer; if (!_context.IsCurrent) - _context.MakeCurrent(null); + _context.MakeCurrent (null); var newSize = eaglLayer.Bounds.Size; - newSize.Width = (float) Math.Round (newSize.Width); + newSize.Width = (float) Math.Round (newSize.Width); newSize.Height = (float) Math.Round (newSize.Height); int oldRenderbuffer = 0, oldFramebuffer = 0; GL.GetInteger (All.RenderbufferBindingOes, out oldRenderbuffer); GL.GetInteger (All.FramebufferBindingOes, out oldFramebuffer); - GL.Oes.GenRenderbuffers (1,out _renderbuffer); + GL.Oes.GenRenderbuffers (1, out _renderbuffer); GL.Oes.BindRenderbuffer (All.RenderbufferOes, _renderbuffer); if (!_context.EAGLContext.RenderBufferStorage ((uint) All.RenderbufferOes, eaglLayer)) { @@ -95,8 +94,7 @@ void CreateSurface () GL.Viewport (0, 0, (int) newSize.Width, (int) newSize.Height); GL.Scissor (0, 0, (int) newSize.Width, (int) newSize.Height); _hasBeenCurrent = true; - } - else + } else GL.Oes.BindFramebuffer (All.FramebufferOes, (uint) oldFramebuffer); GL.Oes.BindRenderbuffer (All.RenderbufferOes, (uint) oldRenderbuffer); @@ -110,7 +108,7 @@ void DestroySurface () EAGLContext oldContext = EAGLContext.CurrentContext; if (!_context.IsCurrent) - _context.MakeCurrent(null); + _context.MakeCurrent (null); if (_depthFormat != 0) { GL.Oes.DeleteRenderbuffers (1, ref _depthbuffer); @@ -145,11 +143,11 @@ void SetAutoResizesEaglSurface (bool resize) public void SetCurrentContext () { - _context.MakeCurrent(null); + _context.MakeCurrent (null); } public bool IsCurrentContext { - get {return _context.IsCurrent;} + get { return _context.IsCurrent; } } public void ClearCurrentContext () @@ -163,7 +161,7 @@ public void SwapBuffers () EAGLContext oldContext = EAGLContext.CurrentContext; if (!_context.IsCurrent) - _context.MakeCurrent(null); + _context.MakeCurrent (null); int oldRenderbuffer = 0; GL.GetInteger (All.RenderbufferBindingOes, out oldRenderbuffer); diff --git a/LowLevelGLPaint/Main.cs b/LowLevelGLPaint/Main.cs index 2831d49b8..ff2e82738 100644 --- a/LowLevelGLPaint/Main.cs +++ b/LowLevelGLPaint/Main.cs @@ -9,21 +9,18 @@ using OpenGLES; using OpenTK.Graphics.ES11; -namespace LowLevelGLPaint -{ - public class Application - { - static void Main (string[] args) +namespace LowLevelGLPaint { + public class Application { + static void Main (string [] args) { - using (var c = Utilities.CreateGraphicsContext(EAGLRenderingAPI.OpenGLES1)) { + using (var c = Utilities.CreateGraphicsContext (EAGLRenderingAPI.OpenGLES1)) { UIApplication.Main (args, null, "AppDelegate"); } } } // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { const int PaletteHeight = 30; const int PaletteSize = 5; @@ -37,9 +34,9 @@ public partial class AppDelegate : UIApplicationDelegate const float TopMarginPadding = 10.0f; const float RightMarginPadding = 10.0f; - double[] myAccelerometer = new double [3]; + double [] myAccelerometer = new double [3]; SoundEffect erasingSound = new SoundEffect (NSBundle.MainBundle.PathForResource ("Erase", "caf")); - SoundEffect selectSound = new SoundEffect (NSBundle.MainBundle.PathForResource ("Select", "caf")); + SoundEffect selectSound = new SoundEffect (NSBundle.MainBundle.PathForResource ("Select", "caf")); DateTime lastTime; PaintingView drawingView; @@ -56,7 +53,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.RootViewController = viewController; // Create a segmented control so that the user can choose the brush color. - var images = new[] { + var images = new [] { UIImage.FromFile ("Images/Red.png"), UIImage.FromFile ("Images/Yellow.png"), UIImage.FromFile ("Images/Green.png"), @@ -116,8 +113,8 @@ public override void OnActivated (UIApplication application) private void OnAccelerated (object sender, UIAccelerometerEventArgs e) { #if LINQ - myAccelerometer = new[]{e.Acceleration.X, e.Acceleration.Y, e.Acceleration.Z} - .Select((v, i) => v * FilteringFactor + myAccelerometer [i] * (1.0f - FilteringFactor)) + myAccelerometer = new [] { e.Acceleration.X, e.Acceleration.Y, e.Acceleration.Z } + .Select ((v, i) => v * FilteringFactor + myAccelerometer [i] * (1.0f - FilteringFactor)) .ToArray (); #else myAccelerometer [0] = e.Acceleration.X * FilteringFactor + myAccelerometer [0] * (1.0 - FilteringFactor); @@ -158,7 +155,7 @@ static void HslToRgb (float h, float s, float l, out float r, out float g, out f float temp1 = 2.0f * l - temp2; // Compute intermediate values based on hue - float[] temp = { + float [] temp = { h + 1.0f / 3.0f, h, h - 1.0f / 3.0f, diff --git a/LowLevelGLPaint/PaintingView.cs b/LowLevelGLPaint/PaintingView.cs index c0d874c63..7942e00f5 100644 --- a/LowLevelGLPaint/PaintingView.cs +++ b/LowLevelGLPaint/PaintingView.cs @@ -10,10 +10,8 @@ using UIKit; using OpenGLES; -namespace LowLevelGLPaint -{ - public class PaintingView : iPhoneOSGameView - { +namespace LowLevelGLPaint { + public class PaintingView : iPhoneOSGameView { public const float BrushOpacity = 1.0f / 3.0f; public const int BrushPixelStep = 3; public const int BrushScale = 2; @@ -42,23 +40,22 @@ public PaintingView (CGRect frame) CreateFrameBuffer (); MakeCurrent (); var brushImage = UIImage.FromFile ("Particle.png").CGImage; - var width = (int)brushImage.Width; - var height = (int)brushImage.Height; + var width = (int) brushImage.Width; + var height = (int) brushImage.Height; if (brushImage != null) { IntPtr brushData = Marshal.AllocHGlobal (width * height * 4); if (brushData == IntPtr.Zero) throw new OutOfMemoryException (); try { using (var brushContext = new CGBitmapContext (brushData, - (int)width, width, 8, width * 4, brushImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) { + (int) width, width, 8, width * 4, brushImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) { brushContext.DrawImage (new CGRect (0.0f, 0.0f, (float) width, (float) height), brushImage); } GL.GenTextures (1, out brushTexture); GL.BindTexture (All.Texture2D, brushTexture); - GL.TexImage2D (All.Texture2D, 0, (int) All.Rgba, (int)width, height, 0, All.Rgba, All.UnsignedByte, brushData); - } - finally { + GL.TexImage2D (All.Texture2D, 0, (int) All.Rgba, (int) width, height, 0, All.Rgba, All.UnsignedByte, brushData); + } finally { Marshal.FreeHGlobal (brushData); } GL.TexParameter (All.Texture2D, All.TextureMinFilter, (int) All.Linear); @@ -68,7 +65,7 @@ public PaintingView (CGRect frame) } GL.Disable (All.Dither); GL.MatrixMode (All.Projection); - GL.Ortho (0, (float)frame.Width, 0, (float)frame.Height, -1, 1); + GL.Ortho (0, (float) frame.Width, 0, (float) frame.Height, -1, 1); GL.MatrixMode (All.Modelview); GL.Enable (All.Texture2D); GL.EnableClientState (All.VertexArray); @@ -101,7 +98,7 @@ public void Erase () SwapBuffers (); } - nfloat[] vertexBuffer; + nfloat [] vertexBuffer; int vertexMax = 64; private void RenderLineFromPoint (CGPoint start, CGPoint end) @@ -137,7 +134,7 @@ void Playback () RenderLineFromPoint (points [i], points [i + 1]); if (dataofs < ShakeMe.Data.Count - 1) { - dataofs ++; + dataofs++; PerformSelector (new Selector ("playback"), null, 0.01f); } } @@ -160,8 +157,7 @@ public override void TouchesMoved (NSSet touches, UIEvent e) firstTouch = false; PreviousLocation = touch.PreviousLocationInView (this); PreviousLocation.Y = bounds.Height - PreviousLocation.Y; - } - else { + } else { Location = touch.LocationInView (this); Location.Y = bounds.Height - Location.Y; PreviousLocation = touch.PreviousLocationInView (this); diff --git a/LowLevelGLPaint/ShakeMe.cs b/LowLevelGLPaint/ShakeMe.cs index af7e7ec73..25ca183d2 100644 --- a/LowLevelGLPaint/ShakeMe.cs +++ b/LowLevelGLPaint/ShakeMe.cs @@ -3,7 +3,7 @@ namespace LowLevelGLPaint { public class ShakeMe { - public static List Data = new List () { + public static List Data = new List () { new CGPoint [] { new CGPoint (62.000000f, 366.000000f), new CGPoint (52.000000f, 363.000000f), diff --git a/LowLevelGLPaint/SoundEffect.cs b/LowLevelGLPaint/SoundEffect.cs index 251380364..94e54a4c1 100644 --- a/LowLevelGLPaint/SoundEffect.cs +++ b/LowLevelGLPaint/SoundEffect.cs @@ -2,10 +2,8 @@ using Foundation; using AudioToolbox; -namespace LowLevelGLPaint -{ - public class SoundEffect : NSObject - { +namespace LowLevelGLPaint { + public class SoundEffect : NSObject { SystemSound sound; public SoundEffect (string path) diff --git a/MTDJsonDemo/AppDelegate.cs b/MTDJsonDemo/AppDelegate.cs index e9f0103a5..1b8b4cb73 100644 --- a/MTDJsonDemo/AppDelegate.cs +++ b/MTDJsonDemo/AppDelegate.cs @@ -6,11 +6,9 @@ using UIKit; using MonoTouch.Dialog; -namespace MTDJsonDemo -{ +namespace MTDJsonDemo { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow _window; UINavigationController _nav; DialogViewController _rootVC; @@ -23,12 +21,12 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) _window = new UIWindow (UIScreen.MainScreen.Bounds); _rootElement = new RootElement ("Json Example"){ - new Section ("Demo Json"){ - (Element)JsonElement.FromFile ("sample.json"), - (Element)new JsonElement ("Load from url", "http://localhost/sample.json") - }, + new Section ("Demo Json"){ + (Element)JsonElement.FromFile ("sample.json"), + (Element)new JsonElement ("Load from url", "http://localhost/sample.json") + }, new Section ("Tasks Sample") - }; + }; _rootVC = new DialogViewController (_rootElement); _nav = new UINavigationController (_rootVC); @@ -40,7 +38,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) ++n; - var task = new Task{Name = "task " + n, DueDate = DateTime.Now}; + var task = new Task { Name = "task " + n, DueDate = DateTime.Now }; var taskElement = JsonElement.FromFile ("task.json"); @@ -59,7 +57,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) duedate.DateValue = task.DueDate; } - _rootElement [1].Add ((Element)taskElement); + _rootElement [1].Add ((Element) taskElement); }; _window.RootViewController = _nav; diff --git a/MTDJsonDemo/Main.cs b/MTDJsonDemo/Main.cs index 278910eff..44babb8a8 100644 --- a/MTDJsonDemo/Main.cs +++ b/MTDJsonDemo/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace MTDJsonDemo -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace MTDJsonDemo { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/MTDJsonDemo/Task.cs b/MTDJsonDemo/Task.cs index 84de99c48..7dbc70c35 100644 --- a/MTDJsonDemo/Task.cs +++ b/MTDJsonDemo/Task.cs @@ -1,17 +1,15 @@ using System; -namespace MTDJsonDemo -{ - public class Task - { - public Task () - { - } +namespace MTDJsonDemo { + public class Task { + public Task () + { + } - public string Name { get; set; } + public string Name { get; set; } - public string Description { get; set; } + public string Description { get; set; } - public DateTime DueDate { get; set; } - } + public DateTime DueDate { get; set; } + } } diff --git a/MTDReflectionWalkthrough/AppDelegate.cs b/MTDReflectionWalkthrough/AppDelegate.cs index dd7dab645..7edb8c0af 100644 --- a/MTDReflectionWalkthrough/AppDelegate.cs +++ b/MTDReflectionWalkthrough/AppDelegate.cs @@ -6,11 +6,9 @@ using UIKit; using MonoTouch.Dialog; -namespace MTDReflectionWalkthrough -{ +namespace MTDReflectionWalkthrough { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UINavigationController nav; @@ -23,7 +21,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) var bctx = new BindingContext (null, expense, "Create a task"); var dvc = new DialogViewController (bctx.Root); - nav = new UINavigationController(dvc); + nav = new UINavigationController (dvc); window.RootViewController = nav; window.MakeKeyAndVisible (); diff --git a/MTDReflectionWalkthrough/Expense.cs b/MTDReflectionWalkthrough/Expense.cs index cbd10da20..093a59115 100644 --- a/MTDReflectionWalkthrough/Expense.cs +++ b/MTDReflectionWalkthrough/Expense.cs @@ -1,29 +1,26 @@ using System; using MonoTouch.Dialog; -namespace MTDReflectionWalkthrough -{ - public enum Category - { +namespace MTDReflectionWalkthrough { + public enum Category { Travel, Lodging, Books } - public class Expense - { - [Section("Expense Entry")] + public class Expense { + [Section ("Expense Entry")] - [Entry("Enter expense name")] + [Entry ("Enter expense name")] public string Name; - [Section("Expense Details")] + [Section ("Expense Details")] - [Caption("Description")] + [Caption ("Description")] [Entry] public string Details; [Checkbox] public bool IsApproved = true; - [Caption("Category")] + [Caption ("Category")] public Category ExpenseCategory; } } diff --git a/MTDReflectionWalkthrough/Main.cs b/MTDReflectionWalkthrough/Main.cs index 5de3783c3..abd28ccdb 100644 --- a/MTDReflectionWalkthrough/Main.cs +++ b/MTDReflectionWalkthrough/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace MTDReflectionWalkthrough -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace MTDReflectionWalkthrough { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/MTDWalkthrough/AppDelegate.cs b/MTDWalkthrough/AppDelegate.cs index 4bde9ea64..7d2a8d898 100644 --- a/MTDWalkthrough/AppDelegate.cs +++ b/MTDWalkthrough/AppDelegate.cs @@ -6,11 +6,9 @@ using UIKit; using MonoTouch.Dialog; -namespace MTDWalkthrough -{ +namespace MTDWalkthrough { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow _window; UINavigationController _nav; DialogViewController _rootVC; @@ -36,24 +34,24 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) ++n; - var task = new Task{Name = "task " + n, DueDate = DateTime.Now}; + var task = new Task { Name = "task " + n, DueDate = DateTime.Now }; var element = new EntryElement (task.Name, "Enter task description", task.Description); var dateElement = new FutureDateElement ("Due Date", task.DueDate); - var taskElement = (Element)new RootElement (task.Name){ - new Section () { + var taskElement = (Element) new RootElement (task.Name){ + new Section () { element }, - new Section () { + new Section () { dateElement - }, + }, new Section ("Demo Retrieving Element Value") { new StringElement ("Output Task Description", delegate { Console.WriteLine (element.Value); }) } - }; + }; _rootElement [0].Add (taskElement); }; @@ -65,9 +63,8 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) } - public class FutureDateElement : DateElement - { - public FutureDateElement(string caption, DateTime date) : base(caption,date) + public class FutureDateElement : DateElement { + public FutureDateElement (string caption, DateTime date) : base (caption, date) { } @@ -75,7 +72,7 @@ public override UIDatePicker CreatePicker () { UIDatePicker futureDatePicker = base.CreatePicker (); futureDatePicker.BackgroundColor = UIColor.White; - futureDatePicker.MinimumDate = (NSDate)DateTime.Today; + futureDatePicker.MinimumDate = (NSDate) DateTime.Today; return futureDatePicker; } diff --git a/MTDWalkthrough/Main.cs b/MTDWalkthrough/Main.cs index 0a49efc38..9478567f9 100644 --- a/MTDWalkthrough/Main.cs +++ b/MTDWalkthrough/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace MTDWalkthrough -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace MTDWalkthrough { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/MTDWalkthrough/Task.cs b/MTDWalkthrough/Task.cs index 926937a90..56bbf8a34 100644 --- a/MTDWalkthrough/Task.cs +++ b/MTDWalkthrough/Task.cs @@ -1,9 +1,7 @@ using System; -namespace MTDWalkthrough -{ - public class Task - { +namespace MTDWalkthrough { + public class Task { public Task () { } diff --git a/MTGKTapper/MTGKTapper/AppDelegate.cs b/MTGKTapper/MTGKTapper/AppDelegate.cs index 803633742..d2951bfb4 100644 --- a/MTGKTapper/MTGKTapper/AppDelegate.cs +++ b/MTGKTapper/MTGKTapper/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace MTGKTapper -{ +namespace MTGKTapper { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; MTGKTapperViewController viewController; diff --git a/MTGKTapper/MTGKTapper/GameCenterManager.cs b/MTGKTapper/MTGKTapper/GameCenterManager.cs index 513799992..22e2f3dbc 100644 --- a/MTGKTapper/MTGKTapper/GameCenterManager.cs +++ b/MTGKTapper/MTGKTapper/GameCenterManager.cs @@ -3,10 +3,8 @@ using GameKit; using UIKit; -namespace MTGKTapper -{ - public class GameCenterManager - { +namespace MTGKTapper { + public class GameCenterManager { NSMutableDictionary earnedAchievementCache; public static bool IsGameCenterAvailable () @@ -30,9 +28,9 @@ public void ReportScore (long score, string category, MTGKTapperViewController c }; scoreReporter.ReportScore (error => { if (error == null) - ShowAlert("Score reported", "Score Reported successfully"); + ShowAlert ("Score reported", "Score Reported successfully"); else - ShowAlert("Score Reported Failed", "Score Reported Failed"); + ShowAlert ("Score Reported Failed", "Score Reported Failed"); NSThread.SleepFor (1); controller.UpdateHighScore (); }); @@ -41,7 +39,8 @@ public void ReportScore (long score, string category, MTGKTapperViewController c public void SubmitAchievement (string identifier, double percentComplete, string achievementName) { if (earnedAchievementCache == null) { - GKAchievement.LoadAchievements (new GKCompletionHandler (delegate(GKAchievement[] achievements, NSError error) { + GKAchievement.LoadAchievements (new GKCompletionHandler (delegate (GKAchievement [] achievements, NSError error) + { NSMutableDictionary tempCache = new NSMutableDictionary (); if (achievements != null) { foreach (var achievement in achievements) { @@ -52,7 +51,7 @@ public void SubmitAchievement (string identifier, double percentComplete, string SubmitAchievement (identifier, percentComplete, achievementName); })); } else { - GKAchievement achievement = (GKAchievement)earnedAchievementCache.ValueForKey (new NSString (identifier)); + GKAchievement achievement = (GKAchievement) earnedAchievementCache.ValueForKey (new NSString (identifier)); if (achievement != null) { if (achievement.PercentComplete >= 100.0 || achievement.PercentComplete >= percentComplete) achievement = null; @@ -62,7 +61,7 @@ public void SubmitAchievement (string identifier, double percentComplete, string achievement = new GKAchievement (identifier) { PercentComplete = percentComplete }; - earnedAchievementCache.Add ((NSString)achievement.Identifier, achievement); + earnedAchievementCache.Add ((NSString) achievement.Identifier, achievement); } if (achievement != null) { achievement.ReportAchievement (error => { @@ -86,7 +85,7 @@ public void ResetAchievement () if (error == null) new UIAlertView ("Achievement reset", "Achievement reset successfully", null, "OK", null).Show (); else - new UIAlertView ("Reset failed", string.Format("Reset failed because: {0}", error), null, "OK", null).Show (); + new UIAlertView ("Reset failed", string.Format ("Reset failed because: {0}", error), null, "OK", null).Show (); }); } @@ -96,4 +95,4 @@ void ShowAlert (string title, string msg) alert.Show (); } } -} \ No newline at end of file +} diff --git a/MTGKTapper/MTGKTapper/MTGKTapperViewController.cs b/MTGKTapper/MTGKTapper/MTGKTapperViewController.cs index 0744f2a2d..3cc96bbf1 100644 --- a/MTGKTapper/MTGKTapper/MTGKTapperViewController.cs +++ b/MTGKTapper/MTGKTapper/MTGKTapperViewController.cs @@ -4,10 +4,8 @@ using UIKit; using GameKit; -namespace MTGKTapper -{ - public partial class MTGKTapperViewController : UIViewController - { +namespace MTGKTapper { + public partial class MTGKTapperViewController : UIViewController { const string EasyLeaderboardID = "com.appledts.EasyTapList"; const string HardLeaderboardID = "com.appledts.HardTapList"; const string AwesomeLeaderboardID = "com.appledts.AwesomeTapList"; @@ -36,7 +34,7 @@ public override void ViewDidLoad () // Perform any additional setup after loading the view, typically from a nib. InitGameCenter (); - string[] categories = { "Easy", "Hard", "Awesome" }; + string [] categories = { "Easy", "Hard", "Awesome" }; var selectCategory = new UIActionSheet ("Choose Leaderboard", null, "Cancel", null, categories); selectCategory.Dismissed += (sender, e) => { switch (e.ButtonIndex) { @@ -189,4 +187,4 @@ void CheckAchievements () gameCenterManager.SubmitAchievement (identifier, percentComplete, achievementName); } } -} \ No newline at end of file +} diff --git a/MTGKTapper/MTGKTapper/Main.cs b/MTGKTapper/MTGKTapper/Main.cs index 97c881942..8c148909a 100644 --- a/MTGKTapper/MTGKTapper/Main.cs +++ b/MTGKTapper/MTGKTapper/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace MTGKTapper -{ - public class Application - { +namespace MTGKTapper { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ManualCameraControls/ManualCameraControls/AppDelegate.cs b/ManualCameraControls/ManualCameraControls/AppDelegate.cs index deeedeb0d..cc681c9f6 100644 --- a/ManualCameraControls/ManualCameraControls/AppDelegate.cs +++ b/ManualCameraControls/ManualCameraControls/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using AVFoundation; using CoreFoundation; @@ -7,14 +7,12 @@ using Foundation; using UIKit; -namespace ManualCameraControls -{ +namespace ManualCameraControls { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { #region Private Variables NSError Error; @@ -127,7 +125,7 @@ public override void FinishedLaunching (UIApplication application) // Configure and attach a still image output for bracketed capture StillImageOutput = new AVCaptureStillImageOutput (); var dict = new NSMutableDictionary (); - dict [AVVideo.CodecKey] = new NSNumber ((int)AVVideoCodec.JPEG); + dict [AVVideo.CodecKey] = new NSNumber ((int) AVVideoCodec.JPEG); Session.AddOutput (StillImageOutput); // Let tabs know that a camera is available diff --git a/ManualCameraControls/ManualCameraControls/BracketedViewController.cs b/ManualCameraControls/ManualCameraControls/BracketedViewController.cs index 02a6105e9..ba929d4c3 100644 --- a/ManualCameraControls/ManualCameraControls/BracketedViewController.cs +++ b/ManualCameraControls/ManualCameraControls/BracketedViewController.cs @@ -7,10 +7,8 @@ using Foundation; using UIKit; -namespace ManualCameraControls -{ - public partial class BracketedViewController : UIViewController - { +namespace ManualCameraControls { + public partial class BracketedViewController : UIViewController { #region Private Variables List Output = new List (); @@ -26,7 +24,7 @@ public partial class BracketedViewController : UIViewController /// The this app. public AppDelegate ThisApp { get { - return (AppDelegate)UIApplication.SharedApplication.Delegate; + return (AppDelegate) UIApplication.SharedApplication.Delegate; } } @@ -94,7 +92,7 @@ public override void ViewDidLoad () Output.Add (BuildOutputView (3)); // Create preset settings - var Settings = new AVCaptureBracketedStillImageSettings[] { + var Settings = new AVCaptureBracketedStillImageSettings [] { AVCaptureAutoExposureBracketedStillImageSettings.Create (-2f), AVCaptureAutoExposureBracketedStillImageSettings.Create (0f), AVCaptureAutoExposureBracketedStillImageSettings.Create (2f) @@ -107,7 +105,7 @@ public override void ViewDidLoad () // Reset output index if (OutputIndex < Settings.Length) return; - + OutputIndex = 0; // Tell the camera that we are getting ready to do a bracketed capture diff --git a/ManualCameraControls/ManualCameraControls/Classes/OutputRecorder.cs b/ManualCameraControls/ManualCameraControls/Classes/OutputRecorder.cs index ff8d08c3f..6991385ab 100644 --- a/ManualCameraControls/ManualCameraControls/Classes/OutputRecorder.cs +++ b/ManualCameraControls/ManualCameraControls/Classes/OutputRecorder.cs @@ -9,14 +9,12 @@ using CoreMedia; using CoreGraphics; -namespace ManualCameraControls -{ +namespace ManualCameraControls { /// /// Helper class that pulls an image from the sample buffer and displays it in the UIImageView /// that it has been attached to. /// - public class OutputRecorder : AVCaptureVideoDataOutputSampleBufferDelegate - { + public class OutputRecorder : AVCaptureVideoDataOutputSampleBufferDelegate { #region Computed Properties /// /// Gets or sets the display view. @@ -41,7 +39,8 @@ public OutputRecorder () /// /// The image from sample buffer. /// Sample buffer. - private UIImage GetImageFromSampleBuffer(CMSampleBuffer sampleBuffer) { + private UIImage GetImageFromSampleBuffer (CMSampleBuffer sampleBuffer) + { // Get a pixel buffer from the sample buffer using (var pixelBuffer = sampleBuffer.GetImageBuffer () as CVPixelBuffer) { @@ -56,12 +55,12 @@ private UIImage GetImageFromSampleBuffer(CMSampleBuffer sampleBuffer) { // Create new context from buffer using (var context = new CGBitmapContext (pixelBuffer.BaseAddress, - pixelBuffer.Width, - pixelBuffer.Height, - 8, - pixelBuffer.BytesPerRow, - cs, - (CGImageAlphaInfo)flags)) { + pixelBuffer.Width, + pixelBuffer.Height, + 8, + pixelBuffer.BytesPerRow, + cs, + (CGImageAlphaInfo) flags)) { // Get the image from the context using (var cgImage = context.ToImage ()) { @@ -94,11 +93,11 @@ public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSam // Trap all errors try { // Grab an image from the buffer - var image = GetImageFromSampleBuffer(sampleBuffer); + var image = GetImageFromSampleBuffer (sampleBuffer); // Display the image - if (DisplayView !=null) { - DisplayView.BeginInvokeOnMainThread(() => { + if (DisplayView != null) { + DisplayView.BeginInvokeOnMainThread (() => { // Set the image var oldImg = DisplayView.Image; oldImg?.Dispose (); @@ -106,15 +105,14 @@ public override void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSam DisplayView.Image = image; // Rotate image to the correct display orientation - DisplayView.Transform = CGAffineTransform.MakeRotation((float)Math.PI/2); + DisplayView.Transform = CGAffineTransform.MakeRotation ((float) Math.PI / 2); }); } // IMPORTANT: You must release the buffer because AVFoundation has a fixed number // of buffers and will stop delivering frames if it runs out. - sampleBuffer.Dispose(); - } - catch(Exception e) { + sampleBuffer.Dispose (); + } catch (Exception e) { // Report error Console.WriteLine ("Error sampling buffer: {0}", e.Message); } diff --git a/ManualCameraControls/ManualCameraControls/ExposureViewController.cs b/ManualCameraControls/ManualCameraControls/ExposureViewController.cs index eb16455bb..1325f2ba1 100644 --- a/ManualCameraControls/ManualCameraControls/ExposureViewController.cs +++ b/ManualCameraControls/ManualCameraControls/ExposureViewController.cs @@ -8,10 +8,8 @@ using ObjCRuntime; using System.Runtime.InteropServices; -namespace ManualCameraControls -{ - public partial class ExposureViewController : UIViewController - { +namespace ManualCameraControls { + public partial class ExposureViewController : UIViewController { #region Private Variables bool Automatic = true; @@ -28,7 +26,7 @@ public partial class ExposureViewController : UIViewController /// The this app. public AppDelegate ThisApp { get { - return (AppDelegate)UIApplication.SharedApplication.Delegate; + return (AppDelegate) UIApplication.SharedApplication.Delegate; } } @@ -57,7 +55,7 @@ public ExposureViewController (IntPtr handle) : base (handle) /// Time. float CMTimeGetSeconds (CMTime time) { - return (float)time.Value / (float)time.TimeScale; + return (float) time.Value / (float) time.TimeScale; } #endregion @@ -103,7 +101,7 @@ public override void ViewDidLoad () var minDurationSeconds = Math.Max (CMTimeGetSeconds (ThisApp.CaptureDevice.ActiveFormat.MinExposureDuration), ExposureMinimumDuration); var maxDurationSeconds = CMTimeGetSeconds (ThisApp.CaptureDevice.ActiveFormat.MaxExposureDuration); var p = (newDurationSeconds - minDurationSeconds) / (maxDurationSeconds - minDurationSeconds); - Duration.Value = (float)Math.Pow (p, 1.0f / ExposureDurationPower); + Duration.Value = (float) Math.Pow (p, 1.0f / ExposureDurationPower); }); ISO.BeginInvokeOnMainThread (() => { @@ -124,7 +122,7 @@ public override void ViewDidLoad () // Take action based on the segment selected switch (Segments.SelectedSegment) { case 0: - // Activate auto exposure and start monitoring position + // Activate auto exposure and start monitoring position Duration.Enabled = false; ISO.Enabled = false; ThisApp.CaptureDevice.ExposureMode = AVCaptureExposureMode.ContinuousAutoExposure; @@ -132,7 +130,7 @@ public override void ViewDidLoad () Automatic = true; break; case 1: - // Lock exposure and allow the user to control the camera + // Lock exposure and allow the user to control the camera SampleTimer.Stop (); ThisApp.CaptureDevice.ExposureMode = AVCaptureExposureMode.Locked; Automatic = false; @@ -140,7 +138,7 @@ public override void ViewDidLoad () ISO.Enabled = false; break; case 2: - // Custom exposure and allow the user to control the camera + // Custom exposure and allow the user to control the camera SampleTimer.Stop (); ThisApp.CaptureDevice.ExposureMode = AVCaptureExposureMode.Custom; Automatic = false; @@ -165,7 +163,7 @@ public override void ViewDidLoad () var p = Math.Pow (Duration.Value, ExposureDurationPower); var minDurationSeconds = Math.Max (ThisApp.CaptureDevice.ActiveFormat.MinExposureDuration.Seconds, ExposureMinimumDuration); var maxDurationSeconds = ThisApp.CaptureDevice.ActiveFormat.MaxExposureDuration.Seconds; - var newDurationSeconds = p * (maxDurationSeconds - minDurationSeconds ) + minDurationSeconds; + var newDurationSeconds = p * (maxDurationSeconds - minDurationSeconds) + minDurationSeconds; NSError err; // Update Focus position diff --git a/ManualCameraControls/ManualCameraControls/FocusViewController.cs b/ManualCameraControls/ManualCameraControls/FocusViewController.cs index 36ce35826..cfd121879 100644 --- a/ManualCameraControls/ManualCameraControls/FocusViewController.cs +++ b/ManualCameraControls/ManualCameraControls/FocusViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace ManualCameraControls -{ - public partial class FocusViewController : UIViewController - { +namespace ManualCameraControls { + public partial class FocusViewController : UIViewController { #region Private Variables NSError Error; @@ -24,7 +22,7 @@ public partial class FocusViewController : UIViewController /// The this app. public AppDelegate ThisApp { get { - return (AppDelegate)UIApplication.SharedApplication.Delegate; + return (AppDelegate) UIApplication.SharedApplication.Delegate; } } @@ -56,7 +54,7 @@ public FocusViewController (IntPtr handle) : base (handle) public override void ViewDidLoad () { base.ViewDidLoad (); - + // Hide no camera label NoCamera.Hidden = ThisApp.CameraAvailable; @@ -77,14 +75,14 @@ public override void ViewDidLoad () // Take action based on the segment selected switch (Segments.SelectedSegment) { case 0: - // Activate auto focus and start monitoring position + // Activate auto focus and start monitoring position Position.Enabled = false; ThisApp.CaptureDevice.FocusMode = AVCaptureFocusMode.ContinuousAutoFocus; SampleTimer.Start (); Automatic = true; break; case 1: - // Stop auto focus and allow the user to control the camera + // Stop auto focus and allow the user to control the camera SampleTimer.Stop (); ThisApp.CaptureDevice.FocusMode = AVCaptureFocusMode.Locked; Automatic = false; diff --git a/ManualCameraControls/ManualCameraControls/Main.cs b/ManualCameraControls/ManualCameraControls/Main.cs index 2fbf2ca21..dbc85877b 100644 --- a/ManualCameraControls/ManualCameraControls/Main.cs +++ b/ManualCameraControls/ManualCameraControls/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace ManualCameraControls -{ - public class Application - { +namespace ManualCameraControls { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ManualCameraControls/ManualCameraControls/Notes.cs b/ManualCameraControls/ManualCameraControls/Notes.cs index 97fbcc31e..abcdfe2cf 100644 --- a/ManualCameraControls/ManualCameraControls/Notes.cs +++ b/ManualCameraControls/ManualCameraControls/Notes.cs @@ -1,4 +1,4 @@ -// // Create a new still image session +// // Create a new still image session // session = new AVCaptureSession(); // var camera = AVCaptureDevice.DefaultDeviceWithMediaType(AVMediaType.Video); // var input = AVCaptureDeviceInput.FromDevice(camera); @@ -15,4 +15,4 @@ // previewLayer.Orientation = AVCaptureVideoOrientation.Portrait; // previewLayer.VideoGravity = "AVLayerVideoGravityResizeAspectFill"; // previewLayer.Frame = CameraView.Frame; -// CameraView.Layer.AddSublayer (previewLayer); \ No newline at end of file +// CameraView.Layer.AddSublayer (previewLayer); diff --git a/ManualCameraControls/ManualCameraControls/WhiteBalanceViewController.cs b/ManualCameraControls/ManualCameraControls/WhiteBalanceViewController.cs index 44703470a..f620117ed 100644 --- a/ManualCameraControls/ManualCameraControls/WhiteBalanceViewController.cs +++ b/ManualCameraControls/ManualCameraControls/WhiteBalanceViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace ManualCameraControls -{ - public partial class WhiteBalanceViewController : UIViewController - { +namespace ManualCameraControls { + public partial class WhiteBalanceViewController : UIViewController { #region Private Variables NSError Error; bool Automatic = true; @@ -20,7 +18,7 @@ public partial class WhiteBalanceViewController : UIViewController /// /// The this app. public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// @@ -40,7 +38,8 @@ public WhiteBalanceViewController (IntPtr handle) : base (handle) /// /// Sets the temperature and tint. /// - void SetTemperatureAndTint() { + void SetTemperatureAndTint () + { // Grab current temp and tint var TempAndTint = new AVCaptureWhiteBalanceTemperatureAndTintValues (Temperature.Value, Tint.Value); @@ -101,7 +100,7 @@ public override void ViewDidLoad () // Take action based on the segment selected switch (Segments.SelectedSegment) { case 0: - // Activate auto focus and start monitoring position + // Activate auto focus and start monitoring position Temperature.Enabled = false; Tint.Enabled = false; ThisApp.CaptureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.ContinuousAutoWhiteBalance; @@ -109,7 +108,7 @@ public override void ViewDidLoad () Automatic = true; break; case 1: - // Stop auto focus and allow the user to control the camera + // Stop auto focus and allow the user to control the camera SampleTimer.Stop (); ThisApp.CaptureDevice.WhiteBalanceMode = AVCaptureWhiteBalanceMode.Locked; Automatic = false; diff --git a/ManualStoryboard/ManualStoryboard/AppDelegate.cs b/ManualStoryboard/ManualStoryboard/AppDelegate.cs index 076a9590f..2cdc3293d 100644 --- a/ManualStoryboard/ManualStoryboard/AppDelegate.cs +++ b/ManualStoryboard/ManualStoryboard/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace ManualStoryboard -{ +namespace ManualStoryboard { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public static UIStoryboard Storyboard = UIStoryboard.FromName ("MainStoryboard", null); public static UIViewController initialViewController; diff --git a/ManualStoryboard/ManualStoryboard/Main.cs b/ManualStoryboard/ManualStoryboard/Main.cs index 36807b45f..a70c33fef 100644 --- a/ManualStoryboard/ManualStoryboard/Main.cs +++ b/ManualStoryboard/ManualStoryboard/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace ManualStoryboard -{ - public class Application - { +namespace ManualStoryboard { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ManualStoryboard/ManualStoryboard/MainViewController.cs b/ManualStoryboard/ManualStoryboard/MainViewController.cs index 5df700dd9..4ee25eda9 100644 --- a/ManualStoryboard/ManualStoryboard/MainViewController.cs +++ b/ManualStoryboard/ManualStoryboard/MainViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace ManualStoryboard -{ - public partial class MainViewController : UIViewController - { +namespace ManualStoryboard { + public partial class MainViewController : UIViewController { UIViewController pinkViewController; public MainViewController (IntPtr handle) : base (handle) @@ -21,7 +19,8 @@ public override void AwakeFromNib () this.Initialize (); } - public void Initialize(){ + public void Initialize () + { var myStoryboard = AppDelegate.Storyboard; //Instatiating View Controller with Storyboard ID 'PinkViewController' diff --git a/ManualStoryboard/ManualStoryboard/PinkViewController.cs b/ManualStoryboard/ManualStoryboard/PinkViewController.cs index 3e69e2a75..599f07835 100644 --- a/ManualStoryboard/ManualStoryboard/PinkViewController.cs +++ b/ManualStoryboard/ManualStoryboard/PinkViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace ManualStoryboard -{ - partial class PinkViewController : UIViewController - { +namespace ManualStoryboard { + partial class PinkViewController : UIViewController { public PinkViewController (IntPtr handle) : base (handle) { } diff --git a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/AppDelegate.cs b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/AppDelegate.cs index 313e24fa0..7566bf109 100644 --- a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/AppDelegate.cs +++ b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/AppDelegate.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace Storyboard.Conditional -{ +namespace Storyboard.Conditional { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public static UIStoryboard Storyboard = UIStoryboard.FromName ("MainStoryboard", null); public static UIViewController initialViewController; diff --git a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/Main.cs b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/Main.cs index 6eff03888..3ac6d4d2e 100644 --- a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/Main.cs +++ b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace Storyboard.Conditional -{ - public class Application - { +namespace Storyboard.Conditional { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/MainViewController.cs b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/MainViewController.cs index 45c1621ba..a3e1d3dfe 100644 --- a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/MainViewController.cs +++ b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/MainViewController.cs @@ -3,11 +3,9 @@ using System.CodeDom.Compiler; using UIKit; -namespace Storyboard.Conditional -{ - partial class MainViewController : UIViewController - { - +namespace Storyboard.Conditional { + partial class MainViewController : UIViewController { + public MainViewController (IntPtr handle) : base (handle) { @@ -15,19 +13,18 @@ public MainViewController (IntPtr handle) : base (handle) public override bool ShouldPerformSegue (string segueIdentifier, NSObject sender) { - - if(segueIdentifier == "SegueToPink"){ + + if (segueIdentifier == "SegueToPink") { if (PasswordTextField.Text == "password") { PasswordTextField.ResignFirstResponder (); return true; - } - else{ + } else { ErrorLabel.Hidden = false; return false; } } return base.ShouldPerformSegue (segueIdentifier, sender); } - + } } diff --git a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/PinkViewController.cs b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/PinkViewController.cs index 12c9c7b50..bb8d506d5 100644 --- a/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/PinkViewController.cs +++ b/ManualStoryboard/Storyboard.Conditional/Storyboard.Conditional/PinkViewController.cs @@ -3,10 +3,8 @@ using System.CodeDom.Compiler; using UIKit; -namespace Storyboard.Conditional -{ - partial class PinkViewController : UIViewController - { +namespace Storyboard.Conditional { + partial class PinkViewController : UIViewController { public PinkViewController (IntPtr handle) : base (handle) { } diff --git a/MapCallouts/AppDelegate.cs b/MapCallouts/AppDelegate.cs index 50d108726..bb843dc86 100644 --- a/MapCallouts/AppDelegate.cs +++ b/MapCallouts/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace MapCallouts -{ +namespace MapCallouts { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; MainViewController viewController; diff --git a/MapCallouts/BridgeAnnotation.cs b/MapCallouts/BridgeAnnotation.cs index 651dbbf0f..b5e982fd2 100644 --- a/MapCallouts/BridgeAnnotation.cs +++ b/MapCallouts/BridgeAnnotation.cs @@ -6,10 +6,8 @@ using MapKit; using UIKit; -namespace MapCallouts -{ - public class BridgeAnnotation : MKAnnotation - { +namespace MapCallouts { + public class BridgeAnnotation : MKAnnotation { public override string Title { get { return "Golden Gate Bridge"; } } public override string Subtitle { get { return "Opened: May 27, 1937"; } } diff --git a/MapCallouts/DetailViewController.cs b/MapCallouts/DetailViewController.cs index fe2dea707..5fbdb712e 100644 --- a/MapCallouts/DetailViewController.cs +++ b/MapCallouts/DetailViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace MapCallouts -{ - public partial class DetailViewController : UIViewController - { +namespace MapCallouts { + public partial class DetailViewController : UIViewController { //loads the DetailViewController.xib file and connects it to this object public DetailViewController () : base ("DetailViewController", null) { diff --git a/MapCallouts/Main.cs b/MapCallouts/Main.cs index bf3cded04..d32188386 100644 --- a/MapCallouts/Main.cs +++ b/MapCallouts/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace MapCallouts -{ - public class Application - { +namespace MapCallouts { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/MapCallouts/MainViewController.cs b/MapCallouts/MainViewController.cs index 5b0cf5626..6f43609cb 100644 --- a/MapCallouts/MainViewController.cs +++ b/MapCallouts/MainViewController.cs @@ -6,17 +6,14 @@ using UIKit; using MapKit; -namespace MapCallouts -{ - public partial class MainViewController : UIViewController - { - enum AnnotationIndex - { +namespace MapCallouts { + public partial class MainViewController : UIViewController { + enum AnnotationIndex { City, Bridge, } - MKAnnotation[] mapAnnotations; + MKAnnotation [] mapAnnotations; DetailViewController detailViewController; const float AnnotationPadding = 10; @@ -54,8 +51,8 @@ public override void ViewDidLoad () NavigationItem.BackBarButtonItem = temporaryBarButtonItem; mapAnnotations = new MKAnnotation [2]; - mapAnnotations [(int)AnnotationIndex.City] = new SFAnnotation (); - mapAnnotations [(int)AnnotationIndex.Bridge] = new BridgeAnnotation (); + mapAnnotations [(int) AnnotationIndex.City] = new SFAnnotation (); + mapAnnotations [(int) AnnotationIndex.Bridge] = new BridgeAnnotation (); GotoLocation (); @@ -74,7 +71,7 @@ public override void ViewDidUnload () void RemoveAllAnnotations () { foreach (var obj in mapView.Annotations) { - mapView.RemoveAnnotation ((MKAnnotation)obj); + mapView.RemoveAnnotation ((MKAnnotation) obj); } } @@ -89,14 +86,14 @@ partial void bridgeAction (Foundation.NSObject sender) { GotoLocation (); RemoveAllAnnotations (); - mapView.AddAnnotation (mapAnnotations [(int)AnnotationIndex.Bridge]); + mapView.AddAnnotation (mapAnnotations [(int) AnnotationIndex.Bridge]); } partial void cityAction (Foundation.NSObject sender) { GotoLocation (); RemoveAllAnnotations (); - mapView.AddAnnotation (mapAnnotations [(int)AnnotationIndex.City]); + mapView.AddAnnotation (mapAnnotations [(int) AnnotationIndex.City]); } void showDetails () @@ -119,7 +116,7 @@ MKAnnotationView GetViewForAnnotation (MKMapView mapView, IMKAnnotation annotati // if (annotation is BridgeAnnotation) { // for Golden Gate Bridge const string BridgeAnnotationIdentifier = "bridgeAnnotationIdentifier"; - MKPinAnnotationView pinView = (MKPinAnnotationView)mapView.DequeueReusableAnnotation (BridgeAnnotationIdentifier); + MKPinAnnotationView pinView = (MKPinAnnotationView) mapView.DequeueReusableAnnotation (BridgeAnnotationIdentifier); if (pinView == null) { MKPinAnnotationView customPinView = new MKPinAnnotationView (annotation, BridgeAnnotationIdentifier); customPinView.PinColor = MKPinAnnotationColor.Purple; @@ -137,7 +134,7 @@ MKAnnotationView GetViewForAnnotation (MKMapView mapView, IMKAnnotation annotati return pinView; } else if (annotation is SFAnnotation) { // for City of San Francisco const string SFAnnotationIdentifier = "SFAnnotationIdentifier"; - MKAnnotationView pinView = (MKAnnotationView)mapView.DequeueReusableAnnotation (SFAnnotationIdentifier); + MKAnnotationView pinView = (MKAnnotationView) mapView.DequeueReusableAnnotation (SFAnnotationIdentifier); if (pinView == null) { MKAnnotationView annotationView = new MKAnnotationView (annotation, SFAnnotationIdentifier); annotationView.CanShowCallout = true; diff --git a/MapCallouts/SFAnnotation.cs b/MapCallouts/SFAnnotation.cs index 378e0ad02..38ae87c0a 100644 --- a/MapCallouts/SFAnnotation.cs +++ b/MapCallouts/SFAnnotation.cs @@ -6,10 +6,8 @@ using MapKit; using UIKit; -namespace MapCallouts -{ - public class SFAnnotation : MKAnnotation - { +namespace MapCallouts { + public class SFAnnotation : MKAnnotation { public UIImage Image { get; set; } public double Latitute { get; set; } diff --git a/MapDemo/MapDemo/AppDelegate.cs b/MapDemo/MapDemo/AppDelegate.cs index 059bb6408..2b92a73df 100644 --- a/MapDemo/MapDemo/AppDelegate.cs +++ b/MapDemo/MapDemo/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace MapDemo -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace MapDemo { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/MapDemo/MapDemo/Main.cs b/MapDemo/MapDemo/Main.cs index 1742d7844..5b526c886 100644 --- a/MapDemo/MapDemo/Main.cs +++ b/MapDemo/MapDemo/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace MapDemo -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace MapDemo { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/MapDemo/MapDemo/MapViewController.cs b/MapDemo/MapDemo/MapViewController.cs index 0110a6308..939d9cfb4 100644 --- a/MapDemo/MapDemo/MapViewController.cs +++ b/MapDemo/MapDemo/MapViewController.cs @@ -1,89 +1,83 @@ -using CoreLocation; +using CoreLocation; using MapKit; -using System; -using UIKit; - -namespace MapDemo -{ - public partial class MapViewController : UIViewController - { - private readonly CLLocationManager locationManager = new CLLocationManager(); - - private UISearchController searchController; - - private MapViewDelegate mapViewDelegate; - - public MapViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - locationManager.RequestWhenInUseAuthorization(); - - // set map center and region - const double lat = 42.374260; - const double lon = -71.120824; - var mapCenter = new CLLocationCoordinate2D(lat, lon); - var mapRegion = MKCoordinateRegion.FromDistance(mapCenter, 2000, 2000); - map.CenterCoordinate = mapCenter; - map.Region = mapRegion; - - // add an annotation - map.AddAnnotation(new MKPointAnnotation - { - Title = "MyAnnotation", - Coordinate = new CLLocationCoordinate2D(42.364260, -71.120824) - }); - - // set the map delegate - mapViewDelegate = new MapViewDelegate(); - map.Delegate = mapViewDelegate; - - // add a custom annotation - map.AddAnnotation(new MonkeyAnnotation("Xamarin", mapCenter)); - - // add an overlay - map.AddOverlay(MKCircle.Circle(mapCenter, 1000)); - - // add search - var searchResultsController = new SearchResultsViewController(map); - - var searchUpdater = new SearchResultsUpdator(); - searchUpdater.UpdateSearchResults += searchResultsController.UpdateSearchResults; - - // add the search controller - searchController = new UISearchController(searchResultsController); - searchController.SearchResultsUpdater = searchUpdater; - - searchController.SearchBar.SizeToFit(); - searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Minimal; - searchController.SearchBar.Placeholder = "Enter a search query"; - - searchController.HidesNavigationBarDuringPresentation = false; - NavigationItem.TitleView = searchController.SearchBar; - DefinesPresentationContext = true; - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if(searchController != null) - { - searchController.Dispose(); - searchController = null; - } - - if (mapViewDelegate != null) - { - mapViewDelegate.Dispose(); - mapViewDelegate = null; - } - - if (locationManager != null) - { - locationManager.Dispose(); - } - } - } -} \ No newline at end of file +using System; +using UIKit; + +namespace MapDemo { + public partial class MapViewController : UIViewController { + private readonly CLLocationManager locationManager = new CLLocationManager (); + + private UISearchController searchController; + + private MapViewDelegate mapViewDelegate; + + public MapViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + locationManager.RequestWhenInUseAuthorization (); + + // set map center and region + const double lat = 42.374260; + const double lon = -71.120824; + var mapCenter = new CLLocationCoordinate2D (lat, lon); + var mapRegion = MKCoordinateRegion.FromDistance (mapCenter, 2000, 2000); + map.CenterCoordinate = mapCenter; + map.Region = mapRegion; + + // add an annotation + map.AddAnnotation (new MKPointAnnotation { + Title = "MyAnnotation", + Coordinate = new CLLocationCoordinate2D (42.364260, -71.120824) + }); + + // set the map delegate + mapViewDelegate = new MapViewDelegate (); + map.Delegate = mapViewDelegate; + + // add a custom annotation + map.AddAnnotation (new MonkeyAnnotation ("Xamarin", mapCenter)); + + // add an overlay + map.AddOverlay (MKCircle.Circle (mapCenter, 1000)); + + // add search + var searchResultsController = new SearchResultsViewController (map); + + var searchUpdater = new SearchResultsUpdator (); + searchUpdater.UpdateSearchResults += searchResultsController.UpdateSearchResults; + + // add the search controller + searchController = new UISearchController (searchResultsController); + searchController.SearchResultsUpdater = searchUpdater; + + searchController.SearchBar.SizeToFit (); + searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Minimal; + searchController.SearchBar.Placeholder = "Enter a search query"; + + searchController.HidesNavigationBarDuringPresentation = false; + NavigationItem.TitleView = searchController.SearchBar; + DefinesPresentationContext = true; + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (searchController != null) { + searchController.Dispose (); + searchController = null; + } + + if (mapViewDelegate != null) { + mapViewDelegate.Dispose (); + mapViewDelegate = null; + } + + if (locationManager != null) { + locationManager.Dispose (); + } + } + } +} diff --git a/MapDemo/MapDemo/MapViewDelegate.cs b/MapDemo/MapDemo/MapViewDelegate.cs index e6dc79167..eeccec854 100644 --- a/MapDemo/MapDemo/MapViewDelegate.cs +++ b/MapDemo/MapDemo/MapViewDelegate.cs @@ -1,59 +1,52 @@ -using MapKit; +using MapKit; using UIKit; -namespace MapDemo -{ - public class MapViewDelegate : MKMapViewDelegate - { - private const string MonkeyId = "MonkeyAnnotation"; - private const string PinId = "PinAnnotation"; - - public override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) - { - MKAnnotationView result = null; - - if (annotation is MKUserLocation) - return result; - - if (annotation is MonkeyAnnotation) - { - // show monkey annotation - result = mapView.DequeueReusableAnnotation(MonkeyId) ?? new MKAnnotationView(annotation, MonkeyId); - result.Draggable = true; - result.CanShowCallout = true; - result.Image = UIImage.FromBundle("Monkey"); - result.RightCalloutAccessoryView = UIButton.FromType(UIButtonType.DetailDisclosure); - } - else - { - // show pin annotation - var annotationView = mapView.DequeueReusableAnnotation(PinId) as MKPinAnnotationView ?? new MKPinAnnotationView(annotation, PinId); - annotationView.PinTintColor = UIColor.Red; - annotationView.CanShowCallout = true; - - result = annotationView; - } - - return result; - } - - public override void CalloutAccessoryControlTapped(MKMapView mapView, MKAnnotationView view, UIControl control) - { - if (view.Annotation is MonkeyAnnotation monkeyAnnotation) - { - var alert = UIAlertController.Create("Monkey Annotation", monkeyAnnotation.Title, UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - UIApplication.SharedApplication.Windows[0].RootViewController.PresentViewController(alert, true, null); - } - } - - public override MKOverlayRenderer OverlayRenderer(MKMapView mapView, IMKOverlay overlay) - { - return new MKCircleRenderer(overlay as MKCircle) - { - FillColor = UIColor.Red, - Alpha = 0.4f - }; - } - } -} \ No newline at end of file +namespace MapDemo { + public class MapViewDelegate : MKMapViewDelegate { + private const string MonkeyId = "MonkeyAnnotation"; + private const string PinId = "PinAnnotation"; + + public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, IMKAnnotation annotation) + { + MKAnnotationView result = null; + + if (annotation is MKUserLocation) + return result; + + if (annotation is MonkeyAnnotation) { + // show monkey annotation + result = mapView.DequeueReusableAnnotation (MonkeyId) ?? new MKAnnotationView (annotation, MonkeyId); + result.Draggable = true; + result.CanShowCallout = true; + result.Image = UIImage.FromBundle ("Monkey"); + result.RightCalloutAccessoryView = UIButton.FromType (UIButtonType.DetailDisclosure); + } else { + // show pin annotation + var annotationView = mapView.DequeueReusableAnnotation (PinId) as MKPinAnnotationView ?? new MKPinAnnotationView (annotation, PinId); + annotationView.PinTintColor = UIColor.Red; + annotationView.CanShowCallout = true; + + result = annotationView; + } + + return result; + } + + public override void CalloutAccessoryControlTapped (MKMapView mapView, MKAnnotationView view, UIControl control) + { + if (view.Annotation is MonkeyAnnotation monkeyAnnotation) { + var alert = UIAlertController.Create ("Monkey Annotation", monkeyAnnotation.Title, UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + UIApplication.SharedApplication.Windows [0].RootViewController.PresentViewController (alert, true, null); + } + } + + public override MKOverlayRenderer OverlayRenderer (MKMapView mapView, IMKOverlay overlay) + { + return new MKCircleRenderer (overlay as MKCircle) { + FillColor = UIColor.Red, + Alpha = 0.4f + }; + } + } +} diff --git a/MapDemo/MapDemo/MonkeyAnnotation.cs b/MapDemo/MapDemo/MonkeyAnnotation.cs index 918c63e7a..a35a5f7cb 100644 --- a/MapDemo/MapDemo/MonkeyAnnotation.cs +++ b/MapDemo/MapDemo/MonkeyAnnotation.cs @@ -1,23 +1,21 @@ - -namespace MapDemo -{ - using CoreLocation; - using MapKit; - public class MonkeyAnnotation : MKAnnotation - { - private CLLocationCoordinate2D coordinate; +namespace MapDemo { + using CoreLocation; + using MapKit; - private readonly string title; + public class MonkeyAnnotation : MKAnnotation { + private CLLocationCoordinate2D coordinate; - public MonkeyAnnotation(string title, CLLocationCoordinate2D coordinate) - { - this.title = title; - this.coordinate = coordinate; - } + private readonly string title; - public override string Title => title; + public MonkeyAnnotation (string title, CLLocationCoordinate2D coordinate) + { + this.title = title; + this.coordinate = coordinate; + } - public override CLLocationCoordinate2D Coordinate => coordinate; - } -} \ No newline at end of file + public override string Title => title; + + public override CLLocationCoordinate2D Coordinate => coordinate; + } +} diff --git a/MapDemo/MapDemo/SearchResultsViewController.cs b/MapDemo/MapDemo/SearchResultsViewController.cs index 8925d8cb1..006dae2e6 100644 --- a/MapDemo/MapDemo/SearchResultsViewController.cs +++ b/MapDemo/MapDemo/SearchResultsViewController.cs @@ -1,86 +1,76 @@ -using Foundation; +using Foundation; using MapKit; using System; using System.Collections.Generic; using UIKit; -namespace MapDemo -{ - public class SearchResultsUpdator : UISearchResultsUpdating - { - public event Action UpdateSearchResults; +namespace MapDemo { + public class SearchResultsUpdator : UISearchResultsUpdating { + public event Action UpdateSearchResults; - public override void UpdateSearchResultsForSearchController(UISearchController searchController) - { - UpdateSearchResults?.Invoke(searchController.SearchBar.Text); - } - } + public override void UpdateSearchResultsForSearchController (UISearchController searchController) + { + UpdateSearchResults?.Invoke (searchController.SearchBar.Text); + } + } - public class SearchResultsViewController : UITableViewController - { - private const string CellIdentifier = "mapItemCellId"; + public class SearchResultsViewController : UITableViewController { + private const string CellIdentifier = "mapItemCellId"; - private List items; + private List items; - private MKMapView map; + private MKMapView map; - public SearchResultsViewController(MKMapView map) - { - this.map = map; - } + public SearchResultsViewController (MKMapView map) + { + this.map = map; + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return items?.Count ?? 0; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return items?.Count ?? 0; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(CellIdentifier) ?? new UITableViewCell(); - cell.TextLabel.Text = items[indexPath.Row].Name; - return cell; - } + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (CellIdentifier) ?? new UITableViewCell (); + cell.TextLabel.Text = items [indexPath.Row].Name; + return cell; + } - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - // add item to map - var coordinate = items[indexPath.Row].Placemark.Location.Coordinate; - map.AddAnnotations(new MKPointAnnotation - { - Coordinate = coordinate, - Title = items[indexPath.Row].Name, - }); + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + // add item to map + var coordinate = items [indexPath.Row].Placemark.Location.Coordinate; + map.AddAnnotations (new MKPointAnnotation { + Coordinate = coordinate, + Title = items [indexPath.Row].Name, + }); - map.SetCenterCoordinate(coordinate, true); - DismissViewController(false, null); - } + map.SetCenterCoordinate (coordinate, true); + DismissViewController (false, null); + } - public void UpdateSearchResults(string query) - { - if (!string.IsNullOrEmpty(query)) - { - // create search request - var searchRequest = new MKLocalSearchRequest - { - NaturalLanguageQuery = query, - Region = new MKCoordinateRegion(map.UserLocation.Coordinate, new MKCoordinateSpan(0.25, 0.25)) - }; + public void UpdateSearchResults (string query) + { + if (!string.IsNullOrEmpty (query)) { + // create search request + var searchRequest = new MKLocalSearchRequest { + NaturalLanguageQuery = query, + Region = new MKCoordinateRegion (map.UserLocation.Coordinate, new MKCoordinateSpan (0.25, 0.25)) + }; - // perform search - var localSearch = new MKLocalSearch(searchRequest); - localSearch.Start((response, error) => - { - if (response != null && error == null) - { - items = new List(response.MapItems); - this.TableView.ReloadData(); - } - else - { - Console.WriteLine($"local search error: {error?.LocalizedDescription ?? ""}"); - } - }); - } - } - } -} \ No newline at end of file + // perform search + var localSearch = new MKLocalSearch (searchRequest); + localSearch.Start ((response, error) => { + if (response != null && error == null) { + items = new List (response.MapItems); + this.TableView.ReloadData (); + } else { + Console.WriteLine ($"local search error: {error?.LocalizedDescription ?? ""}"); + } + }); + } + } + } +} diff --git a/MapKitSearch/MapKitSearch/AppDelegate.cs b/MapKitSearch/MapKitSearch/AppDelegate.cs index e16571906..70772ac24 100644 --- a/MapKitSearch/MapKitSearch/AppDelegate.cs +++ b/MapKitSearch/MapKitSearch/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace MapKitSearch -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace MapKitSearch { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/MapKitSearch/MapKitSearch/Main.cs b/MapKitSearch/MapKitSearch/Main.cs index 27aad596f..5fdfcaaec 100644 --- a/MapKitSearch/MapKitSearch/Main.cs +++ b/MapKitSearch/MapKitSearch/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace MapKitSearch -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace MapKitSearch { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/MapKitSearch/MapKitSearch/SearchResultsController.cs b/MapKitSearch/MapKitSearch/SearchResultsController.cs index f4c80bd18..3d6a616f5 100644 --- a/MapKitSearch/MapKitSearch/SearchResultsController.cs +++ b/MapKitSearch/MapKitSearch/SearchResultsController.cs @@ -1,46 +1,44 @@ -using Foundation; +using Foundation; using MapKit; -using System; -using UIKit; - -namespace MapKitSearch -{ - public partial class SearchResultsController : UITableViewController - { - private const string CellIdentifier = "cellIdentifier"; - - public SearchResultsController (IntPtr handle) : base (handle) { } - - public MKMapItem[] Items { get; set; } - - public string Query { get; set; } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - NavigationItem.Title = Query; - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return Items.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(CellIdentifier, indexPath); - - var item = Items[indexPath.Row]; - cell.TextLabel.Text = item.Name; - cell.DetailTextLabel.Text = item.PhoneNumber; - - return cell; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - Items[indexPath.Row].OpenInMaps(); - tableView.DeselectRow(indexPath, false); - } - } -} \ No newline at end of file +using System; +using UIKit; + +namespace MapKitSearch { + public partial class SearchResultsController : UITableViewController { + private const string CellIdentifier = "cellIdentifier"; + + public SearchResultsController (IntPtr handle) : base (handle) { } + + public MKMapItem [] Items { get; set; } + + public string Query { get; set; } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + NavigationItem.Title = Query; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return Items.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (CellIdentifier, indexPath); + + var item = Items [indexPath.Row]; + cell.TextLabel.Text = item.Name; + cell.DetailTextLabel.Text = item.PhoneNumber; + + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + Items [indexPath.Row].OpenInMaps (); + tableView.DeselectRow (indexPath, false); + } + } +} diff --git a/MapKitSearch/MapKitSearch/ViewController.cs b/MapKitSearch/MapKitSearch/ViewController.cs index 8e860a669..2ff85f21e 100644 --- a/MapKitSearch/MapKitSearch/ViewController.cs +++ b/MapKitSearch/MapKitSearch/ViewController.cs @@ -1,133 +1,116 @@ -using CoreLocation; +using CoreLocation; using Foundation; using MapKit; using System; using System.Threading.Tasks; using UIKit; -namespace MapKitSearch -{ - public partial class ViewController : UIViewController, IUITextFieldDelegate - { - private const string SearchSegueIdentifier = "openSearchResults"; - - private CLLocationManager locationManager; - - private MKMapItem[] searchItems; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - SearchButton.Enabled = false; - QueryTextField.Delegate = this; - LocationTextField.Delegate = this; - - GetLocationButton.Enabled = CLLocationManager.LocationServicesEnabled; - QueryTextField.AddTarget((sender, e) => SearchButton.Enabled = !string.IsNullOrEmpty(QueryTextField.Text), - UIControlEvent.EditingChanged); - - if (CLLocationManager.LocationServicesEnabled) - { - locationManager = new CLLocationManager(); - locationManager.RequestWhenInUseAuthorization(); - locationManager.LocationsUpdated += (sender, e) => - { - locationManager.StopUpdatingLocation(); - var location = e.Locations[e.Locations.Length - 1]; - LocationTextField.Text = string.Format("{0:F4}, {1:F4}", location.Coordinate.Latitude, location.Coordinate.Longitude); - }; - } - } - - partial void GetCurrentLocation(UIButton sender) - { - locationManager.StartUpdatingLocation(); - } - - async partial void Search(UIButton sender) - { - await SearchAsync(QueryTextField.Text, LocationTextField.Text).ConfigureAwait(false); - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if(!string.IsNullOrEmpty(segue?.Identifier) && segue.Identifier == SearchSegueIdentifier) - { - if(segue.DestinationViewController is SearchResultsController searchResultsController) - { - searchResultsController.Query = QueryTextField.Text; - searchResultsController.Items = searchItems; - } - } - } - - private async Task SearchAsync(string what, string where) - { - var span = new MKCoordinateSpan(0.25, 0.25); - var request = new MKLocalSearchRequest - { - NaturalLanguageQuery = what, - Region = new MKCoordinateRegion(ParseCoordinates(where), span), - }; - - var search = new MKLocalSearch(request); - MKLocalSearchResponse response = null; - - try - { - response = await search.StartAsync(); - } - catch (Exception ex) - { - System.Diagnostics.Debug.WriteLine(ex); - } - - if (response != null) - { - searchItems = response.MapItems; - PerformSegue(SearchSegueIdentifier, this); - } - } - - private CLLocationCoordinate2D ParseCoordinates(string coordinates) - { - var result = new CLLocationCoordinate2D(); - - if (!string.IsNullOrEmpty(coordinates)) - { - var values = coordinates.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - if (values.Length == 2) - { - if (double.TryParse(values[0], out double latitude) && - double.TryParse(values[1], out double longitude)) - { - result = new CLLocationCoordinate2D(latitude, longitude); - } - } - } - - return result; - } - - #region IUITextFieldDelegate - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - if (textField == QueryTextField) - { - LocationTextField.BecomeFirstResponder(); - } - else - { - textField.ResignFirstResponder(); - } - - return true; - } - - #endregion - } -} \ No newline at end of file +namespace MapKitSearch { + public partial class ViewController : UIViewController, IUITextFieldDelegate { + private const string SearchSegueIdentifier = "openSearchResults"; + + private CLLocationManager locationManager; + + private MKMapItem [] searchItems; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + SearchButton.Enabled = false; + QueryTextField.Delegate = this; + LocationTextField.Delegate = this; + + GetLocationButton.Enabled = CLLocationManager.LocationServicesEnabled; + QueryTextField.AddTarget ((sender, e) => SearchButton.Enabled = !string.IsNullOrEmpty (QueryTextField.Text), + UIControlEvent.EditingChanged); + + if (CLLocationManager.LocationServicesEnabled) { + locationManager = new CLLocationManager (); + locationManager.RequestWhenInUseAuthorization (); + locationManager.LocationsUpdated += (sender, e) => { + locationManager.StopUpdatingLocation (); + var location = e.Locations [e.Locations.Length - 1]; + LocationTextField.Text = string.Format ("{0:F4}, {1:F4}", location.Coordinate.Latitude, location.Coordinate.Longitude); + }; + } + } + + partial void GetCurrentLocation (UIButton sender) + { + locationManager.StartUpdatingLocation (); + } + + async partial void Search (UIButton sender) + { + await SearchAsync (QueryTextField.Text, LocationTextField.Text).ConfigureAwait (false); + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (!string.IsNullOrEmpty (segue?.Identifier) && segue.Identifier == SearchSegueIdentifier) { + if (segue.DestinationViewController is SearchResultsController searchResultsController) { + searchResultsController.Query = QueryTextField.Text; + searchResultsController.Items = searchItems; + } + } + } + + private async Task SearchAsync (string what, string where) + { + var span = new MKCoordinateSpan (0.25, 0.25); + var request = new MKLocalSearchRequest { + NaturalLanguageQuery = what, + Region = new MKCoordinateRegion (ParseCoordinates (where), span), + }; + + var search = new MKLocalSearch (request); + MKLocalSearchResponse response = null; + + try { + response = await search.StartAsync (); + } catch (Exception ex) { + System.Diagnostics.Debug.WriteLine (ex); + } + + if (response != null) { + searchItems = response.MapItems; + PerformSegue (SearchSegueIdentifier, this); + } + } + + private CLLocationCoordinate2D ParseCoordinates (string coordinates) + { + var result = new CLLocationCoordinate2D (); + + if (!string.IsNullOrEmpty (coordinates)) { + var values = coordinates.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); + if (values.Length == 2) { + if (double.TryParse (values [0], out double latitude) && + double.TryParse (values [1], out double longitude)) { + result = new CLLocationCoordinate2D (latitude, longitude); + } + } + } + + return result; + } + + #region IUITextFieldDelegate + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + if (textField == QueryTextField) { + LocationTextField.BecomeFirstResponder (); + } else { + textField.ResignFirstResponder (); + } + + return true; + } + + #endregion + } +} diff --git a/MapsWalkthrough/MapsWalkthrough/AppDelegate.cs b/MapsWalkthrough/MapsWalkthrough/AppDelegate.cs index 1666d8232..812385a4f 100755 --- a/MapsWalkthrough/MapsWalkthrough/AppDelegate.cs +++ b/MapsWalkthrough/MapsWalkthrough/AppDelegate.cs @@ -1,35 +1,33 @@ -using Foundation; -using UIKit; - -namespace MapsWalkthrough -{ +using Foundation; +using UIKit; + +namespace MapsWalkthrough { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; - EvolveMapViewController viewController; - - // - // This method is invoked when the application has loaded and is ready to run. In this - // method you should instantiate the window, load the UI into it and then make the window - // visible. - // - // You have 17 seconds to return from this method, or iOS will terminate your application. - // - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); - - viewController = new EvolveMapViewController (); - window.RootViewController = viewController; - window.MakeKeyAndVisible (); - - return true; - } - } -} - + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; + EvolveMapViewController viewController; + + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); + + viewController = new EvolveMapViewController (); + window.RootViewController = viewController; + window.MakeKeyAndVisible (); + + return true; + } + } +} + diff --git a/MapsWalkthrough/MapsWalkthrough/ConferenceAnnotation.cs b/MapsWalkthrough/MapsWalkthrough/ConferenceAnnotation.cs index ef36c027b..6bb22ae37 100755 --- a/MapsWalkthrough/MapsWalkthrough/ConferenceAnnotation.cs +++ b/MapsWalkthrough/MapsWalkthrough/ConferenceAnnotation.cs @@ -1,30 +1,28 @@ -using CoreLocation; -using MapKit; - -namespace MapsWalkthrough -{ - public class ConferenceAnnotation : MKAnnotation - { - string title; - CLLocationCoordinate2D coord; - - public ConferenceAnnotation (string title, CLLocationCoordinate2D coord) - { - this.title = title; - this.coord = coord; - } - - public override string Title { - get { - return title; - } - } - - public override CLLocationCoordinate2D Coordinate { - get { - return coord; - } - } - } -} - +using CoreLocation; +using MapKit; + +namespace MapsWalkthrough { + public class ConferenceAnnotation : MKAnnotation { + string title; + CLLocationCoordinate2D coord; + + public ConferenceAnnotation (string title, CLLocationCoordinate2D coord) + { + this.title = title; + this.coord = coord; + } + + public override string Title { + get { + return title; + } + } + + public override CLLocationCoordinate2D Coordinate { + get { + return coord; + } + } + } +} + diff --git a/MapsWalkthrough/MapsWalkthrough/EvolveMapViewController.cs b/MapsWalkthrough/MapsWalkthrough/EvolveMapViewController.cs index 0a78adc22..2ee30c8e4 100755 --- a/MapsWalkthrough/MapsWalkthrough/EvolveMapViewController.cs +++ b/MapsWalkthrough/MapsWalkthrough/EvolveMapViewController.cs @@ -1,79 +1,77 @@ -using System; -using CoreLocation; -using MapKit; -using UIKit; - -namespace MapsWalkthrough -{ - public partial class EvolveMapViewController : UIViewController - { - MKMapView map; - MapDelegate mapDelegate; - CLLocationManager locationManager = new CLLocationManager(); - - public override void LoadView () - { - map = new MKMapView (UIScreen.MainScreen.Bounds); - View = map; - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - if (UIDevice.CurrentDevice.CheckSystemVersion(8,0)){ - locationManager.RequestWhenInUseAuthorization (); - } - - - - // change map type, show user location and allow zooming and panning - map.MapType = MKMapType.Standard; - map.ShowsUserLocation = true; - map.ZoomEnabled = true; - map.ScrollEnabled = true; - - // set map center and region - double lat = 30.2652233534254; - double lon = -97.73815460962083; - CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D (lat, lon); - MKCoordinateRegion mapRegion = MKCoordinateRegion.FromDistance (mapCenter, 100, 100); - map.CenterCoordinate = mapCenter; - map.Region = mapRegion; - - // set the map delegate - mapDelegate = new MapDelegate (); - map.Delegate = mapDelegate; - - // add a custom annotation at the map center - map.AddAnnotations (new ConferenceAnnotation ("Evolve Conference", mapCenter)); - - // add an overlay of the hotel - MKPolygon hotelOverlay = MKPolygon.FromCoordinates ( - new CLLocationCoordinate2D[] { - new CLLocationCoordinate2D(30.2649977168594, -97.73863627705), - new CLLocationCoordinate2D(30.2648461170005, -97.7381627734755), - new CLLocationCoordinate2D(30.2648355402574, -97.7381750192576), - new CLLocationCoordinate2D(30.2647791309417, -97.7379872505988), - new CLLocationCoordinate2D(30.2654525150319, -97.7377341711021), - new CLLocationCoordinate2D(30.2654807195004, -97.7377994819399), - new CLLocationCoordinate2D(30.2655089239607, -97.7377994819399), - new CLLocationCoordinate2D(30.2656428950368, -97.738346460207), - new CLLocationCoordinate2D(30.2650364981811, -97.7385709662122), - new CLLocationCoordinate2D(30.2650470749025, -97.7386199493406) - }); - - map.AddOverlay (hotelOverlay); - - UITapGestureRecognizer tap = new UITapGestureRecognizer (g => { - var pt = g.LocationInView (map); - CLLocationCoordinate2D tapCoord = map.ConvertPoint (pt, map); - - Console.WriteLine ("new CLLocationCoordinate2D({0}, {1}),", tapCoord.Latitude, tapCoord.Longitude); - }); - - map.AddGestureRecognizer (tap); - } - } -} - +using System; +using CoreLocation; +using MapKit; +using UIKit; + +namespace MapsWalkthrough { + public partial class EvolveMapViewController : UIViewController { + MKMapView map; + MapDelegate mapDelegate; + CLLocationManager locationManager = new CLLocationManager (); + + public override void LoadView () + { + map = new MKMapView (UIScreen.MainScreen.Bounds); + View = map; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) { + locationManager.RequestWhenInUseAuthorization (); + } + + + + // change map type, show user location and allow zooming and panning + map.MapType = MKMapType.Standard; + map.ShowsUserLocation = true; + map.ZoomEnabled = true; + map.ScrollEnabled = true; + + // set map center and region + double lat = 30.2652233534254; + double lon = -97.73815460962083; + CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D (lat, lon); + MKCoordinateRegion mapRegion = MKCoordinateRegion.FromDistance (mapCenter, 100, 100); + map.CenterCoordinate = mapCenter; + map.Region = mapRegion; + + // set the map delegate + mapDelegate = new MapDelegate (); + map.Delegate = mapDelegate; + + // add a custom annotation at the map center + map.AddAnnotations (new ConferenceAnnotation ("Evolve Conference", mapCenter)); + + // add an overlay of the hotel + MKPolygon hotelOverlay = MKPolygon.FromCoordinates ( + new CLLocationCoordinate2D [] { + new CLLocationCoordinate2D(30.2649977168594, -97.73863627705), + new CLLocationCoordinate2D(30.2648461170005, -97.7381627734755), + new CLLocationCoordinate2D(30.2648355402574, -97.7381750192576), + new CLLocationCoordinate2D(30.2647791309417, -97.7379872505988), + new CLLocationCoordinate2D(30.2654525150319, -97.7377341711021), + new CLLocationCoordinate2D(30.2654807195004, -97.7377994819399), + new CLLocationCoordinate2D(30.2655089239607, -97.7377994819399), + new CLLocationCoordinate2D(30.2656428950368, -97.738346460207), + new CLLocationCoordinate2D(30.2650364981811, -97.7385709662122), + new CLLocationCoordinate2D(30.2650470749025, -97.7386199493406) + }); + + map.AddOverlay (hotelOverlay); + + UITapGestureRecognizer tap = new UITapGestureRecognizer (g => { + var pt = g.LocationInView (map); + CLLocationCoordinate2D tapCoord = map.ConvertPoint (pt, map); + + Console.WriteLine ("new CLLocationCoordinate2D({0}, {1}),", tapCoord.Latitude, tapCoord.Longitude); + }); + + map.AddGestureRecognizer (tap); + } + } +} + diff --git a/MapsWalkthrough/MapsWalkthrough/Main.cs b/MapsWalkthrough/MapsWalkthrough/Main.cs index b11ec86b6..fcec7f42d 100755 --- a/MapsWalkthrough/MapsWalkthrough/Main.cs +++ b/MapsWalkthrough/MapsWalkthrough/Main.cs @@ -1,15 +1,13 @@ -using UIKit; - -namespace MapsWalkthrough -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } -} +using UIKit; + +namespace MapsWalkthrough { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/MapsWalkthrough/MapsWalkthrough/MapDelegate.cs b/MapsWalkthrough/MapsWalkthrough/MapDelegate.cs index d56df2444..ccd590013 100755 --- a/MapsWalkthrough/MapsWalkthrough/MapDelegate.cs +++ b/MapsWalkthrough/MapsWalkthrough/MapDelegate.cs @@ -1,74 +1,73 @@ -using System; -using MapKit; -using UIKit; -using CoreGraphics; - -namespace MapsWalkthrough -{ - class MapDelegate : MKMapViewDelegate - { - static string annotationId = "ConferenceAnnotation"; - UIImageView venueView; - UIImage venueImage; - - public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, IMKAnnotation annotation) - { - MKAnnotationView annotationView = null; - - if (annotation is MKUserLocation) - return null; - - if (annotation is ConferenceAnnotation) { - - // show conference annotation - annotationView = mapView.DequeueReusableAnnotation (annotationId); - - if (annotationView == null) - annotationView = new MKAnnotationView (annotation, annotationId); - - annotationView.Image = UIImage.FromFile ("conference.png"); - annotationView.CanShowCallout = true; - } - - return annotationView; - } - - public override void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView view) - { - // show an image view when the conference annotation view is selected - if (view.Annotation is ConferenceAnnotation) { - - venueView = new UIImageView (); - venueView.ContentMode = UIViewContentMode.ScaleAspectFit; - venueImage = UIImage.FromFile ("venue.png"); - venueView.Image = venueImage; - view.AddSubview (venueView); - - UIView.Animate (0.4, () => { - venueView.Frame = new CGRect (-75, -75, 200, 200); }); - } - } - - public override void DidDeselectAnnotationView (MKMapView mapView, MKAnnotationView view) - { - // remove the image view when the conference annotation is deselected - if (view.Annotation is ConferenceAnnotation) { - - venueView.RemoveFromSuperview (); - venueView.Dispose (); - venueView = null; - } - } - - public override MKOverlayView GetViewForOverlay (MKMapView mapView, IMKOverlay overlay) - { - // return a view for the polygon - MKPolygon polygon = overlay as MKPolygon; - MKPolygonView polygonView = new MKPolygonView (polygon); - polygonView.FillColor = UIColor.Blue; - polygonView.StrokeColor = UIColor.Red; - return polygonView; - } - } -} - +using System; +using MapKit; +using UIKit; +using CoreGraphics; + +namespace MapsWalkthrough { + class MapDelegate : MKMapViewDelegate { + static string annotationId = "ConferenceAnnotation"; + UIImageView venueView; + UIImage venueImage; + + public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, IMKAnnotation annotation) + { + MKAnnotationView annotationView = null; + + if (annotation is MKUserLocation) + return null; + + if (annotation is ConferenceAnnotation) { + + // show conference annotation + annotationView = mapView.DequeueReusableAnnotation (annotationId); + + if (annotationView == null) + annotationView = new MKAnnotationView (annotation, annotationId); + + annotationView.Image = UIImage.FromFile ("conference.png"); + annotationView.CanShowCallout = true; + } + + return annotationView; + } + + public override void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView view) + { + // show an image view when the conference annotation view is selected + if (view.Annotation is ConferenceAnnotation) { + + venueView = new UIImageView (); + venueView.ContentMode = UIViewContentMode.ScaleAspectFit; + venueImage = UIImage.FromFile ("venue.png"); + venueView.Image = venueImage; + view.AddSubview (venueView); + + UIView.Animate (0.4, () => { + venueView.Frame = new CGRect (-75, -75, 200, 200); + }); + } + } + + public override void DidDeselectAnnotationView (MKMapView mapView, MKAnnotationView view) + { + // remove the image view when the conference annotation is deselected + if (view.Annotation is ConferenceAnnotation) { + + venueView.RemoveFromSuperview (); + venueView.Dispose (); + venueView = null; + } + } + + public override MKOverlayView GetViewForOverlay (MKMapView mapView, IMKOverlay overlay) + { + // return a view for the polygon + MKPolygon polygon = overlay as MKPolygon; + MKPolygonView polygonView = new MKPolygonView (polygon); + polygonView.FillColor = UIColor.Blue; + polygonView.StrokeColor = UIColor.Red; + return polygonView; + } + } +} + diff --git a/MediaNotes/MediaNotes/AppDelegate.cs b/MediaNotes/MediaNotes/AppDelegate.cs index caf189c1a..bc6da7304 100644 --- a/MediaNotes/MediaNotes/AppDelegate.cs +++ b/MediaNotes/MediaNotes/AppDelegate.cs @@ -7,11 +7,9 @@ using UIKit; using AssetsLibrary; -namespace MediaNotes -{ - public class Application - { - static void Main (string[] args) +namespace MediaNotes { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } @@ -21,8 +19,7 @@ static void Main (string[] args) // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; static List photoAssets; @@ -66,7 +63,7 @@ public void InitializePhotos () photoAssets = new List (PHOTO_ASSETS_CAPACITY); int photoIndex = 0; bool syncContentController = true; - assetsLibrary.Enumerate (ALAssetsGroupType.Album, ( ALAssetsGroup group, ref bool stop) => { + assetsLibrary.Enumerate (ALAssetsGroupType.Album, (ALAssetsGroup group, ref bool stop) => { if (group != null) { @@ -93,7 +90,7 @@ public void InitializePhotos () if (currentPhotoIndex == 0) { setCurrentPhotoToIndex (0); } - ((PhotoViewController)(ViewController.contentController)).Synchronize (currentPhotoIndex >= 0); + ((PhotoViewController) (ViewController.contentController)).Synchronize (currentPhotoIndex >= 0); }); } }, @@ -116,8 +113,7 @@ public static void setCurrentPhotoToIndex (int index) currentPhotoIndex = index; } - public class MyDatasource : PNDataSourceProtocol - { + public class MyDatasource : PNDataSourceProtocol { public void ProceedToNextItem () { if (photoAssets.Count > 0) { @@ -129,7 +125,7 @@ public void ProceedToNextItem () public void ProceedToPreviousItem () { if (photoAssets.Count > 0) { - currentPhotoIndex --; + currentPhotoIndex--; setCurrentPhotoToIndex ((currentPhotoIndex < 0) ? photoAssets.Count - 1 : currentPhotoIndex); } } @@ -142,7 +138,7 @@ public UIImage ImageForCurrentItem () public NSUrl UrlForCurrentItem () { NSDictionary map = currentAsset.UtiToUrlDictionary; - return (NSUrl)map.ObjectForKey (new NSString ("public.jpeg")); + return (NSUrl) map.ObjectForKey (new NSString ("public.jpeg")); } } } diff --git a/MediaNotes/MediaNotes/PhotoNotes/PNDataSourceProtocol.cs b/MediaNotes/MediaNotes/PhotoNotes/PNDataSourceProtocol.cs index 445c9ed27..5986be2f9 100644 --- a/MediaNotes/MediaNotes/PhotoNotes/PNDataSourceProtocol.cs +++ b/MediaNotes/MediaNotes/PhotoNotes/PNDataSourceProtocol.cs @@ -2,10 +2,8 @@ using UIKit; using Foundation; -namespace MediaNotes -{ - public interface PNDataSourceProtocol - { +namespace MediaNotes { + public interface PNDataSourceProtocol { UIImage ImageForCurrentItem (); NSUrl UrlForCurrentItem (); void ProceedToNextItem (); diff --git a/MediaNotes/MediaNotes/PhotoNotes/PhotoViewController.cs b/MediaNotes/MediaNotes/PhotoNotes/PhotoViewController.cs index 81c5417cb..6f93b7c54 100644 --- a/MediaNotes/MediaNotes/PhotoNotes/PhotoViewController.cs +++ b/MediaNotes/MediaNotes/PhotoNotes/PhotoViewController.cs @@ -9,12 +9,12 @@ using Foundation; using UIKit; -namespace MediaNotes -{ +namespace MediaNotes { [Register ("PNContainerView")] public class PNContainerView : UIView { - public PNContainerView (IntPtr ptr) : base (ptr) { + public PNContainerView (IntPtr ptr) : base (ptr) + { } @@ -25,18 +25,17 @@ static bool Requires () } } - public partial class PhotoViewController : UIViewController, YYCommentNotifying - { + public partial class PhotoViewController : UIViewController, YYCommentNotifying { static Dictionary photoMap; static NSUrl currentPhotoUrl; bool syncIsNeeded; YYCommentViewController ycommentView; PNDataSourceProtocol datasource; -# if USE_AUTOLAYOUT +#if USE_AUTOLAYOUT NSLayoutConstraint toolbarTopConstraint; #endif - public PNDataSourceProtocol Datasource{ get { return datasource; } set { datasource = value; } } + public PNDataSourceProtocol Datasource { get { return datasource; } set { datasource = value; } } public PhotoViewController () : base ("PhotoViewController", null) { @@ -45,7 +44,7 @@ public PhotoViewController () : base ("PhotoViewController", null) public PhotoViewController (string nibName, NSBundle bundle) : base (NSObjectFlag.Empty) { photoMap = new Dictionary (); -# if USE_FULLSCREEN_LAYOUT +#if USE_FULLSCREEN_LAYOUT WantsFullScreenLayout = true; #endif } @@ -63,21 +62,21 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); -# if USE_AUTOLAYOUT +#if USE_AUTOLAYOUT toolbar.TranslatesAutoresizingMaskIntoConstraints = false; photoImageView.TranslatesAutoresizingMaskIntoConstraints = false; -# endif // Perform any additional setup after loading the view, typically from a nib. +#endif // Perform any additional setup after loading the view, typically from a nib. } -/*# if OVERRIDE_SUPPORTED_ORIENTATIONS + /*# if OVERRIDE_SUPPORTED_ORIENTATIONS - public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) - { - return UIInterfaceOrientationMask.AllButUpsideDown; - } + public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) + { + return UIInterfaceOrientationMask.AllButUpsideDown; + } -# endif*/ + # endif*/ public override void ViewWillLayoutSubviews () { @@ -87,7 +86,7 @@ public override void ViewWillLayoutSubviews () } } -# if USE_AUTOLAYOUT +#if USE_AUTOLAYOUT float GetStatusBarHeight (UIApplication app) { if (app.StatusBarOrientation == UIInterfaceOrientation.LandscapeLeft || app.StatusBarOrientation == UIInterfaceOrientation.LandscapeRight) @@ -101,44 +100,44 @@ public override void UpdateViewConstraints () if (toolbarTopConstraint == null) { var tconstraint2 = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Top, NSLayoutRelation.Equal, - View, NSLayoutAttribute.Top, 1.0f, toolbarVerticalOffset); + View, NSLayoutAttribute.Top, 1.0f, toolbarVerticalOffset); toolbarTopConstraint = tconstraint2; var tconstraint1 = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Width, NSLayoutRelation.Equal, - View, NSLayoutAttribute.Width, 1.0f, 0.0f); + View, NSLayoutAttribute.Width, 1.0f, 0.0f); var tconstraint3 = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Left, NSLayoutRelation.Equal, - View, NSLayoutAttribute.Left, 1.0f, 0.0f); + View, NSLayoutAttribute.Left, 1.0f, 0.0f); var tconstraint4 = NSLayoutConstraint.Create (toolbar, NSLayoutAttribute.Height, NSLayoutRelation.Equal, - toolbar, NSLayoutAttribute.Height, 0.0f, 44.0f); + toolbar, NSLayoutAttribute.Height, 0.0f, 44.0f); var constraint0 = NSLayoutConstraint.Create (photoImageView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, - photoImageView, NSLayoutAttribute.Height, 1.0f, 0.0f); + photoImageView, NSLayoutAttribute.Height, 1.0f, 0.0f); var constraint1 = NSLayoutConstraint.Create (photoImageView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, - View, NSLayoutAttribute.CenterX, 1.0f, 0.0f); + View, NSLayoutAttribute.CenterX, 1.0f, 0.0f); NSLayoutConstraint constraint2; if (WantsFullScreenLayout) { constraint2 = NSLayoutConstraint.Create (photoImageView, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, View, - NSLayoutAttribute.Top, 1.0f, 0.0f); + NSLayoutAttribute.Top, 1.0f, 0.0f); } else { constraint2 = NSLayoutConstraint.Create (photoImageView, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, toolbar, - NSLayoutAttribute.Bottom, 1.0f, 0.0f); + NSLayoutAttribute.Bottom, 1.0f, 0.0f); } NSLayoutConstraint constraint3 = NSLayoutConstraint.Create (photoImageView, NSLayoutAttribute.Bottom, NSLayoutRelation.LessThanOrEqual, - View, NSLayoutAttribute.Bottom, 1.0f, 0.0f); + View, NSLayoutAttribute.Bottom, 1.0f, 0.0f); - View.AddConstraints (new NSLayoutConstraint[] {tconstraint1, tconstraint2, tconstraint3, tconstraint4, constraint0, constraint1, constraint2, constraint3}); + View.AddConstraints (new NSLayoutConstraint [] { tconstraint1, tconstraint2, tconstraint3, tconstraint4, constraint0, constraint1, constraint2, constraint3 }); toolbarTopConstraint.Constant = toolbarVerticalOffset; } base.UpdateViewConstraints (); } -# endif +#endif public void Synchronize () { placeHolderActivityView.StopAnimating (); @@ -200,11 +199,11 @@ public void Synchronize (bool initializationSucceeded) currentPhotoUrl = datasource.UrlForCurrentItem (); var yvc = ParentViewController as YYCommentContainerViewController; ycommentView = yvc.YYcommentViewController (); - ycommentView .AssociatedObjectDidChange (this); + ycommentView.AssociatedObjectDidChange (this); UIView.Animate (.25, () => { - placeHolderActivityView.Alpha = 0.0f; - }, + placeHolderActivityView.Alpha = 0.0f; + }, () => { placeHolderView.RemoveFromSuperview (); placeHolderActivityView = null; @@ -212,8 +211,7 @@ public void Synchronize (bool initializationSucceeded) placeHolderLabel = null; }); - } - else { + } else { placeHolderActivityView.StopAnimating (); placeHolderLabel.Text = "No Photos"; @@ -224,13 +222,13 @@ partial void NextPhoto (UIKit.UIBarButtonItem sender) { datasource.ProceedToNextItem (); - if(currentPhotoUrl != null){ + if (currentPhotoUrl != null) { currentPhotoUrl = datasource.UrlForCurrentItem (); ycommentView.AssociatedObjectDidChange (this); UIView.Animate (.25, () => { - photoImageView.Alpha = 0.0f; - }, + photoImageView.Alpha = 0.0f; + }, () => { photoImageView.Image = datasource.ImageForCurrentItem (); UIView.Animate (.25, () => { @@ -240,7 +238,7 @@ partial void NextPhoto (UIKit.UIBarButtonItem sender) } } - partial void PreviousPhoto (UIKit.UIBarButtonItem sender) + partial void PreviousPhoto (UIKit.UIBarButtonItem sender) { datasource.ProceedToPreviousItem (); if (currentPhotoUrl != null) { diff --git a/MediaNotes/MediaNotes/Shared Files/YYCommentContainerViewController.cs b/MediaNotes/MediaNotes/Shared Files/YYCommentContainerViewController.cs index 1796bb9f4..ecf733466 100644 --- a/MediaNotes/MediaNotes/Shared Files/YYCommentContainerViewController.cs +++ b/MediaNotes/MediaNotes/Shared Files/YYCommentContainerViewController.cs @@ -7,11 +7,9 @@ using UIKit; using Foundation; -namespace MediaNotes -{ +namespace MediaNotes { [Register ("YYCommentContainerView")] - public class YYCommentContainerView : UIView - { + public class YYCommentContainerView : UIView { public YYCommentContainerView (IntPtr ptr) : base (ptr) { @@ -24,8 +22,7 @@ static bool Requires () } } - public class YYCommentContainerViewController : UIViewController - { + public class YYCommentContainerViewController : UIViewController { public YYCommentViewController commentViewController { get; set; } bool commentViewIsVisible; @@ -46,10 +43,10 @@ public YYCommentContainerViewController (UIViewController child) : base () UIApplication.SharedApplication.SetStatusBarStyle (UIStatusBarStyle.BlackTranslucent, false); } commentViewController = new YYCommentViewController (); - commentViewController.associatedObject = (PhotoViewController)child; + commentViewController.associatedObject = (PhotoViewController) child; } - public YYCommentViewController YYcommentViewController () + public YYCommentViewController YYcommentViewController () { YYCommentViewController controller = commentViewController; @@ -80,9 +77,9 @@ public override void LoadView () UILongPressGestureRecognizer gestureRecognizer = new UILongPressGestureRecognizer (this, new ObjCRuntime.Selector ("LongPressGesture:")); View.AddGestureRecognizer (gestureRecognizer); -# if USE_AUTOLAYOUT +#if USE_AUTOLAYOUT commentView.TranslatesAutoresizingMaskIntoConstraints = false; -# endif +#endif } public void AdjustCommentviewFrame () @@ -118,7 +115,7 @@ public override bool ShouldAutomaticallyForwardAppearanceMethods { } } - [Export("LongPressGesture:")] + [Export ("LongPressGesture:")] void toggleCommentViewVisibility (UIGestureRecognizer gestureRecognizer) { bool began = (gestureRecognizer.State == UIGestureRecognizerState.Began); @@ -141,27 +138,28 @@ void toggleCommentViewVisibility (UIGestureRecognizer gestureRecognizer) commentViewController.BeginAppearanceTransition (true, true); View.InsertSubviewAbove (commentView, contentController.View); - # if (!USE_AUTOLAYOUT) +#if (!USE_AUTOLAYOUT) AdjustCommentviewFrame(); - # else +#else View.SetNeedsUpdateConstraints (); - # endif +#endif UIView.Animate (.5, () => { - commentView.Alpha = 0.5f;}, + commentView.Alpha = 0.5f; + }, () => { commentViewController.EndAppearanceTransition (); commentViewController.DidMoveToParentViewController (this); }); } } -# if (!USE_AUTOLAYOUT && ENABLE_LAYOUT_SUBVIEWS) +#if (!USE_AUTOLAYOUT && ENABLE_LAYOUT_SUBVIEWS) public override void ViewWillLayoutSubviews () { if(commentViewIsVisible) AdjustCommentviewFrame(); } -# else +#else // If our content controller has been removed because of a memory warning we need to reinsert if we are appearing. public override void ViewWillLayoutSubviews () { @@ -173,9 +171,9 @@ public override void ViewWillLayoutSubviews () } } } -# endif +#endif -# if ENABLE_WILL_ROTATE_ADJUSTMENT +#if ENABLE_WILL_ROTATE_ADJUSTMENT public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrientation, double duration) { if (commentViewIsVisible) { @@ -183,21 +181,21 @@ public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrie } } -# endif +#endif -# if USE_AUTOLAYOUT +#if USE_AUTOLAYOUT public override void UpdateViewConstraints () { if (commentViewIsVisible) { NSLayoutConstraint constraint1 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, - View, NSLayoutAttribute.CenterX, 1.0f, 0.0f); + View, NSLayoutAttribute.CenterX, 1.0f, 0.0f); NSLayoutConstraint constraint2 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, - View, NSLayoutAttribute.Bottom, 1.0f, 0.0f); + View, NSLayoutAttribute.Bottom, 1.0f, 0.0f); NSLayoutConstraint constraint3 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, - View, NSLayoutAttribute.Width, 0.5f, 0.0f); + View, NSLayoutAttribute.Width, 0.5f, 0.0f); NSLayoutConstraint constarint4 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, - View, NSLayoutAttribute.Height, 0.25f, 0.0f); - View.AddConstraints (new NSLayoutConstraint[] { + View, NSLayoutAttribute.Height, 0.25f, 0.0f); + View.AddConstraints (new NSLayoutConstraint [] { constraint1, constraint2, constraint3, @@ -207,7 +205,7 @@ public override void UpdateViewConstraints () base.UpdateViewConstraints (); } -# endif +#endif public override void ViewWillAppear (bool animated) { contentController.BeginAppearanceTransition (true, true); @@ -231,12 +229,12 @@ public override void ViewDidAppear (bool animated) commentViewController.EndAppearanceTransition (); } -# if ENABLE_KEYBOARD_AVOIDANCE +#if ENABLE_KEYBOARD_AVOIDANCE if (observersregistered == false) { NSNotificationCenter.DefaultCenter.AddObserver (this, new ObjCRuntime.Selector ("KeyBoardWillShow"), UIKeyboard.WillShowNotification, null); NSNotificationCenter.DefaultCenter.AddObserver (this, new ObjCRuntime.Selector ("KeyBoardWillHide"), UIKeyboard.WillHideNotification, null); } -# endif +#endif } public override void ViewDidDisappear (bool animated) @@ -246,15 +244,15 @@ public override void ViewDidDisappear (bool animated) commentViewController.EndAppearanceTransition (); } -# if ENABLE_KEYBOARD_AVOIDANCE +#if ENABLE_KEYBOARD_AVOIDANCE NSNotificationCenter.DefaultCenter.RemoveObserver (this); observersregistered = false; -# endif +#endif } -# if ENABLE_KEYBOARD_AVOIDANCE +#if ENABLE_KEYBOARD_AVOIDANCE - [Export("KeyBoardWillShow:")] + [Export ("KeyBoardWillShow:")] public void KeyboardWillShow (NSNotification notification) { //Gather some info about the keyboard and its information @@ -269,7 +267,7 @@ public void KeyboardWillShow (NSNotification notification) AdjustCommentViewYPosition (keyboardOverlap, animationDuration, false); } - [Export("KeyBoardWillHide:")] + [Export ("KeyBoardWillHide:")] public void KeyBoardWillHide (NSNotification notification) { //Gather some info about the keyboard and its information @@ -278,6 +276,6 @@ public void KeyBoardWillHide (NSNotification notification) AdjustCommentViewYPosition (-1.0f * keyboardOverlap, animationDuration, false); keyboardOverlap = 0; } -# endif +#endif } } diff --git a/MediaNotes/MediaNotes/Shared Files/YYCommentNotifying.cs b/MediaNotes/MediaNotes/Shared Files/YYCommentNotifying.cs index 8f4a28d99..af05c4cb2 100644 --- a/MediaNotes/MediaNotes/Shared Files/YYCommentNotifying.cs +++ b/MediaNotes/MediaNotes/Shared Files/YYCommentNotifying.cs @@ -2,10 +2,8 @@ using System.Collections.Generic; using UIKit; -namespace MediaNotes -{ - public interface YYCommentNotifying - { +namespace MediaNotes { + public interface YYCommentNotifying { void AssociatedCommentDidChange (string comment); string AssociatedComment (); List ItemsForSharing (); diff --git a/MediaNotes/MediaNotes/Shared Files/YYCommentViewController.cs b/MediaNotes/MediaNotes/Shared Files/YYCommentViewController.cs index 412891ad2..4f11a0943 100644 --- a/MediaNotes/MediaNotes/Shared Files/YYCommentViewController.cs +++ b/MediaNotes/MediaNotes/Shared Files/YYCommentViewController.cs @@ -5,13 +5,11 @@ using UIKit; using CoreGraphics; -namespace MediaNotes -{ - public partial class YYCommentViewController : UIViewController - { +namespace MediaNotes { + public partial class YYCommentViewController : UIViewController { bool toolBarIsvisible; - UIPopoverController shareController; - public PhotoViewController associatedObject { get; set;} + UIPopoverController shareController; + public PhotoViewController associatedObject { get; set; } public YYCommentViewController () { @@ -27,7 +25,7 @@ public override void ViewDidLoad () // Perform any additional setup after loading the view, typically from a nib. base.ViewDidLoad (); //check - textView.BackgroundColor = UIColor.FromWhiteAlpha (.25f, .75f); + textView.BackgroundColor = UIColor.FromWhiteAlpha (.25f, .75f); textView.TextColor = UIColor.White; textView.Editable = false; View.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin; @@ -57,7 +55,7 @@ public void setEditing (bool flag) public override void ViewWillAppear (bool animated) { //Console.WriteLine("{0}:{1}",this, char cmd); - textView.Text = Comment(); + textView.Text = Comment (); } public override void ViewWillDisappear (bool animated) @@ -80,10 +78,10 @@ public override void ViewDidDisappear (bool animated) public void TextViewDidEndEditing (UITextView textView) { - if (!Comment ().Equals(textView.Text)){ - SetComment(textView.Text); + if (!Comment ().Equals (textView.Text)) { + SetComment (textView.Text); } - setEditing(true); + setEditing (true); } //YYCommentViewController API @@ -93,7 +91,7 @@ public void ShowToolbar (bool show, bool animated, float duration) UIView.Animate (.5, () => { toolbar.Alpha = show ? 1.0f : 0.0f; toolBarIsvisible = true; - }, () =>{ + }, () => { if (show) { View.AddSubview (toolbar); toolBarIsvisible = true; @@ -109,56 +107,53 @@ public void AssociatedObjectDidChange (PhotoViewController obj) if (obj != associatedObject) { associatedObject = obj; } - textView.Text = obj.AssociatedComment(); + textView.Text = obj.AssociatedComment (); Console.WriteLine (textView.Text); } partial void enableTextEditing (UIKit.UIBarButtonItem sender) { if (textView.Editable) { - setEditing(false); - textView.ResignFirstResponder(); - } - else { - setEditing(true); - textView.BecomeFirstResponder(); + setEditing (false); + textView.ResignFirstResponder (); + } else { + setEditing (true); + textView.BecomeFirstResponder (); } } partial void share (UIKit.UIBarButtonItem sender) { - if(shareController == null){ - List items = associatedObject.ItemsForSharing(); - NSObject [] itemsForSharing = new NSObject [(items == null? 0 : items.Count) + 1]; - int i = 0; - if (items!= null) { + if (shareController == null) { + List items = associatedObject.ItemsForSharing (); + NSObject [] itemsForSharing = new NSObject [(items == null ? 0 : items.Count) + 1]; + int i = 0; + if (items != null) { for (i = 0; i < items.Count; i++) itemsForSharing [i] = items [i]; } itemsForSharing [i] = new NSString (Comment ()); - UIActivityViewController activityController = new UIActivityViewController(itemsForSharing, null); - shareController = new UIPopoverController(activityController); - shareController.Delegate = new MyDelegate(this); - shareController.PresentFromBarButtonItem(shareButton, UIPopoverArrowDirection.Any, true); - } - else{ - shareController.Dismiss(true); + UIActivityViewController activityController = new UIActivityViewController (itemsForSharing, null); + shareController = new UIPopoverController (activityController); + shareController.Delegate = new MyDelegate (this); + shareController.PresentFromBarButtonItem (shareButton, UIPopoverArrowDirection.Any, true); + } else { + shareController.Dismiss (true); shareController = null; - } + } } partial void shootPicture (UIKit.UIBarButtonItem sender) { - UIImagePickerController picker = new UIImagePickerController(); + UIImagePickerController picker = new UIImagePickerController (); picker.SourceType = UIImagePickerControllerSourceType.Camera; picker.ModalPresentationStyle = UIModalPresentationStyle.FullScreen; - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } - class MyDelegate : UIPopoverControllerDelegate - { + class MyDelegate : UIPopoverControllerDelegate { YYCommentViewController _parent; public MyDelegate (YYCommentViewController parent) @@ -166,7 +161,7 @@ public MyDelegate (YYCommentViewController parent) _parent = parent; } - public override void DidDismiss (UIPopoverController popoverController) + public override void DidDismiss (UIPopoverController popoverController) { _parent.shareController = null; } diff --git a/MidiTest/MidiTest/AppDelegate.cs b/MidiTest/MidiTest/AppDelegate.cs index 1e74c4533..8dba52535 100644 --- a/MidiTest/MidiTest/AppDelegate.cs +++ b/MidiTest/MidiTest/AppDelegate.cs @@ -5,11 +5,9 @@ using UIKit; using CoreGraphics; -namespace MidiTest -{ +namespace MidiTest { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -30,7 +28,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary } // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/MidiTest/MidiTest/AudioTest.cs b/MidiTest/MidiTest/AudioTest.cs index 3efa56b15..5cbf9c7ce 100644 --- a/MidiTest/MidiTest/AudioTest.cs +++ b/MidiTest/MidiTest/AudioTest.cs @@ -11,10 +11,8 @@ using CoreFoundation; using UIKit; -namespace MidiTest -{ - public class AudioTest - { +namespace MidiTest { + public class AudioTest { AUGraph processingGraph; AudioUnit.AudioUnit samplerUnit; @@ -31,14 +29,14 @@ bool CreateAUGraph () var musicSampler = new AudioComponentDescription () { ComponentManufacturer = AudioComponentManufacturerType.Apple, ComponentType = AudioComponentType.MusicDevice, - ComponentSubType = (int)AudioTypeMusicDevice.Sampler + ComponentSubType = (int) AudioTypeMusicDevice.Sampler }; samplerNode = processingGraph.AddNode (musicSampler); var remoteOutput = new AudioComponentDescription () { ComponentManufacturer = AudioComponentManufacturerType.Apple, ComponentType = AudioComponentType.Output, - ComponentSubType = (int)AudioTypeOutput.Remote + ComponentSubType = (int) AudioTypeOutput.Remote }; ioNode = processingGraph.AddNode (remoteOutput); @@ -76,7 +74,7 @@ void MidiMessageReceived (object sender, MidiPacketsEventArgs midiPacketArgs) for (int i = 0; i < packets.Length; i++) { var packet = packets [i]; - byte[] data = new byte[packet.Length]; + byte [] data = new byte [packet.Length]; Marshal.Copy (packet.Bytes, data, 0, packet.Length); var midiStatus = data [0]; var midiCommand = midiStatus >> 4; @@ -85,7 +83,7 @@ void MidiMessageReceived (object sender, MidiPacketsEventArgs midiPacketArgs) var note = data [1] & 0x7F; var velocity = data [2] & 0x7F; - int noteNumber = ((int)note) % 12; + int noteNumber = ((int) note) % 12; string noteType; switch (noteNumber) { case 0: @@ -128,9 +126,10 @@ void MidiMessageReceived (object sender, MidiPacketsEventArgs midiPacketArgs) throw new NotImplementedException (); } - samplerUnit.MusicDeviceMIDIEvent ((uint)midiStatus, (uint)note, (uint)velocity); + samplerUnit.MusicDeviceMIDIEvent ((uint) midiStatus, (uint) note, (uint) velocity); - label.InvokeOnMainThread (delegate { + label.InvokeOnMainThread (delegate + { label.Text = String.Format ("Playing: {0}: {1}", noteType, noteNumber); }); } @@ -140,7 +139,7 @@ void MidiMessageReceived (object sender, MidiPacketsEventArgs midiPacketArgs) AudioUnitStatus LoadFromDLSOrSoundFont (CFUrl bankUrl, int presetNumber) { var instrumentData = new SamplerInstrumentData (bankUrl, InstrumentType.SF2Preset) { - PresetID = (byte)presetNumber, + PresetID = (byte) presetNumber, BankMSB = SamplerInstrumentData.DefaultMelodicBankMSB, BankLSB = SamplerInstrumentData.DefaultBankLSB }; diff --git a/MidiTest/MidiTest/MidiTestViewController.cs b/MidiTest/MidiTest/MidiTestViewController.cs index 1170f5c58..028f78a3e 100644 --- a/MidiTest/MidiTest/MidiTestViewController.cs +++ b/MidiTest/MidiTest/MidiTestViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace MidiTest -{ - public partial class MidiTestViewController : UIViewController - { +namespace MidiTest { + public partial class MidiTestViewController : UIViewController { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } diff --git a/MonoCatalog-MonoDevelop/AddressBookController.xib.cs b/MonoCatalog-MonoDevelop/AddressBookController.xib.cs index a1bbb98a7..5c480f29c 100644 --- a/MonoCatalog-MonoDevelop/AddressBookController.xib.cs +++ b/MonoCatalog-MonoDevelop/AddressBookController.xib.cs @@ -6,10 +6,8 @@ using Foundation; using UIKit; -namespace MonoCatalog -{ - public partial class AddressBookController : UIViewController - { +namespace MonoCatalog { + public partial class AddressBookController : UIViewController { ABPeoplePickerNavigationController p; @@ -39,22 +37,22 @@ ABPeoplePickerNavigationController GetPicker () p = new ABPeoplePickerNavigationController (); p.SelectPerson += (o, e) => { - HandlePersonSelection(e.Person); + HandlePersonSelection (e.Person); e.Continue = selectProperty.On; if (!e.Continue) DismissModalViewController (true); }; p.SelectPerson2 += (sender, e) => { - HandlePersonSelection(e.Person); + HandlePersonSelection (e.Person); }; p.PerformAction += (o, e) => { - HandlePersonPropertySelection(e.Person, e.Property, e.Identifier); + HandlePersonPropertySelection (e.Person, e.Property, e.Identifier); if (!e.Continue) DismissModalViewController (true); }; p.PerformAction2 += (sender, e) => { - HandlePersonPropertySelection(e.Person, e.Property, e.Identifier); + HandlePersonPropertySelection (e.Person, e.Property, e.Identifier); }; p.Cancelled += (o, e) => { @@ -75,7 +73,7 @@ partial void showPicker (UIKit.UIButton sender) PresentModalViewController (GetPicker (), true); } - void HandlePersonSelection(AddressBook.ABPerson person) + void HandlePersonSelection (AddressBook.ABPerson person) { Console.Error.WriteLine ("# select Person: {0}", person); toString.Text = person.ToString (); @@ -85,7 +83,7 @@ void HandlePersonSelection(AddressBook.ABPerson person) identifier.Text = ""; } - void HandlePersonPropertySelection(AddressBook.ABPerson person, AddressBook.ABPersonProperty property, int? id) + void HandlePersonPropertySelection (AddressBook.ABPerson person, AddressBook.ABPersonProperty property, int? id) { Console.Error.WriteLine ("# perform action; person={0}", person); toString.Text = person.ToString (); diff --git a/MonoCatalog-MonoDevelop/AlertsViewController.xib.cs b/MonoCatalog-MonoDevelop/AlertsViewController.xib.cs index ef28ae773..1c96df1ee 100644 --- a/MonoCatalog-MonoDevelop/AlertsViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/AlertsViewController.xib.cs @@ -52,10 +52,11 @@ public override void ViewDidLoad () void DialogSimpleAction () { - var actionSheet = new UIActionSheet ("UIActionSheet ", null, null, "OK", null){ + var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, null, "OK", null) { Style = UIActionSheetStyle.Default }; - actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args){ + actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args) + { Console.WriteLine ("Clicked on item {0}", args.ButtonIndex); }; @@ -64,10 +65,11 @@ void DialogSimpleAction () void DialogOkCancelAction () { - var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, "Cancel", "OK", null){ + var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, "Cancel", "OK", null) { Style = UIActionSheetStyle.Default }; - actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args){ + actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args) + { Console.WriteLine ("Clicked on item {0}", args.ButtonIndex); }; @@ -76,10 +78,11 @@ void DialogOkCancelAction () void DialogOtherAction () { - var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, "Cancel", "OK", "Other1"){ + var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, "Cancel", "OK", "Other1") { Style = UIActionSheetStyle.Default }; - actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args){ + actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args) + { Console.WriteLine ("Clicked on item {0}", args.ButtonIndex); }; @@ -95,13 +98,13 @@ void AlertSimpleAction () void AlertOkCancelAction () { using (var alert = new UIAlertView ("UIAlertView", "<Alert Message>", null, "Cancel", "OK")) - alert.Show (); + alert.Show (); } void AlertOtherAction () { using (var alert = new UIAlertView ("UIAlertView", "<Alert Message>", null, "Cancel", "Button1", "Button2")) - alert.Show (); + alert.Show (); } @@ -129,15 +132,15 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde { UITableViewCell cell; - if (indexPath.Row == 0){ + if (indexPath.Row == 0) { cell = tableView.DequeueReusableCell (kDisplayCell_ID); if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID); cell.TextLabel.Text = samples [indexPath.Section].Label; } else { cell = tableView.DequeueReusableCell (kSourceCell_ID); - if (cell == null){ - cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID){ + if (cell == null) { + cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID) { SelectionStyle = UITableViewCellSelectionStyle.None }; var label = cell.TextLabel; @@ -172,8 +175,8 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) // deselect current row tableView.DeselectRow (tableView.IndexPathForSelectedRow, true); - if (indexPath.Row == 0){ - switch (indexPath.Section){ + if (indexPath.Row == 0) { + switch (indexPath.Section) { case 0: avc.DialogSimpleAction (); break; diff --git a/MonoCatalog-MonoDevelop/AppDelegate.cs b/MonoCatalog-MonoDevelop/AppDelegate.cs index 13966532b..3e497f0aa 100644 --- a/MonoCatalog-MonoDevelop/AppDelegate.cs +++ b/MonoCatalog-MonoDevelop/AppDelegate.cs @@ -1,20 +1,18 @@ -using UIKit; +using UIKit; using Foundation; -namespace MonoCatalog -{ - // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class AppDelegate : UIApplicationDelegate +namespace MonoCatalog { + // The name AppDelegate is referenced in the MainWindow.xib file. + public partial class AppDelegate : UIApplicationDelegate { + // This method is invoked when the application is ready to run + // + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { - // This method is invoked when the application is ready to run - // - public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) - { - window.RootViewController = navigationController; - window.MakeKeyAndVisible (); + window.RootViewController = navigationController; + window.MakeKeyAndVisible (); - return true; - } + return true; } + } } diff --git a/MonoCatalog-MonoDevelop/ButtonsViewController.xib.cs b/MonoCatalog-MonoDevelop/ButtonsViewController.xib.cs index 7fd5fc0e3..ecbc7f7e1 100644 --- a/MonoCatalog-MonoDevelop/ButtonsViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/ButtonsViewController.xib.cs @@ -7,11 +7,9 @@ using Foundation; using CoreGraphics; -namespace MonoCatalog -{ +namespace MonoCatalog { - public partial class ButtonsViewController : UITableViewController - { + public partial class ButtonsViewController : UITableViewController { // // This datasource describes how the UITableView should render the @@ -21,8 +19,7 @@ public partial class ButtonsViewController : UITableViewController // Row 0: the actual styled button // Row 1: the text information about the button // - class DataSource : UITableViewDataSource - { + class DataSource : UITableViewDataSource { ButtonsViewController bvc; static NSString kDisplayCell_ID = new NSString ("DisplayCellID"); static NSString kSourceCell_ID = new NSString ("SourceCellID"); @@ -39,7 +36,7 @@ public override nint NumberOfSections (UITableView tableView) public override string TitleForHeader (UITableView tableView, nint section) { - return bvc.samples[section].Title; + return bvc.samples [section].Title; } public override nint RowsInSection (UITableView tableView, nint section) @@ -63,8 +60,8 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde if (viewToRemove != null) viewToRemove.RemoveFromSuperview (); } - cell.TextLabel.Text = bvc.samples[indexPath.Section].Label; - cell.ContentView.AddSubview (bvc.samples[indexPath.Section].Button); + cell.TextLabel.Text = bvc.samples [indexPath.Section].Label; + cell.ContentView.AddSubview (bvc.samples [indexPath.Section].Button); } else { cell = tableView.DequeueReusableCell (kSourceCell_ID); if (cell == null) { @@ -80,15 +77,14 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde label.HighlightedTextColor = UIColor.Black; label.Font = UIFont.SystemFontOfSize (12f); } - cell.TextLabel.Text = bvc.samples[indexPath.Section].Source; + cell.TextLabel.Text = bvc.samples [indexPath.Section].Source; } return cell; } } - class TableDelegate : UITableViewDelegate - { + class TableDelegate : UITableViewDelegate { // // Override to provide the sizing of the rows in our table // @@ -100,7 +96,7 @@ public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath index } // Load our definition from the NIB file - public ButtonsViewController () : base("ButtonsViewController", null) + public ButtonsViewController () : base ("ButtonsViewController", null) { } @@ -120,7 +116,8 @@ static UIButton ButtonWithTitle (string title, CGRect frame, UIImage image, UIIm button.SetTitle (title, UIControlState.Normal); if (darkTextColor) - button.SetTitleColor (UIColor.Black, UIControlState.Normal); else + button.SetTitleColor (UIColor.Black, UIControlState.Normal); + else button.SetTitleColor (UIColor.White, UIControlState.Normal); var newImage = image.StretchableImage (12, 0); @@ -219,8 +216,7 @@ UIButton ContactAddButtonType () return button; } - struct ButtonSample - { + struct ButtonSample { public string Title, Label, Source; public UIButton Button; @@ -233,7 +229,7 @@ public ButtonSample (string t, string l, string s, UIButton b) } } - ButtonSample[] samples; + ButtonSample [] samples; public override void ViewDidLoad () { @@ -241,7 +237,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); Title = "Buttons"; - samples = new ButtonSample[] { + samples = new ButtonSample [] { new ButtonSample ("UIButton", "Background image", "buttons.cs:\rUIButton GrayButton ()", GrayButton ()), new ButtonSample ("UIButton", "Button with image", "buttons.cs:\rUIButton ImageButton ()", ImageButton ()), new ButtonSample ("UIButtonRoundedRect", "Rounded Button", "buttons.cs:\rUIButton RoundedButtonType ()", RoundedButtonType ()), diff --git a/MonoCatalog-MonoDevelop/ControlsViewController.xib.cs b/MonoCatalog-MonoDevelop/ControlsViewController.xib.cs index d9291115f..5d804ca26 100644 --- a/MonoCatalog-MonoDevelop/ControlsViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/ControlsViewController.xib.cs @@ -48,9 +48,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde { UITableViewCell cell; - if (indexPath.Row == 0){ + if (indexPath.Row == 0) { cell = tableView.DequeueReusableCell (kDisplayCell_ID); - if (cell == null){ + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID); cell.SelectionStyle = UITableViewCellSelectionStyle.None; } else { @@ -64,7 +64,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde cell.ContentView.AddSubview (cvc.samples [indexPath.Section].Control); } else { cell = tableView.DequeueReusableCell (kSourceCell_ID); - if (cell == null){ + if (cell == null) { // Construct the cell with reusability (the second argument is not null) cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID); cell.SelectionStyle = UITableViewCellSelectionStyle.None; @@ -102,12 +102,13 @@ public ControlsViewController () : base ("ControlsViewController", null) static UIControl SwitchControl (string id) { - var sw = new UISwitch (new CGRect (198f, 12f, 94f, 27f)){ + var sw = new UISwitch (new CGRect (198f, 12f, 94f, 27f)) { BackgroundColor = UIColor.Clear, Tag = kViewTag, AccessibilityIdentifier = id }; - sw.ValueChanged += delegate { + sw.ValueChanged += delegate + { // The enum variant causes a full-aot crash Console.WriteLine ("New state: {0}", (int) sw.State); }; @@ -116,7 +117,7 @@ static UIControl SwitchControl (string id) static UIControl SliderControl (string id) { - var slider = new UISlider (new CGRect (174f, 12f, 120f, 7f)){ + var slider = new UISlider (new CGRect (174f, 12f, 120f, 7f)) { BackgroundColor = UIColor.Clear, MinValue = 0f, MaxValue = 100f, @@ -125,7 +126,8 @@ static UIControl SliderControl (string id) Tag = kViewTag, AccessibilityIdentifier = id }; - slider.ValueChanged += delegate { + slider.ValueChanged += delegate + { Console.WriteLine ("New value {0}", slider.Value); }; return slider; @@ -133,7 +135,7 @@ static UIControl SliderControl (string id) static UIControl CustomSliderControl (string id) { - var cslider = new UISlider (new CGRect (174f, 12f, 120f, 7f)){ + var cslider = new UISlider (new CGRect (174f, 12f, 120f, 7f)) { BackgroundColor = UIColor.Clear, MinValue = 0f, MaxValue = 100f, @@ -152,7 +154,8 @@ static UIControl CustomSliderControl (string id) cslider.SetMinTrackImage (left, UIControlState.Normal); cslider.SetMaxTrackImage (right, UIControlState.Normal); - cslider.ValueChanged += delegate { + cslider.ValueChanged += delegate + { Console.WriteLine ("New value {0}", cslider.Value); }; return cslider; @@ -160,14 +163,15 @@ static UIControl CustomSliderControl (string id) static UIControl PageControl (string id) { - var page = new UIPageControl (new CGRect (120f, 14f, 178f, 20f)){ + var page = new UIPageControl (new CGRect (120f, 14f, 178f, 20f)) { BackgroundColor = UIColor.Gray, Pages = 10, Tag = kViewTag, AccessibilityIdentifier = id }; - page.TouchUpInside += delegate { + page.TouchUpInside += delegate + { Console.WriteLine ("Current page: {0}", page.CurrentPage); }; @@ -176,7 +180,7 @@ static UIControl PageControl (string id) static UIView ActivityIndicator (string id) { - var pind = new UIActivityIndicatorView (new CGRect (265f, 12f, 40f, 40f)){ + var pind = new UIActivityIndicatorView (new CGRect (265f, 12f, 40f, 40f)) { ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray, AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | @@ -194,7 +198,7 @@ static UIView ActivityIndicator (string id) static UIView ProgressBar (string id) { - return new UIProgressView (new CGRect (126f, 20f, 160f, 24f)){ + return new UIProgressView (new CGRect (126f, 20f, 160f, 24f)) { Style = UIProgressViewStyle.Default, Progress = 0.5f, Tag = kViewTag, diff --git a/MonoCatalog-MonoDevelop/Main.cs b/MonoCatalog-MonoDevelop/Main.cs index 8713be887..1c43fa0c8 100644 --- a/MonoCatalog-MonoDevelop/Main.cs +++ b/MonoCatalog-MonoDevelop/Main.cs @@ -7,13 +7,12 @@ namespace MonoTouch { - class Application - { + class Application { static void Main (string [] args) { // It will load the main UI as specified in the // Info.plist file (MainWindow.nib) - UIApplication.Main (args, null, (string)null); + UIApplication.Main (args, null, (string) null); } } } diff --git a/MonoCatalog-MonoDevelop/MainWindow.xib.cs b/MonoCatalog-MonoDevelop/MainWindow.xib.cs index 918fc993d..b6043bfe6 100644 --- a/MonoCatalog-MonoDevelop/MainWindow.xib.cs +++ b/MonoCatalog-MonoDevelop/MainWindow.xib.cs @@ -42,7 +42,7 @@ public Sample (string title, UIViewController controller) // // Constructor invoked from the NIB loader // - public MainViewController (IntPtr p) : base (p) {} + public MainViewController (IntPtr p) : base (p) { } // // The data source for our TableView @@ -63,7 +63,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (kCellIdentifier); - if (cell == null){ + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, kCellIdentifier); cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; } diff --git a/MonoCatalog-MonoDevelop/MonoDataSqlite.xib.cs b/MonoCatalog-MonoDevelop/MonoDataSqlite.xib.cs index e0162ab6b..e8e5383c7 100644 --- a/MonoCatalog-MonoDevelop/MonoDataSqlite.xib.cs +++ b/MonoCatalog-MonoDevelop/MonoDataSqlite.xib.cs @@ -7,20 +7,18 @@ using Foundation; using UIKit; -namespace MonoCatalog -{ - public partial class MonoDataSqliteController : UITableViewController - { +namespace MonoCatalog { + public partial class MonoDataSqliteController : UITableViewController { // The IntPtr and NSCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public MonoDataSqliteController (IntPtr handle) : base(handle) + public MonoDataSqliteController (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public MonoDataSqliteController (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public MonoDataSqliteController (NSCoder coder) : base (coder) { Initialize (); } @@ -34,8 +32,7 @@ void Initialize () { } - class ItemsTableDelegate : UITableViewDelegate - { + class ItemsTableDelegate : UITableViewDelegate { // // Override to provide the sizing of the rows in our table // @@ -47,8 +44,7 @@ public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath index } } - class ItemsDataSource : UITableViewDataSource - { + class ItemsDataSource : UITableViewDataSource { static readonly NSString kAdd = new NSString ("Add"); static readonly NSString kKey = new NSString ("Key"); @@ -61,7 +57,7 @@ class SectionInfo { public Func<UITableView, NSIndexPath, UITableViewCell> Creator; } - SectionInfo [] Sections = new[]{ + SectionInfo [] Sections = new []{ new SectionInfo { Title = "Add Key/Value Pair", Creator = GetAddKeyValuePairCell }, new SectionInfo { Title = "Key/Value Pairs", Creator = GetKeyValuePairCell }, }; @@ -101,7 +97,7 @@ static UITableViewCell GetAddKeyValuePairCell (UITableView tableView, NSIndexPat cell = new UITableViewCell (UITableViewCellStyle.Default, kAdd); cells.Add (cell); } else { - RemoveViewWithTag (cell, kKeyTag << 1); + RemoveViewWithTag (cell, kKeyTag << 1); RemoveViewWithTag (cell, kKeyTag); RemoveViewWithTag (cell, kValueTag << 1); RemoveViewWithTag (cell, kValueTag); @@ -109,38 +105,38 @@ static UITableViewCell GetAddKeyValuePairCell (UITableView tableView, NSIndexPat } var lblKey = new UILabel () { BaselineAdjustment = UIBaselineAdjustment.AlignCenters, - Frame = new CGRect (10f, 0f, 70f, 31f), - Tag = kKeyTag << 1, - Text = "Key: ", - TextAlignment = UITextAlignment.Right, + Frame = new CGRect (10f, 0f, 70f, 31f), + Tag = kKeyTag << 1, + Text = "Key: ", + TextAlignment = UITextAlignment.Right, }; var key = new UITextField () { - BorderStyle = UITextBorderStyle.Bezel, - ClearButtonMode = UITextFieldViewMode.WhileEditing, - Frame = new CGRect (80f, 1f, 170f, 31f), - Placeholder = "Key", - Tag = kKeyTag, + BorderStyle = UITextBorderStyle.Bezel, + ClearButtonMode = UITextFieldViewMode.WhileEditing, + Frame = new CGRect (80f, 1f, 170f, 31f), + Placeholder = "Key", + Tag = kKeyTag, AccessibilityLabel = "Key" }; var lblValue = new UILabel () { BaselineAdjustment = UIBaselineAdjustment.AlignCenters, - Frame = new CGRect (10f, 37f, 70f, 31f), - Tag = kValueTag << 1, - Text = "Value: ", - TextAlignment = UITextAlignment.Right, + Frame = new CGRect (10f, 37f, 70f, 31f), + Tag = kValueTag << 1, + Text = "Value: ", + TextAlignment = UITextAlignment.Right, }; var value = new UITextField () { - BorderStyle = UITextBorderStyle.Bezel, - ClearButtonMode = UITextFieldViewMode.WhileEditing, - Frame = new CGRect (80f, 38f, 170f, 31f), - Placeholder = "Value", - Tag = kValueTag, + BorderStyle = UITextBorderStyle.Bezel, + ClearButtonMode = UITextFieldViewMode.WhileEditing, + Frame = new CGRect (80f, 38f, 170f, 31f), + Placeholder = "Value", + Tag = kValueTag, AccessibilityLabel = "Value" }; var add = UIButton.FromType (UIButtonType.ContactAdd); add.HorizontalAlignment = UIControlContentHorizontalAlignment.Center; - add.VerticalAlignment = UIControlContentVerticalAlignment.Center; - add.Frame = new CGRect (255, 0, 40f, 70f); + add.VerticalAlignment = UIControlContentVerticalAlignment.Center; + add.Frame = new CGRect (255, 0, 40f, 70f); add.SetTitle ("Add", UIControlState.Normal); add.TouchUpInside += (o, e) => { WithCommand (c => { @@ -148,12 +144,12 @@ static UITableViewCell GetAddKeyValuePairCell (UITableView tableView, NSIndexPat c.Parameters.Add (new SqliteParameter ("@key", key.Text)); c.Parameters.Add (new SqliteParameter ("@value", value.Text)); c.ExecuteNonQuery (); - key.Text = ""; - value.Text = ""; + key.Text = ""; + value.Text = ""; key.ResignFirstResponder (); value.ResignFirstResponder (); var path = NSIndexPath.FromRowSection (GetItemCount () - 1, 1); - tableView.InsertRows (new NSIndexPath [] {path}, UITableViewRowAnimation.Bottom); + tableView.InsertRows (new NSIndexPath [] { path }, UITableViewRowAnimation.Bottom); }); }; cell.ContentView.AddSubview (lblKey); @@ -181,17 +177,16 @@ static UITableViewCell GetKeyValuePairCell (UITableView tableView, NSIndexPath i c.CommandText = query; var r = c.ExecuteReader (); while (r.Read ()) { - key = r ["Key"].ToString (); + key = r ["Key"].ToString (); value = r ["Value"].ToString (); } }); var cell = tableView.DequeueReusableCell (kKey); - if (cell == null){ + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, kKey); cell.SelectionStyle = UITableViewCellSelectionStyle.None; cells.Add (cell); - } - else { + } else { RemoveViewWithTag (cell, kKeyTag); RemoveViewWithTag (cell, kValueTag); } @@ -199,8 +194,8 @@ static UITableViewCell GetKeyValuePairCell (UITableView tableView, NSIndexPath i Func<string, int, bool, UILabel> createLabel = (v, t, left) => { var label = new UILabel (); label.Frame = left - ? new CGRect (10f, 1f, width-10, 40) - : new CGRect (width, 1f, width-30, 40); + ? new CGRect (10f, 1f, width - 10, 40) + : new CGRect (width, 1f, width - 30, 40); label.Text = v; label.TextAlignment = left ? UITextAlignment.Left @@ -249,9 +244,9 @@ static SqliteConnection GetConnection () bool exists = File.Exists (db); if (!exists) SqliteConnection.CreateFile (db); - var conn = new SqliteConnection("Data Source=" + db); + var conn = new SqliteConnection ("Data Source=" + db); if (!exists) { - var commands = new[] { + var commands = new [] { "CREATE TABLE Items (Key ntext, Value ntext)", "INSERT INTO [Items] ([Key], [Value]) VALUES ('sample', 'text')", }; @@ -270,8 +265,7 @@ static void WithConnection (Action<SqliteConnection> action) try { connection.Open (); action (connection); - } - finally { + } finally { connection.Close (); } } diff --git a/MonoCatalog-MonoDevelop/PickerCustomModel.cs b/MonoCatalog-MonoDevelop/PickerCustomModel.cs index 44547a277..f341a69fb 100644 --- a/MonoCatalog-MonoDevelop/PickerCustomModel.cs +++ b/MonoCatalog-MonoDevelop/PickerCustomModel.cs @@ -11,12 +11,14 @@ public class CustomView : UIView { const float MAIN_FONT_SIZE = 18.0f; const float MIN_MAIN_FONT_SIZE = 16.0f; - public CustomView (CGRect frame) : base (new CGRect (CGPoint.Empty, new CGSize (Width, Height))) { + public CustomView (CGRect frame) : base (new CGRect (CGPoint.Empty, new CGSize (Width, Height))) + { AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; BackgroundColor = UIColor.Clear; } - public override void Draw (CGRect rect) { + public override void Draw (CGRect rect) + { nfloat yCoord = (Bounds.Size.Height - Image.Size.Height) / 2f; CGPoint point = new CGPoint (10.0f, yCoord); @@ -35,10 +37,11 @@ public override void Draw (CGRect rect) { } public class CustomPickerModel : UIPickerViewModel { - List <CustomView> views; + List<CustomView> views; - public CustomPickerModel () : base () { - views = new List <CustomView> (); + public CustomPickerModel () : base () + { + views = new List<CustomView> (); var empty = CGRect.Empty; views.Add (new CustomView (empty) { Title = "Early Morning", Image = UIImage.FromFile ("images/12-6AM.png") }); @@ -47,23 +50,28 @@ public CustomPickerModel () : base () { views.Add (new CustomView (empty) { Title = "Evening", Image = UIImage.FromFile ("images/6-12PM.png") }); } - public override nfloat GetComponentWidth (UIPickerView pickerView, nint component) { + public override nfloat GetComponentWidth (UIPickerView pickerView, nint component) + { return CustomView.Width; } - public override nfloat GetRowHeight (UIPickerView pickerView, nint component) { + public override nfloat GetRowHeight (UIPickerView pickerView, nint component) + { return CustomView.Height; } - public override nint GetRowsInComponent (UIPickerView pickerView, nint component) { + public override nint GetRowsInComponent (UIPickerView pickerView, nint component) + { return views.Count; } - public override nint GetComponentCount (UIPickerView pickerView) { + public override nint GetComponentCount (UIPickerView pickerView) + { return 1; } - public override UIView GetView (UIPickerView pickerView, nint row, nint component, UIView view) { - return views[(int)row]; + public override UIView GetView (UIPickerView pickerView, nint row, nint component, UIView view) + { + return views [(int) row]; } } diff --git a/MonoCatalog-MonoDevelop/PickerViewController.xib.cs b/MonoCatalog-MonoDevelop/PickerViewController.xib.cs index de4ccb224..64100db11 100644 --- a/MonoCatalog-MonoDevelop/PickerViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/PickerViewController.xib.cs @@ -8,7 +8,7 @@ namespace MonoCatalog { - public partial class PickerViewController : UIViewController { + public partial class PickerViewController : UIViewController { UIPickerView myPickerView, customPickerView; UIDatePicker datePickerView; UILabel label; @@ -39,7 +39,7 @@ public override void ViewDidLoad () buttonBarSegmentedControl.TintColor = UIColor.DarkGray; pickerStyleSegmentedControl.TintColor = UIColor.DarkGray; - label = new UILabel (new CGRect (20f, myPickerView.Frame.Y - 30f, View.Bounds.Width - 40f, 30f)){ + label = new UILabel (new CGRect (20f, myPickerView.Frame.Y - 30f, View.Bounds.Width - 40f, 30f)) { Font = UIFont.SystemFontOfSize (14), TextAlignment = UITextAlignment.Center, TextColor = labelTextColor, @@ -74,7 +74,7 @@ CGRect PickerFrameWithSize (CGSize size) UIView currentPicker; void ShowPicker (UIView picker) { - if (currentPicker != null){ + if (currentPicker != null) { currentPicker.Hidden = true; label.Text = ""; } @@ -87,7 +87,7 @@ void ShowPicker (UIView picker) [Export ("togglePickers:")] public void TogglePickers (UISegmentedControl sender) { - switch (sender.SelectedSegment){ + switch (sender.SelectedSegment) { case 0: pickerStyleSegmentedControl.Hidden = true; segmentLabel.Hidden = true; @@ -113,7 +113,7 @@ public void TogglePickers (UISegmentedControl sender) [Export ("togglePickerStyle:")] public void TogglePickerStyle (UISegmentedControl sender) { - switch (sender.SelectedSegment){ + switch (sender.SelectedSegment) { case 0: // time datePickerView.Mode = UIDatePickerMode.Time; break; @@ -175,7 +175,7 @@ void CreatePicker () // Empty is used, since UIPickerViews have auto-sizing, // all that is required is the origin // - myPickerView = new UIPickerView (CGRect.Empty){ + myPickerView = new UIPickerView (CGRect.Empty) { AutoresizingMask = UIViewAutoresizing.FlexibleWidth, ShowSelectionIndicator = true, Model = new PeopleModel (this), @@ -199,7 +199,8 @@ public class PeopleModel : UIPickerViewModel { }; PickerViewController pvc; - public PeopleModel (PickerViewController pvc) { + public PeopleModel (PickerViewController pvc) + { this.pvc = pvc; } @@ -224,8 +225,8 @@ public override string GetTitle (UIPickerView picker, nint row, nint component) public override void Selected (UIPickerView picker, nint row, nint component) { pvc.label.Text = String.Format ("{0} - {1}", - names [picker.SelectedRowInComponent (0)], - picker.SelectedRowInComponent (1)); + names [picker.SelectedRowInComponent (0)], + picker.SelectedRowInComponent (1)); } public override nfloat GetComponentWidth (UIPickerView picker, nint component) diff --git a/MonoCatalog-MonoDevelop/SearchBarController.xib.cs b/MonoCatalog-MonoDevelop/SearchBarController.xib.cs index 3169e60ac..54176535b 100644 --- a/MonoCatalog-MonoDevelop/SearchBarController.xib.cs +++ b/MonoCatalog-MonoDevelop/SearchBarController.xib.cs @@ -29,8 +29,8 @@ public override void ViewDidLoad () Title = "Search Bar"; NavigationController.NavigationBar.Translucent = false; View.BackgroundColor = UIColor.GroupTableViewBackgroundColor; - var f = new CGRect (0f, 64f, View.Bounds.Width, 44f); - bar = new UISearchBar (f){ + var f = new CGRect (0f, 64f, View.Bounds.Width, 44f); + bar = new UISearchBar (f) { Delegate = new SearchDelegate (), ShowsCancelButton = true, }; diff --git a/MonoCatalog-MonoDevelop/SegmentViewController.xib.cs b/MonoCatalog-MonoDevelop/SegmentViewController.xib.cs index fceb96758..d6757484e 100644 --- a/MonoCatalog-MonoDevelop/SegmentViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/SegmentViewController.xib.cs @@ -11,7 +11,7 @@ namespace MonoCatalog { public partial class SegmentViewController : UIViewController { - public SegmentViewController () : base ("SegmentViewController", null) {} + public SegmentViewController () : base ("SegmentViewController", null) { } UILabel MakeLabel (string title, CGRect frame) { @@ -19,7 +19,7 @@ UILabel MakeLabel (string title, CGRect frame) TextAlignment = UITextAlignment.Left, Text = title, Font = UIFont.BoldSystemFontOfSize (17f), - TextColor = new UIColor (76/255f, 86/255f, 108/255f, 1.0f), + TextColor = new UIColor (76 / 255f, 86 / 255f, 108 / 255f, 1.0f), BackgroundColor = UIColor.Clear }; } @@ -40,7 +40,7 @@ void CreateControls () var segmentedControl = new UISegmentedControl (new object [] { UIImage.FromFile ("images/segment_check.png"), UIImage.FromFile ("images/segment_search.png"), - UIImage.FromFile ("images/segment_tools.png")}){ + UIImage.FromFile ("images/segment_tools.png")}) { Frame = new CGRect (20f, yPlacement, View.Bounds.Width - 40f, 40f), ControlStyle = UISegmentedControlStyle.Plain, SelectedSegment = 1, @@ -52,13 +52,14 @@ void CreateControls () View.AddSubview (MakeLabel ("UISegmentedControlStyleBordered", new CGRect (20f, yPlacement, View.Bounds.Width - 40f, lHeight))); yPlacement += 40f; - segmentedControl = new UISegmentedControl (items){ + segmentedControl = new UISegmentedControl (items) { Frame = new CGRect (20f, yPlacement, View.Bounds.Width - 40f, 40f), ControlStyle = UISegmentedControlStyle.Bordered, SelectedSegment = 1, AccessibilityLabel = "Bordered" }; - segmentedControl.ValueChanged += delegate { + segmentedControl.ValueChanged += delegate + { Console.WriteLine ("Value changed"); }; View.AddSubview (segmentedControl); @@ -66,7 +67,7 @@ void CreateControls () View.AddSubview (MakeLabel ("UISegmentedControlStyleBar", new CGRect (20f, yPlacement, View.Bounds.Width - 40f, lHeight))); yPlacement += 40f; - segmentedControl = new UISegmentedControl (items){ + segmentedControl = new UISegmentedControl (items) { Frame = new CGRect (20f, yPlacement, View.Bounds.Width - 40f, 40f), ControlStyle = UISegmentedControlStyle.Bar, SelectedSegment = 1, @@ -77,12 +78,12 @@ void CreateControls () View.AddSubview (MakeLabel ("UISegmentedControlStyleBar (tinted)", new CGRect (20f, yPlacement, View.Bounds.Width - 40f, lHeight))); yPlacement += 40f; - segmentedControl = new UISegmentedControl (items){ + segmentedControl = new UISegmentedControl (items) { Frame = new CGRect (20f, yPlacement, View.Bounds.Width - 40f, 40f), ControlStyle = UISegmentedControlStyle.Bar, TintColor = UIColor.FromRGB (0.7f, 0.171f, 0.1f), - SelectedSegment = 1, - AccessibilityLabel = "Tinted" + SelectedSegment = 1, + AccessibilityLabel = "Tinted" }; View.AddSubview (segmentedControl); yPlacement += 60f; diff --git a/MonoCatalog-MonoDevelop/TextFieldController.xib.cs b/MonoCatalog-MonoDevelop/TextFieldController.xib.cs index 0562fb345..84ecbef97 100644 --- a/MonoCatalog-MonoDevelop/TextFieldController.xib.cs +++ b/MonoCatalog-MonoDevelop/TextFieldController.xib.cs @@ -10,7 +10,8 @@ namespace MonoCatalog { public partial class TextFieldController : UITableViewController { - public TextFieldController () : base ("TextFieldController", null) { + public TextFieldController () : base ("TextFieldController", null) + { } const int kViewTag = 1; @@ -45,9 +46,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde UITableViewCell cell = null; int row = indexPath.Row; - if (row == 0){ + if (row == 0) { cell = tableView.DequeueReusableCell (kDisplayCell_ID); - if (cell == null){ + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID); cell.SelectionStyle = UITableViewCellSelectionStyle.None; } else { @@ -59,7 +60,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde cell.ContentView.AddSubview (tvc.samples [indexPath.Section].View); } else { cell = tableView.DequeueReusableCell (kSourceCell_ID); - if (cell == null){ + if (cell == null) { // Construct the cell with reusability (the second argument is not null) cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID); cell.SelectionStyle = UITableViewCellSelectionStyle.None; @@ -95,7 +96,7 @@ bool DoReturn (UITextField tf) UITextField TextFieldNormal () { - return new UITextField (new CGRect (30f, 8f, 260f, 30f)){ + return new UITextField (new CGRect (30f, 8f, 260f, 30f)) { BorderStyle = UITextBorderStyle.Bezel, TextColor = UIColor.Black, Font = UIFont.SystemFontOfSize (17f), @@ -113,7 +114,7 @@ UITextField TextFieldNormal () UITextField TextFieldRounded () { - return new UITextField (new CGRect (30f, 8f, 260f, 30f)){ + return new UITextField (new CGRect (30f, 8f, 260f, 30f)) { BorderStyle = UITextBorderStyle.RoundedRect, TextColor = UIColor.Black, Font = UIFont.SystemFontOfSize (17f), @@ -131,7 +132,7 @@ UITextField TextFieldRounded () UITextField TextFieldSecure () { - return new UITextField (new CGRect (30f, 8f, 260f, 30f)){ + return new UITextField (new CGRect (30f, 8f, 260f, 30f)) { BorderStyle = UITextBorderStyle.Bezel, TextColor = UIColor.Black, Font = UIFont.SystemFontOfSize (17f), @@ -150,7 +151,7 @@ UITextField TextFieldSecure () UITextField TextFieldLeftView () { - return new UITextField (new CGRect (30f, 8f, 260f, 30f)){ + return new UITextField (new CGRect (30f, 8f, 260f, 30f)) { BorderStyle = UITextBorderStyle.Bezel, TextColor = UIColor.Black, Font = UIFont.SystemFontOfSize (17f), diff --git a/MonoCatalog-MonoDevelop/TextViewController.xib.cs b/MonoCatalog-MonoDevelop/TextViewController.xib.cs index 6a6e5a44d..1f954f76e 100644 --- a/MonoCatalog-MonoDevelop/TextViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/TextViewController.xib.cs @@ -17,7 +17,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); Title = "Text View"; - textView = new UITextView (View.Frame){ + textView = new UITextView (View.Frame) { TextColor = UIColor.Black, Font = UIFont.FromName ("Arial", 18f), BackgroundColor = UIColor.White, @@ -29,11 +29,13 @@ public override void ViewDidLoad () }; // Provide our own save button to dismiss the keyboard - textView.Started += delegate { - var saveItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, delegate { + textView.Started += delegate + { + var saveItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, delegate + { textView.ResignFirstResponder (); NavigationItem.RightBarButtonItem = null; - }); + }); NavigationItem.RightBarButtonItem = saveItem; }; @@ -44,7 +46,8 @@ public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); - obs1 = NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, delegate (NSNotification n){ + obs1 = NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, delegate (NSNotification n) + { var kbdRect = UIKeyboard.BoundsFromNotification (n); var duration = UIKeyboard.AnimationDurationFromNotification (n); var frame = View.Frame; @@ -53,9 +56,10 @@ public override void ViewWillAppear (bool animated) UIView.SetAnimationDuration (duration); View.Frame = frame; UIView.CommitAnimations (); - }); + }); - obs2 = NSNotificationCenter.DefaultCenter.AddObserver (new NSString("UIKeyboardWillHideNotification"), delegate (NSNotification n){ + obs2 = NSNotificationCenter.DefaultCenter.AddObserver (new NSString ("UIKeyboardWillHideNotification"), delegate (NSNotification n) + { var kbdRect = UIKeyboard.BoundsFromNotification (n); var duration = UIKeyboard.AnimationDurationFromNotification (n); var frame = View.Frame; diff --git a/MonoCatalog-MonoDevelop/ToolbarViewController.xib.cs b/MonoCatalog-MonoDevelop/ToolbarViewController.xib.cs index 9cd608c47..cdec98347 100644 --- a/MonoCatalog-MonoDevelop/ToolbarViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/ToolbarViewController.xib.cs @@ -38,7 +38,7 @@ public partial class ToolbarViewController : UIViewController { "Redo" }; - public ToolbarViewController () : base ("ToolbarViewController", null) {} + public ToolbarViewController () : base ("ToolbarViewController", null) { } // // This is the general callback that we give to buttons to show how to hook events up @@ -52,9 +52,9 @@ void Action (object sender, EventArgs args) void CreateToolbarItems () { // The order is mapped one to one to the UIBarButtonItemStyle - var style = (UIBarButtonItemStyle)(int) buttonItemStyleSegControl.SelectedSegment; + var style = (UIBarButtonItemStyle) (int) buttonItemStyleSegControl.SelectedSegment; - var systemItem = new UIBarButtonItem (currentSystemItem, Action){ + var systemItem = new UIBarButtonItem (currentSystemItem, Action) { Style = style }; @@ -75,13 +75,13 @@ public override void ViewDidLoad () NavigationController.NavigationBar.Translucent = false; View.BackgroundColor = UIColor.GroupTableViewBackgroundColor; - toolbar = new UIToolbar() { + toolbar = new UIToolbar () { BarStyle = UIBarStyle.Default }; toolbar.SizeToFit (); - float toolbarHeight = (float)toolbar.Frame.Height; + float toolbarHeight = (float) toolbar.Frame.Height; var mainViewBounds = View.Bounds; - toolbar.Frame = new CGRect (mainViewBounds.X, (float)(mainViewBounds.Y + mainViewBounds.Height - toolbarHeight * 2 + 2), + toolbar.Frame = new CGRect (mainViewBounds.X, (float) (mainViewBounds.Y + mainViewBounds.Height - toolbarHeight * 2 + 2), mainViewBounds.Width, toolbarHeight); View.AddSubview (toolbar); currentSystemItem = UIBarButtonSystemItem.Done; @@ -102,7 +102,7 @@ partial void toggleStyle (UISegmentedControl sender) { var style = UIBarButtonItemStyle.Plain; - switch (sender.SelectedSegment){ + switch (sender.SelectedSegment) { case 0: style = UIBarButtonItemStyle.Plain; break; @@ -119,7 +119,7 @@ partial void toggleStyle (UISegmentedControl sender) partial void toggleBarStyle (UISegmentedControl sender) { - switch (sender.SelectedSegment){ + switch (sender.SelectedSegment) { case 0: toolbar.BarStyle = UIBarStyle.Default; break; @@ -137,14 +137,14 @@ partial void toggleBarStyle (UISegmentedControl sender) partial void toggleTintColor (UISwitch sender) { - if (sender.On){ + if (sender.On) { toolbar.TintColor = UIColor.Red; barStyleSegControl.Enabled = false; barStyleSegControl.Alpha = 0.5f; } else { toolbar.TintColor = null; barStyleSegControl.Enabled = true; - barStyleSegControl.Alpha = 1.0f; + barStyleSegControl.Alpha = 1.0f; } } @@ -158,7 +158,7 @@ public ItemPickerModel (ToolbarViewController tvc) public override void Selected (UIPickerView picker, nint row, nint component) { - tvc.currentSystemItem = (UIBarButtonSystemItem) (int)picker.SelectedRowInComponent (0); + tvc.currentSystemItem = (UIBarButtonSystemItem) (int) picker.SelectedRowInComponent (0); tvc.CreateToolbarItems (); } diff --git a/MonoCatalog-MonoDevelop/TransitionViewController.xib.cs b/MonoCatalog-MonoDevelop/TransitionViewController.xib.cs index 68663684f..46a3cb923 100644 --- a/MonoCatalog-MonoDevelop/TransitionViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/TransitionViewController.xib.cs @@ -10,7 +10,7 @@ namespace MonoCatalog { public partial class TransitionViewController : UIViewController { - public TransitionViewController () : base ("TransitionViewController", null) {} + public TransitionViewController () : base ("TransitionViewController", null) { } const float kImageHeight = 200f; const float kImageWidth = 250f; @@ -24,15 +24,15 @@ public override void ViewDidLoad () { Title = "Transition"; - containerView = new UIView (new CGRect ((View.Bounds.Width - kImageWidth)/2.0f, kTopPlacement, kImageWidth, kImageHeight)); + containerView = new UIView (new CGRect ((View.Bounds.Width - kImageWidth) / 2.0f, kTopPlacement, kImageWidth, kImageHeight)); View.AddSubview (containerView); - mainView = new UIImageView (new CGRect (0, 0, kImageWidth, kImageHeight)){ + mainView = new UIImageView (new CGRect (0, 0, kImageWidth, kImageHeight)) { Image = UIImage.FromFile ("images/scene1.jpg") }; containerView.AddSubview (mainView); - flipToView = new UIImageView (new CGRect (0, 0, kImageWidth, kImageHeight)){ + flipToView = new UIImageView (new CGRect (0, 0, kImageWidth, kImageHeight)) { Image = UIImage.FromFile ("images/scene2.jpg") }; } @@ -45,7 +45,7 @@ partial void flipAction (UIBarButtonItem sender) mainView.Superview != null ? UIViewAnimationTransition.FlipFromLeft : UIViewAnimationTransition.FlipFromRight, containerView, true); - if (flipToView.Superview == null){ + if (flipToView.Superview == null) { mainView.RemoveFromSuperview (); containerView.AddSubview (flipToView); } else { @@ -63,7 +63,7 @@ partial void curlAction (UIBarButtonItem sender) mainView.Superview != null ? UIViewAnimationTransition.CurlUp : UIViewAnimationTransition.CurlDown, containerView, true); - if (flipToView.Superview == null){ + if (flipToView.Superview == null) { mainView.RemoveFromSuperview (); containerView.AddSubview (flipToView); } else { diff --git a/MonoCatalog-MonoDevelop/WebViewController.xib.cs b/MonoCatalog-MonoDevelop/WebViewController.xib.cs index ba498f8b9..8cc0c3c99 100644 --- a/MonoCatalog-MonoDevelop/WebViewController.xib.cs +++ b/MonoCatalog-MonoDevelop/WebViewController.xib.cs @@ -42,10 +42,12 @@ public override void ViewDidLoad () ScalesPageToFit = true, AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight }; - web.LoadStarted += delegate { + web.LoadStarted += delegate + { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; }; - web.LoadFinished += delegate { + web.LoadFinished += delegate + { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; }; web.LoadError += (webview, args) => { @@ -55,7 +57,7 @@ public override void ViewDidLoad () View.AddSubview (web); // Delegate = new - var urlField = new UITextField (new CGRect (20f, 10f, View.Bounds.Width - (20f * 2f), 30f)){ + var urlField = new UITextField (new CGRect (20f, 10f, View.Bounds.Width - (20f * 2f), 30f)) { BorderStyle = UITextBorderStyle.Bezel, TextColor = UIColor.Black, Placeholder = "<enter a URL>", @@ -69,7 +71,8 @@ public override void ViewDidLoad () ClearButtonMode = UITextFieldViewMode.Always }; - urlField.ShouldReturn = delegate (UITextField field){ + urlField.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); web.LoadRequest (NSUrlRequest.FromUrl (new NSUrl (field.Text))); diff --git a/MonoDevelopTouchCells/AppDelegate.cs b/MonoDevelopTouchCells/AppDelegate.cs index dd63c1117..65035a3b9 100644 --- a/MonoDevelopTouchCells/AppDelegate.cs +++ b/MonoDevelopTouchCells/AppDelegate.cs @@ -1,14 +1,12 @@ -using System.IO; +using System.IO; using System.Xml.Linq; using System.Linq; using Foundation; using UIKit; -namespace MonoDevelopTouchCells -{ +namespace MonoDevelopTouchCells { // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { DetailViewController detailViewController = new DetailViewController (); // This method is invoked when the application has loaded its UI and its ready to run @@ -46,13 +44,14 @@ void InitializeTableData () XDocument xdoc = XDocument.Load (source);//Path.Combine(Directory.GetCurrentDirectory(), "data.xml")); var items = from c in xdoc.Descendants ("item") - select new Item { - Title = (string)c.Element ("title"), - Checked = (bool)c.Element ("checked"), - }; + select new Item { + Title = (string) c.Element ("title"), + Checked = (bool) c.Element ("checked"), + }; myTableView.Delegate = new TableViewDelegate (); - myTableView.InvokeOnMainThread (delegate { + myTableView.InvokeOnMainThread (delegate + { myTableView.DataSource = new DataSource (items); }); } diff --git a/MonoDevelopTouchCells/CustomCell.cs b/MonoDevelopTouchCells/CustomCell.cs index d337ad428..d4624f2bc 100755 --- a/MonoDevelopTouchCells/CustomCell.cs +++ b/MonoDevelopTouchCells/CustomCell.cs @@ -4,11 +4,9 @@ using System.Collections.Generic; using CoreGraphics; -namespace MonoDevelopTouchCells -{ +namespace MonoDevelopTouchCells { [Register] - public class CustomCell : UITableViewCell - { + public class CustomCell : UITableViewCell { public string Title { get { return this.TextLabel.Text; } set { this.TextLabel.Text = value; } diff --git a/MonoDevelopTouchCells/DataSource.cs b/MonoDevelopTouchCells/DataSource.cs index 80da1bcfa..559336e18 100644 --- a/MonoDevelopTouchCells/DataSource.cs +++ b/MonoDevelopTouchCells/DataSource.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace MonoDevelopTouchCells -{ - public class DataSource : UITableViewDataSource - { +namespace MonoDevelopTouchCells { + public class DataSource : UITableViewDataSource { List<Item> Data { get; set; } public DataSource (IEnumerable<Item> data) @@ -28,7 +26,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde { string customCellID = "MyCellID" + indexPath.Section + indexPath.Row; - CustomCell cell = (CustomCell)tableView.DequeueReusableCell (customCellID); + CustomCell cell = (CustomCell) tableView.DequeueReusableCell (customCellID); if (cell == null) { cell = new CustomCell (UITableViewCellStyle.Default, customCellID); diff --git a/MonoDevelopTouchCells/DetailViewController.xib.cs b/MonoDevelopTouchCells/DetailViewController.xib.cs index 398baefc7..b3fe82a6d 100644 --- a/MonoDevelopTouchCells/DetailViewController.xib.cs +++ b/MonoDevelopTouchCells/DetailViewController.xib.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace MonoDevelopTouchCells -{ - public partial class DetailViewController : UIViewController - { +namespace MonoDevelopTouchCells { + public partial class DetailViewController : UIViewController { // This is required for controllers that need to be able to be // created from a xib rather than from managed code public DetailViewController (IntPtr handle) : base (handle) diff --git a/MonoDevelopTouchCells/Item.cs b/MonoDevelopTouchCells/Item.cs index 4ab2a7511..678f0166a 100644 --- a/MonoDevelopTouchCells/Item.cs +++ b/MonoDevelopTouchCells/Item.cs @@ -1,10 +1,8 @@ using System; using System.Xml.Serialization; -namespace MonoDevelopTouchCells -{ - public class Item - { +namespace MonoDevelopTouchCells { + public class Item { public string Title { get; set; } public bool Checked { get; set; } diff --git a/MonoDevelopTouchCells/Main.cs b/MonoDevelopTouchCells/Main.cs index 68f4e9d17..152526dc4 100644 --- a/MonoDevelopTouchCells/Main.cs +++ b/MonoDevelopTouchCells/Main.cs @@ -1,13 +1,11 @@ using UIKit; -namespace MonoDevelopTouchCells -{ - public class Application - { - static void Main (string[] args) +namespace MonoDevelopTouchCells { + public class Application { + static void Main (string [] args) { UIApplication.Main (args); } } - + } diff --git a/MonoDevelopTouchCells/TableViewDelegate.cs b/MonoDevelopTouchCells/TableViewDelegate.cs index efb2c3919..c0c32f2ff 100644 --- a/MonoDevelopTouchCells/TableViewDelegate.cs +++ b/MonoDevelopTouchCells/TableViewDelegate.cs @@ -2,11 +2,9 @@ using UIKit; using Foundation; -namespace MonoDevelopTouchCells -{ +namespace MonoDevelopTouchCells { - public class TableViewDelegate : UITableViewDelegate - { + public class TableViewDelegate : UITableViewDelegate { public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { CustomCell cell = tableView.CellAt (indexPath) as CustomCell; @@ -23,7 +21,7 @@ public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath i CustomCell cell = tableView.CellAt (indexPath) as CustomCell; if (cell != null) { - AppDelegate ad = (AppDelegate)UIApplication.SharedApplication.Delegate; + AppDelegate ad = (AppDelegate) UIApplication.SharedApplication.Delegate; ad.ShowDetail (cell); } } diff --git a/MotionGraphs/MotionGraphs/AppDelegate.cs b/MotionGraphs/MotionGraphs/AppDelegate.cs index cc03b7db7..e532ace90 100644 --- a/MotionGraphs/MotionGraphs/AppDelegate.cs +++ b/MotionGraphs/MotionGraphs/AppDelegate.cs @@ -6,19 +6,16 @@ using MotionGraphs; -namespace MotionGraphs -{ - public class Application - { - static void Main (string[] args) +namespace MotionGraphs { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } } [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; CMMotionManager motion_manager; @@ -35,7 +32,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window = new UIWindow (UIScreen.MainScreen.Bounds); UITabBarController tabBarController = new UITabBarController (); - tabBarController.SetViewControllers (new UIViewController[] { + tabBarController.SetViewControllers (new UIViewController [] { new GraphViewController ("Accelerometer", MotionDataType.AccelerometerData), new GraphViewController ("Gyro", MotionDataType.GyroData), new GraphViewController ("DeviceMotion", MotionDataType.DeviceMotion) diff --git a/MotionGraphs/MotionGraphs/GraphView.cs b/MotionGraphs/MotionGraphs/GraphView.cs index 634ce23c0..85a861507 100644 --- a/MotionGraphs/MotionGraphs/GraphView.cs +++ b/MotionGraphs/MotionGraphs/GraphView.cs @@ -5,8 +5,7 @@ using CoreGraphics; using CoreAnimation; -namespace MotionGraphs -{ +namespace MotionGraphs { // The GraphView class needs to be able to update the scene // quickly in order to track the data at a fast enough frame // rate. The naive implementation tries to draw the entire @@ -18,13 +17,12 @@ namespace MotionGraphs // // Functions used to draw all content [Register ("GraphView")] - public class GraphView : UIView - { + public class GraphView : UIView { CGPoint kSegmentInitialPosition = new CGPoint (14.0f, 56.0f); List<GraphViewSegment> segments { get; set; } - GraphTextView text { get; set; } + GraphTextView text { get; set; } GraphViewSegment current { get; set; } @@ -67,7 +65,7 @@ public GraphView (NSCoder coder) : base (coder) public static CGColor CreateDeviceGrayColor (float w, float a) { using (var gray = CGColorSpace.CreateDeviceGray ()) { - return new CGColor (gray, new nfloat[] { w, a }); + return new CGColor (gray, new nfloat [] { w, a }); } } @@ -193,8 +191,7 @@ public override void Draw (CGRect rect) // drawn over the graph, and hides the fact that the // graph drawing for each segment is incomplete until // the segment is filled. - class GraphTextView : UIView - { + class GraphTextView : UIView { public GraphTextView (CGRect rect) : base (rect) { } @@ -232,13 +229,12 @@ public override void Draw (CGRect rect) } // The GraphViewSegment manages up to 32 values and a CALayer that it updates with // the segment of the graph that those values represent. - class GraphViewSegment - { + class GraphViewSegment { public CALayer Layer { get; set; } // Need 33 values to fill 32 pixel width. - double[] xhistory = new double [33]; - double[] yhistory = new double [33]; - double[] zhistory = new double [33]; + double [] xhistory = new double [33]; + double [] yhistory = new double [33]; + double [] zhistory = new double [33]; int index; public GraphViewSegment () @@ -250,7 +246,7 @@ public GraphViewSegment () index = 33; } - void Clear (double[] array) + void Clear (double [] array) { for (int i = 0; i < array.Length; i++) array [i] = 0; @@ -292,8 +288,7 @@ public bool AddX (double x, double y, double z) return index == 0; } - class LayerDelegate : CALayerDelegate - { + class LayerDelegate : CALayerDelegate { GraphViewSegment _parent; public LayerDelegate (GraphViewSegment parent) @@ -312,15 +307,15 @@ public override void DrawLayer (CALayer layer, CGContext context) DrawGridLines (context, 0.0f, 32.0f); //Draw the graph - CGPoint[] lines = new CGPoint[64]; + CGPoint [] lines = new CGPoint [64]; int i; //X for (i = 0; i < 32; ++i) { lines [i * 2].X = i; - lines [i * 2].Y = ((float)(_parent.xhistory [i] * (-1)) * 16.0f); + lines [i * 2].Y = ((float) (_parent.xhistory [i] * (-1)) * 16.0f); lines [(i * 2 + 1)].X = i + 1; - lines [(i * 2 + 1)].Y = ((float)(_parent.xhistory [i + 1] * (-1)) * 16.0f); + lines [(i * 2 + 1)].Y = ((float) (_parent.xhistory [i + 1] * (-1)) * 16.0f); } context.SetStrokeColor (GraphXColor ()); @@ -328,8 +323,8 @@ public override void DrawLayer (CALayer layer, CGContext context) //Y for (i = 0; i < 32; ++i) { - lines [i * 2].Y = ((float)(_parent.yhistory [i] * (-1)) * 16.0f); - lines [(i * 2 + 1)].Y = ((float)(_parent.yhistory [i + 1] * (-1)) * 16.0f); + lines [i * 2].Y = ((float) (_parent.yhistory [i] * (-1)) * 16.0f); + lines [(i * 2 + 1)].Y = ((float) (_parent.yhistory [i + 1] * (-1)) * 16.0f); } context.SetStrokeColor (GraphYColor ()); @@ -337,8 +332,8 @@ public override void DrawLayer (CALayer layer, CGContext context) //Z for (i = 0; i < 32; ++i) { - lines [i * 2].Y = ((float)(_parent.zhistory [i] * (-1)) * 16.0f); - lines [(i * 2 + 1)].Y = ((float)(_parent.zhistory [i + 1] * (-1)) * 16.0f); + lines [i * 2].Y = ((float) (_parent.zhistory [i] * (-1)) * 16.0f); + lines [(i * 2 + 1)].Y = ((float) (_parent.zhistory [i + 1] * (-1)) * 16.0f); } context.SetStrokeColor (GraphZColor ()); diff --git a/MotionGraphs/MotionGraphs/GraphViewController.cs b/MotionGraphs/MotionGraphs/GraphViewController.cs index 22fe7dd4e..58ca53803 100644 --- a/MotionGraphs/MotionGraphs/GraphViewController.cs +++ b/MotionGraphs/MotionGraphs/GraphViewController.cs @@ -5,28 +5,24 @@ using CoreMotion; using UIKit; -namespace MotionGraphs -{ - public enum MotionDataType - { +namespace MotionGraphs { + public enum MotionDataType { AccelerometerData, GyroData, DeviceMotion } - public enum DeviceMotionGraphType - { + public enum DeviceMotionGraphType { Attitude, RotationRate, Gravity, UserAcceleration } - public partial class GraphViewController : UIViewController - { + public partial class GraphViewController : UIViewController { MotionDataType graphDataSource; List<string> graphTitles; - List<GraphView>graphs; + List<GraphView> graphs; CMMotionManager mManager; const double accelerometrMin = 0.01; const double gyroMin = 0.01; @@ -50,7 +46,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. //Delegate has to be called - AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; + AppDelegate appDelegate = (AppDelegate) UIApplication.SharedApplication.Delegate; mManager = appDelegate.SharedManager; UpdateIntervalSlider.Value = 0.0f; if (graphDataSource != MotionDataType.DeviceMotion) { @@ -69,7 +65,7 @@ public override void ViewDidLoad () public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); - StartUpdatesWithMotionDataType (graphDataSource, (int)(UpdateIntervalSlider.Value * 100)); + StartUpdatesWithMotionDataType (graphDataSource, (int) (UpdateIntervalSlider.Value * 100)); } public override void ViewDidDisappear (bool animated) @@ -80,16 +76,16 @@ public override void ViewDidDisappear (bool animated) partial void OnSliderValueChanged (UISlider sender) { - StartUpdatesWithMotionDataType (graphDataSource, (int)(sender.Value * 100)); + StartUpdatesWithMotionDataType (graphDataSource, (int) (sender.Value * 100)); } partial void SegmentedControlDidChanged (UISegmentedControl sender) { - GraphView newView = graphs [(int)sender.SelectedSegment]; + GraphView newView = graphs [(int) sender.SelectedSegment]; primaryGraph.RemoveFromSuperview (); View.AddSubview (newView); primaryGraph = newView; - primaryGraphLabel.Text = graphTitles [(int)sender.SelectedSegment]; + primaryGraphLabel.Text = graphTitles [(int) sender.SelectedSegment]; } public void SetLabelValueX (double x, double y, double z) @@ -115,7 +111,7 @@ public void StartUpdatesWithMotionDataType (MotionDataType type, int sliderValue updateInterval = GraphViewController.accelerometrMin + delta * sliderValue; if (mManager.AccelerometerAvailable) { mManager.AccelerometerUpdateInterval = updateInterval; - mManager.StartAccelerometerUpdates (NSOperationQueue.CurrentQueue, ( data, error) => { + mManager.StartAccelerometerUpdates (NSOperationQueue.CurrentQueue, (data, error) => { if (primaryGraph == null) return; @@ -145,12 +141,12 @@ public void StartUpdatesWithMotionDataType (MotionDataType type, int sliderValue mManager.DeviceMotionUpdateInterval = updateInterval; mManager.StartDeviceMotionUpdates (NSOperationQueue.CurrentQueue, (motion, error) => { - graphs [(int)DeviceMotionGraphType.Attitude].AddX (motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw); - graphs [(int)DeviceMotionGraphType.RotationRate].AddX (motion.RotationRate.x, motion.RotationRate.y, motion.RotationRate.z); - graphs [(int)DeviceMotionGraphType.Gravity].AddX (motion.Gravity.X, motion.Gravity.Y, motion.Gravity.Z); - graphs [(int)DeviceMotionGraphType.UserAcceleration].AddX (motion.UserAcceleration.X, motion.UserAcceleration.Y, motion.UserAcceleration.Z); + graphs [(int) DeviceMotionGraphType.Attitude].AddX (motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw); + graphs [(int) DeviceMotionGraphType.RotationRate].AddX (motion.RotationRate.x, motion.RotationRate.y, motion.RotationRate.z); + graphs [(int) DeviceMotionGraphType.Gravity].AddX (motion.Gravity.X, motion.Gravity.Y, motion.Gravity.Z); + graphs [(int) DeviceMotionGraphType.UserAcceleration].AddX (motion.UserAcceleration.X, motion.UserAcceleration.Y, motion.UserAcceleration.Z); - switch ((DeviceMotionGraphType) (int)SegmentedControl.SelectedSegment) { + switch ((DeviceMotionGraphType) (int) SegmentedControl.SelectedSegment) { case DeviceMotionGraphType.Attitude: SetLabelValueRoll (motion.Attitude.Roll, motion.Attitude.Pitch, motion.Attitude.Yaw); break; @@ -166,7 +162,7 @@ public void StartUpdatesWithMotionDataType (MotionDataType type, int sliderValue } }); } - primaryGraphLabel.Text = graphTitles [(int)SegmentedControl.SelectedSegment]; + primaryGraphLabel.Text = graphTitles [(int) SegmentedControl.SelectedSegment]; break; } UpdateIntervalLabel.Text = updateInterval.ToString (); diff --git a/MoviePlayback/MoviePlaybackSample/AppDelegate.cs b/MoviePlayback/MoviePlaybackSample/AppDelegate.cs index a89d8f1ec..a6624f9d4 100644 --- a/MoviePlayback/MoviePlaybackSample/AppDelegate.cs +++ b/MoviePlayback/MoviePlaybackSample/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace MoviePlaybackSample -{ +namespace MoviePlaybackSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; MoviePlaybackSampleViewController viewController; diff --git a/MoviePlayback/MoviePlaybackSample/Main.cs b/MoviePlayback/MoviePlaybackSample/Main.cs index f0f09e93a..5095a4c98 100644 --- a/MoviePlayback/MoviePlaybackSample/Main.cs +++ b/MoviePlayback/MoviePlaybackSample/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace MoviePlaybackSample -{ - public class Application - { +namespace MoviePlaybackSample { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/MoviePlayback/MoviePlaybackSample/MoviePlaybackSampleViewController.cs b/MoviePlayback/MoviePlaybackSample/MoviePlaybackSampleViewController.cs index 80312033f..9fd383c9c 100644 --- a/MoviePlayback/MoviePlaybackSample/MoviePlaybackSampleViewController.cs +++ b/MoviePlayback/MoviePlaybackSample/MoviePlaybackSampleViewController.cs @@ -3,62 +3,56 @@ using Foundation; using MediaPlayer; -namespace MoviePlaybackSample -{ - public partial class MoviePlaybackSampleViewController : UIViewController - { - //class level declarations - MPMoviePlayerController mp = new MPMoviePlayerController(); +namespace MoviePlaybackSample { + public partial class MoviePlaybackSampleViewController : UIViewController { + //class level declarations + MPMoviePlayerController mp = new MPMoviePlayerController (); - static bool UserInterfaceIdiomIsPhone - { - get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } - } + static bool UserInterfaceIdiomIsPhone { + get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } + } - public MoviePlaybackSampleViewController() - : base(UserInterfaceIdiomIsPhone ? "MoviePlaybackSampleViewController_iPhone" : "MoviePlaybackSampleViewController_iPad", null) - { - } + public MoviePlaybackSampleViewController () + : base (UserInterfaceIdiomIsPhone ? "MoviePlaybackSampleViewController_iPhone" : "MoviePlaybackSampleViewController_iPad", null) + { + } - public override void ViewDidLoad() - { + public override void ViewDidLoad () + { - base.ViewDidLoad(); + base.ViewDidLoad (); - //Button Events - playMovieButton.TouchUpInside += delegate - { + //Button Events + playMovieButton.TouchUpInside += delegate + { - try - { - //Set already instantiated MPMoviePlayerController to playback from Movies/file.m4v - mp = new MPMoviePlayerController(NSUrl.FromFilename("Movies/file.m4v")); + try { + //Set already instantiated MPMoviePlayerController to playback from Movies/file.m4v + mp = new MPMoviePlayerController (NSUrl.FromFilename ("Movies/file.m4v")); - //enable AirPlay - mp.AllowsAirPlay = true; + //enable AirPlay + mp.AllowsAirPlay = true; - //Add the MPMoviePlayerController View - this.View.AddSubview(mp.View); + //Add the MPMoviePlayerController View + this.View.AddSubview (mp.View); - //set the view to be full screen and show animated - mp.SetFullscreen(true, true); + //set the view to be full screen and show animated + mp.SetFullscreen (true, true); - //Disable the pinch-to-zoom gesture - mp.ControlStyle = MPMovieControlStyle.Fullscreen; + //Disable the pinch-to-zoom gesture + mp.ControlStyle = MPMovieControlStyle.Fullscreen; - //MPMoviePlayer must be set to PrepareToPlay before playback - mp.PrepareToPlay(); + //MPMoviePlayer must be set to PrepareToPlay before playback + mp.PrepareToPlay (); - //Play Movie - mp.Play(); - } - catch - { - Console.WriteLine("There was a problem playing back Video"); - } + //Play Movie + mp.Play (); + } catch { + Console.WriteLine ("There was a problem playing back Video"); + } - }; + }; - } - } + } + } } diff --git a/MultichannelMixer/MultichannelMixer/AppDelegate.cs b/MultichannelMixer/MultichannelMixer/AppDelegate.cs index be01b7392..9a3190706 100644 --- a/MultichannelMixer/MultichannelMixer/AppDelegate.cs +++ b/MultichannelMixer/MultichannelMixer/AppDelegate.cs @@ -36,14 +36,12 @@ using AVFoundation; using System.Threading.Tasks; -namespace MultichannelMixer -{ +namespace MultichannelMixer { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { @@ -89,7 +87,7 @@ public override void FinishedLaunching (UIApplication application) throw new ApplicationException (); // add interruption handler - sessionInstance.BeginInterruption += (object sender, EventArgs e) => ((MultichannelMixerViewController)Window.RootViewController).StopForInterruption (); + sessionInstance.BeginInterruption += (object sender, EventArgs e) => ((MultichannelMixerViewController) Window.RootViewController).StopForInterruption (); sessionInstance.EndInterruption += (object sender, EventArgs e) => AVAudioSession.SharedInstance ().SetActive (true); // make sure to activate the session // activate the audio session @@ -99,7 +97,7 @@ public override void FinishedLaunching (UIApplication application) Debug.Print ("Hardware Sample Rate: {0} Hz", sessionInstance.SampleRate); // initialize the mixerController object - var controller = (MultichannelMixerViewController)Window.RootViewController; + var controller = (MultichannelMixerViewController) Window.RootViewController; controller.Mixer.InitializeAUGraph (); } } diff --git a/MultichannelMixer/MultichannelMixer/Main.cs b/MultichannelMixer/MultichannelMixer/Main.cs index 6315ff155..364426942 100644 --- a/MultichannelMixer/MultichannelMixer/Main.cs +++ b/MultichannelMixer/MultichannelMixer/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MultichannelMixer -{ - public class Application - { +namespace MultichannelMixer { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/MultichannelMixer/MultichannelMixer/MultichannelMixerController.cs b/MultichannelMixer/MultichannelMixer/MultichannelMixerController.cs index 77722de84..3b01ab714 100644 --- a/MultichannelMixer/MultichannelMixer/MultichannelMixerController.cs +++ b/MultichannelMixer/MultichannelMixer/MultichannelMixerController.cs @@ -7,12 +7,9 @@ using System.Runtime.InteropServices; using System.Threading.Tasks; -namespace MultichannelMixer -{ - public class MultichannelMixerController : NSObject - { - class SoundBuffer - { +namespace MultichannelMixer { + public class MultichannelMixerController : NSObject { + class SoundBuffer { public IntPtr Data { get; set; } public long TotalFrames { get; set; } public int SampleNum { get; set; } @@ -21,8 +18,8 @@ class SoundBuffer const double GraphSampleRate = 44100.0; AUGraph graph; - CFUrl[] sourceURL; - SoundBuffer[] soundBuffer; + CFUrl [] sourceURL; + SoundBuffer [] soundBuffer; bool playing; AudioUnit.AudioUnit mixer; @@ -37,7 +34,7 @@ public MultichannelMixerController () CFUrl.FromFile (sourceB) }; - soundBuffer = new SoundBuffer[sourceURL.Length]; + soundBuffer = new SoundBuffer [sourceURL.Length]; for (int i = 0; i < soundBuffer.Length; ++i) soundBuffer [i] = new SoundBuffer (); } @@ -134,15 +131,15 @@ void LoadFiles () double rateRatio = GraphSampleRate / clientFormat.SampleRate; var numFrames = file.FileLengthFrames; - numFrames = (uint)(numFrames * rateRatio); // account for any sample rate conversion + numFrames = (uint) (numFrames * rateRatio); // account for any sample rate conversion Debug.Print ("Number of Sample Frames after rate conversion (if any): {0}", numFrames); // set up our buffer - soundBuffer[i].TotalFrames = numFrames; + soundBuffer [i].TotalFrames = numFrames; UInt32 samples = (uint) (numFrames * clientFormat.ChannelsPerFrame); - var data_size = (int)(sizeof(uint) * samples); - soundBuffer[i].Data = Marshal.AllocHGlobal (data_size); + var data_size = (int) (sizeof (uint) * samples); + soundBuffer [i].Data = Marshal.AllocHGlobal (data_size); // set up a AudioBufferList to read data into var bufList = new AudioBuffers (1); @@ -180,7 +177,7 @@ unsafe AudioUnitStatus HandleRenderDelegate (AudioUnitRenderActionFlags actionFl outA [i] = 0; outB [i] = input [sample++]; } else { - outA [i] = input[sample++]; + outA [i] = input [sample++]; outB [i] = 0; } diff --git a/MultichannelMixer/MultichannelMixer/MultichannelMixerViewController.cs b/MultichannelMixer/MultichannelMixer/MultichannelMixerViewController.cs index 0bee5b56b..d75ae861d 100644 --- a/MultichannelMixer/MultichannelMixer/MultichannelMixerViewController.cs +++ b/MultichannelMixer/MultichannelMixer/MultichannelMixerViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace MultichannelMixer -{ - public partial class MultichannelMixerViewController : UIViewController - { +namespace MultichannelMixer { + public partial class MultichannelMixerViewController : UIViewController { public MultichannelMixerViewController (IntPtr handle) : base (handle) { Mixer = new MultichannelMixerController (); @@ -63,7 +61,7 @@ partial void doSomethingAction (NSObject sender) partial void setInputVolume (NSObject sender) { var slider = (UISlider) sender; - Mixer.SetInputVolume ((int)slider.Tag, slider.Value); + Mixer.SetInputVolume ((int) slider.Tag, slider.Value); } partial void setOutputVolume (NSObject sender) @@ -85,7 +83,7 @@ partial void enableInput (NSObject sender) break; } - Mixer.EnableInput ((int)ctrl.Tag, ctrl.On); + Mixer.EnableInput ((int) ctrl.Tag, ctrl.On); } // called if we've been interrupted and if we're playing, stop diff --git a/NSZombieApocalypse/NSZombieApocalypse/AppDelegate.cs b/NSZombieApocalypse/NSZombieApocalypse/AppDelegate.cs index 521005bdb..72572260f 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/AppDelegate.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/AppDelegate.cs @@ -1,11 +1,9 @@ using UIKit; using Foundation; -namespace NSZombieApocalypse -{ +namespace NSZombieApocalypse { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { UIWindow window; ViewController viewController; @@ -25,4 +23,4 @@ public override bool AccessibilityPerformMagicTap () return true; } } -} \ No newline at end of file +} diff --git a/NSZombieApocalypse/NSZombieApocalypse/BodyPart.cs b/NSZombieApocalypse/NSZombieApocalypse/BodyPart.cs index 664d030a0..7ec8fbe51 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/BodyPart.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/BodyPart.cs @@ -2,17 +2,15 @@ using CoreGraphics; using UIKit; -namespace NSZombieApocalypse -{ - public class BodyPart : UIView - { +namespace NSZombieApocalypse { + public class BodyPart : UIView { public BodyPart (CGRect frame) : base (frame) { BackgroundColor = UIColor.Clear; ClipsToBounds = false; } - public bool movingright ; + public bool movingright; public bool MovingRight { get { return movingright; diff --git a/NSZombieApocalypse/NSZombieApocalypse/ButtonCollectionView.cs b/NSZombieApocalypse/NSZombieApocalypse/ButtonCollectionView.cs index 639f6d877..1191b84d5 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/ButtonCollectionView.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/ButtonCollectionView.cs @@ -2,10 +2,8 @@ using CoreGraphics; using UIKit; -namespace NSZombieApocalypse -{ - public enum ButtonType - { +namespace NSZombieApocalypse { + public enum ButtonType { Free, DeAlloc, Release, @@ -15,15 +13,14 @@ public enum ButtonType Count } - public sealed class ButtonCollectionView : UIView - { + public sealed class ButtonCollectionView : UIView { UIImageView trackingImageView; public event ButtonSelectedHandler ButtonSelectedEvent; - public event ButtonDraggedHandler ButtonDraggedEvent; + public event ButtonDraggedHandler ButtonDraggedEvent; public event ButtonFinishedHandler ButtonFinishedEvent; - public ButtonCollectionView (CGRect frame) : base(frame) + public ButtonCollectionView (CGRect frame) : base (frame) { Layer.BorderColor = UIColor.Black.CGColor; Layer.BorderWidth = 1; @@ -37,7 +34,7 @@ public ButtonCollectionView (CGRect frame) : base(frame) button.TrackingContinuedEvent += TrackingContinued; button.TrackingEndedEvent += TrackingEnded; button.Tag = k; - button.SetLabel (ButtonLabelForType ((ButtonType)k)); + button.SetLabel (ButtonLabelForType ((ButtonType) k)); } } @@ -65,9 +62,9 @@ public String ButtonLabelForType (ButtonType type) return null; } - public void TrackingStarted (object sender, TrackingEventArgs e) + public void TrackingStarted (object sender, TrackingEventArgs e) { - var button = (ButtonView)sender; + var button = (ButtonView) sender; UIGraphics.BeginImageContext (button.Bounds.Size); button.Layer.RenderInContext (UIGraphics.GetCurrentContext ()); @@ -91,7 +88,7 @@ public void TrackingStarted (object sender, TrackingEventArgs e) public void TrackingContinued (object sender, TrackingEventArgs e) { - var button = (ButtonView)sender; + var button = (ButtonView) sender; UITouch location = e.Touch; CGPoint point = location.LocationInView (Superview); @@ -103,32 +100,32 @@ public void TrackingContinued (object sender, TrackingEventArgs e) ButtonDraggedEvent (button, location); } - public void TrackingEnded (object sender, TrackingEventArgs e) + public void TrackingEnded (object sender, TrackingEventArgs e) { - var button = (ButtonView)sender; + var button = (ButtonView) sender; ButtonFinishedEvent?.Invoke (button, trackingImageView, e.Touch); trackingImageView = null; } public override void LayoutSubviews () { - UIView[] subviews = Subviews; + UIView [] subviews = Subviews; int count = 0; CGRect bounds = Bounds; CGSize buttonSize = ButtonView.ButtonSize; - float xPad = (float)(bounds.Size.Width - (buttonSize.Width * 3)) / 4; - float yPad = (float)(bounds.Size.Height - (buttonSize.Height * 2)) / 3; + float xPad = (float) (bounds.Size.Width - (buttonSize.Width * 3)) / 4; + float yPad = (float) (bounds.Size.Height - (buttonSize.Height * 2)) / 3; float x = xPad, y = 5; foreach (var subview in subviews) { if (count > 0 && count % 3 == 0) { x = xPad; - y += (float)buttonSize.Height + yPad; + y += (float) buttonSize.Height + yPad; } count++; var frame = new CGRect (x, y, buttonSize.Width, buttonSize.Height); subview.Frame = frame.Integral (); - x += (float)buttonSize.Width + xPad; + x += (float) buttonSize.Width + xPad; } } } @@ -136,4 +133,4 @@ public override void LayoutSubviews () public delegate void ButtonSelectedHandler (ButtonView button); public delegate void ButtonDraggedHandler (ButtonView button, UITouch location); public delegate void ButtonFinishedHandler (ButtonView button, UIView trackingview, UITouch location); -} \ No newline at end of file +} diff --git a/NSZombieApocalypse/NSZombieApocalypse/ButtonView.cs b/NSZombieApocalypse/NSZombieApocalypse/ButtonView.cs index 3be0274e2..0fcc74adc 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/ButtonView.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/ButtonView.cs @@ -2,15 +2,12 @@ using CoreGraphics; using UIKit; -namespace NSZombieApocalypse -{ - public class TrackingEventArgs : EventArgs - { +namespace NSZombieApocalypse { + public class TrackingEventArgs : EventArgs { public UITouch Touch { get; set; } } - public sealed class ButtonView: UIControl - { + public sealed class ButtonView : UIControl { UILabel labelView; UIImageView imageView; @@ -18,7 +15,7 @@ public sealed class ButtonView: UIControl public event EventHandler<TrackingEventArgs> TrackingContinuedEvent; public event EventHandler<TrackingEventArgs> TrackingEndedEvent; - public ButtonView (CGRect frame):base (frame) + public ButtonView (CGRect frame) : base (frame) { imageView = new UIImageView (UIImage.FromBundle ("buttonView.png")); AddSubview (imageView); @@ -125,4 +122,4 @@ public void SetLabel (String labelString) labelView.Text = labelString; } } -} \ No newline at end of file +} diff --git a/NSZombieApocalypse/NSZombieApocalypse/HelpView.cs b/NSZombieApocalypse/NSZombieApocalypse/HelpView.cs index 39816d0a4..7c3c8411d 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/HelpView.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/HelpView.cs @@ -4,16 +4,14 @@ using Foundation; using CoreGraphics; -namespace NSZombieApocalypse -{ - public sealed class HelpView : UIView - { +namespace NSZombieApocalypse { + public sealed class HelpView : UIView { UITextView textView; SymbolMarkView nextButton; - public event HelpDidCloseHandler HelpDidClose; + public event HelpDidCloseHandler HelpDidClose; - public HelpView (CGRect frame): base(frame) + public HelpView (CGRect frame) : base (frame) { BackgroundColor = UIColor.White; Layer.CornerRadius = 8; @@ -107,7 +105,8 @@ public void Show () CGRect frame = Frame; frame.Y = 0; UIView.Animate (.35, () => { - Frame = frame;}); + Frame = frame; + }); } } public delegate void HelpDidCloseHandler (HelpView helpView); diff --git a/NSZombieApocalypse/NSZombieApocalypse/Main.cs b/NSZombieApocalypse/NSZombieApocalypse/Main.cs index 0b6d90e1b..325a2f371 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/Main.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace NSZombieApocalypse -{ - public class Application - { +namespace NSZombieApocalypse { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/NSZombieApocalypse/NSZombieApocalypse/MiniPadView.cs b/NSZombieApocalypse/NSZombieApocalypse/MiniPadView.cs index 81b6b0287..54025e89b 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/MiniPadView.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/MiniPadView.cs @@ -6,11 +6,9 @@ using CoreGraphics; using AVFoundation; -namespace NSZombieApocalypse -{ - public sealed class MiniPadView : UIControl - { - readonly List <WalkingDead> zombies; +namespace NSZombieApocalypse { + public sealed class MiniPadView : UIControl { + readonly List<WalkingDead> zombies; AVAudioPlayer newZombieSound, removeZombieSound; @@ -20,7 +18,7 @@ public int ZombieCount { } } - public MiniPadView (CGRect frame): base(frame) + public MiniPadView (CGRect frame) : base (frame) { var image = UIImage.FromBundle ("iPadImage.png"); Frame = new CGRect (Frame.Location, image.Size); @@ -29,7 +27,7 @@ public MiniPadView (CGRect frame): base(frame) var imageView = new UIImageView (image); AddSubview (imageView); - zombies = new List <WalkingDead> (); + zombies = new List<WalkingDead> (); var audioNewZombie = NSUrl.FromFilename ("NewZombie.mp3"); var audioRemoveZombie = NSUrl.FromFilename ("RemoveZombie.mp3"); @@ -84,4 +82,4 @@ public void RemoveZombie () removeZombieSound.Play (); } } -} \ No newline at end of file +} diff --git a/NSZombieApocalypse/NSZombieApocalypse/StatusView.cs b/NSZombieApocalypse/NSZombieApocalypse/StatusView.cs index d480f0095..97f48a2a7 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/StatusView.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/StatusView.cs @@ -1,10 +1,8 @@ using UIKit; using CoreGraphics; -namespace NSZombieApocalypse -{ - public sealed class StatusView : UIView - { +namespace NSZombieApocalypse { + public sealed class StatusView : UIView { readonly UILabel label; public string Status { @@ -32,4 +30,4 @@ public StatusView (CGRect frame) : base (frame) label.Font = UIFont.FromName ("Helvetica", 36); } } -} \ No newline at end of file +} diff --git a/NSZombieApocalypse/NSZombieApocalypse/SymbolMarkView.cs b/NSZombieApocalypse/NSZombieApocalypse/SymbolMarkView.cs index a34bc7b5b..0bd1806e4 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/SymbolMarkView.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/SymbolMarkView.cs @@ -1,10 +1,8 @@ using UIKit; using CoreGraphics; -namespace NSZombieApocalypse -{ - public sealed class SymbolMarkView :UIButton - { +namespace NSZombieApocalypse { + public sealed class SymbolMarkView : UIButton { UILabel label; string symbol; @@ -16,7 +14,7 @@ public string Symbol { } } - public SymbolMarkView (CGRect frame): base (frame) + public SymbolMarkView (CGRect frame) : base (frame) { label = new UILabel (new CGRect (CGPoint.Empty, frame.Size)) { TextAlignment = UITextAlignment.Center, @@ -39,4 +37,4 @@ public override void Draw (CGRect rect) path.Stroke (); } } -} \ No newline at end of file +} diff --git a/NSZombieApocalypse/NSZombieApocalypse/ViewController.cs b/NSZombieApocalypse/NSZombieApocalypse/ViewController.cs index 05eaede77..7b2810143 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/ViewController.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/ViewController.cs @@ -7,10 +7,8 @@ using CoreAnimation; using ObjCRuntime; -namespace NSZombieApocalypse -{ - public enum TimerEvent - { +namespace NSZombieApocalypse { + public enum TimerEvent { AlmostInfiniteLoop, LogicBomb, Leak, @@ -19,8 +17,7 @@ public enum TimerEvent StagnantReleasePool } - public partial class ViewController : UIViewController - { + public partial class ViewController : UIViewController { const int NSEC_PER_SEC = 1000000000; bool buttonDraggedToPad; @@ -79,7 +76,7 @@ public override void ViewWillAppear (bool animated) NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("voiceOverFinished:"), null, null); } - [Export("voiceOverFinished:")] + [Export ("voiceOverFinished:")] void voiceOverFinished (NSObject notification) { isVoiceOverSpeaking = false; @@ -89,7 +86,7 @@ void Pause () { paused = true; miniPadView.PauseZombies (); - UIAccessibility.PostNotification(UIAccessibilityPostNotification.Announcement, (NSString)"Apocalypse On Pause"); + UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString) "Apocalypse On Pause"); } void Unpause () @@ -97,7 +94,7 @@ void Unpause () paused = false; ZombiesOnATimer (); miniPadView.UnpauseZombies (); - UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString)"Apocalypse resumed"); + UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString) "Apocalypse resumed"); } public void HelpDidClose (HelpView view) @@ -129,7 +126,7 @@ void questionPressed () TimerEvent nextZombieEvent () { int random = rand.Next (); - float point = (float)random / (float)Int32.MaxValue; + float point = (float) random / (float) Int32.MaxValue; if (point < .03) return TimerEvent.AlmostInfiniteLoop; else if (point < .10) @@ -152,13 +149,13 @@ static string StringForZombieEvent (TimerEvent timerEvent) case TimerEvent.AlmostInfiniteLoop: return "An infinite loop broke out! (15MB)"; case TimerEvent.Leak: - return "Memory leak! (3MB)"; + return "Memory leak! (3MB)"; case TimerEvent.LogicBomb: return "A logic bomb went off in your code! (4MB)"; case TimerEvent.OverRetain: return "An object was retained too many times (6MB)"; case TimerEvent.StagnantReleasePool: - return "Your release pools stopped draining! (23MB)"; + return "Your release pools stopped draining! (23MB)"; } return string.Empty; @@ -210,14 +207,14 @@ void ZombiesOnATimer () MonitorZombiePressure (); manageVisibleZombies (); - var popTime = new DispatchTime (DispatchTime.Now, (long)6 * NSEC_PER_SEC); + var popTime = new DispatchTime (DispatchTime.Now, (long) 6 * NSEC_PER_SEC); DispatchQueue.MainQueue.DispatchAfter (popTime, ZombiesOnATimer); } void manageVisibleZombies () { float level = meterView.ZombieLevel; - int zombieCount = (int)Math.Floor (level * 10); + int zombieCount = (int) Math.Floor (level * 10); if (zombieCount < miniPadView.ZombieCount) { while (zombieCount < miniPadView.ZombieCount) miniPadView.RemoveZombie (); @@ -234,13 +231,13 @@ void goForthZombies () statusView.Status = "Your program has started. The zombies are massing"; const double delayInSeconds = 2; - var popTime = new DispatchTime (DispatchTime.Now, (long)(delayInSeconds * NSEC_PER_SEC)); + var popTime = new DispatchTime (DispatchTime.Now, (long) (delayInSeconds * NSEC_PER_SEC)); DispatchQueue.MainQueue.DispatchAfter (popTime, ZombiesOnATimer); } void UpdateScoreForDroppedButton (ButtonView button) { - var buttonType = (ButtonType)(int)button.Tag; + var buttonType = (ButtonType) (int) button.Tag; float change = 0; switch (buttonType) { case ButtonType.Free: @@ -271,7 +268,7 @@ void UpdateScoreForDroppedButton (ButtonView button) public void ButtonSelected (ButtonView button) { if (!isVoiceOverSpeaking) - UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString)"Memory Selected, drag to zombies to play"); + UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString) "Memory Selected, drag to zombies to play"); } public void ButtonDragged (ButtonView button, UITouch location) @@ -288,14 +285,14 @@ public void ButtonDragged (ButtonView button, UITouch location) buttonDraggedToPad = true; if (!isVoiceOverSpeaking) { isVoiceOverSpeaking = true; - UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString)"Memory object near the zombies, Lift to deploy"); + UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString) "Memory object near the zombies, Lift to deploy"); } } } else { if (buttonDraggedToPad) { if (!isVoiceOverSpeaking) { isVoiceOverSpeaking = true; - UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString)"Memory object outside iPad. Lift to Cancel"); + UIAccessibility.PostNotification (UIAccessibilityPostNotification.Announcement, (NSString) "Memory object outside iPad. Lift to Cancel"); } } buttonDraggedToPad = false; @@ -313,17 +310,17 @@ public void ButtonFinished (ButtonView button, UIView trackingView, UITouch loca CGPoint point = location.LocationInView (miniPadView); if (miniPadView.PointInside (point, null)) { UpdateScoreForDroppedButton (button); - UIView.Animate (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (10f * (float)Math.PI / 180), async () => { - await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (-10f * (float)Math.PI / 180)); - await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (10f * (float)Math.PI / 180)); - await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (-10f * (float)Math.PI / 180)); + UIView.Animate (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (10f * (float) Math.PI / 180), async () => { + await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (-10f * (float) Math.PI / 180)); + await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (10f * (float) Math.PI / 180)); + await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (-10f * (float) Math.PI / 180)); await UIView.AnimateAsync (.1f, () => trackingView.Transform = CGAffineTransform.MakeRotation (0)); }); } delayInSeconds = 0.5; - var popTime = new DispatchTime (DispatchTime.Now, (long)(delayInSeconds * NSEC_PER_SEC)); + var popTime = new DispatchTime (DispatchTime.Now, (long) (delayInSeconds * NSEC_PER_SEC)); DispatchQueue.MainQueue.DispatchAfter (popTime, async () => { await UIView.AnimateAsync (0.35f, () => { CGRect bounds = trackingView.Bounds; diff --git a/NSZombieApocalypse/NSZombieApocalypse/WalkingDead.cs b/NSZombieApocalypse/NSZombieApocalypse/WalkingDead.cs index e4c5126b1..bc811833d 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/WalkingDead.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/WalkingDead.cs @@ -5,10 +5,8 @@ using CoreGraphics; -namespace NSZombieApocalypse -{ - public class WalkingDead : UIControl - { +namespace NSZombieApocalypse { + public class WalkingDead : UIControl { Head head; Body body; @@ -23,8 +21,7 @@ public class WalkingDead : UIControl bool animated; bool walkingForward; - class Head : BodyPart - { + class Head : BodyPart { public Head (CGRect rect) : base (rect) { } @@ -67,8 +64,7 @@ public override void Draw (CGRect rect) } } - class Body : BodyPart - { + class Body : BodyPart { public Body (CGRect rect) : base (rect) { } @@ -76,7 +72,7 @@ public Body (CGRect rect) : base (rect) public override void Draw (CGRect rect) { rect = rect.Inset (2, 2); - float bodyWidth = (float)rect.Size.Width / 2; + float bodyWidth = (float) rect.Size.Width / 2; UIBezierPath path = UIBezierPath.FromRoundedRect (new CGRect ((rect.Size.Width - bodyWidth) / 2, 0, bodyWidth, rect.Size.Height), UIRectCorner.TopLeft | UIRectCorner.TopRight, new CGSize (8, 8)); UIColor.Black.SetStroke (); UIColor.White.SetFill (); @@ -86,17 +82,16 @@ public override void Draw (CGRect rect) } } - class RightLeg : BodyPart - { + class RightLeg : BodyPart { public RightLeg (CGRect rect) : base (rect) { } public override void Draw (CGRect rect) { - UIView body = ((WalkingDead)Superview).body; + UIView body = ((WalkingDead) Superview).body; CGRect bodyFrame = body.Frame; - float legWidth = (float)rect.Size.Width / 3; + float legWidth = (float) rect.Size.Width / 3; UIBezierPath path = UIBezierPath.FromRoundedRect (new CGRect (20, bodyFrame.GetMaxY () - 5, legWidth, rect.Size.Height * .25f), UIRectCorner.TopRight | UIRectCorner.BottomRight, new CGSize (3, 3)); path.LineWidth = 2; UIColor.White.SetFill (); @@ -105,17 +100,16 @@ public override void Draw (CGRect rect) } } - class LeftLeg : BodyPart - { + class LeftLeg : BodyPart { public LeftLeg (CGRect rect) : base (rect) { } public override void Draw (CGRect rect) { - UIView body = ((WalkingDead)Superview).body; + UIView body = ((WalkingDead) Superview).body; CGRect bodyFrame = body.Frame; - float legWidth = (float)rect.Size.Width / 3; + float legWidth = (float) rect.Size.Width / 3; UIBezierPath path = UIBezierPath.FromRoundedRect (new CGRect (30, bodyFrame.GetMaxY () - 5, legWidth, (rect.Size.Height) * .25f), UIRectCorner.TopRight | UIRectCorner.BottomRight, new CGSize (3, 3)); UIColor.Black.SetColor (); @@ -126,15 +120,14 @@ public override void Draw (CGRect rect) } } - class RightArm : BodyPart - { + class RightArm : BodyPart { public RightArm (CGRect rect) : base (rect) { } public override void Draw (CGRect rect) { - UIView head = ((WalkingDead)Superview).head; + UIView head = ((WalkingDead) Superview).head; var path = new UIBezierPath (); path.LineCapStyle = CGLineCap.Round; CGRect headFrame = head.Frame; @@ -159,15 +152,14 @@ public override void Draw (CGRect rect) } } - sealed class LeftArm : BodyPart - { + sealed class LeftArm : BodyPart { public LeftArm (CGRect rect) : base (rect) { } public override void Draw (CGRect rect) { - UIView head = ((WalkingDead)Superview).head; + UIView head = ((WalkingDead) Superview).head; var path = new UIBezierPath { LineCapStyle = CGLineCap.Round }; @@ -196,7 +188,7 @@ public override void Draw (CGRect rect) public event DidDisassembleHandler WalkingDeadDidDisassemble; - public WalkingDead (CGRect frame) :base (frame) + public WalkingDead (CGRect frame) : base (frame) { BackgroundColor = UIColor.Clear; ClipsToBounds = false; @@ -252,7 +244,7 @@ public void Walk () CGRect superviewFrame = Superview.Frame; startedWalking = NSDate.Now.SecondsSinceReferenceDate; - startedWalkingX = (float)Frame.X; + startedWalkingX = (float) Frame.X; UIView.Animate (10, 0, UIViewAnimationOptions.AllowUserInteraction, () => { if (!animated) return; @@ -270,14 +262,14 @@ public void Walk () TurnAround (); startedWalking = NSDate.Now.SecondsSinceReferenceDate; - startedWalkingX = (float)Frame.X; + startedWalkingX = (float) Frame.X; CGRect frame = Frame; frame.X = 50; UIView.Animate (10, 0, UIViewAnimationOptions.AllowUserInteraction, () => Frame = frame, Walk); }); } - public void Disassemble () + public void Disassemble () { animated = false; @@ -304,7 +296,7 @@ public void MoveArms () if (!animated) return; - float armRotation = 10 * (float)Math.PI / 180; + float armRotation = 10 * (float) Math.PI / 180; UIView.Animate (1.75, () => { rightArm.Transform = CGAffineTransform.MakeRotation (armRotation); leftArm.Transform = CGAffineTransform.MakeRotation (-armRotation); @@ -326,7 +318,7 @@ public void MoveLegs () if (!animated) return; - const float legRotation = (float)(Math.PI / 4 * .35); + const float legRotation = (float) (Math.PI / 4 * .35); UIView.Animate (2.5, () => { rightLeg.Transform = CGAffineTransform.MakeRotation (legRotation); leftLeg.Transform = CGAffineTransform.MakeRotation (-legRotation); @@ -337,7 +329,7 @@ public void MoveLegs () UIView.Animate (2.5, () => { rightLeg.Transform = CGAffineTransform.MakeRotation (-legRotation); leftLeg.Transform = CGAffineTransform.MakeRotation (legRotation); - },MoveLegs); + }, MoveLegs); }); } @@ -358,8 +350,8 @@ public void DeAnimate () rightLeg.Layer.RemoveAllAnimations (); leftLeg.Layer.RemoveAllAnimations (); - float percentage = (float)(NSDate.Now.SecondsSinceReferenceDate - startedWalking / 10); - float xNow = (float)Math.Abs (Frame.X - startedWalkingX) * percentage; + float percentage = (float) (NSDate.Now.SecondsSinceReferenceDate - startedWalking / 10); + float xNow = (float) Math.Abs (Frame.X - startedWalkingX) * percentage; CGRect frame = Frame; Frame = new CGRect (xNow + (frame.Size.Width / 2), frame.Y, frame.Height, frame.Width); } diff --git a/NSZombieApocalypse/NSZombieApocalypse/ZBEWalkingDeadHead.cs b/NSZombieApocalypse/NSZombieApocalypse/ZBEWalkingDeadHead.cs index 93faa1ca4..fe9d4c04a 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/ZBEWalkingDeadHead.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/ZBEWalkingDeadHead.cs @@ -4,10 +4,8 @@ using MonoTouch.UIKit; using MonoTouch.Foundation; -namespace NSZombieApocalypse -{ - public class ZBEWalkingDeadHead : ZBEBodyPart - { +namespace NSZombieApocalypse { + public class ZBEWalkingDeadHead : ZBEBodyPart { public ZBEWalkingDeadHead () { } diff --git a/NSZombieApocalypse/NSZombieApocalypse/ZombieMeter.cs b/NSZombieApocalypse/NSZombieApocalypse/ZombieMeter.cs index be8c27ef0..3eca16542 100644 --- a/NSZombieApocalypse/NSZombieApocalypse/ZombieMeter.cs +++ b/NSZombieApocalypse/NSZombieApocalypse/ZombieMeter.cs @@ -3,10 +3,8 @@ using UIKit; using CoreGraphics; -namespace NSZombieApocalypse -{ - public sealed class ZombieMeter : UIView - { +namespace NSZombieApocalypse { + public sealed class ZombieMeter : UIView { float zombieLevel; public float ZombieLevel { get { @@ -61,7 +59,7 @@ public override void Draw (CGRect rect) const float pad = 20; const float numberOfMeters = 10; const float meterSpacing = 5; - float yOrigin = (float)label.Frame.GetMaxY () + 10; + float yOrigin = (float) label.Frame.GetMaxY () + 10; UIBezierPath background = UIBezierPath.FromRoundedRect (rect, 8); UIColor.White.SetFill (); @@ -76,7 +74,7 @@ public override void Draw (CGRect rect) (rect.Size.Height - yOrigin - (numberOfMeters * meterSpacing)) / numberOfMeters ); - for (int k =0; k < numberOfMeters; k++) { + for (int k = 0; k < numberOfMeters; k++) { meter.Y = yOrigin + (meter.Height + meterSpacing) * (numberOfMeters - 1 - k); var path = UIBezierPath.FromRoundedRect (meter, 2); path.LineWidth = 1; @@ -113,4 +111,4 @@ public override void Draw (CGRect rect) } } } -} \ No newline at end of file +} diff --git a/NavigationBar/NavigationBar/AppDelegate.cs b/NavigationBar/NavigationBar/AppDelegate.cs index 8a78b2c73..038c64d8b 100644 --- a/NavigationBar/NavigationBar/AppDelegate.cs +++ b/NavigationBar/NavigationBar/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace NavigationBar -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace NavigationBar { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/NavigationBar/NavigationBar/CitiesDataSource.cs b/NavigationBar/NavigationBar/CitiesDataSource.cs index 3f61d2488..0ff7e87ec 100644 --- a/NavigationBar/NavigationBar/CitiesDataSource.cs +++ b/NavigationBar/NavigationBar/CitiesDataSource.cs @@ -1,42 +1,38 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace NavigationBar -{ - public class CitiesDataSource : UITableViewDataSource - { - private readonly List<string> cities = new List<string>(); +namespace NavigationBar { + public class CitiesDataSource : UITableViewDataSource { + private readonly List<string> cities = new List<string> (); - public CitiesDataSource() - { - var citiesJSONURL = NSBundle.MainBundle.PathForResource("Cities", "json"); - var citiesJSONData = NSData.FromFile(citiesJSONURL); - var jsonObject = NSJsonSerialization.Deserialize(citiesJSONData, default(NSJsonReadingOptions), out NSError error); - if (jsonObject is NSArray jsonCities) - { - for (nuint i = 0; i < jsonCities.Count; i++) - { - cities.Add(jsonCities.GetItem<NSString>(i)); - } - } - } + public CitiesDataSource () + { + var citiesJSONURL = NSBundle.MainBundle.PathForResource ("Cities", "json"); + var citiesJSONData = NSData.FromFile (citiesJSONURL); + var jsonObject = NSJsonSerialization.Deserialize (citiesJSONData, default (NSJsonReadingOptions), out NSError error); + if (jsonObject is NSArray jsonCities) { + for (nuint i = 0; i < jsonCities.Count; i++) { + cities.Add (jsonCities.GetItem<NSString> (i)); + } + } + } - public string this[int index] => this.cities[index]; + public string this [int index] => this.cities [index]; - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var flavor = this.cities[indexPath.Row]; - var cell = tableView.DequeueReusableCell("Cell", indexPath); - cell.TextLabel.Text = flavor; - return cell; - } + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var flavor = this.cities [indexPath.Row]; + var cell = tableView.DequeueReusableCell ("Cell", indexPath); + cell.TextLabel.Text = flavor; + return cell; + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.cities.Count; - } - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.cities.Count; + } + } } diff --git a/NavigationBar/NavigationBar/CustomAppearanceViewController.cs b/NavigationBar/NavigationBar/CustomAppearanceViewController.cs index a8f6950ea..a5099df52 100644 --- a/NavigationBar/NavigationBar/CustomAppearanceViewController.cs +++ b/NavigationBar/NavigationBar/CustomAppearanceViewController.cs @@ -3,235 +3,228 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// Demonstrates applying a custom background to a navigation bar. - /// </summary> - public partial class CustomAppearanceViewController : UITableViewController - { - // Our data source is an array of city names, populated from Cities.json. - private CitiesDataSource dataSource = new CitiesDataSource(); - - public CustomAppearanceViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - base.TableView.DataSource = dataSource; - - // Place the background switcher in the toolbar. - var backgroundSwitcherItem = new UIBarButtonItem(backgroundSwitcher); - base.ToolbarItems = new UIBarButtonItem[] - { - new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null, null), - backgroundSwitcherItem, - new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null, null), - }; - - this.ApplyImageBackgroundToTheNavigationBar(); - } - - /// <summary> - /// Configures the navigation bar to use an image as its background. - /// </summary> - private void ApplyImageBackgroundToTheNavigationBar() - { - // These background images contain a small pattern which is displayed - // in the lower right corner of the navigation bar. - var backgroundImageForDefaultBarMetrics = UIImage.FromBundle("NavigationBarDefault"); - var backgroundImageForLandscapePhoneBarMetrics = UIImage.FromBundle("NavigationBarLandscapePhone"); - - // Both of the above images are smaller than the navigation bar's - // size. To enable the images to resize gracefully while keeping their - // content pinned to the bottom right corner of the bar, the images are - // converted into resizable images width edge insets extending from the - // bottom up to the second row of pixels from the top, and from the - // right over to the second column of pixels from the left. This results - // in the topmost and leftmost pixels being stretched when the images - // are resized. Not coincidentally, the pixels in these rows/columns - // are empty. - - backgroundImageForDefaultBarMetrics = - backgroundImageForDefaultBarMetrics.CreateResizableImage(new UIEdgeInsets(0f, - 0f, - backgroundImageForDefaultBarMetrics.Size.Height - 1f, - backgroundImageForDefaultBarMetrics.Size.Width - 1f)); - - backgroundImageForLandscapePhoneBarMetrics = - backgroundImageForLandscapePhoneBarMetrics.CreateResizableImage(new UIEdgeInsets(0f, - 0f, - backgroundImageForLandscapePhoneBarMetrics.Size.Height - 1f, - backgroundImageForLandscapePhoneBarMetrics.Size.Width - 1f)); - - // You should use the appearance proxy to customize the appearance of - // UIKit elements. However changes made to an element's appearance - // proxy do not effect any existing instances of that element currently - // in the view hierarchy. Normally this is not an issue because you - // will likely be performing your appearance customizations in - // -application:didFinishLaunchingWithOptions:. However, this example - // allows you to toggle between appearances at runtime which necessitates - // applying appearance customizations directly to the navigation bar. - var navigationBarAppearance = base.NavigationController.NavigationBar; - - // The bar metrics associated with a background image determine when it - // is used. The background image associated with the Default bar metrics - // is used when a more suitable background image can not be found. - navigationBarAppearance.SetBackgroundImage(backgroundImageForDefaultBarMetrics, UIBarMetrics.Default); - // The background image associated with the LandscapePhone bar metrics - // is used by the shorter variant of the navigation bar that is used on - // iPhone when in landscape. - navigationBarAppearance.SetBackgroundImage(backgroundImageForLandscapePhoneBarMetrics, UIBarMetrics.Compact); - } - - /// <summary> - /// Configures the navigation bar to use a transparent background (see-through but without any blur). - /// </summary> - private void ApplyTransparentBackgroundToTheNavigationBar(float opacity) - { - UIImage transparentBackground = null; - - // The background of a navigation bar switches from being translucent - // to transparent when a background image is applied. The intensity of - // the background image's alpha channel is inversely related to the - // transparency of the bar. That is, a smaller alpha channel intensity - // results in a more transparent bar and vis-versa. - // - // Below, a background image is dynamically generated with the desired - // opacity. - UIGraphics.BeginImageContextWithOptions(new CGSize(1f, 1f), - false, - base.NavigationController.NavigationBar.Layer.ContentsScale); - - var context = UIGraphics.GetCurrentContext(); - context.SetFillColor(1f, 1f, 1f, opacity); - UIGraphics.RectFill(new CGRect(0f, 0f, 1f, 1f)); - transparentBackground = UIGraphics.GetImageFromCurrentImageContext(); - UIGraphics.EndImageContext(); - - // You should use the appearance proxy to customize the appearance of - // UIKit elements. However changes made to an element's appearance - // proxy do not effect any existing instances of that element currently - // in the view hierarchy. Normally this is not an issue because you - // will likely be performing your appearance customizations in - // -application:didFinishLaunchingWithOptions:. However, this example - // allows you to toggle between appearances at runtime which necessitates - // applying appearance customizations directly to the navigation bar. - /* let navigationBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]) */ - var navigationBarAppearance = base.NavigationController.NavigationBar; - - navigationBarAppearance.SetBackgroundImage(transparentBackground, UIBarMetrics.Default); - } - - /// <summary> - /// Configures the navigation bar to use a custom color as its background. The navigation bar remains translucent. - /// </summary> - private void ApplyBarTintColorToTheNavigationBar() - { - // Be aware when selecting a barTintColor for a translucent bar that - // the tint color will be blended with the content passing under - // the translucent bar. See QA1808 for more information. - // <https://developer.apple.com/library/ios/qa/qa1808/_index.html> - var barTintColor = UIColor.FromRGBA(176f / 255f, 226f / 255f, 172f / 255f, 1f); - var darkendBarTintColor = UIColor.FromRGBA(176f / 255f - 0.05f, 226f / 255f - 0.02f, 172f / 255f - 0.05f, 1f); - - // You should use the appearance proxy to customize the appearance of - // UIKit elements. However changes made to an element's appearance - // proxy do not effect any existing instances of that element currently - // in the view hierarchy. Normally this is not an issue because you - // will likely be performing your appearance customizations in - // -application:didFinishLaunchingWithOptions:. However, this example - // allows you to toggle between appearances at runtime which necessitates - // applying appearance customizations directly to the navigation bar. - /* let navigationBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]) */ - var navigationBarAppearance = base.NavigationController.NavigationBar; - - navigationBarAppearance.BarTintColor = darkendBarTintColor; - - // For comparison, apply the same barTintColor to the toolbar, which - // has been configured to be opaque. - base.NavigationController.Toolbar.BarTintColor = barTintColor; - base.NavigationController.Toolbar.Translucent = false; - } - - #region UIContentContainer - - public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) - { - base.ViewWillTransitionToSize(toSize, coordinator); - - // This works around a bug in iOS 8.0 - 8.2 in which the navigation bar - // will not display the correct background image after rotating the device. - // This bug affects bars in navigation controllers that are presented - // modally. A bar in the window's rootViewController would not be affected. - coordinator.AnimateAlongsideTransition((_) => - { - // The workaround is to toggle some appearance related setting on the - // navigation bar when we detect that the view controller has changed - // interface orientations. In our example, we call the - // -configureNewNavBarBackground: which reapplies our appearance - // based on the current selection. In a real app, changing just the - // barTintColor or barStyle would have the same effect. - this.ConfigureNewNavigationBarBackground(this.backgroundSwitcher); - }, null); - } - - #endregion - - #region Background Switcher - - partial void ConfigureNewNavigationBarBackground(UISegmentedControl sender) - { - // Reset everything. - base.NavigationController.NavigationBar.SetBackgroundImage(null, UIBarMetrics.Default); - base.NavigationController.NavigationBar.SetBackgroundImage(null, UIBarMetrics.Compact); - base.NavigationController.NavigationBar.BarTintColor = null; - base.NavigationController.Toolbar.BarTintColor = null; - base.NavigationController.Toolbar.Translucent = true; - - switch (sender.SelectedSegment) - { - case 0: // Transparent Background - this.ApplyImageBackgroundToTheNavigationBar(); - break; - - case 1: // Transparent - this.ApplyTransparentBackgroundToTheNavigationBar(0.87f); - break; - - case 2: // Colored - this.ApplyBarTintColorToTheNavigationBar(); - break; - } - } - - #endregion - - #region UITableViewDelegate - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var selected = this.dataSource[indexPath.Row]; - if (base.NavigationItem.Prompt == selected) - { - base.NavigationItem.Prompt = null; - tableView.DeselectRow(indexPath, true); - } - else - { - base.NavigationItem.Prompt = this.dataSource[indexPath.Row]; - } - } - - #endregion - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - this.dataSource.Dispose(); - this.dataSource = null; - } - } -} \ No newline at end of file +namespace NavigationBar { + /// <summary> + /// Demonstrates applying a custom background to a navigation bar. + /// </summary> + public partial class CustomAppearanceViewController : UITableViewController { + // Our data source is an array of city names, populated from Cities.json. + private CitiesDataSource dataSource = new CitiesDataSource (); + + public CustomAppearanceViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + base.TableView.DataSource = dataSource; + + // Place the background switcher in the toolbar. + var backgroundSwitcherItem = new UIBarButtonItem (backgroundSwitcher); + base.ToolbarItems = new UIBarButtonItem [] + { + new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null, null), + backgroundSwitcherItem, + new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null, null), + }; + + this.ApplyImageBackgroundToTheNavigationBar (); + } + + /// <summary> + /// Configures the navigation bar to use an image as its background. + /// </summary> + private void ApplyImageBackgroundToTheNavigationBar () + { + // These background images contain a small pattern which is displayed + // in the lower right corner of the navigation bar. + var backgroundImageForDefaultBarMetrics = UIImage.FromBundle ("NavigationBarDefault"); + var backgroundImageForLandscapePhoneBarMetrics = UIImage.FromBundle ("NavigationBarLandscapePhone"); + + // Both of the above images are smaller than the navigation bar's + // size. To enable the images to resize gracefully while keeping their + // content pinned to the bottom right corner of the bar, the images are + // converted into resizable images width edge insets extending from the + // bottom up to the second row of pixels from the top, and from the + // right over to the second column of pixels from the left. This results + // in the topmost and leftmost pixels being stretched when the images + // are resized. Not coincidentally, the pixels in these rows/columns + // are empty. + + backgroundImageForDefaultBarMetrics = + backgroundImageForDefaultBarMetrics.CreateResizableImage (new UIEdgeInsets (0f, + 0f, + backgroundImageForDefaultBarMetrics.Size.Height - 1f, + backgroundImageForDefaultBarMetrics.Size.Width - 1f)); + + backgroundImageForLandscapePhoneBarMetrics = + backgroundImageForLandscapePhoneBarMetrics.CreateResizableImage (new UIEdgeInsets (0f, + 0f, + backgroundImageForLandscapePhoneBarMetrics.Size.Height - 1f, + backgroundImageForLandscapePhoneBarMetrics.Size.Width - 1f)); + + // You should use the appearance proxy to customize the appearance of + // UIKit elements. However changes made to an element's appearance + // proxy do not effect any existing instances of that element currently + // in the view hierarchy. Normally this is not an issue because you + // will likely be performing your appearance customizations in + // -application:didFinishLaunchingWithOptions:. However, this example + // allows you to toggle between appearances at runtime which necessitates + // applying appearance customizations directly to the navigation bar. + var navigationBarAppearance = base.NavigationController.NavigationBar; + + // The bar metrics associated with a background image determine when it + // is used. The background image associated with the Default bar metrics + // is used when a more suitable background image can not be found. + navigationBarAppearance.SetBackgroundImage (backgroundImageForDefaultBarMetrics, UIBarMetrics.Default); + // The background image associated with the LandscapePhone bar metrics + // is used by the shorter variant of the navigation bar that is used on + // iPhone when in landscape. + navigationBarAppearance.SetBackgroundImage (backgroundImageForLandscapePhoneBarMetrics, UIBarMetrics.Compact); + } + + /// <summary> + /// Configures the navigation bar to use a transparent background (see-through but without any blur). + /// </summary> + private void ApplyTransparentBackgroundToTheNavigationBar (float opacity) + { + UIImage transparentBackground = null; + + // The background of a navigation bar switches from being translucent + // to transparent when a background image is applied. The intensity of + // the background image's alpha channel is inversely related to the + // transparency of the bar. That is, a smaller alpha channel intensity + // results in a more transparent bar and vis-versa. + // + // Below, a background image is dynamically generated with the desired + // opacity. + UIGraphics.BeginImageContextWithOptions (new CGSize (1f, 1f), + false, + base.NavigationController.NavigationBar.Layer.ContentsScale); + + var context = UIGraphics.GetCurrentContext (); + context.SetFillColor (1f, 1f, 1f, opacity); + UIGraphics.RectFill (new CGRect (0f, 0f, 1f, 1f)); + transparentBackground = UIGraphics.GetImageFromCurrentImageContext (); + UIGraphics.EndImageContext (); + + // You should use the appearance proxy to customize the appearance of + // UIKit elements. However changes made to an element's appearance + // proxy do not effect any existing instances of that element currently + // in the view hierarchy. Normally this is not an issue because you + // will likely be performing your appearance customizations in + // -application:didFinishLaunchingWithOptions:. However, this example + // allows you to toggle between appearances at runtime which necessitates + // applying appearance customizations directly to the navigation bar. + /* let navigationBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]) */ + var navigationBarAppearance = base.NavigationController.NavigationBar; + + navigationBarAppearance.SetBackgroundImage (transparentBackground, UIBarMetrics.Default); + } + + /// <summary> + /// Configures the navigation bar to use a custom color as its background. The navigation bar remains translucent. + /// </summary> + private void ApplyBarTintColorToTheNavigationBar () + { + // Be aware when selecting a barTintColor for a translucent bar that + // the tint color will be blended with the content passing under + // the translucent bar. See QA1808 for more information. + // <https://developer.apple.com/library/ios/qa/qa1808/_index.html> + var barTintColor = UIColor.FromRGBA (176f / 255f, 226f / 255f, 172f / 255f, 1f); + var darkendBarTintColor = UIColor.FromRGBA (176f / 255f - 0.05f, 226f / 255f - 0.02f, 172f / 255f - 0.05f, 1f); + + // You should use the appearance proxy to customize the appearance of + // UIKit elements. However changes made to an element's appearance + // proxy do not effect any existing instances of that element currently + // in the view hierarchy. Normally this is not an issue because you + // will likely be performing your appearance customizations in + // -application:didFinishLaunchingWithOptions:. However, this example + // allows you to toggle between appearances at runtime which necessitates + // applying appearance customizations directly to the navigation bar. + /* let navigationBarAppearance = UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]) */ + var navigationBarAppearance = base.NavigationController.NavigationBar; + + navigationBarAppearance.BarTintColor = darkendBarTintColor; + + // For comparison, apply the same barTintColor to the toolbar, which + // has been configured to be opaque. + base.NavigationController.Toolbar.BarTintColor = barTintColor; + base.NavigationController.Toolbar.Translucent = false; + } + + #region UIContentContainer + + public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) + { + base.ViewWillTransitionToSize (toSize, coordinator); + + // This works around a bug in iOS 8.0 - 8.2 in which the navigation bar + // will not display the correct background image after rotating the device. + // This bug affects bars in navigation controllers that are presented + // modally. A bar in the window's rootViewController would not be affected. + coordinator.AnimateAlongsideTransition ((_) => { + // The workaround is to toggle some appearance related setting on the + // navigation bar when we detect that the view controller has changed + // interface orientations. In our example, we call the + // -configureNewNavBarBackground: which reapplies our appearance + // based on the current selection. In a real app, changing just the + // barTintColor or barStyle would have the same effect. + this.ConfigureNewNavigationBarBackground (this.backgroundSwitcher); + }, null); + } + + #endregion + + #region Background Switcher + + partial void ConfigureNewNavigationBarBackground (UISegmentedControl sender) + { + // Reset everything. + base.NavigationController.NavigationBar.SetBackgroundImage (null, UIBarMetrics.Default); + base.NavigationController.NavigationBar.SetBackgroundImage (null, UIBarMetrics.Compact); + base.NavigationController.NavigationBar.BarTintColor = null; + base.NavigationController.Toolbar.BarTintColor = null; + base.NavigationController.Toolbar.Translucent = true; + + switch (sender.SelectedSegment) { + case 0: // Transparent Background + this.ApplyImageBackgroundToTheNavigationBar (); + break; + + case 1: // Transparent + this.ApplyTransparentBackgroundToTheNavigationBar (0.87f); + break; + + case 2: // Colored + this.ApplyBarTintColorToTheNavigationBar (); + break; + } + } + + #endregion + + #region UITableViewDelegate + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var selected = this.dataSource [indexPath.Row]; + if (base.NavigationItem.Prompt == selected) { + base.NavigationItem.Prompt = null; + tableView.DeselectRow (indexPath, true); + } else { + base.NavigationItem.Prompt = this.dataSource [indexPath.Row]; + } + } + + #endregion + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + this.dataSource.Dispose (); + this.dataSource = null; + } + } +} diff --git a/NavigationBar/NavigationBar/CustomBackButtonDetailViewController.cs b/NavigationBar/NavigationBar/CustomBackButtonDetailViewController.cs index 1326f6f08..b8ae0b89a 100644 --- a/NavigationBar/NavigationBar/CustomBackButtonDetailViewController.cs +++ b/NavigationBar/NavigationBar/CustomBackButtonDetailViewController.cs @@ -1,21 +1,19 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// The detail view controller in the Custom Back Button example. - /// </summary> - public partial class CustomBackButtonDetailViewController : UIViewController - { - public CustomBackButtonDetailViewController(IntPtr handle) : base(handle) { } +namespace NavigationBar { + /// <summary> + /// The detail view controller in the Custom Back Button example. + /// </summary> + public partial class CustomBackButtonDetailViewController : UIViewController { + public CustomBackButtonDetailViewController (IntPtr handle) : base (handle) { } - public string City { get; set; } + public string City { get; set; } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.cityLabel.Text = this.City; - } - } -} \ No newline at end of file + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.cityLabel.Text = this.City; + } + } +} diff --git a/NavigationBar/NavigationBar/CustomBackButtonNavController.cs b/NavigationBar/NavigationBar/CustomBackButtonNavController.cs index fb5988aa3..9559aa87b 100644 --- a/NavigationBar/NavigationBar/CustomBackButtonNavController.cs +++ b/NavigationBar/NavigationBar/CustomBackButtonNavController.cs @@ -1,13 +1,11 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// UINavigationController subclass used for targeting appearance proxy changes in the Custom Back Button example. - /// </summary> - public partial class CustomBackButtonNavController : UINavigationController - { - public CustomBackButtonNavController(IntPtr handle) : base(handle) { } - } -} \ No newline at end of file +namespace NavigationBar { + /// <summary> + /// UINavigationController subclass used for targeting appearance proxy changes in the Custom Back Button example. + /// </summary> + public partial class CustomBackButtonNavController : UINavigationController { + public CustomBackButtonNavController (IntPtr handle) : base (handle) { } + } +} diff --git a/NavigationBar/NavigationBar/CustomBackButtonViewController.cs b/NavigationBar/NavigationBar/CustomBackButtonViewController.cs index 14c8296d3..4d159aa95 100644 --- a/NavigationBar/NavigationBar/CustomBackButtonViewController.cs +++ b/NavigationBar/NavigationBar/CustomBackButtonViewController.cs @@ -2,55 +2,51 @@ using Foundation; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// Demonstrates using a custom back button image with no chevron and no text. - /// </summary> - public partial class CustomBackButtonViewController : UITableViewController - { - // Our data source is an array of city names, populated from Cities.json. - private CitiesDataSource dataSource = new CitiesDataSource(); +namespace NavigationBar { + /// <summary> + /// Demonstrates using a custom back button image with no chevron and no text. + /// </summary> + public partial class CustomBackButtonViewController : UITableViewController { + // Our data source is an array of city names, populated from Cities.json. + private CitiesDataSource dataSource = new CitiesDataSource (); - public CustomBackButtonViewController(IntPtr handle) : base(handle) { } + public CustomBackButtonViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - base.TableView.DataSource = this.dataSource; + public override void ViewDidLoad () + { + base.ViewDidLoad (); + base.TableView.DataSource = this.dataSource; - // Note that images configured as the back bar button's background do - // not have the current tintColor applied to them, they are displayed as it. - var backButtonBackgroundImage = UIImage.FromBundle("Menu"); - // The background should be pinned to the left and not stretch. - backButtonBackgroundImage = backButtonBackgroundImage.CreateResizableImage(new UIEdgeInsets(0f, backButtonBackgroundImage.Size.Width - 1f, 0f, 0f)); + // Note that images configured as the back bar button's background do + // not have the current tintColor applied to them, they are displayed as it. + var backButtonBackgroundImage = UIImage.FromBundle ("Menu"); + // The background should be pinned to the left and not stretch. + backButtonBackgroundImage = backButtonBackgroundImage.CreateResizableImage (new UIEdgeInsets (0f, backButtonBackgroundImage.Size.Width - 1f, 0f, 0f)); - var barAppearance = UINavigationBar.AppearanceWhenContainedIn(typeof(CustomBackButtonNavController)); - barAppearance.BackIndicatorImage = backButtonBackgroundImage; - barAppearance.BackIndicatorTransitionMaskImage = backButtonBackgroundImage; + var barAppearance = UINavigationBar.AppearanceWhenContainedIn (typeof (CustomBackButtonNavController)); + barAppearance.BackIndicatorImage = backButtonBackgroundImage; + barAppearance.BackIndicatorTransitionMaskImage = backButtonBackgroundImage; - // Provide an empty backBarButton to hide the 'Back' text present by - // default in the back button. - // - // NOTE: You do not need to provide a target or action. These are set - // by the navigation bar. - // NOTE: Setting the title of this bar button item to ' ' (space) works - // around a bug in iOS 7.0.x where the background image would be - // horizontally compressed if the back button title is empty. - var backBarButton = new UIBarButtonItem(" ", UIBarButtonItemStyle.Plain, null); - base.NavigationItem.BackBarButtonItem = backBarButton; - } + // Provide an empty backBarButton to hide the 'Back' text present by + // default in the back button. + // + // NOTE: You do not need to provide a target or action. These are set + // by the navigation bar. + // NOTE: Setting the title of this bar button item to ' ' (space) works + // around a bug in iOS 7.0.x where the background image would be + // horizontally compressed if the back button title is empty. + var backBarButton = new UIBarButtonItem (" ", UIBarButtonItemStyle.Plain, null); + base.NavigationItem.BackBarButtonItem = backBarButton; + } - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "DetailSegue") - { - var city = this.dataSource[base.TableView.IndexPathForSelectedRow.Row]; - if (segue.DestinationViewController is CustomBackButtonDetailViewController customBackButtonDetailViewController) - { - customBackButtonDetailViewController.City = city; - } - } - } - } -} \ No newline at end of file + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "DetailSegue") { + var city = this.dataSource [base.TableView.IndexPathForSelectedRow.Row]; + if (segue.DestinationViewController is CustomBackButtonDetailViewController customBackButtonDetailViewController) { + customBackButtonDetailViewController.City = city; + } + } + } + } +} diff --git a/NavigationBar/NavigationBar/CustomRightViewController.cs b/NavigationBar/NavigationBar/CustomRightViewController.cs index ed837b571..85199d443 100644 --- a/NavigationBar/NavigationBar/CustomRightViewController.cs +++ b/NavigationBar/NavigationBar/CustomRightViewController.cs @@ -3,69 +3,66 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// Demonstrates configuring various types of controls as the right bar item of the navigation bar. - /// </summary> - public partial class CustomRightViewController : UIViewController - { +namespace NavigationBar { + /// <summary> + /// Demonstrates configuring various types of controls as the right bar item of the navigation bar. + /// </summary> + public partial class CustomRightViewController : UIViewController { public CustomRightViewController (IntPtr handle) : base (handle) { } - public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() - { - return UIInterfaceOrientationMask.Portrait; - } + public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () + { + return UIInterfaceOrientationMask.Portrait; + } - /// <summary> - /// Action for the segemented control. - /// </summary> - partial void ChangeRightBarItem(UISegmentedControl sender) - { - switch (sender.SelectedSegment) - { - case 0: - // Add a custom add button as the nav bar's custom right view - var addButton = new UIBarButtonItem(NSBundle.MainBundle.GetLocalizedString("AddTitle"), - UIBarButtonItemStyle.Plain, - this.Action); + /// <summary> + /// Action for the segemented control. + /// </summary> + partial void ChangeRightBarItem (UISegmentedControl sender) + { + switch (sender.SelectedSegment) { + case 0: + // Add a custom add button as the nav bar's custom right view + var addButton = new UIBarButtonItem (NSBundle.MainBundle.GetLocalizedString ("AddTitle"), + UIBarButtonItemStyle.Plain, + this.Action); - base.NavigationItem.RightBarButtonItem = addButton; - break; + base.NavigationItem.RightBarButtonItem = addButton; + break; - case 1: - // Add a custom add button as the nav bar's custom right view - var emailButton = new UIBarButtonItem(UIImage.FromBundle("Email"), - UIBarButtonItemStyle.Plain, - this.Action); + case 1: + // Add a custom add button as the nav bar's custom right view + var emailButton = new UIBarButtonItem (UIImage.FromBundle ("Email"), + UIBarButtonItemStyle.Plain, + this.Action); - base.NavigationItem.RightBarButtonItem = emailButton; - break; + base.NavigationItem.RightBarButtonItem = emailButton; + break; - case 2: - // "Segmented" control to the right - var segmentedControl = new UISegmentedControl(new UIImage[] { UIImage.FromBundle("UpArrow"), UIImage.FromBundle("DownArrow") }); + case 2: + // "Segmented" control to the right + var segmentedControl = new UISegmentedControl (new UIImage [] { UIImage.FromBundle ("UpArrow"), UIImage.FromBundle ("DownArrow") }); - segmentedControl.AddTarget(this.Action, UIControlEvent.ValueChanged); - segmentedControl.Frame = new CGRect(0f, 0f, 90f, 30f); - segmentedControl.Momentary = true; + segmentedControl.AddTarget (this.Action, UIControlEvent.ValueChanged); + segmentedControl.Frame = new CGRect (0f, 0f, 90f, 30f); + segmentedControl.Momentary = true; - // Add a custom add button as the nav bar's custom right view - var segmentBarItem = new UIBarButtonItem(segmentedControl); + // Add a custom add button as the nav bar's custom right view + var segmentBarItem = new UIBarButtonItem (segmentedControl); - base.NavigationItem.RightBarButtonItem = segmentBarItem; - break; - } - } + base.NavigationItem.RightBarButtonItem = segmentBarItem; + break; + } + } - private void Action(object sender, EventArgs e) - { - Console.WriteLine("Custom Action was invoked"); - } + private void Action (object sender, EventArgs e) + { + Console.WriteLine ("Custom Action was invoked"); + } - partial void RightAction(UIBarButtonItem sender) - { - Console.WriteLine("RightAction was invoked"); - } - } -} \ No newline at end of file + partial void RightAction (UIBarButtonItem sender) + { + Console.WriteLine ("RightAction was invoked"); + } + } +} diff --git a/NavigationBar/NavigationBar/CustomTitleViewController.cs b/NavigationBar/NavigationBar/CustomTitleViewController.cs index bd8afdb5a..e12137275 100644 --- a/NavigationBar/NavigationBar/CustomTitleViewController.cs +++ b/NavigationBar/NavigationBar/CustomTitleViewController.cs @@ -3,44 +3,42 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// Demonstrates configuring the navigation bar to use a UIView as the title. - /// </summary> - public partial class CustomTitleViewController : UIViewController - { - public CustomTitleViewController(IntPtr handle) : base(handle) { } +namespace NavigationBar { + /// <summary> + /// Demonstrates configuring the navigation bar to use a UIView as the title. + /// </summary> + public partial class CustomTitleViewController : UIViewController { + public CustomTitleViewController (IntPtr handle) : base (handle) { } - public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() - { - return UIInterfaceOrientationMask.Portrait; - } + public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () + { + return UIInterfaceOrientationMask.Portrait; + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - var segmentTextContent = new string[] - { - NSBundle.MainBundle.GetLocalizedString("Image"), - NSBundle.MainBundle.GetLocalizedString("Text"), - NSBundle.MainBundle.GetLocalizedString("Video"), - }; + var segmentTextContent = new string [] + { + NSBundle.MainBundle.GetLocalizedString("Image"), + NSBundle.MainBundle.GetLocalizedString("Text"), + NSBundle.MainBundle.GetLocalizedString("Video"), + }; - // Segmented control as the custom title view - var segmentedControl = new UISegmentedControl(segmentTextContent); - segmentedControl.SelectedSegment = 0; - segmentedControl.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; - segmentedControl.Frame = new CGRect(0f, 0f, 400f, 30f); - segmentedControl.AddTarget(this.Action, UIControlEvent.ValueChanged); + // Segmented control as the custom title view + var segmentedControl = new UISegmentedControl (segmentTextContent); + segmentedControl.SelectedSegment = 0; + segmentedControl.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; + segmentedControl.Frame = new CGRect (0f, 0f, 400f, 30f); + segmentedControl.AddTarget (this.Action, UIControlEvent.ValueChanged); - base.NavigationItem.TitleView = segmentedControl; - } + base.NavigationItem.TitleView = segmentedControl; + } - private void Action(object sender, EventArgs e) - { - Console.WriteLine("CustomTitleViewController IBAction invoked!"); - } - } -} \ No newline at end of file + private void Action (object sender, EventArgs e) + { + Console.WriteLine ("CustomTitleViewController IBAction invoked!"); + } + } +} diff --git a/NavigationBar/NavigationBar/LargeTitleViewController.cs b/NavigationBar/NavigationBar/LargeTitleViewController.cs index 26f62c6fc..59cba607b 100644 --- a/NavigationBar/NavigationBar/LargeTitleViewController.cs +++ b/NavigationBar/NavigationBar/LargeTitleViewController.cs @@ -2,40 +2,35 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// Demonstrates applying a large title to the UINavigationBar. - /// </summary> - public partial class LargeTitleViewController : UITableViewController - { - // Our data source is an array of city names, populated from Cities.json. - private CitiesDataSource dataSource = new CitiesDataSource(); +namespace NavigationBar { + /// <summary> + /// Demonstrates applying a large title to the UINavigationBar. + /// </summary> + public partial class LargeTitleViewController : UITableViewController { + // Our data source is an array of city names, populated from Cities.json. + private CitiesDataSource dataSource = new CitiesDataSource (); - public LargeTitleViewController(IntPtr handle) : base(handle) { } + public LargeTitleViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - base.TableView.DataSource = this.dataSource; + public override void ViewDidLoad () + { + base.ViewDidLoad (); + base.TableView.DataSource = this.dataSource; - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { - base.NavigationController.NavigationBar.PrefersLargeTitles = true; - } - } + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { + base.NavigationController.NavigationBar.PrefersLargeTitles = true; + } + } - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "pushSeque") - { - // This segue is pushing a detailed view controller. - segue.DestinationViewController.Title = dataSource[base.TableView.IndexPathForSelectedRow.Row]; - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { - segue.DestinationViewController.NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Never; - } - } - } - } -} \ No newline at end of file + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "pushSeque") { + // This segue is pushing a detailed view controller. + segue.DestinationViewController.Title = dataSource [base.TableView.IndexPathForSelectedRow.Row]; + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { + segue.DestinationViewController.NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Never; + } + } + } + } +} diff --git a/NavigationBar/NavigationBar/Main.cs b/NavigationBar/NavigationBar/Main.cs index dd37ce2ba..62186f1dc 100644 --- a/NavigationBar/NavigationBar/Main.cs +++ b/NavigationBar/NavigationBar/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace NavigationBar -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace NavigationBar { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/NavigationBar/NavigationBar/MainViewController.cs b/NavigationBar/NavigationBar/MainViewController.cs index 8debc01fa..79776efb7 100644 --- a/NavigationBar/NavigationBar/MainViewController.cs +++ b/NavigationBar/NavigationBar/MainViewController.cs @@ -2,65 +2,60 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// The application's main (initial) view controller. - /// </summary> - public partial class MainViewController : UITableViewController, IUIActionSheetDelegate - { - public MainViewController(IntPtr handle) : base(handle) { } - - public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() - { - return UIInterfaceOrientationMask.Portrait; - } - - /// <summary> - /// Action for the 'Style' bar button item. - /// </summary> - partial void StyleAction(NSObject sender) - { - var title = NSBundle.MainBundle.GetLocalizedString("Choose a UIBarStyle:"); - var cancelButtonTitle = NSBundle.MainBundle.GetLocalizedString("Cancel"); - var defaultButtonTitle = NSBundle.MainBundle.GetLocalizedString("Default"); - var blackOpaqueTitle = NSBundle.MainBundle.GetLocalizedString("Black Opaque"); - var blackTranslucentTitle = NSBundle.MainBundle.GetLocalizedString("Black Translucent"); - - var alertController = UIAlertController.Create(title, null, UIAlertControllerStyle.ActionSheet); - - alertController.AddAction(UIAlertAction.Create(cancelButtonTitle, UIAlertActionStyle.Cancel, null)); - alertController.AddAction(UIAlertAction.Create(defaultButtonTitle, UIAlertActionStyle.Default, _ => - { - base.NavigationController.NavigationBar.BarStyle = UIBarStyle.Default; - // Bars are translucent by default. - base.NavigationController.NavigationBar.Translucent = true; - // Reset the bar's tint color to the system default. - base.NavigationController.NavigationBar.TintColor = null; - })); - - alertController.AddAction(UIAlertAction.Create(blackOpaqueTitle, UIAlertActionStyle.Default, (_) => - { - // Change to black-opaque. - base.NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; - base.NavigationController.NavigationBar.Translucent = false; - base.NavigationController.NavigationBar.TintColor = UIColor.FromRGBA(1f, 0.99997437f, 0.9999912977f, 1f); - })); - alertController.AddAction(UIAlertAction.Create(blackTranslucentTitle, UIAlertActionStyle.Default, (_) => - { - // Change to black-translucent. - base.NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; - base.NavigationController.NavigationBar.Translucent = true; - base.NavigationController.NavigationBar.TintColor = UIColor.FromRGBA(1f, 0.99997437f, 0.9999912977f, 1f); - })); - - base.PresentViewController(alertController, true, null); - } - - /// <summary> - /// Unwind action that is targeted by the demos which present a modal view controller, to return to the main screen. - /// </summary> - [Action("unwindToMainViewController:")] - void UnwindToMainViewController(UIStoryboardSegue sender) { } - } -} \ No newline at end of file +namespace NavigationBar { + /// <summary> + /// The application's main (initial) view controller. + /// </summary> + public partial class MainViewController : UITableViewController, IUIActionSheetDelegate { + public MainViewController (IntPtr handle) : base (handle) { } + + public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () + { + return UIInterfaceOrientationMask.Portrait; + } + + /// <summary> + /// Action for the 'Style' bar button item. + /// </summary> + partial void StyleAction (NSObject sender) + { + var title = NSBundle.MainBundle.GetLocalizedString ("Choose a UIBarStyle:"); + var cancelButtonTitle = NSBundle.MainBundle.GetLocalizedString ("Cancel"); + var defaultButtonTitle = NSBundle.MainBundle.GetLocalizedString ("Default"); + var blackOpaqueTitle = NSBundle.MainBundle.GetLocalizedString ("Black Opaque"); + var blackTranslucentTitle = NSBundle.MainBundle.GetLocalizedString ("Black Translucent"); + + var alertController = UIAlertController.Create (title, null, UIAlertControllerStyle.ActionSheet); + + alertController.AddAction (UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, null)); + alertController.AddAction (UIAlertAction.Create (defaultButtonTitle, UIAlertActionStyle.Default, _ => { + base.NavigationController.NavigationBar.BarStyle = UIBarStyle.Default; + // Bars are translucent by default. + base.NavigationController.NavigationBar.Translucent = true; + // Reset the bar's tint color to the system default. + base.NavigationController.NavigationBar.TintColor = null; + })); + + alertController.AddAction (UIAlertAction.Create (blackOpaqueTitle, UIAlertActionStyle.Default, (_) => { + // Change to black-opaque. + base.NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; + base.NavigationController.NavigationBar.Translucent = false; + base.NavigationController.NavigationBar.TintColor = UIColor.FromRGBA (1f, 0.99997437f, 0.9999912977f, 1f); + })); + alertController.AddAction (UIAlertAction.Create (blackTranslucentTitle, UIAlertActionStyle.Default, (_) => { + // Change to black-translucent. + base.NavigationController.NavigationBar.BarStyle = UIBarStyle.Black; + base.NavigationController.NavigationBar.Translucent = true; + base.NavigationController.NavigationBar.TintColor = UIColor.FromRGBA (1f, 0.99997437f, 0.9999912977f, 1f); + })); + + base.PresentViewController (alertController, true, null); + } + + /// <summary> + /// Unwind action that is targeted by the demos which present a modal view controller, to return to the main screen. + /// </summary> + [Action ("unwindToMainViewController:")] + void UnwindToMainViewController (UIStoryboardSegue sender) { } + } +} diff --git a/NavigationBar/NavigationBar/NavigationPromptViewController.cs b/NavigationBar/NavigationBar/NavigationPromptViewController.cs index f61650aeb..0ad078334 100644 --- a/NavigationBar/NavigationBar/NavigationPromptViewController.cs +++ b/NavigationBar/NavigationBar/NavigationPromptViewController.cs @@ -1,32 +1,30 @@ using System; using UIKit; -namespace NavigationBar -{ - /// <summary> - /// Demonstrates displaying text above the navigation bar. - /// </summary> - public partial class NavigationPromptViewController : UIViewController - { +namespace NavigationBar { + /// <summary> + /// Demonstrates displaying text above the navigation bar. + /// </summary> + public partial class NavigationPromptViewController : UIViewController { public NavigationPromptViewController (IntPtr handle) : base (handle) { } - public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() - { - return UIInterfaceOrientationMask.Portrait; - } + public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () + { + return UIInterfaceOrientationMask.Portrait; + } - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); - // There is a bug in iOS 7.x (fixed in iOS 8) which causes the - // topLayoutGuide to not be properly resized if the prompt is set before - // -viewDidAppear: is called. This may result in the navigation bar - // improperly overlapping your content. For this reason, you should - // avoid configuring the prompt in your storyboard and instead configure - // it programmatically in -viewDidAppear: if your application deploys to iOS 7. - // - base.NavigationItem.Prompt = "Navigation prompts appear at the top."; - } - } -} \ No newline at end of file + // There is a bug in iOS 7.x (fixed in iOS 8) which causes the + // topLayoutGuide to not be properly resized if the prompt is set before + // -viewDidAppear: is called. This may result in the navigation bar + // improperly overlapping your content. For this reason, you should + // avoid configuring the prompt in your storyboard and instead configure + // it programmatically in -viewDidAppear: if your application deploys to iOS 7. + // + base.NavigationItem.Prompt = "Navigation prompts appear at the top."; + } + } +} diff --git a/Newsstand/Newsstand/AppDelegate.cs b/Newsstand/Newsstand/AppDelegate.cs index aaf87ae6a..6a11e326d 100644 --- a/Newsstand/Newsstand/AppDelegate.cs +++ b/Newsstand/Newsstand/AppDelegate.cs @@ -17,4 +17,4 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } } -} \ No newline at end of file +} diff --git a/Newsstand/Newsstand/Main.cs b/Newsstand/Newsstand/Main.cs index 6dce1714f..c98a89865 100644 --- a/Newsstand/Newsstand/Main.cs +++ b/Newsstand/Newsstand/Main.cs @@ -2,7 +2,7 @@ namespace Newsstand { public class Application { - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Newsstand/Newsstand/NewsstandUrlDelegate.cs b/Newsstand/Newsstand/NewsstandUrlDelegate.cs index a92defe44..0c020a18d 100644 --- a/Newsstand/Newsstand/NewsstandUrlDelegate.cs +++ b/Newsstand/Newsstand/NewsstandUrlDelegate.cs @@ -13,11 +13,11 @@ public class NewsstandUrlDelegate1 : NSUrlConnectionDownloadDelegate { /// <summary> /// Pass the issue into the delegate to determine the target file location /// </summary> - public NewsstandUrlDelegate1(string name, NKIssue issue) + public NewsstandUrlDelegate1 (string name, NKIssue issue) { Issue = issue; } - + /// <summary> /// Delivers progress information for the download /// </summary> @@ -40,16 +40,16 @@ public override void FinishedDownloading (NSUrlConnection connection, NSUrl dest { Console.WriteLine ($"Downloaded file: {destinationUrl.Path}"); Console.WriteLine ($"Target issue location: {Issue.ContentUrl.Path}"); - + var saveToFilename = Path.Combine (Issue.ContentUrl.Path, "default.html"); if (!File.Exists (saveToFilename)) File.Move (destinationUrl.Path, saveToFilename); - + Console.WriteLine ($"File moved for issue: {Issue.Name}"); if (OnDownloadingFinished != null) OnDownloadingFinished (); } - } -} \ No newline at end of file + } +} diff --git a/Newsstand/Newsstand/NewsstandViewController.cs b/Newsstand/Newsstand/NewsstandViewController.cs index 63fe9009e..89e2bf29a 100644 --- a/Newsstand/Newsstand/NewsstandViewController.cs +++ b/Newsstand/Newsstand/NewsstandViewController.cs @@ -5,28 +5,27 @@ namespace Newsstand { /// <summary> /// View containing Buttons and TextView to show off the samples /// </summary> - public class NewsstandViewController : UIViewController - { + public class NewsstandViewController : UIViewController { UIButton btnGetLibrary, btnSetReading, btnPopulate, btnDownload, btnRead, btnIcon; UITextView txtView; public override void ViewDidLoad () - { + { base.ViewDidLoad (); - + // Create the buttons and TextView to run the sample code btnGetLibrary = UIButton.FromType (UIButtonType.RoundedRect); - btnGetLibrary.Frame = new CGRect (10f,10f,145f, 50f); + btnGetLibrary.Frame = new CGRect (10f, 10f, 145f, 50f); btnGetLibrary.SetTitle ("Get Library", UIControlState.Normal); - + btnPopulate = UIButton.FromType (UIButtonType.RoundedRect); btnPopulate.Frame = new CGRect (165f, 10f, 145f, 50f); btnPopulate.SetTitle ("Populate Library", UIControlState.Normal); btnSetReading = UIButton.FromType (UIButtonType.RoundedRect); - btnSetReading.Frame = new CGRect(10f, 70f, 145f, 50f); - btnSetReading.SetTitle("Set Reading", UIControlState.Normal); - + btnSetReading.Frame = new CGRect (10f, 70f, 145f, 50f); + btnSetReading.SetTitle ("Set Reading", UIControlState.Normal); + btnDownload = UIButton.FromType (UIButtonType.RoundedRect); btnDownload.Frame = new CGRect (165f, 70f, 145f, 50f); btnDownload.SetTitle ("Download", UIControlState.Normal); @@ -39,11 +38,11 @@ public override void ViewDidLoad () btnIcon.Frame = new CGRect (165f, 130f, 145f, 50f); btnIcon.SetTitle ("Update Icon", UIControlState.Normal); - txtView = new UITextView(new CGRect(10f, 190f, 300f, 250f)) { + txtView = new UITextView (new CGRect (10f, 190f, 300f, 250f)) { Editable = false, ScrollEnabled = true }; - + // Wire up the buttons to the SamplCode class methods btnGetLibrary.TouchUpInside += (sender, e) => { SampleCode.GetLibrary (txtView); @@ -64,7 +63,7 @@ public override void ViewDidLoad () btnRead.TouchUpInside += (sender, e) => { SampleCode.Read (txtView); }; - + btnIcon.TouchUpInside += (sender, e) => { SampleCode.UpdateIcon (txtView); }; @@ -79,4 +78,4 @@ public override void ViewDidLoad () Add (txtView); } } -} \ No newline at end of file +} diff --git a/Newsstand/Newsstand/SampleCode.cs b/Newsstand/Newsstand/SampleCode.cs index 8b1a06359..8bfff462f 100644 --- a/Newsstand/Newsstand/SampleCode.cs +++ b/Newsstand/Newsstand/SampleCode.cs @@ -34,7 +34,7 @@ public static void GetLibrary (UITextView display) /// an issue until it's in the library, since the library keeps /// track of downloads and file locations for you. /// </summary> - public static void PopulateLibrary(UITextView display) + public static void PopulateLibrary (UITextView display) { var library = NKLibrary.SharedLibrary; var weekSeconds = 60 * 60 * 24 * 7; @@ -55,10 +55,10 @@ public static void PopulateLibrary(UITextView display) library.AddIssue ("San Francisco", NSDate.Now.AddSeconds (-3 * weekSeconds)); else display.Text += "\nSan Francisco already added"; - + display.Text += "\n\nLibrary populated!"; } - + /// <summary> /// When the user reads an issue, tell NewsstandKit about it so it can keep track /// </summary> @@ -66,7 +66,7 @@ public static void SetReading (UITextView display) { var library = NKLibrary.SharedLibrary; var issues = library.Issues; - + if (library.CurrentlyReadingIssue == null) { display.Text = "No issue is currently being read"; } else { @@ -77,11 +77,11 @@ public static void SetReading (UITextView display) display.Text += "\n\nNotice how the ContentURL changes for each issue - NewsstandKit manages where your issue's files are stored"; } - var randomIssueNumber = new Random().Next(0,3); + var randomIssueNumber = new Random ().Next (0, 3); // Note: it is possible to set this to an issue with Status=None // (content hasn't been downloaded yet). - library.CurrentlyReadingIssue = issues[randomIssueNumber]; // New York - + library.CurrentlyReadingIssue = issues [randomIssueNumber]; // New York + // Set the Badge to zero to remove the 'New' banner UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; } @@ -103,10 +103,10 @@ public static void Download (UITextView display) if (issues.Length == 0) return; - var issue = issues[1] ; // New York + var issue = issues [1]; // New York NKAssetDownload asset = issue.AddAsset (new NSUrlRequest (new NSUrl ("http://xamarin.com/"))); - + newsstandDelegate = new NewsstandUrlDelegate1 ("NewYorkContent", issue); newsstandDelegate.OnDownloadingFinished += () => { downloading = false; @@ -114,8 +114,8 @@ public static void Download (UITextView display) //you do not have background download privileges: add 'newsstand-content' to mainBundle.infoDictionary.UIBackgroundModes asset.DownloadWithDelegate (newsstandDelegate); - - display.Text = string.Format ("Issue {0} downloading has started", issues[1].Name); + + display.Text = string.Format ("Issue {0} downloading has started", issues [1].Name); display.Text += "\n\nPress the Read button quickly to see the 'downloading' status detected"; } @@ -127,28 +127,28 @@ public static void Read (UITextView display) { var library = NKLibrary.SharedLibrary; var issues = library.Issues; - var issue = issues[1]; // New York + var issue = issues [1]; // New York switch (issue.Status) { - case NKIssueContentStatus.Available: - display.Text = "Just download some random HTML to simulate downloading an issue.\n\n"; - display.Text += string.Format ("Issue '{0}' content has been downloaded to \n\t{1}", issue.Name, issue.ContentUrl.Path); - display.Text += "\n\n\n------------------------------------\n\n\n"; - display.Text += File.ReadAllText (Path.Combine (issue.ContentUrl.Path, "default.html")); - - // set this whenever user reads a different issue - library.CurrentlyReadingIssue = issue; - UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; - break; - case NKIssueContentStatus.Downloading: - display.Text = string.Format ("Issue '{0}' is still downloading...\n\nPress Read again until the content appears", issue.Name); - break; - default: - display.Text = string.Format ("Issue '{0}' has not been downloaded", issue.Name); - break; + case NKIssueContentStatus.Available: + display.Text = "Just download some random HTML to simulate downloading an issue.\n\n"; + display.Text += string.Format ("Issue '{0}' content has been downloaded to \n\t{1}", issue.Name, issue.ContentUrl.Path); + display.Text += "\n\n\n------------------------------------\n\n\n"; + display.Text += File.ReadAllText (Path.Combine (issue.ContentUrl.Path, "default.html")); + + // set this whenever user reads a different issue + library.CurrentlyReadingIssue = issue; + UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; + break; + case NKIssueContentStatus.Downloading: + display.Text = string.Format ("Issue '{0}' is still downloading...\n\nPress Read again until the content appears", issue.Name); + break; + default: + display.Text = string.Format ("Issue '{0}' has not been downloaded", issue.Name); + break; } } - + /// <summary> /// Change the icon that appears in Newsstand - you would do this /// when you download a new issue (via a notification or otherwise). @@ -160,25 +160,25 @@ public static void UpdateIcon (UITextView display) display.Text = string.Format ("Newsstand application badge has been set to 1"); string coverFile = "cover_lasvegas.jpg"; - var randomIssueNumber = new Random().Next(0,4); - switch(randomIssueNumber) { - case 1: - coverFile = "cover_newyork.jpg"; - break; - case 2: - coverFile = "cover_sanfrancisco.jpg"; - break; - case 3: - coverFile = "cover_peru.jpg"; - break; + var randomIssueNumber = new Random ().Next (0, 4); + switch (randomIssueNumber) { + case 1: + coverFile = "cover_newyork.jpg"; + break; + case 2: + coverFile = "cover_sanfrancisco.jpg"; + break; + case 3: + coverFile = "cover_peru.jpg"; + break; } // We can use a downloaded image here - it doesn't have to exist in the // application bundle - UIImage newcover = new UIImage(coverFile); + UIImage newcover = new UIImage (coverFile); // Setting the Newsstand Icon in code doesn't seem to have any effect // if your Info.plist doesn't already define the UINewsstandIcon key UIApplication.SharedApplication.SetNewsstandIconImage (newcover); display.Text += string.Format ("\n\nNewsstand Icon has been set to '{0}'\n\n\nClose the app to see the new cover image in Newsstand", coverFile); } } -} \ No newline at end of file +} diff --git a/Notifications/AppDelegate.cs b/Notifications/AppDelegate.cs index 5972014a6..556c7997a 100644 --- a/Notifications/AppDelegate.cs +++ b/Notifications/AppDelegate.cs @@ -3,11 +3,9 @@ using Foundation; using Example_Notifications.Screens; -namespace Example_Notifications -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace Example_Notifications { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { #region -= declarations and properties =- protected UIWindow window; @@ -24,30 +22,30 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - home = new Screens.iPhone.Home.Home_iPhone(); + home = new Screens.iPhone.Home.Home_iPhone (); home.View.Frame = new CoreGraphics.CGRect (0, UIApplication.SharedApplication.StatusBarFrame.Height, UIScreen.MainScreen.ApplicationFrame.Width, UIScreen.MainScreen.ApplicationFrame.Height); window.RootViewController = home; // check for a notification - if(options != null) { + if (options != null) { // check for a local notification - if(options.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey)) { + if (options.ContainsKey (UIApplication.LaunchOptionsLocalNotificationKey)) { - UILocalNotification localNotification = options[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; - if(localNotification != null) { + UILocalNotification localNotification = options [UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; + if (localNotification != null) { - new UIAlertView(localNotification.AlertAction, localNotification.AlertBody, null, "OK", null).Show(); + new UIAlertView (localNotification.AlertAction, localNotification.AlertBody, null, "OK", null).Show (); // reset our badge UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; } } // check for a remote notification - if(options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey)) { + if (options.ContainsKey (UIApplication.LaunchOptionsRemoteNotificationKey)) { - NSDictionary remoteNotification = options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary; - if(remoteNotification != null) { + NSDictionary remoteNotification = options [UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary; + if (remoteNotification != null) { //new UIAlertView(remoteNotification.AlertAction, remoteNotification.AlertBody, null, "OK", null).Show(); } } @@ -55,8 +53,8 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) { var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes ( - UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null - ); + UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null + ); app.RegisterUserNotificationSettings (notificationSettings); app.RegisterForRemoteNotifications (); @@ -65,7 +63,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // set what kind of notification types we want UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge; // register for remote notifications - UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes); + UIApplication.SharedApplication.RegisterForRemoteNotificationTypes (notificationTypes); } return true; @@ -77,7 +75,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) public override void ReceivedLocalNotification (UIApplication application, UILocalNotification notification) { // show an alert - new UIAlertView(notification.AlertAction, notification.AlertBody, null, "OK", null).Show(); + new UIAlertView (notification.AlertAction, notification.AlertBody, null, "OK", null).Show (); // reset our badge UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; @@ -107,7 +105,7 @@ public override void RegisteredForRemoteNotifications (UIApplication application /// </summary> public override void FailedToRegisterForRemoteNotifications (UIApplication application, NSError error) { - new UIAlertView ("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show(); + new UIAlertView ("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show (); } } } diff --git a/Notifications/Application.cs b/Notifications/Application.cs index 87ee84d24..60eb91d27 100644 --- a/Notifications/Application.cs +++ b/Notifications/Application.cs @@ -1,12 +1,10 @@ using UIKit; -namespace Example_Notifications -{ - public class Application - { - public static void Main(string[] args) +namespace Example_Notifications { + public class Application { + public static void Main (string [] args) { - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/Notifications/Screens/iPhone/DeviceToken/GetDeviceTokenScreen.xib.cs b/Notifications/Screens/iPhone/DeviceToken/GetDeviceTokenScreen.xib.cs index d80d0b4cb..31c3ad568 100644 --- a/Notifications/Screens/iPhone/DeviceToken/GetDeviceTokenScreen.xib.cs +++ b/Notifications/Screens/iPhone/DeviceToken/GetDeviceTokenScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_Notifications.Screens.iPhone.DeviceToken -{ - public partial class GetDeviceTokenScreen : UIViewController - { +namespace Example_Notifications.Screens.iPhone.DeviceToken { + public partial class GetDeviceTokenScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public GetDeviceTokenScreen (IntPtr handle) : base(handle) + public GetDeviceTokenScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public GetDeviceTokenScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public GetDeviceTokenScreen (NSCoder coder) : base (coder) { Initialize (); } - public GetDeviceTokenScreen () : base("GetDeviceTokenScreen", null) + public GetDeviceTokenScreen () : base ("GetDeviceTokenScreen", null) { Initialize (); } @@ -40,7 +38,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - this.lblToken.Text = ((AppDelegate)UIApplication.SharedApplication.Delegate).DeviceToken; + this.lblToken.Text = ((AppDelegate) UIApplication.SharedApplication.Delegate).DeviceToken; } } } diff --git a/Notifications/Screens/iPhone/Home/Home_iPhone.xib.cs b/Notifications/Screens/iPhone/Home/Home_iPhone.xib.cs index d87d21343..dcaabc8d5 100644 --- a/Notifications/Screens/iPhone/Home/Home_iPhone.xib.cs +++ b/Notifications/Screens/iPhone/Home/Home_iPhone.xib.cs @@ -4,21 +4,19 @@ using Foundation; using UIKit; -namespace Example_Notifications.Screens.iPhone.Home -{ - public partial class Home_iPhone : UIViewController - { +namespace Example_Notifications.Screens.iPhone.Home { + public partial class Home_iPhone : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public Home_iPhone (IntPtr handle) : base(handle) { } + public Home_iPhone (IntPtr handle) : base (handle) { } - [Export("initWithCoder:")] - public Home_iPhone (NSCoder coder) : base(coder) { } + [Export ("initWithCoder:")] + public Home_iPhone (NSCoder coder) : base (coder) { } - public Home_iPhone () : base("Home_iPhone", null) { } + public Home_iPhone () : base ("Home_iPhone", null) { } #endregion @@ -34,7 +32,7 @@ public override void ViewDidLoad () //---- set the fire date (the date time in which it will fire) var fireDate = DateTime.Now.AddSeconds (60); - notification.FireDate = (NSDate)fireDate; + notification.FireDate = (NSDate) fireDate; //---- configure the alert stuff notification.AlertAction = "View Alert"; @@ -46,8 +44,8 @@ public override void ViewDidLoad () //---- set the sound to be the default sound notification.SoundName = UILocalNotification.DefaultSoundName; -// notification.UserInfo = new NSDictionary(); -// notification.UserInfo[new NSString("Message")] = new NSString("Your 1 minute notification has fired!"); + // notification.UserInfo = new NSDictionary(); + // notification.UserInfo[new NSString("Message")] = new NSString("Your 1 minute notification has fired!"); //---- schedule it UIApplication.SharedApplication.ScheduleLocalNotification (notification); diff --git a/OpenGL/GLKBaseEffectDrawing/AppDelegate.cs b/OpenGL/GLKBaseEffectDrawing/AppDelegate.cs index 4f7e3d1eb..edc9bbcd0 100644 --- a/OpenGL/GLKBaseEffectDrawing/AppDelegate.cs +++ b/OpenGL/GLKBaseEffectDrawing/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace GLKBaseEffectDrawing -{ +namespace GLKBaseEffectDrawing { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; MCViewController controller; diff --git a/OpenGL/GLKBaseEffectDrawing/MCViewController.cs b/OpenGL/GLKBaseEffectDrawing/MCViewController.cs index f0b7a16e9..d59aae83a 100644 --- a/OpenGL/GLKBaseEffectDrawing/MCViewController.cs +++ b/OpenGL/GLKBaseEffectDrawing/MCViewController.cs @@ -6,10 +6,8 @@ using OpenTK.Graphics.ES20; using CoreGraphics; -namespace GLKBaseEffectDrawing -{ - public class MCViewController : GLKViewController, IGLKViewDelegate - { +namespace GLKBaseEffectDrawing { + public class MCViewController : GLKViewController, IGLKViewDelegate { float rotation; uint vertexArray; uint vertexBuffer; @@ -25,7 +23,7 @@ public override void ViewDidLoad () if (context == null) Console.WriteLine ("Failed to create ES context"); - var view = (GLKView)View; + var view = (GLKView) View; view.Context = context; view.DrawableDepthFormat = GLKViewDrawableDepthFormat.Format24; view.Delegate = this; @@ -63,27 +61,27 @@ void setupGL () GL.GenBuffers (1, out vertexBuffer); GL.BindBuffer (BufferTarget.ArrayBuffer, vertexBuffer); - GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr)(Monkey.MeshVertexData.Length * sizeof(float)), - Monkey.MeshVertexData, BufferUsage.StaticDraw); + GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr) (Monkey.MeshVertexData.Length * sizeof (float)), + Monkey.MeshVertexData, BufferUsage.StaticDraw); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.Position); GL.VertexAttribPointer ((int) GLKVertexAttrib.Position, 3, VertexAttribPointerType.Float, - false, 6 * sizeof(float), 0); + false, 6 * sizeof (float), 0); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.Normal); GL.VertexAttribPointer ((int) GLKVertexAttrib.Normal, 3, VertexAttribPointerType.Float, - false, 6 * sizeof(float), 12); + false, 6 * sizeof (float), 12); GL.Oes.BindVertexArray (0); } public override void Update () { - float aspect = (float)Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); + float aspect = (float) Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); Matrix4 projectionMatrix = Matrix4.CreatePerspectiveFieldOfView ((float) (Math.PI * 65f / 180.0f), - aspect, 0.1f, 100.0f); + aspect, 0.1f, 100.0f); effect.Transform.ProjectionMatrix = projectionMatrix; @@ -92,7 +90,7 @@ public override void Update () effect.Transform.ModelViewMatrix = modelViewMatrix; - rotation += (float)TimeSinceLastUpdate * 0.5f; + rotation += (float) TimeSinceLastUpdate * 0.5f; } public void DrawInRect (GLKView view, CGRect rect) diff --git a/OpenGL/GLKBaseEffectDrawing/Main.cs b/OpenGL/GLKBaseEffectDrawing/Main.cs index d2297c5c6..6145ad6ca 100644 --- a/OpenGL/GLKBaseEffectDrawing/Main.cs +++ b/OpenGL/GLKBaseEffectDrawing/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace GLKBaseEffectDrawing -{ - public class Application - { +namespace GLKBaseEffectDrawing { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/OpenGL/GLKBaseEffectDrawing/Monkey.cs b/OpenGL/GLKBaseEffectDrawing/Monkey.cs index 34a551cf8..845ac044c 100644 --- a/OpenGL/GLKBaseEffectDrawing/Monkey.cs +++ b/OpenGL/GLKBaseEffectDrawing/Monkey.cs @@ -1,11 +1,9 @@ using System; using OpenTK; -namespace GLKBaseEffectDrawing -{ - public static class Monkey - { - public static float[] MeshVertexData = { +namespace GLKBaseEffectDrawing { + public static class Monkey { + public static float [] MeshVertexData = { /*v:*/0.351562f, 0.500724f, 0.433432f, /*n:*/0.183599f, -0.005310f, 0.982971f, /*v:*/0.445312f, 0.414787f, 0.386557f, /*n:*/0.715171f, -0.662465f, 0.222724f, /*v:*/0.476562f, 0.500724f, 0.378744f, /*n:*/0.964446f, -0.012665f, 0.263863f, diff --git a/OpenGL/GLKBaseEffectDrawingTexture/AppDelegate.cs b/OpenGL/GLKBaseEffectDrawingTexture/AppDelegate.cs index 1edb76608..02aa2f4ea 100644 --- a/OpenGL/GLKBaseEffectDrawingTexture/AppDelegate.cs +++ b/OpenGL/GLKBaseEffectDrawingTexture/AppDelegate.cs @@ -1,14 +1,12 @@ using Foundation; using UIKit; -namespace GLKBaseEffectDrawingTexture -{ +namespace GLKBaseEffectDrawingTexture { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { MCViewController controller; public override UIWindow Window { get; set; } diff --git a/OpenGL/GLKBaseEffectDrawingTexture/MCViewController.cs b/OpenGL/GLKBaseEffectDrawingTexture/MCViewController.cs index fe61b7665..d216810a6 100644 --- a/OpenGL/GLKBaseEffectDrawingTexture/MCViewController.cs +++ b/OpenGL/GLKBaseEffectDrawingTexture/MCViewController.cs @@ -6,10 +6,8 @@ using Foundation; using CoreGraphics; -namespace GLKBaseEffectDrawingTexture -{ - public class MCViewController : GLKViewController - { +namespace GLKBaseEffectDrawingTexture { + public class MCViewController : GLKViewController { float rotation; uint vertexArray; @@ -59,19 +57,19 @@ void setupGL () GL.GenBuffers (1, out vertexBuffer); GL.BindBuffer (BufferTarget.ArrayBuffer, vertexBuffer); GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr) (Monkey.MeshVertexData.Length * sizeof (float)), - Monkey.MeshVertexData, BufferUsage.StaticDraw); + Monkey.MeshVertexData, BufferUsage.StaticDraw); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.Position); GL.VertexAttribPointer ((int) GLKVertexAttrib.Position, 3, VertexAttribPointerType.Float, - false, 8 * sizeof (float), 0); + false, 8 * sizeof (float), 0); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.Normal); GL.VertexAttribPointer ((int) GLKVertexAttrib.Normal, 3, VertexAttribPointerType.Float, - false, 8 * sizeof(float), 12); + false, 8 * sizeof (float), 12); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.TexCoord0); GL.VertexAttribPointer ((int) GLKVertexAttrib.TexCoord0, 2, VertexAttribPointerType.Float, - false, 8 * sizeof(float), 24); + false, 8 * sizeof (float), 24); GL.ActiveTexture (TextureUnit.Texture0); string path = NSBundle.MainBundle.PathForResource ("monkey", "png"); @@ -82,7 +80,7 @@ void setupGL () texture = GLKTextureLoader.FromFile (path, options, out error); if (texture == null) - Console.WriteLine (String.Format("Error loading texture: {0}", error.LocalizedDescription)); + Console.WriteLine (String.Format ("Error loading texture: {0}", error.LocalizedDescription)); GLKEffectPropertyTexture tex = new GLKEffectPropertyTexture (); tex.Enabled = true; @@ -96,11 +94,11 @@ void setupGL () public override void Update () { - float aspect = (float)Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); + float aspect = (float) Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); Matrix4 projectionMatrix = Matrix4.CreatePerspectiveFieldOfView ((float) (Math.PI * 65f / 180.0f), - aspect, 0.1f, 100.0f); + aspect, 0.1f, 100.0f); effect.Transform.ProjectionMatrix = projectionMatrix; diff --git a/OpenGL/GLKBaseEffectDrawingTexture/Main.cs b/OpenGL/GLKBaseEffectDrawingTexture/Main.cs index ee6385fc8..3a845a5cf 100644 --- a/OpenGL/GLKBaseEffectDrawingTexture/Main.cs +++ b/OpenGL/GLKBaseEffectDrawingTexture/Main.cs @@ -1,11 +1,9 @@ using UIKit; -namespace GLKBaseEffectDrawingTexture -{ - public class Application - { +namespace GLKBaseEffectDrawingTexture { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/OpenGL/GLKBaseEffectDrawingTexture/Monkey.cs b/OpenGL/GLKBaseEffectDrawingTexture/Monkey.cs index e9c9f3ab8..c8204bb0c 100644 --- a/OpenGL/GLKBaseEffectDrawingTexture/Monkey.cs +++ b/OpenGL/GLKBaseEffectDrawingTexture/Monkey.cs @@ -1,11 +1,9 @@ using System; using OpenTK; -namespace GLKBaseEffectDrawingTexture -{ - public static class Monkey - { - public static float[] MeshVertexData = { +namespace GLKBaseEffectDrawingTexture { + public static class Monkey { + public static float [] MeshVertexData = { /*v:*/0.351562f, 0.828125f, -0.242188f, /*n:*/0.183599f, 0.982971f, 0.005310f, /*t:*/0.043703f, 0.945538f, /*v:*/0.445312f, 0.781250f, -0.156250f, /*n:*/0.715171f, 0.222724f, 0.662465f, /*t:*/0.074022f, 0.935954f, /*v:*/0.476562f, 0.773438f, -0.242188f, /*n:*/0.964446f, 0.263863f, 0.012665f, /*t:*/0.073753f, 0.956927f, diff --git a/OpenGL/GLKReflectionMapEffectSkybox/AppDelegate.cs b/OpenGL/GLKReflectionMapEffectSkybox/AppDelegate.cs index b3a515517..be4ed830f 100644 --- a/OpenGL/GLKReflectionMapEffectSkybox/AppDelegate.cs +++ b/OpenGL/GLKReflectionMapEffectSkybox/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace GLKReflectionMapEffectSkybox -{ +namespace GLKReflectionMapEffectSkybox { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; MCViewController controller; diff --git a/OpenGL/GLKReflectionMapEffectSkybox/MCViewController.cs b/OpenGL/GLKReflectionMapEffectSkybox/MCViewController.cs index 0b45bb699..e16ef87d2 100644 --- a/OpenGL/GLKReflectionMapEffectSkybox/MCViewController.cs +++ b/OpenGL/GLKReflectionMapEffectSkybox/MCViewController.cs @@ -8,10 +8,8 @@ using CoreGraphics; using Foundation; -namespace GLKReflectionMapEffectSkybox -{ - public class MCViewController : GLKViewController - { +namespace GLKReflectionMapEffectSkybox { + public class MCViewController : GLKViewController { float rotation; uint vertexArray; @@ -77,17 +75,17 @@ void setupGL () GL.GenBuffers (1, out vertexBuffer); GL.BindBuffer (BufferTarget.ArrayBuffer, vertexBuffer); GL.BufferData (BufferTarget.ArrayBuffer, (IntPtr) (Monkey.MeshVertexData.Length * sizeof (float)), - Monkey.MeshVertexData, BufferUsage.StaticDraw); + Monkey.MeshVertexData, BufferUsage.StaticDraw); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.Position); GL.VertexAttribPointer ((int) GLKVertexAttrib.Position, 3, VertexAttribPointerType.Float, - false, 6 * sizeof (float), 0); + false, 6 * sizeof (float), 0); GL.EnableVertexAttribArray ((int) GLKVertexAttrib.Normal); GL.VertexAttribPointer ((int) GLKVertexAttrib.Normal, 3, VertexAttribPointerType.Float, - false, 6 * sizeof(float), 12); + false, 6 * sizeof (float), 12); - string[] cubeMapFiles = { + string [] cubeMapFiles = { NSBundle.MainBundle.PathForResource ("cubemap1", "png"), NSBundle.MainBundle.PathForResource ("cubemap2", "png"), NSBundle.MainBundle.PathForResource ("cubemap3", "png"), @@ -109,11 +107,11 @@ void setupGL () public override void Update () { - float aspect = (float)Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); + float aspect = (float) Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); Matrix4 projectionMatrix = Matrix4.CreatePerspectiveFieldOfView ((float) (Math.PI * 65f / 180.0f), - aspect, 0.1f, 100.0f); + aspect, 0.1f, 100.0f); effect.Transform.ProjectionMatrix = projectionMatrix; skyboxEffect.Transform.ProjectionMatrix = projectionMatrix; diff --git a/OpenGL/GLKReflectionMapEffectSkybox/Main.cs b/OpenGL/GLKReflectionMapEffectSkybox/Main.cs index f7d20cb73..b160a3323 100644 --- a/OpenGL/GLKReflectionMapEffectSkybox/Main.cs +++ b/OpenGL/GLKReflectionMapEffectSkybox/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace GLKReflectionMapEffectSkybox -{ - public class Application - { +namespace GLKReflectionMapEffectSkybox { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/OpenGL/GLKReflectionMapEffectSkybox/Monkey.cs b/OpenGL/GLKReflectionMapEffectSkybox/Monkey.cs index 27ef5603b..f21f119b4 100644 --- a/OpenGL/GLKReflectionMapEffectSkybox/Monkey.cs +++ b/OpenGL/GLKReflectionMapEffectSkybox/Monkey.cs @@ -1,11 +1,9 @@ using System; using OpenTK; -namespace GLKReflectionMapEffectSkybox -{ - public static class Monkey - { - public static float[] MeshVertexData = { +namespace GLKReflectionMapEffectSkybox { + public static class Monkey { + public static float [] MeshVertexData = { /*v:*/0.351562f, 0.500724f, 0.433432f, /*n:*/0.183599f, -0.005310f, 0.982971f, /*v:*/0.445312f, 0.414787f, 0.386557f, /*n:*/0.715171f, -0.662465f, 0.222724f, /*v:*/0.476562f, 0.500724f, 0.378744f, /*n:*/0.964446f, -0.012665f, 0.263863f, diff --git a/OpenGL/OpenGLES20Example/AppDelegate.cs b/OpenGL/OpenGLES20Example/AppDelegate.cs index 671f3a37a..29ddcca19 100644 --- a/OpenGL/OpenGLES20Example/AppDelegate.cs +++ b/OpenGL/OpenGLES20Example/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace OpenGLES20Example -{ +namespace OpenGLES20Example { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) diff --git a/OpenGL/OpenGLES20Example/GLCommon.cs b/OpenGL/OpenGLES20Example/GLCommon.cs index 098d9c38d..5021050a7 100644 --- a/OpenGL/OpenGLES20Example/GLCommon.cs +++ b/OpenGL/OpenGLES20Example/GLCommon.cs @@ -1,8 +1,7 @@ using System; using OpenTK; -namespace OpenGLES20Example -{ +namespace OpenGLES20Example { struct Color { public float red; public float green; @@ -15,14 +14,13 @@ struct TextureCoord { public float T; } - public static class GLCommon - { + public static class GLCommon { public static float radiansFromDegrees (float degrees) { - return (float)Math.PI * degrees / 180.0f; + return (float) Math.PI * degrees / 180.0f; } - public static void Matrix3DSetRotationByRadians (ref float[] matrix, float radians, ref Vector3 vector) + public static void Matrix3DSetRotationByRadians (ref float [] matrix, float radians, ref Vector3 vector) { float mag = (float) Math.Sqrt ((vector.X * vector.X) + (vector.Y * vector.Y) + (vector.Z * vector.Z)); @@ -53,12 +51,12 @@ public static void Matrix3DSetRotationByRadians (ref float[] matrix, float radia matrix [10] = (vector.Z * vector.Z) * (1 - c) + c; } - public static void Matrix3DSetRotationByDegrees (ref float[] matrix, float degrees, Vector3 vector) + public static void Matrix3DSetRotationByDegrees (ref float [] matrix, float degrees, Vector3 vector) { Matrix3DSetRotationByRadians (ref matrix, radiansFromDegrees (degrees), ref vector); } - public static void Matrix3DSetIdentity (ref float[] matrix) + public static void Matrix3DSetIdentity (ref float [] matrix) { matrix [0] = matrix [5] = matrix [10] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; @@ -66,7 +64,7 @@ public static void Matrix3DSetIdentity (ref float[] matrix) matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; } - public static void Matrix3DSetTranslation (ref float[] matrix, float xTranslate, float yTranslate, float zTranslate) + public static void Matrix3DSetTranslation (ref float [] matrix, float xTranslate, float yTranslate, float zTranslate) { matrix [0] = matrix [5] = matrix [10] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; @@ -77,7 +75,7 @@ public static void Matrix3DSetTranslation (ref float[] matrix, float xTranslate, matrix [14] = zTranslate; } - public static void Matrix3DSetScaling (ref float[] matrix, float xScale, float yScale, float zScale) + public static void Matrix3DSetScaling (ref float [] matrix, float xScale, float yScale, float zScale) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [8] = matrix [9] = 0.0f; @@ -88,15 +86,15 @@ public static void Matrix3DSetScaling (ref float[] matrix, float xScale, float y matrix [15] = 1.0f; } - public static void Matrix3DSetUniformScaling (ref float[] matrix, float scale) + public static void Matrix3DSetUniformScaling (ref float [] matrix, float scale) { Matrix3DSetScaling (ref matrix, scale, scale, scale); } - public static void Matrix3DSetZRotationUsingRadians (ref float[] matrix, float radians) + public static void Matrix3DSetZRotationUsingRadians (ref float [] matrix, float radians) { - matrix [0] = (float)Math.Cos (radians); - matrix [1] = (float)Math.Sin (radians); + matrix [0] = (float) Math.Cos (radians); + matrix [1] = (float) Math.Sin (radians); matrix [4] = -matrix [1]; matrix [5] = matrix [0]; matrix [2] = matrix [3] = matrix [6] = matrix [7] = matrix [8] = 0.0f; @@ -104,47 +102,47 @@ public static void Matrix3DSetZRotationUsingRadians (ref float[] matrix, float r matrix [10] = matrix [15] = 0; } - public static void Matrix3DSetZRotationUsingDegrees (ref float[] matrix, float degrees) + public static void Matrix3DSetZRotationUsingDegrees (ref float [] matrix, float degrees) { Matrix3DSetZRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } - public static void Matrix3DSetXRotationUsingRadians (ref float[] matrix, float radians) + public static void Matrix3DSetXRotationUsingRadians (ref float [] matrix, float radians) { matrix [0] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [7] = matrix [8] = 0.0f; matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [5] = (float) Math.Cos (radians); - matrix [6] = - (float)Math.Sin (radians); - matrix [9] = - matrix [6]; + matrix [6] = -(float) Math.Sin (radians); + matrix [9] = -matrix [6]; matrix [10] = matrix [5]; } - public static void Matrix3DSetXRotationUsingDegrees (ref float[] matrix, float degrees) + public static void Matrix3DSetXRotationUsingDegrees (ref float [] matrix, float degrees) { Matrix3DSetXRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } - public static void Matrix3DSetYRotationUsingRadians (ref float[] matrix, float radians) + public static void Matrix3DSetYRotationUsingRadians (ref float [] matrix, float radians) { - matrix [0] = (float)Math.Cos (radians); - matrix [2] = (float)Math.Sin (radians); - matrix [8] = - matrix [2]; + matrix [0] = (float) Math.Cos (radians); + matrix [2] = (float) Math.Sin (radians); + matrix [8] = -matrix [2]; matrix [10] = matrix [0]; matrix [1] = matrix [3] = matrix [4] = matrix [6] = matrix [7] = 0.0f; matrix [9] = matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [5] = matrix [15] = 1.0f; } - public static void Matrix3DSetYRotationUsingDegrees (ref float[] matrix, float degrees) + public static void Matrix3DSetYRotationUsingDegrees (ref float [] matrix, float degrees) { Matrix3DSetYRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } - public static float[] Matrix3DMultiply (float[] m1, float[] m2) + public static float [] Matrix3DMultiply (float [] m1, float [] m2) { - float[] result = new float[16]; + float [] result = new float [16]; result [0] = m1 [0] * m2 [0] + m1 [4] * m2 [1] + m1 [8] * m2 [2] + m1 [12] * m2 [3]; result [1] = m1 [1] * m2 [0] + m1 [5] * m2 [1] + m1 [9] * m2 [2] + m1 [13] * m2 [3]; @@ -169,8 +167,8 @@ public static float[] Matrix3DMultiply (float[] m1, float[] m2) return result; } - public static void Matrix3DSetOrthoProjection (ref float[] matrix, float left, float right, float bottom, - float top, float near, float far) + public static void Matrix3DSetOrthoProjection (ref float [] matrix, float left, float right, float bottom, + float top, float near, float far) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = matrix [6] = 0.0f; matrix [7] = matrix [8] = matrix [9] = matrix [11] = 0.0f; @@ -183,8 +181,8 @@ public static void Matrix3DSetOrthoProjection (ref float[] matrix, float left, f matrix [15] = 1.0f; } - public static void Matrix3DSetFrustumProjection (ref float[] matrix, float left, float right, float bottom, - float top, float zNear, float zFar) + public static void Matrix3DSetFrustumProjection (ref float [] matrix, float left, float right, float bottom, + float top, float zNear, float zFar) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [12] = matrix [13] = matrix [15] = 0.0f; @@ -193,17 +191,17 @@ public static void Matrix3DSetFrustumProjection (ref float[] matrix, float left, matrix [5] = 2 * zNear / (top - bottom); matrix [8] = (right + left) / (right - left); matrix [9] = (top + bottom) / (top - bottom); - matrix [10] = - (zFar + zNear) / (zFar - zNear); - matrix [11] = - 1.0f; - matrix [14] = - (2 * zFar * zNear) / (zFar - zNear); + matrix [10] = -(zFar + zNear) / (zFar - zNear); + matrix [11] = -1.0f; + matrix [14] = -(2 * zFar * zNear) / (zFar - zNear); } - public static void Matrix3DSetPerspectiveProjectionWithFieldOfView (ref float[] matrix, float fieldOfVision, - float near, float far, float aspectRatio) + public static void Matrix3DSetPerspectiveProjectionWithFieldOfView (ref float [] matrix, float fieldOfVision, + float near, float far, float aspectRatio) { - float size = near * (float)Math.Tan (radiansFromDegrees (fieldOfVision) / 2.0f); + float size = near * (float) Math.Tan (radiansFromDegrees (fieldOfVision) / 2.0f); Matrix3DSetFrustumProjection (ref matrix, -size, size, -size / aspectRatio, - size / aspectRatio, near, far); + size / aspectRatio, near, far); } } } diff --git a/OpenGL/OpenGLES20Example/GLProgram.cs b/OpenGL/OpenGLES20Example/GLProgram.cs index 4313d830d..c7308f5ac 100644 --- a/OpenGL/OpenGLES20Example/GLProgram.cs +++ b/OpenGL/OpenGLES20Example/GLProgram.cs @@ -5,10 +5,8 @@ using System.Collections.Generic; using System.Text; -namespace OpenGLES20Example -{ - public class GLProgram - { +namespace OpenGLES20Example { + public class GLProgram { int program, vertShader, fragShader; @@ -37,8 +35,8 @@ bool compileShader (ref int shader, ShaderType type, string file) int status; string source; - using (StreamReader sr = new StreamReader(file)) - source = sr.ReadToEnd(); + using (StreamReader sr = new StreamReader (file)) + source = sr.ReadToEnd (); shader = GL.CreateShader (type); GL.ShaderSource (shader, source); @@ -89,7 +87,8 @@ public void Use () GL.UseProgram (program); } - string GetLog (int obj) { + string GetLog (int obj) + { string log; if (GL.IsShader (obj)) { log = GL.GetShaderInfoLog (obj); diff --git a/OpenGL/OpenGLES20Example/GLTexture.cs b/OpenGL/OpenGLES20Example/GLTexture.cs index d358a703b..5f640c3fb 100644 --- a/OpenGL/OpenGLES20Example/GLTexture.cs +++ b/OpenGL/OpenGLES20Example/GLTexture.cs @@ -7,10 +7,8 @@ using CoreImage; using CoreGraphics; -namespace OpenGLES20Example -{ - public class GLTexture - { +namespace OpenGLES20Example { + public class GLTexture { string filename; uint texture; @@ -32,7 +30,7 @@ public GLTexture (string inFilename) GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Nearest); //TODO Remove the Substring method if you don't support iOS versions prior to iOS 6. - string extension = Path.GetExtension (filename).Substring(1); + string extension = Path.GetExtension (filename).Substring (1); string baseFilename = Path.GetFileNameWithoutExtension (filename); string path = NSBundle.MainBundle.PathForResource (baseFilename, extension); @@ -46,9 +44,9 @@ public GLTexture (string inFilename) nint height = image.CGImage.Height; CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB (); - byte [] imageData = new byte[height * width * 4]; - CGContext context = new CGBitmapContext (imageData, width, height, 8, 4 * width, colorSpace, - CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big); + byte [] imageData = new byte [height * width * 4]; + CGContext context = new CGBitmapContext (imageData, width, height, 8, 4 * width, colorSpace, + CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big); context.TranslateCTM (0, height); context.ScaleCTM (1, -1); @@ -56,7 +54,7 @@ public GLTexture (string inFilename) context.ClearRect (new CGRect (0, 0, width, height)); context.DrawImage (new CGRect (0, 0, width, height), image.CGImage); - GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)width, (int)height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, imageData); + GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int) width, (int) height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, imageData); context.Dispose (); } diff --git a/OpenGL/OpenGLES20Example/GLView.cs b/OpenGL/OpenGLES20Example/GLView.cs index c6a742b5c..5e4685280 100644 --- a/OpenGL/OpenGLES20Example/GLView.cs +++ b/OpenGL/OpenGLES20Example/GLView.cs @@ -6,10 +6,8 @@ using CoreAnimation; using ObjCRuntime; -namespace OpenGLES20Example -{ - public class GLView : UIView - { +namespace OpenGLES20Example { + public class GLView : UIView { int backingWidth; int backingHeight; uint frameBuffer; @@ -45,7 +43,7 @@ public static Class LayerClass () public GLView () : base () { - CAEAGLLayer eaglLayer = (CAEAGLLayer)Layer; + CAEAGLLayer eaglLayer = (CAEAGLLayer) Layer; eaglLayer.Opaque = true; context = new EAGLContext (EAGLRenderingAPI.OpenGLES2); @@ -109,7 +107,7 @@ public override void LayoutSubviews () if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) Console.WriteLine (String.Format ("Failed to make complete framebuffer object {0}", - GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer).ToString ())); + GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer).ToString ())); GL.Viewport (0, 0, backingWidth, backingHeight); diff --git a/OpenGL/OpenGLES20Example/GLViewController.cs b/OpenGL/OpenGLES20Example/GLViewController.cs index c8b270d31..ce27aa6d2 100644 --- a/OpenGL/OpenGLES20Example/GLViewController.cs +++ b/OpenGL/OpenGLES20Example/GLViewController.cs @@ -3,25 +3,23 @@ using UIKit; using OpenTK.Graphics.ES20; -namespace OpenGLES20Example -{ - public class GLViewController : UIViewController - { +namespace OpenGLES20Example { + public class GLViewController : UIViewController { GLProgram program; GLTexture texture; float rot = 0f; int positionAttribute, - textureCoordinateAttribute, - matrixUniform, + textureCoordinateAttribute, + matrixUniform, textureUniform; - float[] rotationMatrix = new float[16], - translationMatrix = new float[16], - modelViewMatrix = new float[16], - projectionMatrix = new float[16], - matrix = new float[16]; + float [] rotationMatrix = new float [16], + translationMatrix = new float [16], + modelViewMatrix = new float [16], + projectionMatrix = new float [16], + matrix = new float [16]; public GLViewController () { @@ -62,7 +60,7 @@ public void Setup () public void Draw () { - Vector3[] vertices = + Vector3 [] vertices = { new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f }, new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f}, @@ -126,7 +124,7 @@ public void Draw () new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f}, }; - TextureCoord[] textureCoordinates = + TextureCoord [] textureCoordinates = { new TextureCoord { S = .648752f, T = 0.445995f}, new TextureCoord { S = 0.914415f, T = 0.532311f}, @@ -207,7 +205,7 @@ public void Draw () modelViewMatrix = GLCommon.Matrix3DMultiply (translationMatrix, rotationMatrix); GLCommon.Matrix3DSetPerspectiveProjectionWithFieldOfView (ref projectionMatrix, 45.0f, 0.1f, 100.0f, - (float)(View.Frame.Size.Width / View.Frame.Size.Height)); + (float) (View.Frame.Size.Width / View.Frame.Size.Height)); matrix = GLCommon.Matrix3DMultiply (projectionMatrix, modelViewMatrix); GL.UniformMatrix4 (matrixUniform, 1, false, matrix); diff --git a/OpenGL/OpenGLES20Example/Main.cs b/OpenGL/OpenGLES20Example/Main.cs index 06741001e..353f62de4 100644 --- a/OpenGL/OpenGLES20Example/Main.cs +++ b/OpenGL/OpenGLES20Example/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace OpenGLES2Example -{ - public class Application - { +namespace OpenGLES2Example { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/OpenGL/PerVertexDirectionalLighting/AppDelegate.cs b/OpenGL/PerVertexDirectionalLighting/AppDelegate.cs index 7a32dc227..0a2843f75 100644 --- a/OpenGL/PerVertexDirectionalLighting/AppDelegate.cs +++ b/OpenGL/PerVertexDirectionalLighting/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace PerVertexDirectionalLighting -{ +namespace PerVertexDirectionalLighting { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) diff --git a/OpenGL/PerVertexDirectionalLighting/GLCommon.cs b/OpenGL/PerVertexDirectionalLighting/GLCommon.cs index cb21a14d0..e20bf81d5 100644 --- a/OpenGL/PerVertexDirectionalLighting/GLCommon.cs +++ b/OpenGL/PerVertexDirectionalLighting/GLCommon.cs @@ -1,8 +1,7 @@ using System; using OpenTK; -namespace PerVertexDirectionalLighting -{ +namespace PerVertexDirectionalLighting { struct Color { public float red; public float green; @@ -15,14 +14,13 @@ struct TextureCoord { public float T; } - public static class GLCommon - { + public static class GLCommon { public static float radiansFromDegrees (float degrees) { - return (float)Math.PI * degrees / 180.0f; + return (float) Math.PI * degrees / 180.0f; } - public static void Matrix3DSetRotationByRadians (ref float[] matrix, float radians, ref Vector3 vector) + public static void Matrix3DSetRotationByRadians (ref float [] matrix, float radians, ref Vector3 vector) { float mag = (float) Math.Sqrt ((vector.X * vector.X) + (vector.Y * vector.Y) + (vector.Z * vector.Z)); @@ -53,12 +51,12 @@ public static void Matrix3DSetRotationByRadians (ref float[] matrix, float radia matrix [10] = (vector.Z * vector.Z) * (1 - c) + c; } - public static void Matrix3DSetRotationByDegrees (ref float[] matrix, float degrees, Vector3 vector) + public static void Matrix3DSetRotationByDegrees (ref float [] matrix, float degrees, Vector3 vector) { Matrix3DSetRotationByRadians (ref matrix, radiansFromDegrees (degrees), ref vector); } - public static void Matrix3DSetIdentity (ref float[] matrix) + public static void Matrix3DSetIdentity (ref float [] matrix) { matrix [0] = matrix [5] = matrix [10] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; @@ -66,7 +64,7 @@ public static void Matrix3DSetIdentity (ref float[] matrix) matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; } - public static void Matrix3DSetTranslation (ref float[] matrix, float xTranslate, float yTranslate, float zTranslate) + public static void Matrix3DSetTranslation (ref float [] matrix, float xTranslate, float yTranslate, float zTranslate) { matrix [0] = matrix [5] = matrix [10] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; @@ -77,7 +75,7 @@ public static void Matrix3DSetTranslation (ref float[] matrix, float xTranslate, matrix [14] = zTranslate; } - public static void Matrix3DSetScaling (ref float[] matrix, float xScale, float yScale, float zScale) + public static void Matrix3DSetScaling (ref float [] matrix, float xScale, float yScale, float zScale) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [8] = matrix [9] = 0.0f; @@ -88,15 +86,15 @@ public static void Matrix3DSetScaling (ref float[] matrix, float xScale, float y matrix [15] = 1.0f; } - public static void Matrix3DSetUniformScaling (ref float[] matrix, float scale) + public static void Matrix3DSetUniformScaling (ref float [] matrix, float scale) { Matrix3DSetScaling (ref matrix, scale, scale, scale); } - public static void Matrix3DSetZRotationUsingRadians (ref float[] matrix, float radians) + public static void Matrix3DSetZRotationUsingRadians (ref float [] matrix, float radians) { - matrix [0] = (float)Math.Cos (radians); - matrix [1] = (float)Math.Sin (radians); + matrix [0] = (float) Math.Cos (radians); + matrix [1] = (float) Math.Sin (radians); matrix [4] = -matrix [1]; matrix [5] = matrix [0]; matrix [2] = matrix [3] = matrix [6] = matrix [7] = matrix [8] = 0.0f; @@ -104,47 +102,47 @@ public static void Matrix3DSetZRotationUsingRadians (ref float[] matrix, float r matrix [10] = matrix [15] = 0; } - public static void Matrix3DSetZRotationUsingDegrees (ref float[] matrix, float degrees) + public static void Matrix3DSetZRotationUsingDegrees (ref float [] matrix, float degrees) { Matrix3DSetZRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } - public static void Matrix3DSetXRotationUsingRadians (ref float[] matrix, float radians) + public static void Matrix3DSetXRotationUsingRadians (ref float [] matrix, float radians) { matrix [0] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [7] = matrix [8] = 0.0f; matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [5] = (float) Math.Cos (radians); - matrix [6] = - (float)Math.Sin (radians); - matrix [9] = - matrix [6]; + matrix [6] = -(float) Math.Sin (radians); + matrix [9] = -matrix [6]; matrix [10] = matrix [5]; } - public static void Matrix3DSetXRotationUsingDegrees (ref float[] matrix, float degrees) + public static void Matrix3DSetXRotationUsingDegrees (ref float [] matrix, float degrees) { Matrix3DSetXRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } - public static void Matrix3DSetYRotationUsingRadians (ref float[] matrix, float radians) + public static void Matrix3DSetYRotationUsingRadians (ref float [] matrix, float radians) { - matrix [0] = (float)Math.Cos (radians); - matrix [2] = (float)Math.Sin (radians); - matrix [8] = - matrix [2]; + matrix [0] = (float) Math.Cos (radians); + matrix [2] = (float) Math.Sin (radians); + matrix [8] = -matrix [2]; matrix [10] = matrix [0]; matrix [1] = matrix [3] = matrix [4] = matrix [6] = matrix [7] = 0.0f; matrix [9] = matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [5] = matrix [15] = 1.0f; } - public static void Matrix3DSetYRotationUsingDegrees (ref float[] matrix, float degrees) + public static void Matrix3DSetYRotationUsingDegrees (ref float [] matrix, float degrees) { Matrix3DSetYRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } - public static float[] Matrix3DMultiply (float[] m1, float[] m2) + public static float [] Matrix3DMultiply (float [] m1, float [] m2) { - float[] result = new float[16]; + float [] result = new float [16]; result [0] = m1 [0] * m2 [0] + m1 [4] * m2 [1] + m1 [8] * m2 [2] + m1 [12] * m2 [3]; result [1] = m1 [1] * m2 [0] + m1 [5] * m2 [1] + m1 [9] * m2 [2] + m1 [13] * m2 [3]; @@ -169,8 +167,8 @@ public static float[] Matrix3DMultiply (float[] m1, float[] m2) return result; } - public static void Matrix3DSetOrthoProjection (ref float[] matrix, float left, float right, float bottom, - float top, float near, float far) + public static void Matrix3DSetOrthoProjection (ref float [] matrix, float left, float right, float bottom, + float top, float near, float far) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = matrix [6] = 0.0f; matrix [7] = matrix [8] = matrix [9] = matrix [11] = 0.0f; @@ -183,8 +181,8 @@ public static void Matrix3DSetOrthoProjection (ref float[] matrix, float left, f matrix [15] = 1.0f; } - public static void Matrix3DSetFrustumProjection (ref float[] matrix, float left, float right, float bottom, - float top, float zNear, float zFar) + public static void Matrix3DSetFrustumProjection (ref float [] matrix, float left, float right, float bottom, + float top, float zNear, float zFar) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [12] = matrix [13] = matrix [15] = 0.0f; @@ -193,17 +191,17 @@ public static void Matrix3DSetFrustumProjection (ref float[] matrix, float left, matrix [5] = 2 * zNear / (top - bottom); matrix [8] = (right + left) / (right - left); matrix [9] = (top + bottom) / (top - bottom); - matrix [10] = - (zFar + zNear) / (zFar - zNear); - matrix [11] = - 1.0f; - matrix [14] = - (2 * zFar * zNear) / (zFar - zNear); + matrix [10] = -(zFar + zNear) / (zFar - zNear); + matrix [11] = -1.0f; + matrix [14] = -(2 * zFar * zNear) / (zFar - zNear); } - public static void Matrix3DSetPerspectiveProjectionWithFieldOfView (ref float[] matrix, float fieldOfVision, - float near, float far, float aspectRatio) + public static void Matrix3DSetPerspectiveProjectionWithFieldOfView (ref float [] matrix, float fieldOfVision, + float near, float far, float aspectRatio) { - float size = near * (float)Math.Tan (radiansFromDegrees (fieldOfVision) / 2.0f); + float size = near * (float) Math.Tan (radiansFromDegrees (fieldOfVision) / 2.0f); Matrix3DSetFrustumProjection (ref matrix, -size, size, -size / aspectRatio, - size / aspectRatio, near, far); + size / aspectRatio, near, far); } } } diff --git a/OpenGL/PerVertexDirectionalLighting/GLProgram.cs b/OpenGL/PerVertexDirectionalLighting/GLProgram.cs index 50a9f6422..b69d78fba 100644 --- a/OpenGL/PerVertexDirectionalLighting/GLProgram.cs +++ b/OpenGL/PerVertexDirectionalLighting/GLProgram.cs @@ -5,10 +5,8 @@ using System.Collections.Generic; using System.Text; -namespace PerVertexDirectionalLighting -{ - public class GLProgram - { +namespace PerVertexDirectionalLighting { + public class GLProgram { int program, vertShader, fragShader; @@ -37,8 +35,8 @@ bool compileShader (ref int shader, ShaderType type, string file) int status; string source; - using (StreamReader sr = new StreamReader(file)) - source = sr.ReadToEnd(); + using (StreamReader sr = new StreamReader (file)) + source = sr.ReadToEnd (); shader = GL.CreateShader (type); GL.ShaderSource (shader, source); diff --git a/OpenGL/PerVertexDirectionalLighting/GLTexture.cs b/OpenGL/PerVertexDirectionalLighting/GLTexture.cs index 06a044f40..d10a87440 100644 --- a/OpenGL/PerVertexDirectionalLighting/GLTexture.cs +++ b/OpenGL/PerVertexDirectionalLighting/GLTexture.cs @@ -7,10 +7,8 @@ using CoreImage; using CoreGraphics; -namespace PerVertexDirectionalLighting -{ - public class GLTexture - { +namespace PerVertexDirectionalLighting { + public class GLTexture { string filename; uint texture; @@ -45,9 +43,9 @@ public GLTexture (string inFilename) nint height = image.CGImage.Height; CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB (); - byte [] imageData = new byte[height * width * 4]; - CGContext context = new CGBitmapContext (imageData, width, height, 8, 4 * width, colorSpace, - CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big); + byte [] imageData = new byte [height * width * 4]; + CGContext context = new CGBitmapContext (imageData, width, height, 8, 4 * width, colorSpace, + CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Big); context.TranslateCTM (0, height); context.ScaleCTM (1, -1); @@ -55,7 +53,7 @@ public GLTexture (string inFilename) context.ClearRect (new CGRect (0, 0, width, height)); context.DrawImage (new CGRect (0, 0, width, height), image.CGImage); - GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)width, (int)height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, imageData); + GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int) width, (int) height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, imageData); context.Dispose (); } diff --git a/OpenGL/PerVertexDirectionalLighting/GLView.cs b/OpenGL/PerVertexDirectionalLighting/GLView.cs index 964294055..8c52e6b51 100644 --- a/OpenGL/PerVertexDirectionalLighting/GLView.cs +++ b/OpenGL/PerVertexDirectionalLighting/GLView.cs @@ -6,10 +6,8 @@ using CoreAnimation; using ObjCRuntime; -namespace PerVertexDirectionalLighting -{ - public class GLView : UIView - { +namespace PerVertexDirectionalLighting { + public class GLView : UIView { int backingWidth; int backingHeight; uint frameBuffer; @@ -45,7 +43,7 @@ public static Class LayerClass () public GLView () : base () { - CAEAGLLayer eaglLayer = (CAEAGLLayer)Layer; + CAEAGLLayer eaglLayer = (CAEAGLLayer) Layer; eaglLayer.Opaque = true; context = new EAGLContext (EAGLRenderingAPI.OpenGLES2); @@ -109,7 +107,7 @@ public override void LayoutSubviews () if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) Console.WriteLine (String.Format ("Failed to make complete framebuffer object {0}", - GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer).ToString ())); + GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer).ToString ())); GL.Viewport (0, 0, backingWidth, backingHeight); diff --git a/OpenGL/PerVertexDirectionalLighting/GLViewController.cs b/OpenGL/PerVertexDirectionalLighting/GLViewController.cs index 2f15b98d2..c734015b1 100644 --- a/OpenGL/PerVertexDirectionalLighting/GLViewController.cs +++ b/OpenGL/PerVertexDirectionalLighting/GLViewController.cs @@ -3,28 +3,26 @@ using UIKit; using OpenTK.Graphics.ES20; -namespace PerVertexDirectionalLighting -{ - public class GLViewController : UIViewController - { +namespace PerVertexDirectionalLighting { + public class GLViewController : UIViewController { GLProgram program; GLTexture texture; float rot = 0f; int positionAttribute, - textureCoordinateAttribute, - normalsAttribute, - matrixUniform, + textureCoordinateAttribute, + normalsAttribute, + matrixUniform, textureUniform, - lightDirectionUniform, + lightDirectionUniform, lightDiffuseColorUniform; - float[] rotationMatrix = new float[16], - translationMatrix = new float[16], - modelViewMatrix = new float[16], - projectionMatrix = new float[16], - matrix = new float[16]; + float [] rotationMatrix = new float [16], + translationMatrix = new float [16], + modelViewMatrix = new float [16], + projectionMatrix = new float [16], + matrix = new float [16]; public GLViewController () { @@ -70,7 +68,7 @@ public void Setup () public void Draw () { - Vector3[] vertices = { + Vector3 [] vertices = { new Vector3 { X = -0.276385f, Y = -0.850640f, Z = -0.447215f }, new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f}, new Vector3 { X = 0.723600f, Y = -0.525720f, Z = -0.447215f}, @@ -133,7 +131,7 @@ public void Draw () new Vector3 { X = 0.000000f, Y = 0.000000f, Z = 1.000000f}, }; - TextureCoord[] textureCoordinates = { + TextureCoord [] textureCoordinates = { new TextureCoord { S = .648752f, T = 0.445995f}, new TextureCoord { S = 0.914415f, T = 0.532311f}, new TextureCoord { S = 0.722181f, T = 0.671980f}, @@ -196,7 +194,7 @@ public void Draw () new TextureCoord { S = 0.254949f, T = 0.686495f}, }; - Vector3[] normals = { + Vector3 [] normals = { new Vector3 { X = -0.276376f, Y = -0.850642f, Z = -0.447188f }, new Vector3 { X = 0.000000f, Y = 0.000000f, Z = -1.000000f }, new Vector3 { X = 0.723594f, Y = -0.525712f, Z = -0.447188f }, @@ -279,7 +277,7 @@ public void Draw () modelViewMatrix = GLCommon.Matrix3DMultiply (translationMatrix, rotationMatrix); GLCommon.Matrix3DSetPerspectiveProjectionWithFieldOfView (ref projectionMatrix, 45.0f, 0.1f, 100.0f, - (float)(View.Frame.Size.Width / View.Frame.Size.Height)); + (float) (View.Frame.Size.Width / View.Frame.Size.Height)); matrix = GLCommon.Matrix3DMultiply (projectionMatrix, modelViewMatrix); GL.UniformMatrix4 (matrixUniform, 1, false, matrix); diff --git a/OpenGL/PerVertexDirectionalLighting/Main.cs b/OpenGL/PerVertexDirectionalLighting/Main.cs index a9c41a320..9b8e9d6be 100644 --- a/OpenGL/PerVertexDirectionalLighting/Main.cs +++ b/OpenGL/PerVertexDirectionalLighting/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace PerVertexDirectionalLighting -{ - public class Application - { +namespace PerVertexDirectionalLighting { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/OpenGLESSample/AppDelegate.cs b/OpenGLESSample/AppDelegate.cs index a73f623da..8b671efd6 100644 --- a/OpenGLESSample/AppDelegate.cs +++ b/OpenGLESSample/AppDelegate.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; using Foundation; -namespace OpenGLESSample -{ +namespace OpenGLESSample { // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate - { + public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { @@ -14,7 +12,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary }; window.RootViewController = rootViewController; glView.AnimationInterval = 1.0 / 60.0; - glView.StartAnimation(); + glView.StartAnimation (); window.MakeKeyAndVisible (); diff --git a/OpenGLESSample/EAGLView.cs b/OpenGLESSample/EAGLView.cs index 6695ff33b..db65d0f60 100644 --- a/OpenGLESSample/EAGLView.cs +++ b/OpenGLESSample/EAGLView.cs @@ -8,10 +8,8 @@ using OpenTK.Graphics.ES11; using ObjCRuntime; -namespace OpenGLESSample -{ - public partial class EAGLView : UIView - { +namespace OpenGLESSample { + public partial class EAGLView : UIView { int BackingWidth; int BackingHeight; iPhoneOSGraphicsContext Context; @@ -39,26 +37,26 @@ public EAGLView (NSCoder coder) : base (coder) ); Context = (iPhoneOSGraphicsContext) ((IGraphicsContextInternal) GraphicsContext.CurrentContext).Implementation; - Context.MakeCurrent(null); + Context.MakeCurrent (null); AnimationInterval = 1.0 / 60.0; } void DrawView () { - float[] squareVertices = { + float [] squareVertices = { -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, }; - byte[] squareColors = { + byte [] squareColors = { 255, 255, 0, 255, 0, 255, 255, 255, 0, 0, 0, 0, 255, 0, 255, 255, }; - Context.MakeCurrent(null); + Context.MakeCurrent (null); GL.Oes.BindFramebuffer (All.FramebufferOes, ViewFrameBuffer); GL.Viewport (0, 0, BackingWidth, BackingHeight); @@ -84,7 +82,7 @@ void DrawView () public override void LayoutSubviews () { - Context.MakeCurrent(null); + Context.MakeCurrent (null); DestroyFrameBuffer (); CreateFrameBuffer (); DrawView (); @@ -107,7 +105,7 @@ bool CreateFrameBuffer () GL.Oes.GetRenderbufferParameter (All.RenderbufferOes, All.RenderbufferHeightOes, out BackingHeight); if (GL.Oes.CheckFramebufferStatus (All.FramebufferOes) != All.FramebufferCompleteOes) { - Console.Error.WriteLine("failed to make complete framebuffer object {0}", + Console.Error.WriteLine ("failed to make complete framebuffer object {0}", GL.Oes.CheckFramebufferStatus (All.FramebufferOes)); } return true; diff --git a/OpenGLESSample/Main.cs b/OpenGLESSample/Main.cs index 33188f52e..800fa8424 100644 --- a/OpenGLESSample/Main.cs +++ b/OpenGLESSample/Main.cs @@ -2,13 +2,11 @@ using OpenTK.Platform; using OpenGLES; -namespace OpenGLESSample -{ - public class Application - { - static void Main (string[] args) +namespace OpenGLESSample { + public class Application { + static void Main (string [] args) { - using (var c = Utilities.CreateGraphicsContext(EAGLRenderingAPI.OpenGLES1)) { + using (var c = Utilities.CreateGraphicsContext (EAGLRenderingAPI.OpenGLES1)) { UIApplication.Main (args); diff --git a/OpenGLESSample_GameView/AppDelegate.cs b/OpenGLESSample_GameView/AppDelegate.cs index 7d0745cdc..b90e802b3 100644 --- a/OpenGLESSample_GameView/AppDelegate.cs +++ b/OpenGLESSample_GameView/AppDelegate.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; using Foundation; -namespace OpenGLESSampleGameView -{ +namespace OpenGLESSampleGameView { // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate - { + public partial class OpenGLESSampleAppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { @@ -21,15 +19,15 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary public override void OnResignActivation (UIApplication application) { - glView.Stop(); - glView.Run(5.0); + glView.Stop (); + glView.Run (5.0); } // This method is required in iPhoneOS 3.0 public override void OnActivated (UIApplication application) { - glView.Stop(); - glView.Run(60.0); + glView.Stop (); + glView.Run (60.0); } } diff --git a/OpenGLESSample_GameView/EAGLView.cs b/OpenGLESSample_GameView/EAGLView.cs index a3cfcd1d4..9c1633e3a 100644 --- a/OpenGLESSample_GameView/EAGLView.cs +++ b/OpenGLESSample_GameView/EAGLView.cs @@ -7,13 +7,11 @@ using OpenGLES; using OpenTK.Graphics.ES11; -namespace OpenGLESSampleGameView -{ - public partial class EAGLView : iPhoneOSGameView - { +namespace OpenGLESSampleGameView { + public partial class EAGLView : iPhoneOSGameView { [Export ("layerClass")] - static Class LayerClass() + static Class LayerClass () { return iPhoneOSGameView.GetLayerClass (); } @@ -22,34 +20,34 @@ static Class LayerClass() public EAGLView (NSCoder coder) : base (coder) { LayerRetainsBacking = false; - LayerColorFormat = EAGLColorFormat.RGBA8; + LayerColorFormat = EAGLColorFormat.RGBA8; ContextRenderingApi = EAGLRenderingAPI.OpenGLES1; } - protected override void ConfigureLayer(CAEAGLLayer eaglLayer) + protected override void ConfigureLayer (CAEAGLLayer eaglLayer) { eaglLayer.Opaque = true; } - protected override void OnRenderFrame(FrameEventArgs e) + protected override void OnRenderFrame (FrameEventArgs e) { base.OnRenderFrame (e); - float[] squareVertices = { + float [] squareVertices = { -0.5f, -0.5f, 0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f, }; - byte[] squareColors = { + byte [] squareColors = { 255, 255, 0, 255, 0, 255, 255, 255, 0, 0, 0, 0, 255, 0, 255, 255, }; - MakeCurrent(); + MakeCurrent (); GL.Viewport (0, 0, Size.Width, Size.Height); GL.MatrixMode (All.Projection); @@ -68,7 +66,7 @@ protected override void OnRenderFrame(FrameEventArgs e) GL.DrawArrays (All.TriangleStrip, 0, 4); - SwapBuffers(); + SwapBuffers (); } } } diff --git a/OpenGLESSample_GameView/Main.cs b/OpenGLESSample_GameView/Main.cs index 2509564aa..8bc434c7e 100644 --- a/OpenGLESSample_GameView/Main.cs +++ b/OpenGLESSample_GameView/Main.cs @@ -1,14 +1,12 @@ using UIKit; -namespace OpenGLESSampleGameView -{ - public class Application - { - static void Main (string[] args) +namespace OpenGLESSampleGameView { + public class Application { + static void Main (string [] args) { UIApplication.Main (args); } } - + } diff --git a/OpenGLScroller/AppDelegate.cs b/OpenGLScroller/AppDelegate.cs index c7eaee375..446dde00e 100644 --- a/OpenGLScroller/AppDelegate.cs +++ b/OpenGLScroller/AppDelegate.cs @@ -3,26 +3,23 @@ using Foundation; using UIKit; -namespace OpenGLScroller -{ +namespace OpenGLScroller { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - window.RootViewController = new ViewController(); + window.RootViewController = new ViewController (); window.MakeKeyAndVisible (); return true; } } - public class Application - { - static void Main (string[] args) + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/OpenGLScroller/CubeView.cs b/OpenGLScroller/CubeView.cs index 648a01083..aee218ce1 100644 --- a/OpenGLScroller/CubeView.cs +++ b/OpenGLScroller/CubeView.cs @@ -10,10 +10,8 @@ using GLKit; using UIKit; -namespace OpenGLScroller -{ - public class CubeView : GLKView - { +namespace OpenGLScroller { + public class CubeView : GLKView { const int NumLittleCubes = 20; const float LittleCubeWidth = (320 / 3); const float ScrollerHeight = LittleCubeWidth; @@ -22,7 +20,7 @@ public class CubeView : GLKView int vertexArray; int vertexBuffer; - float[] gCubeVertexData = + float [] gCubeVertexData = { // Data layout for each line below is: // positionX, positionY, positionZ, normalX, normalY, normalZ, @@ -69,8 +67,7 @@ public class CubeView : GLKView -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f }; - struct CubeInfo - { + struct CubeInfo { public float Red; public float Green; public float Blue; @@ -105,7 +102,7 @@ public CubeInfo (float r, float g, float b, float x, float y, float z, float s, public CGPoint scrollOffset; GLKBaseEffect effect; - Random gen = new Random(); + Random gen = new Random (); public CubeView (CGRect frame) : base (frame) { @@ -114,14 +111,14 @@ public CubeView (CGRect frame) : base (frame) public CGRect ScrollableFrame { get { - return new CGRect (0, 30, 320, (int)ScrollerHeight); + return new CGRect (0, 30, 320, (int) ScrollerHeight); } } public CGSize ScrollableContentSize { get { float width = NumLittleCubes * LittleCubeWidth; - return new CGSize ((int)width, (int)ScrollerHeight); + return new CGSize ((int) width, (int) ScrollerHeight); } } @@ -147,7 +144,7 @@ public override CGRect Frame { set { base.Frame = value; - float aspect = (float)Math.Abs (Bounds.Size.Width / Bounds.Size.Height); + float aspect = (float) Math.Abs (Bounds.Size.Width / Bounds.Size.Height); Matrix4 projectionMatrix = Matrix4.CreatePerspectiveFieldOfView (MathHelper.DegreesToRadians (65), aspect, 0.1f, 100); if (effect != null) @@ -169,13 +166,13 @@ public override void Draw (CGRect rect) var cube = littleCube [i]; var translationX = ((i - 1) * UnitLittleCubeWidth) - (scrollOffset.X * UnitLittleCubeWidth / LittleCubeWidth); - var cubeMatrix = Matrix4.CreateTranslation ((float)translationX, 2.8f, -7); + var cubeMatrix = Matrix4.CreateTranslation ((float) translationX, 2.8f, -7); cubeMatrix = Matrix4.Mult (Matrix4.CreateFromAxisAngle (new Vector3 (cube.XAxis, cube.YAxis, cube.ZAxis), cube.RotationRadians), cubeMatrix); effect.Light0.DiffuseColor = new Vector4 (cube.Red, cube.Green, cube.Blue, 1.0f); effect.Transform.ModelViewMatrix = cubeMatrix; - effect.PrepareToDraw(); + effect.PrepareToDraw (); GL.DrawArrays (BeginMode.Triangles, 0, 36); } @@ -271,30 +268,30 @@ public void SetupGL () RandomizeBigCube (); - for (int i = 0; i< NumLittleCubes; i++) - littleCube[i] = bigCube; + for (int i = 0; i < NumLittleCubes; i++) + littleCube [i] = bigCube; - timeOfLastRenderedFrame = CAAnimation.CurrentMediaTime(); + timeOfLastRenderedFrame = CAAnimation.CurrentMediaTime (); } - public void RandomizeBigCube() + public void RandomizeBigCube () { - bigCube.Red = (minimums.Red + ((float) gen.NextDouble() * (maximums.Red - minimums.Red))); - bigCube.Green = (minimums.Green + ((float) gen.NextDouble() * (maximums.Green - minimums.Green))); - bigCube.Blue = (minimums.Blue + ((float) gen.NextDouble() * (maximums.Blue - minimums.Blue))); - bigCube.XAxis = (minimums.XAxis + ((float) gen.NextDouble() * (maximums.XAxis - minimums.XAxis))); - bigCube.YAxis = (minimums.YAxis + ((float) gen.NextDouble() * (maximums.YAxis - minimums.YAxis))); - bigCube.ZAxis = (minimums.ZAxis + ((float) gen.NextDouble() * (maximums.ZAxis - minimums.ZAxis))); - bigCube.Speed = (minimums.Speed + ((float) gen.NextDouble() * (maximums.Speed - minimums.Speed))); - bigCube.RotationRadians = (minimums.RotationRadians + ((float) gen.NextDouble() * (maximums.RotationRadians - minimums.RotationRadians))); - - bigCubeDirections.Red = PositiveOrNegative(); - bigCubeDirections.Green = PositiveOrNegative(); - bigCubeDirections.Blue = PositiveOrNegative(); - bigCubeDirections.XAxis = PositiveOrNegative(); - bigCubeDirections.YAxis = PositiveOrNegative(); - bigCubeDirections.ZAxis = PositiveOrNegative(); - bigCubeDirections.Speed = PositiveOrNegative(); + bigCube.Red = (minimums.Red + ((float) gen.NextDouble () * (maximums.Red - minimums.Red))); + bigCube.Green = (minimums.Green + ((float) gen.NextDouble () * (maximums.Green - minimums.Green))); + bigCube.Blue = (minimums.Blue + ((float) gen.NextDouble () * (maximums.Blue - minimums.Blue))); + bigCube.XAxis = (minimums.XAxis + ((float) gen.NextDouble () * (maximums.XAxis - minimums.XAxis))); + bigCube.YAxis = (minimums.YAxis + ((float) gen.NextDouble () * (maximums.YAxis - minimums.YAxis))); + bigCube.ZAxis = (minimums.ZAxis + ((float) gen.NextDouble () * (maximums.ZAxis - minimums.ZAxis))); + bigCube.Speed = (minimums.Speed + ((float) gen.NextDouble () * (maximums.Speed - minimums.Speed))); + bigCube.RotationRadians = (minimums.RotationRadians + ((float) gen.NextDouble () * (maximums.RotationRadians - minimums.RotationRadians))); + + bigCubeDirections.Red = PositiveOrNegative (); + bigCubeDirections.Green = PositiveOrNegative (); + bigCubeDirections.Blue = PositiveOrNegative (); + bigCubeDirections.XAxis = PositiveOrNegative (); + bigCubeDirections.YAxis = PositiveOrNegative (); + bigCubeDirections.ZAxis = PositiveOrNegative (); + bigCubeDirections.Speed = PositiveOrNegative (); bigCubeDirections.RotationRadians = 0.0f; } diff --git a/OpenGLScroller/ViewController.cs b/OpenGLScroller/ViewController.cs index 598c3e687..6761f27ff 100644 --- a/OpenGLScroller/ViewController.cs +++ b/OpenGLScroller/ViewController.cs @@ -10,10 +10,8 @@ using GLKit; using UIKit; -namespace OpenGLScroller -{ - public class ViewController : GLKViewController - { +namespace OpenGLScroller { + public class ViewController : GLKViewController { CADisplayLink displayLink; UIScrollView scrollView; @@ -60,7 +58,7 @@ void DraggingStarted (object sender, EventArgs ea) StartDisplayLinkIfNeeded (); } - void DraggingEnded (object sender, DraggingEventArgs ea) + void DraggingEnded (object sender, DraggingEventArgs ea) { if (!ea.Decelerate) StopDisplayLink (); diff --git a/PaintCode/PaintCodeDemo/AppDelegate.cs b/PaintCode/PaintCodeDemo/AppDelegate.cs index 49eaa7c7a..9bf9e4f95 100644 --- a/PaintCode/PaintCodeDemo/AppDelegate.cs +++ b/PaintCode/PaintCodeDemo/AppDelegate.cs @@ -5,19 +5,16 @@ using Foundation; using UIKit; -namespace PaintCode -{ - public class Application - { - static void Main (string[] args) +namespace PaintCode { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } } [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UINavigationController navCtrlr; UITabBarController tabBarController; @@ -36,10 +33,10 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) lineart = new DrawingViewController (); news = new NewsDialogViewController (); -// news.View.Frame = new System.Drawing.RectangleF (0 -// , UIApplication.SharedApplication.StatusBarFrame.Height -// , UIScreen.MainScreen.ApplicationFrame.Width -// , UIScreen.MainScreen.ApplicationFrame.Height); + // news.View.Frame = new System.Drawing.RectangleF (0 + // , UIApplication.SharedApplication.StatusBarFrame.Height + // , UIScreen.MainScreen.ApplicationFrame.Width + // , UIScreen.MainScreen.ApplicationFrame.Height); navCtrlr.PushViewController (news, false); diff --git a/PaintCode/PaintCodeDemo/BlueButton/BlueButton.cs b/PaintCode/PaintCodeDemo/BlueButton/BlueButton.cs index e96319035..882e46be6 100644 --- a/PaintCode/PaintCodeDemo/BlueButton/BlueButton.cs +++ b/PaintCode/PaintCodeDemo/BlueButton/BlueButton.cs @@ -2,8 +2,7 @@ using UIKit; using CoreGraphics; -namespace PaintCode -{ +namespace PaintCode { /// <summary> /// Blue button example /// http://paintcodeapp.com/examples.html @@ -53,7 +52,7 @@ public override bool BeginTracking (UITouch uitouch, UIEvent uievent) public override void EndTracking (UITouch uitouch, UIEvent uievent) { - if (isPressed && Enabled){ + if (isPressed && Enabled) { if (Tapped != null) Tapped (this); } @@ -80,7 +79,7 @@ public override void Draw (CGRect rect) //UIColor background = Enabled ? isPressed ? HighlightedColor : NormalColor : DisabledColor; UIColor buttonColor = NormalColor; //UIColor.FromRGBA (0.00f, 0.37f, 0.89f, 1.00f); - var buttonColorRGBA = new nfloat[4]; + var buttonColorRGBA = new nfloat [4]; buttonColor.GetRGBA ( out buttonColorRGBA [0], out buttonColorRGBA [1], @@ -89,7 +88,7 @@ out buttonColorRGBA [3] ); if (isPressed) { // Get the Hue Saturation Brightness Alpha copy of the color - var buttonColorHSBA = new nfloat[4]; + var buttonColorHSBA = new nfloat [4]; buttonColor.GetHSBA ( out buttonColorHSBA [0], out buttonColorHSBA [1], @@ -99,7 +98,7 @@ out buttonColorHSBA [3] // Change the brightness to a fixed value (0.5f) buttonColor = UIColor.FromHSBA (buttonColorHSBA [0], buttonColorHSBA [1], 0.5f, buttonColorHSBA [3]); // Re-set the base buttonColorRGBA because everything else is relative to it - buttonColorRGBA = new nfloat[4]; + buttonColorRGBA = new nfloat [4]; buttonColor.GetRGBA ( out buttonColorRGBA [0], out buttonColorRGBA [1], @@ -112,39 +111,39 @@ out buttonColorRGBA [3] // ------------- START PAINTCODE ------------- -//// Color Declarations + //// Color Declarations UIColor upColorOut = UIColor.FromRGBA (0.79f, 0.79f, 0.79f, 1.00f); UIColor bottomColorDown = UIColor.FromRGBA (0.21f, 0.21f, 0.21f, 1.00f); UIColor upColorInner = UIColor.FromRGBA (0.17f, 0.18f, 0.20f, 1.00f); UIColor bottomColorInner = UIColor.FromRGBA (0.98f, 0.98f, 0.99f, 1.00f); UIColor buttonFlareUpColor = UIColor.FromRGBA ( - (buttonColorRGBA [0] * 0.3f + 0.7f), - (buttonColorRGBA [1] * 0.3f + 0.7f), - (buttonColorRGBA [2] * 0.3f + 0.7f), - (buttonColorRGBA [3] * 0.3f + 0.7f) - ); + (buttonColorRGBA [0] * 0.3f + 0.7f), + (buttonColorRGBA [1] * 0.3f + 0.7f), + (buttonColorRGBA [2] * 0.3f + 0.7f), + (buttonColorRGBA [3] * 0.3f + 0.7f) + ); UIColor buttonTopColor = UIColor.FromRGBA ( - (buttonColorRGBA [0] * 0.8f), - (buttonColorRGBA [1] * 0.8f), - (buttonColorRGBA [2] * 0.8f), - (buttonColorRGBA [3] * 0.8f + 0.2f) - ); + (buttonColorRGBA [0] * 0.8f), + (buttonColorRGBA [1] * 0.8f), + (buttonColorRGBA [2] * 0.8f), + (buttonColorRGBA [3] * 0.8f + 0.2f) + ); UIColor buttonBottomColor = UIColor.FromRGBA ( - (buttonColorRGBA [0] * 0 + 1), - (buttonColorRGBA [1] * 0 + 1), - (buttonColorRGBA [2] * 0 + 1), - (buttonColorRGBA [3] * 0 + 1) - ); + (buttonColorRGBA [0] * 0 + 1), + (buttonColorRGBA [1] * 0 + 1), + (buttonColorRGBA [2] * 0 + 1), + (buttonColorRGBA [3] * 0 + 1) + ); UIColor buttonFlareBottomColor = UIColor.FromRGBA ( - (buttonColorRGBA [0] * 0.8f + 0.2f), - (buttonColorRGBA [1] * 0.8f + 0.2f), - (buttonColorRGBA [2] * 0.8f + 0.2f), - (buttonColorRGBA [3] * 0.8f + 0.2f) - ); + (buttonColorRGBA [0] * 0.8f + 0.2f), + (buttonColorRGBA [1] * 0.8f + 0.2f), + (buttonColorRGBA [2] * 0.8f + 0.2f), + (buttonColorRGBA [3] * 0.8f + 0.2f) + ); UIColor flareWhite = UIColor.FromRGBA (1.00f, 1.00f, 1.00f, 0.83f); -//// Gradient Declarations + //// Gradient Declarations var ringGradientColors = new CGColor [] { upColorOut.CGColor, bottomColorDown.CGColor @@ -176,16 +175,16 @@ out buttonColorRGBA [3] var buttonFlareGradientLocations = new nfloat [] { 0, 1 }; var buttonFlareGradient = new CGGradient (colorSpace, buttonFlareGradientColors, buttonFlareGradientLocations); -//// Shadow Declarations + //// Shadow Declarations var buttonInnerShadow = UIColor.Black.CGColor; var buttonInnerShadowOffset = new CGSize (0, -0); var buttonInnerShadowBlurRadius = 5; var buttonOuterShadow = UIColor.Black.CGColor; var buttonOuterShadowOffset = new CGSize (0, 2); - var buttonOuterShadowBlurRadius = isPressed ? 2 : 5; // ADDED this code after PaintCode + var buttonOuterShadowBlurRadius = isPressed ? 2 : 5; // ADDED this code after PaintCode -//// outerOval Drawing + //// outerOval Drawing var outerOvalPath = UIBezierPath.FromOval (new CGRect (5, 5, 63, 63)); context.SaveState (); context.SetShadow (buttonOuterShadowOffset, buttonOuterShadowBlurRadius, buttonOuterShadow); @@ -195,7 +194,7 @@ out buttonColorRGBA [3] context.EndTransparencyLayer (); context.RestoreState (); -//// overlayOval Drawing + //// overlayOval Drawing var overlayOvalPath = UIBezierPath.FromOval (new CGRect (5, 5, 63, 63)); context.SaveState (); overlayOvalPath.AddClip (); @@ -205,14 +204,14 @@ out buttonColorRGBA [3] CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); context.RestoreState (); -//// innerOval Drawing + //// innerOval Drawing var innerOvalPath = UIBezierPath.FromOval (new CGRect (12, 12, 49, 49)); context.SaveState (); innerOvalPath.AddClip (); context.DrawLinearGradient (ringInnerGradient, new CGPoint (36.5f, 12), new CGPoint (36.5f, 61), 0); context.RestoreState (); -//// buttonOval Drawing + //// buttonOval Drawing var buttonOvalPath = UIBezierPath.FromOval (new CGRect (14, 13, 46, 46)); context.SaveState (); buttonOvalPath.AddClip (); @@ -222,7 +221,7 @@ out buttonColorRGBA [3] CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); context.RestoreState (); -////// buttonOval Inner Shadow + ////// buttonOval Inner Shadow var buttonOvalBorderRect = buttonOvalPath.Bounds; buttonOvalBorderRect.Inflate (buttonInnerShadowBlurRadius, buttonInnerShadowBlurRadius); buttonOvalBorderRect.Offset (-buttonInnerShadowOffset.Width, -buttonInnerShadowOffset.Height); @@ -235,7 +234,7 @@ out buttonColorRGBA [3] context.SaveState (); { - var xOffset = buttonInnerShadowOffset.Width + (float)Math.Round (buttonOvalBorderRect.Width); + var xOffset = buttonInnerShadowOffset.Width + (float) Math.Round (buttonOvalBorderRect.Width); var yOffset = buttonInnerShadowOffset.Height; context.SetShadow ( new CGSize (xOffset + (xOffset >= 0 ? 0.1f : -0.1f), yOffset + (yOffset >= 0 ? 0.1f : -0.1f)), @@ -243,14 +242,14 @@ out buttonColorRGBA [3] buttonInnerShadow); buttonOvalPath.AddClip (); - var transform = CGAffineTransform.MakeTranslation (-(float)Math.Round (buttonOvalBorderRect.Width), 0); + var transform = CGAffineTransform.MakeTranslation (-(float) Math.Round (buttonOvalBorderRect.Width), 0); buttonOvalNegativePath.ApplyTransform (transform); UIColor.Gray.SetFill (); buttonOvalNegativePath.Fill (); } context.RestoreState (); -//// flareOval Drawing + //// flareOval Drawing var flareOvalPath = UIBezierPath.FromOval (new CGRect (22, 14, 29, 15)); context.SaveState (); flareOvalPath.AddClip (); diff --git a/PaintCode/PaintCodeDemo/BlueButton/BlueButtonViewController.cs b/PaintCode/PaintCodeDemo/BlueButton/BlueButtonViewController.cs index 3d268f59d..57aafc7fe 100644 --- a/PaintCode/PaintCodeDemo/BlueButton/BlueButtonViewController.cs +++ b/PaintCode/PaintCodeDemo/BlueButton/BlueButtonViewController.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace PaintCode -{ - public class BlueButtonViewController : UIViewController - { +namespace PaintCode { + public class BlueButtonViewController : UIViewController { public BlueButtonViewController () { } @@ -19,7 +17,7 @@ public override void ViewDidLoad () View.BackgroundColor = UIColor.White; - nfloat statusBarHeight = UIDevice.CurrentDevice.CheckSystemVersion (7,0) ? + nfloat statusBarHeight = UIDevice.CurrentDevice.CheckSystemVersion (7, 0) ? UIApplication.SharedApplication.StatusBarFrame.Height : 0f; button = new BlueButton (new CGRect (10, 10 + statusBarHeight, 120, 120 - statusBarHeight)); diff --git a/PaintCode/PaintCodeDemo/Calendar/CustomBadgeElement.cs b/PaintCode/PaintCodeDemo/Calendar/CustomBadgeElement.cs index 3ff2308ed..824af6822 100644 --- a/PaintCode/PaintCodeDemo/Calendar/CustomBadgeElement.cs +++ b/PaintCode/PaintCodeDemo/Calendar/CustomBadgeElement.cs @@ -15,13 +15,11 @@ using CoreGraphics; using Foundation; -namespace PaintCode -{ +namespace PaintCode { /// <summary> /// Lifted this code from MT.D source, so it could be customized /// </summary> - public class CustomBadgeElement - { + public class CustomBadgeElement { public CustomBadgeElement () { } @@ -32,32 +30,32 @@ public static UIImage MakeCalendarBadge (string smallText, string bigText) // ------------- START PAINTCODE ---------------- -//// Abstracted Graphic Attributes + //// Abstracted Graphic Attributes var textContent = bigText; var text2Content = smallText; -//// General Declarations + //// General Declarations using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) { using (var context = UIGraphics.GetCurrentContext ()) { -//// Color Declarations + //// Color Declarations UIColor dateRed = UIColor.FromRGBA (0.83f, 0.11f, 0.06f, 1.00f); -//// Gradient Declarations + //// Gradient Declarations var greyGradientColors = new CGColor [] { UIColor.White.CGColor, UIColor.FromRGBA (0.57f, 0.57f, 0.57f, 1.00f).CGColor, UIColor.Black.CGColor }; var greyGradientLocations = new nfloat [] { 0.65f, 0.75f, 0.75f }; - var greyGradient = new CGGradient (colorSpace, greyGradientColors, greyGradientLocations); + var greyGradient = new CGGradient (colorSpace, greyGradientColors, greyGradientLocations); -//// Shadow Declarations + //// Shadow Declarations var dropShadow = UIColor.DarkGray.CGColor; var dropShadowOffset = new CGSize (2, 2); var dropShadowBlurRadius = 1; -//// Rounded Rectangle Drawing + //// Rounded Rectangle Drawing var roundedRectanglePath = UIBezierPath.FromRoundedRect (new CGRect (1.5f, 1.5f, 38, 38), 4); context.SaveState (); context.SetShadow (dropShadowOffset, dropShadowBlurRadius, dropShadow); @@ -71,17 +69,17 @@ public static UIImage MakeCalendarBadge (string smallText, string bigText) roundedRectanglePath.LineWidth = 1; roundedRectanglePath.Stroke (); -//// Rounded Rectangle 2 Drawing + //// Rounded Rectangle 2 Drawing var roundedRectangle2Path = UIBezierPath.FromRoundedRect (new CGRect (2, 28, 37, 11), UIRectCorner.BottomLeft | UIRectCorner.BottomRight, new CGSize (4, 4)); dateRed.SetFill (); roundedRectangle2Path.Fill (); -//// Text Drawing + //// Text Drawing var textRect = new CGRect (2, 0, 37, 28); UIColor.Black.SetFill (); new NSString (textContent).DrawString (textRect, UIFont.FromName ("Helvetica-Bold", 24), UILineBreakMode.WordWrap, UITextAlignment.Center); -//// Text 2 Drawing + //// Text 2 Drawing var text2Rect = new CGRect (2, 27, 37, 15); UIColor.White.SetFill (); new NSString (text2Content).DrawString (text2Rect, UIFont.FromName ("HelveticaNeue-Bold", 9), UILineBreakMode.WordWrap, UITextAlignment.Center); diff --git a/PaintCode/PaintCodeDemo/Calendar/NewsDialogViewController.cs b/PaintCode/PaintCodeDemo/Calendar/NewsDialogViewController.cs index 96aa8cc35..3ae8b16f7 100644 --- a/PaintCode/PaintCodeDemo/Calendar/NewsDialogViewController.cs +++ b/PaintCode/PaintCodeDemo/Calendar/NewsDialogViewController.cs @@ -3,11 +3,9 @@ using MonoTouch.Dialog; using System.Collections.Generic; -namespace PaintCode -{ - public class NewsDialogViewController : DialogViewController - { - List<Tuple<DateTime,string>> newsItems = new List<Tuple<DateTime, string>> { +namespace PaintCode { + public class NewsDialogViewController : DialogViewController { + List<Tuple<DateTime, string>> newsItems = new List<Tuple<DateTime, string>> { new Tuple<DateTime, string> (new DateTime(2012,07,04), "Fireworks"), new Tuple<DateTime, string> (new DateTime(2012,05,01), "S-O-S"), new Tuple<DateTime, string> (new DateTime(2012,02,29), "Is it a leap year?") @@ -24,7 +22,7 @@ public NewsDialogViewController () : base (UITableViewStyle.Plain, null) foreach (var item in newsItems) { var published = item.Item1; var image = CustomBadgeElement.MakeCalendarBadge ( - published.ToString ("MMM").ToUpper () + published.ToString ("MMM").ToUpper () , published.ToString ("dd")); var badgeRow = new BadgeElement (image, item.Item2); @@ -32,7 +30,7 @@ public NewsDialogViewController () : base (UITableViewStyle.Plain, null) var dv = new DrawingViewController (); NavigationController.PushViewController (dv, true); }; - section.Add (badgeRow); + section.Add (badgeRow); } Root = new RootElement ("PaintCode examples") { section }; } diff --git a/PaintCode/PaintCodeDemo/GlossyButton/GlossyButton.cs b/PaintCode/PaintCodeDemo/GlossyButton/GlossyButton.cs index 783fe08b9..81da25d86 100644 --- a/PaintCode/PaintCodeDemo/GlossyButton/GlossyButton.cs +++ b/PaintCode/PaintCodeDemo/GlossyButton/GlossyButton.cs @@ -3,8 +3,7 @@ using CoreGraphics; using Foundation; -namespace PaintCode -{ +namespace PaintCode { /// <summary> /// Blue button example /// http://paintcodeapp.com/examples.html @@ -13,8 +12,7 @@ namespace PaintCode /// This implementation only deals with Normal and Pressed states. /// There is no handling for the Disabled state. /// </remarks> - public class GlossyButton : UIButton - { + public class GlossyButton : UIButton { bool isPressed; public UIColor NormalColor; @@ -80,7 +78,7 @@ public override void Draw (CGRect rect) //UIColor background = Enabled ? isPressed ? HighlightedColor : NormalColor : DisabledColor; UIColor buttonColor = NormalColor; //UIColor.FromRGBA (0.00f, 0.37f, 0.89f, 1.00f); - var buttonColorRGBA = new nfloat[4]; + var buttonColorRGBA = new nfloat [4]; buttonColor.GetRGBA ( out buttonColorRGBA [0], out buttonColorRGBA [1], @@ -89,7 +87,7 @@ out buttonColorRGBA [3] ); if (isPressed) { // Get the Hue Saturation Brightness Alpha copy of the color - var buttonColorHSBA = new nfloat[4]; + var buttonColorHSBA = new nfloat [4]; buttonColor.GetHSBA ( out buttonColorHSBA [0], out buttonColorHSBA [1], @@ -99,7 +97,7 @@ out buttonColorHSBA [3] // Change the brightness to a fixed value (0.5f) buttonColor = UIColor.FromHSBA (buttonColorHSBA [0], buttonColorHSBA [1], 0.5f, buttonColorHSBA [3]); // Re-set the base buttonColorRGBA because everything else is relative to it - buttonColorRGBA = new nfloat[4]; + buttonColorRGBA = new nfloat [4]; buttonColor.GetRGBA ( out buttonColorRGBA [0], out buttonColorRGBA [1], @@ -116,24 +114,24 @@ out buttonColorRGBA [3] // ------------- START PAINTCODE ------------- -// Color Declarations + // Color Declarations UIColor frameColorTop = UIColor.FromRGBA (0.20f, 0.20f, 0.20f, 1.00f); UIColor frameShadowColor = UIColor.FromRGBA (1.00f, 1.00f, 1.00f, 0.40f); UIColor glossyColorBottom = UIColor.FromRGBA ( - (buttonColorRGBA [0] * 0.6f + 0.4f), - (buttonColorRGBA [1] * 0.6f + 0.4f), - (buttonColorRGBA [2] * 0.6f + 0.4f), - (buttonColorRGBA [3] * 0.6f + 0.4f) - ); + (buttonColorRGBA [0] * 0.6f + 0.4f), + (buttonColorRGBA [1] * 0.6f + 0.4f), + (buttonColorRGBA [2] * 0.6f + 0.4f), + (buttonColorRGBA [3] * 0.6f + 0.4f) + ); UIColor glossyColorUp = UIColor.FromRGBA ( - (buttonColorRGBA [0] * 0.2f + 0.8f), - (buttonColorRGBA [1] * 0.2f + 0.8f), - (buttonColorRGBA [2] * 0.2f + 0.8f), - (buttonColorRGBA [3] * 0.2f + 0.8f) - ); + (buttonColorRGBA [0] * 0.2f + 0.8f), + (buttonColorRGBA [1] * 0.2f + 0.8f), + (buttonColorRGBA [2] * 0.2f + 0.8f), + (buttonColorRGBA [3] * 0.2f + 0.8f) + ); -// Gradient Declarations + // Gradient Declarations var glossyGradientColors = new CGColor [] { glossyColorUp.CGColor, glossyColorBottom.CGColor @@ -141,7 +139,7 @@ out buttonColorRGBA [3] var glossyGradientLocations = new nfloat [] { 0, 1 }; var glossyGradient = new CGGradient (colorSpace, glossyGradientColors, glossyGradientLocations); -// Shadow Declarations + // Shadow Declarations var frameInnerShadow = frameShadowColor.CGColor; var frameInnerShadowOffset = new CGSize (0, -0); const int frameInnerShadowBlurRadius = 3; @@ -153,10 +151,10 @@ out buttonColorRGBA [3] const int textShadowBlurRadius = 1; var buttonShadow = UIColor.Black.CGColor; - var buttonShadowOffset = new CGSize (0, isPressed ? 0 : 2); // ADDED this code after PaintCode - var buttonShadowBlurRadius = isPressed ? 2 : 3; // ADDED this code after PaintCode + var buttonShadowOffset = new CGSize (0, isPressed ? 0 : 2); // ADDED this code after PaintCode + var buttonShadowBlurRadius = isPressed ? 2 : 3; // ADDED this code after PaintCode -// outerFrame Drawing + // outerFrame Drawing var outerFramePath = UIBezierPath.FromRoundedRect (new CGRect (2.5f, 1.5f, 120, 32), 8); context.SaveState (); context.SetShadow (buttonShadowOffset, buttonShadowBlurRadius, buttonShadow); @@ -168,14 +166,14 @@ out buttonColorRGBA [3] outerFramePath.LineWidth = 1; outerFramePath.Stroke (); -// innerFrame Drawing + // innerFrame Drawing var innerFramePath = UIBezierPath.FromRoundedRect (new CGRect (5.5f, 4.5f, 114, 26), 5); context.SaveState (); context.SetShadow (frameInnerShadowOffset, frameInnerShadowBlurRadius, frameInnerShadow); buttonColor.SetFill (); innerFramePath.Fill (); -// innerFrame Inner Shadow + // innerFrame Inner Shadow var innerFrameBorderRect = innerFramePath.Bounds; innerFrameBorderRect.Inflate (buttonInnerShadowBlurRadius, buttonInnerShadowBlurRadius); innerFrameBorderRect.Offset (-buttonInnerShadowOffset.Width, -buttonInnerShadowOffset.Height); @@ -188,7 +186,7 @@ out buttonColorRGBA [3] context.SaveState (); { - var xOffset = buttonInnerShadowOffset.Width + (float)Math.Round (innerFrameBorderRect.Width); + var xOffset = buttonInnerShadowOffset.Width + (float) Math.Round (innerFrameBorderRect.Width); var yOffset = buttonInnerShadowOffset.Height; context.SetShadow ( new CGSize (xOffset + (xOffset >= 0 ? 0.1f : -0.1f), yOffset + (yOffset >= 0 ? 0.1f : -0.1f)), @@ -196,7 +194,7 @@ out buttonColorRGBA [3] buttonInnerShadow); innerFramePath.AddClip (); - var transform = CGAffineTransform.MakeTranslation (-(float)Math.Round (innerFrameBorderRect.Width), 0); + var transform = CGAffineTransform.MakeTranslation (-(float) Math.Round (innerFrameBorderRect.Width), 0); innerFrameNegativePath.ApplyTransform (transform); UIColor.Gray.SetFill (); innerFrameNegativePath.Fill (); @@ -209,17 +207,17 @@ out buttonColorRGBA [3] innerFramePath.LineWidth = 1; innerFramePath.Stroke (); -// Rounded Rectangle Drawing + // Rounded Rectangle Drawing var roundedRectanglePath = UIBezierPath.FromRoundedRect (new CGRect (8, 6, 109, 9), 4); context.SaveState (); roundedRectanglePath.AddClip (); context.DrawLinearGradient (glossyGradient, new CGPoint (62.5f, 6), new CGPoint (62.5f, 15), 0); context.RestoreState (); -// Text Drawing + // Text Drawing // var textRect = new CGRect (18, 6, 90, 28); context.SaveState (); - context.SetShadow(textShadowOffset, textShadowBlurRadius, textShadow); + context.SetShadow (textShadowOffset, textShadowBlurRadius, textShadow); glossyColorUp.SetFill (); // Use default button-drawn text diff --git a/PaintCode/PaintCodeDemo/GlossyButton/GlossyButtonViewController.cs b/PaintCode/PaintCodeDemo/GlossyButton/GlossyButtonViewController.cs index 1f70f98df..5e319b0c5 100644 --- a/PaintCode/PaintCodeDemo/GlossyButton/GlossyButtonViewController.cs +++ b/PaintCode/PaintCodeDemo/GlossyButton/GlossyButtonViewController.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace PaintCode -{ - public class GlossyButtonViewController : UIViewController - { +namespace PaintCode { + public class GlossyButtonViewController : UIViewController { public GlossyButtonViewController () { } @@ -19,7 +17,7 @@ public override void ViewDidLoad () View.BackgroundColor = UIColor.White; - nfloat statusBarHeight = UIDevice.CurrentDevice.CheckSystemVersion (7,0) ? + nfloat statusBarHeight = UIDevice.CurrentDevice.CheckSystemVersion (7, 0) ? UIApplication.SharedApplication.StatusBarFrame.Height : 0f; button = new GlossyButton (new CGRect (30, 30 + statusBarHeight, 130, 38)); button.SetTitle ("Stop!", UIControlState.Normal); @@ -30,15 +28,15 @@ public override void ViewDidLoad () View.AddSubview (button); - text = new UITextView (new CGRect (10, 100 + statusBarHeight , 300, 300 - statusBarHeight)); + text = new UITextView (new CGRect (10, 100 + statusBarHeight, 300, 300 - statusBarHeight)); text.Font = UIFont.SystemFontOfSize (14f); text.Editable = false; text.Text = "PaintCode GlossyButton Example\n\n" - +"After the button is drawn in PaintCode then added to a UIButton subclass " - +"Draw() method override, some color/style properties are tweaked in code " - +"to create the TouchDown effect.\n\n" - +"The button is sized exactly so that the 'built-in' UIButton.Title " - +"is displayed in the center of the PaintCode-generated design."; + + "After the button is drawn in PaintCode then added to a UIButton subclass " + + "Draw() method override, some color/style properties are tweaked in code " + + "to create the TouchDown effect.\n\n" + + "The button is sized exactly so that the 'built-in' UIButton.Title " + + "is displayed in the center of the PaintCode-generated design."; View.AddSubview (text); } } diff --git a/PaintCode/PaintCodeDemo/LineArt/DrawingView.cs b/PaintCode/PaintCodeDemo/LineArt/DrawingView.cs index 3f9b43b03..d86b57945 100644 --- a/PaintCode/PaintCodeDemo/LineArt/DrawingView.cs +++ b/PaintCode/PaintCodeDemo/LineArt/DrawingView.cs @@ -3,17 +3,15 @@ using CoreGraphics; using Foundation; -namespace PaintCode -{ +namespace PaintCode { // http://mikebluestein.wordpress.com/2010/02/21/drawing-with-coregraphics-in-monotouch-2/ - public class DrawingView : UIView - { + public class DrawingView : UIView { public DrawingView () { BackgroundColor = UIColor.White; } - public DrawingView (IntPtr p) : base(p) + public DrawingView (IntPtr p) : base (p) { BackgroundColor = UIColor.White; } @@ -28,14 +26,14 @@ public override void Draw (CGRect rect) using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) { using (var context = UIGraphics.GetCurrentContext ()) { -//// Color Declarations + //// Color Declarations UIColor gold = UIColor.FromRGBA (1.00f, 0.95f, 0.57f, 1.00f); UIColor brown = UIColor.FromRGBA (0.79f, 0.75f, 0.18f, 1.00f); UIColor lightBrown = UIColor.FromRGBA (0.69f, 0.57f, 0.23f, 1.00f); UIColor darkishBlue = UIColor.FromRGBA (0.20f, 0.39f, 0.98f, 1.00f); UIColor bottomColorDown = UIColor.FromRGBA (0.21f, 0.21f, 0.21f, 1.00f); -//// Gradient Declarations + //// Gradient Declarations var newGradientColors = new CGColor [] { UIColor.Black.CGColor, UIColor.White.CGColor @@ -50,18 +48,18 @@ public override void Draw (CGRect rect) var calendarGradientLocations = new nfloat [] { 0, 0.26f, 0.26f }; var calendarGradient = new CGGradient (colorSpace, calendarGradientColors, calendarGradientLocations); -//// Shadow Declarations + //// Shadow Declarations var shadow = UIColor.DarkGray.CGColor; var shadowOffset = new CGSize (2, 2); var shadowBlurRadius = 2; -//// Abstracted Graphic Attributes + //// Abstracted Graphic Attributes var monthContent = "MAR"; var dayContent = "24"; var dayFont = UIFont.FromName ("Helvetica-Bold", 24); var textContent = "News Headline"; -//// Oval 11 Drawing + //// Oval 11 Drawing var oval11Path = UIBezierPath.FromOval (new CGRect (256.5f, 46.5f, 13, 14)); lightBrown.SetFill (); oval11Path.Fill (); @@ -70,7 +68,7 @@ public override void Draw (CGRect rect) oval11Path.LineWidth = 1; oval11Path.Stroke (); -//// Oval 12 Drawing + //// Oval 12 Drawing var oval12Path = UIBezierPath.FromOval (new CGRect (280.5f, 46.5f, 13, 14)); lightBrown.SetFill (); oval12Path.Fill (); @@ -79,7 +77,7 @@ public override void Draw (CGRect rect) oval12Path.LineWidth = 1; oval12Path.Stroke (); -//// Rounded Rectangle Drawing + //// Rounded Rectangle Drawing var roundedRectanglePath = UIBezierPath.FromRoundedRect (new CGRect (8.5f, 60.5f, 37, 36), 4); context.SaveState (); context.SetShadow (shadowOffset, shadowBlurRadius, shadow); @@ -93,7 +91,7 @@ public override void Draw (CGRect rect) roundedRectanglePath.LineWidth = 1; roundedRectanglePath.Stroke (); -//// Rounded Rectangle 3 Drawing + //// Rounded Rectangle 3 Drawing UIBezierPath roundedRectangle3Path = new UIBezierPath (); roundedRectangle3Path.MoveTo (new CGPoint (9, 91.2f)); roundedRectangle3Path.AddCurveToPoint (new CGPoint (12.56f, 95), new CGPoint (9, 93.3f), new CGPoint (10.32f, 95)); @@ -108,7 +106,7 @@ public override void Draw (CGRect rect) UIColor.Red.SetFill (); roundedRectangle3Path.Fill (); -//// Month Drawing + //// Month Drawing var monthRect = new CGRect (10, 84, 34, 15); UIColor.White.SetFill (); new NSString (monthContent).DrawString ( @@ -118,12 +116,12 @@ public override void Draw (CGRect rect) UITextAlignment.Center ); -//// Day Drawing + //// Day Drawing var dayRect = new CGRect (0, 58, 54, 31); UIColor.Black.SetFill (); new NSString (dayContent).DrawString (dayRect, dayFont, UILineBreakMode.WordWrap, UITextAlignment.Center); -//// Text Drawing + //// Text Drawing var textRect = new CGRect (54, 60, 75, 38); UIColor.Black.SetFill (); new NSString (textContent).DrawString ( @@ -133,7 +131,7 @@ public override void Draw (CGRect rect) UITextAlignment.Left ); -//// Star Drawing + //// Star Drawing UIBezierPath starPath = new UIBezierPath (); starPath.MoveTo (new CGPoint (31, 14.5f)); starPath.AddLineTo (new CGPoint (26.24f, 21.45f)); @@ -153,7 +151,7 @@ public override void Draw (CGRect rect) starPath.LineWidth = 1; starPath.Stroke (); -//// Blue blob Drawing + //// Blue blob Drawing UIBezierPath blueBlobPath = new UIBezierPath (); blueBlobPath.MoveTo (new CGPoint (256.5f, 16.5f)); blueBlobPath.AddCurveToPoint (new CGPoint (240.5f, 41.5f), new CGPoint (235.5f, 37.5f), new CGPoint (217.53f, 41.55f)); @@ -169,7 +167,7 @@ public override void Draw (CGRect rect) blueBlobPath.LineWidth = 1; blueBlobPath.Stroke (); -//// Button Drawing + //// Button Drawing var buttonPath = UIBezierPath.FromRoundedRect (new CGRect (54.5f, 10.5f, 163, 31), 4); context.SaveState (); buttonPath.AddClip (); @@ -183,7 +181,7 @@ public override void Draw (CGRect rect) buttonPath.LineWidth = 1; buttonPath.Stroke (); -//// Smiley face Drawing + //// Smiley face Drawing var smileyFacePath = UIBezierPath.FromOval (new CGRect (159.5f, 49.5f, 47, 47)); gold.SetFill (); smileyFacePath.Fill (); @@ -192,7 +190,7 @@ public override void Draw (CGRect rect) smileyFacePath.LineWidth = 1; smileyFacePath.Stroke (); -//// Oval 2 Drawing + //// Oval 2 Drawing var oval2Path = UIBezierPath.FromOval (new CGRect (169.5f, 64.5f, 8, 8)); UIColor.Black.SetFill (); oval2Path.Fill (); @@ -201,7 +199,7 @@ public override void Draw (CGRect rect) oval2Path.LineWidth = 1; oval2Path.Stroke (); -//// Oval 3 Drawing + //// Oval 3 Drawing var oval3Path = UIBezierPath.FromOval (new CGRect (188.5f, 64.5f, 8, 8)); UIColor.Black.SetFill (); oval3Path.Fill (); @@ -210,7 +208,7 @@ public override void Draw (CGRect rect) oval3Path.LineWidth = 1; oval3Path.Stroke (); -//// Bezier 2 Drawing + //// Bezier 2 Drawing UIBezierPath bezier2Path = new UIBezierPath (); bezier2Path.MoveTo (new CGPoint (172.5f, 80.5f)); bezier2Path.AddCurveToPoint (new CGPoint (185.5f, 85.5f), new CGPoint (177.75f, 85), new CGPoint (182.04f, 86.03f)); @@ -219,7 +217,7 @@ public override void Draw (CGRect rect) bezier2Path.LineWidth = 2; bezier2Path.Stroke (); -//// Oval 5 Drawing + //// Oval 5 Drawing var oval5Path = UIBezierPath.FromOval (new CGRect (256.5f, 52.5f, 36, 33)); lightBrown.SetFill (); oval5Path.Fill (); @@ -228,7 +226,7 @@ public override void Draw (CGRect rect) oval5Path.LineWidth = 1; oval5Path.Stroke (); -//// Oval 6 Drawing + //// Oval 6 Drawing var oval6Path = UIBezierPath.FromOval (new CGRect (262.5f, 59.5f, 10, 19)); UIColor.White.SetFill (); oval6Path.Fill (); @@ -237,7 +235,7 @@ public override void Draw (CGRect rect) oval6Path.LineWidth = 1; oval6Path.Stroke (); -//// Oval 7 Drawing + //// Oval 7 Drawing var oval7Path = UIBezierPath.FromOval (new CGRect (275.5f, 59.5f, 10, 19)); UIColor.White.SetFill (); oval7Path.Fill (); @@ -246,7 +244,7 @@ public override void Draw (CGRect rect) oval7Path.LineWidth = 1; oval7Path.Stroke (); -//// Oval 9 Drawing + //// Oval 9 Drawing var oval9Path = UIBezierPath.FromOval (new CGRect (264.5f, 68.5f, 6, 5)); UIColor.Black.SetFill (); oval9Path.Fill (); @@ -255,7 +253,7 @@ public override void Draw (CGRect rect) oval9Path.LineWidth = 1; oval9Path.Stroke (); -//// Oval 10 Drawing + //// Oval 10 Drawing var oval10Path = UIBezierPath.FromOval (new CGRect (277.5f, 68.5f, 6, 5)); UIColor.Black.SetFill (); oval10Path.Fill (); @@ -264,7 +262,7 @@ public override void Draw (CGRect rect) oval10Path.LineWidth = 1; oval10Path.Stroke (); -//// Oval 4 Drawing + //// Oval 4 Drawing var oval4Path = UIBezierPath.FromOval (new CGRect (250.5f, 70.5f, 47, 24)); lightBrown.SetFill (); oval4Path.Fill (); @@ -273,7 +271,7 @@ public override void Draw (CGRect rect) oval4Path.LineWidth = 1; oval4Path.Stroke (); -//// Oval 8 Drawing + //// Oval 8 Drawing var oval8Path = UIBezierPath.FromOval (new CGRect (267.5f, 77.5f, 9, 4)); UIColor.Black.SetFill (); oval8Path.Fill (); @@ -282,7 +280,7 @@ public override void Draw (CGRect rect) oval8Path.LineWidth = 1; oval8Path.Stroke (); -//// Bezier 5 Drawing + //// Bezier 5 Drawing UIBezierPath bezier5Path = new UIBezierPath (); bezier5Path.MoveTo (new CGPoint (270.5f, 81.5f)); bezier5Path.AddCurveToPoint (new CGPoint (267.5f, 88.5f), new CGPoint (269.5f, 85.5f), new CGPoint (267.5f, 88.5f)); @@ -290,7 +288,7 @@ public override void Draw (CGRect rect) bezier5Path.LineWidth = 1; bezier5Path.Stroke (); -//// Bezier 6 Drawing + //// Bezier 6 Drawing UIBezierPath bezier6Path = new UIBezierPath (); bezier6Path.MoveTo (new CGPoint (272.5f, 81.5f)); bezier6Path.AddLineTo (new CGPoint (274.5f, 87.5f)); diff --git a/PaintCode/PaintCodeDemo/LineArt/DrawingViewController.cs b/PaintCode/PaintCodeDemo/LineArt/DrawingViewController.cs index 7f712ac1e..e80e24f5f 100644 --- a/PaintCode/PaintCodeDemo/LineArt/DrawingViewController.cs +++ b/PaintCode/PaintCodeDemo/LineArt/DrawingViewController.cs @@ -3,10 +3,8 @@ using Foundation; using CoreGraphics; -namespace PaintCode -{ - public class DrawingViewController : UIViewController - { +namespace PaintCode { + public class DrawingViewController : UIViewController { public DrawingViewController () { } @@ -21,7 +19,7 @@ public override void ViewDidLoad () View.BackgroundColor = UIColor.White; drawing = new DrawingView (); - nfloat statusBarHeight = UIDevice.CurrentDevice.CheckSystemVersion (7,0) ? + nfloat statusBarHeight = UIDevice.CurrentDevice.CheckSystemVersion (7, 0) ? UIApplication.SharedApplication.StatusBarFrame.Height : 0f; drawing.Frame = new CGRect (0, statusBarHeight, 320, 640 - statusBarHeight); @@ -30,9 +28,9 @@ public override void ViewDidLoad () text = new UITextView (new CGRect (10, 150 + statusBarHeight, 300, 300 - statusBarHeight)); text.Font = UIFont.SystemFontOfSize (14f); text.Editable = false; - text.Text = "Xamarin Shapes Example\n\n"+ + text.Text = "Xamarin Shapes Example\n\n" + "These are a few random shapes drawn with PaintCode and rendered in a UIView\n\n" - +"http://www.paintcodeapp.com/"; + + "http://www.paintcodeapp.com/"; View.AddSubview (text); } } diff --git a/PassKit/PassLibrary/AppDelegate.cs b/PassKit/PassLibrary/AppDelegate.cs index 62d561b74..75dc11352 100755 --- a/PassKit/PassLibrary/AppDelegate.cs +++ b/PassKit/PassLibrary/AppDelegate.cs @@ -4,7 +4,7 @@ namespace PassLibrary { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,9 +13,8 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; UINavigationController navigation; HomeScreen iPhoneHome; @@ -25,15 +24,15 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - iPhoneHome = new HomeScreen(); + iPhoneHome = new HomeScreen (); iPhoneHome.Title = "Pass Library"; - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - navigation = new UINavigationController(); - navigation.PushViewController (iPhoneHome,false); + navigation = new UINavigationController (); + navigation.PushViewController (iPhoneHome, false); window.RootViewController = navigation; return true; diff --git a/PassKit/PassLibrary/HomeScreen.cs b/PassKit/PassLibrary/HomeScreen.cs index d6d83d48a..7fcf35888 100644 --- a/PassKit/PassLibrary/HomeScreen.cs +++ b/PassKit/PassLibrary/HomeScreen.cs @@ -59,8 +59,8 @@ public override void ViewDidLoad () // Notification for changes to the library! noteCenter = NSNotificationCenter.DefaultCenter.AddObserver (PKPassLibrary.DidChangeNotification, (not) => { BeginInvokeOnMainThread (() => { - new UIAlertView("Pass Library Changed" - , "Notification Received", null, "OK", null).Show(); + new UIAlertView ("Pass Library Changed" + , "Notification Received", null, "OK", null).Show (); // refresh the list var passlist = library.GetPasses (); table.Source = new TableSource (passlist, library); @@ -110,27 +110,27 @@ void HandleAddTouchUpInside (object sender, EventArgs e) var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder var newFilePath = Path.Combine (documentsPath, "CouponBanana2.pkpass"); var builtInPassPath = Path.Combine (System.Environment.CurrentDirectory, "CouponBanana2.pkpass"); - if (!System.IO.File.Exists(newFilePath)) + if (!System.IO.File.Exists (newFilePath)) System.IO.File.Copy (builtInPassPath, newFilePath); NSData nsdata; - using ( FileStream oStream = File.Open (newFilePath, FileMode.Open ) ) { - nsdata = NSData.FromStream ( oStream ); + using (FileStream oStream = File.Open (newFilePath, FileMode.Open)) { + nsdata = NSData.FromStream (oStream); } - var err = new NSError(new NSString("42"), -42); - var newPass = new PKPass(nsdata,out err); + var err = new NSError (new NSString ("42"), -42); + var newPass = new PKPass (nsdata, out err); bool alreadyExists = library.Contains (newPass); if (alreadyExists) { - new UIAlertView(newPass.LocalizedDescription + " Tapped" - , "Already exists", null, "OK", null).Show(); + new UIAlertView (newPass.LocalizedDescription + " Tapped" + , "Already exists", null, "OK", null).Show (); } else { -// new UIAlertView(newPass.LocalizedDescription + " Tapped" -// , "Isn't in Pass Library", null, "OK, add it", null).Show(); + // new UIAlertView(newPass.LocalizedDescription + " Tapped" + // , "Isn't in Pass Library", null, "OK, add it", null).Show(); - var pkapvc = new PKAddPassesViewController(newPass); + var pkapvc = new PKAddPassesViewController (newPass); NavigationController.PresentModalViewController (pkapvc, true); } } @@ -147,26 +147,26 @@ void HandleReplaceTouchUpInside (object sender, EventArgs e) var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder var newFilePath = Path.Combine (documentsPath, "CouponBanana2.pkpass"); var builtInPassPath = Path.Combine (System.Environment.CurrentDirectory, "CouponBanana2.pkpass"); - if (!System.IO.File.Exists(newFilePath)) + if (!System.IO.File.Exists (newFilePath)) System.IO.File.Copy (builtInPassPath, newFilePath); NSData nsdata; - using ( FileStream oStream = File.Open (newFilePath, FileMode.Open ) ) { - nsdata = NSData.FromStream ( oStream ); + using (FileStream oStream = File.Open (newFilePath, FileMode.Open)) { + nsdata = NSData.FromStream (oStream); } - var err = new NSError(new NSString("42"), -42); - var newPass = new PKPass(nsdata,out err); + var err = new NSError (new NSString ("42"), -42); + var newPass = new PKPass (nsdata, out err); bool alreadyExists = library.Contains (newPass); if (alreadyExists) { library.Replace (newPass); - new UIAlertView(newPass.LocalizedDescription + " replaced!" - , "your choice if you offer UI when you update", null, "OK", null).Show(); + new UIAlertView (newPass.LocalizedDescription + " replaced!" + , "your choice if you offer UI when you update", null, "OK", null).Show (); } else - new UIAlertView(newPass.LocalizedDescription + " doesn't exit" - , "Can't *replace* if the pass isn't already in library", null, "OK", null).Show(); + new UIAlertView (newPass.LocalizedDescription + " doesn't exit" + , "Can't *replace* if the pass isn't already in library", null, "OK", null).Show (); } } } diff --git a/PassKit/PassLibrary/TableSource.cs b/PassKit/PassLibrary/TableSource.cs index fd56284c6..a9ff66d81 100755 --- a/PassKit/PassLibrary/TableSource.cs +++ b/PassKit/PassLibrary/TableSource.cs @@ -14,12 +14,12 @@ namespace PassLibrary { /// our Team ID). /// </summary> public class TableSource : UITableViewSource { - protected PKPass[] tableItems; + protected PKPass [] tableItems; PKPassLibrary library; protected string cellIdentifier = "TableCell"; - public TableSource (PKPass[] items, PKPassLibrary library) + public TableSource (PKPass [] items, PKPassLibrary library) { tableItems = items; this.library = library; @@ -38,7 +38,7 @@ public override nint RowsInSection (UITableView tableview, nint section) /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - var pass = tableItems[indexPath.Row]; + var pass = tableItems [indexPath.Row]; string passInfo = "Desc:" + pass.LocalizedDescription + "\nOrg:" + pass.OrganizationName @@ -49,8 +49,8 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + "\n#" + pass.SerialNumber + "\nPassUrl:" + pass.PassUrl; - new UIAlertView(pass.LocalizedName + " Selected" - ,passInfo , null, "OK", null).Show(); + new UIAlertView (pass.LocalizedName + " Selected" + , passInfo, null, "OK", null).Show (); tableView.DeselectRow (indexPath, true); } @@ -65,9 +65,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Subtitle, cellIdentifier); - cell.ImageView.Image = tableItems[indexPath.Row].Icon; - cell.TextLabel.Text = tableItems[indexPath.Row].LocalizedDescription; - cell.DetailTextLabel.Text = tableItems[indexPath.Row].LocalizedName; + cell.ImageView.Image = tableItems [indexPath.Row].Icon; + cell.TextLabel.Text = tableItems [indexPath.Row].LocalizedDescription; + cell.DetailTextLabel.Text = tableItems [indexPath.Row].LocalizedName; cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton; @@ -79,7 +79,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde /// </summary> public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath) { - var p = tableItems[indexPath.Row]; + var p = tableItems [indexPath.Row]; var pass = library.GetPass (p.PassTypeIdentifier, p.SerialNumber); UIApplication.SharedApplication.OpenUrl (p.PassUrl); diff --git a/PeekPopNavigation/PeekPopNavigation/AppDelegate.cs b/PeekPopNavigation/PeekPopNavigation/AppDelegate.cs index 568184856..63e9d2bc5 100644 --- a/PeekPopNavigation/PeekPopNavigation/AppDelegate.cs +++ b/PeekPopNavigation/PeekPopNavigation/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace PeekPopNavigation -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace PeekPopNavigation { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/ColorItemViewController.cs b/PeekPopNavigation/PeekPopNavigation/ColorItemViewController.cs index 79fb257e8..be34b2d70 100644 --- a/PeekPopNavigation/PeekPopNavigation/ColorItemViewController.cs +++ b/PeekPopNavigation/PeekPopNavigation/ColorItemViewController.cs @@ -2,74 +2,68 @@ using PeekPopNavigation.Models; using System; using UIKit; - -namespace PeekPopNavigation -{ - /// <summary> - /// A view controller to show a preview of a color and provide two alternative techniques for - /// starring/unstarring and deleting it.The first technique is an action method linked from the - /// navigation bar in the storyboard and the second is to support Peek Quick Actions by overriding the previewActionItems property. - /// </summary> - public partial class ColorItemViewController : UIViewController - { - public ColorItemViewController(IntPtr handle) : base(handle) { } - public ColorData ColorData { get; set; } +namespace PeekPopNavigation { + /// <summary> + /// A view controller to show a preview of a color and provide two alternative techniques for + /// starring/unstarring and deleting it.The first technique is an action method linked from the + /// navigation bar in the storyboard and the second is to support Peek Quick Actions by overriding the previewActionItems property. + /// </summary> + public partial class ColorItemViewController : UIViewController { + public ColorItemViewController (IntPtr handle) : base (handle) { } - public ColorItem ColorItem { get; set; } + public ColorData ColorData { get; set; } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public ColorItem ColorItem { get; set; } - base.Title = this.ColorItem.Name; - base.View.BackgroundColor = this.ColorItem.Color; - this.starButton.Title = this.GetStarButtonTitle(); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); - partial void TriggerStar(NSObject sender) - { - this.ColorItem.Starred = !this.ColorItem.Starred; - this.starButton.Title = this.GetStarButtonTitle(); - } + base.Title = this.ColorItem.Name; + base.View.BackgroundColor = this.ColorItem.Color; + this.starButton.Title = this.GetStarButtonTitle (); + } - partial void Delete(NSObject sender) - { - this.ColorData.Delete(this.ColorItem); + partial void TriggerStar (NSObject sender) + { + this.ColorItem.Starred = !this.ColorItem.Starred; + this.starButton.Title = this.GetStarButtonTitle (); + } - // The color no longer exists so dismiss this view controller. - base.NavigationController.PopViewController(true); - } + partial void Delete (NSObject sender) + { + this.ColorData.Delete (this.ColorItem); - private string GetStarButtonTitle() - { - return this.ColorItem.Starred ? "Unstar" : "Star"; - } + // The color no longer exists so dismiss this view controller. + base.NavigationController.PopViewController (true); + } - #region Supporting Peek Quick Actions + private string GetStarButtonTitle () + { + return this.ColorItem.Starred ? "Unstar" : "Star"; + } - public override IUIPreviewActionItem[] PreviewActionItems - { - get - { - var starAction = UIPreviewAction.Create(this.GetStarButtonTitle(), - UIPreviewActionStyle.Default, - (_, __) => - { - this.ColorItem.Starred = !this.ColorItem.Starred; - }); + #region Supporting Peek Quick Actions - var deleteAction = UIPreviewAction.Create("Delete", - UIPreviewActionStyle.Destructive, - (_, __) => - { - this.ColorData.Delete(this.ColorItem); - }); + public override IUIPreviewActionItem [] PreviewActionItems { + get { + var starAction = UIPreviewAction.Create (this.GetStarButtonTitle (), + UIPreviewActionStyle.Default, + (_, __) => { + this.ColorItem.Starred = !this.ColorItem.Starred; + }); - return new IUIPreviewActionItem[] { starAction, deleteAction }; - } - } + var deleteAction = UIPreviewAction.Create ("Delete", + UIPreviewActionStyle.Destructive, + (_, __) => { + this.ColorData.Delete (this.ColorItem); + }); - #endregion - } -} \ No newline at end of file + return new IUIPreviewActionItem [] { starAction, deleteAction }; + } + } + + #endregion + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerBase.cs b/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerBase.cs index fd1ec0c2e..fdca3755c 100644 --- a/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerBase.cs +++ b/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerBase.cs @@ -1,89 +1,82 @@ -using Foundation; +using Foundation; using PeekPopNavigation.Models; using System; using UIKit; -namespace PeekPopNavigation -{ - public class ColorsViewControllerBase : UITableViewController - { - public ColorsViewControllerBase(IntPtr handle) : base(handle) { } +namespace PeekPopNavigation { + public class ColorsViewControllerBase : UITableViewController { + public ColorsViewControllerBase (IntPtr handle) : base (handle) { } - protected static ColorData ColorData { get; } = new ColorData(); + protected static ColorData ColorData { get; } = new ColorData (); - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - NSNotificationCenter.DefaultCenter.AddObserver(ColorItem.ColorItemUpdated, OnColorItemUpdated); - NSNotificationCenter.DefaultCenter.AddObserver(ColorItem.ColorItemDeleted, OnColorItemDeleted); - } + NSNotificationCenter.DefaultCenter.AddObserver (ColorItem.ColorItemUpdated, OnColorItemUpdated); + NSNotificationCenter.DefaultCenter.AddObserver (ColorItem.ColorItemDeleted, OnColorItemDeleted); + } - #region Table view data source + #region Table view data source - public override nint RowsInSection(UITableView tableView, nint section) - { - return ColorData.Colors.Count; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return ColorData.Colors.Count; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("BasicCell", indexPath); + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("BasicCell", indexPath); - var colorItem = ColorData.Colors[indexPath.Row]; + var colorItem = ColorData.Colors [indexPath.Row]; - cell.TextLabel.Text = colorItem.Name; - cell.ImageView.Image = colorItem.Starred ? UIImage.FromBundle("StarFilled") : UIImage.FromBundle("StarOutline"); - cell.ImageView.TintColor = colorItem.Color; + cell.TextLabel.Text = colorItem.Name; + cell.ImageView.Image = colorItem.Starred ? UIImage.FromBundle ("StarFilled") : UIImage.FromBundle ("StarOutline"); + cell.ImageView.TintColor = colorItem.Color; - return cell; - } + return cell; + } - #endregion + #endregion - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.DestinationViewController is ColorItemViewController colorItemViewController) - { - var index = base.TableView.IndexPathForSelectedRow ?? base.TableView.IndexPathForCell(sender as UITableViewCell); - // Pass over a reference to the ColorData object and the specific ColorItem being viewed. - colorItemViewController.ColorData = ColorData; - colorItemViewController.ColorItem = ColorData.Colors[index.Row]; - } - } + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.DestinationViewController is ColorItemViewController colorItemViewController) { + var index = base.TableView.IndexPathForSelectedRow ?? base.TableView.IndexPathForCell (sender as UITableViewCell); + // Pass over a reference to the ColorData object and the specific ColorItem being viewed. + colorItemViewController.ColorData = ColorData; + colorItemViewController.ColorItem = ColorData.Colors [index.Row]; + } + } - private void OnColorItemDeleted(NSNotification notification) - { - // As there are two instances of colorData between `ColorsViewControllerStoryboard` and - // `ColorsViewControllerCode`, this method must only process notification callbacks when - // the instances of colorData match. - if (notification.Object is ColorData colorData) - { - // Grab the index of the deleted object from the userInfo dictionary - if (notification.UserInfo != null && - notification.UserInfo.TryGetValue(new NSString("index"), out NSObject @object) && - @object is NSNumber number) - { - var indexPath = NSIndexPath.FromRowSection(number.Int32Value, 0); - base.TableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); - } - } - } + private void OnColorItemDeleted (NSNotification notification) + { + // As there are two instances of colorData between `ColorsViewControllerStoryboard` and + // `ColorsViewControllerCode`, this method must only process notification callbacks when + // the instances of colorData match. + if (notification.Object is ColorData colorData) { + // Grab the index of the deleted object from the userInfo dictionary + if (notification.UserInfo != null && + notification.UserInfo.TryGetValue (new NSString ("index"), out NSObject @object) && + @object is NSNumber number) { + var indexPath = NSIndexPath.FromRowSection (number.Int32Value, 0); + base.TableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); + } + } + } - private void OnColorItemUpdated(NSNotification notification) - { - // As there are two instances of colorData between `ColorsViewControllerStoryboard` and - // `ColorsViewControllerCode`, this method must only process notification callbacks when - // the object for this notification exists in *this* view controller's colorData array. - if (notification.Object is ColorItem colorItem) - { - var arrayIndex = ColorData.Colors.IndexOf(colorItem); - if (arrayIndex != -1) - { - var indexPath = NSIndexPath.FromRowSection(arrayIndex, 0); - base.TableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); - } - } - } - } -} \ No newline at end of file + private void OnColorItemUpdated (NSNotification notification) + { + // As there are two instances of colorData between `ColorsViewControllerStoryboard` and + // `ColorsViewControllerCode`, this method must only process notification callbacks when + // the object for this notification exists in *this* view controller's colorData array. + if (notification.Object is ColorItem colorItem) { + var arrayIndex = ColorData.Colors.IndexOf (colorItem); + if (arrayIndex != -1) { + var indexPath = NSIndexPath.FromRowSection (arrayIndex, 0); + base.TableView.ReloadRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); + } + } + } + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerCode.cs b/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerCode.cs index 783a3660b..69a2304a5 100644 --- a/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerCode.cs +++ b/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerCode.cs @@ -2,58 +2,54 @@ using System; using UIKit; -namespace PeekPopNavigation -{ - /// <summary> - /// A subclass of `ColorsViewControllerBase` that adds support for Peek and Pop with code by calling - /// registerForPreviewing(with:sourceView:) and implementing UIViewControllerPreviewingDelegate. - /// </summary> - public partial class ColorsViewControllerCode : ColorsViewControllerBase, IUIViewControllerPreviewingDelegate - { - public ColorsViewControllerCode(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - base.RegisterForPreviewingWithDelegate(this, base.TableView); - } - - #region IUIViewControllerPreviewingDelegate - - public void CommitViewController(IUIViewControllerPreviewing previewingContext, UIViewController viewControllerToCommit) - { - // Push the configured view controller onto the navigation stack. - base.NavigationController.PushViewController(viewControllerToCommit, true); - } - - public UIViewController GetViewControllerForPreview(IUIViewControllerPreviewing previewingContext, CGPoint location) - { - UIViewController result = null; - - // First, get the index path and view for the previewed cell. - var indexPath = base.TableView.IndexPathForRowAtPoint(location); - if (indexPath != null) - { - var cell = base.TableView.CellAt(indexPath); - if (cell != null) - { - // Enable blurring of other UI elements, and a zoom in animation while peeking. - previewingContext.SourceRect = cell.Frame; - - // Create and configure an instance of the color item view controller to show for the peek. - var viewController = base.Storyboard.InstantiateViewController("ColorItemViewController") as ColorItemViewController; - - // Pass over a reference to the ColorData object and the specific ColorItem being viewed. - viewController.ColorData = ColorData; - viewController.ColorItem = ColorData.Colors[indexPath.Row]; - - result = viewController; - } - } - - return result; - } - - #endregion - } -} \ No newline at end of file +namespace PeekPopNavigation { + /// <summary> + /// A subclass of `ColorsViewControllerBase` that adds support for Peek and Pop with code by calling + /// registerForPreviewing(with:sourceView:) and implementing UIViewControllerPreviewingDelegate. + /// </summary> + public partial class ColorsViewControllerCode : ColorsViewControllerBase, IUIViewControllerPreviewingDelegate { + public ColorsViewControllerCode (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + base.RegisterForPreviewingWithDelegate (this, base.TableView); + } + + #region IUIViewControllerPreviewingDelegate + + public void CommitViewController (IUIViewControllerPreviewing previewingContext, UIViewController viewControllerToCommit) + { + // Push the configured view controller onto the navigation stack. + base.NavigationController.PushViewController (viewControllerToCommit, true); + } + + public UIViewController GetViewControllerForPreview (IUIViewControllerPreviewing previewingContext, CGPoint location) + { + UIViewController result = null; + + // First, get the index path and view for the previewed cell. + var indexPath = base.TableView.IndexPathForRowAtPoint (location); + if (indexPath != null) { + var cell = base.TableView.CellAt (indexPath); + if (cell != null) { + // Enable blurring of other UI elements, and a zoom in animation while peeking. + previewingContext.SourceRect = cell.Frame; + + // Create and configure an instance of the color item view controller to show for the peek. + var viewController = base.Storyboard.InstantiateViewController ("ColorItemViewController") as ColorItemViewController; + + // Pass over a reference to the ColorData object and the specific ColorItem being viewed. + viewController.ColorData = ColorData; + viewController.ColorItem = ColorData.Colors [indexPath.Row]; + + result = viewController; + } + } + + return result; + } + + #endregion + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerStoryboard.cs b/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerStoryboard.cs index 1d4d1dc46..30da456c6 100644 --- a/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerStoryboard.cs +++ b/PeekPopNavigation/PeekPopNavigation/ColorsViewControllerStoryboard.cs @@ -1,12 +1,10 @@ using System; -namespace PeekPopNavigation -{ - /// <summary> - /// This class intentionally adds no additional code to the base class as none is needed. - /// </summary> - public partial class ColorsViewControllerStoryboard : ColorsViewControllerBase - { - public ColorsViewControllerStoryboard (IntPtr handle) : base (handle) { } - } -} \ No newline at end of file +namespace PeekPopNavigation { + /// <summary> + /// This class intentionally adds no additional code to the base class as none is needed. + /// </summary> + public partial class ColorsViewControllerStoryboard : ColorsViewControllerBase { + public ColorsViewControllerStoryboard (IntPtr handle) : base (handle) { } + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/Main.cs b/PeekPopNavigation/PeekPopNavigation/Main.cs index e5a889b57..08cbe6ca0 100644 --- a/PeekPopNavigation/PeekPopNavigation/Main.cs +++ b/PeekPopNavigation/PeekPopNavigation/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PeekPopNavigation -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace PeekPopNavigation { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/Models/ColorData.cs b/PeekPopNavigation/PeekPopNavigation/Models/ColorData.cs index 8ca374351..76c017d3a 100644 --- a/PeekPopNavigation/PeekPopNavigation/Models/ColorData.cs +++ b/PeekPopNavigation/PeekPopNavigation/Models/ColorData.cs @@ -1,42 +1,39 @@ -using Foundation; +using Foundation; using System; using System.Collections.Generic; using UIKit; -namespace PeekPopNavigation.Models -{ - /// <summary> - /// A class that provides a sample set of color data. - /// </summary> - public class ColorData : NSObject - { - public List<ColorItem> Colors { get; } = new List<ColorItem> - { - new ColorItem("Red", UIColor.FromRGBA(1f, 0.231372549f, 0.1882352941f, 1f), false), - new ColorItem("Orange", UIColor.FromRGBA(1f, 0.5843137255f, 0f, 1f), false), - new ColorItem("Yellow", UIColor.FromRGBA(1f, 0.8f, 0f, 1f), false), - new ColorItem("Green", UIColor.FromRGBA(0.2980392157f, 0.8509803922f, 0.3921568627f, 1f), false), - new ColorItem("Teal Blue", UIColor.FromRGBA(0.3529411765f, 0.7843137255f, 0.9803921569f, 1f), false), - new ColorItem("Blue", UIColor.FromRGBA(0f, 0.4784313725f, 1f, 1f), false), - new ColorItem("Purple", UIColor.FromRGBA(0.3450980392f, 0.337254902f, 0.8392156863f, 1f), false), - new ColorItem("Pink", UIColor.FromRGBA(1f, 0.1764705882f, 0.3333333333f, 1f), false) - }; +namespace PeekPopNavigation.Models { + /// <summary> + /// A class that provides a sample set of color data. + /// </summary> + public class ColorData : NSObject { + public List<ColorItem> Colors { get; } = new List<ColorItem> + { + new ColorItem("Red", UIColor.FromRGBA(1f, 0.231372549f, 0.1882352941f, 1f), false), + new ColorItem("Orange", UIColor.FromRGBA(1f, 0.5843137255f, 0f, 1f), false), + new ColorItem("Yellow", UIColor.FromRGBA(1f, 0.8f, 0f, 1f), false), + new ColorItem("Green", UIColor.FromRGBA(0.2980392157f, 0.8509803922f, 0.3921568627f, 1f), false), + new ColorItem("Teal Blue", UIColor.FromRGBA(0.3529411765f, 0.7843137255f, 0.9803921569f, 1f), false), + new ColorItem("Blue", UIColor.FromRGBA(0f, 0.4784313725f, 1f, 1f), false), + new ColorItem("Purple", UIColor.FromRGBA(0.3450980392f, 0.337254902f, 0.8392156863f, 1f), false), + new ColorItem("Pink", UIColor.FromRGBA(1f, 0.1764705882f, 0.3333333333f, 1f), false) + }; - /// <summary> - /// Delete a ColorItem object from the set of colors. - /// </summary> - public void Delete(ColorItem colorItem) - { - var arrayIndex = Colors.IndexOf(colorItem); - if (arrayIndex == -1) - { - throw new ArgumentOutOfRangeException("Expected colorItem to exist in colors"); - } + /// <summary> + /// Delete a ColorItem object from the set of colors. + /// </summary> + public void Delete (ColorItem colorItem) + { + var arrayIndex = Colors.IndexOf (colorItem); + if (arrayIndex == -1) { + throw new ArgumentOutOfRangeException ("Expected colorItem to exist in colors"); + } - this.Colors.RemoveAt(arrayIndex); + this.Colors.RemoveAt (arrayIndex); - // Send a notifications so that UI can be updated and pass the index where the colorItem was removed from. - NSNotificationCenter.DefaultCenter.PostNotificationName(ColorItem.ColorItemDeleted, this, NSDictionary.FromObjectAndKey(new NSNumber(arrayIndex), new NSString("index"))); - } - } -} \ No newline at end of file + // Send a notifications so that UI can be updated and pass the index where the colorItem was removed from. + NSNotificationCenter.DefaultCenter.PostNotificationName (ColorItem.ColorItemDeleted, this, NSDictionary.FromObjectAndKey (new NSNumber (arrayIndex), new NSString ("index"))); + } + } +} diff --git a/PeekPopNavigation/PeekPopNavigation/Models/ColorItem.cs b/PeekPopNavigation/PeekPopNavigation/Models/ColorItem.cs index 8fb6054b3..071717cfb 100644 --- a/PeekPopNavigation/PeekPopNavigation/Models/ColorItem.cs +++ b/PeekPopNavigation/PeekPopNavigation/Models/ColorItem.cs @@ -1,67 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace PeekPopNavigation.Models -{ - /// <summary> - /// A model class used to represent starred and unstarred colors. - /// </summary> - public class ColorItem : NSObject - { - public static NSString ColorItemUpdated { get; } = new NSString("com.xamarin.peek-pop-navigation.ColorItemUpdated"); - public static NSString ColorItemDeleted { get; } = new NSString("com.xamarin.peek-pop-navigation.ColorItemDeleted"); - - private string name; - private UIColor color; - private bool starred; - - public ColorItem(string name, UIColor color, bool starred) - { - this.name = name; - this.color = color; - this.starred = starred; - } - - public string Name - { - get - { - return this.name; - } - - set - { - this.name = value; - NSNotificationCenter.DefaultCenter.PostNotificationName(ColorItemUpdated, this); - } - } - - public UIColor Color - { - get - { - return this.color; - } - - set - { - this.color = value; - NSNotificationCenter.DefaultCenter.PostNotificationName(ColorItemUpdated, this); - } - } - - public bool Starred - { - get - { - return this.starred; - } - - set - { - this.starred = value; - NSNotificationCenter.DefaultCenter.PostNotificationName(ColorItemUpdated, this); - } - } - } -} \ No newline at end of file +namespace PeekPopNavigation.Models { + /// <summary> + /// A model class used to represent starred and unstarred colors. + /// </summary> + public class ColorItem : NSObject { + public static NSString ColorItemUpdated { get; } = new NSString ("com.xamarin.peek-pop-navigation.ColorItemUpdated"); + public static NSString ColorItemDeleted { get; } = new NSString ("com.xamarin.peek-pop-navigation.ColorItemDeleted"); + + private string name; + private UIColor color; + private bool starred; + + public ColorItem (string name, UIColor color, bool starred) + { + this.name = name; + this.color = color; + this.starred = starred; + } + + public string Name { + get { + return this.name; + } + + set { + this.name = value; + NSNotificationCenter.DefaultCenter.PostNotificationName (ColorItemUpdated, this); + } + } + + public UIColor Color { + get { + return this.color; + } + + set { + this.color = value; + NSNotificationCenter.DefaultCenter.PostNotificationName (ColorItemUpdated, this); + } + } + + public bool Starred { + get { + return this.starred; + } + + set { + this.starred = value; + NSNotificationCenter.DefaultCenter.PostNotificationName (ColorItemUpdated, this); + } + } + } +} diff --git a/PickerControl/PickerControl/AppDelegate.cs b/PickerControl/PickerControl/AppDelegate.cs index ccad919c8..99159c1ae 100644 --- a/PickerControl/PickerControl/AppDelegate.cs +++ b/PickerControl/PickerControl/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace PickerControl -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace PickerControl { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/PickerControl/PickerControl/DatePickerViewController.cs b/PickerControl/PickerControl/DatePickerViewController.cs index f82092c18..8ff3e12fd 100644 --- a/PickerControl/PickerControl/DatePickerViewController.cs +++ b/PickerControl/PickerControl/DatePickerViewController.cs @@ -1,113 +1,109 @@ -using Foundation; -using System; -using UIKit; - -namespace PickerControl -{ - public partial class DatePickerViewController : UIViewController - { - - public DatePickerViewController (IntPtr handle) : base (handle) - { - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - datePickerMode.SelectedSegment = 0; - datePickerView.Mode = UIDatePickerMode.Time; - //datePickerView.TimeZone = NSTimeZone.FromName("America/New_York"); - //datePickerView.Locale = NSLocale.FromLocaleIdentifier("en_GB"); - - var calendar = new NSCalendar(NSCalendarType.Gregorian); - var currentDate = NSDate.Now; - var components = new NSDateComponents(); - - components.Year = -60; - - NSDate minDate = calendar.DateByAddingComponents(components, NSDate.Now, NSCalendarOptions.None); - - //Uncomment to set min and max date - - //datePickerView.MinimumDate = minDate; - //datePickerView.MaximumDate = (NSDate)DateTime.Today.AddYears(-7); - } - - partial void DateModeValueChanged(UISegmentedControl sender) - { - dateLabel.Text = ""; - - switch (sender.SelectedSegment) - { - case 0: // time - datePickerView.Mode = UIDatePickerMode.Time; - break; - - case 1: // date - datePickerView.Mode = UIDatePickerMode.Date; - break; - - case 2: // date & time - datePickerView.Mode = UIDatePickerMode.DateAndTime; - break; - - case 3: // counter - datePickerView.Mode = UIDatePickerMode.CountDownTimer; - datePickerView.MinuteInterval = 10; - break; - } - - datePickerView.Date = NSDate.Now; - - } - - partial void DateTimeChanged(UIDatePicker sender) - { - //Formatting for Date - NSDateFormatter dateFormat = new NSDateFormatter(); +using Foundation; +using System; +using UIKit; + +namespace PickerControl { + public partial class DatePickerViewController : UIViewController { + + public DatePickerViewController (IntPtr handle) : base (handle) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + datePickerMode.SelectedSegment = 0; + datePickerView.Mode = UIDatePickerMode.Time; + //datePickerView.TimeZone = NSTimeZone.FromName("America/New_York"); + //datePickerView.Locale = NSLocale.FromLocaleIdentifier("en_GB"); + + var calendar = new NSCalendar (NSCalendarType.Gregorian); + var currentDate = NSDate.Now; + var components = new NSDateComponents (); + + components.Year = -60; + + NSDate minDate = calendar.DateByAddingComponents (components, NSDate.Now, NSCalendarOptions.None); + + //Uncomment to set min and max date + + //datePickerView.MinimumDate = minDate; + //datePickerView.MaximumDate = (NSDate)DateTime.Today.AddYears(-7); + } + + partial void DateModeValueChanged (UISegmentedControl sender) + { + dateLabel.Text = ""; + + switch (sender.SelectedSegment) { + case 0: // time + datePickerView.Mode = UIDatePickerMode.Time; + break; + + case 1: // date + datePickerView.Mode = UIDatePickerMode.Date; + break; + + case 2: // date & time + datePickerView.Mode = UIDatePickerMode.DateAndTime; + break; + + case 3: // counter + datePickerView.Mode = UIDatePickerMode.CountDownTimer; + datePickerView.MinuteInterval = 10; + break; + } + + datePickerView.Date = NSDate.Now; + + } + + partial void DateTimeChanged (UIDatePicker sender) + { + //Formatting for Date + NSDateFormatter dateFormat = new NSDateFormatter (); dateFormat.DateFormat = "yyyy-MM-dd"; - - //Formatting for Time - NSDateFormatter timeFormat = new NSDateFormatter(); - timeFormat.TimeStyle = NSDateFormatterStyle.Short; - - //Formatting for Date and Time - NSDateFormatter dateTimeformat = new NSDateFormatter(); - dateTimeformat.DateStyle = NSDateFormatterStyle.Long; - dateTimeformat.TimeStyle = NSDateFormatterStyle.Short; - - // Figuring out when countdown is finished - var currentTime = NSDate.Now; - var countDownTimerTime = datePickerView.CountDownDuration; - var finishCountdown = currentTime.AddSeconds(countDownTimerTime); - - //Formatting Countdown display - NSDateFormatter coundownTimeformat = new NSDateFormatter(); - coundownTimeformat.DateStyle = NSDateFormatterStyle.Medium; - coundownTimeformat.TimeStyle = NSDateFormatterStyle.Medium; - - switch (datePickerMode.SelectedSegment) - { - case 0: // time - dateLabel.Text = timeFormat.ToString(datePickerView.Date); - break; - - case 1: // date - dateLabel.Text = dateFormat.ToString(datePickerView.Date); - break; - - case 2: // date & time - dateLabel.Text = dateTimeformat.ToString(datePickerView.Date); - break; - - case 3: // counter - dateLabel.Text = "Alarm set for:" + coundownTimeformat.ToString(finishCountdown); - break; - } - - } - - - } -} \ No newline at end of file + + //Formatting for Time + NSDateFormatter timeFormat = new NSDateFormatter (); + timeFormat.TimeStyle = NSDateFormatterStyle.Short; + + //Formatting for Date and Time + NSDateFormatter dateTimeformat = new NSDateFormatter (); + dateTimeformat.DateStyle = NSDateFormatterStyle.Long; + dateTimeformat.TimeStyle = NSDateFormatterStyle.Short; + + // Figuring out when countdown is finished + var currentTime = NSDate.Now; + var countDownTimerTime = datePickerView.CountDownDuration; + var finishCountdown = currentTime.AddSeconds (countDownTimerTime); + + //Formatting Countdown display + NSDateFormatter coundownTimeformat = new NSDateFormatter (); + coundownTimeformat.DateStyle = NSDateFormatterStyle.Medium; + coundownTimeformat.TimeStyle = NSDateFormatterStyle.Medium; + + switch (datePickerMode.SelectedSegment) { + case 0: // time + dateLabel.Text = timeFormat.ToString (datePickerView.Date); + break; + + case 1: // date + dateLabel.Text = dateFormat.ToString (datePickerView.Date); + break; + + case 2: // date & time + dateLabel.Text = dateTimeformat.ToString (datePickerView.Date); + break; + + case 3: // counter + dateLabel.Text = "Alarm set for:" + coundownTimeformat.ToString (finishCountdown); + break; + } + + } + + + } +} diff --git a/PickerControl/PickerControl/Main.cs b/PickerControl/PickerControl/Main.cs index aba7361fc..41db18201 100644 --- a/PickerControl/PickerControl/Main.cs +++ b/PickerControl/PickerControl/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PickerControl -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace PickerControl { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/PickerControl/PickerControl/PickerViewController.cs b/PickerControl/PickerControl/PickerViewController.cs index 0b0807ae1..8a3839c57 100644 --- a/PickerControl/PickerControl/PickerViewController.cs +++ b/PickerControl/PickerControl/PickerViewController.cs @@ -1,75 +1,72 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using System.Collections.Generic; -namespace PickerControl -{ - public partial class PickerViewController : UIViewController - { - public PickerViewController (IntPtr handle) : base (handle) - { - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - - var pickerModel = new PeopleModel(personLabel); - - personPicker.Model = pickerModel; - personPicker.ShowSelectionIndicator = true; - } - } +namespace PickerControl { + public partial class PickerViewController : UIViewController { + public PickerViewController (IntPtr handle) : base (handle) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); - public class PeopleModel : UIPickerViewModel - { - public string[] names = new string[] { - "Amy Burns", - "Kevin Mullins", - "Craig Dunn", - "Joel Martinez", - "Charles Petzold", - "David Britch", - "Mark McLemore", - "Tom Opegenorth", - "Joseph Hill", - "Miguel De Icaza" - }; - private UILabel personLabel; + var pickerModel = new PeopleModel (personLabel); + + personPicker.Model = pickerModel; + personPicker.ShowSelectionIndicator = true; + } + } + + public class PeopleModel : UIPickerViewModel { + public string [] names = new string [] { + "Amy Burns", + "Kevin Mullins", + "Craig Dunn", + "Joel Martinez", + "Charles Petzold", + "David Britch", + "Mark McLemore", + "Tom Opegenorth", + "Joseph Hill", + "Miguel De Icaza" + }; - public PeopleModel(UILabel personLabel) - { - this.personLabel = personLabel; - } + private UILabel personLabel; - public override nint GetComponentCount(UIPickerView pickerView) + public PeopleModel (UILabel personLabel) + { + this.personLabel = personLabel; + } + + public override nint GetComponentCount (UIPickerView pickerView) { return 2; } - public override nint GetRowsInComponent(UIPickerView pickerView, nint component) + public override nint GetRowsInComponent (UIPickerView pickerView, nint component) { return names.Length; } - public override string GetTitle(UIPickerView pickerView, nint row, nint component) + public override string GetTitle (UIPickerView pickerView, nint row, nint component) { if (component == 0) - return names[row]; + return names [row]; else - return row.ToString(); + return row.ToString (); } - public override void Selected(UIPickerView pickerView, nint row, nint component) - { - - personLabel.Text = $"This person is: {names[pickerView.SelectedRowInComponent(0)]},\n they are number {pickerView.SelectedRowInComponent(1)}"; + public override void Selected (UIPickerView pickerView, nint row, nint component) + { + + personLabel.Text = $"This person is: {names [pickerView.SelectedRowInComponent (0)]},\n they are number {pickerView.SelectedRowInComponent (1)}"; } - public override nfloat GetComponentWidth(UIPickerView picker, nint component) + public override nfloat GetComponentWidth (UIPickerView picker, nint component) { if (component == 0) return 240f; @@ -77,9 +74,9 @@ public override nfloat GetComponentWidth(UIPickerView picker, nint component) return 40f; } - public override nfloat GetRowHeight(UIPickerView picker, nint component) + public override nfloat GetRowHeight (UIPickerView picker, nint component) { return 40f; - } - } -} \ No newline at end of file + } + } +} diff --git a/PickerControl/PickerControl/ViewController.cs b/PickerControl/PickerControl/ViewController.cs index 1f65a20af..fb2483dfc 100644 --- a/PickerControl/PickerControl/ViewController.cs +++ b/PickerControl/PickerControl/ViewController.cs @@ -1,28 +1,26 @@ -using System; +using System; using UIKit; -namespace PickerControl -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } +namespace PickerControl { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - // Perform any additional setup after loading the view, typically from a nib. + public override void ViewDidLoad () + { + base.ViewDidLoad (); + // Perform any additional setup after loading the view, typically from a nib. - UIPickerView pickerView = new UIPickerView(); - } + UIPickerView pickerView = new UIPickerView (); + } - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - // Release any cached data, images, etc that aren't in use. - } - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + // Release any cached data, images, etc that aren't in use. + } + } } diff --git a/PinchIt/AppDelegate.cs b/PinchIt/AppDelegate.cs index a7e7d55c3..83f7d1013 100755 --- a/PinchIt/AppDelegate.cs +++ b/PinchIt/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace PinchIt -{ +namespace PinchIt { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) @@ -31,9 +29,8 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) } } - public class Application - { - static void Main (string[] args) + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/PinchIt/Cell.cs b/PinchIt/Cell.cs index af91dc3c4..10c9c78ae 100755 --- a/PinchIt/Cell.cs +++ b/PinchIt/Cell.cs @@ -4,10 +4,8 @@ using CoreGraphics; using Foundation; -namespace PinchIt -{ - public partial class Cell : UICollectionViewCell - { +namespace PinchIt { + public partial class Cell : UICollectionViewCell { UILabel label; [Export ("initWithFrame:")] diff --git a/PinchIt/PinchLayout.cs b/PinchIt/PinchLayout.cs index 166745b75..c49a41625 100755 --- a/PinchIt/PinchLayout.cs +++ b/PinchIt/PinchLayout.cs @@ -5,12 +5,10 @@ using Foundation; using CoreAnimation; -namespace PinchIt -{ - public class PinchLayout : UICollectionViewFlowLayout - { +namespace PinchIt { + public class PinchLayout : UICollectionViewFlowLayout { float pinchedCellScale; - CGPoint pinchedCellCenter ; + CGPoint pinchedCellCenter; public NSIndexPath pinchedCellPath { get; set; } public void applyPinchToLayoutAttributes (UICollectionViewLayoutAttributes layoutAttributes) @@ -22,7 +20,7 @@ public void applyPinchToLayoutAttributes (UICollectionViewLayoutAttributes layou } } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { var array = base.LayoutAttributesForElementsInRect (rect); @@ -34,7 +32,7 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath indexPath) { - var attributes = base.LayoutAttributesForItem(indexPath); + var attributes = base.LayoutAttributesForItem (indexPath); applyPinchToLayoutAttributes (attributes); @@ -44,13 +42,13 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSInde public void setPinchedCellScale (float scale) { pinchedCellScale = scale; - InvalidateLayout(); + InvalidateLayout (); } public void setPinchedCellCenter (CGPoint origin) { pinchedCellCenter = origin; - InvalidateLayout(); + InvalidateLayout (); } } } diff --git a/PinchIt/ViewController.cs b/PinchIt/ViewController.cs index 7eb5f04ff..6bb43e15e 100755 --- a/PinchIt/ViewController.cs +++ b/PinchIt/ViewController.cs @@ -4,10 +4,8 @@ using UIKit; using Foundation; -namespace PinchIt -{ - public class ViewController : UICollectionViewController - { +namespace PinchIt { + public class ViewController : UICollectionViewController { static NSString cellClass = new NSString ("Cell"); public ViewController (UICollectionViewFlowLayout layout) : base (layout) @@ -44,11 +42,12 @@ public void handlePinchGesture (UIPinchGestureRecognizer sender) pinchLayout.pinchedCellPath = CollectionView.IndexPathForItemAtPoint (initialPinchPoint); break; case UIGestureRecognizerState.Changed: - pinchLayout.setPinchedCellScale ((float)sender.Scale); + pinchLayout.setPinchedCellScale ((float) sender.Scale); pinchLayout.setPinchedCellCenter (sender.LocationInView (CollectionView)); break; default: - CollectionView.PerformBatchUpdates (delegate { + CollectionView.PerformBatchUpdates (delegate + { pinchLayout.pinchedCellPath = null; pinchLayout.setPinchedCellScale (1.0f); }, null); diff --git a/PokerNightVoting/AppDelegate.cs b/PokerNightVoting/AppDelegate.cs index 3cab9dd12..cce7e5c45 100644 --- a/PokerNightVoting/AppDelegate.cs +++ b/PokerNightVoting/AppDelegate.cs @@ -3,17 +3,14 @@ using Foundation; using UIKit; -namespace PokerNightVoting -{ +namespace PokerNightVoting { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } - public class Application - { - static void Main (string[] args) + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/PokerNightVoting/PNVModel.cs b/PokerNightVoting/PNVModel.cs index 701fbf42b..54b527f31 100644 --- a/PokerNightVoting/PNVModel.cs +++ b/PokerNightVoting/PNVModel.cs @@ -7,10 +7,8 @@ using EventKit; using CoreFoundation; -namespace PokerNightVoting -{ - public class PNVModel : NSObject - { +namespace PokerNightVoting { + public class PNVModel : NSObject { public EKEventStore EventStore { get; set; } public EKCalendar SelectedCalendar { get; set; } @@ -18,14 +16,15 @@ public class PNVModel : NSObject // updated by fetchPokerEvents: to store the matching events. List<EKEvent> events = new List<EKEvent> (); public List<DateTime> EventDates = new List<DateTime> (); - public Dictionary<DateTime,List<EKEvent>> eventDateToEventsDictionary = new Dictionary<DateTime,List<EKEvent>> (); + public Dictionary<DateTime, List<EKEvent>> eventDateToEventsDictionary = new Dictionary<DateTime, List<EKEvent>> (); public NSString PNVModelChangedNotification = new NSString ("PNVModelChangedNotification"); public PNVModel () { EventStore = new EKEventStore (); - EventStore.RequestAccess(EKEntityType.Event, delegate (bool arg1, NSError arg2) { + EventStore.RequestAccess (EKEntityType.Event, delegate (bool arg1, NSError arg2) + { if (arg2 != null) { Console.WriteLine (arg2.ToString ()); } @@ -41,7 +40,8 @@ public void StartBoradcastingModelChangedNotificaitons () // We want to listen to the EKEventStoreChangedNotification on the EKEventStore, // so that we update our list of events if anything changes in the EKEventStore. - NSNotificationCenter.DefaultCenter.AddObserver (EKEventStore.ChangedNotification, delegate { + NSNotificationCenter.DefaultCenter.AddObserver (EKEventStore.ChangedNotification, delegate + { FetchPokerEvents (); }, EventStore); } @@ -87,14 +87,13 @@ public EKCalendar CalendarWithTitle (string title) // updates data structures to only unclude events with the default title in our calendar. public void FetchPokerEvents () { - ThreadPool.QueueUserWorkItem ((v) => - { + ThreadPool.QueueUserWorkItem ((v) => { // create NSDates to represent arbitrary fetch date range. //approximately 2 days ago: var yesterday = DateTime.Now - TimeSpan.FromDays (1); var twoMonthsInFuture = DateTime.Now + TimeSpan.FromDays (60); - var predicate = EventStore.PredicateForEvents ((NSDate)yesterday, (NSDate)twoMonthsInFuture, null); + var predicate = EventStore.PredicateForEvents ((NSDate) yesterday, (NSDate) twoMonthsInFuture, null); var allEvents = EventStore.EventsMatching (predicate); if (allEvents == null) @@ -106,7 +105,8 @@ public void FetchPokerEvents () UpdateDataStructuresWithMatchingEvents (result); // notify the UI (on the main thread) that our model has changed - BeginInvokeOnMainThread (delegate { + BeginInvokeOnMainThread (delegate + { NSNotificationCenter.DefaultCenter.PostNotificationName (PNVModelChangedNotification, this); }); }); @@ -119,7 +119,7 @@ public void UpdateDataStructuresWithMatchingEvents (IEnumerable<EKEvent> evts) // Create a list of event start dates // Create a dictionary mapping from event start date to events with that start date var eventDates = new List<DateTime> (); - var eventDictionary = new Dictionary<DateTime,List<EKEvent>> (); + var eventDictionary = new Dictionary<DateTime, List<EKEvent>> (); foreach (var e in events) { var dt = (DateTime) e.StartDate; diff --git a/PokerNightVoting/PokerNightVotingViewController.cs b/PokerNightVoting/PokerNightVotingViewController.cs index 8000560b6..77fd31d7d 100644 --- a/PokerNightVoting/PokerNightVotingViewController.cs +++ b/PokerNightVoting/PokerNightVotingViewController.cs @@ -9,10 +9,8 @@ using EventKitUI; using MonoTouch.Dialog; -namespace PokerNightVoting -{ - public partial class PokerNightVotingViewController : DialogViewController - { +namespace PokerNightVoting { + public partial class PokerNightVotingViewController : DialogViewController { public PNVModel model { get; set; } public PokerNightVotingViewController (IntPtr handle) : base (handle) @@ -24,12 +22,13 @@ public override void ViewDidLoad () base.ViewDidLoad (); model = new PNVModel (); - if(model.SelectedCalendar != null) + if (model.SelectedCalendar != null) Title = model.SelectedCalendar.Title; // Start listening for changes model.StartBoradcastingModelChangedNotificaitons (); - NSNotificationCenter.DefaultCenter.AddObserver (model.PNVModelChangedNotification, delegate { + NSNotificationCenter.DefaultCenter.AddObserver (model.PNVModelChangedNotification, delegate + { RefreshView (); }); @@ -94,12 +93,12 @@ public void RefreshView () var entry = new StyledStringElement (local.ToShortTimeString (), votes, UITableViewCellStyle.Value1); - entry.Tapped += delegate { + entry.Tapped += delegate + { var controller = new EKEventViewController (); controller.Event = EventAtIndexPath (entry.IndexPath); controller.AllowsEditing = true; - controller.Completed += (object sender, EKEventViewEventArgs e) => - { + controller.Completed += (object sender, EKEventViewEventArgs e) => { model.FetchPokerEvents (); }; @@ -108,7 +107,8 @@ public void RefreshView () entry.Accessory = UITableViewCellAccessory.DetailDisclosureButton; - entry.AccessoryTapped += delegate { + entry.AccessoryTapped += delegate + { var ekevent = EventAtIndexPath (entry.IndexPath); model.IncreaseVoteOnEvent (ekevent); }; @@ -125,8 +125,7 @@ partial void addTime (UIKit.UIBarButtonItem sender) // Show the EKEventEditViewController var controller = new EKEventEditViewController (); controller.EventStore = model.EventStore; - controller.Completed += (object obj, EKEventEditEventArgs e) => - { + controller.Completed += (object obj, EKEventEditEventArgs e) => { DismissViewController (true, null); if (e.Action != EKEventEditViewAction.Canceled) { @@ -153,32 +152,29 @@ partial void showCalendarChooser (UIKit.UIBarButtonItem sender) { // Show the EKCalendarChooser var calendarChooser = new EKCalendarChooser (EKCalendarChooserSelectionStyle.Single, - EKCalendarChooserDisplayStyle.WritableCalendarsOnly, - model.EventStore); + EKCalendarChooserDisplayStyle.WritableCalendarsOnly, + model.EventStore); calendarChooser.ShowsDoneButton = true; calendarChooser.ShowsCancelButton = false; - calendarChooser.SelectionChanged += (object obj, EventArgs e) => - { + calendarChooser.SelectionChanged += (object obj, EventArgs e) => { // Called whenever the selection is changed by the user model.SelectedCalendar = (EKCalendar) calendarChooser.SelectedCalendars.AnyObject; Title = model.SelectedCalendar.Title; }; - calendarChooser.Finished += (object obj, EventArgs e) => - { + calendarChooser.Finished += (object obj, EventArgs e) => { // These are called when the corresponding button is pressed to dismiss the // controller. It is up to the recipient to dismiss the chooser. model.FetchPokerEvents (); DismissViewController (true, null); }; - calendarChooser.SelectionChanged += (object obj, EventArgs e) => - { + calendarChooser.SelectionChanged += (object obj, EventArgs e) => { // Update our events, since the selected calendar may have changed. model.SelectedCalendar = (EKCalendar) calendarChooser.SelectedCalendars.AnyObject; Title = model.SelectedCalendar.Title; }; if (model.SelectedCalendar != null) { - EKCalendar[] temp = new EKCalendar [1]; + EKCalendar [] temp = new EKCalendar [1]; temp [0] = model.SelectedCalendar; var selectedCalendars = new NSSet (temp); calendarChooser.SelectedCalendars = selectedCalendars; diff --git a/Popovers/AppDelegate.cs b/Popovers/AppDelegate.cs index de07880da..9df7f341e 100644 --- a/Popovers/AppDelegate.cs +++ b/Popovers/AppDelegate.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace Popovers -{ +namespace Popovers { [Register ("PopoversAppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - [Outlet] + public partial class AppDelegate : UIApplicationDelegate { + [Outlet] public override UIWindow Window { get; set; } [Outlet] diff --git a/Popovers/DetailViewController.cs b/Popovers/DetailViewController.cs index 4a97d1304..8f1864ca3 100644 --- a/Popovers/DetailViewController.cs +++ b/Popovers/DetailViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Popovers -{ - public partial class DetailViewController : UIViewController - { +namespace Popovers { + public partial class DetailViewController : UIViewController { [Outlet] public UIToolbar Toolbar { get; set; } @@ -49,7 +47,7 @@ class SplitViewDelegate : UISplitViewControllerDelegate { public override void WillHideViewController (UISplitViewController svc, UIViewController aViewController, UIBarButtonItem barButtonItem, UIPopoverController pc) { - barButtonItem.Title = "MasterList"; + barButtonItem.Title = "MasterList"; var items = new List<UIBarButtonItem> (Parent.Toolbar.Items); items.Insert (0, barButtonItem); Parent.Toolbar.SetItems (items.ToArray (), true); @@ -75,22 +73,22 @@ public override void WillPresentViewController (UISplitViewController svc, UIPop public DetailViewController (IntPtr handle) : base (handle) { // lost connection to DetailView.xib, create buttons manually for now - Button1 = new UIButton(); - Button2 = new UIButton(); - Button3 = new UIButton(); - Button4 = new UIButton(); - Button5 = new UIButton(); + Button1 = new UIButton (); + Button2 = new UIButton (); + Button3 = new UIButton (); + Button4 = new UIButton (); + Button5 = new UIButton (); } //loads the DetailViewController.xib file and connects it to this object public DetailViewController () : base ("DetailViewController", null) { // lost connection to DetailView.xib, create buttons manually for now - Button1 = new UIButton(); - Button2 = new UIButton(); - Button3 = new UIButton(); - Button4 = new UIButton(); - Button5 = new UIButton(); + Button1 = new UIButton (); + Button2 = new UIButton (); + Button3 = new UIButton (); + Button4 = new UIButton (); + Button5 = new UIButton (); } public override void ViewDidLoad () @@ -109,9 +107,10 @@ public override void ViewDidLoad () } [Action ("showPopover:")] - public void ShowPopover (NSObject sender) { + public void ShowPopover (NSObject sender) + { // Set the sender to a UIButton. - UIButton tappedButton = (UIButton)sender; + UIButton tappedButton = (UIButton) sender; // Present the popover from the button that was tapped in the detail view. DetailViewPopover.PresentFromRect (tappedButton.Frame, View, UIPopoverArrowDirection.Any, true); @@ -121,9 +120,10 @@ public void ShowPopover (NSObject sender) { } [Action ("showPopoverFromBarButtonItem:")] - public void ShowPopoverFromBarButtonItem (NSObject sender) { + public void ShowPopoverFromBarButtonItem (NSObject sender) + { // Set the sender to a UIBarButtonItem. - UIBarButtonItem tappedButton = (UIBarButtonItem)sender; + UIBarButtonItem tappedButton = (UIBarButtonItem) sender; // If the master list popover is showing, dismiss it before presenting the popover from the bar button item. if (MainPopoverController != null) @@ -145,7 +145,7 @@ public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) { - if (LastTappedButton != null) + if (LastTappedButton != null) ShowPopover (LastTappedButton); } @@ -159,7 +159,7 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat Button5.Frame = new CGRect (588, 824, 160, 160); } else { Button1.Frame = new CGRect (20, 64, 160, 160); - Button2.Frame = new CGRect(524, 64, 160, 160); + Button2.Frame = new CGRect (524, 64, 160, 160); Button3.Frame = new CGRect (272, 311, 160, 160); Button4.Frame = new CGRect (20, 568, 160, 160); Button5.Frame = new CGRect (524, 568, 160, 160); @@ -169,7 +169,7 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat public void WillHideViewController (object sender, UISplitViewHideEventArgs args) { - args.BarButtonItem.Title = "MasterList"; + args.BarButtonItem.Title = "MasterList"; var items = new List<UIBarButtonItem> (Toolbar.Items); items.Insert (0, args.BarButtonItem); Toolbar.SetItems (items.ToArray (), true); diff --git a/Popovers/Main.cs b/Popovers/Main.cs index c8b0ddb16..2adca5c5d 100644 --- a/Popovers/Main.cs +++ b/Popovers/Main.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace Popovers -{ - public class Application - { +namespace Popovers { + public class Application { /// <summary> /// This is the main entry point of the application. /// </summary> - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Popovers/PopoverContentViewController.cs b/Popovers/PopoverContentViewController.cs index 39048296f..674647ecd 100644 --- a/Popovers/PopoverContentViewController.cs +++ b/Popovers/PopoverContentViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Popovers -{ - public partial class PopoverContentViewController : UIViewController - { +namespace Popovers { + public partial class PopoverContentViewController : UIViewController { public PopoverContentViewController (IntPtr handle) : base (handle) { } diff --git a/Popovers/RootViewController.cs b/Popovers/RootViewController.cs index e79e0a1d8..131eb268d 100644 --- a/Popovers/RootViewController.cs +++ b/Popovers/RootViewController.cs @@ -5,8 +5,7 @@ using Foundation; using UIKit; -namespace Popovers -{ +namespace Popovers { class TableSource : UITableViewSource { public override nint NumberOfSections (UITableView tableView) { @@ -32,8 +31,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde } } - public partial class RootViewController : UITableViewController - { + public partial class RootViewController : UITableViewController { [Outlet] public DetailViewController DetailViewController { get; set; } diff --git a/PrintBanner/PrintBanner/AppDelegate.cs b/PrintBanner/PrintBanner/AppDelegate.cs index fd7ec9205..e6481c69e 100644 --- a/PrintBanner/PrintBanner/AppDelegate.cs +++ b/PrintBanner/PrintBanner/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace PrintBanner -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace PrintBanner { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/PrintBanner/PrintBanner/Main.cs b/PrintBanner/PrintBanner/Main.cs index 2c302d188..e8b5eb0dd 100644 --- a/PrintBanner/PrintBanner/Main.cs +++ b/PrintBanner/PrintBanner/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PrintBanner -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace PrintBanner { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/PrintBanner/PrintBanner/PrintBannerViewController.cs b/PrintBanner/PrintBanner/PrintBannerViewController.cs index 1eb5484e6..0378cb111 100644 --- a/PrintBanner/PrintBanner/PrintBannerViewController.cs +++ b/PrintBanner/PrintBanner/PrintBannerViewController.cs @@ -2,112 +2,107 @@ using System; using UIKit; -namespace PrintBanner -{ - public partial class PrintBannerViewController : UIViewController - { - private static readonly string[] FontNames = { "American Typewriter", "Snell Roundhand", "Courier", "Arial" }; - - private static readonly UIColor[] Colors = { UIColor.Black, UIColor.Orange, UIColor.Purple, UIColor.Red }; - - private const float DefaultFontSize = 48f; - - private const float PaddingFactor = 0.1f; - - private UISimpleTextPrintFormatter textFormatter; - - public PrintBannerViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - textField.EditingDidEndOnExit += (sender, e) => textField.ResignFirstResponder(); - } - - partial void Print(UIButton sender) - { - var controller = UIPrintInteractionController.SharedPrintController; - controller.CutLengthForPaper = delegate (UIPrintInteractionController printController, UIPrintPaper paper) - { - // Create a font with arbitrary size so that you can calculate the approximate - // font points per screen point for the height of the text. - var font = textFormatter.Font; - - var text = new NSString(textField.Text); - var attributes = new UIStringAttributes { Font = font }; - var size = text.GetSizeUsingAttributes(attributes); - - nfloat approximateFontPointPerScreenPoint = font.PointSize / size.Height; - - // Create a new font using a size that will fill the width of the paper - font = GetSelectedFont((float)(paper.PrintableRect.Size.Width * approximateFontPointPerScreenPoint)); - - // Calculate the height and width of the text with the final font size - attributes.Font = font; - var finalTextSize = text.GetSizeUsingAttributes(attributes); - - // Set the UISimpleTextFormatter font to the font with the size calculated - textFormatter.Font = font; - - // Calculate the margins of the roll. Roll printers may have unprintable areas - // before and after the cut. We must add this to our cut length to ensure the - // printable area has enough room for our text. - nfloat lengthOfMargins = paper.PaperSize.Height - paper.PrintableRect.Size.Height; - - // The cut length is the width of the text, plus margins, plus some padding - return finalTextSize.Width + lengthOfMargins + paper.PrintableRect.Size.Width * PaddingFactor; - }; - - var printInfo = UIPrintInfo.PrintInfo; - printInfo.OutputType = UIPrintInfoOutputType.General; - printInfo.Orientation = UIPrintInfoOrientation.Landscape; - printInfo.JobName = textField.Text; - - textFormatter = new UISimpleTextPrintFormatter(textField.Text) - { - Color = GetSelectedColor(), - Font = GetSelectedFont() - }; - - controller.PrintInfo = printInfo; - controller.PrintFormatter = textFormatter; - controller.Present(true, OnPrintingComplete); - - printInfo.Dispose(); - printInfo = null; - } - - private void OnPrintingComplete(UIPrintInteractionController controller, bool completed, NSError error) - { - if (completed && error != null) - { - var message = $"Due to error in domain `{error.Domain}` with code: {error.Code}"; - Console.WriteLine($"FAILED! {message}"); - - var alert = UIAlertController.Create("Failed!", message, UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - ShowViewController(alert, this); - } - } - - private UIFont GetSelectedFont(float size = DefaultFontSize) - { - return UIFont.FromName(FontNames[fontSelection.SelectedSegment], size) ?? UIFont.SystemFontOfSize(size); - } - - private UIColor GetSelectedColor() - { - return Colors[colorSelection.SelectedSegment]; - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (textFormatter != null) - { - textFormatter.Dispose(); - textFormatter = null; - } - } - } -} \ No newline at end of file +namespace PrintBanner { + public partial class PrintBannerViewController : UIViewController { + private static readonly string [] FontNames = { "American Typewriter", "Snell Roundhand", "Courier", "Arial" }; + + private static readonly UIColor [] Colors = { UIColor.Black, UIColor.Orange, UIColor.Purple, UIColor.Red }; + + private const float DefaultFontSize = 48f; + + private const float PaddingFactor = 0.1f; + + private UISimpleTextPrintFormatter textFormatter; + + public PrintBannerViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + textField.EditingDidEndOnExit += (sender, e) => textField.ResignFirstResponder (); + } + + partial void Print (UIButton sender) + { + var controller = UIPrintInteractionController.SharedPrintController; + controller.CutLengthForPaper = delegate (UIPrintInteractionController printController, UIPrintPaper paper) + { + // Create a font with arbitrary size so that you can calculate the approximate + // font points per screen point for the height of the text. + var font = textFormatter.Font; + + var text = new NSString (textField.Text); + var attributes = new UIStringAttributes { Font = font }; + var size = text.GetSizeUsingAttributes (attributes); + + nfloat approximateFontPointPerScreenPoint = font.PointSize / size.Height; + + // Create a new font using a size that will fill the width of the paper + font = GetSelectedFont ((float) (paper.PrintableRect.Size.Width * approximateFontPointPerScreenPoint)); + + // Calculate the height and width of the text with the final font size + attributes.Font = font; + var finalTextSize = text.GetSizeUsingAttributes (attributes); + + // Set the UISimpleTextFormatter font to the font with the size calculated + textFormatter.Font = font; + + // Calculate the margins of the roll. Roll printers may have unprintable areas + // before and after the cut. We must add this to our cut length to ensure the + // printable area has enough room for our text. + nfloat lengthOfMargins = paper.PaperSize.Height - paper.PrintableRect.Size.Height; + + // The cut length is the width of the text, plus margins, plus some padding + return finalTextSize.Width + lengthOfMargins + paper.PrintableRect.Size.Width * PaddingFactor; + }; + + var printInfo = UIPrintInfo.PrintInfo; + printInfo.OutputType = UIPrintInfoOutputType.General; + printInfo.Orientation = UIPrintInfoOrientation.Landscape; + printInfo.JobName = textField.Text; + + textFormatter = new UISimpleTextPrintFormatter (textField.Text) { + Color = GetSelectedColor (), + Font = GetSelectedFont () + }; + + controller.PrintInfo = printInfo; + controller.PrintFormatter = textFormatter; + controller.Present (true, OnPrintingComplete); + + printInfo.Dispose (); + printInfo = null; + } + + private void OnPrintingComplete (UIPrintInteractionController controller, bool completed, NSError error) + { + if (completed && error != null) { + var message = $"Due to error in domain `{error.Domain}` with code: {error.Code}"; + Console.WriteLine ($"FAILED! {message}"); + + var alert = UIAlertController.Create ("Failed!", message, UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + ShowViewController (alert, this); + } + } + + private UIFont GetSelectedFont (float size = DefaultFontSize) + { + return UIFont.FromName (FontNames [fontSelection.SelectedSegment], size) ?? UIFont.SystemFontOfSize (size); + } + + private UIColor GetSelectedColor () + { + return Colors [colorSelection.SelectedSegment]; + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (textFormatter != null) { + textFormatter.Dispose (); + textFormatter = null; + } + } + } +} diff --git a/PrintSample/PrintSample/AppDelegate.cs b/PrintSample/PrintSample/AppDelegate.cs index aa6339d68..3bdeeb810 100644 --- a/PrintSample/PrintSample/AppDelegate.cs +++ b/PrintSample/PrintSample/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace PrintSample -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace PrintSample { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/PrintSample/PrintSample/Main.cs b/PrintSample/PrintSample/Main.cs index 6aa13edd8..460f67a23 100644 --- a/PrintSample/PrintSample/Main.cs +++ b/PrintSample/PrintSample/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PrintSample -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace PrintSample { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/PrintSample/PrintSample/ViewController.cs b/PrintSample/PrintSample/ViewController.cs index 763335e04..e8fa6b0e3 100644 --- a/PrintSample/PrintSample/ViewController.cs +++ b/PrintSample/PrintSample/ViewController.cs @@ -1,39 +1,34 @@ -using System; +using System; using UIKit; -namespace PrintSample -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) { } +namespace PrintSample { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { } - partial void Print(UIButton sender) - { - var printInfo = UIPrintInfo.PrintInfo; - printInfo.JobName = "My first Print Job"; - printInfo.OutputType = UIPrintInfoOutputType.General; + partial void Print (UIButton sender) + { + var printInfo = UIPrintInfo.PrintInfo; + printInfo.JobName = "My first Print Job"; + printInfo.OutputType = UIPrintInfoOutputType.General; - var textFormatter = new UISimpleTextPrintFormatter("Once upon a time...") - { - StartPage = 0, - MaximumContentWidth = 6 * 72, - PerPageContentInsets = new UIEdgeInsets(72, 72, 72, 72), - }; + var textFormatter = new UISimpleTextPrintFormatter ("Once upon a time...") { + StartPage = 0, + MaximumContentWidth = 6 * 72, + PerPageContentInsets = new UIEdgeInsets (72, 72, 72, 72), + }; - var printer = UIPrintInteractionController.SharedPrintController; - printer.PrintInfo = printInfo; - printer.PrintFormatter = textFormatter; - printer.ShowsPageRange = true; - printer.Present(true, (handler, completed, error) => - { - if (!completed && error != null) - { - Console.WriteLine($"Error: {error.LocalizedDescription ?? ""}"); - } - }); + var printer = UIPrintInteractionController.SharedPrintController; + printer.PrintInfo = printInfo; + printer.PrintFormatter = textFormatter; + printer.ShowsPageRange = true; + printer.Present (true, (handler, completed, error) => { + if (!completed && error != null) { + Console.WriteLine ($"Error: {error.LocalizedDescription ?? ""}"); + } + }); - printInfo.Dispose(); - textFormatter.Dispose(); - } - } -} \ No newline at end of file + printInfo.Dispose (); + textFormatter.Dispose (); + } + } +} diff --git a/PrivacyPrompts/PrivacyPrompts/AppDelegate.cs b/PrivacyPrompts/PrivacyPrompts/AppDelegate.cs index bf8d1a090..bb72a770e 100644 --- a/PrivacyPrompts/PrivacyPrompts/AppDelegate.cs +++ b/PrivacyPrompts/PrivacyPrompts/AppDelegate.cs @@ -15,7 +15,7 @@ public override UIWindow Window { set; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } @@ -23,7 +23,7 @@ static void Main (string[] args) public override void DidRegisterUserNotificationSettings (UIApplication application, UIUserNotificationSettings notificationSettings) { var handler = NotificationsRegistered; - if(handler != null) + if (handler != null) handler (notificationSettings); } } diff --git a/PrivacyPrompts/PrivacyPrompts/Controllers/LocationPrivacyViewController.cs b/PrivacyPrompts/PrivacyPrompts/Controllers/LocationPrivacyViewController.cs index 4327ae486..77ba873c5 100644 --- a/PrivacyPrompts/PrivacyPrompts/Controllers/LocationPrivacyViewController.cs +++ b/PrivacyPrompts/PrivacyPrompts/Controllers/LocationPrivacyViewController.cs @@ -5,14 +5,12 @@ using MapKit; using CoreLocation; -namespace PrivacyPrompts -{ - public partial class LocationPrivacyViewController : UIViewController - { +namespace PrivacyPrompts { + public partial class LocationPrivacyViewController : UIViewController { public LocationPrivacyManager PrivacyManager { get; set; } - public LocationPrivacyViewController(IntPtr handle) - : base(handle) + public LocationPrivacyViewController (IntPtr handle) + : base (handle) { } @@ -55,4 +53,4 @@ async void RequestAccessButtonClicked (object sender, EventArgs e) accessStatus.Text = PrivacyManager.CheckAccess (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/Controllers/MotionPrivacyController.cs b/PrivacyPrompts/PrivacyPrompts/Controllers/MotionPrivacyController.cs index 9d968683b..1bfedd088 100644 --- a/PrivacyPrompts/PrivacyPrompts/Controllers/MotionPrivacyController.cs +++ b/PrivacyPrompts/PrivacyPrompts/Controllers/MotionPrivacyController.cs @@ -2,16 +2,14 @@ using UIKit; -namespace PrivacyPrompts -{ +namespace PrivacyPrompts { /// <summary> /// Note: Accessing motion activity requires your project to have an entitlements.plist file /// There is no API that allows you to directly check for access. Instead, you have to use /// the technique illustrated here: perform a query and check for an error of type /// CMError.MotionActivityNotAuthorized /// </summary> - public partial class MotionPrivacyController : UIViewController - { + public partial class MotionPrivacyController : UIViewController { public MotionPrivacyManager PrivacyManager { get; set; } public MotionPrivacyController (IntPtr handle) @@ -40,4 +38,4 @@ async void RequestAccessButtonClicked (object sender, EventArgs e) StepsLbl.Text = PrivacyManager.GetCountsInfo (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyClassesTableViewController.cs b/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyClassesTableViewController.cs index 6c871e236..aba50af4c 100644 --- a/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyClassesTableViewController.cs +++ b/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyClassesTableViewController.cs @@ -6,10 +6,8 @@ using EventKit; using Accounts; -namespace PrivacyPrompts -{ - public partial class PrivacyClassesTableViewController : UITableViewController - { +namespace PrivacyPrompts { + public partial class PrivacyClassesTableViewController : UITableViewController { const string LocationSegueId = "LocationSegue"; const string MotionSegueId = "MotionSegue"; const string DefaultSegueId = "DefaultSegue"; @@ -63,11 +61,11 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) vc.Title = currentSelection.ToString (); if (segue.Identifier == DefaultSegueId) - Setup ((PrivacyDetailViewController)vc, currentSelection); + Setup ((PrivacyDetailViewController) vc, currentSelection); else if (segue.Identifier == MotionSegueId) - Setup ((MotionPrivacyController)vc); + Setup ((MotionPrivacyController) vc); else if (segue.Identifier == LocationSegueId) - Setup ((LocationPrivacyViewController)vc); + Setup ((LocationPrivacyViewController) vc); else base.PrepareForSegue (segue, sender); } @@ -79,121 +77,121 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) PerformSegue (segueId, this); } - DataClass GetDataClass(NSIndexPath indexPath) + DataClass GetDataClass (NSIndexPath indexPath) { return availableItems [indexPath.Row]; } - string GetSegueIdFor(DataClass type) + string GetSegueIdFor (DataClass type) { switch (type) { - case DataClass.Location: - return LocationSegueId; - - case DataClass.Motion: - return MotionSegueId; - - case DataClass.Advertising: - case DataClass.AppleMusic: - case DataClass.Bluetooth: - case DataClass.Calendars: - case DataClass.Contacts: - case DataClass.Facebook: - case DataClass.Microphone: - case DataClass.Notifications: - case DataClass.Photos: - case DataClass.Reminders: - case DataClass.SinaWeibo: - case DataClass.SpeechRecognition: - case DataClass.TencentWeibo: - case DataClass.Twitter: - case DataClass.Video: - return DefaultSegueId; - - default: - throw new NotImplementedException (); + case DataClass.Location: + return LocationSegueId; + + case DataClass.Motion: + return MotionSegueId; + + case DataClass.Advertising: + case DataClass.AppleMusic: + case DataClass.Bluetooth: + case DataClass.Calendars: + case DataClass.Contacts: + case DataClass.Facebook: + case DataClass.Microphone: + case DataClass.Notifications: + case DataClass.Photos: + case DataClass.Reminders: + case DataClass.SinaWeibo: + case DataClass.SpeechRecognition: + case DataClass.TencentWeibo: + case DataClass.Twitter: + case DataClass.Video: + return DefaultSegueId; + + default: + throw new NotImplementedException (); } } - void Setup(PrivacyDetailViewController vc, DataClass type) + void Setup (PrivacyDetailViewController vc, DataClass type) { IPrivacyManager manager = null; switch (type) { - case DataClass.Reminders: - manager = new EKEntityPrivacyManager (EKEntityType.Reminder); - break; + case DataClass.Reminders: + manager = new EKEntityPrivacyManager (EKEntityType.Reminder); + break; - case DataClass.Calendars: - manager = new EKEntityPrivacyManager (EKEntityType.Event); - break; + case DataClass.Calendars: + manager = new EKEntityPrivacyManager (EKEntityType.Event); + break; - case DataClass.Facebook: - manager = new SocialNetworkPrivacyManager (ACAccountType.Facebook); - break; + case DataClass.Facebook: + manager = new SocialNetworkPrivacyManager (ACAccountType.Facebook); + break; - case DataClass.Twitter: - manager = new SocialNetworkPrivacyManager (ACAccountType.Twitter); - break; + case DataClass.Twitter: + manager = new SocialNetworkPrivacyManager (ACAccountType.Twitter); + break; - case DataClass.SinaWeibo: - manager = new SocialNetworkPrivacyManager (ACAccountType.SinaWeibo); - break; + case DataClass.SinaWeibo: + manager = new SocialNetworkPrivacyManager (ACAccountType.SinaWeibo); + break; - case DataClass.TencentWeibo: - manager = new SocialNetworkPrivacyManager (ACAccountType.TencentWeibo); - break; + case DataClass.TencentWeibo: + manager = new SocialNetworkPrivacyManager (ACAccountType.TencentWeibo); + break; - case DataClass.Notifications: - manager = new NotificationsPrivacyManager ((AppDelegate)UIApplication.SharedApplication.Delegate); - break; + case DataClass.Notifications: + manager = new NotificationsPrivacyManager ((AppDelegate) UIApplication.SharedApplication.Delegate); + break; - case DataClass.Contacts: - manager = new AddressBookPrivacyManager (); - break; + case DataClass.Contacts: + manager = new AddressBookPrivacyManager (); + break; - case DataClass.Photos: - manager = new PhotoPrivacyManager (); - break; + case DataClass.Photos: + manager = new PhotoPrivacyManager (); + break; - case DataClass.Video: - manager = new VideoCapturePrivacyManager (); - break; + case DataClass.Video: + manager = new VideoCapturePrivacyManager (); + break; - case DataClass.Microphone: - manager = new MicrophonePrivacyManager (); - break; + case DataClass.Microphone: + manager = new MicrophonePrivacyManager (); + break; - case DataClass.Bluetooth: - manager = new BluetoothPrivacyManager (); - break; + case DataClass.Bluetooth: + manager = new BluetoothPrivacyManager (); + break; - case DataClass.Advertising: - manager = new AdvertisingPrivacyManager (); - break; + case DataClass.Advertising: + manager = new AdvertisingPrivacyManager (); + break; - case DataClass.AppleMusic: - manager = new AppleMusicPrivacyManager(); - break; + case DataClass.AppleMusic: + manager = new AppleMusicPrivacyManager (); + break; - case DataClass.SpeechRecognition: - manager = new SpeechRecognitionPrivacyManager(); - break; + case DataClass.SpeechRecognition: + manager = new SpeechRecognitionPrivacyManager (); + break; - default: - throw new NotImplementedException (); + default: + throw new NotImplementedException (); } vc.PrivacyManager = manager; } - void Setup(MotionPrivacyController vc) + void Setup (MotionPrivacyController vc) { vc.PrivacyManager = new MotionPrivacyManager (); } - void Setup(LocationPrivacyViewController vc) + void Setup (LocationPrivacyViewController vc) { vc.PrivacyManager = new LocationPrivacyManager (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyDetailViewController.cs b/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyDetailViewController.cs index 7c5a15570..5dded5c71 100644 --- a/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyDetailViewController.cs +++ b/PrivacyPrompts/PrivacyPrompts/Controllers/PrivacyDetailViewController.cs @@ -2,19 +2,17 @@ using UIKit; -namespace PrivacyPrompts -{ - public partial class PrivacyDetailViewController : UIViewController - { +namespace PrivacyPrompts { + public partial class PrivacyDetailViewController : UIViewController { // Dependency Injection via property public IPrivacyManager PrivacyManager { get; set; } - public PrivacyDetailViewController(IntPtr handle) - : base(handle) + public PrivacyDetailViewController (IntPtr handle) + : base (handle) { } - public PrivacyDetailViewController() + public PrivacyDetailViewController () { throw new InvalidProgramException (); } @@ -38,4 +36,4 @@ async void RequestAccessButtonClicked (object sender, EventArgs e) accessStatus.Text = PrivacyManager.CheckAccess (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/DataClass.cs b/PrivacyPrompts/PrivacyPrompts/DataClass.cs index ffaa52903..a8bbfefaf 100644 --- a/PrivacyPrompts/PrivacyPrompts/DataClass.cs +++ b/PrivacyPrompts/PrivacyPrompts/DataClass.cs @@ -1,9 +1,8 @@ using System; -namespace PrivacyPrompts -{ +namespace PrivacyPrompts { public enum DataClass { - + Advertising, AppleMusic, Bluetooth, @@ -25,4 +24,4 @@ public enum DataClass { // iOS8 Notifications, } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AddressBookPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AddressBookPrivacyManager.cs index 8c096309a..65240179c 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AddressBookPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AddressBookPrivacyManager.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using AddressBook; using Foundation; -namespace PrivacyPrompts -{ - public class AddressBookPrivacyManager : IPrivacyManager, IDisposable - { +namespace PrivacyPrompts { + public class AddressBookPrivacyManager : IPrivacyManager, IDisposable { ABAddressBook addressBook; public AddressBookPrivacyManager () @@ -18,7 +16,7 @@ public AddressBookPrivacyManager () public Task RequestAccess () { if (addressBook == null) - return Task.FromResult<object>(null); + return Task.FromResult<object> (null); var tcs = new TaskCompletionSource<object> (); addressBook.RequestAccess ((granted, accessError) => tcs.SetResult (null)); diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AdvertisingPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AdvertisingPrivacyManager.cs index 3d360100f..47127df74 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AdvertisingPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AdvertisingPrivacyManager.cs @@ -1,11 +1,9 @@ -using System; +using System; using System.Threading.Tasks; using AdSupport; -namespace PrivacyPrompts -{ - public class AdvertisingPrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class AdvertisingPrivacyManager : IPrivacyManager { public Task RequestAccess () { return Task.FromResult<object> (null); diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AppleMusicPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AppleMusicPrivacyManager.cs index 3075c33e9..9657ce979 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AppleMusicPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/AppleMusicPrivacyManager.cs @@ -1,28 +1,26 @@ -using System; +using System; using System.Diagnostics.Contracts; using System.Threading.Tasks; using Foundation; using StoreKit; -namespace PrivacyPrompts -{ - public class AppleMusicPrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class AppleMusicPrivacyManager : IPrivacyManager { - public Task RequestAccess() - { - var tcs = new TaskCompletionSource<object>(); + public Task RequestAccess () + { + var tcs = new TaskCompletionSource<object> (); - SKCloudServiceController.RequestAuthorization(_ => { - tcs.SetResult(null); + SKCloudServiceController.RequestAuthorization (_ => { + tcs.SetResult (null); }); return tcs.Task; } - public string CheckAccess() + public string CheckAccess () { - return SKCloudServiceController.AuthorizationStatus.ToString(); + return SKCloudServiceController.AuthorizationStatus.ToString (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/BluetoothPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/BluetoothPrivacyManager.cs index f807cc01e..ec02724a0 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/BluetoothPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/BluetoothPrivacyManager.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CoreBluetooth; using UIKit; -namespace PrivacyPrompts -{ - public class BluetoothPrivacyManager : IPrivacyManager, IDisposable - { +namespace PrivacyPrompts { + public class BluetoothPrivacyManager : IPrivacyManager, IDisposable { readonly CBCentralManager cbManager = new CBCentralManager (); public Task RequestAccess () @@ -27,4 +25,4 @@ public void Dispose () cbManager.Dispose (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/EKEntityPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/EKEntityPrivacyManager.cs index 2cf427d4c..15a73a5cd 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/EKEntityPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/EKEntityPrivacyManager.cs @@ -1,14 +1,12 @@ -using System; +using System; using EventKit; using Foundation; using System.Threading.Tasks; -namespace PrivacyPrompts -{ - public class EKEntityPrivacyManager : IPrivacyManager, IDisposable - { +namespace PrivacyPrompts { + public class EKEntityPrivacyManager : IPrivacyManager, IDisposable { readonly EKEntityType type; - readonly EKEventStore eventStore = new EKEventStore(); + readonly EKEventStore eventStore = new EKEventStore (); public EKEntityPrivacyManager (EKEntityType entityType) { @@ -33,4 +31,4 @@ public void Dispose () eventStore.Dispose (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/IPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/IPrivacyManager.cs index 9eced012b..45b3607cf 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/IPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/IPrivacyManager.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; -namespace PrivacyPrompts -{ - public interface IPrivacyManager - { - Task RequestAccess(); - string CheckAccess(); +namespace PrivacyPrompts { + public interface IPrivacyManager { + Task RequestAccess (); + string CheckAccess (); } } diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/LocationPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/LocationPrivacyManager.cs index bde8573ba..bf994d538 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/LocationPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/LocationPrivacyManager.cs @@ -1,13 +1,11 @@ -using System; +using System; using CoreLocation; using Foundation; using MapKit; using System.Threading.Tasks; -namespace PrivacyPrompts -{ - public class LocationPrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class LocationPrivacyManager : IPrivacyManager { public event EventHandler LocationChanged; readonly CLLocationManager locationManager; @@ -24,7 +22,7 @@ public CLLocationManager LocationManager { public string LocationInfo { get { - return LocationManager.Location.ToString(); + return LocationManager.Location.ToString (); } } @@ -34,7 +32,7 @@ public LocationPrivacyManager () // If previously allowed, start location manager if (CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse) - locationManager.StartUpdatingLocation(); + locationManager.StartUpdatingLocation (); locationManager.Failed += OnFailed; locationManager.LocationsUpdated += OnLocationsUpdated; @@ -48,7 +46,7 @@ void OnFailed (object sender, NSErrorEventArgs e) void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e) { - Region = new MKCoordinateRegion(LocationManager.Location.Coordinate, new MKCoordinateSpan(0.1, 0.1)); + Region = new MKCoordinateRegion (LocationManager.Location.Coordinate, new MKCoordinateSpan (0.1, 0.1)); var handler = LocationChanged; if (handler != null) @@ -60,7 +58,7 @@ void OnAuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e) if (e.Status == CLAuthorizationStatus.AuthorizedWhenInUse) LocationManager.StartUpdatingLocation (); - if(tcs != null) + if (tcs != null) tcs.SetResult (null); } @@ -90,4 +88,4 @@ public void Dispose () locationManager.Dispose (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MicrophonePrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MicrophonePrivacyManager.cs index 2a36c62a6..2781b416e 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MicrophonePrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MicrophonePrivacyManager.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Threading.Tasks; using AVFoundation; using Foundation; using UIKit; -namespace PrivacyPrompts -{ - public class MicrophonePrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class MicrophonePrivacyManager : IPrivacyManager { string micAccessText = "Not determined"; public Task RequestAccess () @@ -16,8 +14,8 @@ public Task RequestAccess () AVAudioSession audioSession = AVAudioSession.SharedInstance (); audioSession.RequestRecordPermission (granted => { - micAccessText = GetTextStatus(granted); - tcs.SetResult(null); + micAccessText = GetTextStatus (granted); + tcs.SetResult (null); }); return tcs.Task; @@ -36,9 +34,9 @@ public string CheckAccess () return micAccessText; } - static string GetTextStatus(bool granted) + static string GetTextStatus (bool granted) { return string.Format ("Access {0}", granted ? "allowed" : "denied"); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MotionPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MotionPrivacyManager.cs index 69597ba48..0cb26f3fc 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MotionPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/MotionPrivacyManager.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Threading.Tasks; using CoreMotion; using Foundation; using UIKit; -namespace PrivacyPrompts -{ - public class MotionPrivacyManager : IPrivacyManager, IDisposable - { +namespace PrivacyPrompts { + public class MotionPrivacyManager : IPrivacyManager, IDisposable { CMStepCounter stepCounter; string motionStatus = "Indeterminate"; nint steps = 0; @@ -33,7 +31,7 @@ public Task RequestAccess () var yesterday = NSDate.FromTimeIntervalSinceNow (-60 * 60 * 24); if (UIDevice.CurrentDevice.CheckSystemVersion (8, 0)) { - if(!CMPedometer.IsStepCountingAvailable) + if (!CMPedometer.IsStepCountingAvailable) return Task.FromResult<object> (null); return pedometer.QueryPedometerDataAsync (yesterday, NSDate.Now) @@ -48,11 +46,11 @@ public Task RequestAccess () } - void PedometrQueryContinuation(Task<CMPedometerData> t) + void PedometrQueryContinuation (Task<CMPedometerData> t) { if (t.IsFaulted) { - var code = ((NSErrorException)t.Exception.InnerException).Code; - if (code == (int)CMError.MotionActivityNotAuthorized) + var code = ((NSErrorException) t.Exception.InnerException).Code; + if (code == (int) CMError.MotionActivityNotAuthorized) motionStatus = "Not Authorized"; return; } @@ -60,11 +58,11 @@ void PedometrQueryContinuation(Task<CMPedometerData> t) steps = t.Result.NumberOfSteps.NIntValue; } - void StepQueryContinuation(Task<nint> t) + void StepQueryContinuation (Task<nint> t) { if (t.IsFaulted) { - var code = ((NSErrorException)t.Exception.InnerException).Code; - if (code == (int)CMError.MotionActivityNotAuthorized) + var code = ((NSErrorException) t.Exception.InnerException).Code; + if (code == (int) CMError.MotionActivityNotAuthorized) motionStatus = "Not Authorized"; return; } @@ -77,7 +75,7 @@ public string CheckAccess () return motionStatus; } - public string GetCountsInfo() + public string GetCountsInfo () { return steps > 0 ? string.Format ("You have taken {0} steps in the past 24 hours", steps) : string.Empty; } @@ -88,4 +86,4 @@ public void Dispose () stepCounter.Dispose (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/NotificationsPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/NotificationsPrivacyManager.cs index 311be9081..3de8e131d 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/NotificationsPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/NotificationsPrivacyManager.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; using System.Threading.Tasks; -namespace PrivacyPrompts -{ - public class NotificationsPrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class NotificationsPrivacyManager : IPrivacyManager { readonly AppDelegate applicationDelegate; TaskCompletionSource<object> tcs; @@ -22,7 +20,7 @@ public NotificationsPrivacyManager (AppDelegate appDelegate) // After the user interacts with the permissions dialog, AppDelegate.DidRegisterUserNotificationSettings // is called. In this example, we've hooked that up to an event - applicationDelegate.NotificationsRegistered += (obj) => tcs.SetResult(null); + applicationDelegate.NotificationsRegistered += (obj) => tcs.SetResult (null); } public Task RequestAccess () @@ -48,4 +46,4 @@ public string CheckAccess () return string.Format ("Allowed types: {0}", NotificationTypes); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/PhotoPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/PhotoPrivacyManager.cs index 198256ccd..de99f2519 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/PhotoPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/PhotoPrivacyManager.cs @@ -1,11 +1,9 @@ -using System; +using System; using System.Threading.Tasks; using Photos; -namespace PrivacyPrompts -{ - public class PhotoPrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class PhotoPrivacyManager : IPrivacyManager { public Task RequestAccess () { var tcs = new TaskCompletionSource<object> (); diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SimplePrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SimplePrivacyManager.cs index 284dbc5e8..25d3b5813 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SimplePrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SimplePrivacyManager.cs @@ -1,10 +1,8 @@ -using System; +using System; using System.Threading.Tasks; -namespace PrivacyPrompts -{ - public class SimplePrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class SimplePrivacyManager : IPrivacyManager { public Task RequestAccess () { return Task.FromResult<object> (true); diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SocialNetworkPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SocialNetworkPrivacyManager.cs index e60290321..b20b44a1e 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SocialNetworkPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SocialNetworkPrivacyManager.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Threading.Tasks; using Accounts; using Foundation; -namespace PrivacyPrompts -{ - public class SocialNetworkPrivacyManager : IPrivacyManager, IDisposable - { +namespace PrivacyPrompts { + public class SocialNetworkPrivacyManager : IPrivacyManager, IDisposable { readonly ACAccountStore accountStore; readonly NSString socialNetwork; @@ -23,11 +21,11 @@ public Task RequestAccess () ACAccountType account = accountStore.FindAccountType (socialNetwork); var tcs = new TaskCompletionSource<object> (); - accountStore.RequestAccess (account, options, (granted, error) => tcs.SetResult(null)); + accountStore.RequestAccess (account, options, (granted, error) => tcs.SetResult (null)); return tcs.Task; } - AccountStoreOptions GetOptions() + AccountStoreOptions GetOptions () { if (socialNetwork == ACAccountType.Facebook) return GetFacebookOptions (); @@ -38,7 +36,7 @@ AccountStoreOptions GetOptions() return null; } - AccountStoreOptions GetFacebookOptions() + AccountStoreOptions GetFacebookOptions () { AccountStoreOptions options = new AccountStoreOptions () { FacebookAppId = "MY_CODE" }; options.SetPermissions (ACFacebookAudience.Friends, new [] { @@ -49,7 +47,7 @@ AccountStoreOptions GetFacebookOptions() return options; } - AccountStoreOptions GetTencentWeibo() + AccountStoreOptions GetTencentWeibo () { return new AccountStoreOptions { TencentWeiboAppId = "MY_ID" @@ -67,4 +65,4 @@ public void Dispose () accountStore.Dispose (); } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SpeechRecognitionPrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SpeechRecognitionPrivacyManager.cs index fbb5ea179..f41653281 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SpeechRecognitionPrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/SpeechRecognitionPrivacyManager.cs @@ -1,25 +1,23 @@ -using System; +using System; using System.Threading.Tasks; using Speech; -namespace PrivacyPrompts -{ - public class SpeechRecognitionPrivacyManager : IPrivacyManager - { - public string CheckAccess() +namespace PrivacyPrompts { + public class SpeechRecognitionPrivacyManager : IPrivacyManager { + public string CheckAccess () { - return SFSpeechRecognizer.AuthorizationStatus.ToString(); + return SFSpeechRecognizer.AuthorizationStatus.ToString (); } - public Task RequestAccess() + public Task RequestAccess () { - var tcs = new TaskCompletionSource<object>(); + var tcs = new TaskCompletionSource<object> (); - SFSpeechRecognizer.RequestAuthorization(_ => { - tcs.SetResult(null); + SFSpeechRecognizer.RequestAuthorization (_ => { + tcs.SetResult (null); }); return tcs.Task; } } -} \ No newline at end of file +} diff --git a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/VideoCapturePrivacyManager.cs b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/VideoCapturePrivacyManager.cs index b253e4804..c56648b3c 100644 --- a/PrivacyPrompts/PrivacyPrompts/PrivacyManager/VideoCapturePrivacyManager.cs +++ b/PrivacyPrompts/PrivacyPrompts/PrivacyManager/VideoCapturePrivacyManager.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using AVFoundation; -namespace PrivacyPrompts -{ - public class VideoCapturePrivacyManager : IPrivacyManager - { +namespace PrivacyPrompts { + public class VideoCapturePrivacyManager : IPrivacyManager { public Task RequestAccess () { return AVCaptureDevice.RequestAccessForMediaTypeAsync (AVMediaType.Video); @@ -17,4 +15,4 @@ public string CheckAccess () return AVCaptureDevice.GetAuthorizationStatus (AVMediaType.Video).ToString (); } } -} \ No newline at end of file +} diff --git a/Profiling/MemoryDemo/MemoryDemo/AppDelegate.cs b/Profiling/MemoryDemo/MemoryDemo/AppDelegate.cs index 17fcb96c9..62c429a74 100644 --- a/Profiling/MemoryDemo/MemoryDemo/AppDelegate.cs +++ b/Profiling/MemoryDemo/MemoryDemo/AppDelegate.cs @@ -25,4 +25,4 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } } -} \ No newline at end of file +} diff --git a/Profiling/MemoryDemo/MemoryDemo/Main.cs b/Profiling/MemoryDemo/MemoryDemo/Main.cs index 448fd8f34..6b40ad3fb 100644 --- a/Profiling/MemoryDemo/MemoryDemo/Main.cs +++ b/Profiling/MemoryDemo/MemoryDemo/Main.cs @@ -2,7 +2,7 @@ namespace MemoryDemo { public class Application { - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerAfter.cs b/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerAfter.cs index 0a831d269..6fa60ec86 100644 --- a/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerAfter.cs +++ b/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerAfter.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreGraphics; using Foundation; @@ -6,10 +6,8 @@ #if !GREEDY -namespace MemoryDemo -{ - public class MemoryDemoViewController : UICollectionViewController - { +namespace MemoryDemo { + public class MemoryDemoViewController : UICollectionViewController { // Id used for cell reuse public const string CellId = "ImageCell"; @@ -29,10 +27,10 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - CollectionView.RegisterClassForCell(typeof(ImageCell), CellId); + CollectionView.RegisterClassForCell (typeof (ImageCell), CellId); } - public override nint GetItemsCount(UICollectionView collectionView, nint section) + public override nint GetItemsCount (UICollectionView collectionView, nint section) { return 10000; } @@ -40,7 +38,7 @@ public override nint GetItemsCount(UICollectionView collectionView, nint section public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { // Dequeue a cell from the reuse pool - var imageCell = (ImageCell)collectionView.DequeueReusableCell(CellId, indexPath); + var imageCell = (ImageCell) collectionView.DequeueReusableCell (CellId, indexPath); // Reuse the image declared at the class level imageCell.ImageView.Image = image; @@ -49,14 +47,13 @@ public override UICollectionViewCell GetCell (UICollectionView collectionView, N } } - public class ImageCell : UICollectionViewCell - { + public class ImageCell : UICollectionViewCell { public UIImageView ImageView { get; private set; } [Export ("initWithFrame:")] public ImageCell (CGRect frame) : base (frame) { - ImageView = new UIImageView (new CGRect(0f, 0f, 50f, 50f)); + ImageView = new UIImageView (new CGRect (0f, 0f, 50f, 50f)); ImageView.ContentMode = UIViewContentMode.ScaleAspectFit; ContentView.AddSubview (ImageView); } diff --git a/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerBefore.cs b/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerBefore.cs index ad352f6fa..8027517ba 100644 --- a/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerBefore.cs +++ b/Profiling/MemoryDemo/MemoryDemo/MemoryDemoViewControllerBefore.cs @@ -76,4 +76,4 @@ public ImageCell (CGRect frame) : base (frame) } } -#endif // GREEDY \ No newline at end of file +#endif // GREEDY diff --git a/Protocols_Delegates_Events/Protocols_Delegates_Events/AppDelegate.cs b/Protocols_Delegates_Events/Protocols_Delegates_Events/AppDelegate.cs index 235d37568..fd07fa6a8 100644 --- a/Protocols_Delegates_Events/Protocols_Delegates_Events/AppDelegate.cs +++ b/Protocols_Delegates_Events/Protocols_Delegates_Events/AppDelegate.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace Protocols_Delegates_Events -{ +namespace Protocols_Delegates_Events { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/Protocols_Delegates_Events/Protocols_Delegates_Events/Main.cs b/Protocols_Delegates_Events/Protocols_Delegates_Events/Main.cs index e32ccf82c..ea13fe20f 100644 --- a/Protocols_Delegates_Events/Protocols_Delegates_Events/Main.cs +++ b/Protocols_Delegates_Events/Protocols_Delegates_Events/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace Protocols_Delegates_Events -{ - public class Application - { +namespace Protocols_Delegates_Events { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Protocols_Delegates_Events/Protocols_Delegates_Events/Protocols_Delegates_EventsViewController.cs b/Protocols_Delegates_Events/Protocols_Delegates_Events/Protocols_Delegates_EventsViewController.cs index 4a761fd97..6ad32e4eb 100644 --- a/Protocols_Delegates_Events/Protocols_Delegates_Events/Protocols_Delegates_EventsViewController.cs +++ b/Protocols_Delegates_Events/Protocols_Delegates_Events/Protocols_Delegates_EventsViewController.cs @@ -5,10 +5,8 @@ using MapKit; using UIKit; -namespace Protocols_Delegates_Events -{ - public partial class Protocols_Delegates_EventsViewController : UIViewController - { +namespace Protocols_Delegates_Events { + public partial class Protocols_Delegates_EventsViewController : UIViewController { #region Private Variables private SampleMapDelegate _mapDelegate; #endregion diff --git a/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapAnnotation.cs b/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapAnnotation.cs index 8f713d544..e76c1971b 100644 --- a/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapAnnotation.cs +++ b/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapAnnotation.cs @@ -2,22 +2,20 @@ using CoreLocation; using MapKit; -namespace Protocols_Delegates_Events -{ - /// <summary> - /// Annotation class that subclasses MKAnnotation abstract class - /// MKAnnotation is bound by MonoTouch to the MKAnnotation protocol - /// </summary> - public class SampleMapAnnotation : MKAnnotation - { +namespace Protocols_Delegates_Events { + /// <summary> + /// Annotation class that subclasses MKAnnotation abstract class + /// MKAnnotation is bound by MonoTouch to the MKAnnotation protocol + /// </summary> + public class SampleMapAnnotation : MKAnnotation { CLLocationCoordinate2D coordinate; - string _title; + string _title; - public SampleMapAnnotation (CLLocationCoordinate2D coordinateToSet) - { + public SampleMapAnnotation (CLLocationCoordinate2D coordinateToSet) + { coordinate = coordinateToSet; - _title = "Sample"; - } + _title = "Sample"; + } public override CLLocationCoordinate2D Coordinate { get { @@ -30,11 +28,11 @@ public override void SetCoordinate (CLLocationCoordinate2D coordinateToSet) coordinate = coordinateToSet; } - public override string Title { - get { - return _title; - } - } - } + public override string Title { + get { + return _title; + } + } + } } diff --git a/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapDelegate.cs b/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapDelegate.cs index 40132f898..734c72fcb 100644 --- a/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapDelegate.cs +++ b/Protocols_Delegates_Events/Protocols_Delegates_Events/SampleMapDelegate.cs @@ -5,10 +5,8 @@ using MapKit; using UIKit; -namespace Protocols_Delegates_Events -{ - class SampleMapDelegate : MKMapViewDelegate - { +namespace Protocols_Delegates_Events { + class SampleMapDelegate : MKMapViewDelegate { public override void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView annotationView) { var sampleAnnotation = annotationView.Annotation as SampleMapAnnotation; diff --git a/Protocols_Delegates_Events/Xib Solution/AppDelegate.cs b/Protocols_Delegates_Events/Xib Solution/AppDelegate.cs index 296900824..9df318ee8 100644 --- a/Protocols_Delegates_Events/Xib Solution/AppDelegate.cs +++ b/Protocols_Delegates_Events/Xib Solution/AppDelegate.cs @@ -4,35 +4,33 @@ using Foundation; using UIKit; -namespace Protocols_Delegates_Events -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; - Protocols_Delegates_EventsViewController viewController; +namespace Protocols_Delegates_Events { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; + Protocols_Delegates_EventsViewController viewController; - // - // This method is invoked when the application has loaded and is ready to run. In this - // method you should instantiate the window, load the UI into it and then make the window - // visible. - // - // You have 17 seconds to return from this method, or iOS will terminate your application. - // - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); - viewController = new Protocols_Delegates_EventsViewController ("Protocols_Delegates_EventsViewController", null); - window.RootViewController = viewController; - window.MakeKeyAndVisible (); + viewController = new Protocols_Delegates_EventsViewController ("Protocols_Delegates_EventsViewController", null); + window.RootViewController = viewController; + window.MakeKeyAndVisible (); - return true; - } - } + return true; + } + } } diff --git a/Protocols_Delegates_Events/Xib Solution/Main.cs b/Protocols_Delegates_Events/Xib Solution/Main.cs index 9fb5c2e15..791c572a2 100644 --- a/Protocols_Delegates_Events/Xib Solution/Main.cs +++ b/Protocols_Delegates_Events/Xib Solution/Main.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace Protocols_Delegates_Events -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace Protocols_Delegates_Events { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/Protocols_Delegates_Events/Xib Solution/Protocols_Delegates_EventsViewController.cs b/Protocols_Delegates_Events/Xib Solution/Protocols_Delegates_EventsViewController.cs index 6add9dc56..bedb4e63a 100644 --- a/Protocols_Delegates_Events/Xib Solution/Protocols_Delegates_EventsViewController.cs +++ b/Protocols_Delegates_Events/Xib Solution/Protocols_Delegates_EventsViewController.cs @@ -5,93 +5,90 @@ using MapKit; using UIKit; -namespace Protocols_Delegates_Events -{ - public partial class Protocols_Delegates_EventsViewController : UIViewController - { - SampleMapDelegate _mapDelegate; +namespace Protocols_Delegates_Events { + public partial class Protocols_Delegates_EventsViewController : UIViewController { + SampleMapDelegate _mapDelegate; - public Protocols_Delegates_EventsViewController (string nibName, NSBundle bundle) : base (nibName, bundle) - { - } + public Protocols_Delegates_EventsViewController (string nibName, NSBundle bundle) : base (nibName, bundle) + { + } - public override void DidReceiveMemoryWarning () - { - base.DidReceiveMemoryWarning (); - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + } - public override void ViewDidLoad () - { - base.ViewDidLoad (); + public override void ViewDidLoad () + { + base.ViewDidLoad (); // HINT: Select the commented example code blocks below and type Command + / to uncomment - //Exmaple 1 - Using Strongly typed delegate - //set the map's delegate -// _mapDelegate = new SampleMapDelegate (); -// map.Delegate = _mapDelegate; - - //Example 2 - Using weak delegate -// map.WeakDelegate = this; - - //Exmaple 3 - Using .NET event -// map.DidSelectAnnotationView += (s,e) => { -// -// var sampleAnnotation = e.View.Annotation as SampleMapAnnotation; -// -// if (sampleAnnotation != null) { -// -// //demo accessing the coordinate of the selected annotation to zoom in on it -// map.Region = MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500); -// -// //demo accessing the title of the selected annotation -// Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); -// } -// }; - - //an arbitrary coordinate used for demonstration here - var sampleCoordinate = new CLLocationCoordinate2D (42.3467512, -71.0969456); - - //center the map on the coordinate - map.SetCenterCoordinate (sampleCoordinate, false); - - //create an annotation and add it to the map - map.AddAnnotation (new SampleMapAnnotation (sampleCoordinate)); - } - - class SampleMapDelegate : MKMapViewDelegate - { - public override void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView annotationView) - { - var sampleAnnotation = annotationView.Annotation as SampleMapAnnotation; - - if (sampleAnnotation != null) { - - //demo accessing the coordinate of the selected annotation to zoom in on it - mapView.Region = MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500); - - //demo accessing the title of the selected annotation - Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); - } - - } - } - - //bind to the Objective-C selector mapView:didSelectAnnotationView: - [Export("mapView:didSelectAnnotationView:")] - public void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView annotationView) - { - var sampleAnnotation = annotationView.Annotation as SampleMapAnnotation; - - if (sampleAnnotation != null) { - - //demo accessing the coordinate of the selected annotation to zoom in on it - mapView.Region = MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500); - - //demo accessing the title of the selected annotation - Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); - } - } - - } + //Exmaple 1 - Using Strongly typed delegate + //set the map's delegate + // _mapDelegate = new SampleMapDelegate (); + // map.Delegate = _mapDelegate; + + //Example 2 - Using weak delegate + // map.WeakDelegate = this; + + //Exmaple 3 - Using .NET event + // map.DidSelectAnnotationView += (s,e) => { + // + // var sampleAnnotation = e.View.Annotation as SampleMapAnnotation; + // + // if (sampleAnnotation != null) { + // + // //demo accessing the coordinate of the selected annotation to zoom in on it + // map.Region = MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500); + // + // //demo accessing the title of the selected annotation + // Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); + // } + // }; + + //an arbitrary coordinate used for demonstration here + var sampleCoordinate = new CLLocationCoordinate2D (42.3467512, -71.0969456); + + //center the map on the coordinate + map.SetCenterCoordinate (sampleCoordinate, false); + + //create an annotation and add it to the map + map.AddAnnotation (new SampleMapAnnotation (sampleCoordinate)); + } + + class SampleMapDelegate : MKMapViewDelegate { + public override void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView annotationView) + { + var sampleAnnotation = annotationView.Annotation as SampleMapAnnotation; + + if (sampleAnnotation != null) { + + //demo accessing the coordinate of the selected annotation to zoom in on it + mapView.Region = MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500); + + //demo accessing the title of the selected annotation + Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); + } + + } + } + + //bind to the Objective-C selector mapView:didSelectAnnotationView: + [Export ("mapView:didSelectAnnotationView:")] + public void DidSelectAnnotationView (MKMapView mapView, MKAnnotationView annotationView) + { + var sampleAnnotation = annotationView.Annotation as SampleMapAnnotation; + + if (sampleAnnotation != null) { + + //demo accessing the coordinate of the selected annotation to zoom in on it + mapView.Region = MKCoordinateRegion.FromDistance (sampleAnnotation.Coordinate, 500, 500); + + //demo accessing the title of the selected annotation + Console.WriteLine ("{0} was tapped", sampleAnnotation.Title); + } + } + + } } diff --git a/Protocols_Delegates_Events/Xib Solution/SampleMapAnnotation.cs b/Protocols_Delegates_Events/Xib Solution/SampleMapAnnotation.cs index 4690b316c..eb589b6f7 100644 --- a/Protocols_Delegates_Events/Xib Solution/SampleMapAnnotation.cs +++ b/Protocols_Delegates_Events/Xib Solution/SampleMapAnnotation.cs @@ -2,14 +2,12 @@ using CoreLocation; using MapKit; -namespace Protocols_Delegates_Events -{ +namespace Protocols_Delegates_Events { /// <summary> /// Annotation class that subclasses MKAnnotation abstract class /// MKAnnotation is bound by MonoTouch to the MKAnnotation protocol /// </summary> - public class SampleMapAnnotation : MKAnnotation - { + public class SampleMapAnnotation : MKAnnotation { string _title; CLLocationCoordinate2D _coordinate; diff --git a/QRchestra/QRchestra/AppDelegate.cs b/QRchestra/QRchestra/AppDelegate.cs index 9f50f320b..ef0ea8ce9 100644 --- a/QRchestra/QRchestra/AppDelegate.cs +++ b/QRchestra/QRchestra/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace QRchestra -{ +namespace QRchestra { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; UIViewController mainController; diff --git a/QRchestra/QRchestra/Extensions.cs b/QRchestra/QRchestra/Extensions.cs index 8e563fc93..6459602a3 100644 --- a/QRchestra/QRchestra/Extensions.cs +++ b/QRchestra/QRchestra/Extensions.cs @@ -2,10 +2,8 @@ using Foundation; using System.Collections.Generic; -namespace QRchestra -{ - public static class Extensions - { +namespace QRchestra { + public static class Extensions { public static NSNumber ToNSNumber (this int num) { return NSNumber.FromInt32 (num); diff --git a/QRchestra/QRchestra/Main.cs b/QRchestra/QRchestra/Main.cs index f7e84c73c..e17bdf271 100644 --- a/QRchestra/QRchestra/Main.cs +++ b/QRchestra/QRchestra/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace QRchestra -{ - public class Application - { +namespace QRchestra { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/QRchestra/QRchestra/ReceiveViewController.cs b/QRchestra/QRchestra/ReceiveViewController.cs index 3d1f7942c..131170f0d 100644 --- a/QRchestra/QRchestra/ReceiveViewController.cs +++ b/QRchestra/QRchestra/ReceiveViewController.cs @@ -9,10 +9,8 @@ using ObjCRuntime; using System.Threading; -namespace QRchestra -{ - public partial class ReceiveViewController : UIViewController - { +namespace QRchestra { + public partial class ReceiveViewController : UIViewController { int barcodeIndex; AVCaptureVideoPreviewLayer previewLayer; @@ -20,9 +18,9 @@ public partial class ReceiveViewController : UIViewController SessionManager sessionManager; Synth synth; NSTimer barcodeTimer; - #pragma warning disable 414 +#pragma warning disable 414 NSTimer stepTimer; // the sample requries this timer to run! - #pragma warning restore 414 +#pragma warning restore 414 public UIColor OverlayColor { get { @@ -30,7 +28,7 @@ public UIColor OverlayColor { } } - CGPath createPathForPoints (CGPoint[] points) + CGPath createPathForPoints (CGPoint [] points) { CGPath path = new CGPath (); CGPoint point; @@ -132,7 +130,7 @@ void resetFocusAndExposure () } // called from ViewDidLoad in a timer loop - [Export("step:")] + [Export ("step:")] void step (NSTimer timer) { if (sessionManager.Barcodes == null || sessionManager.Barcodes.Count < 1) @@ -140,13 +138,13 @@ void step (NSTimer timer) lock (sessionManager) { barcodeIndex = (barcodeIndex + 1) % sessionManager.Barcodes.Count; - var barcode = (AVMetadataMachineReadableCodeObject)sessionManager.Barcodes [barcodeIndex]; + var barcode = (AVMetadataMachineReadableCodeObject) sessionManager.Barcodes [barcodeIndex]; if (barcodeTimer != null) barcodeTimer.Invalidate (); barcodeTimer = NSTimer.CreateScheduledTimer (0.5, this, new Selector ("removeDetectedBarcodeUI"), null, false); var transformedBarcode = - (AVMetadataMachineReadableCodeObject)previewLayer.GetTransformedMetadataObject (barcode); + (AVMetadataMachineReadableCodeObject) previewLayer.GetTransformedMetadataObject (barcode); CGPath barcodeBoundary = createPathForPoints (transformedBarcode.Corners); CATransaction.Begin (); @@ -172,7 +170,7 @@ void step (NSTimer timer) } } - [Export("removeDetectedBarcodeUI")] + [Export ("removeDetectedBarcodeUI")] void removeDetectedBarcodeUI () { removeAllSublayersFromLayer (barcodeTargetLayer); diff --git a/QRchestra/QRchestra/SendViewController.cs b/QRchestra/QRchestra/SendViewController.cs index bd8822a8c..34c52052e 100644 --- a/QRchestra/QRchestra/SendViewController.cs +++ b/QRchestra/QRchestra/SendViewController.cs @@ -6,15 +6,13 @@ using CoreImage; using CoreGraphics; -namespace QRchestra -{ - public partial class SendViewController : UIViewController - { +namespace QRchestra { + public partial class SendViewController : UIViewController { public Action<SendViewController> Finished; - string[] mainBank = new [] { "67", "71", "74", "80" }; - string[] altBank = new [] { "60", "64", "67", "72" }; - int[] currentBank = new [] { 0, 0, 0, 0 }; + string [] mainBank = new [] { "67", "71", "74", "80" }; + string [] altBank = new [] { "60", "64", "67", "72" }; + int [] currentBank = new [] { 0, 0, 0, 0 }; const int maxNumberOfBanks = 3; List<UIImageView> keyImageViews; @@ -67,9 +65,9 @@ UIImage machineReadableCodeFromMessage (string message) { var mrcFilter = CIFilter.FromName ("CIQRCodeGenerator"); NSData messageData = NSData.FromString (new NSString (message), NSStringEncoding.UTF8); - mrcFilter.SetValueForKey (messageData, (NSString)"inputMessage"); + mrcFilter.SetValueForKey (messageData, (NSString) "inputMessage"); - var barcodeCIImage = (CIImage)mrcFilter.ValueForKey ((NSString)"outputImage"); + var barcodeCIImage = (CIImage) mrcFilter.ValueForKey ((NSString) "outputImage"); CGRect extent = barcodeCIImage.Extent; CGImage barcodeCGImage = CIContext.CreateCGImage (barcodeCIImage, extent); @@ -96,7 +94,7 @@ partial void handleTap (UITapGestureRecognizer tapGestureRecognizer) if (!(tapGestureRecognizer.View is UIImageView)) return; - var keyImageView = (UIImageView)tapGestureRecognizer.View; + var keyImageView = (UIImageView) tapGestureRecognizer.View; int keyIndex = keyImageViews.IndexOf (keyImageView); if (keyIndex < 0) diff --git a/QRchestra/QRchestra/SessionManager.cs b/QRchestra/QRchestra/SessionManager.cs index bb0e4b06d..50abf8091 100644 --- a/QRchestra/QRchestra/SessionManager.cs +++ b/QRchestra/QRchestra/SessionManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using AVFoundation; using Foundation; using System.Collections.Generic; @@ -7,10 +7,8 @@ using System.Linq; using CoreGraphics; -namespace QRchestra -{ - public class SessionManager : NSObject - { +namespace QRchestra { + public class SessionManager : NSObject { public Action<SessionManager, NSError> StoppedRunning; public AVCaptureSession CaptureSession { get; set; } @@ -40,7 +38,8 @@ public SessionManager () public void StartRunning () { - sessionQueue.DispatchSync (delegate { + sessionQueue.DispatchSync (delegate + { try { setupCaptureSession (); CaptureSession.StartRunning (); @@ -54,7 +53,8 @@ public void StartRunning () public void StopRunning () { - sessionQueue.DispatchSync (delegate { + sessionQueue.DispatchSync (delegate + { running = false; CaptureSession.StopRunning (); @@ -76,10 +76,11 @@ void setupCaptureSession () applicationWillEnterForegroundNotificationObserver = NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillEnterForegroundNotification.ToString (), - UIApplication.SharedApplication, - NSOperationQueue.CurrentQueue, delegate(NSNotification notification) { - applicationWillEnterForeground (); - }); + UIApplication.SharedApplication, + NSOperationQueue.CurrentQueue, delegate (NSNotification notification) + { + applicationWillEnterForeground (); + }); videoDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); @@ -111,10 +112,11 @@ void teardownCaptureSession () } } - [Export("captureSessionNotification:")] - void captureSessionNotification (NSNotification notification) + [Export ("captureSessionNotification:")] + void captureSessionNotification (NSNotification notification) { - sessionQueue.DispatchAsync (delegate { + sessionQueue.DispatchAsync (delegate + { if (notification.Name == AVCaptureSession.WasInterruptedNotification.ToString ()) { Console.WriteLine ("Session interrupted"); @@ -124,10 +126,10 @@ void captureSessionNotification (NSNotification notification) else if (notification.Name == AVCaptureSession.RuntimeErrorNotification.ToString ()) { captureSessionStoppedRunning (); - NSError error = (NSError)notification.UserInfo [AVCaptureSession.ErrorKey]; - if (error.Code == (int)AVError.DeviceIsNotAvailableInBackground) { + NSError error = (NSError) notification.UserInfo [AVCaptureSession.ErrorKey]; + if (error.Code == (int) AVError.DeviceIsNotAvailableInBackground) { Console.WriteLine ("Device not available in background"); - } else if (error.Code == (int)AVError.MediaServicesWereReset) + } else if (error.Code == (int) AVError.MediaServicesWereReset) Console.WriteLine ("Media services were reset"); else handleNonRecoverableCaptureSessionRuntimeError (error); @@ -146,7 +148,8 @@ void handleNonRecoverableCaptureSessionRuntimeError (NSError error) teardownCaptureSession (); if (StoppedRunning != null) - delegateCallbackQueue.DispatchAsync (delegate { + delegateCallbackQueue.DispatchAsync (delegate + { StoppedRunning (this, error); }); } @@ -158,7 +161,8 @@ void captureSessionStoppedRunning () void applicationWillEnterForeground () { - sessionQueue.DispatchSync (delegate { + sessionQueue.DispatchSync (delegate + { if (running) CaptureSession.StartRunning (); }); @@ -171,9 +175,10 @@ void teardownVideoPipeline () void videoPipelineWillStartRunning () { - pipelineRunningTask = UIApplication.SharedApplication.BeginBackgroundTask (delegate { + pipelineRunningTask = UIApplication.SharedApplication.BeginBackgroundTask (delegate + { Console.WriteLine ("Video capture pipeline background task expired"); - UIApplication.SharedApplication.EndBackgroundTask(pipelineRunningTask); + UIApplication.SharedApplication.EndBackgroundTask (pipelineRunningTask); }); } @@ -184,8 +189,8 @@ void videoPipelineFinishedRunning () } public void DidOutputMetadataObjects (AVCaptureOutput captureOutput, - AVMetadataObject[] metadataObjects, - AVCaptureConnection connection) + AVMetadataObject [] metadataObjects, + AVCaptureConnection connection) { Barcodes = metadataObjects.ToList (); } @@ -289,11 +294,10 @@ public void Expose (CGPoint point) } } - class MetadataObjectsDelegate : AVCaptureMetadataOutputObjectsDelegate - { - public Action<AVCaptureMetadataOutput, AVMetadataObject[], AVCaptureConnection> DidOutputMetadataObjectsAction; + class MetadataObjectsDelegate : AVCaptureMetadataOutputObjectsDelegate { + public Action<AVCaptureMetadataOutput, AVMetadataObject [], AVCaptureConnection> DidOutputMetadataObjectsAction; - public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection) + public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject [] metadataObjects, AVCaptureConnection connection) { if (DidOutputMetadataObjectsAction != null) DidOutputMetadataObjectsAction (captureOutput, metadataObjects, connection); diff --git a/QRchestra/QRchestra/Synth.cs b/QRchestra/QRchestra/Synth.cs index 15c638acb..ac39c00b0 100644 --- a/QRchestra/QRchestra/Synth.cs +++ b/QRchestra/QRchestra/Synth.cs @@ -7,10 +7,8 @@ using CoreMidi; using AudioToolbox; -namespace QRchestra -{ - public class Synth : UIViewController - { +namespace QRchestra { + public class Synth : UIViewController { enum MIDIMessage { NoteOn = 0x9, NoteOff = 0x8 @@ -49,12 +47,12 @@ bool createAUGraph () processingGraph = new AUGraph (); cd.ComponentType = AudioComponentType.MusicDevice; - cd.ComponentSubType = (int)AudioTypeMusicDevice.Sampler; //0x73616d70; + cd.ComponentSubType = (int) AudioTypeMusicDevice.Sampler; //0x73616d70; samplerNode = processingGraph.AddNode (cd); cd.ComponentType = AudioComponentType.Output; - cd.ComponentSubType = (int)AudioTypeOutput.Remote; //0x72696f63; + cd.ComponentSubType = (int) AudioTypeOutput.Remote; //0x72696f63; ioNode = processingGraph.AddNode (cd); @@ -80,7 +78,7 @@ void configureAndStartAudioProcessingGraph (AUGraph graph) var status = ioUnit.SetSampleRate (graphSampleRate, AudioUnitScopeType.Output); if (status != AudioUnitStatus.NoError) - throw new Exception ("AudioUnitSetProperty (set Sample output stream sample rate). Error code: " + (int)status); + throw new Exception ("AudioUnitSetProperty (set Sample output stream sample rate). Error code: " + (int) status); framesPerSlice = ioUnit.GetMaximumFramesPerSlice (AudioUnitScopeType.Global); @@ -88,15 +86,15 @@ void configureAndStartAudioProcessingGraph (AUGraph graph) samplerUnit.SetMaximumFramesPerSlice (framesPerSlice, AudioUnitScopeType.Global); if (graph != null) { - result = (int)graph.Initialize (); - if (result != (int)AUGraphError.OK) + result = (int) graph.Initialize (); + if (result != (int) AUGraphError.OK) throw new Exception ("Unable to initialize AUGraph object. Error code: " + result); - result = (int)graph.Start (); - if (result != (int)AUGraphError.OK) + result = (int) graph.Start (); + if (result != (int) AUGraphError.OK) throw new Exception ("Unable to start audio processing graph. Error code: " + result); -// TODO: CAShow + // TODO: CAShow Console.WriteLine (graph); } } @@ -119,7 +117,7 @@ int loadSynth (NSUrl presetUrl) var preset = new ClassInfoDictionary (dict); var error = samplerUnit.SetClassInfo (preset); - return (int)error; + return (int) error; } bool setupAudioSession () @@ -157,21 +155,21 @@ bool setupAudioSession () public void StartPlayNoteNumber (int noteNum) { uint onVelocity = 127; - uint noteCommand = (int)MIDIMessage.NoteOn << 4 | 0; + uint noteCommand = (int) MIDIMessage.NoteOn << 4 | 0; - var result = samplerUnit.MusicDeviceMIDIEvent (noteCommand, (uint)noteNum, onVelocity, 0); + var result = samplerUnit.MusicDeviceMIDIEvent (noteCommand, (uint) noteNum, onVelocity, 0); if (result != AudioUnitStatus.NoError) - Console.WriteLine ("Unable to start playing the mid note. Error code: {0}", (int)result); + Console.WriteLine ("Unable to start playing the mid note. Error code: {0}", (int) result); } public void StopPlayNoteNumber (int noteNum) { - uint noteCommand = (int)MIDIMessage.NoteOff << 4 | 0; + uint noteCommand = (int) MIDIMessage.NoteOff << 4 | 0; - var result = samplerUnit.MusicDeviceMIDIEvent (noteCommand, (uint)noteNum, 0, 0); + var result = samplerUnit.MusicDeviceMIDIEvent (noteCommand, (uint) noteNum, 0, 0); if (result != AudioUnitStatus.NoError) - Console.WriteLine ("Unable to stop playing the mid note. Error code: {0}", (int)result); + Console.WriteLine ("Unable to stop playing the mid note. Error code: {0}", (int) result); } void stopAudioProcessingGraph () @@ -194,7 +192,7 @@ void restartAudioProcessingGraph () throw new Exception ("Unable to restart the audio processing graph. Error code: " + result); } -// [Export("beginInterruption")] + // [Export("beginInterruption")] void Interruption (object sender, AVAudioSessionInterruptionEventArgs e) { if (e.InterruptionType == AVAudioSessionInterruptionType.Began) @@ -213,13 +211,13 @@ void Interruption (object sender, AVAudioSessionInterruptionEventArgs e) } } - [Export("beginInterruption")] + [Export ("beginInterruption")] void beginInterruption () { stopAudioProcessingGraph (); } -// - [Export("endInterruptionWithFlags:")] + // + [Export ("endInterruptionWithFlags:")] void endInterruption (AVAudioSessionInterruptionFlags flags) { NSError error = null; @@ -229,13 +227,13 @@ void endInterruption (AVAudioSessionInterruptionFlags flags) Console.WriteLine ("Unable to reactivate the audio session"); return; } - #pragma warning disable 472 +#pragma warning disable 472 if ((flags & AVAudioSessionInterruptionFlags.ShouldResume) != null) restartAudioProcessingGraph (); - #pragma warning restore 472 +#pragma warning restore 472 } - [Export("inputIsAvailableChanged:")] + [Export ("inputIsAvailableChanged:")] public void InputIsAvailableChanged (bool isInputAvailable) { @@ -246,12 +244,12 @@ void registerForUIApplicationNotifications () NSNotificationCenter notificationCenter = NSNotificationCenter.DefaultCenter; notificationCenter.AddObserver (UIApplication.WillResignActiveNotification, - handleResigningActive, - UIApplication.SharedApplication); + handleResigningActive, + UIApplication.SharedApplication); notificationCenter.AddObserver (UIApplication.DidBecomeActiveNotification, - handleBecomingActive, - UIApplication.SharedApplication); + handleBecomingActive, + UIApplication.SharedApplication); } void handleResigningActive (NSNotification notification) diff --git a/QuartzSample/AppDelegate.cs b/QuartzSample/AppDelegate.cs index e0a539293..4658339c6 100644 --- a/QuartzSample/AppDelegate.cs +++ b/QuartzSample/AppDelegate.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; using Foundation; -namespace QuartzSample -{ +namespace QuartzSample { // The name AppDelegate is referenced in the MainWindow.xib file. - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { diff --git a/QuartzSample/CurveDrawing.cs b/QuartzSample/CurveDrawing.cs index c59b863a2..f1a187f47 100644 --- a/QuartzSample/CurveDrawing.cs +++ b/QuartzSample/CurveDrawing.cs @@ -5,8 +5,7 @@ using QuartzSample; [Register] -public class EllipseArcDrawingView : QuartzView -{ +public class EllipseArcDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Drawing with a white stroke color @@ -27,23 +26,23 @@ public override void DrawInContext (CGContext context) context.FillEllipseInRect (new CGRect (30, 210, 60, 60)); // Stroke 2 seperate arcs - context.AddArc (150, 60, 30, 0, (float)Math.PI / 2, false); + context.AddArc (150, 60, 30, 0, (float) Math.PI / 2, false); context.StrokePath (); - context.AddArc (150, 60, 30, (float)(3 * Math.PI / 2), (float)Math.PI, true); + context.AddArc (150, 60, 30, (float) (3 * Math.PI / 2), (float) Math.PI, true); context.StrokePath (); // Stroke 2 arcs together going opposite directions. - context.AddArc (150, 150, 30, 0, (float)Math.PI / 2, false); - context.AddArc (150, 150, 30, (float)(3 * Math.PI / 2), (float)Math.PI, true); + context.AddArc (150, 150, 30, 0, (float) Math.PI / 2, false); + context.AddArc (150, 150, 30, (float) (3 * Math.PI / 2), (float) Math.PI, true); context.StrokePath (); // Stroke 2 arcs together going the same direction.. - context.AddArc (150, 240, 30, 0, (float)(Math.PI / 2), false); - context.AddArc (150, 240, 30, (float)Math.PI, (float)(3 * Math.PI / 2), false); + context.AddArc (150, 240, 30, 0, (float) (Math.PI / 2), false); + context.AddArc (150, 240, 30, (float) Math.PI, (float) (3 * Math.PI / 2), false); context.StrokePath (); // Stroke an arc using AddArcToPoint - CGPoint[] p = { + CGPoint [] p = { new CGPoint (210, 30), new CGPoint (210, 60), new CGPoint (240, 60), @@ -106,8 +105,7 @@ public override void DrawInContext (CGContext context) } [Register] -public class BezierDrawingView : QuartzView -{ +public class BezierDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Drawing with a white stroke color diff --git a/QuartzSample/ImageDrawing.cs b/QuartzSample/ImageDrawing.cs index b8970c79d..e1de497ab 100644 --- a/QuartzSample/ImageDrawing.cs +++ b/QuartzSample/ImageDrawing.cs @@ -5,8 +5,7 @@ using System.IO; using QuartzSample; -public class ImageDrawingView : QuartzView -{ +public class ImageDrawingView : QuartzView { UIImage uiimage; CGImage image; @@ -55,8 +54,7 @@ public override void DrawInContext (CGContext context) } } -public class PDFDrawingView : QuartzView -{ +public class PDFDrawingView : QuartzView { CGPDFDocument doc; public PDFDrawingView () : base () diff --git a/QuartzSample/LineDrawing.cs b/QuartzSample/LineDrawing.cs index 06acd661e..6d8b8c78d 100644 --- a/QuartzSample/LineDrawing.cs +++ b/QuartzSample/LineDrawing.cs @@ -4,8 +4,7 @@ using CoreGraphics; using QuartzSample; -public class LineDrawingView : QuartzView -{ +public class LineDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Draw lines with a white stroke color @@ -46,8 +45,7 @@ public override void DrawInContext (CGContext context) } } -public class LineWidthDrawingView : QuartzView -{ +public class LineWidthDrawingView : QuartzView { public override void DrawInContext (CGContext context) { context.SetStrokeColor (1, 1, 1, 1f); @@ -55,8 +53,8 @@ public override void DrawInContext (CGContext context) // Draw lines with a stroke width from 1-10 for (int i = 1; i <= 10; ++i) { context.SetLineWidth (i); - context.MoveTo (10, (float)i * 20.5f); - context.AddLineToPoint (310, (float)i * 20.5f); + context.MoveTo (10, (float) i * 20.5f); + context.AddLineToPoint (310, (float) i * 20.5f); context.StrokePath (); } @@ -74,8 +72,7 @@ public override void DrawInContext (CGContext context) } } -public class LineCapJoinDrawingView : QuartzView -{ +public class LineCapJoinDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Drawing lines with a white stroke color @@ -160,8 +157,7 @@ public override void DrawInContext (CGContext context) } } -public class LineDashDrawingView : QuartzView -{ +public class LineDashDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Drawing lines with a white stroke color @@ -189,13 +185,13 @@ public override void DrawInContext (CGContext context) // phase=6 starts 6 points in, so we draw 4, skip 10, draw 20, skip 20, draw 10, skip 10, etc. // phase=12 stats us 12 points in, so we skip 8, draw 20, skip 20, draw 10, skip 10, etc. // and so on. - nfloat[] dash2 = { 10, 10, 20, 20 }; + nfloat [] dash2 = { 10, 10, 20, 20 }; // Different dash phases for (int i = 0; i < 10; ++i) { context.SetLineDash (i * 6, dash2, 4); - context.MoveTo (10, (float)(i + 6) * 20); - context.AddLineToPoint (310, (float)(i + 6) * 20); + context.MoveTo (10, (float) (i + 6) * 20); + context.AddLineToPoint (310, (float) (i + 6) * 20); context.StrokePath (); } } diff --git a/QuartzSample/Main.cs b/QuartzSample/Main.cs index cae9f1ddd..821740ad7 100644 --- a/QuartzSample/Main.cs +++ b/QuartzSample/Main.cs @@ -1,10 +1,8 @@ using UIKit; -namespace QuartzSample -{ - public class Application - { - static void Main (string[] args) +namespace QuartzSample { + public class Application { + static void Main (string [] args) { UIApplication.Main (args); } diff --git a/QuartzSample/MainViewController.cs b/QuartzSample/MainViewController.cs index 153a34260..4e09bfadf 100644 --- a/QuartzSample/MainViewController.cs +++ b/QuartzSample/MainViewController.cs @@ -2,13 +2,11 @@ using UIKit; using Foundation; -namespace QuartzSample -{ +namespace QuartzSample { - public partial class MainViewController : UITableViewController - { + public partial class MainViewController : UITableViewController { - QuartzViewController[] controllers; + QuartzViewController [] controllers; public MainViewController (IntPtr b) : base (b) { @@ -47,8 +45,7 @@ public override void ViewWillAppear (bool animated) // // The data source for our TableView // - class DataSource : UITableViewDataSource - { + class DataSource : UITableViewDataSource { static NSString kCellIdentifier = new NSString ("MyIdentifier"); MainViewController mvc; @@ -86,8 +83,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde // // This class receives notifications that happen on the UITableView // - class TableDelegate : UITableViewDelegate - { + class TableDelegate : UITableViewDelegate { MainViewController mvc; public TableDelegate (MainViewController mvc) diff --git a/QuartzSample/PolyDrawing.cs b/QuartzSample/PolyDrawing.cs index 490424e8a..0e7a46cee 100644 --- a/QuartzSample/PolyDrawing.cs +++ b/QuartzSample/PolyDrawing.cs @@ -4,8 +4,7 @@ using CoreGraphics; using QuartzSample; -public class RectDrawingView : QuartzView -{ +public class RectDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Drawing with a white stroke color @@ -48,8 +47,7 @@ public override void DrawInContext (CGContext context) } } -public class PolyDrawingView : QuartzView -{ +public class PolyDrawingView : QuartzView { public override void DrawInContext (CGContext context) { // Drawing with a white stroke color @@ -65,8 +63,8 @@ public override void DrawInContext (CGContext context) center = new CGPoint (90, 90); context.MoveTo (center.X, center.Y + 60); for (int i = 1; i < 5; ++i) { - float x = (float)(60 * Math.Sin (i * 4 * Math.PI / 5)); - float y = (float)(60 * Math.Cos (i * 4 * Math.PI / 5)); + float x = (float) (60 * Math.Sin (i * 4 * Math.PI / 5)); + float y = (float) (60 * Math.Cos (i * 4 * Math.PI / 5)); context.AddLineToPoint (center.X + x, center.Y + y); } @@ -79,8 +77,8 @@ public override void DrawInContext (CGContext context) center = new CGPoint (90, 210); context.MoveTo (center.X, center.Y + 60); for (int i = 1; i < 5; ++i) { - float x = (float)(60 * Math.Sin (i * 4 * Math.PI / 5)); - float y = (float)(60 * Math.Cos (i * 4 * Math.PI / 5)); + float x = (float) (60 * Math.Sin (i * 4 * Math.PI / 5)); + float y = (float) (60 * Math.Cos (i * 4 * Math.PI / 5)); context.AddLineToPoint (center.X + x, center.Y + y); } // Closing the path connects the current point to the start of the current path. @@ -92,8 +90,8 @@ public override void DrawInContext (CGContext context) center = new CGPoint (90, 330); context.MoveTo (center.X, center.Y + 60); for (int i = 1; i < 5; ++i) { - float x = (float)(60 * Math.Sin (i * 4 * Math.PI / 5)); - float y = (float)(60 * Math.Cos (i * 4 * Math.PI / 5)); + float x = (float) (60 * Math.Sin (i * 4 * Math.PI / 5)); + float y = (float) (60 * Math.Cos (i * 4 * Math.PI / 5)); context.AddLineToPoint (center.X + x, center.Y + y); } // Closing the path connects the current point to the start of the current path. @@ -105,8 +103,8 @@ public override void DrawInContext (CGContext context) center = new CGPoint (210, 90); context.MoveTo (center.X, center.Y + 60); for (int i = 1; i < 6; ++i) { - float x = (float)(60 * Math.Sin (i * 2 * Math.PI / 6)); - float y = (float)(60 * Math.Cos (i * 2 * Math.PI / 6)); + float x = (float) (60 * Math.Sin (i * 2 * Math.PI / 6)); + float y = (float) (60 * Math.Cos (i * 2 * Math.PI / 6)); context.AddLineToPoint (center.X + x, center.Y + y); } // Closing the path connects the current point to the start of the current path. @@ -118,8 +116,8 @@ public override void DrawInContext (CGContext context) center = new CGPoint (210, 240); context.MoveTo (center.X, center.Y + 60); for (int i = 1; i < 6; ++i) { - float x = (float)(60 * Math.Sin (i * 2 * Math.PI / 6)); - float y = (float)(60 * Math.Cos (i * 2 * Math.PI / 6)); + float x = (float) (60 * Math.Sin (i * 2 * Math.PI / 6)); + float y = (float) (60 * Math.Cos (i * 2 * Math.PI / 6)); context.AddLineToPoint (center.X + x, center.Y + y); } // Closing the path connects the current point to the start of the current path. diff --git a/QuartzSample/QuartzBlendingViewController.xib.cs b/QuartzSample/QuartzBlendingViewController.xib.cs index aae68bf94..2b2e390a1 100644 --- a/QuartzSample/QuartzBlendingViewController.xib.cs +++ b/QuartzSample/QuartzBlendingViewController.xib.cs @@ -6,10 +6,8 @@ using QuartzSample; using CoreGraphics; -namespace QuartzSample -{ - public partial class QuartzBlendingViewController : QuartzViewController - { +namespace QuartzSample { + public partial class QuartzBlendingViewController : QuartzViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need @@ -108,16 +106,16 @@ static nfloat LuminanceForColor (UIColor color) var components = cgcolor.Components; nfloat luminance = 0; - switch (cgcolor.ColorSpace.Model){ + switch (cgcolor.ColorSpace.Model) { case CGColorSpaceModel.Monochrome: // For grayscale colors, the luminance is the color value - luminance = components[0]; + luminance = components [0]; break; case CGColorSpaceModel.RGB: // For RGB colors, we calculate luminance assuming sRGB Primaries as per // http://en.wikipedia.org/wiki/Luminance_(relative) - luminance = 0.2126f * components[0] + 0.7152f * components[1] + 0.0722f * components[2]; + luminance = 0.2126f * components [0] + 0.7152f * components [1] + 0.0722f * components [2]; break; default: @@ -131,10 +129,10 @@ static nfloat LuminanceForColor (UIColor color) } // Simple comparison function that sorts the two (presumed) UIColors according to their luminance value. - static int ColorSortByLuminance (UIColor color1, UIColor color2) + static int ColorSortByLuminance (UIColor color1, UIColor color2) { - nfloat luminance1 = LuminanceForColor(color1); - nfloat luminance2 = LuminanceForColor(color2); + nfloat luminance1 = LuminanceForColor (color1); + nfloat luminance2 = LuminanceForColor (color2); if (luminance1 == luminance2) return 0; @@ -144,8 +142,7 @@ static int ColorSortByLuminance (UIColor color1, UIColor color2) return 1; } - public class BlendSelector : UIPickerViewModel - { + public class BlendSelector : UIPickerViewModel { QuartzBlendingViewController parent; public BlendSelector (QuartzBlendingViewController parent) @@ -153,7 +150,8 @@ public BlendSelector (QuartzBlendingViewController parent) this.parent = parent; } - public override nint GetComponentCount (UIPickerView picker){ + public override nint GetComponentCount (UIPickerView picker) + { return 3; } @@ -178,16 +176,16 @@ public override UIView GetView (UIPickerView picker, nint row, nint component, U { var size = picker.RowSizeForComponent (component); - if (component == 0 || component == 1){ - if (view == null || view.Tag != kColorTag){ - view = new UIView (new CGRect (0, 0, size.Width-4, size.Height-4)){ + if (component == 0 || component == 1) { + if (view == null || view.Tag != kColorTag) { + view = new UIView (new CGRect (0, 0, size.Width - 4, size.Height - 4)) { Tag = kColorTag }; } view.BackgroundColor = Colors [row]; } else { - if (view == null || view.Tag != kLabelTag){ - view = new UILabel (new CGRect (0, 0, size.Width-4, size.Height-4)){ + if (view == null || view.Tag != kLabelTag) { + view = new UILabel (new CGRect (0, 0, size.Width - 4, size.Height - 4)) { Tag = kLabelTag, Opaque = false, BackgroundColor = UIColor.Clear @@ -206,7 +204,7 @@ public override void Selected (UIPickerView picker, nint row, nint component) var qbv = (QuartzBlendingView) parent.quartzView; qbv.DestinationColor = Colors [picker.SelectedRowInComponent (0)]; qbv.SourceColor = Colors [picker.SelectedRowInComponent (1)]; - qbv.BlendMode = (CGBlendMode) (int)picker.SelectedRowInComponent (2); + qbv.BlendMode = (CGBlendMode) (int) picker.SelectedRowInComponent (2); qbv.SetNeedsDisplay (); } } @@ -217,7 +215,8 @@ public class QuartzBlendingView : QuartzView { public UIColor DestinationColor { get; set; } public CGBlendMode BlendMode { get; set; } - public QuartzBlendingView () : base () { + public QuartzBlendingView () : base () + { SourceColor = UIColor.White; DestinationColor = UIColor.Black; BlendMode = CGBlendMode.Normal; @@ -230,11 +229,11 @@ public override void DrawInContext (CGContext context) context.FillRect (Bounds); // We want to just lay down the background without any blending so we use the Copy mode rather than Normal - context.SetBlendMode(CGBlendMode.Copy); + context.SetBlendMode (CGBlendMode.Copy); // Draw a rect with the "background" color - this is the "Destination" for the blending formulas context.SetFillColor (DestinationColor.CGColor); - context.FillRect(new CGRect (110, 20, 100, 100)); + context.FillRect (new CGRect (110, 20, 100, 100)); // Set up our blend mode context.SetBlendMode (BlendMode); diff --git a/QuartzSample/QuartzViewController.xib.cs b/QuartzSample/QuartzViewController.xib.cs index de9d7f8a8..dd15fb782 100644 --- a/QuartzSample/QuartzViewController.xib.cs +++ b/QuartzSample/QuartzViewController.xib.cs @@ -5,22 +5,19 @@ using UIKit; using CoreGraphics; -namespace QuartzSample -{ - public abstract class QuartzView : UIView - { +namespace QuartzSample { + public abstract class QuartzView : UIView { public abstract void DrawInContext (CGContext context); public override void Draw (CGRect rect) { using (var ctxt = UIGraphics.GetCurrentContext ()) { - DrawInContext ( ctxt ); + DrawInContext (ctxt); } } } - public partial class QuartzViewController : UIViewController - { + public partial class QuartzViewController : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need diff --git a/QuartzSample/RenderedDrawing.cs b/QuartzSample/RenderedDrawing.cs index 5d96a520e..6bb2fd4b6 100644 --- a/QuartzSample/RenderedDrawing.cs +++ b/QuartzSample/RenderedDrawing.cs @@ -4,14 +4,13 @@ using CoreGraphics; using QuartzSample; -public class GradientDrawingView : QuartzView -{ +public class GradientDrawingView : QuartzView { CGGradient gradient; public GradientDrawingView () : base () { using (var rgb = CGColorSpace.CreateDeviceRGB ()) { - nfloat[] colors = { + nfloat [] colors = { 204f / 255f, 224f / 255f, 244f / 255f, 10f, 29f / 255f, 156f / 255f, 215f / 255f, 10f, 0f / 255f, 50f / 255f, 126f / 255f, 10f, @@ -166,8 +165,7 @@ public override void DrawInContext (CGContext context) } [Register] -public class PatternDrawingView : QuartzView -{ +public class PatternDrawingView : QuartzView { CGColor coloredPatternColor; CGPattern uncoloredPattern; CGColorSpace uncoloredPatternColorSpace; @@ -198,12 +196,12 @@ public PatternDrawingView () : base () // First we need to create a CGPattern that specifies the qualities of our pattern. using (var coloredPattern = new CGPattern ( - new CGRect (0, 0, 16, 16), // the pattern coordinate space, drawing is clipped to this rectangle - CGAffineTransform.MakeIdentity (), // a transform on the pattern coordinate space used before it is drawn. - 16, 16, // the spacing (horizontal, vertical) of the pattern - how far to move after drawing each cell - CGPatternTiling.NoDistortion, - true, // this is a colored pattern, which means that you only specify an alpha value when drawing it - DrawColored)) { + new CGRect (0, 0, 16, 16), // the pattern coordinate space, drawing is clipped to this rectangle + CGAffineTransform.MakeIdentity (), // a transform on the pattern coordinate space used before it is drawn. + 16, 16, // the spacing (horizontal, vertical) of the pattern - how far to move after drawing each cell + CGPatternTiling.NoDistortion, + true, // this is a colored pattern, which means that you only specify an alpha value when drawing it + DrawColored)) { // To draw a pattern, you need a pattern colorspace. // Since this is an colored pattern, the parent colorspace is NULL, indicating that it only has an alpha value. diff --git a/Quotes/AppDelegate.cs b/Quotes/AppDelegate.cs index b4908de04..11b854a93 100644 --- a/Quotes/AppDelegate.cs +++ b/Quotes/AppDelegate.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace Quotes -{ +namespace Quotes { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; UINavigationController viewController = new UINavigationController (); @@ -24,7 +22,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Quotes/MasterViewController.cs b/Quotes/MasterViewController.cs index 79ac68ae1..8dd3ff4b2 100644 --- a/Quotes/MasterViewController.cs +++ b/Quotes/MasterViewController.cs @@ -11,12 +11,10 @@ using UIKit; using Foundation; -namespace Quotes -{ - public class MasterViewController : UICollectionViewController - { +namespace Quotes { + public class MasterViewController : UICollectionViewController { List<Page> pages; - string[] titles = new string [5]; + string [] titles = new string [5]; NSString cellName = new NSString ("PagePreview"); [Export ("initWithNibName:bundle:")] @@ -77,7 +75,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (PagePreview)collectionView.DequeueReusableCell (cellName, indexPath); + var cell = (PagePreview) collectionView.DequeueReusableCell (cellName, indexPath); cell.Page = pages.ElementAt (indexPath.Row); diff --git a/Quotes/Page.cs b/Quotes/Page.cs index b53ae5f23..8c0c957e0 100644 --- a/Quotes/Page.cs +++ b/Quotes/Page.cs @@ -9,10 +9,8 @@ using UIKit; using CoreText; -namespace Quotes -{ - public class Page : NSObject - { +namespace Quotes { + public class Page : NSObject { // The paragraphs loaded from the XML file public List<XElement> Paragraphs { get; set; } @@ -55,17 +53,17 @@ public NSAttributedString AttributedStringForParagraph (XElement paragraph) // TODO: find stage directions and format them differently if (ParagraphIsStageDirection (paragraph)) { var stageDirection = new NSAttributedString (TextForParagraph (paragraph), - font: UIFont.FromName ("Helvetica-LightOblique", 24), - paragraphStyle: new NSMutableParagraphStyle () { Alignment = UITextAlignment.Center, LineSpacing = 10}); + font: UIFont.FromName ("Helvetica-LightOblique", 24), + paragraphStyle: new NSMutableParagraphStyle () { Alignment = UITextAlignment.Center, LineSpacing = 10 }); returnValue.Append (stageDirection); } else { var speaker = new NSAttributedString (SpeakerForParagraph (paragraph), - font: UIFont.FromName ("HoeflerText-Black", 24), - foregroundColor: UIColor.Brown - ); + font: UIFont.FromName ("HoeflerText-Black", 24), + foregroundColor: UIColor.Brown + ); var text = new NSAttributedString (TextForParagraph (paragraph), - font: UIFont.FromName ("HoeflerText-Regular", 24.0f), - foregroundColor: UIColor.Black + font: UIFont.FromName ("HoeflerText-Regular", 24.0f), + foregroundColor: UIColor.Black #if TEST_OTHER_ATTRIBUTES ,backgroundColor: UIColor.Yellow, ligatures: NSLigatureType.None, @@ -85,13 +83,13 @@ public NSAttributedString AttributedStringForParagraph (XElement paragraph) } returnValue.EnumerateAttribute (UIStringAttributeKey.ParagraphStyle, new NSRange (0, returnValue.Length), NSAttributedStringEnumeration.LongestEffectiveRangeNotRequired, - (NSObject value, NSRange range, ref bool stop) => { - var style = value == null ? new NSMutableParagraphStyle () : (NSMutableParagraphStyle)value.MutableCopy (); - style.MinimumLineHeight = LineHeight; - style.MaximumLineHeight = LineHeight; + (NSObject value, NSRange range, ref bool stop) => { + var style = value == null ? new NSMutableParagraphStyle () : (NSMutableParagraphStyle) value.MutableCopy (); + style.MinimumLineHeight = LineHeight; + style.MaximumLineHeight = LineHeight; - returnValue.AddAttribute (UIStringAttributeKey.ParagraphStyle, style, range); - }); + returnValue.AddAttribute (UIStringAttributeKey.ParagraphStyle, style, range); + }); return returnValue; } diff --git a/Quotes/PagePreview.cs b/Quotes/PagePreview.cs index 054e099d0..d9a913f42 100644 --- a/Quotes/PagePreview.cs +++ b/Quotes/PagePreview.cs @@ -6,10 +6,8 @@ using Foundation; using CoreText; -namespace Quotes -{ - public partial class PagePreview : UICollectionViewCell - { +namespace Quotes { + public partial class PagePreview : UICollectionViewCell { Page cellPage; [Export ("initWithCoder:")] diff --git a/Quotes/PageView.cs b/Quotes/PageView.cs index 63c7e06b6..1a268d30a 100644 --- a/Quotes/PageView.cs +++ b/Quotes/PageView.cs @@ -6,14 +6,12 @@ using CoreGraphics; using CoreText; -namespace Quotes -{ +namespace Quotes { [Register ("PageView")] - public class PageView : UIImageView - { + public class PageView : UIImageView { Page page; public bool UnstyledDrawing; - CGRect[] paragraphBounds; + CGRect [] paragraphBounds; public PageView (IntPtr handle) : base (handle) { @@ -52,7 +50,7 @@ public void SetLineHeight (float lHeight) } } - [Export("getLineHeight")] + [Export ("getLineHeight")] public float GetLineHeight () { return page.LineHeight; @@ -119,7 +117,7 @@ public CGRect [] RenderPage (Page page, CGSize size, bool unstyledDrawing) public void SelectParagraphAtPosition (CGPoint position, bool shouldShowMenu) { - page.SelectedParagraph = (int)NSRange.NotFound; + page.SelectedParagraph = (int) NSRange.NotFound; var bounds = CGRect.Empty; for (int i = 0; i < paragraphBounds.Length; i++) { diff --git a/Quotes/PageViewController.cs b/Quotes/PageViewController.cs index b124ff4ad..e6763d47c 100644 --- a/Quotes/PageViewController.cs +++ b/Quotes/PageViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace Quotes -{ - public partial class PageViewController : UIViewController - { +namespace Quotes { + public partial class PageViewController : UIViewController { public Page controllerPage { get; set; } public override void ViewDidLoad () @@ -41,7 +39,7 @@ public override string Title { partial void ParagraphSelected (UIKit.UILongPressGestureRecognizer sender) { pageView.SelectParagraphAtPosition (sender.LocationInView (pageView), - sender.State == UIKit.UIGestureRecognizerState.Ended); + sender.State == UIKit.UIGestureRecognizerState.Ended); } partial void DrawingModeToggled (UIKit.UISwipeGestureRecognizer sender) diff --git a/Reachability/Reachability/AppDelegate.cs b/Reachability/Reachability/AppDelegate.cs index 98603750d..fc8c7ba5d 100644 --- a/Reachability/Reachability/AppDelegate.cs +++ b/Reachability/Reachability/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Reachability -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace Reachability { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/Reachability/Reachability/Main.cs b/Reachability/Reachability/Main.cs index cc94fc6d8..6a738ed6e 100644 --- a/Reachability/Reachability/Main.cs +++ b/Reachability/Reachability/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Reachability -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace Reachability { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/Reachability/Reachability/Reachability.cs b/Reachability/Reachability/Reachability.cs index 3c6958191..578cb956c 100644 --- a/Reachability/Reachability/Reachability.cs +++ b/Reachability/Reachability/Reachability.cs @@ -3,152 +3,137 @@ using SystemConfiguration; using System.Net; -namespace Reachability -{ - public enum NetworkStatus - { - NotReachable, - ReachableViaWWAN, - ReachableViaWiFi - } - - /// <summary> - /// Basic demonstration of how to use the SystemConfiguration Reachablity APIs. - /// </summary> - public class Reachability : NSObject - { - ~Reachability() - { - StopNotifier(); - if (NetworkReachability != null) - { - NetworkReachability.Dispose(); - } - } - - public static string ReachabilityChangedNotification { get; } = "kNetworkReachabilityChangedNotification"; - - public NetworkReachability NetworkReachability { get; private set; } - - public static Reachability ReachabilityWithHostName(string hostName) - { - var reachability = new NetworkReachability(hostName); - return new Reachability { NetworkReachability = reachability }; - } - - public static Reachability ReachabilityWithAddress(IPAddress hostAddress) - { - var reachability = new NetworkReachability(hostAddress); - return new Reachability { NetworkReachability = reachability }; - } - - public static Reachability ReachabilityForInternetConnection() - { - var reachability = new NetworkReachability(new IPAddress(0)); - return new Reachability { NetworkReachability = reachability }; - } - - private void HandleNotification(NetworkReachabilityFlags flags) - { - // Post a notification to notify the client that the network reachability changed. - NSNotificationCenter.DefaultCenter.PostNotificationName(ReachabilityChangedNotification, this); - } - - #region Start and stop notifier - - public bool StartNotifier() - { - var result = false; - - var status = NetworkReachability.SetNotification(HandleNotification); - if (status == StatusCode.OK) - { - result = NetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault); - } - - return result; - } - - private void StopNotifier() - { - if (NetworkReachability != null) - { - NetworkReachability.Unschedule(CFRunLoop.Current, CFRunLoop.ModeDefault); - } - } - - #endregion - - #region Network Flag Handling - - public NetworkStatus NetworkStatusForFlags(NetworkReachabilityFlags flags) - { - if ((flags & NetworkReachabilityFlags.Reachable) == 0) - { - // The target host is not reachable. - return NetworkStatus.NotReachable; - } - - NetworkStatus result = NetworkStatus.NotReachable; - if ((flags & NetworkReachabilityFlags.ConnectionRequired) == 0) - { - // If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi... - result = NetworkStatus.ReachableViaWiFi; - } - - if ((flags & NetworkReachabilityFlags.ConnectionOnDemand) != 0 || - (flags & NetworkReachabilityFlags.ConnectionOnTraffic) != 0) - { - // ... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs... - if ((flags & NetworkReachabilityFlags.InterventionRequired) == 0) - { - // ... and no [user] intervention is needed... - result = NetworkStatus.ReachableViaWiFi; - } - } - - if ((flags & NetworkReachabilityFlags.IsWWAN) == NetworkReachabilityFlags.IsWWAN) - { - // ... but WWAN connections are OK if the calling application is using the CFNetwork APIs. - result = NetworkStatus.ReachableViaWWAN; - } - - return result; - } - - public bool ConnectionRequired() - { - if (NetworkReachability.TryGetFlags(out NetworkReachabilityFlags flags)) - { - return (flags & NetworkReachabilityFlags.ConnectionRequired) != 0; - } - - return false; - } - - public NetworkStatus CurrentReachabilityStatus() - { - var returnValue = NetworkStatus.NotReachable; - if (NetworkReachability.TryGetFlags(out NetworkReachabilityFlags flags)) - { - returnValue = this.NetworkStatusForFlags(flags); - } - - return returnValue; - } - - #endregion - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (disposing) - { - if (NetworkReachability != null) - { - NetworkReachability.Dispose(); - } - } - } - } -} \ No newline at end of file +namespace Reachability { + public enum NetworkStatus { + NotReachable, + ReachableViaWWAN, + ReachableViaWiFi + } + + /// <summary> + /// Basic demonstration of how to use the SystemConfiguration Reachablity APIs. + /// </summary> + public class Reachability : NSObject { + ~Reachability () + { + StopNotifier (); + if (NetworkReachability != null) { + NetworkReachability.Dispose (); + } + } + + public static string ReachabilityChangedNotification { get; } = "kNetworkReachabilityChangedNotification"; + + public NetworkReachability NetworkReachability { get; private set; } + + public static Reachability ReachabilityWithHostName (string hostName) + { + var reachability = new NetworkReachability (hostName); + return new Reachability { NetworkReachability = reachability }; + } + + public static Reachability ReachabilityWithAddress (IPAddress hostAddress) + { + var reachability = new NetworkReachability (hostAddress); + return new Reachability { NetworkReachability = reachability }; + } + + public static Reachability ReachabilityForInternetConnection () + { + var reachability = new NetworkReachability (new IPAddress (0)); + return new Reachability { NetworkReachability = reachability }; + } + + private void HandleNotification (NetworkReachabilityFlags flags) + { + // Post a notification to notify the client that the network reachability changed. + NSNotificationCenter.DefaultCenter.PostNotificationName (ReachabilityChangedNotification, this); + } + + #region Start and stop notifier + + public bool StartNotifier () + { + var result = false; + + var status = NetworkReachability.SetNotification (HandleNotification); + if (status == StatusCode.OK) { + result = NetworkReachability.Schedule (CFRunLoop.Current, CFRunLoop.ModeDefault); + } + + return result; + } + + private void StopNotifier () + { + if (NetworkReachability != null) { + NetworkReachability.Unschedule (CFRunLoop.Current, CFRunLoop.ModeDefault); + } + } + + #endregion + + #region Network Flag Handling + + public NetworkStatus NetworkStatusForFlags (NetworkReachabilityFlags flags) + { + if ((flags & NetworkReachabilityFlags.Reachable) == 0) { + // The target host is not reachable. + return NetworkStatus.NotReachable; + } + + NetworkStatus result = NetworkStatus.NotReachable; + if ((flags & NetworkReachabilityFlags.ConnectionRequired) == 0) { + // If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi... + result = NetworkStatus.ReachableViaWiFi; + } + + if ((flags & NetworkReachabilityFlags.ConnectionOnDemand) != 0 || + (flags & NetworkReachabilityFlags.ConnectionOnTraffic) != 0) { + // ... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs... + if ((flags & NetworkReachabilityFlags.InterventionRequired) == 0) { + // ... and no [user] intervention is needed... + result = NetworkStatus.ReachableViaWiFi; + } + } + + if ((flags & NetworkReachabilityFlags.IsWWAN) == NetworkReachabilityFlags.IsWWAN) { + // ... but WWAN connections are OK if the calling application is using the CFNetwork APIs. + result = NetworkStatus.ReachableViaWWAN; + } + + return result; + } + + public bool ConnectionRequired () + { + if (NetworkReachability.TryGetFlags (out NetworkReachabilityFlags flags)) { + return (flags & NetworkReachabilityFlags.ConnectionRequired) != 0; + } + + return false; + } + + public NetworkStatus CurrentReachabilityStatus () + { + var returnValue = NetworkStatus.NotReachable; + if (NetworkReachability.TryGetFlags (out NetworkReachabilityFlags flags)) { + returnValue = this.NetworkStatusForFlags (flags); + } + + return returnValue; + } + + #endregion + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (disposing) { + if (NetworkReachability != null) { + NetworkReachability.Dispose (); + } + } + } + } +} diff --git a/Reachability/Reachability/ViewController.cs b/Reachability/Reachability/ViewController.cs index 07be7c4e0..14fe2f2fe 100644 --- a/Reachability/Reachability/ViewController.cs +++ b/Reachability/Reachability/ViewController.cs @@ -1,111 +1,104 @@ -using System; +using System; using Foundation; using UIKit; -namespace Reachability -{ - public partial class ViewController : UIViewController - { - private Reachability internetReachability; - - private Reachability hostReachability; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - summaryLabel.Hidden = true; - - // Change the host name here to change the server you want to monitor. - const string remoteHostName = "www.google.com"; - remoteHostLabel.Text = $"Remote Host: {remoteHostName}"; - - hostReachability = Reachability.ReachabilityWithHostName(remoteHostName); - hostReachability.StartNotifier(); - UpdateInterfaceWithReachability(hostReachability); - - internetReachability = Reachability.ReachabilityForInternetConnection(); - internetReachability.StartNotifier(); - UpdateInterfaceWithReachability(internetReachability); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the method reachabilityChanged will be called. - NSNotificationCenter.DefaultCenter.AddObserver(new NSString(Reachability.ReachabilityChangedNotification), OnReachabilityChanged); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - NSNotificationCenter.DefaultCenter.RemoveObserver(this, Reachability.ReachabilityChangedNotification); - } - - /// <summary> - /// Called by Reachability whenever status changes. - /// </summary> - /// <param name="notification">Object.</param> - private void OnReachabilityChanged(NSNotification notification) - { - var reachability = notification.Object as Reachability; - UpdateInterfaceWithReachability(reachability); - } - - private void UpdateInterfaceWithReachability(Reachability reachability) - { - if (reachability == hostReachability) - { - ConfigureTextField(remoteHostStatusField, remoteHostImageView, reachability); - - var networkStatus = reachability.CurrentReachabilityStatus(); - var connectionRequired = reachability.ConnectionRequired(); - var baseLabelText = connectionRequired ? "Cellular data network is available.\nInternet traffic will be routed through it after a connection is established." - : "Cellular data network is active.\nInternet traffic will be routed through it."; - summaryLabel.Text = baseLabelText; - summaryLabel.Hidden = networkStatus != NetworkStatus.ReachableViaWWAN; - } - else if (reachability == internetReachability) - { - ConfigureTextField(internetConnectionStatusField, internetConnectionImageView, reachability); - } - } - - private void ConfigureTextField(UITextField textField, UIImageView imageView, Reachability reachability) - { - var networkStatus = reachability.CurrentReachabilityStatus(); - var connectionRequired = reachability.ConnectionRequired(); - var statusString = string.Empty; - - switch (networkStatus) - { - case NetworkStatus.NotReachable: - statusString = "Access Not Available"; - imageView.Image = UIImage.FromBundle("stop-32.png"); - // Minor interface detail - connectionRequired may return YES even when the host is unreachable. We cover that up here... - connectionRequired = false; - break; - - case NetworkStatus.ReachableViaWWAN: - statusString = "Reachable WWAN"; - imageView.Image = UIImage.FromBundle("WWAN5.png"); - break; - - case NetworkStatus.ReachableViaWiFi: - statusString = "Reachable WiFi"; - imageView.Image = UIImage.FromBundle("Airport.png"); - break; - } - - if (connectionRequired) - { - statusString = $"{statusString}, Connection Required"; - } - - textField.Text = statusString; - } - } -} \ No newline at end of file +namespace Reachability { + public partial class ViewController : UIViewController { + private Reachability internetReachability; + + private Reachability hostReachability; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + summaryLabel.Hidden = true; + + // Change the host name here to change the server you want to monitor. + const string remoteHostName = "www.google.com"; + remoteHostLabel.Text = $"Remote Host: {remoteHostName}"; + + hostReachability = Reachability.ReachabilityWithHostName (remoteHostName); + hostReachability.StartNotifier (); + UpdateInterfaceWithReachability (hostReachability); + + internetReachability = Reachability.ReachabilityForInternetConnection (); + internetReachability.StartNotifier (); + UpdateInterfaceWithReachability (internetReachability); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the method reachabilityChanged will be called. + NSNotificationCenter.DefaultCenter.AddObserver (new NSString (Reachability.ReachabilityChangedNotification), OnReachabilityChanged); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + NSNotificationCenter.DefaultCenter.RemoveObserver (this, Reachability.ReachabilityChangedNotification); + } + + /// <summary> + /// Called by Reachability whenever status changes. + /// </summary> + /// <param name="notification">Object.</param> + private void OnReachabilityChanged (NSNotification notification) + { + var reachability = notification.Object as Reachability; + UpdateInterfaceWithReachability (reachability); + } + + private void UpdateInterfaceWithReachability (Reachability reachability) + { + if (reachability == hostReachability) { + ConfigureTextField (remoteHostStatusField, remoteHostImageView, reachability); + + var networkStatus = reachability.CurrentReachabilityStatus (); + var connectionRequired = reachability.ConnectionRequired (); + var baseLabelText = connectionRequired ? "Cellular data network is available.\nInternet traffic will be routed through it after a connection is established." + : "Cellular data network is active.\nInternet traffic will be routed through it."; + summaryLabel.Text = baseLabelText; + summaryLabel.Hidden = networkStatus != NetworkStatus.ReachableViaWWAN; + } else if (reachability == internetReachability) { + ConfigureTextField (internetConnectionStatusField, internetConnectionImageView, reachability); + } + } + + private void ConfigureTextField (UITextField textField, UIImageView imageView, Reachability reachability) + { + var networkStatus = reachability.CurrentReachabilityStatus (); + var connectionRequired = reachability.ConnectionRequired (); + var statusString = string.Empty; + + switch (networkStatus) { + case NetworkStatus.NotReachable: + statusString = "Access Not Available"; + imageView.Image = UIImage.FromBundle ("stop-32.png"); + // Minor interface detail - connectionRequired may return YES even when the host is unreachable. We cover that up here... + connectionRequired = false; + break; + + case NetworkStatus.ReachableViaWWAN: + statusString = "Reachable WWAN"; + imageView.Image = UIImage.FromBundle ("WWAN5.png"); + break; + + case NetworkStatus.ReachableViaWiFi: + statusString = "Reachable WiFi"; + imageView.Image = UIImage.FromBundle ("Airport.png"); + break; + } + + if (connectionRequired) { + statusString = $"{statusString}, Connection Required"; + } + + textField.Text = statusString; + } + } +} diff --git a/RecipesAndPrinting/AppDelegate.cs b/RecipesAndPrinting/AppDelegate.cs index 07bacf28d..61266056b 100644 --- a/RecipesAndPrinting/AppDelegate.cs +++ b/RecipesAndPrinting/AppDelegate.cs @@ -30,14 +30,12 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ +namespace RecipesAndPrinting { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations RecipeListTableViewController mainViewController; UINavigationController navController; diff --git a/RecipesAndPrinting/InstructionsViewController.cs b/RecipesAndPrinting/InstructionsViewController.cs index 34966ab52..575fcd398 100644 --- a/RecipesAndPrinting/InstructionsViewController.cs +++ b/RecipesAndPrinting/InstructionsViewController.cs @@ -29,10 +29,8 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public partial class InstructionsViewController : UIViewController - { +namespace RecipesAndPrinting { + public partial class InstructionsViewController : UIViewController { public InstructionsViewController () : base ("RecipeInstructionsView", null) { NavigationItem.Title = "Instructions"; diff --git a/RecipesAndPrinting/Main.cs b/RecipesAndPrinting/Main.cs index cfbccc3ca..9004ac095 100644 --- a/RecipesAndPrinting/Main.cs +++ b/RecipesAndPrinting/Main.cs @@ -30,12 +30,10 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public class Application - { +namespace RecipesAndPrinting { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/RecipesAndPrinting/Recipe.cs b/RecipesAndPrinting/Recipe.cs index 086b022d0..19b2d2c11 100644 --- a/RecipesAndPrinting/Recipe.cs +++ b/RecipesAndPrinting/Recipe.cs @@ -32,15 +32,13 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ +namespace RecipesAndPrinting { public class Ingredient { public string Name; public string Amount; } - public class Recipe : IDisposable - { + public class Recipe : IDisposable { public Recipe () { } @@ -53,7 +51,7 @@ public string Description { get; set; } - public string PrepTime { + public string PrepTime { get; set; } @@ -69,7 +67,7 @@ public UIImage ThumbnailImage { get; set; } - public Ingredient[] Ingredients { + public Ingredient [] Ingredients { get; set; } diff --git a/RecipesAndPrinting/RecipeDetailViewController.cs b/RecipesAndPrinting/RecipeDetailViewController.cs index 2eea67677..b206a66ad 100644 --- a/RecipesAndPrinting/RecipeDetailViewController.cs +++ b/RecipesAndPrinting/RecipeDetailViewController.cs @@ -31,10 +31,8 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public partial class RecipeDetailViewController : UITableViewController - { +namespace RecipesAndPrinting { + public partial class RecipeDetailViewController : UITableViewController { RecipePhotoViewController recipePhotoViewController; RecipeDetailSource tableSource; @@ -87,7 +85,7 @@ public override string TitleForHeader (UITableView tableView, nint section) public override nint RowsInSection (UITableView tableView, nint section) { // HACK: Cast nint to int - switch ((RecipeSection)(int)section) { + switch ((RecipeSection) (int) section) { case RecipeSection.Instructions: return 1; case RecipeSection.Ingredients: return Recipe.Ingredients.Length; default: return 0; @@ -116,8 +114,8 @@ UITableViewCell GetIngredientsCellAtIndex (UITableView tableView, int index) amountLabel = cell.ViewWithTag (AmountTag) as UILabel; } - cell.TextLabel.Text = Recipe.Ingredients[index].Name; - amountLabel.Text = Recipe.Ingredients[index].Amount; + cell.TextLabel.Text = Recipe.Ingredients [index].Name; + amountLabel.Text = Recipe.Ingredients [index].Amount; CGSize desiredSize = amountLabel.SizeThatFits (new CGSize (160.0f, 32.0f)); // HACK: Change float to nfloat diff --git a/RecipesAndPrinting/RecipeListTableViewController.cs b/RecipesAndPrinting/RecipeListTableViewController.cs index 0609e20cd..cec96c385 100644 --- a/RecipesAndPrinting/RecipeListTableViewController.cs +++ b/RecipesAndPrinting/RecipeListTableViewController.cs @@ -30,10 +30,8 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public partial class RecipeListTableViewController : UITableViewController - { +namespace RecipesAndPrinting { + public partial class RecipeListTableViewController : UITableViewController { RecipeDetailViewController details; UIBarButtonItem printButtonItem; RecipesController recipes; @@ -100,7 +98,7 @@ public RecipeListSource (RecipeListTableViewController controller) this.controller = controller; } - Recipe[] Recipes { + Recipe [] Recipes { get { return controller.recipes.Recipes; } } @@ -125,7 +123,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde cell = new RecipeTableViewCell (UITableViewCellStyle.Default, RecipeCellId); // Provide to the cell its corresponding recipe depending on the argument row - cell.Recipe = Recipes[indexPath.Row]; + cell.Recipe = Recipes [indexPath.Row]; // Right arrow-looking indicator on the right side of the table view cell cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; @@ -135,7 +133,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - Recipe recipe = Recipes[indexPath.Row]; + Recipe recipe = Recipes [indexPath.Row]; controller.ShowRecipe (recipe, true); } diff --git a/RecipesAndPrinting/RecipePhotoViewController.cs b/RecipesAndPrinting/RecipePhotoViewController.cs index a7c83edf5..5ca3f4293 100644 --- a/RecipesAndPrinting/RecipePhotoViewController.cs +++ b/RecipesAndPrinting/RecipePhotoViewController.cs @@ -29,10 +29,8 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public class RecipePhotoViewController : UIViewController - { +namespace RecipesAndPrinting { + public class RecipePhotoViewController : UIViewController { UIImageView imageView; public RecipePhotoViewController () diff --git a/RecipesAndPrinting/RecipePrintPageRenderer.cs b/RecipesAndPrinting/RecipePrintPageRenderer.cs index 4f00f2783..8a19b3efa 100644 --- a/RecipesAndPrinting/RecipePrintPageRenderer.cs +++ b/RecipesAndPrinting/RecipePrintPageRenderer.cs @@ -33,10 +33,8 @@ using UIKit; using CoreFoundation; -namespace RecipesAndPrinting -{ - public class RecipePrintPageRenderer : UIPrintPageRenderer - { +namespace RecipesAndPrinting { + public class RecipePrintPageRenderer : UIPrintPageRenderer { const float RecipeInfoHeight = 150.0f; const float TitleSize = 24.0f; const float Padding = 10.0f; @@ -45,9 +43,9 @@ public class RecipePrintPageRenderer : UIPrintPageRenderer Dictionary<UIPrintFormatter, Recipe> recipeFormatterMap = new Dictionary<UIPrintFormatter, Recipe> (); NSRange pageRange; - Recipe[] recipes; + Recipe [] recipes; - public RecipePrintPageRenderer (Recipe[] recipes) + public RecipePrintPageRenderer (Recipe [] recipes) { this.HeaderHeight = 20.0f; this.FooterHeight = 20.0f; @@ -175,7 +173,7 @@ public override void DrawPrintFormatterForPage (UIPrintFormatter printFormatter, border.MoveTo (rect.Location); border.AddLineTo (new CGPoint (rect.Right, rect.Top)); - Recipe recipe = recipeFormatterMap[printFormatter]; + Recipe recipe = recipeFormatterMap [printFormatter]; // Run custom code to draw upper portion of the recipe presentation (image, title, desc) DrawRecipe (recipe, rect); @@ -215,7 +213,7 @@ void DrawRecipeImage (UIImage image, CGRect rect) // Scale the image to fit in the infoRect float maxImageDimension = RecipeInfoHeight - Padding * 2; // HACK: Change float to nfloat - nfloat largestImageDimension = (nfloat)Math.Max (image.Size.Width, image.Size.Height); + nfloat largestImageDimension = (nfloat) Math.Max (image.Size.Width, image.Size.Height); nfloat scale = maxImageDimension / largestImageDimension; imageRect.Size = new CGSize (image.Size.Width * scale, image.Size.Height * scale); diff --git a/RecipesAndPrinting/RecipeTableViewCell.cs b/RecipesAndPrinting/RecipeTableViewCell.cs index 544f02d51..9a16cb51a 100644 --- a/RecipesAndPrinting/RecipeTableViewCell.cs +++ b/RecipesAndPrinting/RecipeTableViewCell.cs @@ -30,10 +30,8 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public class RecipeTableViewCell : UITableViewCell - { +namespace RecipesAndPrinting { + public class RecipeTableViewCell : UITableViewCell { const float ImageSize = 42.0f; const float EditingInset = 10.0f; const float TextLeftMargin = 8.0f; diff --git a/RecipesAndPrinting/RecipesController.cs b/RecipesAndPrinting/RecipesController.cs index a1a7653cf..77d973be8 100644 --- a/RecipesAndPrinting/RecipesController.cs +++ b/RecipesAndPrinting/RecipesController.cs @@ -33,27 +33,25 @@ using Foundation; using UIKit; -namespace RecipesAndPrinting -{ - public class RecipesController - { - Recipe[] recipes; +namespace RecipesAndPrinting { + public class RecipesController { + Recipe [] recipes; public RecipesController () { recipes = CreateDemoData (); } - public Recipe[] Recipes { + public Recipe [] Recipes { get { return recipes; } } - static Recipe[] CreateDemoData () + static Recipe [] CreateDemoData () { Assembly assembly = typeof (Recipe).Assembly; - Recipe[] recipes = new Recipe [2]; + Recipe [] recipes = new Recipe [2]; - recipes[0] = new Recipe () { + recipes [0] = new Recipe () { Name = "Cherry Cobbler", Description = "Cherry cobbler with homemade whipped cream", PrepTime = "1.5 hours", @@ -74,7 +72,7 @@ static Recipe[] CreateDemoData () }, }; - recipes[1] = new Recipe () { + recipes [1] = new Recipe () { Name = "Chocolate Cake", Description = "Chocolate cake with chocolate frosting", PrepTime = "1 hour", diff --git a/RegionDefiner/RegionDefiner/AppDelegate.cs b/RegionDefiner/RegionDefiner/AppDelegate.cs index 48a1ceaa5..1f4971af4 100644 --- a/RegionDefiner/RegionDefiner/AppDelegate.cs +++ b/RegionDefiner/RegionDefiner/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace RegionDefiner -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace RegionDefiner { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/RegionDefiner/RegionDefiner/Main.cs b/RegionDefiner/RegionDefiner/Main.cs index 972f1477c..aa487cf90 100644 --- a/RegionDefiner/RegionDefiner/Main.cs +++ b/RegionDefiner/RegionDefiner/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace RegionDefiner -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace RegionDefiner { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/RegionDefiner/RegionDefiner/MyAnnotation.cs b/RegionDefiner/RegionDefiner/MyAnnotation.cs index c9d9d89f6..8029d29aa 100644 --- a/RegionDefiner/RegionDefiner/MyAnnotation.cs +++ b/RegionDefiner/RegionDefiner/MyAnnotation.cs @@ -1,25 +1,23 @@ using CoreLocation; using MapKit; -namespace RegionDefiner -{ - public class MyAnnotation : MKAnnotation - { - private readonly CLLocationCoordinate2D coordinate; - private readonly string title; - private readonly string subtitle; +namespace RegionDefiner { + public class MyAnnotation : MKAnnotation { + private readonly CLLocationCoordinate2D coordinate; + private readonly string title; + private readonly string subtitle; - public MyAnnotation(CLLocationCoordinate2D coordinate, string title, string subtitle) - { - this.coordinate = coordinate; - this.title = title; - this.subtitle = subtitle; - } + public MyAnnotation (CLLocationCoordinate2D coordinate, string title, string subtitle) + { + this.coordinate = coordinate; + this.title = title; + this.subtitle = subtitle; + } - public override string Title => this.title; + public override string Title => this.title; - public override string Subtitle => this.subtitle; + public override string Subtitle => this.subtitle; - public override CLLocationCoordinate2D Coordinate => this.coordinate; - } -} \ No newline at end of file + public override CLLocationCoordinate2D Coordinate => this.coordinate; + } +} diff --git a/RegionDefiner/RegionDefiner/ViewController.cs b/RegionDefiner/RegionDefiner/ViewController.cs index 1d9275c8f..34e5d473a 100644 --- a/RegionDefiner/RegionDefiner/ViewController.cs +++ b/RegionDefiner/RegionDefiner/ViewController.cs @@ -1,4 +1,4 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; using MapKit; using System; @@ -7,117 +7,108 @@ using System.Text; using UIKit; -namespace RegionDefiner -{ - public partial class ViewController : UIViewController, IMKMapViewDelegate, IUIGestureRecognizerDelegate - { - private readonly List<MyAnnotation> items = new List<MyAnnotation>(); - - private MKPolygon polygon; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - mapView.Delegate = this; - } - - partial void Log(UIBarButtonItem sender) - { - if (items.Count < 3) - { - Console.WriteLine("Minimum of 3 vertices to make polygon"); - } - - var builder = new StringBuilder("\n{\n \"type\": \"MultiPolygon\",\n \"coordinates\":\n [[[\n"); - foreach (var item in items) - { - builder.AppendLine($"\t[{item.Coordinate.Longitude}, {item.Coordinate.Latitude}],"); - } - - // GeoJSON requires that the first and last vertices be identical - var first = items.First(); - builder.AppendLine($"\t[{first.Coordinate.Longitude}, {first.Coordinate.Latitude}]"); - builder.AppendLine(" ]]]\n}\n"); - - Console.WriteLine(builder); - } - - partial void Reset(UIBarButtonItem sender) - { - if (mapView.Annotations != null && polygon != null) - { - mapView.RemoveAnnotations(mapView.Annotations); - - items.Clear(); - UpdatePolygon(); - } - } - - private void UpdatePolygon() - { - var points = items.Select(item => item.Coordinate).ToArray(); - if (polygon != null) - { - mapView.RemoveOverlay(polygon); - polygon.Dispose(); - polygon = null; - } - - polygon = MKPolygon.FromCoordinates(points); - mapView.AddOverlay(polygon); - } - - #region IUIGestureRecognizerDelegate - - partial void HandleLongPress(UILongPressGestureRecognizer recognizer) - { - if (recognizer.State == UIGestureRecognizerState.Began) - { - var longPressPoint = recognizer.LocationInView(mapView); - DropPinAtPoint(longPressPoint); - } - } - - private void DropPinAtPoint(CGPoint pointToConvert) - { - var convertedPoint = mapView.ConvertPoint(pointToConvert, mapView); - - var pinTitle = $"Pin Number {items.Count}"; - var subCoordinates = $"{convertedPoint.Latitude},{convertedPoint.Longitude}"; - var droppedPin = new MyAnnotation(convertedPoint, pinTitle, subCoordinates); - - mapView.AddAnnotation(droppedPin); - items.Add(droppedPin); - UpdatePolygon(); - } - - #endregion - - #region IMKMapViewDelegate - - private MKPolygonRenderer polygonRenderer; - - [Export("mapView:rendererForOverlay:")] - public MKOverlayRenderer OverlayRenderer(MKMapView mapView, IMKOverlay overlay) - { - if (polygonRenderer != null && polygonRenderer.Polygon == polygon) - { - return polygonRenderer; - } - - polygon = overlay as MKPolygon; - polygonRenderer = new MKPolygonRenderer(polygon) - { - FillColor = new UIColor(0, 1, 0, .3f), - StrokeColor = new UIColor(0, 1, 0, 0.9f), - LineWidth = 1f - }; - - return polygonRenderer; - } - - #endregion - } -} \ No newline at end of file +namespace RegionDefiner { + public partial class ViewController : UIViewController, IMKMapViewDelegate, IUIGestureRecognizerDelegate { + private readonly List<MyAnnotation> items = new List<MyAnnotation> (); + + private MKPolygon polygon; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + mapView.Delegate = this; + } + + partial void Log (UIBarButtonItem sender) + { + if (items.Count < 3) { + Console.WriteLine ("Minimum of 3 vertices to make polygon"); + } + + var builder = new StringBuilder ("\n{\n \"type\": \"MultiPolygon\",\n \"coordinates\":\n [[[\n"); + foreach (var item in items) { + builder.AppendLine ($"\t[{item.Coordinate.Longitude}, {item.Coordinate.Latitude}],"); + } + + // GeoJSON requires that the first and last vertices be identical + var first = items.First (); + builder.AppendLine ($"\t[{first.Coordinate.Longitude}, {first.Coordinate.Latitude}]"); + builder.AppendLine (" ]]]\n}\n"); + + Console.WriteLine (builder); + } + + partial void Reset (UIBarButtonItem sender) + { + if (mapView.Annotations != null && polygon != null) { + mapView.RemoveAnnotations (mapView.Annotations); + + items.Clear (); + UpdatePolygon (); + } + } + + private void UpdatePolygon () + { + var points = items.Select (item => item.Coordinate).ToArray (); + if (polygon != null) { + mapView.RemoveOverlay (polygon); + polygon.Dispose (); + polygon = null; + } + + polygon = MKPolygon.FromCoordinates (points); + mapView.AddOverlay (polygon); + } + + #region IUIGestureRecognizerDelegate + + partial void HandleLongPress (UILongPressGestureRecognizer recognizer) + { + if (recognizer.State == UIGestureRecognizerState.Began) { + var longPressPoint = recognizer.LocationInView (mapView); + DropPinAtPoint (longPressPoint); + } + } + + private void DropPinAtPoint (CGPoint pointToConvert) + { + var convertedPoint = mapView.ConvertPoint (pointToConvert, mapView); + + var pinTitle = $"Pin Number {items.Count}"; + var subCoordinates = $"{convertedPoint.Latitude},{convertedPoint.Longitude}"; + var droppedPin = new MyAnnotation (convertedPoint, pinTitle, subCoordinates); + + mapView.AddAnnotation (droppedPin); + items.Add (droppedPin); + UpdatePolygon (); + } + + #endregion + + #region IMKMapViewDelegate + + private MKPolygonRenderer polygonRenderer; + + [Export ("mapView:rendererForOverlay:")] + public MKOverlayRenderer OverlayRenderer (MKMapView mapView, IMKOverlay overlay) + { + if (polygonRenderer != null && polygonRenderer.Polygon == polygon) { + return polygonRenderer; + } + + polygon = overlay as MKPolygon; + polygonRenderer = new MKPolygonRenderer (polygon) { + FillColor = new UIColor (0, 1, 0, .3f), + StrokeColor = new UIColor (0, 1, 0, 0.9f), + LineWidth = 1f + }; + + return polygonRenderer; + } + + #endregion + } +} diff --git a/RosyWriter/RosyWriter/AppDelegate.cs b/RosyWriter/RosyWriter/AppDelegate.cs index 7a776c569..c6d41adb2 100644 --- a/RosyWriter/RosyWriter/AppDelegate.cs +++ b/RosyWriter/RosyWriter/AppDelegate.cs @@ -1,23 +1,21 @@ -using Foundation; +using Foundation; using UIKit; -namespace RosyWriter -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace RosyWriter { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window { get; set; } + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/RosyWriter/RosyWriter/Helpers/RosyWriterPreview.cs b/RosyWriter/RosyWriter/Helpers/RosyWriterPreview.cs index 2a5917b7e..021b12bf6 100644 --- a/RosyWriter/RosyWriter/Helpers/RosyWriterPreview.cs +++ b/RosyWriter/RosyWriter/Helpers/RosyWriterPreview.cs @@ -1,300 +1,282 @@ -using CoreAnimation; +using CoreAnimation; using CoreGraphics; using CoreVideo; -using Foundation; +using Foundation; using ObjCRuntime; using OpenGLES; -using OpenTK.Graphics.ES20; -using System; -using UIKit; - -namespace RosyWriter -{ - public partial class RosyWriterPreview : UIView - { - // Open GL Stuff - private const int UNIFORM_Y = 0; - private const int UNIFORM_UV = 1; - private const int ATTRIB_VERTEX = 0; - private const int ATTRIB_TEXCOORD = 1; - - private readonly EAGLContext context; - private CVOpenGLESTextureCache videoTextureCache; - private uint frameBuffer, colorBuffer; - private int renderBufferWidth, renderBufferHeight; - - private int glProgram; - - public RosyWriterPreview(IntPtr handle) : base(handle) - { - // Initialize OpenGL ES 2 - var eagleLayer = Layer as CAEAGLLayer; - eagleLayer.Opaque = true; - eagleLayer.DrawableProperties = new NSDictionary(EAGLDrawableProperty.RetainedBacking, false, - EAGLDrawableProperty.ColorFormat, EAGLColorFormat.RGBA8); - - context = new EAGLContext(EAGLRenderingAPI.OpenGLES2); - if (!EAGLContext.SetCurrentContext(context)) - { - throw new ApplicationException("Could not set EAGLContext"); - } - } - - [Export("layerClass")] - public static Class LayerClass() - { - return new Class(typeof(CAEAGLLayer)); - } - - #region Setup - - private bool CreateFrameBuffer() - { - var success = true; - - GL.Disable(EnableCap.DepthTest); - - GL.GenFramebuffers(1, out frameBuffer); - GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer); - - GL.GenRenderbuffers(1, out colorBuffer); - GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, colorBuffer); - - context.RenderBufferStorage((uint)All.Renderbuffer, (CAEAGLLayer)Layer); - - GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out renderBufferWidth); - GL.GetRenderbufferParameter(RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out renderBufferHeight); - - GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, RenderbufferTarget.Renderbuffer, colorBuffer); - - if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) - { - Console.WriteLine("Failure with framebuffer generation"); - success = false; - } - - // Create a new CVOpenGLESTexture Cache - videoTextureCache = CVOpenGLESTextureCache.FromEAGLContext(context); - - glProgram = CreateProgram(); - - return success && (glProgram != 0); - } - - private static int CreateProgram() - { - // Create shader program - int program = GL.CreateProgram(); - - // Create and Compile Vertex Shader - int vertShader = 0; - int fragShader = 0; - var success = true; - success = success && CompileShader(out vertShader, ShaderType.VertexShader, "Shaders/passThrough.vsh"); - - // Create and Compile fragment shader - success = success && CompileShader(out fragShader, ShaderType.FragmentShader, "Shaders/passThrough.fsh"); - - // Attach Vertext Shader - GL.AttachShader(program, vertShader); - - // Attach fragment shader - GL.AttachShader(program, fragShader); - - // Bind attribute locations - GL.BindAttribLocation(program, ATTRIB_VERTEX, "position"); - GL.BindAttribLocation(program, ATTRIB_TEXCOORD, "textureCoordinate"); - - // Link program - success = success && LinkProgram(program); - if (success) - { - // Delete these ones, we do not need them anymore - GL.DeleteShader(vertShader); - GL.DeleteShader(fragShader); - } - else - { - Console.WriteLine("Failed to compile and link the shader programs"); - GL.DeleteProgram(program); - program = 0; - } - - return program; - } - - private static bool LinkProgram(int program) - { - GL.LinkProgram(program); - GL.GetProgram(program, ProgramParameter.LinkStatus, out int status); - - if (status == 0) - { - GL.GetProgram(program, ProgramParameter.InfoLogLength, out int len); - var sb = new System.Text.StringBuilder(len); - GL.GetProgramInfoLog(program, len, out len, sb); - Console.WriteLine("Link error: {0}", sb); - } - return status != 0; - } - - private static bool CompileShader(out int shader, ShaderType type, string path) - { - string shaderProgram = System.IO.File.ReadAllText(path); - int len = shaderProgram.Length; - shader = GL.CreateShader(type); - - GL.ShaderSource(shader, 1, new[] { shaderProgram }, ref len); - GL.CompileShader(shader); - GL.GetShader(shader, ShaderParameter.CompileStatus, out int status); - - if (status == 0) - { - GL.DeleteShader(shader); - return false; - } - - return true; - } - - #endregion - - #region Rendering - - public void DisplayPixelBuffer(CVImageBuffer imageBuffer) - { - // First check to make sure we have a FrameBuffer to write to. - if (frameBuffer == 0) - { - var success = CreateFrameBuffer(); - if (!success) - { - Console.WriteLine("Problem initializing OpenGL buffers."); - return; - } - } - - if (videoTextureCache == null) - { - Console.WriteLine("Video Texture Cache not initialized"); - return; - } - - if (!(imageBuffer is CVPixelBuffer pixelBuffer)) - { - Console.WriteLine("Could not get Pixel Buffer from Image Buffer"); - return; - } - - // Create a CVOpenGLESTexture from the CVImageBuffer - var frameWidth = (int)pixelBuffer.Width; - var frameHeight = (int)pixelBuffer.Height; - - using (var texture = videoTextureCache.TextureFromImage(imageBuffer, true, All.Rgba, frameWidth, frameHeight, All.Bgra, DataType.UnsignedByte, 0, out CVReturn ret)) - { - if (texture == null || ret != CVReturn.Success) - { - Console.WriteLine("Could not create Texture from Texture Cache"); - return; - } - - GL.BindTexture(texture.Target, texture.Name); - - // Set texture parameters - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBuffer); - - // Set the view port to the entire view - GL.Viewport(0, 0, renderBufferWidth, renderBufferHeight); - - var squareVerticies = new float[,] - { - { -1.0F, -1.0F}, - { 1.0F, -1.0F }, - { -1.0F, 1.0F }, - { 1.0F, 1.0F } - }; - - // The texture verticies are setup such that we flip the texture vertically. - // This is so that our top left origin buffers match OpenGL's bottom left texture coordinate system. - var textureSamplingRect = TextureSamplingRectForCroppingTextureWithAspectRatio(new CGSize(frameWidth, frameHeight), Bounds.Size); - - var textureVertices = new float[,] - { - {(float)textureSamplingRect.Left, (float)textureSamplingRect.Bottom}, - {(float)textureSamplingRect.Right, (float)textureSamplingRect.Bottom}, - {(float)textureSamplingRect.Left, (float)textureSamplingRect.Top}, - {(float)textureSamplingRect.Right, (float)textureSamplingRect.Top} - }; - - // Draw the texture on the screen with OpenGL ES 2 - RenderWithSquareVerticies(squareVerticies, textureVertices); - - GL.BindTexture(texture.Target, texture.Name); - - // Flush the CVOpenGLESTexture cache and release the texture - videoTextureCache.Flush(CVOptionFlags.None); - } - } - - private static CGRect TextureSamplingRectForCroppingTextureWithAspectRatio(CGSize textureAspectRatio, CGSize croppingAspectRatio) - { - CGRect normalizedSamplingRect; - var cropScaleAmount = new CGSize(croppingAspectRatio.Width / textureAspectRatio.Width, croppingAspectRatio.Height / textureAspectRatio.Height); - var maxScale = Math.Max(cropScaleAmount.Width, cropScaleAmount.Height); - - // HACK: double to nfloat - var scaledTextureSize = new CGSize((nfloat)(textureAspectRatio.Width * maxScale), (nfloat)(textureAspectRatio.Height * maxScale)); - - // Changed the floats width, height to nfloats - nfloat width, height; - if (cropScaleAmount.Height > cropScaleAmount.Width) - { - width = croppingAspectRatio.Width / scaledTextureSize.Width; - height = 1f; - normalizedSamplingRect = new CGRect(0, 0, width, height); - } - else - { - height = croppingAspectRatio.Height / scaledTextureSize.Height; - width = 1f; - normalizedSamplingRect = new CGRect(0, 0, height, width); - } - - // Center crop - normalizedSamplingRect.X = (1f - normalizedSamplingRect.Size.Width) / 2f; - normalizedSamplingRect.Y = (1f - normalizedSamplingRect.Size.Height) / 2f; - - return normalizedSamplingRect; - } - - private void RenderWithSquareVerticies(float[,] squareVerticies, float[,] textureVerticies) - { - // Use Shader Program - GL.UseProgram(glProgram); - - // Update attribute values - GL.VertexAttribPointer(ATTRIB_VERTEX, 2, VertexAttribPointerType.Float, false, 0, squareVerticies); - GL.EnableVertexAttribArray(ATTRIB_VERTEX); - - GL.VertexAttribPointer(ATTRIB_TEXCOORD, 2, VertexAttribPointerType.Float, false, 0, textureVerticies); - GL.EnableVertexAttribArray(ATTRIB_TEXCOORD); - - // Validate program before drawing. (For Debugging purposes) -#if DEBUG - GL.ValidateProgram(glProgram); -#endif - GL.DrawArrays(BeginMode.TriangleStrip, 0, 4); - - // Present - GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, colorBuffer); - context.PresentRenderBuffer((uint)All.Renderbuffer); - } - - #endregion - } -} \ No newline at end of file +using OpenTK.Graphics.ES20; +using System; +using UIKit; + +namespace RosyWriter { + public partial class RosyWriterPreview : UIView { + // Open GL Stuff + private const int UNIFORM_Y = 0; + private const int UNIFORM_UV = 1; + private const int ATTRIB_VERTEX = 0; + private const int ATTRIB_TEXCOORD = 1; + + private readonly EAGLContext context; + private CVOpenGLESTextureCache videoTextureCache; + private uint frameBuffer, colorBuffer; + private int renderBufferWidth, renderBufferHeight; + + private int glProgram; + + public RosyWriterPreview (IntPtr handle) : base (handle) + { + // Initialize OpenGL ES 2 + var eagleLayer = Layer as CAEAGLLayer; + eagleLayer.Opaque = true; + eagleLayer.DrawableProperties = new NSDictionary (EAGLDrawableProperty.RetainedBacking, false, + EAGLDrawableProperty.ColorFormat, EAGLColorFormat.RGBA8); + + context = new EAGLContext (EAGLRenderingAPI.OpenGLES2); + if (!EAGLContext.SetCurrentContext (context)) { + throw new ApplicationException ("Could not set EAGLContext"); + } + } + + [Export ("layerClass")] + public static Class LayerClass () + { + return new Class (typeof (CAEAGLLayer)); + } + + #region Setup + + private bool CreateFrameBuffer () + { + var success = true; + + GL.Disable (EnableCap.DepthTest); + + GL.GenFramebuffers (1, out frameBuffer); + GL.BindFramebuffer (FramebufferTarget.Framebuffer, frameBuffer); + + GL.GenRenderbuffers (1, out colorBuffer); + GL.BindRenderbuffer (RenderbufferTarget.Renderbuffer, colorBuffer); + + context.RenderBufferStorage ((uint) All.Renderbuffer, (CAEAGLLayer) Layer); + + GL.GetRenderbufferParameter (RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out renderBufferWidth); + GL.GetRenderbufferParameter (RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out renderBufferHeight); + + GL.FramebufferRenderbuffer (FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, RenderbufferTarget.Renderbuffer, colorBuffer); + + if (GL.CheckFramebufferStatus (FramebufferTarget.Framebuffer) != FramebufferErrorCode.FramebufferComplete) { + Console.WriteLine ("Failure with framebuffer generation"); + success = false; + } + + // Create a new CVOpenGLESTexture Cache + videoTextureCache = CVOpenGLESTextureCache.FromEAGLContext (context); + + glProgram = CreateProgram (); + + return success && (glProgram != 0); + } + + private static int CreateProgram () + { + // Create shader program + int program = GL.CreateProgram (); + + // Create and Compile Vertex Shader + int vertShader = 0; + int fragShader = 0; + var success = true; + success = success && CompileShader (out vertShader, ShaderType.VertexShader, "Shaders/passThrough.vsh"); + + // Create and Compile fragment shader + success = success && CompileShader (out fragShader, ShaderType.FragmentShader, "Shaders/passThrough.fsh"); + + // Attach Vertext Shader + GL.AttachShader (program, vertShader); + + // Attach fragment shader + GL.AttachShader (program, fragShader); + + // Bind attribute locations + GL.BindAttribLocation (program, ATTRIB_VERTEX, "position"); + GL.BindAttribLocation (program, ATTRIB_TEXCOORD, "textureCoordinate"); + + // Link program + success = success && LinkProgram (program); + if (success) { + // Delete these ones, we do not need them anymore + GL.DeleteShader (vertShader); + GL.DeleteShader (fragShader); + } else { + Console.WriteLine ("Failed to compile and link the shader programs"); + GL.DeleteProgram (program); + program = 0; + } + + return program; + } + + private static bool LinkProgram (int program) + { + GL.LinkProgram (program); + GL.GetProgram (program, ProgramParameter.LinkStatus, out int status); + + if (status == 0) { + GL.GetProgram (program, ProgramParameter.InfoLogLength, out int len); + var sb = new System.Text.StringBuilder (len); + GL.GetProgramInfoLog (program, len, out len, sb); + Console.WriteLine ("Link error: {0}", sb); + } + return status != 0; + } + + private static bool CompileShader (out int shader, ShaderType type, string path) + { + string shaderProgram = System.IO.File.ReadAllText (path); + int len = shaderProgram.Length; + shader = GL.CreateShader (type); + + GL.ShaderSource (shader, 1, new [] { shaderProgram }, ref len); + GL.CompileShader (shader); + GL.GetShader (shader, ShaderParameter.CompileStatus, out int status); + + if (status == 0) { + GL.DeleteShader (shader); + return false; + } + + return true; + } + + #endregion + + #region Rendering + + public void DisplayPixelBuffer (CVImageBuffer imageBuffer) + { + // First check to make sure we have a FrameBuffer to write to. + if (frameBuffer == 0) { + var success = CreateFrameBuffer (); + if (!success) { + Console.WriteLine ("Problem initializing OpenGL buffers."); + return; + } + } + + if (videoTextureCache == null) { + Console.WriteLine ("Video Texture Cache not initialized"); + return; + } + + if (!(imageBuffer is CVPixelBuffer pixelBuffer)) { + Console.WriteLine ("Could not get Pixel Buffer from Image Buffer"); + return; + } + + // Create a CVOpenGLESTexture from the CVImageBuffer + var frameWidth = (int) pixelBuffer.Width; + var frameHeight = (int) pixelBuffer.Height; + + using (var texture = videoTextureCache.TextureFromImage (imageBuffer, true, All.Rgba, frameWidth, frameHeight, All.Bgra, DataType.UnsignedByte, 0, out CVReturn ret)) { + if (texture == null || ret != CVReturn.Success) { + Console.WriteLine ("Could not create Texture from Texture Cache"); + return; + } + + GL.BindTexture (texture.Target, texture.Name); + + // Set texture parameters + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); + + GL.BindFramebuffer (FramebufferTarget.Framebuffer, frameBuffer); + + // Set the view port to the entire view + GL.Viewport (0, 0, renderBufferWidth, renderBufferHeight); + + var squareVerticies = new float [,] + { + { -1.0F, -1.0F}, + { 1.0F, -1.0F }, + { -1.0F, 1.0F }, + { 1.0F, 1.0F } + }; + + // The texture verticies are setup such that we flip the texture vertically. + // This is so that our top left origin buffers match OpenGL's bottom left texture coordinate system. + var textureSamplingRect = TextureSamplingRectForCroppingTextureWithAspectRatio (new CGSize (frameWidth, frameHeight), Bounds.Size); + + var textureVertices = new float [,] + { + {(float)textureSamplingRect.Left, (float)textureSamplingRect.Bottom}, + {(float)textureSamplingRect.Right, (float)textureSamplingRect.Bottom}, + {(float)textureSamplingRect.Left, (float)textureSamplingRect.Top}, + {(float)textureSamplingRect.Right, (float)textureSamplingRect.Top} + }; + + // Draw the texture on the screen with OpenGL ES 2 + RenderWithSquareVerticies (squareVerticies, textureVertices); + + GL.BindTexture (texture.Target, texture.Name); + + // Flush the CVOpenGLESTexture cache and release the texture + videoTextureCache.Flush (CVOptionFlags.None); + } + } + + private static CGRect TextureSamplingRectForCroppingTextureWithAspectRatio (CGSize textureAspectRatio, CGSize croppingAspectRatio) + { + CGRect normalizedSamplingRect; + var cropScaleAmount = new CGSize (croppingAspectRatio.Width / textureAspectRatio.Width, croppingAspectRatio.Height / textureAspectRatio.Height); + var maxScale = Math.Max (cropScaleAmount.Width, cropScaleAmount.Height); + + // HACK: double to nfloat + var scaledTextureSize = new CGSize ((nfloat) (textureAspectRatio.Width * maxScale), (nfloat) (textureAspectRatio.Height * maxScale)); + + // Changed the floats width, height to nfloats + nfloat width, height; + if (cropScaleAmount.Height > cropScaleAmount.Width) { + width = croppingAspectRatio.Width / scaledTextureSize.Width; + height = 1f; + normalizedSamplingRect = new CGRect (0, 0, width, height); + } else { + height = croppingAspectRatio.Height / scaledTextureSize.Height; + width = 1f; + normalizedSamplingRect = new CGRect (0, 0, height, width); + } + + // Center crop + normalizedSamplingRect.X = (1f - normalizedSamplingRect.Size.Width) / 2f; + normalizedSamplingRect.Y = (1f - normalizedSamplingRect.Size.Height) / 2f; + + return normalizedSamplingRect; + } + + private void RenderWithSquareVerticies (float [,] squareVerticies, float [,] textureVerticies) + { + // Use Shader Program + GL.UseProgram (glProgram); + + // Update attribute values + GL.VertexAttribPointer (ATTRIB_VERTEX, 2, VertexAttribPointerType.Float, false, 0, squareVerticies); + GL.EnableVertexAttribArray (ATTRIB_VERTEX); + + GL.VertexAttribPointer (ATTRIB_TEXCOORD, 2, VertexAttribPointerType.Float, false, 0, textureVerticies); + GL.EnableVertexAttribArray (ATTRIB_TEXCOORD); + + // Validate program before drawing. (For Debugging purposes) +#if DEBUG + GL.ValidateProgram(glProgram); +#endif + GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); + + // Present + GL.BindRenderbuffer (RenderbufferTarget.Renderbuffer, colorBuffer); + context.PresentRenderBuffer ((uint) All.Renderbuffer); + } + + #endregion + } +} diff --git a/RosyWriter/RosyWriter/Helpers/RosyWriterVideoProcessor.cs b/RosyWriter/RosyWriter/Helpers/RosyWriterVideoProcessor.cs index 2f4e48dd0..04599926f 100644 --- a/RosyWriter/RosyWriter/Helpers/RosyWriterVideoProcessor.cs +++ b/RosyWriter/RosyWriter/Helpers/RosyWriterVideoProcessor.cs @@ -12,694 +12,619 @@ using System.IO; using UIKit; -namespace RosyWriter.Helpers -{ - public delegate void RosyWriterVideoProcessorDelegate(); - - public class RosyWriterVideoProcessor : NSObject, IAVCaptureVideoDataOutputSampleBufferDelegate, IAVCaptureAudioDataOutputSampleBufferDelegate - { - private const int BYTES_PER_PIXEL = 4; - - // Only Accessed on movie writing Queue - private bool readyToRecordAudio; - private bool readyToRecordVideo; - private bool recordingWillBeStarted; - private bool recordingWillBeStopped; - - private readonly NSUrl movieUrl; - - private AVCaptureSession captureSession; - private AVCaptureConnection videoConnection; - private AVCaptureConnection audioConnection; - - private AVAssetWriter assetWriter; - private AVAssetWriterInput assetWriterAudioIn; - private AVAssetWriterInput assetWriterVideoIn; - - private readonly List<CMTime> previousSecondTimestamps = new List<CMTime>(); - private AVCaptureVideoOrientation videoOrientation; - - private DispatchQueue movieWritingQueue; - private CMBufferQueue previewBufferQueue; - - public event Action RecordingDidStart; - public event Action RecordingWillStop; - public event Action RecordingDidStop; - public event Action<CVImageBuffer> PixelBufferReadyForDisplay; - public event Action RecordingWillStart; - - public RosyWriterVideoProcessor() - { - ReferenceOrientation = AVCaptureVideoOrientation.Portrait; - - // The temp path for the video before saving it to photo album - movieUrl = NSUrl.FromFilename(Path.Combine(Path.GetTempPath(), "Movie.MOV")); - } - - public AVCaptureVideoOrientation ReferenceOrientation { get; set; } - - public bool IsRecording { get; private set; } - - public double VideoFrameRate { get; private set; } - - public CGSize VideoDimensions { get; private set; } - - public uint VideoType { get; private set; } - - private static void RemoveFile(NSUrl fileUrl) - { - var filePath = fileUrl?.Path; - if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) - { - File.Delete(filePath); - } - } - - private static float AngleOffsetFromPortraitOrientationToOrientation(AVCaptureVideoOrientation orientation) - { - switch (orientation) - { - case AVCaptureVideoOrientation.LandscapeRight: - return (float)(-Math.PI / 2d); - case AVCaptureVideoOrientation.LandscapeLeft: - return (float)(Math.PI / 2d); - case AVCaptureVideoOrientation.PortraitUpsideDown: - return (float)Math.PI; - //case AVCaptureVideoOrientation.Portrait: - default: - return 0f; - } - } - - /// <summary> - /// Saves the movie to the camera roll. - /// </summary> - private void SaveMovieToCameraRoll() - { - //Console.WriteLine ("Save movie to camera roll"); - using (var library = new ALAssetsLibrary()) - { - library.WriteVideoToSavedPhotosAlbum(movieUrl, (assetUrl, error) => - { - if (error != null) - { - ShowError(error); - } - else - { - RemoveFile(movieUrl); - } - - movieWritingQueue.DispatchAsync(() => - { - recordingWillBeStopped = false; - IsRecording = false; - RecordingDidStop?.Invoke(); - }); - }); - } - } - - /// <summary> - /// Creates a Transform to apply to the OpenGL view to display the Video at the proper orientation - /// </summary> - /// <returns> A transform to correct the orientation</returns> - /// <param name='orientation'>Current Orientation</param> - public CGAffineTransform TransformFromCurrentVideoOrientationToOrientation(AVCaptureVideoOrientation orientation) - { - // Calculate offsets from an arbitrary reference orientation (portrait) - var orientationAngleOffset = AngleOffsetFromPortraitOrientationToOrientation(orientation); - var videoOrientationAngleOffset = AngleOffsetFromPortraitOrientationToOrientation(videoOrientation); - - // Find the difference in angle between the passed in orientation and the current video orientation - var angleOffset = orientationAngleOffset - videoOrientationAngleOffset; - return CGAffineTransform.MakeRotation(angleOffset); - } - - private void WriteSampleBuffer(CMSampleBuffer sampleBuffer, NSString mediaType) - { - if (assetWriter.Status == AVAssetWriterStatus.Unknown) - { - if (assetWriter.StartWriting()) - { - assetWriter.StartSessionAtSourceTime(sampleBuffer.OutputPresentationTimeStamp); - } - else - { - ShowError(assetWriter.Error); - } - } - - if (assetWriter.Status == AVAssetWriterStatus.Writing) - { - if (mediaType == AVMediaType.Video) - { - if (assetWriterVideoIn.ReadyForMoreMediaData) - { - if (!assetWriterVideoIn.AppendSampleBuffer(sampleBuffer)) - { - ShowError(assetWriter.Error); - } - } - } - else if (mediaType == AVMediaType.Audio) - { - if (assetWriterAudioIn.ReadyForMoreMediaData) - { - if (!assetWriterAudioIn.AppendSampleBuffer(sampleBuffer)) - { - ShowError(assetWriter.Error); - } - } - } - } - } - - #region Recording - - /// <summary> - /// Starts the recording. - /// </summary> - public void StartRecording() - { - //Console.WriteLine ("Start Recording"); - movieWritingQueue.DispatchAsync(() => - { - if (recordingWillBeStarted || IsRecording) - return; - - recordingWillBeStarted = true; - - // recordingDidStart is called from captureOutput.DidOutputSampleBuffer.FromeConnection one the asset writere is setup - RecordingWillStart?.Invoke(); - - // Remove the file if one with the same name already exists - RemoveFile(movieUrl); - - // Create an asset writer - assetWriter = new AVAssetWriter(movieUrl, AVFileType.QuickTimeMovie, out NSError error); - if (error != null) - { - ShowError(error); - } - }); - } - - public void StopRecording() - { - movieWritingQueue.DispatchAsync(() => - { - if (recordingWillBeStopped || !IsRecording) - return; - - recordingWillBeStopped = true; - - // recordingDidStop is called from saveMovieToCameraRoll - RecordingWillStop?.Invoke(); - - if (assetWriter.FinishWriting()) - { - if (assetWriterAudioIn != null) - { - assetWriterAudioIn.Dispose(); - assetWriterAudioIn = null; - } - - if (assetWriterVideoIn != null) - { - assetWriterVideoIn.Dispose(); - assetWriterVideoIn = null; - } - - lock (inUse) - { - assetWriter.Dispose(); - assetWriter = null; - - // Clear the 'Inuse' list when we're creating a new Recording session. - inUse.Clear(); - } - - readyToRecordVideo = false; - readyToRecordAudio = false; - - SaveMovieToCameraRoll(); - } - else - { - ShowError(assetWriter.Error); - } - }); - } - - #endregion - - #region Capture - - private readonly List<CMSampleBuffer> inUse = new List<CMSampleBuffer>(); - - // This is used to solve the issue with the movieWriter queue and the DisplayPixelBuffer - // thread not releasing CMSampleBuffers when - private void CompleteBufferUse(CMSampleBuffer buffer) - { - lock (inUse) - { - if (inUse.Contains(buffer)) - { - inUse.Remove(buffer); - buffer.Dispose(); - } - else - { - inUse.Add(buffer); - } - } - } - - /// <summary> - /// Videos the device available for passed in position. - /// </summary> - /// <returns> - /// The available device - /// </returns> - /// <param name='position'> The desired Position.</param> - private static AVCaptureDevice VideoDeviceWithPosition(AVCaptureDevicePosition position) - { - var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); - foreach (var device in devices) - { - if (device.Position == position) - return device; - } - return null; - } - - /// <summary> - /// Returns an audio device - /// </summary> - /// <returns> The audio device.</returns> - private static AVCaptureDevice AudioDevice() - { - var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Audio); - return (devices.Length == 0) ? null : devices[0]; - } - - private bool SetupCaptureSession() - { - // Overview: RosyWriter uses separate GCD queues for audio and video capture. If a single GCD queue - // is used to deliver both audio and video buffers, and our video processing consistently takes - // too long, the delivery queue can back up, resulting in audio being dropped. - // - // When recording, RosyWriter creates a third GCD queue for calls to AVAssetWriter. This ensures - // that AVAssetWriter is not called to start or finish writing from multiple threads simultaneously. - // - // RosyWriter uses AVCaptureSession's default preset, AVCaptureSessionPresetHigh. - - // Create Capture session - captureSession = new AVCaptureSession(); - captureSession.BeginConfiguration(); - - // Create audio connection - var audioDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Audio); - if (audioDevice == null) - return false; // e.g. simulator - - var audioIn = new AVCaptureDeviceInput(audioDevice, out NSError error); - if (captureSession.CanAddInput(audioIn)) - captureSession.AddInput(audioIn); - - var audioOut = new AVCaptureAudioDataOutput(); - var audioCaptureQueue = new DispatchQueue("Audio Capture Queue"); - - // Add the Delegate to capture each sample that comes through - audioOut.SetSampleBufferDelegateQueue(this, audioCaptureQueue); - - if (captureSession.CanAddOutput(audioOut)) - captureSession.AddOutput(audioOut); - - audioConnection = audioOut.ConnectionFromMediaType(AVMediaType.Audio); - - // Create Video Session - var videoDevice = VideoDeviceWithPosition(AVCaptureDevicePosition.Back); - var videoIn = new AVCaptureDeviceInput(videoDevice, out error); - - if (captureSession.CanAddInput(videoIn)) - captureSession.AddInput(videoIn); - - // RosyWriter prefers to discard late video frames early in the capture pipeline, since its - // processing can take longer than real-time on some platforms (such as iPhone 3GS). - // Clients whose image processing is faster than real-time should consider setting AVCaptureVideoDataOutput's - // alwaysDiscardsLateVideoFrames property to NO. - var videoOut = new AVCaptureVideoDataOutput - { - AlwaysDiscardsLateVideoFrames = true, - // HACK: Change VideoSettings to WeakVideoSettings, and AVVideoSettings to CVPixelBufferAttributes - // VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA) - WeakVideoSettings = new CVPixelBufferAttributes - { - PixelFormatType = CVPixelFormatType.CV32BGRA - }.Dictionary - }; - - // Create a DispatchQueue for the Video Processing - var videoCaptureQueue = new DispatchQueue("Video Capture Queue"); - videoOut.SetSampleBufferDelegateQueue(this, videoCaptureQueue); - - if (captureSession.CanAddOutput(videoOut)) - captureSession.AddOutput(videoOut); - - // Set the Video connection from the Video Output object - videoConnection = videoOut.ConnectionFromMediaType(AVMediaType.Video); - videoOrientation = videoConnection.VideoOrientation; - - captureSession.CommitConfiguration(); - - return true; - } - - public bool SetupAndStartCaptureSession() - { - // Create a shallow queue for buffers going to the display for preview. - previewBufferQueue = CMBufferQueue.CreateUnsorted(1); - - // Create serial queue for movie writing - movieWritingQueue = new DispatchQueue("Movie Writing Queue"); - - var isSupported = true; - if (captureSession == null) - { - isSupported = SetupCaptureSession(); - } - - NSNotificationCenter.DefaultCenter.AddObserver(AVCaptureSession.DidStopRunningNotification, CaptureSessionStoppedRunningNotification, captureSession); - - if (!captureSession.Running) - { - if (isSupported) - { - captureSession.StartRunning(); - } - else - { - StopAndTearDownCaptureSession(); - } - } - - return isSupported; - } - - public void CaptureSessionStoppedRunningNotification(NSNotification notification) - { - movieWritingQueue.DispatchAsync(() => - { - if (IsRecording) - { - StopRecording(); - } - }); - } - - public void PauseCaptureSession() - { - if (captureSession.Running) - { - captureSession.StopRunning(); - } - } - - public void ResumeCaptureSession() - { - if (!captureSession.Running) - { - captureSession.StartRunning(); - } - } - - /// <summary> - /// Stops the and tears down the capture session. - /// </summary> - public void StopAndTearDownCaptureSession() - { - if (captureSession != null) - { - if (captureSession.Running) - { - captureSession.StopRunning(); - } - - NSNotificationCenter.DefaultCenter.RemoveObserver(this, AVCaptureSession.DidStopRunningNotification, captureSession); - - captureSession.Dispose(); - captureSession = null; - } - - if (previewBufferQueue != null) - { - previewBufferQueue.Dispose(); - previewBufferQueue = null; - } - - if (movieWritingQueue != null) - { - movieWritingQueue.Dispose(); - movieWritingQueue = null; - } - } - - #endregion - - public void ShowError(NSError error) - { - InvokeOnMainThread(() => - { - var alert = UIAlertController.Create(error.LocalizedDescription, error.ToString(), UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - UIApplication.SharedApplication.Windows[0].RootViewController.PresentViewController(alert, true, null); - }); - } - - #region AVCapture[Audio|Video]DataOutputSampleBufferDelegate - - [Export("captureOutput:didOutputSampleBuffer:fromConnection:")] - public virtual void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) - { - // HACK: Change CMSampleBuffer.GetFormatDescription() to CMSampleBuffer.GetVideoFormatDescription() - // HACK Change CMFormatDescription to CMVideoFormatDescription - // CMFormatDescription formatDescription = sampleBuffer.GetFormatDescription (); - CMVideoFormatDescription formatDescription = sampleBuffer.GetVideoFormatDescription(); - - if (connection == videoConnection) - { - // Get framerate - CMTime timestamp = sampleBuffer.PresentationTimeStamp; - CalculateFramerateAtTimestamp(timestamp); - - // Get frame dimensions (for onscreen display) - if (VideoDimensions.IsEmpty) - // HACK: Change GetVideoPresentationDimensions() to GetPresentationDimensions() - // VideoDimensions = formatDescription.GetVideoPresentationDimensions (true, false); - VideoDimensions = formatDescription.GetPresentationDimensions(true, false); - - // Get the buffer type - if (VideoType == 0) - VideoType = formatDescription.MediaSubType; - - // Synchronously process the pixel buffer to de-green it. - using (var pixelBuffer = sampleBuffer.GetImageBuffer()) - ProcessPixelBuffer(pixelBuffer); - - previewBufferQueue.Enqueue(sampleBuffer); - - //var writeBuffer = sampleBuffer.Duplicate (); - InvokeOnMainThread(() => - { - INativeObject j = previewBufferQueue.Dequeue(); - if (!(j is CMSampleBuffer sbuf)) - { +namespace RosyWriter.Helpers { + public delegate void RosyWriterVideoProcessorDelegate (); + + public class RosyWriterVideoProcessor : NSObject, IAVCaptureVideoDataOutputSampleBufferDelegate, IAVCaptureAudioDataOutputSampleBufferDelegate { + private const int BYTES_PER_PIXEL = 4; + + // Only Accessed on movie writing Queue + private bool readyToRecordAudio; + private bool readyToRecordVideo; + private bool recordingWillBeStarted; + private bool recordingWillBeStopped; + + private readonly NSUrl movieUrl; + + private AVCaptureSession captureSession; + private AVCaptureConnection videoConnection; + private AVCaptureConnection audioConnection; + + private AVAssetWriter assetWriter; + private AVAssetWriterInput assetWriterAudioIn; + private AVAssetWriterInput assetWriterVideoIn; + + private readonly List<CMTime> previousSecondTimestamps = new List<CMTime> (); + private AVCaptureVideoOrientation videoOrientation; + + private DispatchQueue movieWritingQueue; + private CMBufferQueue previewBufferQueue; + + public event Action RecordingDidStart; + public event Action RecordingWillStop; + public event Action RecordingDidStop; + public event Action<CVImageBuffer> PixelBufferReadyForDisplay; + public event Action RecordingWillStart; + + public RosyWriterVideoProcessor () + { + ReferenceOrientation = AVCaptureVideoOrientation.Portrait; + + // The temp path for the video before saving it to photo album + movieUrl = NSUrl.FromFilename (Path.Combine (Path.GetTempPath (), "Movie.MOV")); + } + + public AVCaptureVideoOrientation ReferenceOrientation { get; set; } + + public bool IsRecording { get; private set; } + + public double VideoFrameRate { get; private set; } + + public CGSize VideoDimensions { get; private set; } + + public uint VideoType { get; private set; } + + private static void RemoveFile (NSUrl fileUrl) + { + var filePath = fileUrl?.Path; + if (!string.IsNullOrEmpty (filePath) && File.Exists (filePath)) { + File.Delete (filePath); + } + } + + private static float AngleOffsetFromPortraitOrientationToOrientation (AVCaptureVideoOrientation orientation) + { + switch (orientation) { + case AVCaptureVideoOrientation.LandscapeRight: + return (float) (-Math.PI / 2d); + case AVCaptureVideoOrientation.LandscapeLeft: + return (float) (Math.PI / 2d); + case AVCaptureVideoOrientation.PortraitUpsideDown: + return (float) Math.PI; + //case AVCaptureVideoOrientation.Portrait: + default: + return 0f; + } + } + + /// <summary> + /// Saves the movie to the camera roll. + /// </summary> + private void SaveMovieToCameraRoll () + { + //Console.WriteLine ("Save movie to camera roll"); + using (var library = new ALAssetsLibrary ()) { + library.WriteVideoToSavedPhotosAlbum (movieUrl, (assetUrl, error) => { + if (error != null) { + ShowError (error); + } else { + RemoveFile (movieUrl); + } + + movieWritingQueue.DispatchAsync (() => { + recordingWillBeStopped = false; + IsRecording = false; + RecordingDidStop?.Invoke (); + }); + }); + } + } + + /// <summary> + /// Creates a Transform to apply to the OpenGL view to display the Video at the proper orientation + /// </summary> + /// <returns> A transform to correct the orientation</returns> + /// <param name='orientation'>Current Orientation</param> + public CGAffineTransform TransformFromCurrentVideoOrientationToOrientation (AVCaptureVideoOrientation orientation) + { + // Calculate offsets from an arbitrary reference orientation (portrait) + var orientationAngleOffset = AngleOffsetFromPortraitOrientationToOrientation (orientation); + var videoOrientationAngleOffset = AngleOffsetFromPortraitOrientationToOrientation (videoOrientation); + + // Find the difference in angle between the passed in orientation and the current video orientation + var angleOffset = orientationAngleOffset - videoOrientationAngleOffset; + return CGAffineTransform.MakeRotation (angleOffset); + } + + private void WriteSampleBuffer (CMSampleBuffer sampleBuffer, NSString mediaType) + { + if (assetWriter.Status == AVAssetWriterStatus.Unknown) { + if (assetWriter.StartWriting ()) { + assetWriter.StartSessionAtSourceTime (sampleBuffer.OutputPresentationTimeStamp); + } else { + ShowError (assetWriter.Error); + } + } + + if (assetWriter.Status == AVAssetWriterStatus.Writing) { + if (mediaType == AVMediaType.Video) { + if (assetWriterVideoIn.ReadyForMoreMediaData) { + if (!assetWriterVideoIn.AppendSampleBuffer (sampleBuffer)) { + ShowError (assetWriter.Error); + } + } + } else if (mediaType == AVMediaType.Audio) { + if (assetWriterAudioIn.ReadyForMoreMediaData) { + if (!assetWriterAudioIn.AppendSampleBuffer (sampleBuffer)) { + ShowError (assetWriter.Error); + } + } + } + } + } + + #region Recording + + /// <summary> + /// Starts the recording. + /// </summary> + public void StartRecording () + { + //Console.WriteLine ("Start Recording"); + movieWritingQueue.DispatchAsync (() => { + if (recordingWillBeStarted || IsRecording) + return; + + recordingWillBeStarted = true; + + // recordingDidStart is called from captureOutput.DidOutputSampleBuffer.FromeConnection one the asset writere is setup + RecordingWillStart?.Invoke (); + + // Remove the file if one with the same name already exists + RemoveFile (movieUrl); + + // Create an asset writer + assetWriter = new AVAssetWriter (movieUrl, AVFileType.QuickTimeMovie, out NSError error); + if (error != null) { + ShowError (error); + } + }); + } + + public void StopRecording () + { + movieWritingQueue.DispatchAsync (() => { + if (recordingWillBeStopped || !IsRecording) + return; + + recordingWillBeStopped = true; + + // recordingDidStop is called from saveMovieToCameraRoll + RecordingWillStop?.Invoke (); + + if (assetWriter.FinishWriting ()) { + if (assetWriterAudioIn != null) { + assetWriterAudioIn.Dispose (); + assetWriterAudioIn = null; + } + + if (assetWriterVideoIn != null) { + assetWriterVideoIn.Dispose (); + assetWriterVideoIn = null; + } + + lock (inUse) { + assetWriter.Dispose (); + assetWriter = null; + + // Clear the 'Inuse' list when we're creating a new Recording session. + inUse.Clear (); + } + + readyToRecordVideo = false; + readyToRecordAudio = false; + + SaveMovieToCameraRoll (); + } else { + ShowError (assetWriter.Error); + } + }); + } + + #endregion + + #region Capture + + private readonly List<CMSampleBuffer> inUse = new List<CMSampleBuffer> (); + + // This is used to solve the issue with the movieWriter queue and the DisplayPixelBuffer + // thread not releasing CMSampleBuffers when + private void CompleteBufferUse (CMSampleBuffer buffer) + { + lock (inUse) { + if (inUse.Contains (buffer)) { + inUse.Remove (buffer); + buffer.Dispose (); + } else { + inUse.Add (buffer); + } + } + } + + /// <summary> + /// Videos the device available for passed in position. + /// </summary> + /// <returns> + /// The available device + /// </returns> + /// <param name='position'> The desired Position.</param> + private static AVCaptureDevice VideoDeviceWithPosition (AVCaptureDevicePosition position) + { + var devices = AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video); + foreach (var device in devices) { + if (device.Position == position) + return device; + } + return null; + } + + /// <summary> + /// Returns an audio device + /// </summary> + /// <returns> The audio device.</returns> + private static AVCaptureDevice AudioDevice () + { + var devices = AVCaptureDevice.DevicesWithMediaType (AVMediaType.Audio); + return (devices.Length == 0) ? null : devices [0]; + } + + private bool SetupCaptureSession () + { + // Overview: RosyWriter uses separate GCD queues for audio and video capture. If a single GCD queue + // is used to deliver both audio and video buffers, and our video processing consistently takes + // too long, the delivery queue can back up, resulting in audio being dropped. + // + // When recording, RosyWriter creates a third GCD queue for calls to AVAssetWriter. This ensures + // that AVAssetWriter is not called to start or finish writing from multiple threads simultaneously. + // + // RosyWriter uses AVCaptureSession's default preset, AVCaptureSessionPresetHigh. + + // Create Capture session + captureSession = new AVCaptureSession (); + captureSession.BeginConfiguration (); + + // Create audio connection + var audioDevice = AVCaptureDevice.GetDefaultDevice (AVMediaType.Audio); + if (audioDevice == null) + return false; // e.g. simulator + + var audioIn = new AVCaptureDeviceInput (audioDevice, out NSError error); + if (captureSession.CanAddInput (audioIn)) + captureSession.AddInput (audioIn); + + var audioOut = new AVCaptureAudioDataOutput (); + var audioCaptureQueue = new DispatchQueue ("Audio Capture Queue"); + + // Add the Delegate to capture each sample that comes through + audioOut.SetSampleBufferDelegateQueue (this, audioCaptureQueue); + + if (captureSession.CanAddOutput (audioOut)) + captureSession.AddOutput (audioOut); + + audioConnection = audioOut.ConnectionFromMediaType (AVMediaType.Audio); + + // Create Video Session + var videoDevice = VideoDeviceWithPosition (AVCaptureDevicePosition.Back); + var videoIn = new AVCaptureDeviceInput (videoDevice, out error); + + if (captureSession.CanAddInput (videoIn)) + captureSession.AddInput (videoIn); + + // RosyWriter prefers to discard late video frames early in the capture pipeline, since its + // processing can take longer than real-time on some platforms (such as iPhone 3GS). + // Clients whose image processing is faster than real-time should consider setting AVCaptureVideoDataOutput's + // alwaysDiscardsLateVideoFrames property to NO. + var videoOut = new AVCaptureVideoDataOutput { + AlwaysDiscardsLateVideoFrames = true, + // HACK: Change VideoSettings to WeakVideoSettings, and AVVideoSettings to CVPixelBufferAttributes + // VideoSettings = new AVVideoSettings (CVPixelFormatType.CV32BGRA) + WeakVideoSettings = new CVPixelBufferAttributes { + PixelFormatType = CVPixelFormatType.CV32BGRA + }.Dictionary + }; + + // Create a DispatchQueue for the Video Processing + var videoCaptureQueue = new DispatchQueue ("Video Capture Queue"); + videoOut.SetSampleBufferDelegateQueue (this, videoCaptureQueue); + + if (captureSession.CanAddOutput (videoOut)) + captureSession.AddOutput (videoOut); + + // Set the Video connection from the Video Output object + videoConnection = videoOut.ConnectionFromMediaType (AVMediaType.Video); + videoOrientation = videoConnection.VideoOrientation; + + captureSession.CommitConfiguration (); + + return true; + } + + public bool SetupAndStartCaptureSession () + { + // Create a shallow queue for buffers going to the display for preview. + previewBufferQueue = CMBufferQueue.CreateUnsorted (1); + + // Create serial queue for movie writing + movieWritingQueue = new DispatchQueue ("Movie Writing Queue"); + + var isSupported = true; + if (captureSession == null) { + isSupported = SetupCaptureSession (); + } + + NSNotificationCenter.DefaultCenter.AddObserver (AVCaptureSession.DidStopRunningNotification, CaptureSessionStoppedRunningNotification, captureSession); + + if (!captureSession.Running) { + if (isSupported) { + captureSession.StartRunning (); + } else { + StopAndTearDownCaptureSession (); + } + } + + return isSupported; + } + + public void CaptureSessionStoppedRunningNotification (NSNotification notification) + { + movieWritingQueue.DispatchAsync (() => { + if (IsRecording) { + StopRecording (); + } + }); + } + + public void PauseCaptureSession () + { + if (captureSession.Running) { + captureSession.StopRunning (); + } + } + + public void ResumeCaptureSession () + { + if (!captureSession.Running) { + captureSession.StartRunning (); + } + } + + /// <summary> + /// Stops the and tears down the capture session. + /// </summary> + public void StopAndTearDownCaptureSession () + { + if (captureSession != null) { + if (captureSession.Running) { + captureSession.StopRunning (); + } + + NSNotificationCenter.DefaultCenter.RemoveObserver (this, AVCaptureSession.DidStopRunningNotification, captureSession); + + captureSession.Dispose (); + captureSession = null; + } + + if (previewBufferQueue != null) { + previewBufferQueue.Dispose (); + previewBufferQueue = null; + } + + if (movieWritingQueue != null) { + movieWritingQueue.Dispose (); + movieWritingQueue = null; + } + } + + #endregion + + public void ShowError (NSError error) + { + InvokeOnMainThread (() => { + var alert = UIAlertController.Create (error.LocalizedDescription, error.ToString (), UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + UIApplication.SharedApplication.Windows [0].RootViewController.PresentViewController (alert, true, null); + }); + } + + #region AVCapture[Audio|Video]DataOutputSampleBufferDelegate + + [Export ("captureOutput:didOutputSampleBuffer:fromConnection:")] + public virtual void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + { + // HACK: Change CMSampleBuffer.GetFormatDescription() to CMSampleBuffer.GetVideoFormatDescription() + // HACK Change CMFormatDescription to CMVideoFormatDescription + // CMFormatDescription formatDescription = sampleBuffer.GetFormatDescription (); + CMVideoFormatDescription formatDescription = sampleBuffer.GetVideoFormatDescription (); + + if (connection == videoConnection) { + // Get framerate + CMTime timestamp = sampleBuffer.PresentationTimeStamp; + CalculateFramerateAtTimestamp (timestamp); + + // Get frame dimensions (for onscreen display) + if (VideoDimensions.IsEmpty) + // HACK: Change GetVideoPresentationDimensions() to GetPresentationDimensions() + // VideoDimensions = formatDescription.GetVideoPresentationDimensions (true, false); + VideoDimensions = formatDescription.GetPresentationDimensions (true, false); + + // Get the buffer type + if (VideoType == 0) + VideoType = formatDescription.MediaSubType; + + // Synchronously process the pixel buffer to de-green it. + using (var pixelBuffer = sampleBuffer.GetImageBuffer ()) + ProcessPixelBuffer (pixelBuffer); + + previewBufferQueue.Enqueue (sampleBuffer); + + //var writeBuffer = sampleBuffer.Duplicate (); + InvokeOnMainThread (() => { + INativeObject j = previewBufferQueue.Dequeue (); + if (!(j is CMSampleBuffer sbuf)) { #if DEBUG // Record the current sampleBuffer.ClassHandle // Then run another iteration and on the next one, print the ClassHandle Console.WriteLine("The type is {0}", j.ToString()); #endif - return; - } - - using (CVImageBuffer pixBuf = sbuf.GetImageBuffer()) - { - PixelBufferReadyForDisplay?.Invoke(pixBuf); - } - }); - } - - // keep a reference to 'sampleBuffer', movieWritingQueue will remove it - CompleteBufferUse(sampleBuffer); - - movieWritingQueue.DispatchAsync(() => - { - if (assetWriter != null) - { - bool wasReadyToRecord = (readyToRecordAudio && readyToRecordVideo); - - if (connection == videoConnection) - { - // Initialize the video input if this is not done yet - if (!readyToRecordVideo) - readyToRecordVideo = SetupAssetWriterVideoInput(formatDescription); - - // Write the video data to file - if (readyToRecordVideo && readyToRecordAudio) - { - WriteSampleBuffer(sampleBuffer, AVMediaType.Video); - } - } - else if (connection == audioConnection) - { - if (!readyToRecordAudio) - readyToRecordAudio = SetupAssetWriterAudioInput(formatDescription); - - if (readyToRecordAudio && readyToRecordVideo) - WriteSampleBuffer(sampleBuffer, AVMediaType.Audio); - } - bool isReadyToRecord = (readyToRecordAudio && readyToRecordVideo); - - if (!wasReadyToRecord && isReadyToRecord) - { - recordingWillBeStarted = false; - IsRecording = true; - - RecordingDidStart?.Invoke(); - } - } - CompleteBufferUse(sampleBuffer); - }); - } - - // HACK: Change CMFormatDescription to CMVideoFormatDescription - public bool SetupAssetWriterVideoInput(CMVideoFormatDescription currentFormatDescription) - { - //Console.WriteLine ("Setting up Video Asset Writer"); - float bitsPerPixel; - // HACK: Change VideoDimensions to Dimensions, as this type was changed to CMVideoFormatDescription - var dimensions = currentFormatDescription.Dimensions; - int numPixels = dimensions.Width * dimensions.Height; - int bitsPerSecond; - - // Assume that lower-than-SD resolution are intended for streaming, and use a lower bitrate - bitsPerPixel = numPixels < (640 * 480) ? 4.05F : 11.4F; - - bitsPerSecond = (int)(numPixels * bitsPerPixel); - - var videoCompressionSettings = new NSDictionary(AVVideo.CodecKey, AVVideo.CodecH264, - AVVideo.WidthKey, dimensions.Width, - AVVideo.HeightKey, dimensions.Height, - AVVideo.CompressionPropertiesKey, new NSDictionary(AVVideo.AverageBitRateKey, bitsPerSecond, - AVVideo.MaxKeyFrameIntervalKey, 30)); - - if (assetWriter.CanApplyOutputSettings(videoCompressionSettings, AVMediaType.Video)) - { - // HACK: Change NSDictionary into AVVideoSettingsCompressed created using that NSDictionary (videoCompressionSettings) - assetWriterVideoIn = new AVAssetWriterInput(AVMediaType.Video, new AVVideoSettingsCompressed(videoCompressionSettings)); - assetWriterVideoIn.ExpectsMediaDataInRealTime = true; - assetWriterVideoIn.Transform = TransformFromCurrentVideoOrientationToOrientation(ReferenceOrientation); - - if (assetWriter.CanAddInput(assetWriterVideoIn)) - assetWriter.AddInput(assetWriterVideoIn); - else - { - Console.WriteLine("Couldn't add asset writer video input."); - return false; - } - } - else - { - Console.WriteLine("Couldn't apply video output settings."); - } - - return true; - } - - public bool SetupAssetWriterAudioInput(CMFormatDescription currentFormatDescription) - { - // If the AudioStreamBasicDescription is null return false; - if (!currentFormatDescription.AudioStreamBasicDescription.HasValue) - return false; - - var currentASBD = currentFormatDescription.AudioStreamBasicDescription.Value; - - // Get the Audio Channel Layout from the Format Description. - var currentChannelLayout = currentFormatDescription.AudioChannelLayout; - var currentChannelLayoutData = currentChannelLayout == null ? new NSData() : currentChannelLayout.AsData(); - - var audioCompressionSettings = new NSDictionary(AVAudioSettings.AVFormatIDKey, AudioFormatType.MPEG4AAC, - AVAudioSettings.AVSampleRateKey, currentASBD.SampleRate, - AVAudioSettings.AVEncoderBitRateKey, 64000, - AVAudioSettings.AVNumberOfChannelsKey, currentASBD.ChannelsPerFrame, - AVAudioSettings.AVChannelLayoutKey, currentChannelLayoutData); - - if (assetWriter.CanApplyOutputSettings(audioCompressionSettings, AVMediaType.Audio)) - { - // HACK: Change NSDictionary into AudioSettings created using that NSDictionary (audioCompressionSettings) - assetWriterAudioIn = new AVAssetWriterInput(AVMediaType.Audio, new AudioSettings(audioCompressionSettings)); - assetWriterAudioIn.ExpectsMediaDataInRealTime = true; - - if (assetWriter.CanAddInput(assetWriterAudioIn)) - assetWriter.AddInput(assetWriterAudioIn); - else - { - Console.WriteLine("Couldn't add asset writer audio input."); - return false; - } - } - else - { - Console.WriteLine("Couldn't apply audio output settings."); - return false; - } - - return true; - } - - public void CalculateFramerateAtTimestamp(CMTime timeStamp) - { - previousSecondTimestamps.Add(timeStamp); - - var oneSecond = CMTime.FromSeconds(1, 1); - var oneSecondAgo = CMTime.Subtract(timeStamp, oneSecond); - - while (previousSecondTimestamps.Count > 0 && CMTime.Compare(previousSecondTimestamps[0], oneSecondAgo) < 0) - { - previousSecondTimestamps.RemoveAt(0); - } - - var newRate = Convert.ToDouble(previousSecondTimestamps.Count); - VideoFrameRate = (VideoFrameRate + newRate) / 2; - } - - public unsafe void ProcessPixelBuffer(CVImageBuffer imageBuffer) - { - using (var pixelBuffer = imageBuffer as CVPixelBuffer) - { - pixelBuffer.Lock(CVOptionFlags.None); - - //HACK: Cast nint to int - int bufferWidth = (int)pixelBuffer.Width; - int bufferHeight = (int)pixelBuffer.Height; - // offset by one to de-green the BGRA array (green is second) - byte* pixelPtr = (byte*)pixelBuffer.BaseAddress.ToPointer() + 1; - - for (var row = 0; row < bufferHeight; row++) - { - for (var column = 0; column < bufferWidth; column++) - { - *pixelPtr = 0; - pixelPtr += BYTES_PER_PIXEL; - } - } - - pixelBuffer.Unlock(CVOptionFlags.None); - } - } - - #endregion - } -} \ No newline at end of file + return; + } + + using (CVImageBuffer pixBuf = sbuf.GetImageBuffer ()) { + PixelBufferReadyForDisplay?.Invoke (pixBuf); + } + }); + } + + // keep a reference to 'sampleBuffer', movieWritingQueue will remove it + CompleteBufferUse (sampleBuffer); + + movieWritingQueue.DispatchAsync (() => { + if (assetWriter != null) { + bool wasReadyToRecord = (readyToRecordAudio && readyToRecordVideo); + + if (connection == videoConnection) { + // Initialize the video input if this is not done yet + if (!readyToRecordVideo) + readyToRecordVideo = SetupAssetWriterVideoInput (formatDescription); + + // Write the video data to file + if (readyToRecordVideo && readyToRecordAudio) { + WriteSampleBuffer (sampleBuffer, AVMediaType.Video); + } + } else if (connection == audioConnection) { + if (!readyToRecordAudio) + readyToRecordAudio = SetupAssetWriterAudioInput (formatDescription); + + if (readyToRecordAudio && readyToRecordVideo) + WriteSampleBuffer (sampleBuffer, AVMediaType.Audio); + } + bool isReadyToRecord = (readyToRecordAudio && readyToRecordVideo); + + if (!wasReadyToRecord && isReadyToRecord) { + recordingWillBeStarted = false; + IsRecording = true; + + RecordingDidStart?.Invoke (); + } + } + CompleteBufferUse (sampleBuffer); + }); + } + + // HACK: Change CMFormatDescription to CMVideoFormatDescription + public bool SetupAssetWriterVideoInput (CMVideoFormatDescription currentFormatDescription) + { + //Console.WriteLine ("Setting up Video Asset Writer"); + float bitsPerPixel; + // HACK: Change VideoDimensions to Dimensions, as this type was changed to CMVideoFormatDescription + var dimensions = currentFormatDescription.Dimensions; + int numPixels = dimensions.Width * dimensions.Height; + int bitsPerSecond; + + // Assume that lower-than-SD resolution are intended for streaming, and use a lower bitrate + bitsPerPixel = numPixels < (640 * 480) ? 4.05F : 11.4F; + + bitsPerSecond = (int) (numPixels * bitsPerPixel); + + var videoCompressionSettings = new NSDictionary (AVVideo.CodecKey, AVVideo.CodecH264, + AVVideo.WidthKey, dimensions.Width, + AVVideo.HeightKey, dimensions.Height, + AVVideo.CompressionPropertiesKey, new NSDictionary (AVVideo.AverageBitRateKey, bitsPerSecond, + AVVideo.MaxKeyFrameIntervalKey, 30)); + + if (assetWriter.CanApplyOutputSettings (videoCompressionSettings, AVMediaType.Video)) { + // HACK: Change NSDictionary into AVVideoSettingsCompressed created using that NSDictionary (videoCompressionSettings) + assetWriterVideoIn = new AVAssetWriterInput (AVMediaType.Video, new AVVideoSettingsCompressed (videoCompressionSettings)); + assetWriterVideoIn.ExpectsMediaDataInRealTime = true; + assetWriterVideoIn.Transform = TransformFromCurrentVideoOrientationToOrientation (ReferenceOrientation); + + if (assetWriter.CanAddInput (assetWriterVideoIn)) + assetWriter.AddInput (assetWriterVideoIn); + else { + Console.WriteLine ("Couldn't add asset writer video input."); + return false; + } + } else { + Console.WriteLine ("Couldn't apply video output settings."); + } + + return true; + } + + public bool SetupAssetWriterAudioInput (CMFormatDescription currentFormatDescription) + { + // If the AudioStreamBasicDescription is null return false; + if (!currentFormatDescription.AudioStreamBasicDescription.HasValue) + return false; + + var currentASBD = currentFormatDescription.AudioStreamBasicDescription.Value; + + // Get the Audio Channel Layout from the Format Description. + var currentChannelLayout = currentFormatDescription.AudioChannelLayout; + var currentChannelLayoutData = currentChannelLayout == null ? new NSData () : currentChannelLayout.AsData (); + + var audioCompressionSettings = new NSDictionary (AVAudioSettings.AVFormatIDKey, AudioFormatType.MPEG4AAC, + AVAudioSettings.AVSampleRateKey, currentASBD.SampleRate, + AVAudioSettings.AVEncoderBitRateKey, 64000, + AVAudioSettings.AVNumberOfChannelsKey, currentASBD.ChannelsPerFrame, + AVAudioSettings.AVChannelLayoutKey, currentChannelLayoutData); + + if (assetWriter.CanApplyOutputSettings (audioCompressionSettings, AVMediaType.Audio)) { + // HACK: Change NSDictionary into AudioSettings created using that NSDictionary (audioCompressionSettings) + assetWriterAudioIn = new AVAssetWriterInput (AVMediaType.Audio, new AudioSettings (audioCompressionSettings)); + assetWriterAudioIn.ExpectsMediaDataInRealTime = true; + + if (assetWriter.CanAddInput (assetWriterAudioIn)) + assetWriter.AddInput (assetWriterAudioIn); + else { + Console.WriteLine ("Couldn't add asset writer audio input."); + return false; + } + } else { + Console.WriteLine ("Couldn't apply audio output settings."); + return false; + } + + return true; + } + + public void CalculateFramerateAtTimestamp (CMTime timeStamp) + { + previousSecondTimestamps.Add (timeStamp); + + var oneSecond = CMTime.FromSeconds (1, 1); + var oneSecondAgo = CMTime.Subtract (timeStamp, oneSecond); + + while (previousSecondTimestamps.Count > 0 && CMTime.Compare (previousSecondTimestamps [0], oneSecondAgo) < 0) { + previousSecondTimestamps.RemoveAt (0); + } + + var newRate = Convert.ToDouble (previousSecondTimestamps.Count); + VideoFrameRate = (VideoFrameRate + newRate) / 2; + } + + public unsafe void ProcessPixelBuffer (CVImageBuffer imageBuffer) + { + using (var pixelBuffer = imageBuffer as CVPixelBuffer) { + pixelBuffer.Lock (CVOptionFlags.None); + + //HACK: Cast nint to int + int bufferWidth = (int) pixelBuffer.Width; + int bufferHeight = (int) pixelBuffer.Height; + // offset by one to de-green the BGRA array (green is second) + byte* pixelPtr = (byte*) pixelBuffer.BaseAddress.ToPointer () + 1; + + for (var row = 0; row < bufferHeight; row++) { + for (var column = 0; column < bufferWidth; column++) { + *pixelPtr = 0; + pixelPtr += BYTES_PER_PIXEL; + } + } + + pixelBuffer.Unlock (CVOptionFlags.None); + } + } + + #endregion + } +} diff --git a/RosyWriter/RosyWriter/Helpers/StatisticView.cs b/RosyWriter/RosyWriter/Helpers/StatisticView.cs index e4280655a..7efb04e62 100644 --- a/RosyWriter/RosyWriter/Helpers/StatisticView.cs +++ b/RosyWriter/RosyWriter/Helpers/StatisticView.cs @@ -3,30 +3,27 @@ using System; using UIKit; -namespace RosyWriter -{ - public partial class StatisticView : UIView - { - public StatisticView (IntPtr handle) : base (handle) { } +namespace RosyWriter { + public partial class StatisticView : UIView { + public StatisticView (IntPtr handle) : base (handle) { } - internal void UpdateLabel(RosyWriterVideoProcessor videoProcessor) - { - fpsLabel.Text = String.Format("{0:F} FPS", videoProcessor.VideoFrameRate); + internal void UpdateLabel (RosyWriterVideoProcessor videoProcessor) + { + fpsLabel.Text = String.Format ("{0:F} FPS", videoProcessor.VideoFrameRate); - var dimension = videoProcessor.VideoDimensions; - dimensionsLabel.Text = String.Format("{0} x {1}", dimension.Width, dimension.Height); + var dimension = videoProcessor.VideoDimensions; + dimensionsLabel.Text = String.Format ("{0} x {1}", dimension.Width, dimension.Height); - // Turn the integer constant into something human readable - var type = videoProcessor.VideoType; - char[] code = new char[4]; - for (int i = 0; i < 4; i++) - { - code[3 - i] = (char)(type & 0xff); - type = type >> 8; - } - var typeString = new String(code); + // Turn the integer constant into something human readable + var type = videoProcessor.VideoType; + char [] code = new char [4]; + for (int i = 0; i < 4; i++) { + code [3 - i] = (char) (type & 0xff); + type = type >> 8; + } + var typeString = new String (code); - colorLabel.Text = typeString; - } - } -} \ No newline at end of file + colorLabel.Text = typeString; + } + } +} diff --git a/RosyWriter/RosyWriter/Main.cs b/RosyWriter/RosyWriter/Main.cs index 15cc603d2..9eda02aac 100644 --- a/RosyWriter/RosyWriter/Main.cs +++ b/RosyWriter/RosyWriter/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace RosyWriter -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace RosyWriter { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/RosyWriter/RosyWriter/ViewController.cs b/RosyWriter/RosyWriter/ViewController.cs index d7bf83bf4..985afca3f 100644 --- a/RosyWriter/RosyWriter/ViewController.cs +++ b/RosyWriter/RosyWriter/ViewController.cs @@ -1,4 +1,4 @@ -using AVFoundation; +using AVFoundation; using CoreGraphics; using CoreVideo; using Foundation; @@ -6,199 +6,180 @@ using System; using UIKit; -namespace RosyWriter -{ - public partial class ViewController : UIViewController - { - private RosyWriterVideoProcessor videoProcessor; - - private nint backgroundRecordingID; - - private bool shouldShowStats; - - private NSTimer timer; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - statisticView.Layer.CornerRadius = 4f; - - // Initialize the class responsible for managing AV capture session and asset writer - videoProcessor = new RosyWriterVideoProcessor(); - - // Setup and start the capture session - var isSupported = videoProcessor.SetupAndStartCaptureSession(); - if (isSupported) - { - // Our interface is always in portrait - previewView.Transform = videoProcessor.TransformFromCurrentVideoOrientationToOrientation(AVCaptureVideoOrientation.Portrait); - previewView.Bounds = View.ConvertRectToView(View.Bounds, previewView); - previewView.Center = new CGPoint(View.Bounds.Size.Width / 2f, View.Bounds.Size.Height / 2f); - - UIApplication.Notifications.ObserveDidBecomeActive(OnApplicationDidBecomeActive); - - // Set up labels - shouldShowStats = true; - - // Video Processor Event Handlers - videoProcessor.RecordingDidStart += OnRecordingDidStart; - videoProcessor.RecordingDidStop += OnRecordingDidStop; - videoProcessor.RecordingWillStart += OnRecordingWillStart; - videoProcessor.RecordingWillStop += OnRecordingWillStop; - videoProcessor.PixelBufferReadyForDisplay += OnPixelBufferReadyForDisplay; - } - else - { - errorLabel.Hidden = false; - - previewView.Hidden = true; - recordButton.Enabled = false; - } - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - timer = NSTimer.CreateRepeatingScheduledTimer(.25, UpdateLabels); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - - if (timer != null) - { - timer.Invalidate(); - timer.Dispose(); - timer = null; - } - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - if (timer != null) - { - timer.Invalidate(); - timer.Dispose(); - timer = null; - } - - if (videoProcessor != null) - { - videoProcessor.Dispose(); - videoProcessor = null; - } - } - - private void UpdateLabels(NSTimer time) - { - statisticView.Hidden = !shouldShowStats; - if (shouldShowStats) - { - statisticView.UpdateLabel(videoProcessor); - } - } - - #region Event Handler - - public void OnPixelBufferReadyForDisplay(CVImageBuffer imageBuffer) - { - // Don't make OpenGLES calls while in the backgroud. - if (UIApplication.SharedApplication.ApplicationState != UIApplicationState.Background) - { - previewView.DisplayPixelBuffer(imageBuffer); - } - } - - partial void OnRecordButtonClicked(UIBarButtonItem sender) - { - // Wait for the recording to start/stop before re-enabling the record button. - InvokeOnMainThread(() => recordButton.Enabled = false); - - // The recordingWill/DidStop delegate methods will fire asynchronously in the response to this call. - if (videoProcessor.IsRecording) - { - videoProcessor.StopRecording(); - } - else - { - videoProcessor.StartRecording(); - } - } - - private void OnApplicationDidBecomeActive(object sender, NSNotificationEventArgs e) - { - // For performance reasons, we manually pause/resume the session when saving a recoding. - // If we try to resume the session in the background it will fail. Resume the session here as well to ensure we will succeed. - videoProcessor.ResumeCaptureSession(); - } - - #endregion - - #region Video Processer Event handlers - - public void OnRecordingWillStart() - { - InvokeOnMainThread(() => - { - recordButton.Enabled = false; - recordButton.Title = "Stop"; - - // Disable the idle timer while we are recording - UIApplication.SharedApplication.IdleTimerDisabled = true; - - // Make sure we have time to finish saving the movie if the app is backgrounded during recording - if (UIDevice.CurrentDevice.IsMultitaskingSupported) - { - backgroundRecordingID = UIApplication.SharedApplication.BeginBackgroundTask(() => - { - UIApplication.SharedApplication.EndBackgroundTask(backgroundRecordingID); - }); - } - }); - } - - public void OnRecordingDidStart() - { - InvokeOnMainThread(() => recordButton.Enabled = true); - } - - public void OnRecordingWillStop() - { - InvokeOnMainThread(() => - { - // Disable until saving to the camera roll is complete - recordButton.Title = "Record"; - recordButton.Enabled = false; - - // Pause the capture session so the saving will be as fast as possible. - // We resme the session in recordingDidStop - videoProcessor.PauseCaptureSession(); - }); - } - - public void OnRecordingDidStop() - { - InvokeOnMainThread(() => - { - recordButton.Enabled = true; - UIApplication.SharedApplication.IdleTimerDisabled = false; - - videoProcessor.ResumeCaptureSession(); - - if (UIDevice.CurrentDevice.IsMultitaskingSupported) - { - UIApplication.SharedApplication.EndBackgroundTask(backgroundRecordingID); - backgroundRecordingID = 0; - } - }); - } - - #endregion - } -} \ No newline at end of file +namespace RosyWriter { + public partial class ViewController : UIViewController { + private RosyWriterVideoProcessor videoProcessor; + + private nint backgroundRecordingID; + + private bool shouldShowStats; + + private NSTimer timer; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + statisticView.Layer.CornerRadius = 4f; + + // Initialize the class responsible for managing AV capture session and asset writer + videoProcessor = new RosyWriterVideoProcessor (); + + // Setup and start the capture session + var isSupported = videoProcessor.SetupAndStartCaptureSession (); + if (isSupported) { + // Our interface is always in portrait + previewView.Transform = videoProcessor.TransformFromCurrentVideoOrientationToOrientation (AVCaptureVideoOrientation.Portrait); + previewView.Bounds = View.ConvertRectToView (View.Bounds, previewView); + previewView.Center = new CGPoint (View.Bounds.Size.Width / 2f, View.Bounds.Size.Height / 2f); + + UIApplication.Notifications.ObserveDidBecomeActive (OnApplicationDidBecomeActive); + + // Set up labels + shouldShowStats = true; + + // Video Processor Event Handlers + videoProcessor.RecordingDidStart += OnRecordingDidStart; + videoProcessor.RecordingDidStop += OnRecordingDidStop; + videoProcessor.RecordingWillStart += OnRecordingWillStart; + videoProcessor.RecordingWillStop += OnRecordingWillStop; + videoProcessor.PixelBufferReadyForDisplay += OnPixelBufferReadyForDisplay; + } else { + errorLabel.Hidden = false; + + previewView.Hidden = true; + recordButton.Enabled = false; + } + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + timer = NSTimer.CreateRepeatingScheduledTimer (.25, UpdateLabels); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + + if (timer != null) { + timer.Invalidate (); + timer.Dispose (); + timer = null; + } + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + if (timer != null) { + timer.Invalidate (); + timer.Dispose (); + timer = null; + } + + if (videoProcessor != null) { + videoProcessor.Dispose (); + videoProcessor = null; + } + } + + private void UpdateLabels (NSTimer time) + { + statisticView.Hidden = !shouldShowStats; + if (shouldShowStats) { + statisticView.UpdateLabel (videoProcessor); + } + } + + #region Event Handler + + public void OnPixelBufferReadyForDisplay (CVImageBuffer imageBuffer) + { + // Don't make OpenGLES calls while in the backgroud. + if (UIApplication.SharedApplication.ApplicationState != UIApplicationState.Background) { + previewView.DisplayPixelBuffer (imageBuffer); + } + } + + partial void OnRecordButtonClicked (UIBarButtonItem sender) + { + // Wait for the recording to start/stop before re-enabling the record button. + InvokeOnMainThread (() => recordButton.Enabled = false); + + // The recordingWill/DidStop delegate methods will fire asynchronously in the response to this call. + if (videoProcessor.IsRecording) { + videoProcessor.StopRecording (); + } else { + videoProcessor.StartRecording (); + } + } + + private void OnApplicationDidBecomeActive (object sender, NSNotificationEventArgs e) + { + // For performance reasons, we manually pause/resume the session when saving a recoding. + // If we try to resume the session in the background it will fail. Resume the session here as well to ensure we will succeed. + videoProcessor.ResumeCaptureSession (); + } + + #endregion + + #region Video Processer Event handlers + + public void OnRecordingWillStart () + { + InvokeOnMainThread (() => { + recordButton.Enabled = false; + recordButton.Title = "Stop"; + + // Disable the idle timer while we are recording + UIApplication.SharedApplication.IdleTimerDisabled = true; + + // Make sure we have time to finish saving the movie if the app is backgrounded during recording + if (UIDevice.CurrentDevice.IsMultitaskingSupported) { + backgroundRecordingID = UIApplication.SharedApplication.BeginBackgroundTask (() => { + UIApplication.SharedApplication.EndBackgroundTask (backgroundRecordingID); + }); + } + }); + } + + public void OnRecordingDidStart () + { + InvokeOnMainThread (() => recordButton.Enabled = true); + } + + public void OnRecordingWillStop () + { + InvokeOnMainThread (() => { + // Disable until saving to the camera roll is complete + recordButton.Title = "Record"; + recordButton.Enabled = false; + + // Pause the capture session so the saving will be as fast as possible. + // We resme the session in recordingDidStop + videoProcessor.PauseCaptureSession (); + }); + } + + public void OnRecordingDidStop () + { + InvokeOnMainThread (() => { + recordButton.Enabled = true; + UIApplication.SharedApplication.IdleTimerDisabled = false; + + videoProcessor.ResumeCaptureSession (); + + if (UIDevice.CurrentDevice.IsMultitaskingSupported) { + UIApplication.SharedApplication.EndBackgroundTask (backgroundRecordingID); + backgroundRecordingID = 0; + } + }); + } + + #endregion + } +} diff --git a/Rotation/HandlingRotation/AppDelegate.cs b/Rotation/HandlingRotation/AppDelegate.cs index 1d7d300c7..262c6efa6 100755 --- a/Rotation/HandlingRotation/AppDelegate.cs +++ b/Rotation/HandlingRotation/AppDelegate.cs @@ -3,7 +3,7 @@ using Foundation; namespace HandlingRotation { - [Register("AppDelegate")] + [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { protected UIWindow window; @@ -29,17 +29,16 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) mainNavController = new UINavigationController (); mainNavController.NavigationBar.Translucent = false; - switch (CurrentDevice) - { - case DeviceType.iPhone: - iPhoneHome = new HandlingRotation.Screens.iPhone.Home.HomeScreen (); - mainNavController.PushViewController (iPhoneHome, false); - break; - - case DeviceType.iPad: - iPadHome = new HandlingRotation.Screens.iPad.Home.HomeScreenPad (); - mainNavController.PushViewController (iPadHome, false); - break; + switch (CurrentDevice) { + case DeviceType.iPhone: + iPhoneHome = new HandlingRotation.Screens.iPhone.Home.HomeScreen (); + mainNavController.PushViewController (iPhoneHome, false); + break; + + case DeviceType.iPad: + iPadHome = new HandlingRotation.Screens.iPad.Home.HomeScreenPad (); + mainNavController.PushViewController (iPadHome, false); + break; } window.RootViewController = mainNavController; diff --git a/Rotation/HandlingRotation/Application.cs b/Rotation/HandlingRotation/Application.cs index 717a4c650..057c3d4df 100755 --- a/Rotation/HandlingRotation/Application.cs +++ b/Rotation/HandlingRotation/Application.cs @@ -3,7 +3,7 @@ namespace HandlingRotation { public class Application {// : UIApplication - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); diff --git a/Rotation/HandlingRotation/DeviceType.cs b/Rotation/HandlingRotation/DeviceType.cs index 3a479f05e..c2da32efc 100755 --- a/Rotation/HandlingRotation/DeviceType.cs +++ b/Rotation/HandlingRotation/DeviceType.cs @@ -4,8 +4,7 @@ namespace HandlingRotation { /// <summary> /// The type of device, e.g. iPhone, or iPad /// </summary> - public enum DeviceType - { + public enum DeviceType { iPhone, iPad } diff --git a/Rotation/HandlingRotation/Screens/iPad/Home/HomeScreenPad.xib.cs b/Rotation/HandlingRotation/Screens/iPad/Home/HomeScreenPad.xib.cs index 686d91329..00fe398e8 100755 --- a/Rotation/HandlingRotation/Screens/iPad/Home/HomeScreenPad.xib.cs +++ b/Rotation/HandlingRotation/Screens/iPad/Home/HomeScreenPad.xib.cs @@ -11,18 +11,18 @@ public partial class HomeScreenPad : UIViewController { // The IntPtr and initWithCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public HomeScreenPad (IntPtr handle) : base(handle) + public HomeScreenPad (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public HomeScreenPad (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public HomeScreenPad (NSCoder coder) : base (coder) { Initialize (); } - public HomeScreenPad () : base("HomeScreen", null) + public HomeScreenPad () : base ("HomeScreen", null) { Initialize (); } @@ -70,12 +70,12 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // just return true, but this switch illustrates how you can test for the // different cases switch (toInterfaceOrientation) { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } } diff --git a/Rotation/HandlingRotation/Screens/iPad/Method1Autosize/AutosizeScreenPad.xib.cs b/Rotation/HandlingRotation/Screens/iPad/Method1Autosize/AutosizeScreenPad.xib.cs index fef90788c..89c337f48 100755 --- a/Rotation/HandlingRotation/Screens/iPad/Method1Autosize/AutosizeScreenPad.xib.cs +++ b/Rotation/HandlingRotation/Screens/iPad/Method1Autosize/AutosizeScreenPad.xib.cs @@ -14,18 +14,18 @@ public partial class AutosizeScreenPad : UIViewController { // The IntPtr and initWithCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public AutosizeScreenPad (IntPtr handle) : base(handle) + public AutosizeScreenPad (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public AutosizeScreenPad (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public AutosizeScreenPad (NSCoder coder) : base (coder) { Initialize (); } - public AutosizeScreenPad () : base("AutosizeScreen", null) + public AutosizeScreenPad () : base ("AutosizeScreen", null) { Initialize (); } @@ -56,14 +56,13 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // we're passed to orientation that it will rotate to. in our case, we could // just return true, but this switch illustrates how you can test for the // different cases - switch (toInterfaceOrientation) - { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + switch (toInterfaceOrientation) { + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } @@ -81,14 +80,14 @@ protected void CreateData () tableItems.Add ("Elbow"); } - [Export("tableView:numberOfRowsInSection:")] + [Export ("tableView:numberOfRowsInSection:")] public int RowsInSection (UITableView tableView, int section) { Console.WriteLine ("RowsInSection"); return tableItems.Count; } - [Export("tableView:cellForRowAtIndexPath:")] + [Export ("tableView:cellForRowAtIndexPath:")] public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { Console.WriteLine ("GetCell"); @@ -104,7 +103,7 @@ public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) } // set the cell properties - cell.TextLabel.Text = this.tableItems[indexPath.Row]; + cell.TextLabel.Text = this.tableItems [indexPath.Row]; // return the cell return cell; diff --git a/Rotation/HandlingRotation/Screens/iPad/Method2MoveControls/Controller.cs b/Rotation/HandlingRotation/Screens/iPad/Method2MoveControls/Controller.cs index 03ecda242..16d30f2d5 100755 --- a/Rotation/HandlingRotation/Screens/iPad/Method2MoveControls/Controller.cs +++ b/Rotation/HandlingRotation/Screens/iPad/Method2MoveControls/Controller.cs @@ -6,7 +6,7 @@ public class Controller : UIViewController { UIButton button1 = UIButton.FromType (UIButtonType.RoundedRect); UIButton button2 = UIButton.FromType (UIButtonType.RoundedRect); - UIImageView image = new UIImageView(UIImage.FromFile("icon-144.png")); + UIImageView image = new UIImageView (UIImage.FromFile ("icon-144.png")); public Controller () { @@ -43,14 +43,13 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // we're passed to orientation that it will rotate to. in our case, we could // just return true, but this switch illustrates how you can test for the // different cases - switch (toInterfaceOrientation) - { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + switch (toInterfaceOrientation) { + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } @@ -78,31 +77,31 @@ protected void PositionControls (UIInterfaceOrientation toInterfaceOrientation) // depending one what orientation we start in, we want to position our controls // appropriately switch (toInterfaceOrientation) { - // if we're switchign to landscape - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: + // if we're switchign to landscape + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: - // reposition the buttons - button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); - button2.Frame = new CoreGraphics.CGRect (10, 200, 100, 33); + // reposition the buttons + button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); + button2.Frame = new CoreGraphics.CGRect (10, 200, 100, 33); - // reposition the image - image.Frame = new CoreGraphics.CGRect (240, 25, this.image.Frame.Width, this.image.Frame.Height); + // reposition the image + image.Frame = new CoreGraphics.CGRect (240, 25, this.image.Frame.Width, this.image.Frame.Height); - break; + break; - // we're switch back to portrait - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: + // we're switch back to portrait + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: - // reposition the buttons - button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); - button2.Frame = new CoreGraphics.CGRect (200, 10, 100, 33); + // reposition the buttons + button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); + button2.Frame = new CoreGraphics.CGRect (200, 10, 100, 33); - // reposition the image - image.Frame = new CoreGraphics.CGRect (20, 150, this.image.Frame.Width, this.image.Frame.Height); + // reposition the image + image.Frame = new CoreGraphics.CGRect (20, 150, this.image.Frame.Width, this.image.Frame.Height); - break; + break; } } } diff --git a/Rotation/HandlingRotation/Screens/iPad/Method3SwapViews/Controller.cs b/Rotation/HandlingRotation/Screens/iPad/Method3SwapViews/Controller.cs index 43f173b2a..5ad7c5d6e 100644 --- a/Rotation/HandlingRotation/Screens/iPad/Method3SwapViews/Controller.cs +++ b/Rotation/HandlingRotation/Screens/iPad/Method3SwapViews/Controller.cs @@ -2,10 +2,8 @@ using UIKit; using Foundation; -namespace HandlingRotation.Screens.iPad.Method3SwapViews -{ - public class Controller : UIViewController - { +namespace HandlingRotation.Screens.iPad.Method3SwapViews { + public class Controller : UIViewController { public override void ViewDidLoad () { base.ViewDidLoad (); diff --git a/Rotation/HandlingRotation/Screens/iPhone/Home/HomeScreen.xib.cs b/Rotation/HandlingRotation/Screens/iPhone/Home/HomeScreen.xib.cs index cd260b63b..11ea2a90e 100755 --- a/Rotation/HandlingRotation/Screens/iPhone/Home/HomeScreen.xib.cs +++ b/Rotation/HandlingRotation/Screens/iPhone/Home/HomeScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace HandlingRotation.Screens.iPhone.Home -{ - public partial class HomeScreen : UIViewController - { +namespace HandlingRotation.Screens.iPhone.Home { + public partial class HomeScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public HomeScreen (IntPtr handle) : base(handle) + public HomeScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public HomeScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public HomeScreen (NSCoder coder) : base (coder) { Initialize (); } - public HomeScreen () : base("HomeScreen", null) + public HomeScreen () : base ("HomeScreen", null) { Initialize (); } @@ -59,13 +57,16 @@ public override void ViewDidLoad () base.ViewDidLoad (); // wire up our button TouchUpInside handlers - btnMethod1.TouchUpInside += delegate { + btnMethod1.TouchUpInside += delegate + { NavigationController.PushViewController (new Method1Autosize.AutosizeScreen (), true); }; - btnMethod2.TouchUpInside += delegate { + btnMethod2.TouchUpInside += delegate + { NavigationController.PushViewController (new Method2MoveControls.Controller (), true); }; - btnMethod3.TouchUpInside += delegate { + btnMethod3.TouchUpInside += delegate + { NavigationController.PushViewController (new Method3SwapViews.Controller (), true); }; } @@ -79,14 +80,13 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // we're passed to orientation that it will rotate to. in our case, we could // just return true, but this switch illustrates how you can test for the // different cases - switch (toInterfaceOrientation) - { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + switch (toInterfaceOrientation) { + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } } diff --git a/Rotation/HandlingRotation/Screens/iPhone/Method1Autosize/AutosizeScreen.xib.cs b/Rotation/HandlingRotation/Screens/iPhone/Method1Autosize/AutosizeScreen.xib.cs index a802a519f..7e6fb595d 100755 --- a/Rotation/HandlingRotation/Screens/iPhone/Method1Autosize/AutosizeScreen.xib.cs +++ b/Rotation/HandlingRotation/Screens/iPhone/Method1Autosize/AutosizeScreen.xib.cs @@ -7,25 +7,25 @@ namespace HandlingRotation.Screens.iPhone.Method1Autosize { public partial class AutosizeScreen : UIViewController { - List<string> tableItems = new List<string>(); + List<string> tableItems = new List<string> (); #region Constructors // The IntPtr and initWithCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public AutosizeScreen (IntPtr handle) : base(handle) + public AutosizeScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public AutosizeScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public AutosizeScreen (NSCoder coder) : base (coder) { Initialize (); } - public AutosizeScreen () : base("AutosizeScreen", null) + public AutosizeScreen () : base ("AutosizeScreen", null) { Initialize (); } @@ -57,12 +57,12 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // just return true, but this switch illustrates how you can test for the // different cases switch (toInterfaceOrientation) { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } @@ -80,14 +80,14 @@ protected void CreateData () tableItems.Add ("Elbow"); } - [Export("tableView:numberOfRowsInSection:")] + [Export ("tableView:numberOfRowsInSection:")] public int RowsInSection (UITableView tableView, int section) { Console.WriteLine ("RowsInSection"); return tableItems.Count; } - [Export("tableView:cellForRowAtIndexPath:")] + [Export ("tableView:cellForRowAtIndexPath:")] public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { Console.WriteLine ("GetCell"); @@ -103,7 +103,7 @@ public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) } // set the cell properties - cell.TextLabel.Text = this.tableItems[indexPath.Row]; + cell.TextLabel.Text = this.tableItems [indexPath.Row]; // return the cell return cell; diff --git a/Rotation/HandlingRotation/Screens/iPhone/Method2MoveControls/Controller.cs b/Rotation/HandlingRotation/Screens/iPhone/Method2MoveControls/Controller.cs index a312d357d..11e16da41 100755 --- a/Rotation/HandlingRotation/Screens/iPhone/Method2MoveControls/Controller.cs +++ b/Rotation/HandlingRotation/Screens/iPhone/Method2MoveControls/Controller.cs @@ -2,11 +2,10 @@ using UIKit; namespace HandlingRotation.Screens.iPhone.Method2MoveControls { - public class Controller : UIViewController - { + public class Controller : UIViewController { UIButton button1 = UIButton.FromType (UIButtonType.RoundedRect); UIButton button2 = UIButton.FromType (UIButtonType.RoundedRect); - UIImageView image = new UIImageView(UIImage.FromBundle("icon-144.png")); + UIImageView image = new UIImageView (UIImage.FromBundle ("icon-144.png")); public Controller () { @@ -44,12 +43,12 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // just return true, but this switch illustrates how you can test for the // different cases switch (toInterfaceOrientation) { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } @@ -77,31 +76,31 @@ protected void PositionControls (UIInterfaceOrientation toInterfaceOrientation) // depending one what orientation we start in, we want to position our controls // appropriately switch (toInterfaceOrientation) { - // if we're switching to landscape - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: + // if we're switching to landscape + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: - // reposition the buttons - button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); - button2.Frame = new CoreGraphics.CGRect (10, 200, 100, 33); + // reposition the buttons + button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); + button2.Frame = new CoreGraphics.CGRect (10, 200, 100, 33); - // reposition the image - image.Frame = new CoreGraphics.CGRect (240, 25, image.Frame.Width, image.Frame.Height); + // reposition the image + image.Frame = new CoreGraphics.CGRect (240, 25, image.Frame.Width, image.Frame.Height); - break; + break; - // we're switching back to portrait - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: + // we're switching back to portrait + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: - // reposition the buttons - button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); - button2.Frame = new CoreGraphics.CGRect (200, 10, 100, 33); + // reposition the buttons + button1.Frame = new CoreGraphics.CGRect (10, 10, 100, 33); + button2.Frame = new CoreGraphics.CGRect (200, 10, 100, 33); - // reposition the image - image.Frame = new CoreGraphics.CGRect (20, 150, this.image.Frame.Width, this.image.Frame.Height); + // reposition the image + image.Frame = new CoreGraphics.CGRect (20, 150, this.image.Frame.Width, this.image.Frame.Height); - break; + break; } } } diff --git a/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/Controller.cs b/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/Controller.cs index d50f81473..33314bb5c 100755 --- a/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/Controller.cs +++ b/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/Controller.cs @@ -19,21 +19,21 @@ public override void LoadView () base.LoadView (); switch (InterfaceOrientation) { - // if we're switching to landscape - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: + // if we're switching to landscape + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: - NSBundle.MainBundle.LoadNib ("LandscapeView", this, null); + NSBundle.MainBundle.LoadNib ("LandscapeView", this, null); - break; + break; - // we're switching back to portrait - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: + // we're switching back to portrait + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: - NSBundle.MainBundle.LoadNib ("PortraitView", this, null); + NSBundle.MainBundle.LoadNib ("PortraitView", this, null); - break; + break; } } @@ -55,14 +55,13 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat // we're passed to orientation that it will rotate to. in our case, we could // just return true, but this switch illustrates how you can test for the // different cases - switch (toInterfaceOrientation) - { - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: - default: - return true; + switch (toInterfaceOrientation) { + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: + default: + return true; } } @@ -76,21 +75,21 @@ public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrie base.WillAnimateRotation (toInterfaceOrientation, duration); switch (toInterfaceOrientation) { - // if we're switching to landscape - case UIInterfaceOrientation.LandscapeLeft: - case UIInterfaceOrientation.LandscapeRight: + // if we're switching to landscape + case UIInterfaceOrientation.LandscapeLeft: + case UIInterfaceOrientation.LandscapeRight: - NSBundle.MainBundle.LoadNib ("LandscapeView", this, null); + NSBundle.MainBundle.LoadNib ("LandscapeView", this, null); - break; + break; - // we're switch back to portrait - case UIInterfaceOrientation.Portrait: - case UIInterfaceOrientation.PortraitUpsideDown: + // we're switch back to portrait + case UIInterfaceOrientation.Portrait: + case UIInterfaceOrientation.PortraitUpsideDown: - NSBundle.MainBundle.LoadNib ("PortraitView", this, null); + NSBundle.MainBundle.LoadNib ("PortraitView", this, null); - break; + break; } } } diff --git a/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/LandscapeView.xib.cs b/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/LandscapeView.xib.cs index 114499e88..04e37d6b9 100755 --- a/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/LandscapeView.xib.cs +++ b/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/LandscapeView.xib.cs @@ -5,9 +5,7 @@ using Foundation; using UIKit; -namespace HandlingRotation.Screens.iPhone.Method3SwapViews -{ - public partial class LandscapeView : UIView - { +namespace HandlingRotation.Screens.iPhone.Method3SwapViews { + public partial class LandscapeView : UIView { } } diff --git a/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/PortraitView.xib.cs b/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/PortraitView.xib.cs index b02fc7136..27412caed 100755 --- a/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/PortraitView.xib.cs +++ b/Rotation/HandlingRotation/Screens/iPhone/Method3SwapViews/PortraitView.xib.cs @@ -5,9 +5,8 @@ using Foundation; using UIKit; -namespace HandlingRotation.Screens.iPhone.Method3SwapViews -{ - public partial class PortraitView : UIView {} +namespace HandlingRotation.Screens.iPhone.Method3SwapViews { + public partial class PortraitView : UIView { } } diff --git a/ScratchTicket/ScratchTicket/AppDelegate.cs b/ScratchTicket/ScratchTicket/AppDelegate.cs index 6e1aed709..267411e3a 100644 --- a/ScratchTicket/ScratchTicket/AppDelegate.cs +++ b/ScratchTicket/ScratchTicket/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace ScratchTicket -{ +namespace ScratchTicket { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ScratchTicket/ScratchTicket/Main.cs b/ScratchTicket/ScratchTicket/Main.cs index fe240c77b..16be956d9 100644 --- a/ScratchTicket/ScratchTicket/Main.cs +++ b/ScratchTicket/ScratchTicket/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace ScratchTicket -{ - public class Application - { +namespace ScratchTicket { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ScratchTicket/ScratchTicket/ScratchTicketView.cs b/ScratchTicket/ScratchTicket/ScratchTicketView.cs index b6ed1a40a..ef6a2d2f7 100644 --- a/ScratchTicket/ScratchTicket/ScratchTicketView.cs +++ b/ScratchTicket/ScratchTicket/ScratchTicketView.cs @@ -1,114 +1,103 @@ -using System; +using System; using System.ComponentModel; using CoreGraphics; using Foundation; using UIKit; -namespace ScratchTicket -{ - [Register("ScratchTicketView"), DesignTimeVisible(true)] - public class ScratchTicketView : UIView - { +namespace ScratchTicket { + [Register ("ScratchTicketView"), DesignTimeVisible (true)] + public class ScratchTicketView : UIView { CGPath path; CGPoint initialPoint; CGPoint latestPoint; bool startNewPath = false; UIImage image; - [Export("Image"), Browsable(true)] - public UIImage Image - { + [Export ("Image"), Browsable (true)] + public UIImage Image { get { return image; } - set - { + set { image = value; - SetNeedsDisplay(); + SetNeedsDisplay (); } } - public ScratchTicketView(IntPtr p) - : base(p) + public ScratchTicketView (IntPtr p) + : base (p) { - Initialize(); + Initialize (); } - public ScratchTicketView() + public ScratchTicketView () { - Initialize(); + Initialize (); } - void Initialize() + void Initialize () { initialPoint = CGPoint.Empty; latestPoint = CGPoint.Empty; BackgroundColor = UIColor.Clear; Opaque = false; - path = new CGPath(); - SetNeedsDisplay(); + path = new CGPath (); + SetNeedsDisplay (); } - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); + base.TouchesBegan (touches, evt); var touch = touches.AnyObject as UITouch; - if (touch != null) - { - initialPoint = touch.LocationInView(this); + if (touch != null) { + initialPoint = touch.LocationInView (this); } } - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); var touch = touches.AnyObject as UITouch; - if (touch != null) - { - latestPoint = touch.LocationInView(this); - SetNeedsDisplay(); + if (touch != null) { + latestPoint = touch.LocationInView (this); + SetNeedsDisplay (); } } - public override void TouchesEnded(NSSet touches, UIEvent evt) + public override void TouchesEnded (NSSet touches, UIEvent evt) { - base.TouchesEnded(touches, evt); + base.TouchesEnded (touches, evt); startNewPath = true; } - public override void Draw(CGRect rect) + public override void Draw (CGRect rect) { - base.Draw(rect); + base.Draw (rect); - using (var g = UIGraphics.GetCurrentContext()) - { + using (var g = UIGraphics.GetCurrentContext ()) { if (image != null) - g.SetFillColor((UIColor.FromPatternImage(image).CGColor)); + g.SetFillColor ((UIColor.FromPatternImage (image).CGColor)); else - g.SetFillColor(UIColor.LightGray.CGColor); - g.FillRect(rect); - - if (!initialPoint.IsEmpty) - { - g.SetLineWidth(20); - g.SetBlendMode(CGBlendMode.Clear); - UIColor.Clear.SetColor(); - - if (path.IsEmpty || startNewPath) - { - path.AddLines(new CGPoint[] { initialPoint, latestPoint }); + g.SetFillColor (UIColor.LightGray.CGColor); + g.FillRect (rect); + + if (!initialPoint.IsEmpty) { + g.SetLineWidth (20); + g.SetBlendMode (CGBlendMode.Clear); + UIColor.Clear.SetColor (); + + if (path.IsEmpty || startNewPath) { + path.AddLines (new CGPoint [] { initialPoint, latestPoint }); startNewPath = false; - } - else - { - path.AddLineToPoint(latestPoint); + } else { + path.AddLineToPoint (latestPoint); } - g.SetLineCap(CGLineCap.Round); - g.AddPath(path); - g.DrawPath(CGPathDrawingMode.Stroke); + g.SetLineCap (CGLineCap.Round); + g.AddPath (path); + g.DrawPath (CGPathDrawingMode.Stroke); } } } diff --git a/ScratchTicket/ScratchTicket/ViewController.cs b/ScratchTicket/ScratchTicket/ViewController.cs index 38eadf7d7..a3930b661 100644 --- a/ScratchTicket/ScratchTicket/ViewController.cs +++ b/ScratchTicket/ScratchTicket/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace ScratchTicket -{ - public partial class ViewController : UIViewController - { +namespace ScratchTicket { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } diff --git a/SearchDemo/SearchDemo/AppDelegate.cs b/SearchDemo/SearchDemo/AppDelegate.cs index 844b62a50..30f5ab292 100644 --- a/SearchDemo/SearchDemo/AppDelegate.cs +++ b/SearchDemo/SearchDemo/AppDelegate.cs @@ -5,36 +5,34 @@ using Foundation; using UIKit; -namespace SearchDemo -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; - UINavigationController navController; - SearchResultsController searchResultsController; +namespace SearchDemo { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; + UINavigationController navController; + SearchResultsController searchResultsController; - // - // This method is invoked when the application has loaded and is ready to run. In this - // method you should instantiate the window, load the UI into it and then make the window - // visible. - // - // You have 17 seconds to return from this method, or iOS will terminate your application. - // - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); + // + // This method is invoked when the application has loaded and is ready to run. In this + // method you should instantiate the window, load the UI into it and then make the window + // visible. + // + // You have 17 seconds to return from this method, or iOS will terminate your application. + // + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); - searchResultsController = new SearchResultsController (); - navController = new UINavigationController (searchResultsController); - window.RootViewController = navController; - window.MakeKeyAndVisible (); + searchResultsController = new SearchResultsController (); + navController = new UINavigationController (searchResultsController); + window.RootViewController = navController; + window.MakeKeyAndVisible (); - return true; - } - } + return true; + } + } } diff --git a/SearchDemo/SearchDemo/Bing.cs b/SearchDemo/SearchDemo/Bing.cs index 0da4ecd3f..9f82fcd65 100644 --- a/SearchDemo/SearchDemo/Bing.cs +++ b/SearchDemo/SearchDemo/Bing.cs @@ -7,53 +7,51 @@ using System.Web; using Foundation; -namespace SearchDemo -{ - public delegate void SynchronizerDelegate (List<SearchItem> results); +namespace SearchDemo { + public delegate void SynchronizerDelegate (List<SearchItem> results); - public class Bing - { - const string AZURE_KEY = "Enter API key here"; + public class Bing { + const string AZURE_KEY = "Enter API key here"; - static SynchronizerDelegate sync; + static SynchronizerDelegate sync; - public Bing (SynchronizerDelegate sync) - { - Bing.sync = sync; - } + public Bing (SynchronizerDelegate sync) + { + Bing.sync = sync; + } - public void Search (string text) - { - var t = new Thread (Search); - t.Start (text); - } + public void Search (string text) + { + var t = new Thread (Search); + t.Start (text); + } - void Search (object text) - { - string bingSearch = String.Format ("https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27{0}%27&$top=10&$format=Json", text); + void Search (object text) + { + string bingSearch = String.Format ("https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27{0}%27&$top=10&$format=Json", text); - var httpReq = (HttpWebRequest)HttpWebRequest.Create (new Uri (bingSearch)); + var httpReq = (HttpWebRequest) HttpWebRequest.Create (new Uri (bingSearch)); - httpReq.Credentials = new NetworkCredential (AZURE_KEY, AZURE_KEY); + httpReq.Credentials = new NetworkCredential (AZURE_KEY, AZURE_KEY); - try { - using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse ()) { + try { + using (HttpWebResponse httpRes = (HttpWebResponse) httpReq.GetResponse ()) { - var response = httpRes.GetResponseStream (); - var json = (JsonObject)JsonObject.Load (response); + var response = httpRes.GetResponseStream (); + var json = (JsonObject) JsonObject.Load (response); - var results = (from result in (JsonArray)json ["d"] ["results"] - let jResult = result as JsonObject - select new SearchItem { Title = jResult["Title"], Url = jResult["Url"] }).ToList (); + var results = (from result in (JsonArray) json ["d"] ["results"] + let jResult = result as JsonObject + select new SearchItem { Title = jResult ["Title"], Url = jResult ["Url"] }).ToList (); - if (sync != null) - sync (results); - } - } catch (Exception) { - if (sync != null) - sync (null); - } - } + if (sync != null) + sync (results); + } + } catch (Exception) { + if (sync != null) + sync (null); + } + } - } + } } diff --git a/SearchDemo/SearchDemo/Main.cs b/SearchDemo/SearchDemo/Main.cs index 2397d4953..ce46161dc 100644 --- a/SearchDemo/SearchDemo/Main.cs +++ b/SearchDemo/SearchDemo/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace SearchDemo -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace SearchDemo { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/SearchDemo/SearchDemo/SearchItem.cs b/SearchDemo/SearchDemo/SearchItem.cs index 8c1ed07be..52206300d 100644 --- a/SearchDemo/SearchDemo/SearchItem.cs +++ b/SearchDemo/SearchDemo/SearchItem.cs @@ -1,16 +1,14 @@ using System; -namespace SearchDemo -{ - public class SearchItem - { - public SearchItem () - { - } +namespace SearchDemo { + public class SearchItem { + public SearchItem () + { + } - public string Title { get; set; } + public string Title { get; set; } - public string Url { get; set; } - } + public string Url { get; set; } + } } diff --git a/SearchDemo/SearchDemo/SearchItemViewController.cs b/SearchDemo/SearchDemo/SearchItemViewController.cs index 238e1c4bc..b7a60acb0 100644 --- a/SearchDemo/SearchDemo/SearchItemViewController.cs +++ b/SearchDemo/SearchDemo/SearchItemViewController.cs @@ -4,30 +4,28 @@ using Foundation; using UIKit; -namespace SearchDemo -{ - public partial class SearchItemViewController : UIViewController - { - public SearchItem Item { get; set; } - - public SearchItemViewController () : base ("SearchItemViewController", null) - { - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - webView.LoadStarted += (sender, e) => { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - }; - - webView.LoadFinished += (sender, e) => { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - }; - - webView.LoadRequest (new NSUrlRequest (new NSUrl (Item.Url))); - } - } +namespace SearchDemo { + public partial class SearchItemViewController : UIViewController { + public SearchItem Item { get; set; } + + public SearchItemViewController () : base ("SearchItemViewController", null) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + webView.LoadStarted += (sender, e) => { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; + }; + + webView.LoadFinished += (sender, e) => { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + }; + + webView.LoadRequest (new NSUrlRequest (new NSUrl (Item.Url))); + } + } } diff --git a/SearchDemo/SearchDemo/SearchResultsController.cs b/SearchDemo/SearchDemo/SearchResultsController.cs index 36ee3fc50..57d8cc817 100644 --- a/SearchDemo/SearchDemo/SearchResultsController.cs +++ b/SearchDemo/SearchDemo/SearchResultsController.cs @@ -5,95 +5,93 @@ using UIKit; using CoreGraphics; -namespace SearchDemo -{ - public partial class SearchResultsController : UITableViewController - { - static NSString cellId = new NSString ("SearchResultCell"); - List<SearchItem> searchResults; - UISearchBar searchBar; - - public SearchResultsController () - { - searchResults = new List<SearchItem> (); - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - Title = "Bing Search Demo "; - TableView.Source = new TableSource (this); - - searchBar = new UISearchBar (); - searchBar.Placeholder = "Enter Search Text"; - searchBar.SizeToFit (); - searchBar.AutocorrectionType = UITextAutocorrectionType.No; - searchBar.AutocapitalizationType = UITextAutocapitalizationType.None; - searchBar.SearchButtonClicked += (sender, e) => { - Search (); - }; - - TableView.TableHeaderView = searchBar; - } - - void Search () - { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - var bing = new Bing (SyncToMain); - bing.Search (searchBar.Text); - searchBar.ResignFirstResponder (); - } - - void SyncToMain (List<SearchItem> results) - { - this.InvokeOnMainThread (delegate { - if (results != null) { - searchResults = results; - TableView.ReloadData (); - } else { - new UIAlertView ("", "Could not retrieve results", null, "OK").Show (); - } - - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - }); - } - - class TableSource : UITableViewSource - { - SearchResultsController controller; - - public TableSource (SearchResultsController controller) - { - this.controller = controller; - } - - public override nint RowsInSection (UITableView tableView, nint section) - { - return controller.searchResults.Count; - } - - public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) - { - UITableViewCell cell = tableView.DequeueReusableCell (cellId); - - if (cell == null) - cell = new UITableViewCell ( - UITableViewCellStyle.Default, - cellId - ); - - cell.TextLabel.Text = controller.searchResults [indexPath.Row].Title; - - return cell; - } - - public override void RowSelected (UITableView tableView, NSIndexPath indexPath) - { - var vc = new SearchItemViewController (){Item = controller.searchResults [indexPath.Row]}; - controller.NavigationController.PushViewController (vc, true); - } - } - } +namespace SearchDemo { + public partial class SearchResultsController : UITableViewController { + static NSString cellId = new NSString ("SearchResultCell"); + List<SearchItem> searchResults; + UISearchBar searchBar; + + public SearchResultsController () + { + searchResults = new List<SearchItem> (); + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + Title = "Bing Search Demo "; + TableView.Source = new TableSource (this); + + searchBar = new UISearchBar (); + searchBar.Placeholder = "Enter Search Text"; + searchBar.SizeToFit (); + searchBar.AutocorrectionType = UITextAutocorrectionType.No; + searchBar.AutocapitalizationType = UITextAutocapitalizationType.None; + searchBar.SearchButtonClicked += (sender, e) => { + Search (); + }; + + TableView.TableHeaderView = searchBar; + } + + void Search () + { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; + var bing = new Bing (SyncToMain); + bing.Search (searchBar.Text); + searchBar.ResignFirstResponder (); + } + + void SyncToMain (List<SearchItem> results) + { + this.InvokeOnMainThread (delegate + { + if (results != null) { + searchResults = results; + TableView.ReloadData (); + } else { + new UIAlertView ("", "Could not retrieve results", null, "OK").Show (); + } + + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + }); + } + + class TableSource : UITableViewSource { + SearchResultsController controller; + + public TableSource (SearchResultsController controller) + { + this.controller = controller; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return controller.searchResults.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + UITableViewCell cell = tableView.DequeueReusableCell (cellId); + + if (cell == null) + cell = new UITableViewCell ( + UITableViewCellStyle.Default, + cellId + ); + + cell.TextLabel.Text = controller.searchResults [indexPath.Row].Title; + + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var vc = new SearchItemViewController () { Item = controller.searchResults [indexPath.Row] }; + controller.NavigationController.PushViewController (vc, true); + } + } + } } diff --git a/SharedResources/SharedResources/AppDelegate.cs b/SharedResources/SharedResources/AppDelegate.cs index 28d20ebec..2eb3c1c46 100755 --- a/SharedResources/SharedResources/AppDelegate.cs +++ b/SharedResources/SharedResources/AppDelegate.cs @@ -2,12 +2,10 @@ using UIKit; using Foundation; -namespace Example_SharedResources -{ +namespace Example_SharedResources { //======================================================================== - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { //======================================================================== #region -= declarations and properties =- @@ -44,12 +42,10 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) /// Keeps a running reference of items that want to turn the network activity on or off /// so it doesn't get turned off by one activity if another is still active /// </summary> - public void SetNetworkActivityIndicator(bool onOrOff) + public void SetNetworkActivityIndicator (bool onOrOff) { //---- increment or decrement our reference count - if(onOrOff) - { networkActivityCount++; } - else { networkActivityCount--; } + if (onOrOff) { networkActivityCount++; } else { networkActivityCount--; } //---- set it's visibility based on whether or not there is still activity UIApplication.SharedApplication.NetworkActivityIndicatorVisible = (networkActivityCount > 0); diff --git a/SharedResources/SharedResources/Application.cs b/SharedResources/SharedResources/Application.cs index 68a16ee9d..813c6ef52 100755 --- a/SharedResources/SharedResources/Application.cs +++ b/SharedResources/SharedResources/Application.cs @@ -1,18 +1,14 @@ using System; using UIKit; -namespace Example_SharedResources -{ +namespace Example_SharedResources { public class Application// : UIApplication { - public static void Main (string[] args) + public static void Main (string [] args) { - try - { + try { UIApplication.Main (args, null, "AppDelegate"); - } - catch (Exception e) - { + } catch (Exception e) { Console.WriteLine (e.ToString ()); } } diff --git a/SharedResources/SharedResources/Code/NavItem.cs b/SharedResources/SharedResources/Code/NavItem.cs index 4a28d5087..1cc37a951 100755 --- a/SharedResources/SharedResources/Code/NavItem.cs +++ b/SharedResources/SharedResources/Code/NavItem.cs @@ -2,15 +2,12 @@ using System; using UIKit; -namespace Example_SharedResources.Code -{ - public class NavItem - { +namespace Example_SharedResources.Code { + public class NavItem { /// <summary> /// The name of the nav item, shows up as the label /// </summary> - public string Name - { + public string Name { get { return name; } set { name = value; } } @@ -22,8 +19,7 @@ public string Name /// otherwise just set the Type property and it will lazy-instantiate when the /// nav item is clicked on. /// </summary> - public UIViewController Controller - { + public UIViewController Controller { get { return controller; } set { controller = value; } } @@ -32,8 +28,7 @@ public UIViewController Controller /// <summary> /// Path to the image to show in the nav item /// </summary> - public string ImagePath - { + public string ImagePath { get { return imagePath; } set { imagePath = value; } } @@ -44,8 +39,7 @@ public string ImagePath /// property empty to lazy-instantiate the ViewController when the nav item is /// clicked. /// </summary> - public Type ControllerType - { + public Type ControllerType { get { return controllerType; } set { controllerType = value; } } @@ -55,35 +49,32 @@ public Type ControllerType /// a list of the constructor args (if neccesary) for the controller. use this in /// conjunction with ControllerType if lazy-creating controllers. /// </summary> - public object[] ControllerConstructorArgs - { + public object [] ControllerConstructorArgs { get { return controllerConstructorArgs; } - set - { + set { controllerConstructorArgs = value; - controllerConstructorTypes = new Type[controllerConstructorArgs.Length]; + controllerConstructorTypes = new Type [controllerConstructorArgs.Length]; for (int i = 0; i < controllerConstructorArgs.Length; i++) { - controllerConstructorTypes[i] = controllerConstructorArgs[i].GetType (); + controllerConstructorTypes [i] = controllerConstructorArgs [i].GetType (); } } } - protected object[] controllerConstructorArgs = new object[] {}; + protected object [] controllerConstructorArgs = new object [] { }; /// <summary> /// The types of constructor args. /// </summary> - public Type[] ControllerConstructorTypes - { + public Type [] ControllerConstructorTypes { get { return controllerConstructorTypes; } } - protected Type[] controllerConstructorTypes = Type.EmptyTypes; + protected Type [] controllerConstructorTypes = Type.EmptyTypes; public NavItem () { } - public NavItem (string name) : this() + public NavItem (string name) : this () { this.name = name; } @@ -98,7 +89,7 @@ public NavItem (string name, Type controllerType) : this (name) this.controllerType = controllerType; } - public NavItem (string name, Type controllerType, object[] controllerConstructorArgs) : this (name, controllerType) + public NavItem (string name, Type controllerType, object [] controllerConstructorArgs) : this (name, controllerType) { this.ControllerConstructorArgs = controllerConstructorArgs; } @@ -113,7 +104,7 @@ public NavItem (string name, string imagePath, Type controllerType) : this (name this.imagePath = imagePath; } - public NavItem (string name, string imagePath, Type controllerType, object[] controllerConstructorArgs) : this (name, controllerType, controllerConstructorArgs) + public NavItem (string name, string imagePath, Type controllerType, object [] controllerConstructorArgs) : this (name, controllerType, controllerConstructorArgs) { this.imagePath = imagePath; } diff --git a/SharedResources/SharedResources/Code/NavItemGroup.cs b/SharedResources/SharedResources/Code/NavItemGroup.cs index 24dc58381..49e51a5c7 100755 --- a/SharedResources/SharedResources/Code/NavItemGroup.cs +++ b/SharedResources/SharedResources/Code/NavItemGroup.cs @@ -1,19 +1,16 @@ using System; using System.Collections.Generic; -namespace Example_SharedResources.Code -{ +namespace Example_SharedResources.Code { /// <summary> /// A group that contains table items /// </summary> - public class NavItemGroup - { + public class NavItemGroup { public string Name { get; set; } public string Footer { get; set; } - public List<NavItem> Items - { + public List<NavItem> Items { get { return items; } set { items = value; } } diff --git a/SharedResources/SharedResources/Code/NavItemTableSource.cs b/SharedResources/SharedResources/Code/NavItemTableSource.cs index 60a2efd05..5cf3a6743 100755 --- a/SharedResources/SharedResources/Code/NavItemTableSource.cs +++ b/SharedResources/SharedResources/Code/NavItemTableSource.cs @@ -4,13 +4,11 @@ using Foundation; using System.Reflection; -namespace Example_SharedResources.Code -{ +namespace Example_SharedResources.Code { /// <summary> /// Combined DataSource and Delegate for our UITableView /// </summary> - public class NavItemTableSource : UITableViewSource - { + public class NavItemTableSource : UITableViewSource { protected List<NavItemGroup> navItems; string cellIdentifier = "NavTableCellView"; UINavigationController navigationController; @@ -35,7 +33,7 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableview, nint section) { //HACK: Parse section to int - return navItems[(int)section].Items.Count; + return navItems [(int) section].Items.Count; } /// <summary> @@ -44,7 +42,7 @@ public override nint RowsInSection (UITableView tableview, nint section) public override string TitleForHeader (UITableView tableView, nint section) { //HACK: Parse section to int - return navItems[(int)section].Name; + return navItems [(int) section].Name; } /// <summary> @@ -53,7 +51,7 @@ public override string TitleForHeader (UITableView tableView, nint section) public override string TitleForFooter (UITableView tableView, nint section) { //HACK: Parse section to int - return navItems[(int)section].Footer; + return navItems [(int) section].Footer; } /// <summary> @@ -62,7 +60,7 @@ public override string TitleForFooter (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { // declare vars - NavItem navItem = navItems[indexPath.Section].Items[indexPath.Row]; + NavItem navItem = navItems [indexPath.Section].Items [indexPath.Row]; var cell = tableView.DequeueReusableCell (this.cellIdentifier); if (cell == null) { @@ -71,7 +69,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde } // set the cell properties - cell.TextLabel.Text = navItems[indexPath.Section].Items[indexPath.Row].Name; + cell.TextLabel.Text = navItems [indexPath.Section].Items [indexPath.Row].Name; cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; // return the cell @@ -84,7 +82,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { // get a reference to the nav item - NavItem navItem = navItems[indexPath.Section].Items[indexPath.Row]; + NavItem navItem = navItems [indexPath.Section].Items [indexPath.Row]; // if the nav item has a proper controller, push it on to the NavigationController // NOTE: we could also raise an event here, to loosely couple this, but isn't neccessary, @@ -93,9 +91,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) navigationController.PushViewController (navItem.Controller, true); // show the nav bar (we don't show it on the home page) navigationController.NavigationBarHidden = false; - } - else - { + } else { if (navItem.ControllerType != null) { // ConstructorInfo ctor = null; @@ -104,23 +100,20 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) if (navItem.ControllerConstructorArgs.Length > 0) { // look for the constructor ctor = navItem.ControllerType.GetConstructor (navItem.ControllerConstructorTypes); - } - else { + } else { // search for the default constructor ctor = navItem.ControllerType.GetConstructor (System.Type.EmptyTypes); } // if we found the constructor - if (ctor != null) - { + if (ctor != null) { // UIViewController instance = null; if (navItem.ControllerConstructorArgs.Length > 0) { // instance the view controller instance = ctor.Invoke (navItem.ControllerConstructorArgs) as UIViewController; - } - else { + } else { // instance the view controller instance = ctor.Invoke (null) as UIViewController; } @@ -131,13 +124,10 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) // push the view controller onto the stack navigationController.PushViewController (navItem.Controller, true); - } - else { + } else { Console.WriteLine ("instance of view controller not created"); } - } - else - { + } else { Console.WriteLine ("constructor not found"); } } diff --git a/SharedResources/SharedResources/Code/Network/NetworkStatus.cs b/SharedResources/SharedResources/Code/Network/NetworkStatus.cs index 0346b2721..116380716 100644 --- a/SharedResources/SharedResources/Code/Network/NetworkStatus.cs +++ b/SharedResources/SharedResources/Code/Network/NetworkStatus.cs @@ -1,11 +1,9 @@ using System; -namespace Example_SharedResources.Code.Network -{ +namespace Example_SharedResources.Code.Network { /// <summary> /// Contains the potential network availability status /// </summary> - public enum NetworkStatus - { + public enum NetworkStatus { NotReachable, ReachableViaCarrierDataNetwork, ReachableViaWiFiNetwork diff --git a/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetEnumerationScreen.cs b/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetEnumerationScreen.cs index 9f8f8e449..e6b069df4 100644 --- a/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetEnumerationScreen.cs +++ b/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetEnumerationScreen.cs @@ -4,10 +4,8 @@ using Foundation; using System.Collections.Generic; -namespace Example_SharedResources.Screens.iPhone.AVAssets -{ - public class AssetEnumerationScreen : UITableViewController - { +namespace Example_SharedResources.Screens.iPhone.AVAssets { + public class AssetEnumerationScreen : UITableViewController { // declare vars string groupName = string.Empty; List<ALAsset> assets = null; @@ -27,15 +25,14 @@ public override void ViewDidLoad () Title = groupName; // create our table source - dataSource = new AssetsDataSource(assets); + dataSource = new AssetsDataSource (assets); TableView.Source = dataSource; } /// <summary> /// Simple data source to display the assets /// </summary> - protected class AssetsDataSource : UITableViewSource - { + protected class AssetsDataSource : UITableViewSource { protected List<ALAsset> items; public AssetsDataSource (List<ALAsset> items) { this.items = items; } @@ -50,15 +47,15 @@ public override nint RowsInSection (UITableView tableview, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell ("AssetCell"); - if(cell == null) + if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Subtitle, "AssetCell"); // set the text - cell.TextLabel.Text = items[indexPath.Row].AssetType.ToString (); - cell.DetailTextLabel.Text = items[indexPath.Row].Date.ToString (); + cell.TextLabel.Text = items [indexPath.Row].AssetType.ToString (); + cell.DetailTextLabel.Text = items [indexPath.Row].Date.ToString (); // set the image - if(items[indexPath.Row].Thumbnail != null) - cell.ImageView.Image = UIImage.FromImage(items[indexPath.Row].Thumbnail); + if (items [indexPath.Row].Thumbnail != null) + cell.ImageView.Image = UIImage.FromImage (items [indexPath.Row].Thumbnail); return cell; } diff --git a/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetGroupEnumerationScreen.cs b/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetGroupEnumerationScreen.cs index ac08a040b..302fc0fca 100644 --- a/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetGroupEnumerationScreen.cs +++ b/SharedResources/SharedResources/Screens/iPhone/AVAssets/AssetGroupEnumerationScreen.cs @@ -4,10 +4,8 @@ using Foundation; using System.Collections.Generic; -namespace Example_SharedResources.Screens.iPhone.AVAssets -{ - public class AssetGroupEnumerationScreen : UITableViewController - { +namespace Example_SharedResources.Screens.iPhone.AVAssets { + public class AssetGroupEnumerationScreen : UITableViewController { // declare vars protected ALAssetsLibrary assetsLibrary; protected AssetGroupTableSource assetGroupTableSource; @@ -24,9 +22,9 @@ public override void ViewDidLoad () Title = "All Asset Groups"; // instantiate a reference to the shared assets library - assetsLibrary = new ALAssetsLibrary(); + assetsLibrary = new ALAssetsLibrary (); // enumerate the photo albums - assetsLibrary.Enumerate(ALAssetsGroupType.All, GroupsEnumerator, + assetsLibrary.Enumerate (ALAssetsGroupType.All, GroupsEnumerator, (NSError e) => { Console.WriteLine ("Could not enumerate albums: " + e.LocalizedDescription); }); } @@ -34,7 +32,7 @@ public override void ViewDidLoad () // Called for each group that is enumerated protected void GroupsEnumerator (ALAssetsGroup group, ref bool stop) { - // when the enumeration is completed, this method is invoked with group set to null + // when the enumeration is completed, this method is invoked with group set to null if (group != null) { Console.WriteLine ("Group found: " + group.Type.ToString ()); @@ -45,23 +43,23 @@ protected void GroupsEnumerator (ALAssetsGroup group, ref bool stop) group.SetAssetsFilter (ALAssetsFilter.AllAssets); if (group.Name != null) - Console.WriteLine("Group Name: " + group.Name); + Console.WriteLine ("Group Name: " + group.Name); // add the group to the assets dictionary - groups.Add(group); - assetGroups.Add(group, new List<ALAsset> ()); + groups.Add (group); + assetGroups.Add (group, new List<ALAsset> ()); currentGroup = group; // enumerate each asset within the group - group.Enumerate(AssetEnumerator); - } else { + group.Enumerate (AssetEnumerator); + } else { Console.WriteLine ("Group enumeration completed."); assetGroupTableSource = new AssetGroupTableSource (groups); TableView.Source = assetGroupTableSource; assetGroupTableSource.GroupSelected += (object sender, AssetGroupTableSource.GroupSelectedEventArgs e) => { - AssetEnumerationScreen assetScreen = new AssetEnumerationScreen (e.Group.Name, assetGroups[e.Group]); + AssetEnumerationScreen assetScreen = new AssetEnumerationScreen (e.Group.Name, assetGroups [e.Group]); NavigationController.PushViewController (assetScreen, true); }; @@ -74,31 +72,29 @@ protected void GroupsEnumerator (ALAssetsGroup group, ref bool stop) /// </summary> protected void AssetEnumerator (ALAsset asset, nint index, ref bool stop) { - // when the enumeration is completed, this method is invoked with group set to null - if(asset != null) { + // when the enumeration is completed, this method is invoked with group set to null + if (asset != null) { Console.WriteLine ("Found asset: " + index.ToString ()); // add the asset to the group list - assetGroups[currentGroup].Add (asset); + assetGroups [currentGroup].Add (asset); // keep going stop = false; //Console.WriteLine(asset.AssetType.ToString()); - } - else - Console.WriteLine("Asset enumeration completed."); + } else + Console.WriteLine ("Asset enumeration completed."); } /// <summary> /// Simple data source to display the asset groups /// </summary> - protected class AssetGroupTableSource : UITableViewSource - { + protected class AssetGroupTableSource : UITableViewSource { public event EventHandler<GroupSelectedEventArgs> GroupSelected; protected List<ALAssetsGroup> groups; - public AssetGroupTableSource(List<ALAssetsGroup> groups) { this.groups = groups; } + public AssetGroupTableSource (List<ALAssetsGroup> groups) { this.groups = groups; } public override nint NumberOfSections (UITableView tableView) { return 1; } @@ -107,9 +103,9 @@ protected class AssetGroupTableSource : UITableViewSource public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell ("AlbumCell"); - if(cell == null) + if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Default, "AlbumCell"); - cell.TextLabel.Text = groups[indexPath.Row].Name; + cell.TextLabel.Text = groups [indexPath.Row].Name; return cell; } @@ -118,13 +114,12 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) // raise our event var handler = GroupSelected; if (handler != null) - handler (this, new GroupSelectedEventArgs (groups[indexPath.Row])); + handler (this, new GroupSelectedEventArgs (groups [indexPath.Row])); } - public class GroupSelectedEventArgs : EventArgs - { + public class GroupSelectedEventArgs : EventArgs { public ALAssetsGroup Group { get; set; } - public GroupSelectedEventArgs(ALAssetsGroup group) : base() + public GroupSelectedEventArgs (ALAssetsGroup group) : base () { Group = group; } } } diff --git a/SharedResources/SharedResources/Screens/iPhone/AVAssets/PhotoLibraryController.cs b/SharedResources/SharedResources/Screens/iPhone/AVAssets/PhotoLibraryController.cs index fc4151065..cea4b2d4e 100644 --- a/SharedResources/SharedResources/Screens/iPhone/AVAssets/PhotoLibraryController.cs +++ b/SharedResources/SharedResources/Screens/iPhone/AVAssets/PhotoLibraryController.cs @@ -2,10 +2,8 @@ using UIKit; using AssetsLibrary; -namespace Example_SharedResources.Screens.iPhone.AVAssets -{ - public class PhotoLibraryController : UITableViewController - { +namespace Example_SharedResources.Screens.iPhone.AVAssets { + public class PhotoLibraryController : UITableViewController { public PhotoLibraryController () { diff --git a/SharedResources/SharedResources/Screens/iPhone/Accelerometer/ShakeScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Accelerometer/ShakeScreen.xib.cs index cd5524b35..dd19f683d 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Accelerometer/ShakeScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Accelerometer/ShakeScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Accelerometer -{ - public partial class ShakeScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Accelerometer { + public partial class ShakeScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public ShakeScreen (IntPtr handle) : base(handle) + public ShakeScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public ShakeScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public ShakeScreen (NSCoder coder) : base (coder) { Initialize (); } - public ShakeScreen () : base("ShakeScreen", null) + public ShakeScreen () : base ("ShakeScreen", null) { Initialize (); } @@ -45,8 +43,7 @@ public override void ViewDidLoad () // Called by the iOS to determine if the controller can receive touches and action // messages (such as motion events) - public override bool CanBecomeFirstResponder - { + public override bool CanBecomeFirstResponder { get { return true; } } @@ -54,25 +51,25 @@ public override void ViewDidAppear (bool animated) { base.ViewWillAppear (animated); // tell the iOS that we want motion events - BecomeFirstResponder(); + BecomeFirstResponder (); } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); // be a good citizen and allow other controllers to become first responder - ResignFirstResponder(); + ResignFirstResponder (); } // Called after the iOS determines the motion wasn't noise (such as walking up stairs). public override void MotionEnded (UIEventSubtype motion, UIEvent evt) { - Console.WriteLine("Motion Ended"); - base.MotionEnded(motion, evt); + Console.WriteLine ("Motion Ended"); + base.MotionEnded (motion, evt); // if the motion was a shake - if(motion == UIEventSubtype.MotionShake) { - Console.Write("Shake Detected"); + if (motion == UIEventSubtype.MotionShake) { + Console.Write ("Shake Detected"); lblShakeStatus.Text = "Shook!"; } diff --git a/SharedResources/SharedResources/Screens/iPhone/Accelerometer/XYZDataScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Accelerometer/XYZDataScreen.xib.cs index 30526cfc9..c72b66fe4 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Accelerometer/XYZDataScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Accelerometer/XYZDataScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Accelerometer -{ - public partial class XYZDataScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Accelerometer { + public partial class XYZDataScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public XYZDataScreen (IntPtr handle) : base(handle) + public XYZDataScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public XYZDataScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public XYZDataScreen (NSCoder coder) : base (coder) { Initialize (); } - public XYZDataScreen () : base("XYZDataScreen", null) + public XYZDataScreen () : base ("XYZDataScreen", null) { Initialize (); } @@ -47,11 +45,11 @@ public override void ViewDidLoad () // update the XYZ data when the accelerometer receives data UIAccelerometer.SharedAccelerometer.Acceleration += (object sender, UIAccelerometerEventArgs e) => { - InvokeOnMainThread( () => { - lblX.Text = e.Acceleration.X.ToString(); - lblY.Text = e.Acceleration.Y.ToString(); - lblZ.Text = e.Acceleration.Z.ToString(); - } ); + InvokeOnMainThread (() => { + lblX.Text = e.Acceleration.X.ToString (); + lblY.Text = e.Acceleration.Y.ToString (); + lblZ.Text = e.Acceleration.Z.ToString (); + }); }; } diff --git a/SharedResources/SharedResources/Screens/iPhone/Battery/BatteryStatusScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Battery/BatteryStatusScreen.xib.cs index 4ba99fd7e..d65a25119 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Battery/BatteryStatusScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Battery/BatteryStatusScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Battery -{ - public partial class BatteryStatusScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Battery { + public partial class BatteryStatusScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public BatteryStatusScreen (IntPtr handle) : base(handle) + public BatteryStatusScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public BatteryStatusScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public BatteryStatusScreen (NSCoder coder) : base (coder) { Initialize (); } - public BatteryStatusScreen () : base("BatteryStatusScreen", null) + public BatteryStatusScreen () : base ("BatteryStatusScreen", null) { Initialize (); } @@ -53,15 +51,15 @@ public override void ViewDidLoad () UIDevice.BatteryLevelDidChangeNotification, (NSNotification n) => { barBatteryLevel.Progress = UIDevice.CurrentDevice.BatteryLevel; - n.Dispose(); + n.Dispose (); }); // add a notification handler for battery state changes NSNotificationCenter.DefaultCenter.AddObserver ( UIDevice.BatteryStateDidChangeNotification, (NSNotification n) => { - lblBatteryState.Text = UIDevice.CurrentDevice.BatteryState.ToString(); - n.Dispose(); + lblBatteryState.Text = UIDevice.CurrentDevice.BatteryState.ToString (); + n.Dispose (); }); } diff --git a/SharedResources/SharedResources/Screens/iPhone/Contacts/AddressBookScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Contacts/AddressBookScreen.xib.cs index a71d22b7e..eac79551e 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Contacts/AddressBookScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Contacts/AddressBookScreen.xib.cs @@ -8,10 +8,8 @@ using AddressBookUI; using CoreGraphics; -namespace Example_SharedResources.Screens.iPhone.Contacts -{ - public partial class AddressBookScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Contacts { + public partial class AddressBookScreen : UIViewController { /// <summary> /// Our address book picker control /// </summary> @@ -112,7 +110,8 @@ public override void ViewDidLoad () // code to deal with changes }; - addressBook.RequestAccess (delegate (bool granted, NSError error) { + addressBook.RequestAccess (delegate (bool granted, NSError error) + { if (!granted || error != null) return; @@ -148,13 +147,15 @@ public override void ViewDidLoad () // wire up our keyboard events NSNotificationCenter.DefaultCenter.AddObserver ( - UIKeyboard.WillShowNotification, delegate (NSNotification n) { - KeyboardOpenedOrClosed (n, "Open"); - }); + UIKeyboard.WillShowNotification, delegate (NSNotification n) + { + KeyboardOpenedOrClosed (n, "Open"); + }); NSNotificationCenter.DefaultCenter.AddObserver ( - UIKeyboard.WillHideNotification, delegate (NSNotification n) { - KeyboardOpenedOrClosed (n, "Close"); - }); + UIKeyboard.WillHideNotification, delegate (NSNotification n) + { + KeyboardOpenedOrClosed (n, "Close"); + }); #endregion } @@ -208,7 +209,7 @@ protected void DeletePhoneNumber (int phoneNumberID) // loop backwards and delete the phone number // HACK: Cast nint to int - for (int i = (int)phones.Count - 1; i >= 0; i--) { + for (int i = (int) phones.Count - 1; i >= 0; i--) { if (phones [i].Identifier == phoneNumberID) phones.RemoveAt (i); } @@ -242,7 +243,7 @@ protected void BtnSaveChangesTouchUpInside (object sender, EventArgs e) // remove all phones data // HACK: Cast nint to int - for (int i = (int)phones.Count - 1; i >= 0; i--) { + for (int i = (int) phones.Count - 1; i >= 0; i--) { phones.RemoveAt (i); } @@ -286,8 +287,8 @@ protected void PopulatePage (ABPerson contact) // wire up our delete clicked handler tableDataSource.DeleteClicked += (object sender, PhoneNumberTableSource.PhoneNumberClickedEventArgs e) => { - DeletePhoneNumber (e.PhoneNumberID); - }; + DeletePhoneNumber (e.PhoneNumberID); + }; } // Opens up a contact picker and then populates the screen, based on the contact chosen @@ -309,7 +310,7 @@ protected void SelectContact (object s, EventArgs e) PopulatePage (args.Person); EnableTextFields (true); // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController - NavigationController.DismissModalViewController(true); + NavigationController.DismissModalViewController (true); }; } @@ -337,8 +338,7 @@ private void EnableTextFields (bool enable) /// <summary> /// A simple table view source to bind our phone numbers to the table /// </summary> - protected class PhoneNumberTableSource : UITableViewSource - { + protected class PhoneNumberTableSource : UITableViewSource { public event EventHandler<PhoneNumberClickedEventArgs> DeleteClicked; protected ABMultiValue<string> phoneNumbers { get; set; } @@ -389,8 +389,8 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde numbers [cell.dataIndex] = cell.PhoneNumber; }; } -// cell.PhoneLabel = phoneNumbers[indexPath.Row].Label.ToString ().Replace ("_$!<", "").Replace (">!$_", ""); -// cell.PhoneNumber = phoneNumbers[indexPath.Row].Value.ToString (); + // cell.PhoneLabel = phoneNumbers[indexPath.Row].Label.ToString ().Replace ("_$!<", "").Replace (">!$_", ""); + // cell.PhoneNumber = phoneNumbers[indexPath.Row].Value.ToString (); cell.PhoneLabel = labels [indexPath.Row].Replace ("_$!<", "").Replace (">!$_", ""); cell.PhoneNumber = numbers [indexPath.Row]; cell.SelectionStyle = UITableViewCellSelectionStyle.None; @@ -417,8 +417,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE } // We use this so we can pass the id of the phone number that was clicked along with the event - public class PhoneNumberClickedEventArgs : EventArgs - { + public class PhoneNumberClickedEventArgs : EventArgs { public int PhoneNumberID { get; set; } public PhoneNumberClickedEventArgs (int phoneNumberID) : base () @@ -432,8 +431,7 @@ public PhoneNumberClickedEventArgs (int phoneNumberID) : base () /// <summary> /// A simple, two text box cell, that will hold our phone label, and our phone number. /// </summary> - protected class EditablePhoneTableCell : UITableViewCell - { + protected class EditablePhoneTableCell : UITableViewCell { // label and phone number text boxes public UITextField txtLabel = new UITextField (new CGRect (10, 5, 110, 33)); public UITextField txtPhoneNumber = new UITextField (new CGRect (130, 5, 140, 33)); @@ -491,7 +489,7 @@ protected void KeyboardOpenedOrClosed (NSNotification n, string openOrClose) scrlMain.Frame = newFrame; UIView.CommitAnimations (); } else { // if it's closing, resize - // declare vars + // declare vars double animationDuration = UIKeyboard.AnimationDurationFromNotification (n); // apply the size change UIView.BeginAnimations ("ResizeForKeyboard"); diff --git a/SharedResources/SharedResources/Screens/iPhone/Contacts/ContactPickerScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Contacts/ContactPickerScreen.xib.cs index 8f8c49e5d..9e121acce 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Contacts/ContactPickerScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Contacts/ContactPickerScreen.xib.cs @@ -7,10 +7,8 @@ using AddressBookUI; using AddressBook; -namespace Example_SharedResources.Screens.iPhone.Contacts -{ - public partial class ContactPickerScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Contacts { + public partial class ContactPickerScreen : UIViewController { // you must declare the Address Book Controllers at the class-level, otherwise they'll get // garbage collected when the method that creates them returns. When the events fire, the handlers // will have also been GC'd @@ -24,18 +22,18 @@ public partial class ContactPickerScreen : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public ContactPickerScreen (IntPtr handle) : base(handle) + public ContactPickerScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public ContactPickerScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public ContactPickerScreen (NSCoder coder) : base (coder) { Initialize (); } - public ContactPickerScreen () : base("ContactPickerScreen", null) + public ContactPickerScreen () : base ("ContactPickerScreen", null) { Initialize (); } @@ -55,15 +53,15 @@ public override void ViewDidLoad () // displays the contact picker controller when the choose contact button is clicked btnChooseContact.TouchUpInside += (s, e) => { // create the picker control - addressBookPicker = new ABPeoplePickerNavigationController(); + addressBookPicker = new ABPeoplePickerNavigationController (); // in this case, we can call present modal view controller from the nav controller, // but we could have just as well called PresentModalViewController(...) - NavigationController.PresentModalViewController(addressBookPicker, true); + NavigationController.PresentModalViewController (addressBookPicker, true); // when cancel is clicked, dismiss the controller // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController - addressBookPicker.Cancelled += (sender, eventArgs) => { NavigationController.DismissModalViewController(true); }; + addressBookPicker.Cancelled += (sender, eventArgs) => { NavigationController.DismissModalViewController (true); }; // when a contact is chosen, populate the page with details and dismiss the controller addressBookPicker.SelectPerson2 += (sender, args) => { @@ -71,7 +69,7 @@ public override void ViewDidLoad () lblFirstName.Text = selectedPerson.FirstName; lblLastName.Text = selectedPerson.LastName; // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController - NavigationController.DismissModalViewController(true); + NavigationController.DismissModalViewController (true); }; }; @@ -79,8 +77,7 @@ public override void ViewDidLoad () btnViewSelectedContact.TouchUpInside += (s, e) => { // if a contact hasn't been selected, show an alert and return out - if(selectedPerson == null) - { + if (selectedPerson == null) { new UIAlertView ("Alert", "You must select a contact first.", null, "OK", null).Show (); return; } diff --git a/SharedResources/SharedResources/Screens/iPhone/Contacts/NewAndUnknownContactScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Contacts/NewAndUnknownContactScreen.xib.cs index 39b840bc2..0e876f86f 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Contacts/NewAndUnknownContactScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Contacts/NewAndUnknownContactScreen.xib.cs @@ -7,10 +7,8 @@ using AddressBook; using AddressBookUI; -namespace Example_SharedResources.Screens.iPhone.Contacts -{ - public partial class NewAndUnknownContactScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Contacts { + public partial class NewAndUnknownContactScreen : UIViewController { // you must declare the Address Book Controllers at the class-level, otherwise they'll get // garbage collected when the method that creates them returns. When the events fire, the handlers // will have also been GC'd @@ -22,18 +20,18 @@ public partial class NewAndUnknownContactScreen : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public NewAndUnknownContactScreen (IntPtr handle) : base(handle) + public NewAndUnknownContactScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public NewAndUnknownContactScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public NewAndUnknownContactScreen (NSCoder coder) : base (coder) { Initialize (); } - public NewAndUnknownContactScreen () : base("NewAndUnknownContactScreen", null) + public NewAndUnknownContactScreen () : base ("NewAndUnknownContactScreen", null) { Initialize (); } @@ -71,14 +69,14 @@ public override void ViewDidLoad () addressBookNewPerson.NewPersonComplete += (object sender, ABNewPersonCompleteEventArgs args) => { // if the "done" button was clicked, rather than cancel - if(args.Completed) { + if (args.Completed) { // show an alert view with the new contact ID - new UIAlertView ("Alert", "New contact created, ID: " + args.Person.Id.ToString(), null, "OK", null).Show(); + new UIAlertView ("Alert", "New contact created, ID: " + args.Person.Id.ToString (), null, "OK", null).Show (); } // pop the controller off the stack // HACK: NavigationController.PopViewControllerAnimated to NavigationController.PopViewController - NavigationController.PopViewController(true); + NavigationController.PopViewController (true); }; }; @@ -111,7 +109,7 @@ public override void ViewDidLoad () // this dialog can be cancelled out of as well, but there is no Completed property, so we // just have to do a null check - if(args.Person != null) { + if (args.Person != null) { // show an alert view with the new contact ID new UIAlertView ("Alert", "New contact created, ID: " + args.Person.Id.ToString (), null, "OK", null).Show (); } diff --git a/SharedResources/SharedResources/Screens/iPhone/FileSystem/FileSystemInfo.xib.cs b/SharedResources/SharedResources/Screens/iPhone/FileSystem/FileSystemInfo.xib.cs index 466c42449..54e29d97f 100644 --- a/SharedResources/SharedResources/Screens/iPhone/FileSystem/FileSystemInfo.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/FileSystem/FileSystemInfo.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.FileSystem -{ - public partial class FileSystemInfo : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.FileSystem { + public partial class FileSystemInfo : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public FileSystemInfo (IntPtr handle) : base(handle) + public FileSystemInfo (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public FileSystemInfo (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public FileSystemInfo (NSCoder coder) : base (coder) { Initialize (); } - public FileSystemInfo () : base("FileSystemInfo", null) + public FileSystemInfo () : base ("FileSystemInfo", null) { Initialize (); } diff --git a/SharedResources/SharedResources/Screens/iPhone/Home/HomeTableViewController.cs b/SharedResources/SharedResources/Screens/iPhone/Home/HomeTableViewController.cs index d1457e27b..975adac69 100755 --- a/SharedResources/SharedResources/Screens/iPhone/Home/HomeTableViewController.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Home/HomeTableViewController.cs @@ -3,16 +3,14 @@ using Example_SharedResources.Code; using System.Collections.Generic; -namespace Example_SharedResources.Screens.iPhone.Home -{ - public class HomeNavController : UITableViewController - { +namespace Example_SharedResources.Screens.iPhone.Home { + public class HomeNavController : UITableViewController { // declare vars - List<NavItemGroup> navItems = new List<NavItemGroup>(); + List<NavItemGroup> navItems = new List<NavItemGroup> (); NavItemTableSource tableSource; UITableView tableView; - public HomeNavController () : base(UITableViewStyle.Grouped) + public HomeNavController () : base (UITableViewStyle.Grouped) { } diff --git a/SharedResources/SharedResources/Screens/iPhone/Network/ActivityIndicatorScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Network/ActivityIndicatorScreen.xib.cs index d7f318d02..0cf58600e 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Network/ActivityIndicatorScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Network/ActivityIndicatorScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Network -{ - public partial class ActivityIndicatorScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Network { + public partial class ActivityIndicatorScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public ActivityIndicatorScreen (IntPtr handle) : base(handle) + public ActivityIndicatorScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public ActivityIndicatorScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public ActivityIndicatorScreen (NSCoder coder) : base (coder) { Initialize (); } - public ActivityIndicatorScreen () : base("ActivityIndicatorScreen", null) + public ActivityIndicatorScreen () : base ("ActivityIndicatorScreen", null) { Initialize (); } diff --git a/SharedResources/SharedResources/Screens/iPhone/Network/ReachabilityScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Network/ReachabilityScreen.xib.cs index 6b9625b0e..b6cbeb777 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Network/ReachabilityScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Network/ReachabilityScreen.xib.cs @@ -5,27 +5,25 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Network -{ - public partial class ReachabilityScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Network { + public partial class ReachabilityScreen : UIViewController { #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public ReachabilityScreen (IntPtr handle) : base(handle) + public ReachabilityScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public ReachabilityScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public ReachabilityScreen (NSCoder coder) : base (coder) { Initialize (); } - public ReachabilityScreen () : base("ReachabilityScreen", null) + public ReachabilityScreen () : base ("ReachabilityScreen", null) { Initialize (); } diff --git a/SharedResources/SharedResources/Screens/iPhone/Photos/CameraOverlayView.cs b/SharedResources/SharedResources/Screens/iPhone/Photos/CameraOverlayView.cs index 3dacaf4b3..c3e5b3536 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Photos/CameraOverlayView.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Photos/CameraOverlayView.cs @@ -2,16 +2,14 @@ using UIKit; using CoreGraphics; -namespace Example_SharedResources.Screens.iPhone.Photos -{ - public class CameraOverlayView : UIView - { +namespace Example_SharedResources.Screens.iPhone.Photos { + public class CameraOverlayView : UIView { #region -= constructors =- - public CameraOverlayView() : base() { Initialize(); } - public CameraOverlayView (CGRect frame) : base(frame) { Initialize(); } + public CameraOverlayView () : base () { Initialize (); } + public CameraOverlayView (CGRect frame) : base (frame) { Initialize (); } - protected void Initialize() + protected void Initialize () { this.BackgroundColor = UIColor.Clear; } @@ -67,7 +65,7 @@ protected void DrawStar (CGContext context, float starDiameter) { // declare vars // 144º - float theta = 2 * (float)Math.PI * (2f / 5f); + float theta = 2 * (float) Math.PI * (2f / 5f); float radius = starDiameter / 2; // move up and over @@ -75,7 +73,7 @@ protected void DrawStar (CGContext context, float starDiameter) context.MoveTo (0, radius); for (int i = 1; i < 5; i++) { - context.AddLineToPoint (radius * (float)Math.Sin (i * theta), radius * (float)Math.Cos (i * theta)); + context.AddLineToPoint (radius * (float) Math.Sin (i * theta), radius * (float) Math.Cos (i * theta)); } //context.SetRGBFillColor (1, 1, 1, 1); context.ClosePath (); diff --git a/SharedResources/SharedResources/Screens/iPhone/Photos/CustomCameraViewScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Photos/CustomCameraViewScreen.xib.cs index 09119c282..34cbcfb55 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Photos/CustomCameraViewScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Photos/CustomCameraViewScreen.xib.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Photos -{ - public partial class CustomCameraViewScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Photos { + public partial class CustomCameraViewScreen : UIViewController { protected UIImagePickerController imagePicker; protected PickerDelegate pickerDelegate; @@ -17,18 +15,18 @@ public partial class CustomCameraViewScreen : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public CustomCameraViewScreen (IntPtr handle) : base(handle) + public CustomCameraViewScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public CustomCameraViewScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public CustomCameraViewScreen (NSCoder coder) : base (coder) { Initialize (); } - public CustomCameraViewScreen () : base("CustomCameraViewScreen", null) + public CustomCameraViewScreen () : base ("CustomCameraViewScreen", null) { Initialize (); } @@ -55,7 +53,7 @@ public override void ViewDidLoad () imagePicker.SourceType = UIImagePickerControllerSourceType.Camera; // set - imagePicker.MediaTypes = new string[] { "public.image" }; + imagePicker.MediaTypes = new string [] { "public.image" }; // show the camera controls imagePicker.ShowsCameraControls = true; @@ -86,8 +84,7 @@ public override void ViewDidLoad () // Our custom picker delegate. The events haven't been exposed so we have to use a // delegate. - protected class PickerDelegate : UIImagePickerControllerDelegate - { + protected class PickerDelegate : UIImagePickerControllerDelegate { public override void Canceled (UIImagePickerController picker) { Console.WriteLine ("picker cancelled"); @@ -112,52 +109,52 @@ public override void FinishedPickingMedia (UIImagePickerController picker, NSDic //MT BUGBUG: Console.Write ("Reference URL: [" + UIImagePickerController.ReferenceUrl + "]"); -// // get common info (shared between images and video) -// NSUrl referenceURL = info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl; -// if(referenceURL != null) -// { -// // -// Console.WriteLine(referenceURL.ToString()); -// } + // // get common info (shared between images and video) + // NSUrl referenceURL = info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl; + // if(referenceURL != null) + // { + // // + // Console.WriteLine(referenceURL.ToString()); + // } // if it was an image, get the other image info if (isImage) { -// // get the original image -// UIImage originalImage = info[UIImagePickerController.OriginalImage] as UIImage; -// if(originalImage != null) -// { -// // do something with the image -// Console.WriteLine("got the original image"); -// } - -// // get the edited image -// UIImage editedImage = info[UIImagePickerController.EditedImage] as UIImage; -// if(editedImage != null) -// { -// // do something with the image -// Console.WriteLine("got the edited image"); -// -// -// } - -// // get the cropping, if any -// try -// { -// RectangleF cropRectangle = (RectangleF)info[UIImagePickerController.CropRect]; -// if(cropRectangle != null) -// { -// // do something with the crop rectangle -// Console.WriteLine("Got the crop rectangle"); -// } -// } finally {} - -// //- get the image metadata -// NSDictionary imageMetadata = info[UIImagePickerController.MediaMetadata] as NSDictionary; -// if(imageMetadata != null) -// { -// // do something with the metadata -// Console.WriteLine("got image metadata"); -// } + // // get the original image + // UIImage originalImage = info[UIImagePickerController.OriginalImage] as UIImage; + // if(originalImage != null) + // { + // // do something with the image + // Console.WriteLine("got the original image"); + // } + + // // get the edited image + // UIImage editedImage = info[UIImagePickerController.EditedImage] as UIImage; + // if(editedImage != null) + // { + // // do something with the image + // Console.WriteLine("got the edited image"); + // + // + // } + + // // get the cropping, if any + // try + // { + // RectangleF cropRectangle = (RectangleF)info[UIImagePickerController.CropRect]; + // if(cropRectangle != null) + // { + // // do something with the crop rectangle + // Console.WriteLine("Got the crop rectangle"); + // } + // } finally {} + + // //- get the image metadata + // NSDictionary imageMetadata = info[UIImagePickerController.MediaMetadata] as NSDictionary; + // if(imageMetadata != null) + // { + // // do something with the metadata + // Console.WriteLine("got image metadata"); + // } } diff --git a/SharedResources/SharedResources/Screens/iPhone/Photos/ImagePickerScreen.xib.cs b/SharedResources/SharedResources/Screens/iPhone/Photos/ImagePickerScreen.xib.cs index 3b4d6a88f..1437826e7 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Photos/ImagePickerScreen.xib.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Photos/ImagePickerScreen.xib.cs @@ -6,10 +6,8 @@ using UIKit; using CoreGraphics; -namespace Example_SharedResources.Screens.iPhone.Photos -{ - public partial class ImagePickerScreen : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Photos { + public partial class ImagePickerScreen : UIViewController { protected UIImagePickerController imagePicker; protected FeaturesTableDataSource tableSource; protected PickerDelegate pickerDelegate; @@ -19,18 +17,18 @@ public partial class ImagePickerScreen : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public ImagePickerScreen (IntPtr handle) : base(handle) + public ImagePickerScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public ImagePickerScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public ImagePickerScreen (NSCoder coder) : base (coder) { Initialize (); } - public ImagePickerScreen () : base("ImagePickerScreen", null) + public ImagePickerScreen () : base ("ImagePickerScreen", null) { Initialize (); } @@ -64,10 +62,10 @@ public override void ViewDidLoad () // wire up a delegate. in this first one, i wire up the events. in the other two, // i use a delegate imagePicker.FinishedPickingMedia += Handle_imagePickerhandleFinishedPickingMedia; - imagePicker.Canceled += (sender,evt) => { + imagePicker.Canceled += (sender, evt) => { Console.WriteLine ("picker cancelled"); // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController - imagePicker.DismissModalViewController(true); + imagePicker.DismissModalViewController (true); }; // show the picker @@ -191,7 +189,7 @@ protected void PopulateFeaturesTable () // declare vars List<FeatureGroup> features = new List<FeatureGroup> (); FeatureGroup featGroup; - string[] mediaTypes; + string [] mediaTypes; // Sources featGroup = new FeatureGroup () { Name = "Sources" }; @@ -262,13 +260,12 @@ protected void PopulateFeaturesTable () // Our custom picker delegate. The events haven't been exposed so we have to use a // delegate. - protected class PickerDelegate : UIImagePickerControllerDelegate - { + protected class PickerDelegate : UIImagePickerControllerDelegate { public override void Canceled (UIImagePickerController picker) { Console.WriteLine ("picker cancelled"); // HACK: NavigationController.DismissModalViewControllerAnimated to NavigationController.DismissModalViewController - picker.DismissModalViewController(true); + picker.DismissModalViewController (true); } public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) @@ -312,16 +309,16 @@ public override void FinishedPickingMedia (UIImagePickerController picker, NSDic } -// // get the cropping, if any -// try -// { -// RectangleF cropRectangle = info[UIImagePickerController.CropRect] as RectangleF; -// if(cropRectangle != null) -// { -// // do something with the crop rectangle -// Console.WriteLine("Got the crop rectangle"); -// } -// } finally {} + // // get the cropping, if any + // try + // { + // RectangleF cropRectangle = info[UIImagePickerController.CropRect] as RectangleF; + // if(cropRectangle != null) + // { + // // do something with the crop rectangle + // Console.WriteLine("Got the crop rectangle"); + // } + // } finally {} //- get the image metadata NSDictionary imageMetadata = info [UIImagePickerController.MediaMetadata] as NSDictionary; @@ -353,12 +350,10 @@ public override void FinishedPickingMedia (UIImagePickerController picker, NSDic /// <summary> /// Group that holds features available /// </summary> - protected class FeatureGroup - { + protected class FeatureGroup { public string Name { get; set; } - public List<Feature> Features - { get { return features; } set { features = value; } } + public List<Feature> Features { get { return features; } set { features = value; } } protected List<Feature> features = new List<Feature> (); } @@ -366,8 +361,7 @@ public List<Feature> Features /// <summary> /// A feature, such as whether or not the front camera is available /// </summary> - protected class Feature - { + protected class Feature { public string Name { get; set; } public bool IsAvailable { get; set; } @@ -376,8 +370,7 @@ protected class Feature /// <summary> /// /// </summary> - protected class FeaturesTableDataSource : UITableViewSource - { + protected class FeaturesTableDataSource : UITableViewSource { protected List<FeatureGroup> features { get; set; } public FeaturesTableDataSource (List<FeatureGroup> features) @@ -393,7 +386,7 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableview, nint section) { // HACK: Cast nitn to int - return features [(int)section].Features.Count; + return features [(int) section].Features.Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) @@ -411,7 +404,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override string TitleForHeader (UITableView tableView, nint section) { // HACK: Cast nint to int - return features [(int)section].Name; + return features [(int) section].Name; } public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) diff --git a/SharedResources/SharedResources/Screens/iPhone/Photos/TestCameraOverlayController.cs b/SharedResources/SharedResources/Screens/iPhone/Photos/TestCameraOverlayController.cs index b10ea1168..7178f1802 100644 --- a/SharedResources/SharedResources/Screens/iPhone/Photos/TestCameraOverlayController.cs +++ b/SharedResources/SharedResources/Screens/iPhone/Photos/TestCameraOverlayController.cs @@ -1,12 +1,10 @@ using System; using UIKit; -namespace Example_SharedResources.Screens.iPhone.Photos -{ - public class TestCameraOverlayController : UIViewController - { +namespace Example_SharedResources.Screens.iPhone.Photos { + public class TestCameraOverlayController : UIViewController { #region -= constructors =- - public TestCameraOverlayController () : base() + public TestCameraOverlayController () : base () { } diff --git a/SimpleBackgroundFetch/SimpleBackgroundFetch/AppDelegate.cs b/SimpleBackgroundFetch/SimpleBackgroundFetch/AppDelegate.cs index 5094e1dfa..71525c734 100644 --- a/SimpleBackgroundFetch/SimpleBackgroundFetch/AppDelegate.cs +++ b/SimpleBackgroundFetch/SimpleBackgroundFetch/AppDelegate.cs @@ -3,14 +3,12 @@ using Foundation; using UIKit; -namespace SimpleBackgroundFetch -{ +namespace SimpleBackgroundFetch { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/SimpleBackgroundFetch/SimpleBackgroundFetch/DetailViewController.cs b/SimpleBackgroundFetch/SimpleBackgroundFetch/DetailViewController.cs index 005eba12a..d1fb279c3 100644 --- a/SimpleBackgroundFetch/SimpleBackgroundFetch/DetailViewController.cs +++ b/SimpleBackgroundFetch/SimpleBackgroundFetch/DetailViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace SimpleBackgroundFetch -{ - public partial class DetailViewController : UIViewController - { +namespace SimpleBackgroundFetch { + public partial class DetailViewController : UIViewController { object detailItem; public DetailViewController (IntPtr handle) : base (handle) diff --git a/SimpleBackgroundFetch/SimpleBackgroundFetch/Main.cs b/SimpleBackgroundFetch/SimpleBackgroundFetch/Main.cs index 0329a1092..13a50bafe 100644 --- a/SimpleBackgroundFetch/SimpleBackgroundFetch/Main.cs +++ b/SimpleBackgroundFetch/SimpleBackgroundFetch/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace SimpleBackgroundFetch -{ - public class Application - { +namespace SimpleBackgroundFetch { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/SimpleBackgroundFetch/SimpleBackgroundFetch/RootViewController.cs b/SimpleBackgroundFetch/SimpleBackgroundFetch/RootViewController.cs index f017505cf..fcdb83445 100644 --- a/SimpleBackgroundFetch/SimpleBackgroundFetch/RootViewController.cs +++ b/SimpleBackgroundFetch/SimpleBackgroundFetch/RootViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace SimpleBackgroundFetch -{ - public partial class RootViewController : UITableViewController - { +namespace SimpleBackgroundFetch { + public partial class RootViewController : UITableViewController { DataSource dataSource; public RootViewController (IntPtr handle) : base (handle) @@ -28,7 +26,7 @@ void AddNewItem (object sender, EventArgs args) dataSource.Objects.Insert (0, DateTime.Now); using (var indexPath = NSIndexPath.FromRowSection (0, 0)) - TableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); } public override void DidReceiveMemoryWarning () @@ -50,8 +48,7 @@ public override void ViewDidLoad () NavigationItem.RightBarButtonItem = addButton; } - class DataSource : UITableViewSource - { + class DataSource : UITableViewSource { static readonly NSString CellIdentifier = new NSString ("DataSourceCell"); List<object> objects = new List<object> (); RootViewController controller; @@ -97,7 +94,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE if (editingStyle == UITableViewCellEditingStyle.Delete) { // Delete the row from the data source. objects.RemoveAt (indexPath.Row); - controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); + controller.TableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); } } } @@ -108,7 +105,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) var indexPath = TableView.IndexPathForSelectedRow; var item = dataSource.Objects [indexPath.Row]; - ((DetailViewController)segue.DestinationViewController).SetDetailItem (item); + ((DetailViewController) segue.DestinationViewController).SetDetailItem (item); } } } diff --git a/SimpleBackgroundTransfer/SimpleBackgroundTransfer/Main.cs b/SimpleBackgroundTransfer/SimpleBackgroundTransfer/Main.cs index 32de3f2c2..a08bdfc85 100644 --- a/SimpleBackgroundTransfer/SimpleBackgroundTransfer/Main.cs +++ b/SimpleBackgroundTransfer/SimpleBackgroundTransfer/Main.cs @@ -3,7 +3,7 @@ namespace SimpleBackgroundTransfer { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/SimpleBackgroundTransfer/SimpleBackgroundTransfer/SimpleBackgroundTransferViewController.cs b/SimpleBackgroundTransfer/SimpleBackgroundTransfer/SimpleBackgroundTransferViewController.cs index 5abeb3b54..1e13c9843 100644 --- a/SimpleBackgroundTransfer/SimpleBackgroundTransfer/SimpleBackgroundTransferViewController.cs +++ b/SimpleBackgroundTransfer/SimpleBackgroundTransfer/SimpleBackgroundTransferViewController.cs @@ -32,7 +32,8 @@ public override void ViewDidLoad () startButton.Clicked += Start; // Force the app to crash - crashButton.Clicked += delegate { + crashButton.Clicked += delegate + { string s = null; s.ToString (); }; @@ -70,8 +71,7 @@ public UIImageView ImageView { } } - public class UrlSessionDelegate : NSObject, INSUrlSessionDownloadDelegate - { + public class UrlSessionDelegate : NSObject, INSUrlSessionDownloadDelegate { public SimpleBackgroundTransferViewController controller; public UrlSessionDelegate (SimpleBackgroundTransferViewController controller) @@ -84,9 +84,9 @@ public void DidWriteData (NSUrlSession session, NSUrlSessionDownloadTask downloa { Console.WriteLine ("Set Progress"); if (downloadTask == controller.downloadTask) { - float progress = totalBytesWritten / (float)totalBytesExpectedToWrite; + float progress = totalBytesWritten / (float) totalBytesExpectedToWrite; Console.WriteLine (string.Format ("DownloadTask: {0} progress: {1}", downloadTask, progress)); - InvokeOnMainThread( () => { + InvokeOnMainThread (() => { controller.ProgressView.Progress = progress; }); } @@ -131,7 +131,7 @@ public void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, N else Console.WriteLine ("Task: {0} completed with error: {1}", task, error.LocalizedDescription); - float progress = task.BytesReceived / (float)task.BytesExpectedToReceive; + float progress = task.BytesReceived / (float) task.BytesExpectedToReceive; InvokeOnMainThread (() => { controller.ProgressView.Progress = progress; }); @@ -152,7 +152,7 @@ public void DidFinishEventsForBackgroundSession (NSUrlSession session) var handler = appDelegate.BackgroundSessionCompletionHandler; if (handler != null) { appDelegate.BackgroundSessionCompletionHandler = null; - handler(); + handler (); } } diff --git a/SimpleCollectionView/SimpleCollectionView/AppDelegate.cs b/SimpleCollectionView/SimpleCollectionView/AppDelegate.cs index c8d663397..ff843ced3 100644 --- a/SimpleCollectionView/SimpleCollectionView/AppDelegate.cs +++ b/SimpleCollectionView/SimpleCollectionView/AppDelegate.cs @@ -6,52 +6,50 @@ using UIKit; using CoreGraphics; -namespace SimpleCollectionView -{ - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - #pragma warning disable 414 - // class-level declarations - UIWindow window; - UICollectionViewController simpleCollectionViewController; - CircleLayout circleLayout; - LineLayout lineLayout; - UICollectionViewFlowLayout flowLayout; - #pragma warning restore 414 - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - window = new UIWindow (UIScreen.MainScreen.Bounds); - - // Flow Layout - flowLayout = new UICollectionViewFlowLayout (){ - HeaderReferenceSize = new CGSize (100, 100), - SectionInset = new UIEdgeInsets (20,20,20,20), - ScrollDirection = UICollectionViewScrollDirection.Vertical, +namespace SimpleCollectionView { + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { +#pragma warning disable 414 + // class-level declarations + UIWindow window; + UICollectionViewController simpleCollectionViewController; + CircleLayout circleLayout; + LineLayout lineLayout; + UICollectionViewFlowLayout flowLayout; +#pragma warning restore 414 + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + window = new UIWindow (UIScreen.MainScreen.Bounds); + + // Flow Layout + flowLayout = new UICollectionViewFlowLayout () { + HeaderReferenceSize = new CGSize (100, 100), + SectionInset = new UIEdgeInsets (20, 20, 20, 20), + ScrollDirection = UICollectionViewScrollDirection.Vertical, MinimumInteritemSpacing = 50, // minimum spacing between cells MinimumLineSpacing = 50 // minimum spacing between rows if ScrollDirection is Vertical or between columns if Horizontal - }; + }; - // Line Layout - lineLayout = new LineLayout (){ - HeaderReferenceSize = new CGSize (160, 100), - ScrollDirection = UICollectionViewScrollDirection.Horizontal - }; + // Line Layout + lineLayout = new LineLayout () { + HeaderReferenceSize = new CGSize (160, 100), + ScrollDirection = UICollectionViewScrollDirection.Horizontal + }; - // Circle Layout - circleLayout = new CircleLayout (); + // Circle Layout + circleLayout = new CircleLayout (); -// simpleCollectionViewController = new SimpleCollectionViewController (flowLayout); -// simpleCollectionViewController = new SimpleCollectionViewController (lineLayout); - simpleCollectionViewController = new SimpleCollectionViewController (circleLayout); + // simpleCollectionViewController = new SimpleCollectionViewController (flowLayout); + // simpleCollectionViewController = new SimpleCollectionViewController (lineLayout); + simpleCollectionViewController = new SimpleCollectionViewController (circleLayout); - simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (50, 0, 0, 0); + simpleCollectionViewController.CollectionView.ContentInset = new UIEdgeInsets (50, 0, 0, 0); - window.RootViewController = simpleCollectionViewController; - window.MakeKeyAndVisible (); + window.RootViewController = simpleCollectionViewController; + window.MakeKeyAndVisible (); - return true; - } - } + return true; + } + } } diff --git a/SimpleCollectionView/SimpleCollectionView/CircleLayout.cs b/SimpleCollectionView/SimpleCollectionView/CircleLayout.cs index 3c83bee8d..a618dc850 100755 --- a/SimpleCollectionView/SimpleCollectionView/CircleLayout.cs +++ b/SimpleCollectionView/SimpleCollectionView/CircleLayout.cs @@ -5,10 +5,8 @@ using CoreAnimation; using UIKit; -namespace SimpleCollectionView -{ - public class CircleLayout : UICollectionViewLayout - { +namespace SimpleCollectionView { + public class CircleLayout : UICollectionViewLayout { const float ItemSize = 70.0f; int cellCount = 20; float radius; @@ -18,7 +16,7 @@ public class CircleLayout : UICollectionViewLayout public CircleLayout () { - RegisterClassForDecorationView (typeof(MyDecorationView), myDecorationViewId); + RegisterClassForDecorationView (typeof (MyDecorationView), myDecorationViewId); } public override void PrepareLayout () @@ -26,9 +24,9 @@ public override void PrepareLayout () base.PrepareLayout (); CGSize size = CollectionView.Frame.Size; - cellCount = (int)CollectionView.NumberOfItemsInSection (0); + cellCount = (int) CollectionView.NumberOfItemsInSection (0); center = new CGPoint (size.Width / 2.0f, size.Height / 2.0f); - radius = (float)Math.Min (size.Width, size.Height) / 2.5f; + radius = (float) Math.Min (size.Width, size.Height) / 2.5f; } public override CGSize CollectionViewContentSize { @@ -37,21 +35,21 @@ public override CGSize CollectionViewContentSize { } } - public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) - { - return true; - } + public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) + { + return true; + } public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath path) { UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell (path); attributes.Size = new CGSize (ItemSize, ItemSize); - attributes.Center = new CGPoint (center.X + radius * (float)Math.Cos (2 * path.Row * Math.PI / cellCount), - center.Y + radius * (float)Math.Sin (2 * path.Row * Math.PI / cellCount)); + attributes.Center = new CGPoint (center.X + radius * (float) Math.Cos (2 * path.Row * Math.PI / cellCount), + center.Y + radius * (float) Math.Sin (2 * path.Row * Math.PI / cellCount)); return attributes; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { var attributes = new UICollectionViewLayoutAttributes [cellCount + 1]; @@ -60,8 +58,8 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn attributes [i] = LayoutAttributesForItem (indexPath); } - var decorationAttribs = UICollectionViewLayoutAttributes.CreateForDecorationView (myDecorationViewId, NSIndexPath.FromItemSection (0, 0)); - decorationAttribs.Size = CollectionView.Frame.Size; + var decorationAttribs = UICollectionViewLayoutAttributes.CreateForDecorationView (myDecorationViewId, NSIndexPath.FromItemSection (0, 0)); + decorationAttribs.Size = CollectionView.Frame.Size; decorationAttribs.Center = CollectionView.Center; decorationAttribs.ZIndex = -1; attributes [cellCount] = decorationAttribs; @@ -71,8 +69,7 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn } - public class MyDecorationView : UICollectionReusableView - { + public class MyDecorationView : UICollectionReusableView { [Export ("initWithFrame:")] public MyDecorationView (CGRect frame) : base (frame) { diff --git a/SimpleCollectionView/SimpleCollectionView/GridLayout.cs b/SimpleCollectionView/SimpleCollectionView/GridLayout.cs index 9de0159fc..10a490110 100644 --- a/SimpleCollectionView/SimpleCollectionView/GridLayout.cs +++ b/SimpleCollectionView/SimpleCollectionView/GridLayout.cs @@ -3,34 +3,32 @@ using Foundation; using UIKit; -namespace SimpleCollectionView -{ - public class GridLayout : UICollectionViewFlowLayout - { - public GridLayout () - { - } +namespace SimpleCollectionView { + public class GridLayout : UICollectionViewFlowLayout { + public GridLayout () + { + } - public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) - { - return true; - } + public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) + { + return true; + } - public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath path) - { - return base.LayoutAttributesForItem (path); - } + public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSIndexPath path) + { + return base.LayoutAttributesForItem (path); + } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) - { - return base.LayoutAttributesForElementsInRect (rect); - } + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) + { + return base.LayoutAttributesForElementsInRect (rect); + } -// public override SizeF CollectionViewContentSize { -// get { -// return CollectionView.Bounds.Size; -// } -// } - } + // public override SizeF CollectionViewContentSize { + // get { + // return CollectionView.Bounds.Size; + // } + // } + } } diff --git a/SimpleCollectionView/SimpleCollectionView/IAnimal.cs b/SimpleCollectionView/SimpleCollectionView/IAnimal.cs index 08c7140f5..8ba990bd7 100644 --- a/SimpleCollectionView/SimpleCollectionView/IAnimal.cs +++ b/SimpleCollectionView/SimpleCollectionView/IAnimal.cs @@ -1,10 +1,8 @@ using System; using UIKit; -namespace SimpleCollectionView -{ - public interface IAnimal - { +namespace SimpleCollectionView { + public interface IAnimal { string Name { get; } UIImage Image { get; } diff --git a/SimpleCollectionView/SimpleCollectionView/LineLayout.cs b/SimpleCollectionView/SimpleCollectionView/LineLayout.cs index 5966ed0ea..9f92e2423 100644 --- a/SimpleCollectionView/SimpleCollectionView/LineLayout.cs +++ b/SimpleCollectionView/SimpleCollectionView/LineLayout.cs @@ -4,10 +4,8 @@ using CoreGraphics; using CoreAnimation; -namespace SimpleCollectionView -{ - public class LineLayout : UICollectionViewFlowLayout - { +namespace SimpleCollectionView { + public class LineLayout : UICollectionViewFlowLayout { public const float ITEM_SIZE = 200.0f; public const int ACTIVE_DISTANCE = 200; public const float ZOOM_FACTOR = 0.3f; @@ -16,7 +14,7 @@ public LineLayout () { ItemSize = new CGSize (ITEM_SIZE, ITEM_SIZE); ScrollDirection = UICollectionViewScrollDirection.Horizontal; - SectionInset = new UIEdgeInsets (400,0,400,0); + SectionInset = new UIEdgeInsets (400, 0, 400, 0); MinimumLineSpacing = 50.0f; } @@ -25,14 +23,14 @@ public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) return true; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { var array = base.LayoutAttributesForElementsInRect (rect); - var visibleRect = new CGRect (CollectionView.ContentOffset, CollectionView.Bounds.Size); + var visibleRect = new CGRect (CollectionView.ContentOffset, CollectionView.Bounds.Size); foreach (var attributes in array) { if (attributes.Frame.IntersectsWith (rect)) { - float distance = (float)(visibleRect.GetMidX () - attributes.Center.X); + float distance = (float) (visibleRect.GetMidX () - attributes.Center.X); float normalizedDistance = distance / ACTIVE_DISTANCE; if (Math.Abs (distance) < ACTIVE_DISTANCE) { float zoom = 1 + ZOOM_FACTOR * (1 - Math.Abs (normalizedDistance)); @@ -47,16 +45,16 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn public override CGPoint TargetContentOffset (CGPoint proposedContentOffset, CGPoint scrollingVelocity) { float offSetAdjustment = float.MaxValue; - float horizontalCenter = (float)(proposedContentOffset.X + (this.CollectionView.Bounds.Size.Width / 2.0)); + float horizontalCenter = (float) (proposedContentOffset.X + (this.CollectionView.Bounds.Size.Width / 2.0)); CGRect targetRect = new CGRect (proposedContentOffset.X, 0.0f, this.CollectionView.Bounds.Size.Width, this.CollectionView.Bounds.Size.Height); var array = base.LayoutAttributesForElementsInRect (targetRect); foreach (var layoutAttributes in array) { - float itemHorizontalCenter = (float)layoutAttributes.Center.X; + float itemHorizontalCenter = (float) layoutAttributes.Center.X; if (Math.Abs (itemHorizontalCenter - horizontalCenter) < Math.Abs (offSetAdjustment)) { offSetAdjustment = itemHorizontalCenter - horizontalCenter; } } - return new CGPoint (proposedContentOffset.X + offSetAdjustment, proposedContentOffset.Y); + return new CGPoint (proposedContentOffset.X + offSetAdjustment, proposedContentOffset.Y); } } diff --git a/SimpleCollectionView/SimpleCollectionView/Main.cs b/SimpleCollectionView/SimpleCollectionView/Main.cs index 3f5286964..411fa251d 100644 --- a/SimpleCollectionView/SimpleCollectionView/Main.cs +++ b/SimpleCollectionView/SimpleCollectionView/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace SimpleCollectionView -{ - public class Application - { +namespace SimpleCollectionView { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/SimpleCollectionView/SimpleCollectionView/Monkey.cs b/SimpleCollectionView/SimpleCollectionView/Monkey.cs index 34f712bb5..9ccd79a9d 100644 --- a/SimpleCollectionView/SimpleCollectionView/Monkey.cs +++ b/SimpleCollectionView/SimpleCollectionView/Monkey.cs @@ -1,23 +1,21 @@ using System; using UIKit; -namespace SimpleCollectionView -{ - public class Monkey : IAnimal - { +namespace SimpleCollectionView { + public class Monkey : IAnimal { public Monkey () { } public string Name { - get{ + get { return "Monkey"; } } - public UIImage Image{ - get{ - return UIImage.FromBundle("monkey.png"); + public UIImage Image { + get { + return UIImage.FromBundle ("monkey.png"); } } diff --git a/SimpleCollectionView/SimpleCollectionView/SimpleCollectionViewController.cs b/SimpleCollectionView/SimpleCollectionView/SimpleCollectionViewController.cs index 19eb3749e..21d046710 100644 --- a/SimpleCollectionView/SimpleCollectionView/SimpleCollectionViewController.cs +++ b/SimpleCollectionView/SimpleCollectionView/SimpleCollectionViewController.cs @@ -5,103 +5,101 @@ using CoreGraphics; using ObjCRuntime; -namespace SimpleCollectionView -{ - public class SimpleCollectionViewController : UICollectionViewController - { - static NSString animalCellId = new NSString ("AnimalCell"); - static NSString headerId = new NSString ("Header"); - List<IAnimal> animals; - - public SimpleCollectionViewController (UICollectionViewLayout layout) : base (layout) - { - animals = new List<IAnimal> (); - for (int i = 0; i < 20; i++) { - animals.Add (new Monkey ()); - } - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - CollectionView.RegisterClassForCell (typeof(AnimalCell), animalCellId); - CollectionView.RegisterClassForSupplementaryView (typeof(Header), UICollectionElementKindSection.Header, headerId); - - UIMenuController.SharedMenuController.MenuItems = new UIMenuItem[] { +namespace SimpleCollectionView { + public class SimpleCollectionViewController : UICollectionViewController { + static NSString animalCellId = new NSString ("AnimalCell"); + static NSString headerId = new NSString ("Header"); + List<IAnimal> animals; + + public SimpleCollectionViewController (UICollectionViewLayout layout) : base (layout) + { + animals = new List<IAnimal> (); + for (int i = 0; i < 20; i++) { + animals.Add (new Monkey ()); + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + CollectionView.RegisterClassForCell (typeof (AnimalCell), animalCellId); + CollectionView.RegisterClassForSupplementaryView (typeof (Header), UICollectionElementKindSection.Header, headerId); + + UIMenuController.SharedMenuController.MenuItems = new UIMenuItem [] { new UIMenuItem ("Custom", new Selector ("custom")) }; } - public override nint NumberOfSections (UICollectionView collectionView) - { - return 1; - } + public override nint NumberOfSections (UICollectionView collectionView) + { + return 1; + } - public override nint GetItemsCount (UICollectionView collectionView, nint section) - { - return animals.Count; - } + public override nint GetItemsCount (UICollectionView collectionView, nint section) + { + return animals.Count; + } - public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) - { - var animalCell = (AnimalCell)collectionView.DequeueReusableCell (animalCellId, indexPath); + public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) + { + var animalCell = (AnimalCell) collectionView.DequeueReusableCell (animalCellId, indexPath); - var animal = animals [indexPath.Row]; + var animal = animals [indexPath.Row]; - animalCell.Image = animal.Image; + animalCell.Image = animal.Image; - return animalCell; - } + return animalCell; + } - public override UICollectionReusableView GetViewForSupplementaryElement (UICollectionView collectionView, NSString elementKind, NSIndexPath indexPath) - { - var headerView = (Header)collectionView.DequeueReusableSupplementaryView (elementKind, headerId, indexPath); - headerView.Text = "Supplementary View"; - return headerView; - } + public override UICollectionReusableView GetViewForSupplementaryElement (UICollectionView collectionView, NSString elementKind, NSIndexPath indexPath) + { + var headerView = (Header) collectionView.DequeueReusableSupplementaryView (elementKind, headerId, indexPath); + headerView.Text = "Supplementary View"; + return headerView; + } - public override void ItemHighlighted (UICollectionView collectionView, NSIndexPath indexPath) - { - var cell = collectionView.CellForItem (indexPath); - cell.ContentView.BackgroundColor = UIColor.Yellow; - } + public override void ItemHighlighted (UICollectionView collectionView, NSIndexPath indexPath) + { + var cell = collectionView.CellForItem (indexPath); + cell.ContentView.BackgroundColor = UIColor.Yellow; + } - public override void ItemUnhighlighted (UICollectionView collectionView, NSIndexPath indexPath) - { - var cell = collectionView.CellForItem (indexPath); - cell.ContentView.BackgroundColor = UIColor.White; - } + public override void ItemUnhighlighted (UICollectionView collectionView, NSIndexPath indexPath) + { + var cell = collectionView.CellForItem (indexPath); + cell.ContentView.BackgroundColor = UIColor.White; + } - public override bool ShouldHighlightItem (UICollectionView collectionView, NSIndexPath indexPath) - { - return true; - } + public override bool ShouldHighlightItem (UICollectionView collectionView, NSIndexPath indexPath) + { + return true; + } -// public override bool ShouldSelectItem (UICollectionView collectionView, NSIndexPath indexPath) -// { -// return false; -// } + // public override bool ShouldSelectItem (UICollectionView collectionView, NSIndexPath indexPath) + // { + // return false; + // } - // for edit menu - public override bool ShouldShowMenu (UICollectionView collectionView, NSIndexPath indexPath) - { - return true; - } + // for edit menu + public override bool ShouldShowMenu (UICollectionView collectionView, NSIndexPath indexPath) + { + return true; + } - public override bool CanPerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender) + public override bool CanPerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender) { // Selector should be the same as what's in the custom UIMenuItem if (action == new Selector ("custom")) return true; else return false; - } + } - public override void PerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender) - { + public override void PerformAction (UICollectionView collectionView, Selector action, NSIndexPath indexPath, NSObject sender) + { System.Diagnostics.Debug.WriteLine ("code to perform action"); - } + } // CanBecomeFirstResponder and CanPerform are needed for a custom menu item to appear public override bool CanBecomeFirstResponder { @@ -118,53 +116,51 @@ public override bool CanBecomeFirstResponder { return false; }*/ - public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) - { - base.WillRotate (toInterfaceOrientation, duration); - - var lineLayout = CollectionView.CollectionViewLayout as LineLayout; - if (lineLayout != null) - { - if((toInterfaceOrientation == UIInterfaceOrientation.Portrait) || (toInterfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown)) - lineLayout.SectionInset = new UIEdgeInsets (400,0,400,0); - else - lineLayout.SectionInset = new UIEdgeInsets (220, 0.0f, 200, 0.0f); - } - } + public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) + { + base.WillRotate (toInterfaceOrientation, duration); + + var lineLayout = CollectionView.CollectionViewLayout as LineLayout; + if (lineLayout != null) { + if ((toInterfaceOrientation == UIInterfaceOrientation.Portrait) || (toInterfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown)) + lineLayout.SectionInset = new UIEdgeInsets (400, 0, 400, 0); + else + lineLayout.SectionInset = new UIEdgeInsets (220, 0.0f, 200, 0.0f); + } + } - } + } - public class AnimalCell : UICollectionViewCell - { - UIImageView imageView; + public class AnimalCell : UICollectionViewCell { + UIImageView imageView; - [Export ("initWithFrame:")] - public AnimalCell (CGRect frame) : base (frame) - { - BackgroundView = new UIView{BackgroundColor = UIColor.Orange}; + [Export ("initWithFrame:")] + public AnimalCell (CGRect frame) : base (frame) + { + BackgroundView = new UIView { BackgroundColor = UIColor.Orange }; - SelectedBackgroundView = new UIView{BackgroundColor = UIColor.Green}; + SelectedBackgroundView = new UIView { BackgroundColor = UIColor.Green }; - ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; - ContentView.Layer.BorderWidth = 2.0f; - ContentView.BackgroundColor = UIColor.White; - ContentView.Transform = CGAffineTransform.MakeScale (0.8f, 0.8f); + ContentView.Layer.BorderColor = UIColor.LightGray.CGColor; + ContentView.Layer.BorderWidth = 2.0f; + ContentView.BackgroundColor = UIColor.White; + ContentView.Transform = CGAffineTransform.MakeScale (0.8f, 0.8f); - imageView = new UIImageView (UIImage.FromBundle ("placeholder.png")); - imageView.Center = ContentView.Center; - imageView.Transform = CGAffineTransform.MakeScale (0.7f, 0.7f); + imageView = new UIImageView (UIImage.FromBundle ("placeholder.png")); + imageView.Center = ContentView.Center; + imageView.Transform = CGAffineTransform.MakeScale (0.7f, 0.7f); - ContentView.AddSubview (imageView); - } + ContentView.AddSubview (imageView); + } - public UIImage Image { - set { - imageView.Image = value; - } - } + public UIImage Image { + set { + imageView.Image = value; + } + } - [Export("custom")] - void Custom() + [Export ("custom")] + void Custom () { // Put all your custom menu behavior code here Console.WriteLine ("custom in the cell"); @@ -178,29 +174,28 @@ public override bool CanPerform (Selector action, NSObject withSender) else return false; } - } - - public class Header : UICollectionReusableView - { - UILabel label; - - public string Text { - get { - return label.Text; - } - set { - label.Text = value; - SetNeedsDisplay (); - } - } - - [Export ("initWithFrame:")] - public Header (CGRect frame) : base (frame) - { - label = new UILabel (){Frame = new CGRect (0,0,300,50), BackgroundColor = UIColor.Yellow}; - AddSubview (label); - } - } + } + + public class Header : UICollectionReusableView { + UILabel label; + + public string Text { + get { + return label.Text; + } + set { + label.Text = value; + SetNeedsDisplay (); + } + } + + [Export ("initWithFrame:")] + public Header (CGRect frame) : base (frame) + { + label = new UILabel () { Frame = new CGRect (0, 0, 300, 50), BackgroundColor = UIColor.Yellow }; + AddSubview (label); + } + } } diff --git a/SimpleDrillDown/Main.cs b/SimpleDrillDown/Main.cs index 67e6a57ff..d122c248f 100644 --- a/SimpleDrillDown/Main.cs +++ b/SimpleDrillDown/Main.cs @@ -36,7 +36,7 @@ public class Application { /// <summary> /// This is the main entry point of the application. /// </summary> - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/SimpleDrillDown/Play.cs b/SimpleDrillDown/Play.cs index 4e999b033..69c9ac965 100644 --- a/SimpleDrillDown/Play.cs +++ b/SimpleDrillDown/Play.cs @@ -35,7 +35,7 @@ public class Play { public string Genre { get; set; } public string Title { get; set; } - public static List <Play> CreateDemoPlays () + public static List<Play> CreateDemoPlays () { var plays = new List<Play> (); plays.Add (new Play { @@ -49,7 +49,7 @@ public class Play { Title = "King Lear", Genre = "Tragedy", Date = new DateTime (1605, 1, 1), - Characters = new List<string> { "Captain", "Cordelia", "Curan", "Doctor", "Duke of Albany", "Duke of Burgundy", "Duke of Cornwall", "Earl of Gloucester", "Earl of Kent", "Edgar", "Edmund", "Fool", "Gentleman", "Goneril", "Herald", "King of France", "Knight", "Lear", "Messenger", "Old Man", "Oswald", "Regan", "Servant 1", "Servant 2", "Servant 3" } + Characters = new List<string> { "Captain", "Cordelia", "Curan", "Doctor", "Duke of Albany", "Duke of Burgundy", "Duke of Cornwall", "Earl of Gloucester", "Earl of Kent", "Edgar", "Edmund", "Fool", "Gentleman", "Goneril", "Herald", "King of France", "Knight", "Lear", "Messenger", "Old Man", "Oswald", "Regan", "Servant 1", "Servant 2", "Servant 3" } }); plays.Add (new Play { diff --git a/SimpleLogin/CodeOnlyProject/AppDelegate.cs b/SimpleLogin/CodeOnlyProject/AppDelegate.cs index 66cd5af8d..f4727cc61 100644 --- a/SimpleLogin/CodeOnlyProject/AppDelegate.cs +++ b/SimpleLogin/CodeOnlyProject/AppDelegate.cs @@ -1,28 +1,26 @@ -using Foundation; +using Foundation; using UIKit; -namespace CodeOnlyDemo -{ - [Register("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; +namespace CodeOnlyDemo { + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; - public override bool FinishedLaunching(UIApplication app, NSDictionary options) - { - // create a new window instance based on the screen size - window = new UIWindow(UIScreen.MainScreen.Bounds); + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + // create a new window instance based on the screen size + window = new UIWindow (UIScreen.MainScreen.Bounds); - var controller = new CustomViewController(); + var controller = new CustomViewController (); - window.RootViewController = controller; + window.RootViewController = controller; - // make the window visible - window.MakeKeyAndVisible(); - - return true; - } - } + // make the window visible + window.MakeKeyAndVisible (); + + return true; + } + } } diff --git a/SimpleLogin/CodeOnlyProject/CircleController.cs b/SimpleLogin/CodeOnlyProject/CircleController.cs index 159e466d7..41c409aff 100644 --- a/SimpleLogin/CodeOnlyProject/CircleController.cs +++ b/SimpleLogin/CodeOnlyProject/CircleController.cs @@ -1,14 +1,12 @@ -using UIKit; +using UIKit; -namespace CodeOnlyDemo -{ - class CircleController : UIViewController - { +namespace CodeOnlyDemo { + class CircleController : UIViewController { CircleView view; - public override void LoadView() + public override void LoadView () { - view = new CircleView(); + view = new CircleView (); View = view; } } diff --git a/SimpleLogin/CodeOnlyProject/CircleView.cs b/SimpleLogin/CodeOnlyProject/CircleView.cs index 91f6fcb55..0384e8d10 100644 --- a/SimpleLogin/CodeOnlyProject/CircleView.cs +++ b/SimpleLogin/CodeOnlyProject/CircleView.cs @@ -1,34 +1,31 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace CodeOnlyDemo -{ - class CircleView : UIView - { - public override void Draw(CGRect rect) +namespace CodeOnlyDemo { + class CircleView : UIView { + public override void Draw (CGRect rect) { - base.Draw(rect); + base.Draw (rect); //get graphics context - using (var g = UIGraphics.GetCurrentContext()) - { + using (var g = UIGraphics.GetCurrentContext ()) { // set up drawing attributes - g.SetLineWidth(10.0f); - UIColor.Green.SetFill(); - UIColor.Blue.SetStroke(); + g.SetLineWidth (10.0f); + UIColor.Green.SetFill (); + UIColor.Blue.SetStroke (); // create geometry - var path = new CGPath(); - path.AddArc(Bounds.GetMidX(), Bounds.GetMidY(), 50f, 0, 2.0f * (float)Math.PI, true); + var path = new CGPath (); + path.AddArc (Bounds.GetMidX (), Bounds.GetMidY (), 50f, 0, 2.0f * (float) Math.PI, true); // add geometry to graphics context and draw - g.AddPath(path); - g.DrawPath(CGPathDrawingMode.FillStroke); + g.AddPath (path); + g.DrawPath (CGPathDrawingMode.FillStroke); } } - public CircleView() + public CircleView () { BackgroundColor = UIColor.White; } diff --git a/SimpleLogin/CodeOnlyProject/CustomViewController.cs b/SimpleLogin/CodeOnlyProject/CustomViewController.cs index 018b470dc..3901eccf2 100644 --- a/SimpleLogin/CodeOnlyProject/CustomViewController.cs +++ b/SimpleLogin/CodeOnlyProject/CustomViewController.cs @@ -1,56 +1,52 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace CodeOnlyDemo -{ - - public class CustomViewController : UIViewController - { - UITextField usernameField, passwordField; - CircleController circleController; - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - View.BackgroundColor = UIColor.Gray; - - nfloat h = 31.0f; - nfloat w = View.Bounds.Width; - - usernameField = new UITextField - { - Placeholder = "Enter your username", - BorderStyle = UITextBorderStyle.RoundedRect, - Frame = new CGRect(10, 32, w - 20, h), - AutoresizingMask = UIViewAutoresizing.FlexibleWidth - }; - - passwordField = new UITextField - { - Placeholder = "Enter your password", - BorderStyle = UITextBorderStyle.RoundedRect, - Frame = new CGRect(10, 64, w - 20, h), - SecureTextEntry = true, - AutoresizingMask = UIViewAutoresizing.FlexibleWidth - }; - - var submitButton = UIButton.FromType(UIButtonType.RoundedRect); - submitButton.Frame = new CGRect(10, 120, w - 20, 44); - submitButton.SetTitle("Submit", UIControlState.Normal); - submitButton.BackgroundColor = UIColor.White; - submitButton.Layer.CornerRadius = 5f; - submitButton.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; - - submitButton.TouchUpInside += delegate - { - Console.WriteLine("Submit button pressed"); - circleController = new CircleController(); - PresentViewController(circleController, true, null); - }; - - View.AddSubviews(new UIView[]{ usernameField, passwordField, submitButton }); - } - } +namespace CodeOnlyDemo { + + public class CustomViewController : UIViewController { + UITextField usernameField, passwordField; + CircleController circleController; + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + View.BackgroundColor = UIColor.Gray; + + nfloat h = 31.0f; + nfloat w = View.Bounds.Width; + + usernameField = new UITextField { + Placeholder = "Enter your username", + BorderStyle = UITextBorderStyle.RoundedRect, + Frame = new CGRect (10, 32, w - 20, h), + AutoresizingMask = UIViewAutoresizing.FlexibleWidth + }; + + passwordField = new UITextField { + Placeholder = "Enter your password", + BorderStyle = UITextBorderStyle.RoundedRect, + Frame = new CGRect (10, 64, w - 20, h), + SecureTextEntry = true, + AutoresizingMask = UIViewAutoresizing.FlexibleWidth + }; + + var submitButton = UIButton.FromType (UIButtonType.RoundedRect); + submitButton.Frame = new CGRect (10, 120, w - 20, 44); + submitButton.SetTitle ("Submit", UIControlState.Normal); + submitButton.BackgroundColor = UIColor.White; + submitButton.Layer.CornerRadius = 5f; + submitButton.AutoresizingMask = UIViewAutoresizing.FlexibleWidth; + + submitButton.TouchUpInside += delegate + { + Console.WriteLine ("Submit button pressed"); + circleController = new CircleController (); + PresentViewController (circleController, true, null); + }; + + View.AddSubviews (new UIView [] { usernameField, passwordField, submitButton }); + } + } } diff --git a/SimpleLogin/CodeOnlyProject/Main.cs b/SimpleLogin/CodeOnlyProject/Main.cs index 074473343..a408d0b14 100644 --- a/SimpleLogin/CodeOnlyProject/Main.cs +++ b/SimpleLogin/CodeOnlyProject/Main.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace CodeOnlyProject -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace CodeOnlyProject { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/SimpleTextInput/AppDelegate.cs b/SimpleTextInput/AppDelegate.cs index 10001cb7b..aace2eb4b 100644 --- a/SimpleTextInput/AppDelegate.cs +++ b/SimpleTextInput/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace SimpleTextInput -{ +namespace SimpleTextInput { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; SimpleTextInputViewController viewController; diff --git a/SimpleTextInput/EditableCoreTextView.cs b/SimpleTextInput/EditableCoreTextView.cs index e789d88a4..195441b4f 100644 --- a/SimpleTextInput/EditableCoreTextView.cs +++ b/SimpleTextInput/EditableCoreTextView.cs @@ -8,14 +8,12 @@ using ObjCRuntime; using CoreText; -namespace SimpleTextInput -{ +namespace SimpleTextInput { [Adopts ("UITextInput")] [Adopts ("UIKeyInput")] [Adopts ("UITextInputTraits")] [Register ("EditableCoreTextView")] - public class EditableCoreTextView : UIView - { + public class EditableCoreTextView : UIView { StringBuilder text = new StringBuilder (); IUITextInputTokenizer tokenizer; SimpleCoreTextView textView; @@ -30,7 +28,8 @@ public EditableCoreTextView (CGRect frame) { // Add tap gesture recognizer to let the user enter editing mode UITapGestureRecognizer tap = new UITapGestureRecognizer (Tap) { - ShouldReceiveTouch = delegate(UIGestureRecognizer recognizer, UITouch touch) { + ShouldReceiveTouch = delegate (UIGestureRecognizer recognizer, UITouch touch) + { // If gesture touch occurs in our view, we want to handle it return touch.View == this; } @@ -59,7 +58,7 @@ protected override void Dispose (bool disposing) base.Dispose (disposing); } -#region Custom user interaction + #region Custom user interaction // UIResponder protocol override - our view can become first responder to // receive user text input @@ -88,7 +87,7 @@ public void Tap (UITapGestureRecognizer tap) ViewWillEdit (this); // Flag that underlying SimpleCoreTextView is now in edit mode textView.IsEditing = true; - // Become first responder state (which shows software keyboard, if applicable) + // Become first responder state (which shows software keyboard, if applicable) BecomeFirstResponder (); } else { // Already in editing mode, set insertion point (via selectedTextRange) @@ -98,9 +97,9 @@ public void Tap (UITapGestureRecognizer tap) textView.SelectedTextRange = new NSRange (index, 0); } } -#endregion + #endregion -#region UITextInput methods + #region UITextInput methods [Export ("inputDelegate")] public IUITextInputDelegate InputDelegate { get { @@ -121,14 +120,14 @@ public NSDictionary MarkedTextStyle { } } -#region UITextInput - Replacing and Returning Text + #region UITextInput - Replacing and Returning Text // UITextInput required method - called by text system to get the string for // a given range in the text storage [Export ("textInRange:")] string TextInRange (UITextRange range) { IndexedRange r = (IndexedRange) range; - return text.ToString ().Substring ((int)r.Range.Location, (int)r.Range.Length); + return text.ToString ().Substring ((int) r.Range.Location, (int) r.Range.Length); } // UITextInput required method - called by text system to replace the given @@ -149,15 +148,15 @@ void ReplaceRange (UITextRange range, string text) } // Now replace characters in text storage - this.text.Remove ((int)r.Range.Location, (int)r.Range.Length); - this.text.Insert ((int)r.Range.Location, text); + this.text.Remove ((int) r.Range.Location, (int) r.Range.Length); + this.text.Insert ((int) r.Range.Location, text); // Update underlying SimpleCoreTextView textView.Text = this.text.ToString (); textView.SelectedTextRange = selectedNSRange; } -#endregion -#region UITextInput - Working with Marked and Selected Text + #endregion + #region UITextInput - Working with Marked and Selected Text // UITextInput selectedTextRange property accessor overrides // (access/update underlaying SimpleCoreTextView) @@ -193,23 +192,23 @@ void SetMarkedText (string markedText, NSRange selectedRange) if (markedTextRange.Location != NSRange.NotFound) { // Replace characters in text storage and update markedText range length - text.Remove ((int)markedTextRange.Location, (int)markedTextRange.Length); - text.Insert ((int)markedTextRange.Location, markedText); + text.Remove ((int) markedTextRange.Location, (int) markedTextRange.Length); + text.Insert ((int) markedTextRange.Location, markedText); markedTextRange.Length = markedText.Length; } else if (selectedNSRange.Length > 0) { // There currently isn't a marked text range, but there is a selected range, // so replace text storage at selected range and update markedTextRange. - text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); - text.Insert ((int)selectedNSRange.Location, markedText); + text.Remove ((int) selectedNSRange.Location, (int) selectedNSRange.Length); + text.Insert ((int) selectedNSRange.Location, markedText); markedTextRange.Location = selectedNSRange.Location; markedTextRange.Length = markedText.Length; } else { // There currently isn't marked or selected text ranges, so just insert // given text into storage and update markedTextRange. - text.Insert ((int)selectedNSRange.Location, markedText); + text.Insert ((int) selectedNSRange.Location, markedText); markedTextRange.Location = selectedNSRange.Location; markedTextRange.Length = markedText.Length; - } + } // Updated selected text range and underlying SimpleCoreTextView selectedNSRange = new NSRange (selectedRange.Location + markedTextRange.Location, selectedRange.Length); @@ -222,18 +221,18 @@ void SetMarkedText (string markedText, NSRange selectedRange) [Export ("unmarkText")] void UnmarkText () { - NSRange markedTextRange = textView.MarkedTextRange; + NSRange markedTextRange = textView.MarkedTextRange; - if (markedTextRange.Location == NSRange.NotFound) - return; + if (markedTextRange.Location == NSRange.NotFound) + return; // unmark the underlying SimpleCoreTextView.markedTextRange - markedTextRange.Location = NSRange.NotFound; - textView.MarkedTextRange = markedTextRange; + markedTextRange.Location = NSRange.NotFound; + textView.MarkedTextRange = markedTextRange; } -#endregion -#region UITextInput - Computing Text Ranges and Text Positions + #endregion + #region UITextInput - Computing Text Ranges and Text Positions // UITextInput beginningOfDocument property accessor override [Export ("beginningOfDocument")] @@ -315,8 +314,8 @@ IndexedPosition GetPosition (UITextPosition position, UITextLayoutDirection dire return IndexedPosition.GetPosition (newPos); } -#endregion -#region UITextInput - Evaluating Text Positions + #endregion + #region UITextInput - Evaluating Text Positions // UITextInput protocol required method - Return how one text position compares to another // text position. @@ -343,8 +342,8 @@ int GetOffset (IndexedPosition @from, IndexedPosition toPosition) { return @from.Index - toPosition.Index; } -#endregion -#region UITextInput - Text Input Delegate and Text Input Tokenizer + #endregion + #region UITextInput - Text Input Delegate and Text Input Tokenizer // UITextInput tokenizer property accessor override // @@ -361,8 +360,8 @@ IUITextInputTokenizer Tokenizer { return tokenizer; } } -#endregion -#region UITextInput - Text Layout, writing direction and position related methods + #endregion + #region UITextInput - Text Layout, writing direction and position related methods // UITextInput protocol method - Return the text position that is at the farthest // extent in a given layout direction within a range of text. [Export ("positionWithinRange:farthestInDirection:")] @@ -370,7 +369,7 @@ IndexedPosition GetPosition (UITextRange range, UITextLayoutDirection direction) { // Note that this sample assumes LTR text direction IndexedRange r = (IndexedRange) range; - int pos = (int)r.Range.Location; + int pos = (int) r.Range.Location; // For this sample, we just return the extent of the given range if the // given direction is "forward" in a LTR context (UITextLayoutDirectionRight @@ -378,11 +377,11 @@ IndexedPosition GetPosition (UITextRange range, UITextLayoutDirection direction) switch (direction) { case UITextLayoutDirection.Up: case UITextLayoutDirection.Left: - pos = (int)r.Range.Location; + pos = (int) r.Range.Location; break; case UITextLayoutDirection.Right: case UITextLayoutDirection.Down: - pos = (int)(r.Range.Location + r.Range.Length); + pos = (int) (r.Range.Location + r.Range.Length); break; } @@ -431,8 +430,8 @@ void SetBaseWritingDirection (UITextWritingDirection writingDirection, UITextRan { // This sample assumes LTR text direction and does not currently support BiDi or RTL. } -#endregion -#region UITextInput - Geometry methods + #endregion + #region UITextInput - Geometry methods // UITextInput protocol required method - Return the first rectangle that encloses // a range of text in a document. [Export ("firstRectForRange:")] @@ -464,8 +463,8 @@ CGRect CaretRect (UITextPosition position) // Convert rect to our view coordinates return ConvertRectFromView (rect, textView); } -#endregion -#region UITextInput - Hit testing + #endregion + #region UITextInput - Hit testing // Note that for this sample hit testing methods are not implemented, as there // is no implemented mechanic for letting user select text via touches. There // is a wide variety of approaches for this (gestures, drag rects, etc) and @@ -500,8 +499,8 @@ UITextRange CharacterRange (CGPoint point) // SimpleCoreTextView:closestIndexToPoint:point return null; } -#endregion -#region UITextInput - Returning Text Styling Information + #endregion + #region UITextInput - Returning Text Styling Information // UITextInput protocol method - Return a dictionary with properties that specify // how text is to be style at a certain location in a document. [Export ("textStylingAtPosition:inDirection:")] @@ -510,8 +509,8 @@ NSDictionary TextStyling (UITextPosition position, UITextStorageDirection direct // This sample assumes all text is single-styled, so this is easy. return new NSDictionary (CTStringAttributeKey.Font, textView.Font); } -#endregion -#region UIKeyInput methods + #endregion + #region UIKeyInput methods // UIKeyInput required method - A Boolean value that indicates whether the text-entry // objects have any text. [Export ("hasText")] @@ -532,20 +531,20 @@ void InsertText (string text) // these ranges and acts accordingly. if (markedTextRange.Location != NSRange.NotFound) { // There is marked text -- replace marked text with user-entered text - this.text.Remove ((int)markedTextRange.Location, (int)markedTextRange.Length); - this.text.Insert ((int)markedTextRange.Location, text); + this.text.Remove ((int) markedTextRange.Location, (int) markedTextRange.Length); + this.text.Insert ((int) markedTextRange.Location, text); selectedNSRange.Location = markedTextRange.Location + text.Length; selectedNSRange.Length = 0; markedTextRange = new NSRange (NSRange.NotFound, 0); } else if (selectedNSRange.Length > 0) { // Replace selected text with user-entered text - this.text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); - this.text.Insert ((int)selectedNSRange.Location, text); + this.text.Remove ((int) selectedNSRange.Location, (int) selectedNSRange.Length); + this.text.Insert ((int) selectedNSRange.Location, text); selectedNSRange.Length = 0; selectedNSRange.Location += text.Length; } else { // Insert user-entered text at current insertion point - this.text.Insert ((int)selectedNSRange.Location, text); + this.text.Insert ((int) selectedNSRange.Location, text); selectedNSRange.Location += text.Length; } @@ -569,19 +568,19 @@ void DeleteBackward () // these ranges and acts accordingly. if (markedTextRange.Location != NSRange.NotFound) { // There is marked text, so delete it - text.Remove ((int)markedTextRange.Location, (int)markedTextRange.Length); + text.Remove ((int) markedTextRange.Location, (int) markedTextRange.Length); selectedNSRange.Location = markedTextRange.Location; selectedNSRange.Length = 0; markedTextRange = new NSRange (NSRange.NotFound, 0); } else if (selectedNSRange.Length > 0) { // Delete the selected text - text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); + text.Remove ((int) selectedNSRange.Location, (int) selectedNSRange.Length); selectedNSRange.Length = 0; } else if (selectedNSRange.Location > 0) { // Delete one char of text at the current insertion point selectedNSRange.Location--; selectedNSRange.Length = 1; - text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); + text.Remove ((int) selectedNSRange.Location, (int) selectedNSRange.Length); selectedNSRange.Length = 0; } @@ -591,6 +590,6 @@ void DeleteBackward () textView.SelectedTextRange = selectedNSRange; } } -#endregion -#endregion + #endregion + #endregion } diff --git a/SimpleTextInput/IndexedPosition.cs b/SimpleTextInput/IndexedPosition.cs index 571029b95..18e2c61f5 100644 --- a/SimpleTextInput/IndexedPosition.cs +++ b/SimpleTextInput/IndexedPosition.cs @@ -8,8 +8,7 @@ using ObjCRuntime; using CoreText; -namespace SimpleTextInput -{ +namespace SimpleTextInput { // A UITextPosition object represents a position in a text container; in other words, it is // an index into the backing string in a text-displaying view. // @@ -18,8 +17,7 @@ namespace SimpleTextInput // system uses both these objects and UITextRange objects for communicating text-layout information. // // We could use more sophisticated objects, but for demonstration purposes it suffices to wrap integers. - class IndexedPosition : UITextPosition - { + class IndexedPosition : UITextPosition { public int Index { get; private set; } private IndexedPosition (int index) diff --git a/SimpleTextInput/IndexedRange.cs b/SimpleTextInput/IndexedRange.cs index b2192abf9..b85e5af84 100644 --- a/SimpleTextInput/IndexedRange.cs +++ b/SimpleTextInput/IndexedRange.cs @@ -8,8 +8,7 @@ using ObjCRuntime; using CoreText; -namespace SimpleTextInput -{ +namespace SimpleTextInput { // A UITextRange object represents a range of characters in a text container; in other words, // it identifies a starting index and an ending index in string backing a text-entry object. // @@ -17,8 +16,7 @@ namespace SimpleTextInput // representing ranges within the text managed by the class. The starting and ending indexes // of the range are represented by UITextPosition objects. The text system uses both UITextRange // and UITextPosition objects for communicating text-layout information. - class IndexedRange : UITextRange - { + class IndexedRange : UITextRange { public NSRange Range { get; private set; } private IndexedRange () @@ -28,13 +26,13 @@ private IndexedRange () public override UITextPosition Start { get { - return IndexedPosition.GetPosition ((int)Range.Location); + return IndexedPosition.GetPosition ((int) Range.Location); } } public override UITextPosition End { get { - return IndexedPosition.GetPosition ((int)Range.Location + (int)Range.Length); + return IndexedPosition.GetPosition ((int) Range.Location + (int) Range.Length); } } @@ -62,8 +60,7 @@ public static IndexedRange GetRange (NSRange theRange) return result; } - class NSRangeEqualityComparer : IEqualityComparer<NSRange> - { + class NSRangeEqualityComparer : IEqualityComparer<NSRange> { #region IEqualityComparer[NSRange] implementation public bool Equals (NSRange x, NSRange y) { diff --git a/SimpleTextInput/Main.cs b/SimpleTextInput/Main.cs index 00b283db3..9b332a1d5 100644 --- a/SimpleTextInput/Main.cs +++ b/SimpleTextInput/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace SimpleTextInput -{ - public class Application - { +namespace SimpleTextInput { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/SimpleTextInput/SimpleCoreTextView.cs b/SimpleTextInput/SimpleCoreTextView.cs index ad9374463..2723c2372 100644 --- a/SimpleTextInput/SimpleCoreTextView.cs +++ b/SimpleTextInput/SimpleCoreTextView.cs @@ -8,10 +8,8 @@ using ObjCRuntime; using CoreText; -namespace SimpleTextInput -{ - public class SimpleCoreTextView : UIView - { +namespace SimpleTextInput { + public class SimpleCoreTextView : UIView { string text; UIFont font; bool is_editing; @@ -110,7 +108,7 @@ NSRange RangeIntersection (NSRange first, NSRange second) // Find the overlap intersection range between first and second if (second.Location < first.Location + first.Length) { result.Location = second.Location; - int end = Math.Min ((int)(first.Location + first.Length), (int)(second.Location + second.Length)); + int end = Math.Min ((int) (first.Location + first.Length), (int) (second.Location + second.Length)); result.Length = end - result.Location; } @@ -142,12 +140,12 @@ void DrawRangeAsSelection (NSRange selectionRange) NSRange range = new NSRange (lineRange.Location, lineRange.Length); NSRange intersection = RangeIntersection (range, selectionRange); if (intersection.Location != NSRange.NotFound && intersection.Length > 0) { - // The text range for this line intersects our selection range + // The text range for this line intersects our selection range nfloat xStart = line.GetOffsetForStringIndex (intersection.Location); nfloat xEnd = line.GetOffsetForStringIndex (intersection.Location + intersection.Length); var origin = new CGPoint [lines.Length]; // Get coordinate and bounds information for the intersection text range - frame.GetLineOrigins (new NSRange (i, 0), origin ); + frame.GetLineOrigins (new NSRange (i, 0), origin); nfloat ascent, descent, leading; line.GetTypographicBounds (out ascent, out descent, out leading); // Create a rect for the intersection and draw it with selection color @@ -180,7 +178,7 @@ public int ClosestIndex (CGPoint point) if (point.Y > origins [i].Y) { // This line origin is closest to the y-coordinate of our point, // now look for the closest string index in this line. - return (int)lines [i].GetStringIndexForPosition (point); + return (int) lines [i].GetStringIndexForPosition (point); } } @@ -197,7 +195,7 @@ public CGRect CaretRect (int index) if (text.Length == 0) { CGPoint origin = new CGPoint (Bounds.GetMinX (), Bounds.GetMinY () - font.Leading); // Note: using fabs() for typically negative descender from fonts - return new CGRect (origin.X, origin.Y - (nfloat)Math.Abs (font.Descender), 3, font.Ascender + (nfloat)Math.Abs (font.Descender)); + return new CGRect (origin.X, origin.Y - (nfloat) Math.Abs (font.Descender), 3, font.Ascender + (nfloat) Math.Abs (font.Descender)); } // Special case, insertion point at final position in text after newline @@ -210,7 +208,7 @@ public CGRect CaretRect (int index) line.GetTypographicBounds (out ascent, out descent, out leading); frame.GetLineOrigins (new NSRange (lines.Length - 1, 0), origins); // Place point after last line, including any font leading spacing if applicable - origins[0].Y -= font.Leading; + origins [0].Y -= font.Leading; return new CGRect (xPos, origins [0].Y - descent, 3, ascent + descent); } @@ -218,7 +216,7 @@ public CGRect CaretRect (int index) for (int i = 0; i < lines.Length; i++) { CTLine line = lines [i]; NSRange range = line.StringRange; - int localIndex = index - (int)range.Location; + int localIndex = index - (int) range.Location; if (localIndex >= 0 && localIndex <= range.Length) { // index is in the range for this line nfloat xPos = line.GetOffsetForStringIndex (index); @@ -239,17 +237,17 @@ public CGRect CaretRect (int index) // UITextInput:firstRectForRange method public CGRect FirstRect (NSRange range) { - int index = (int)range.Location; + int index = (int) range.Location; // Iterate over our CTLines, looking for the line that encompasses the given range var lines = frame.GetLines (); for (int i = 0; i < lines.Length; i++) { CTLine line = lines [i]; NSRange lineRange = line.StringRange; - int localIndex = index - (int)lineRange.Location; + int localIndex = index - (int) lineRange.Location; if (localIndex >= 0 && localIndex < lineRange.Length) { // For this sample, we use just the first line that intersects range - int finalIndex = (int)Math.Min (lineRange.Location + lineRange.Length, range.Location + range.Length); + int finalIndex = (int) Math.Min (lineRange.Location + lineRange.Length, range.Location + range.Length); // Create a rect for the given range within this line nfloat xStart = line.GetOffsetForStringIndex (index); nfloat xEnd = line.GetOffsetForStringIndex (finalIndex); @@ -277,7 +275,7 @@ void SelectionChanged () // If there is no selection range (always true for this sample), find the // insert point rect and create a caretView to draw the caret at this position if (SelectedTextRange.Length == 0) { - caretView.Frame = CaretRect ((int)SelectedTextRange.Location); + caretView.Frame = CaretRect ((int) SelectedTextRange.Location); if (caretView.Superview == null) { AddSubview (caretView); SetNeedsDisplay (); @@ -331,8 +329,7 @@ public bool IsEditing { } } - class SimpleCaretView : UIView - { + class SimpleCaretView : UIView { NSTimer blink_timer; const double InitialBlinkDelay = 0.7; const double BlinkRate = 0.5; diff --git a/SimpleTextInput/SimpleTextInputViewController.cs b/SimpleTextInput/SimpleTextInputViewController.cs index 4727cd00c..1a08fe139 100644 --- a/SimpleTextInput/SimpleTextInputViewController.cs +++ b/SimpleTextInput/SimpleTextInputViewController.cs @@ -3,10 +3,8 @@ using System; using Foundation; -namespace SimpleTextInput -{ - public partial class SimpleTextInputViewController : UIViewController - { +namespace SimpleTextInput { + public partial class SimpleTextInputViewController : UIViewController { EditableCoreTextView editableCoreTextView { get; set; } public SimpleTextInputViewController (string nibName, NSBundle bundle) : base (nibName, bundle) diff --git a/SoZoomy/SoZoomy/AppDelegate.cs b/SoZoomy/SoZoomy/AppDelegate.cs index ac316d06c..c4df19ca5 100644 --- a/SoZoomy/SoZoomy/AppDelegate.cs +++ b/SoZoomy/SoZoomy/AppDelegate.cs @@ -17,7 +17,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/SoZoomy/SoZoomy/FaceView.cs b/SoZoomy/SoZoomy/FaceView.cs index 61e454788..3957175db 100644 --- a/SoZoomy/SoZoomy/FaceView.cs +++ b/SoZoomy/SoZoomy/FaceView.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace SoZoomy -{ - public class FaceView : UIView - { +namespace SoZoomy { + public class FaceView : UIView { public Action<int, FaceView> Callback; public int Id; diff --git a/SoZoomy/SoZoomy/PreviewView.cs b/SoZoomy/SoZoomy/PreviewView.cs index c68ab2165..5cffb32b1 100644 --- a/SoZoomy/SoZoomy/PreviewView.cs +++ b/SoZoomy/SoZoomy/PreviewView.cs @@ -5,10 +5,8 @@ using ObjCRuntime; using UIKit; -namespace SoZoomy -{ - public partial class PreviewView : UIView - { +namespace SoZoomy { + public partial class PreviewView : UIView { public AVCaptureSession Session { get { return (Layer as AVCaptureVideoPreviewLayer).Session; @@ -18,14 +16,14 @@ public AVCaptureSession Session { } } -/* public PreviewView () : base () - { - } + /* public PreviewView () : base () + { + } - public PreviewView (RectangleF frame) : base (frame) - { - } -*/ + public PreviewView (RectangleF frame) : base (frame) + { + } + */ public PreviewView (IntPtr handle) : base (handle) { } diff --git a/SoZoomy/SoZoomy/ViewController.cs b/SoZoomy/SoZoomy/ViewController.cs index 4b4a67271..36d20353b 100644 --- a/SoZoomy/SoZoomy/ViewController.cs +++ b/SoZoomy/SoZoomy/ViewController.cs @@ -9,14 +9,12 @@ using Foundation; using UIKit; -namespace SoZoomy -{ - public partial class ViewController : UIViewController - { +namespace SoZoomy { + public partial class ViewController : UIViewController { AVCaptureSession session; AVCaptureDevice device; AVCaptureMetadataOutput metadataOutput; - Dictionary <int, FaceView> faceViews; + Dictionary<int, FaceView> faceViews; int? lockedFaceID; float lockedFaceSize; double lockTime; @@ -31,7 +29,7 @@ public partial class ViewController : UIViewController float MaxZoom { get { - return (float)Math.Min (device != null ? device.ActiveFormat.VideoMaxZoomFactor : 1, 6); + return (float) Math.Min (device != null ? device.ActiveFormat.VideoMaxZoomFactor : 1, 6); } } @@ -64,10 +62,10 @@ void setupAVCapture () setupAVFoundationFaceDetection (); if (device != null) { - device.AddObserver (this, (NSString) "videoZoomFactor", (NSKeyValueObservingOptions)0, - VideoZoomFactorContext); - device.AddObserver (this, (NSString) "rampingVideoZoom", (NSKeyValueObservingOptions)0, - VideoZoomRampingContext); + device.AddObserver (this, (NSString) "videoZoomFactor", (NSKeyValueObservingOptions) 0, + VideoZoomFactorContext); + device.AddObserver (this, (NSString) "rampingVideoZoom", (NSKeyValueObservingOptions) 0, + VideoZoomRampingContext); } session.StartRunning (); @@ -155,7 +153,7 @@ void updateCameraSelection () { session.BeginConfiguration (); - AVCaptureInput[] oldInputs = session.Inputs; + AVCaptureInput [] oldInputs = session.Inputs; foreach (var oldInput in oldInputs) session.RemoveInput (oldInput); @@ -177,7 +175,7 @@ void updateCameraSelection () session.CommitConfiguration (); } - public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] faces, AVCaptureConnection connection) + public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject [] faces, AVCaptureConnection connection) { List<int> unseen = faceViews.Keys.ToList (); List<int> seen = new List<int> (); @@ -187,7 +185,7 @@ public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVM foreach (var face in faces) { // HACK: int faceId = (face as AVMetadataFaceObject).FaceID; - int faceId = (int)(face as AVMetadataFaceObject).FaceID; + int faceId = (int) (face as AVMetadataFaceObject).FaceID; unseen.Remove (faceId); seen.Add (faceId); @@ -207,7 +205,7 @@ public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVM view.Alpha = 0; } - AVMetadataFaceObject adjusted = (AVMetadataFaceObject)(previewView.Layer as AVCaptureVideoPreviewLayer).GetTransformedMetadataObject (face); + AVMetadataFaceObject adjusted = (AVMetadataFaceObject) (previewView.Layer as AVCaptureVideoPreviewLayer).GetTransformedMetadataObject (face); view.Frame = adjusted.Bounds; } @@ -223,10 +221,10 @@ public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVM FaceView view = faceViews [lockedFaceID.GetValueOrDefault ()]; // HACK: Cast resulting nfloat to float // float size = (float)Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor; - float size = (float)(Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); + float size = (float) (Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); float zoomDelta = lockedFaceSize / size; - float lockTime = (float)(CATransition.CurrentMediaTime () - this.lockTime); - float zoomRate = (float)(Math.Log (zoomDelta) / lockTime); + float lockTime = (float) (CATransition.CurrentMediaTime () - this.lockTime); + float zoomRate = (float) (Math.Log (zoomDelta) / lockTime); if (Math.Abs (zoomDelta) > 0.1) device.RampToVideoZoom (zoomRate > 0 ? MaxZoom : 1, zoomRate); } @@ -239,7 +237,7 @@ void TouchCallBack (int faceId, FaceView view) lockedFaceID = faceId; // HACK: Cast double to float // lockedFaceSize = Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor; - lockedFaceSize = (float)(Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); + lockedFaceSize = (float) (Math.Max (view.Frame.Size.Width, view.Frame.Size.Height) / device.VideoZoomFactor); lockTime = CATransition.CurrentMediaTime (); UIView.BeginAnimations (null, IntPtr.Zero); @@ -257,7 +255,8 @@ void TouchCallBack (int faceId, FaceView view) void displayErrorOnMainQueue (NSError error, string message) { - DispatchQueue.MainQueue.DispatchAsync (delegate { + DispatchQueue.MainQueue.DispatchAsync (delegate + { UIAlertView alert = new UIAlertView (); if (error != null) { alert.Title = message + " (" + error.Code + ")"; @@ -276,7 +275,7 @@ public override void TouchesEnded (NSSet touches, UIEvent evt) if (lockedFaceID != null) clearLockedFace (); else { - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; CGPoint point = touch.LocationInView (previewView); point = (previewView.Layer as AVCaptureVideoPreviewLayer).CaptureDevicePointOfInterestForPoint (point); @@ -303,7 +302,7 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio if (context == VideoZoomFactorContext) { // HACK: Cast nfloat to float // setZoomSliderValue (device.VideoZoomFactor); - setZoomSliderValue ((float)device.VideoZoomFactor); + setZoomSliderValue ((float) device.VideoZoomFactor); memeButton.Enabled = (device.VideoZoomFactor > 1); } else if (context == VideoZoomRampingContext) { slider.Enabled = device.RampingVideoZoom; @@ -324,7 +323,7 @@ public override void ViewDidLoad () string path = NSBundle.MainBundle.PathForResource ("Dramatic2", "m4a"); if (path != null) { memeEffect = AVPlayer.FromUrl (NSUrl.FromFilename (path)); - memeEffect.AddObserver (this, (NSString) "rate", (NSKeyValueObservingOptions)0, MemePlaybackContext); + memeEffect.AddObserver (this, (NSString) "rate", (NSKeyValueObservingOptions) 0, MemePlaybackContext); } path = NSBundle.MainBundle.PathForResource ("Sosumi", "wav"); if (path != null) @@ -341,7 +340,7 @@ public override void ViewDidLoad () public override void WillRotate (UIInterfaceOrientation toInterfaceOrientation, double duration) { (previewView.Layer as AVCaptureVideoPreviewLayer).Connection.VideoOrientation = - (AVCaptureVideoOrientation)toInterfaceOrientation; + (AVCaptureVideoOrientation) toInterfaceOrientation; } partial void meme (NSObject sender) @@ -355,25 +354,24 @@ partial void meme (NSObject sender) if (faceViews == null) return; - - foreach (var faceId in faceViews.Keys) - { - FaceView view = faceViews[faceId]; + + foreach (var faceId in faceViews.Keys) { + FaceView view = faceViews [faceId]; view.Alpha = 0; } } - [Export("flash")] + [Export ("flash")] void flash () { if (device.TorchAvailable) device.TorchMode = AVCaptureTorchMode.On; } - [Export("startZoom:")] + [Export ("startZoom:")] void startZoom (NSNumber target) { - float zoomPower = (float)Math.Log (target.FloatValue); + float zoomPower = (float) Math.Log (target.FloatValue); device.RampToVideoZoom (target.FloatValue, zoomPower / MEME_ZOOM_TIME); } @@ -403,19 +401,18 @@ void fadeInFaces () float getZoomSliderValue () { - return (float)Math.Pow (MaxZoom, slider.Value); + return (float) Math.Pow (MaxZoom, slider.Value); } void setZoomSliderValue (float value) { - slider.Value = (float)Math.Log (value) / (float)Math.Log (MaxZoom); + slider.Value = (float) Math.Log (value) / (float) Math.Log (MaxZoom); } - public class MetaDataObjectDelegate : AVCaptureMetadataOutputObjectsDelegate - { - public Action<AVCaptureMetadataOutput, AVMetadataObject[], AVCaptureConnection> DidOutputMetadataObjectsAction; + public class MetaDataObjectDelegate : AVCaptureMetadataOutputObjectsDelegate { + public Action<AVCaptureMetadataOutput, AVMetadataObject [], AVCaptureConnection> DidOutputMetadataObjectsAction; - public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject[] faces, AVCaptureConnection connection) + public override void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject [] faces, AVCaptureConnection connection) { if (DidOutputMetadataObjectsAction != null) DidOutputMetadataObjectsAction (captureOutput, faces, connection); diff --git a/SocialFrameworkDemo/SocialFrameworkDemo/AppDelegate.cs b/SocialFrameworkDemo/SocialFrameworkDemo/AppDelegate.cs index b25d8a48d..5beccddd8 100644 --- a/SocialFrameworkDemo/SocialFrameworkDemo/AppDelegate.cs +++ b/SocialFrameworkDemo/SocialFrameworkDemo/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace SocialFrameworkDemo { diff --git a/SocialFrameworkDemo/SocialFrameworkDemo/Main.cs b/SocialFrameworkDemo/SocialFrameworkDemo/Main.cs index 80bee2a4b..c88652c12 100644 --- a/SocialFrameworkDemo/SocialFrameworkDemo/Main.cs +++ b/SocialFrameworkDemo/SocialFrameworkDemo/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace SocialFrameworkDemo { public class Application { diff --git a/SocialFrameworkDemo/SocialFrameworkDemo/ViewController.cs b/SocialFrameworkDemo/SocialFrameworkDemo/ViewController.cs index 2dae2a2d3..e9f602755 100644 --- a/SocialFrameworkDemo/SocialFrameworkDemo/ViewController.cs +++ b/SocialFrameworkDemo/SocialFrameworkDemo/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Accounts; using Foundation; @@ -132,7 +132,7 @@ partial void RequestTwitterTimeline_TouchUpInside (UIButton sender) { // Initialize request var parameters = new NSDictionary (); - var url = new NSUrl("https://api.twitter.com/1.1/statuses/user_timeline.json?count=10"); + var url = new NSUrl ("https://api.twitter.com/1.1/statuses/user_timeline.json?count=10"); var request = SLRequest.Create (SLServiceKind.Twitter, SLRequestMethod.Get, url, parameters); // Request data diff --git a/Sound/Sound/AppDelegate.cs b/Sound/Sound/AppDelegate.cs index 0732d2ccb..c0ca5882b 100644 --- a/Sound/Sound/AppDelegate.cs +++ b/Sound/Sound/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Sound -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace Sound { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/Sound/Sound/Main.cs b/Sound/Sound/Main.cs index 50b0a1f6f..a12ef7a70 100644 --- a/Sound/Sound/Main.cs +++ b/Sound/Sound/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Sound -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace Sound { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/Sound/Sound/ViewController.cs b/Sound/Sound/ViewController.cs index d07a75d60..1e79552eb 100644 --- a/Sound/Sound/ViewController.cs +++ b/Sound/Sound/ViewController.cs @@ -1,269 +1,233 @@ -using System; +using System; using System.Diagnostics; using System.IO; using AVFoundation; using Foundation; using UIKit; -namespace Sound -{ - public partial class ViewController : UIViewController - { - private NSObject observer; - - private AVPlayer player; - - private NSUrl audioFilePath; - - private AVAudioRecorder recorder; - - private Stopwatch stopwatch; - - private Status status; - - protected ViewController(IntPtr handle) : base(handle) { } - - protected Status Status - { - get - { - return status; - } - - set - { - if (status != value) - { - status = value; - UpdateUserInterface(); - } - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - playButton.Enabled = false; - stopButton.Enabled = false; - statusLabel.Text = string.Empty; - lenghtButton.Text = string.Empty; - - observer = AVPlayerItem.Notifications.ObserveDidPlayToEndTime(OnDidPlayToEndTime); - } - - private void UpdateUserInterface() - { - switch (status) - { - case Status.PreparingError: - statusLabel.Text = "Error preparing"; - lenghtButton.Text = string.Empty; - startButton.Enabled = true; - stopButton.Enabled = false; - playButton.Enabled = false; - break; - - case Status.Playing: - statusLabel.Text = "Playing"; - startButton.Enabled = false; - stopButton.Enabled = false; - playButton.Enabled = false; - break; - - case Status.Recording: - lenghtButton.Text = string.Empty; - statusLabel.Text = "Recording"; - startButton.Enabled = false; - stopButton.Enabled = true; - playButton.Enabled = false; - break; - - case Status.Recorded: - lenghtButton.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed); - statusLabel.Text = string.Empty; - startButton.Enabled = true; - stopButton.Enabled = false; - playButton.Enabled = true; - break; - } - } - - partial void StartRecording(UIButton sender) - { - Console.WriteLine("Begin Recording"); - - var session = AVAudioSession.SharedInstance(); - session.RequestRecordPermission((granted) => - { - Console.WriteLine($"Audio Permission: {granted}"); - - if (granted) - { - session.SetCategory(AVAudioSession.CategoryRecord, out NSError error); - if (error == null) - { - session.SetActive(true, out error); - if (error != null) - { - Status = Status.PreparingError; - } - else - { - var isPrepared = PrepareAudioRecording() && recorder.Record(); - if (isPrepared) - { - stopwatch = new Stopwatch(); - stopwatch.Start(); - Status = Status.Recording; - } - else - { - Status = Status.PreparingError; - } - } - } - else - { - Console.WriteLine(error.LocalizedDescription); - } - } - else - { - Console.WriteLine("YOU MUST ENABLE MICROPHONE PERMISSION"); - } - }); - } - - partial void StopRecording(UIButton sender) - { - if (recorder != null) - { - recorder.Stop(); - stopwatch?.Stop(); - - Status = Status.Recorded; - } - } - - private NSUrl CreateOutputUrl() - { - var fileName = $"Myfile-{DateTime.Now.ToString("yyyyMMddHHmmss")}.aac"; - var tempRecording = Path.Combine(Path.GetTempPath(), fileName); - - return NSUrl.FromFilename(tempRecording); - } - - private void OnDidPlayToEndTime(object sender, NSNotificationEventArgs e) - { - player.Dispose(); - player = null; - - Status = Status.Recorded; - } - - partial void PlayRecorded(UIButton sender) - { - Console.WriteLine($"Playing Back Recording {audioFilePath}"); - - // The following line prevents the audio from stopping - // when the device autolocks. will also make sure that it plays, even - // if the device is in mute - AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out NSError error); - if (error == null) - { - Status = Status.Playing; - player = new AVPlayer(audioFilePath); - player.Play(); - } - else - { - Status = Status.Recorded; - Console.WriteLine(error.LocalizedDescription); - } - } - - private bool PrepareAudioRecording() - { - var result = false; - - audioFilePath = CreateOutputUrl(); - - var audioSettings = new AudioSettings - { - SampleRate = 44100, - NumberChannels = 1, - AudioQuality = AVAudioQuality.High, - Format = AudioToolbox.AudioFormatType.MPEG4AAC, - }; - - // Set recorder parameters - recorder = AVAudioRecorder.Create(audioFilePath, audioSettings, out NSError error); - if (error == null) - { - // Set Recorder to Prepare To Record - if (!recorder.PrepareToRecord()) - { - recorder.Dispose(); - recorder = null; - } - else - { - recorder.FinishedRecording += OnFinishedRecording; - result = true; - } - } - else - { - Console.WriteLine(error.LocalizedDescription); - } - - return result; - } - - private void OnFinishedRecording(object sender, AVStatusEventArgs e) - { - recorder.Dispose(); - recorder = null; - - Console.WriteLine($"Done Recording (status: {e.Status})"); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (observer != null) - { - observer.Dispose(); - observer = null; - } - - if (player != null) - { - player.Dispose(); - player = null; - } - - if (recorder != null) - { - recorder.Dispose(); - recorder = null; - } - - if (audioFilePath != null) - { - audioFilePath.Dispose(); - audioFilePath = null; - } - } - } - - public enum Status - { - Unknown, - PreparingError, - Recording, - Recorded, - Playing, - } -} \ No newline at end of file +namespace Sound { + public partial class ViewController : UIViewController { + private NSObject observer; + + private AVPlayer player; + + private NSUrl audioFilePath; + + private AVAudioRecorder recorder; + + private Stopwatch stopwatch; + + private Status status; + + protected ViewController (IntPtr handle) : base (handle) { } + + protected Status Status { + get { + return status; + } + + set { + if (status != value) { + status = value; + UpdateUserInterface (); + } + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + playButton.Enabled = false; + stopButton.Enabled = false; + statusLabel.Text = string.Empty; + lenghtButton.Text = string.Empty; + + observer = AVPlayerItem.Notifications.ObserveDidPlayToEndTime (OnDidPlayToEndTime); + } + + private void UpdateUserInterface () + { + switch (status) { + case Status.PreparingError: + statusLabel.Text = "Error preparing"; + lenghtButton.Text = string.Empty; + startButton.Enabled = true; + stopButton.Enabled = false; + playButton.Enabled = false; + break; + + case Status.Playing: + statusLabel.Text = "Playing"; + startButton.Enabled = false; + stopButton.Enabled = false; + playButton.Enabled = false; + break; + + case Status.Recording: + lenghtButton.Text = string.Empty; + statusLabel.Text = "Recording"; + startButton.Enabled = false; + stopButton.Enabled = true; + playButton.Enabled = false; + break; + + case Status.Recorded: + lenghtButton.Text = string.Format ("{0:hh\\:mm\\:ss}", stopwatch.Elapsed); + statusLabel.Text = string.Empty; + startButton.Enabled = true; + stopButton.Enabled = false; + playButton.Enabled = true; + break; + } + } + + partial void StartRecording (UIButton sender) + { + Console.WriteLine ("Begin Recording"); + + var session = AVAudioSession.SharedInstance (); + session.RequestRecordPermission ((granted) => { + Console.WriteLine ($"Audio Permission: {granted}"); + + if (granted) { + session.SetCategory (AVAudioSession.CategoryRecord, out NSError error); + if (error == null) { + session.SetActive (true, out error); + if (error != null) { + Status = Status.PreparingError; + } else { + var isPrepared = PrepareAudioRecording () && recorder.Record (); + if (isPrepared) { + stopwatch = new Stopwatch (); + stopwatch.Start (); + Status = Status.Recording; + } else { + Status = Status.PreparingError; + } + } + } else { + Console.WriteLine (error.LocalizedDescription); + } + } else { + Console.WriteLine ("YOU MUST ENABLE MICROPHONE PERMISSION"); + } + }); + } + + partial void StopRecording (UIButton sender) + { + if (recorder != null) { + recorder.Stop (); + stopwatch?.Stop (); + + Status = Status.Recorded; + } + } + + private NSUrl CreateOutputUrl () + { + var fileName = $"Myfile-{DateTime.Now.ToString ("yyyyMMddHHmmss")}.aac"; + var tempRecording = Path.Combine (Path.GetTempPath (), fileName); + + return NSUrl.FromFilename (tempRecording); + } + + private void OnDidPlayToEndTime (object sender, NSNotificationEventArgs e) + { + player.Dispose (); + player = null; + + Status = Status.Recorded; + } + + partial void PlayRecorded (UIButton sender) + { + Console.WriteLine ($"Playing Back Recording {audioFilePath}"); + + // The following line prevents the audio from stopping + // when the device autolocks. will also make sure that it plays, even + // if the device is in mute + AVAudioSession.SharedInstance ().SetCategory (AVAudioSession.CategoryPlayback, out NSError error); + if (error == null) { + Status = Status.Playing; + player = new AVPlayer (audioFilePath); + player.Play (); + } else { + Status = Status.Recorded; + Console.WriteLine (error.LocalizedDescription); + } + } + + private bool PrepareAudioRecording () + { + var result = false; + + audioFilePath = CreateOutputUrl (); + + var audioSettings = new AudioSettings { + SampleRate = 44100, + NumberChannels = 1, + AudioQuality = AVAudioQuality.High, + Format = AudioToolbox.AudioFormatType.MPEG4AAC, + }; + + // Set recorder parameters + recorder = AVAudioRecorder.Create (audioFilePath, audioSettings, out NSError error); + if (error == null) { + // Set Recorder to Prepare To Record + if (!recorder.PrepareToRecord ()) { + recorder.Dispose (); + recorder = null; + } else { + recorder.FinishedRecording += OnFinishedRecording; + result = true; + } + } else { + Console.WriteLine (error.LocalizedDescription); + } + + return result; + } + + private void OnFinishedRecording (object sender, AVStatusEventArgs e) + { + recorder.Dispose (); + recorder = null; + + Console.WriteLine ($"Done Recording (status: {e.Status})"); + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (observer != null) { + observer.Dispose (); + observer = null; + } + + if (player != null) { + player.Dispose (); + player = null; + } + + if (recorder != null) { + recorder.Dispose (); + recorder = null; + } + + if (audioFilePath != null) { + audioFilePath.Dispose (); + audioFilePath = null; + } + } + } + + public enum Status { + Unknown, + PreparingError, + Recording, + Recorded, + Playing, + } +} diff --git a/SplitView/SplitView/AppDelegate.cs b/SplitView/SplitView/AppDelegate.cs index 00fd6d3d0..9fd1f358b 100755 --- a/SplitView/SplitView/AppDelegate.cs +++ b/SplitView/SplitView/AppDelegate.cs @@ -3,11 +3,9 @@ using Foundation; using Example_SplitView.Screens; -namespace Example_SplitView -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace Example_SplitView { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected Screens.MainSplitView.MainSplitView splitView; diff --git a/SplitView/SplitView/Application.cs b/SplitView/SplitView/Application.cs index ed614dc6c..db3582e92 100755 --- a/SplitView/SplitView/Application.cs +++ b/SplitView/SplitView/Application.cs @@ -1,11 +1,10 @@ using System; using UIKit; -namespace Example_SplitView -{ +namespace Example_SplitView { public class Application// : UIApplication { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); diff --git a/SplitView/SplitView/Screens/DetailView/DetailViewScreen.xib.cs b/SplitView/SplitView/Screens/DetailView/DetailViewScreen.xib.cs index 0bdaaf51d..236b79805 100755 --- a/SplitView/SplitView/Screens/DetailView/DetailViewScreen.xib.cs +++ b/SplitView/SplitView/Screens/DetailView/DetailViewScreen.xib.cs @@ -5,17 +5,14 @@ using Foundation; using UIKit; -namespace Example_SplitView.Screens.DetailView -{ - public partial class DetailViewScreen : UIViewController - { +namespace Example_SplitView.Screens.DetailView { + public partial class DetailViewScreen : UIViewController { /// <summary> /// The text for the item number label. I expose this to show a way /// you can communicate between master and detail view. /// </summary> - public string Text - { + public string Text { get { return lblItemNumber.Text; } set { lblItemNumber.Text = value; } } @@ -25,18 +22,18 @@ public string Text // The IntPtr and initWithCoder constructors are required for controllers that need // to be able to be created from a xib rather than from managed code - public DetailViewScreen (IntPtr handle) : base(handle) + public DetailViewScreen (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public DetailViewScreen (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public DetailViewScreen (NSCoder coder) : base (coder) { Initialize (); } - public DetailViewScreen () : base("DetailViewScreen", null) + public DetailViewScreen () : base ("DetailViewScreen", null) { Initialize (); } @@ -61,12 +58,12 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat public void AddContentsButton (UIBarButtonItem button) { button.Title = "Contents"; - tlbrTop.SetItems (new UIBarButtonItem[] { button }, false ); + tlbrTop.SetItems (new UIBarButtonItem [] { button }, false); } public void RemoveContentsButton () { - tlbrTop.SetItems (new UIBarButtonItem[0], false); + tlbrTop.SetItems (new UIBarButtonItem [0], false); } } diff --git a/SplitView/SplitView/Screens/MainSplitView/MainSplitView.cs b/SplitView/SplitView/Screens/MainSplitView/MainSplitView.cs index 9eef52417..043165da2 100755 --- a/SplitView/SplitView/Screens/MainSplitView/MainSplitView.cs +++ b/SplitView/SplitView/Screens/MainSplitView/MainSplitView.cs @@ -2,14 +2,12 @@ using UIKit; using CoreFoundation; -namespace Example_SplitView.Screens.MainSplitView -{ - public class MainSplitView : UISplitViewController - { +namespace Example_SplitView.Screens.MainSplitView { + public class MainSplitView : UISplitViewController { protected Screens.MasterView.MasterTableView masterView; protected Screens.DetailView.DetailViewScreen detailView; - public MainSplitView () : base() + public MainSplitView () : base () { // create our master and detail views masterView = new Screens.MasterView.MasterTableView (); @@ -25,7 +23,7 @@ public MainSplitView () : base() // when the master view controller is hid (portrait mode), we add a button to // the detail view that when clicked will show the master view in a popover controller this.WillHideViewController += (object sender, UISplitViewHideEventArgs e) => { - detailView.AddContentsButton(e.BarButtonItem); + detailView.AddContentsButton (e.BarButtonItem); }; // when the master view controller is shown (landscape mode), remove the button @@ -45,7 +43,7 @@ public MainSplitView () : base() // http://spouliot.wordpress.com/2012/03/26/events-vs-objective-c-delegates/ // create an array of controllers from them and then assign it to the // controllers property - ViewControllers = new UIViewController[] { masterView, detailView }; + ViewControllers = new UIViewController [] { masterView, detailView }; } } } diff --git a/SplitView/SplitView/Screens/MasterView/MasterTableView.cs b/SplitView/SplitView/Screens/MasterView/MasterTableView.cs index 398832657..d9ccfff63 100755 --- a/SplitView/SplitView/Screens/MasterView/MasterTableView.cs +++ b/SplitView/SplitView/Screens/MasterView/MasterTableView.cs @@ -2,10 +2,8 @@ using UIKit; using System.Collections.Generic; -namespace Example_SplitView.Screens.MasterView -{ - public class MasterTableView : UITableViewController - { +namespace Example_SplitView.Screens.MasterView { + public class MasterTableView : UITableViewController { TableSource tableSource; public event EventHandler<RowClickedEventArgs> RowClicked; @@ -23,7 +21,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); // setup our data source - List<string> items = new List<string>(); + List<string> items = new List<string> (); for (int i = 1; i <= 10; i++) items.Add (i.ToString ()); tableSource = new TableSource (items, this); @@ -38,21 +36,19 @@ public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientat return true; } - public class RowClickedEventArgs : EventArgs - { + public class RowClickedEventArgs : EventArgs { public string Item { get; set; } - public RowClickedEventArgs(string item) : base() + public RowClickedEventArgs (string item) : base () { this.Item = item; } } - protected class TableSource : UITableViewSource - { + protected class TableSource : UITableViewSource { public List<string> Items = new List<string> (); protected string cellIdentifier = "basicCell"; protected MasterTableView parentController; - public TableSource(List<string> items, MasterTableView parentController) + public TableSource (List<string> items, MasterTableView parentController) { Items = items; this.parentController = parentController; @@ -74,7 +70,7 @@ public override UITableViewCell GetCell (UITableView tableView, Foundation.NSInd if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier); // set the item text - cell.TextLabel.Text = Items[indexPath.Row]; + cell.TextLabel.Text = Items [indexPath.Row]; return cell; } @@ -82,7 +78,7 @@ public override UITableViewCell GetCell (UITableView tableView, Foundation.NSInd public override void RowSelected (UITableView tableView, Foundation.NSIndexPath indexPath) { if (parentController.RowClicked != null) - parentController.RowClicked (this, new RowClickedEventArgs(Items[indexPath.Row])); + parentController.RowClicked (this, new RowClickedEventArgs (Items [indexPath.Row])); } } } diff --git a/SpriteKit/SpriteKit/AppDelegate.cs b/SpriteKit/SpriteKit/AppDelegate.cs index a6a92f85a..8720760d9 100644 --- a/SpriteKit/SpriteKit/AppDelegate.cs +++ b/SpriteKit/SpriteKit/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace SpriteKit -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace SpriteKit { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/SpriteKit/SpriteKit/GameScene.cs b/SpriteKit/SpriteKit/GameScene.cs index 02de434ef..12e457e06 100644 --- a/SpriteKit/SpriteKit/GameScene.cs +++ b/SpriteKit/SpriteKit/GameScene.cs @@ -1,53 +1,48 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; using System; using UIKit; -namespace SpriteKit -{ - public class GameScene : SKScene - { - protected GameScene(IntPtr handle) : base(handle) { } - - public GameScene(CGSize size) : base(size) { } - - public override void DidMoveToView(SKView view) - { - // Setup your scene here - BackgroundColor = new UIKit.UIColor (.15f, .15f, .3f, 1); - var myLabel = new SKLabelNode("Chalkduster") - { - FontSize = 30, - Text = "Hello, World!", - Position = new CGPoint(Frame.GetMidX(),Frame.GetMidY()) - }; - - AddChild(myLabel); - } - - public override void TouchesBegan(NSSet touches, UIEvent evt) - { - // Called when a touch begins - foreach (UITouch touch in touches) - { - var location = touch.LocationInNode(this); - var sprite = new SKSpriteNode("Spaceship") - { - Position = location, - XScale = 0.5f, - YScale = 0.5f - }; - - var action = SKAction.RotateByAngle(NMath.PI, 1.0); - sprite.RunAction(SKAction.RepeatActionForever(action)); - - AddChild(sprite); - } - } - - public override void Update(double currentTime) - { - // Called before each frame is rendered - } - } -} \ No newline at end of file +namespace SpriteKit { + public class GameScene : SKScene { + protected GameScene (IntPtr handle) : base (handle) { } + + public GameScene (CGSize size) : base (size) { } + + public override void DidMoveToView (SKView view) + { + // Setup your scene here + BackgroundColor = new UIKit.UIColor (.15f, .15f, .3f, 1); + var myLabel = new SKLabelNode ("Chalkduster") { + FontSize = 30, + Text = "Hello, World!", + Position = new CGPoint (Frame.GetMidX (), Frame.GetMidY ()) + }; + + AddChild (myLabel); + } + + public override void TouchesBegan (NSSet touches, UIEvent evt) + { + // Called when a touch begins + foreach (UITouch touch in touches) { + var location = touch.LocationInNode (this); + var sprite = new SKSpriteNode ("Spaceship") { + Position = location, + XScale = 0.5f, + YScale = 0.5f + }; + + var action = SKAction.RotateByAngle (NMath.PI, 1.0); + sprite.RunAction (SKAction.RepeatActionForever (action)); + + AddChild (sprite); + } + } + + public override void Update (double currentTime) + { + // Called before each frame is rendered + } + } +} diff --git a/SpriteKit/SpriteKit/GameViewController.cs b/SpriteKit/SpriteKit/GameViewController.cs index 6c9260093..ba15f85bf 100644 --- a/SpriteKit/SpriteKit/GameViewController.cs +++ b/SpriteKit/SpriteKit/GameViewController.cs @@ -1,45 +1,43 @@ -using SpriteKit; +using SpriteKit; using System; using UIKit; -namespace SpriteKit -{ - public partial class GameViewController : UIViewController - { - protected GameViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Configure the view. - var skView = View as SKView; - skView.ShowsFPS = true; - skView.ShowsNodeCount = true; - /* Sprite Kit applies additional optimizations to improve rendering performance */ - skView.IgnoresSiblingOrder = true; - - // Create and configure the scene. - var scene = new GameScene(View.Bounds.Size); - scene.ScaleMode = SKSceneScaleMode.AspectFill; - - // Present the scene. - skView.PresentScene(scene); - } - - public override bool ShouldAutorotate() - { - return true; - } - - public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() - { - return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone ? UIInterfaceOrientationMask.AllButUpsideDown : UIInterfaceOrientationMask.All; - } - - public override bool PrefersStatusBarHidden() - { - return true; - } - } -} \ No newline at end of file +namespace SpriteKit { + public partial class GameViewController : UIViewController { + protected GameViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Configure the view. + var skView = View as SKView; + skView.ShowsFPS = true; + skView.ShowsNodeCount = true; + /* Sprite Kit applies additional optimizations to improve rendering performance */ + skView.IgnoresSiblingOrder = true; + + // Create and configure the scene. + var scene = new GameScene (View.Bounds.Size); + scene.ScaleMode = SKSceneScaleMode.AspectFill; + + // Present the scene. + skView.PresentScene (scene); + } + + public override bool ShouldAutorotate () + { + return true; + } + + public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () + { + return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone ? UIInterfaceOrientationMask.AllButUpsideDown : UIInterfaceOrientationMask.All; + } + + public override bool PrefersStatusBarHidden () + { + return true; + } + } +} diff --git a/SpriteKit/SpriteKit/Main.cs b/SpriteKit/SpriteKit/Main.cs index 47b45eee1..39c5f9b4e 100644 --- a/SpriteKit/SpriteKit/Main.cs +++ b/SpriteKit/SpriteKit/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace SpriteKit -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace SpriteKit { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/AppDelegate.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/AppDelegate.cs index 7344bc46b..a7dcbb36e 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/AppDelegate.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/AppDelegate.cs @@ -12,7 +12,7 @@ public override UIWindow Window { set; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Category.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Category.cs index 09f14531c..f6eeb4c9b 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Category.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Category.cs @@ -1,15 +1,13 @@ -using System; +using System; -namespace SpriteKitPhysicsCollisions -{ +namespace SpriteKitPhysicsCollisions { // an enum [Flag] could be used but would require more casts - public static class Category - { - public const uint Missile = 0x1 << 0; - public const uint Ship = 0x1 << 1; + public static class Category { + public const uint Missile = 0x1 << 0; + public const uint Ship = 0x1 << 1; public const uint Asteroid = 0x1 << 2; - public const uint Planet = 0x1 << 3; - public const uint Edge = 0x1 << 4; + public const uint Planet = 0x1 << 3; + public const uint Edge = 0x1 << 4; } } diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ArchiveBasedNode.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ArchiveBasedNode.cs index 05ebc8c88..fde875ea6 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ArchiveBasedNode.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ArchiveBasedNode.cs @@ -1,19 +1,17 @@ -using System; +using System; using SpriteKit; using Foundation; -namespace SpriteKitPhysicsCollisions -{ - public abstract class ArchiveBasedNode : SKEmitterNode - { +namespace SpriteKitPhysicsCollisions { + public abstract class ArchiveBasedNode : SKEmitterNode { public ArchiveBasedNode (IntPtr template) : base (template) { // calling the base .ctor with the Handle of the Copy will add an extra Retain //Release (); } - + protected static SKEmitterNode UnarchiveNode (string name, string type) { var path = NSBundle.MainBundle.PathForResource (name, type); diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/AsteroidNode.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/AsteroidNode.cs index 1d9c32f31..d61188022 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/AsteroidNode.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/AsteroidNode.cs @@ -1,19 +1,17 @@ -using System; +using System; using UIKit; using SpriteKit; using CoreGraphics; -namespace SpriteKitPhysicsCollisions -{ - public class AsteroidNode : SKShapeNode - { +namespace SpriteKitPhysicsCollisions { + public class AsteroidNode : SKShapeNode { const float defaultSize = 18f; public AsteroidNode (CGPoint initialPosition, float size = defaultSize) { var path = new CGPath (); - path.AddArc (0, 0, size, 0, (float)Math.PI * 2f, true); + path.AddArc (0, 0, size, 0, (float) Math.PI * 2f, true); Path = path; StrokeColor = UIColor.Clear; FillColor = UIColor.Brown; diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/DamageNode.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/DamageNode.cs index 45082a9da..c520ef2c8 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/DamageNode.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/DamageNode.cs @@ -1,11 +1,9 @@ -using System; +using System; using SpriteKit; using Foundation; -namespace SpriteKitPhysicsCollisions -{ - public class DamageNode : ArchiveBasedNode - { +namespace SpriteKitPhysicsCollisions { + public class DamageNode : ArchiveBasedNode { static readonly SKEmitterNode template; static DamageNode () @@ -20,4 +18,4 @@ public DamageNode (SKNode target) TargetNode = target; } } -} \ No newline at end of file +} diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExhaustNoder.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExhaustNoder.cs index 97c4f6520..7e999fbd9 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExhaustNoder.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExhaustNoder.cs @@ -4,10 +4,8 @@ using Foundation; using CoreGraphics; -namespace SpriteKitPhysicsCollisions -{ - public class ExhaustNode : ArchiveBasedNode - { +namespace SpriteKitPhysicsCollisions { + public class ExhaustNode : ArchiveBasedNode { public const float IdleAlpha = 0.05f; static SKEmitterNode template; diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExplosionNode.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExplosionNode.cs index 6d51f51cb..a802d4f78 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExplosionNode.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/ExplosionNode.cs @@ -1,13 +1,11 @@ -using System; +using System; using SpriteKit; using Foundation; using CoreGraphics; -namespace SpriteKitPhysicsCollisions -{ - public class ExplosionNode : ArchiveBasedNode - { +namespace SpriteKitPhysicsCollisions { + public class ExplosionNode : ArchiveBasedNode { const double defaultDuration = 0.1f; static SKEmitterNode template = UnarchiveNode ("explosion", "sks"); diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/NodeFactory.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/NodeFactory.cs index 12bd99c6c..fe0d7c1c8 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/NodeFactory.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/NodeFactory.cs @@ -1,13 +1,11 @@ -using System; +using System; using SpriteKit; using Foundation; using CoreGraphics; -namespace SpriteKitPhysicsCollisions -{ - public static class NodeFactory - { +namespace SpriteKitPhysicsCollisions { + public static class NodeFactory { static readonly nfloat shotSize = 4; static SKEmitterNode UnarchiveEmitterNode (string name) @@ -24,7 +22,7 @@ public static SKEmitterNode CreateExplosionNode (SKNode target, double duration) emitter.TargetNode = target; // Stop spawning particles after enough have been spawned. - emitter.NumParticlesToEmit =(nuint)(duration * emitter.ParticleBirthRate); + emitter.NumParticlesToEmit = (nuint) (duration * emitter.ParticleBirthRate); // Calculate a time value that allows all the spawned particles to die. After this, the emitter node can be removed. @@ -33,11 +31,11 @@ public static SKEmitterNode CreateExplosionNode (SKNode target, double duration) return emitter; } - public static SKNode CreateMissileNode(SKNode target) + public static SKNode CreateMissileNode (SKNode target) { // Creates and returns a new missile game object. // This method loads a preconfigured emitter from an archive, and then configures it with a physics body. - SKEmitterNode missile = UnarchiveEmitterNode("missile"); + SKEmitterNode missile = UnarchiveEmitterNode ("missile"); // The missile particles should be spawned in the scene, not on the missile object. missile.TargetNode = target; diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/PlanetNode.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/PlanetNode.cs index 3ff48dea6..fb0e9752d 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/PlanetNode.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/Nodes/PlanetNode.cs @@ -1,19 +1,17 @@ -using System; +using System; using UIKit; using SpriteKit; using CoreGraphics; -namespace SpriteKitPhysicsCollisions -{ - public class PlanetNode : SKShapeNode - { +namespace SpriteKitPhysicsCollisions { + public class PlanetNode : SKShapeNode { const float defaultSize = 64f; public PlanetNode (CGPoint initialPosition, float size = defaultSize) { var path = new CGPath (); - path.AddArc (0, 0, size, 0, (float)Math.PI * 2f, true); + path.AddArc (0, 0, size, 0, (float) Math.PI * 2f, true); Path = path; StrokeColor = UIColor.Clear; FillColor = UIColor.Green; @@ -26,4 +24,4 @@ public PlanetNode (CGPoint initialPosition, float size = defaultSize) PhysicsBody = body; } } -} \ No newline at end of file +} diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/PlayerActions.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/PlayerActions.cs index a0183432f..f68f48c1f 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/PlayerActions.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/PlayerActions.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace SpriteKitPhysicsCollisions -{ - public enum PlayerActions - { +namespace SpriteKitPhysicsCollisions { + public enum PlayerActions { Forward = 0, Left = 1, Right = 2, diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/ShipSprite.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/ShipSprite.cs index 604634318..ccdc92e6b 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/ShipSprite.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/ShipSprite.cs @@ -4,10 +4,8 @@ using SpriteKit; using UIKit; -namespace SpriteKitPhysicsCollisions -{ - public class ShipSprite : SKSpriteNode - { +namespace SpriteKitPhysicsCollisions { + public class ShipSprite : SKSpriteNode { const int startingShipHealth = 10; const int showDamageBelowHealth = 4; @@ -38,7 +36,7 @@ public class ShipSprite : SKSpriteNode static readonly Random rand = new Random (); static float myRand (float low, float high) { - return (float)rand.NextDouble () * (high - low) + low; + return (float) rand.NextDouble () * (high - low) + low; } public ShipSprite (CGPoint initialPosition) @@ -82,7 +80,7 @@ public ExhaustNode ExhaustNode { get { if (exhaustNode == null) { var emitter = new ExhaustNode (Scene); - engineEngagedAlpha = (float)emitter.ParticleAlpha; + engineEngagedAlpha = (float) emitter.ParticleAlpha; AddChild (emitter); exhaustNode = emitter; } @@ -90,32 +88,31 @@ public ExhaustNode ExhaustNode { } } - void ShowDamage() + void ShowDamage () { // When the ship first shows damage, a damage node is created and added as a child. // If it takes more damage, then the number of particles is increased. - if (visibleDamageNode == null) - { - visibleDamageNode = (SKEmitterNode)NSKeyedUnarchiver.UnarchiveFile (NSBundle.MainBundle.PathForResource ("damage", "sks")); + if (visibleDamageNode == null) { + visibleDamageNode = (SKEmitterNode) NSKeyedUnarchiver.UnarchiveFile (NSBundle.MainBundle.PathForResource ("damage", "sks")); visibleDamageNode.Name = @"damaged"; // Make the scene the target node because the ship is moving around in the scene. Smoke particles // should be spawned based on the ship, but should otherwise exist independently of the ship. visibleDamageNode.TargetNode = Scene; - AddChild(visibleDamageNode); + AddChild (visibleDamageNode); } else { visibleDamageNode.ParticleBirthRate = visibleDamageNode.ParticleBirthRate * 2; } } - void MakeExhaustNode() + void MakeExhaustNode () { - var emitter = (ExhaustNode)NSKeyedUnarchiver.UnarchiveFile (NSBundle.MainBundle.PathForResource ("exhaust", "sks")); + var emitter = (ExhaustNode) NSKeyedUnarchiver.UnarchiveFile (NSBundle.MainBundle.PathForResource ("exhaust", "sks")); // Hard coded position at the back of the ship. - emitter.Position = new CGPoint(0, -40); + emitter.Position = new CGPoint (0, -40); emitter.Name = "exhaust"; // Make the scene the target node because the ship is moving around in the scene. Exhaust particles @@ -133,7 +130,7 @@ void MakeExhaustNode() exhaustNode = emitter; } - void MakeExhaustNodeIfNeeded() + void MakeExhaustNodeIfNeeded () { if (exhaustNode == null) MakeExhaustNode (); @@ -158,12 +155,12 @@ void Explode () { // Create a bunch of explosion emitters and send them flying in all directions. Then remove the ship from the scene. for (int i = 0; i < numberOfChunks; i++) { - SKEmitterNode explosion = NodeFactory.CreateExplosionNode(Scene, shipExplosionDuration); + SKEmitterNode explosion = NodeFactory.CreateExplosionNode (Scene, shipExplosionDuration); float angle = myRand (0, (float) Math.PI * 2); float speed = myRand (shipChunkMinimumSpeed, shipChunkMaximumSpeed); - var x = myRand ((float)Position.X - shipChunkDispersion, (float)Position.X + shipChunkDispersion); - var y = myRand ((float)Position.Y - shipChunkDispersion, (float)Position.Y + shipChunkDispersion); + var x = myRand ((float) Position.X - shipChunkDispersion, (float) Position.X + shipChunkDispersion); + var y = myRand ((float) Position.Y - shipChunkDispersion, (float) Position.Y + shipChunkDispersion); explosion.Position = new CGPoint (x, y); var body = SKPhysicsBody.CreateCircularBody (0.25f); @@ -186,7 +183,7 @@ public float ShipOrientation { get { // The ship art is oriented so that it faces the top of the scene, but Sprite Kit's rotation default is to the right. // This method calculates the ship orientation for use in other calculations. - return (float)ZRotation + (float)Math.PI / 2; + return (float) ZRotation + (float) Math.PI / 2; } } @@ -194,7 +191,7 @@ public float ShipExhaustAngle { get { // The ship art is oriented so that it faces the top of the scene, but Sprite Kit's rotation default is to the right. // This method calculates the direction for the ship's rear. - return (float)ZRotation - (float)Math.PI / 2; + return (float) ZRotation - (float) Math.PI / 2; } } @@ -203,8 +200,8 @@ public void ActivateMainEngine () // Add flames out the back and apply thrust to the ship. float shipDirection = ShipOrientation; - var dx = mainEngineThrust * (float)Math.Cos (shipDirection); - var dy = mainEngineThrust * (float)Math.Sin (shipDirection); + var dx = mainEngineThrust * (float) Math.Cos (shipDirection); + var dy = mainEngineThrust * (float) Math.Sin (shipDirection); PhysicsBody.ApplyForce (new CGVector (dx, dy)); MakeExhaustNodeIfNeeded (); @@ -221,8 +218,8 @@ public void DeactivateMainEngine () public void ReverseThrust () { double reverseDirection = ShipOrientation + Math.PI; - var dx = reverseThrust * (float)Math.Cos (reverseDirection); - var dy = reverseThrust * (float)Math.Sin (reverseDirection); + var dx = reverseThrust * (float) Math.Cos (reverseDirection); + var dy = reverseThrust * (float) Math.Sin (reverseDirection); PhysicsBody.ApplyForce (new CGVector (dx, dy)); } @@ -261,4 +258,4 @@ public void AttemptMissileLaunch (double currentTime) } } } -} \ No newline at end of file +} diff --git a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/SpaceScene.cs b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/SpaceScene.cs index 06cc77602..bb99f97c5 100644 --- a/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/SpaceScene.cs +++ b/SpriteKitPhysicsCollisions/SpriteKitPhysicsCollisions/SpaceScene.cs @@ -5,14 +5,12 @@ using Foundation; using CoreGraphics; -namespace SpriteKitPhysicsCollisions -{ - public class SpaceScene : SKScene, ISKPhysicsContactDelegate - { +namespace SpriteKitPhysicsCollisions { + public class SpaceScene : SKScene, ISKPhysicsContactDelegate { const float collisionDamageThreshold = 1.0f; const int missileDamage = 1; - bool[] actions = new bool [5]; + bool [] actions = new bool [5]; bool contentCreated; ShipSprite controlledShip; @@ -20,7 +18,7 @@ public class SpaceScene : SKScene, ISKPhysicsContactDelegate static float myRand (float low, float high) { - return (float)rand.NextDouble () * (high - low) + low; + return (float) rand.NextDouble () * (high - low) + low; } public SpaceScene (CGSize size) @@ -68,12 +66,12 @@ void AttackTarget (SKPhysicsBody target, SKNode missile) { // Only ships take damage from missiles. if ((target.CategoryBitMask & Category.Ship) != 0) - ((ShipSprite)target.Node).ApplyDamage (missileDamage); + ((ShipSprite) target.Node).ApplyDamage (missileDamage); DetonateMissile (missile); } - void DetonateMissile(SKNode missile) + void DetonateMissile (SKNode missile) { SKEmitterNode explosion = new ExplosionNode (this); explosion.Position = missile.Position; @@ -117,10 +115,10 @@ public void DidBeginContact (SKPhysicsContact contact) // so ships should not take damage when they hit the edge. if (contact.CollisionImpulse > collisionDamageThreshold && (secondBody.CategoryBitMask & Category.Edge) == 0) { int damage = (int) (contact.CollisionImpulse / collisionDamageThreshold); - ((ShipSprite)firstBody.Node).ApplyDamage (damage); + ((ShipSprite) firstBody.Node).ApplyDamage (damage); if ((secondBody.CategoryBitMask == Category.Ship)) - ((ShipSprite)secondBody.Node).ApplyDamage (damage); + ((ShipSprite) secondBody.Node).ApplyDamage (damage); } } @@ -140,21 +138,21 @@ public override void Update (double currentTime) // if the target ship was controlled by the computer, you might run AI from this routine. // Use the stored key information to control the ship. - if (actions [(int)PlayerActions.Forward]) + if (actions [(int) PlayerActions.Forward]) controlledShip.ActivateMainEngine (); else controlledShip.DeactivateMainEngine (); - if (actions [(int)PlayerActions.Back]) + if (actions [(int) PlayerActions.Back]) controlledShip.ReverseThrust (); - if (actions [(int)PlayerActions.Left]) + if (actions [(int) PlayerActions.Left]) controlledShip.RotateShipLeft (); - if (actions [(int)PlayerActions.Right]) + if (actions [(int) PlayerActions.Right]) controlledShip.RotateShipRight (); - if (actions [(int)PlayerActions.Action]) + if (actions [(int) PlayerActions.Action]) controlledShip.AttemptMissileLaunch (currentTime); } @@ -164,30 +162,30 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); - actions [(int)PlayerActions.Action] = false; - actions [(int)PlayerActions.Left] = false; - actions [(int)PlayerActions.Right] = false; - actions [(int)PlayerActions.Forward] = false; - actions [(int)PlayerActions.Back] = false; + actions [(int) PlayerActions.Action] = false; + actions [(int) PlayerActions.Left] = false; + actions [(int) PlayerActions.Right] = false; + actions [(int) PlayerActions.Forward] = false; + actions [(int) PlayerActions.Back] = false; - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; var location = touch.LocationInView (View); var deltaX = location.X - controlledShip.Position.X; var deltaY = (View.Bounds.Height - location.Y) - controlledShip.Position.Y; if (Math.Abs (deltaX) < 30 && Math.Abs (deltaY) < 30) { - actions [(int)PlayerActions.Action] = true; + actions [(int) PlayerActions.Action] = true; } else if (Math.Abs (deltaX) > Math.Abs (deltaY)) { if (deltaX < 0) - actions [(int)PlayerActions.Left] = true; + actions [(int) PlayerActions.Left] = true; else - actions [(int)PlayerActions.Right] = true; + actions [(int) PlayerActions.Right] = true; } else { if (deltaY < 0) - actions [(int)PlayerActions.Forward] = true; + actions [(int) PlayerActions.Forward] = true; else - actions [(int)PlayerActions.Back] = true; + actions [(int) PlayerActions.Back] = true; } } @@ -195,30 +193,30 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); - actions [(int)PlayerActions.Action] = false; - actions [(int)PlayerActions.Left] = false; - actions [(int)PlayerActions.Right] = false; - actions [(int)PlayerActions.Forward] = false; - actions [(int)PlayerActions.Back] = false; + actions [(int) PlayerActions.Action] = false; + actions [(int) PlayerActions.Left] = false; + actions [(int) PlayerActions.Right] = false; + actions [(int) PlayerActions.Forward] = false; + actions [(int) PlayerActions.Back] = false; - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; var location = touch.LocationInView (View); var deltaX = location.X - controlledShip.Position.X; var deltaY = (View.Bounds.Height - location.Y) - controlledShip.Position.Y; if (Math.Abs (deltaX) < 30 && Math.Abs (deltaY) < 30) - actions [(int)PlayerActions.Action] = true; + actions [(int) PlayerActions.Action] = true; else if (Math.Abs (deltaX) > Math.Abs (deltaY)) { if (deltaX < 0) - actions [(int)PlayerActions.Left] = true; + actions [(int) PlayerActions.Left] = true; else - actions [(int)PlayerActions.Right] = true; + actions [(int) PlayerActions.Right] = true; } else { if (deltaY < 0) - actions [(int)PlayerActions.Forward] = true; + actions [(int) PlayerActions.Forward] = true; else - actions [(int)PlayerActions.Back] = true; + actions [(int) PlayerActions.Back] = true; } } @@ -226,11 +224,11 @@ public override void TouchesEnded (NSSet touches, UIEvent evt) { base.TouchesMoved (touches, evt); - actions [(int)PlayerActions.Action] = false; - actions [(int)PlayerActions.Left] = false; - actions [(int)PlayerActions.Right] = false; - actions [(int)PlayerActions.Forward] = false; - actions [(int)PlayerActions.Back] = false; + actions [(int) PlayerActions.Action] = false; + actions [(int) PlayerActions.Left] = false; + actions [(int) PlayerActions.Right] = false; + actions [(int) PlayerActions.Forward] = false; + actions [(int) PlayerActions.Back] = false; } } } diff --git a/SpriteTour/SpriteTour/AnchorsSpritesViewController.cs b/SpriteTour/SpriteTour/AnchorsSpritesViewController.cs index b1200c3f4..26cd47b19 100644 --- a/SpriteTour/SpriteTour/AnchorsSpritesViewController.cs +++ b/SpriteTour/SpriteTour/AnchorsSpritesViewController.cs @@ -28,7 +28,7 @@ void AddAnchorGrid () SKSpriteNode sprite = new SKSpriteNode ("Art/rocket.png") { AnchorPoint = new CGPoint (0.25f * x, 0.25f * y), Position = new CGPoint (Scene.Frame.GetMidX () - 400 + 100 * x, - Scene.Frame.GetMidY () - 200 + 100 * y) + Scene.Frame.GetMidY () - 200 + 100 * y) }; sprite.SetScale (0.25f); Scene.AddChild (sprite); @@ -74,7 +74,7 @@ SKAction NewAnimateAnchorAction () }); SKAction moveAnchorLeft = SKAction.CustomActionWithDuration (1.0f, (node, elapsedTime) => { - (node as SKSpriteNode).AnchorPoint = new CGPoint(1.0f - elapsedTime, 1.0f); + (node as SKSpriteNode).AnchorPoint = new CGPoint (1.0f - elapsedTime, 1.0f); }); SKAction moveAnchorDown = SKAction.CustomActionWithDuration (1.0f, (node, elapsedTime) => { diff --git a/SpriteTour/SpriteTour/AnimatedSpritesViewController.cs b/SpriteTour/SpriteTour/AnimatedSpritesViewController.cs index 8fb4bb09a..bac0b3449 100644 --- a/SpriteTour/SpriteTour/AnimatedSpritesViewController.cs +++ b/SpriteTour/SpriteTour/AnimatedSpritesViewController.cs @@ -15,7 +15,7 @@ protected override void CreateSceneContents () { base.CreateSceneContents (); - SKTexture[] walkFrames = LoadFrames ("Art/warrior_walk_", 28); + SKTexture [] walkFrames = LoadFrames ("Art/warrior_walk_", 28); SKSpriteNode sprite = new SKSpriteNode (walkFrames [0]) { Position = new CGPoint (Scene.Frame.GetMidX (), Scene.Frame.GetMidY ()) diff --git a/SpriteTour/SpriteTour/AppDelegate.cs b/SpriteTour/SpriteTour/AppDelegate.cs index 754b387fd..61f404f63 100644 --- a/SpriteTour/SpriteTour/AppDelegate.cs +++ b/SpriteTour/SpriteTour/AppDelegate.cs @@ -5,8 +5,7 @@ namespace SpriteTour { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { return true; diff --git a/SpriteTour/SpriteTour/BlendingSpritesViewController.cs b/SpriteTour/SpriteTour/BlendingSpritesViewController.cs index 02cac891b..84bf8a4d1 100644 --- a/SpriteTour/SpriteTour/BlendingSpritesViewController.cs +++ b/SpriteTour/SpriteTour/BlendingSpritesViewController.cs @@ -23,8 +23,8 @@ protected override void CreateSceneContents () // no point in recomputing constant values each time var half_range = range / 2.0f; - basex = (float)Scene.Frame.GetMidX () - half_range; - basey = (float)Scene.Frame.GetMidY () - half_range; + basex = (float) Scene.Frame.GetMidX () - half_range; + basey = (float) Scene.Frame.GetMidY () - half_range; Scene.AddDescription ("These textured sprite nodes are combined using an additive blend", new CGPoint (Scene.Frame.GetMidX (), 100)); diff --git a/SpriteTour/SpriteTour/ColorizedSpritesViewController.cs b/SpriteTour/SpriteTour/ColorizedSpritesViewController.cs index 19299496f..f36c7e79a 100644 --- a/SpriteTour/SpriteTour/ColorizedSpritesViewController.cs +++ b/SpriteTour/SpriteTour/ColorizedSpritesViewController.cs @@ -66,7 +66,7 @@ void AddAnimatedSprite () Scene.AddChild (animatedSprite); Scene.AddDescription ("Animated Color Blending", - new CGPoint (animatedSprite.Position.X, animatedSprite.Position.Y - 90)); + new CGPoint (animatedSprite.Position.X, animatedSprite.Position.Y - 90)); animatedSprite.RunAction (SKAction.RepeatActionForever (SKAction.Sequence ( SKAction.WaitForDuration (1.0), diff --git a/SpriteTour/SpriteTour/Main.cs b/SpriteTour/SpriteTour/Main.cs index 7802835c4..784ee77da 100644 --- a/SpriteTour/SpriteTour/Main.cs +++ b/SpriteTour/SpriteTour/Main.cs @@ -2,12 +2,10 @@ using Foundation; using UIKit; -namespace SpriteTour -{ - public class Application - { +namespace SpriteTour { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/Stars/StarsAppDelegate.cs b/Stars/StarsAppDelegate.cs index af4d6dbc3..48b685c9a 100755 --- a/Stars/StarsAppDelegate.cs +++ b/Stars/StarsAppDelegate.cs @@ -3,24 +3,22 @@ using Foundation; using UIKit; -namespace Stars -{ +namespace Stars { [Register ("StarsAppDelegate")] - public partial class StarsAppDelegate : UIApplicationDelegate - { + public partial class StarsAppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); - window.RootViewController = new StarsViewController(); + window.RootViewController = new StarsViewController (); window.MakeKeyAndVisible (); return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "StarsAppDelegate"); } diff --git a/Stars/StarsViewController.cs b/Stars/StarsViewController.cs index 8ae34bdd8..f99302364 100755 --- a/Stars/StarsViewController.cs +++ b/Stars/StarsViewController.cs @@ -11,10 +11,8 @@ using OpenTK.Graphics.ES20; using OpenTK; -namespace Stars -{ - public class StarsViewController : GLKViewController - { +namespace Stars { + public class StarsViewController : GLKViewController { //comment const double RadiansToDegrees = (180 / Math.PI); const int NumCubes = 11; @@ -23,10 +21,10 @@ public class StarsViewController : GLKViewController const float NearZ = 0.1f; const float FarZ = 1000; - Vector3[] star = new Vector3 [NumStars]; - int[] perm = new int [NumStars]; + Vector3 [] star = new Vector3 [NumStars]; + int [] perm = new int [NumStars]; - static readonly float[] gCubeVertexData = + static readonly float [] gCubeVertexData = { // Data layout for each line below is: // positionX, positionY, positionZ, normalX, normalY, normalZ, @@ -73,7 +71,7 @@ public class StarsViewController : GLKViewController -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f }; - static readonly float[] gColorData = + static readonly float [] gColorData = { 255.0f, 51.0f, 51.0f, 255.0f, 153.0f, 51.0f, @@ -189,7 +187,7 @@ public override void DrawInRect (GLKView view, CGRect rect) // Render the objects with GLKit for (int i = 0; i < (NumCubes + NumStars); i++) { var effect = effects [i]; - effect.PrepareToDraw(); + effect.PrepareToDraw (); GL.DrawArrays (BeginMode.Triangles, 0, 36); } } @@ -204,9 +202,9 @@ public void setupGL () var effect = new GLKBaseEffect (); effect.Light0.Enabled = true; effect.Light0.DiffuseColor = new Vector4 (gColorData [3 * i] / 255.0f, - gColorData [3 * i + 1] / 255.0f, - gColorData [3 * i + 2] / 255.0f, - 1); + gColorData [3 * i + 1] / 255.0f, + gColorData [3 * i + 2] / 255.0f, + 1); effects.Add (effect); } @@ -258,13 +256,13 @@ public override void Update () return; var r = dm.Attitude.RotationMatrix; - float aspect = (float)Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); + float aspect = (float) Math.Abs (View.Bounds.Size.Width / View.Bounds.Size.Height); var projectionMatrix = Matrix4.CreatePerspectiveFieldOfView (MathHelper.DegreesToRadians (65.0f), aspect, NearZ, FarZ); Matrix4 baseModelViewMatrix = new Matrix4 ((float) r.m11, (float) r.m21, (float) r.m31, 0, - (float) r.m12, (float) r.m22, (float) r.m32, 0, - (float) r.m13, (float) r.m23, (float) r.m33, 0, - 0, 0, 0, 1); + (float) r.m12, (float) r.m22, (float) r.m32, 0, + (float) r.m13, (float) r.m23, (float) r.m33, 0, + 0, 0, 0, 1); // Compute the model view matrix for the objects rendered with the GLKIT // the planets @@ -296,9 +294,9 @@ public override void Update () rotation += (float) TimeSinceLastUpdate * 0.8f; rpyLabel.Text = String.Format ("roll: {0}° pitch: {1}° yaw: {2}°", - String.Format("{0:0.#}", dm.Attitude.Roll * RadiansToDegrees), - String.Format("{0:0.#}", dm.Attitude.Pitch * RadiansToDegrees), - String.Format("{0:0.#}", dm.Attitude.Yaw * RadiansToDegrees)); + String.Format ("{0:0.#}", dm.Attitude.Roll * RadiansToDegrees), + String.Format ("{0:0.#}", dm.Attitude.Pitch * RadiansToDegrees), + String.Format ("{0:0.#}", dm.Attitude.Yaw * RadiansToDegrees)); //...now we can print out coordinates } diff --git a/StateRestoration/StateRestoration/AppDelegate.cs b/StateRestoration/StateRestoration/AppDelegate.cs index 11b21c88d..c29f2338f 100644 --- a/StateRestoration/StateRestoration/AppDelegate.cs +++ b/StateRestoration/StateRestoration/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace StateRestoration -{ +namespace StateRestoration { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { DataSource dataSource; public override UIWindow Window { get; set; } @@ -21,11 +19,11 @@ public override bool WillFinishLaunching (UIApplication application, NSDictionar UIApplication.RegisterObjectForStateRestoration (dataSource, "DataSource"); - var navigationController = (UINavigationController)Window.RootViewController; + var navigationController = (UINavigationController) Window.RootViewController; navigationController.NavigationBar.BarStyle = UIBarStyle.Black; navigationController.NavigationBar.Translucent = true; - var viewController = (CollectionViewController)navigationController.ViewControllers [0]; + var viewController = (CollectionViewController) navigationController.ViewControllers [0]; viewController.DataSource = dataSource; Window.MakeKeyAndVisible (); diff --git a/StateRestoration/StateRestoration/Cell/CollectionCell.cs b/StateRestoration/StateRestoration/Cell/CollectionCell.cs index 5263de85d..94d5ed46c 100644 --- a/StateRestoration/StateRestoration/Cell/CollectionCell.cs +++ b/StateRestoration/StateRestoration/Cell/CollectionCell.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace StateRestoration -{ - public partial class CollectionCell : UICollectionViewCell - { +namespace StateRestoration { + public partial class CollectionCell : UICollectionViewCell { UIColor labelColor; public override bool Selected { diff --git a/StateRestoration/StateRestoration/Cell/CustomCellBackground.cs b/StateRestoration/StateRestoration/Cell/CustomCellBackground.cs index d74c7c6b1..9cfc1ba53 100644 --- a/StateRestoration/StateRestoration/Cell/CustomCellBackground.cs +++ b/StateRestoration/StateRestoration/Cell/CustomCellBackground.cs @@ -3,10 +3,8 @@ using UIKit; -namespace StateRestoration -{ - public class CustomCellBackground : UIView - { +namespace StateRestoration { + public class CustomCellBackground : UIView { CustomCellBackground (CGRect frame) : base (frame) { BackgroundColor = UIColor.White; diff --git a/StateRestoration/StateRestoration/CollectionViewController.cs b/StateRestoration/StateRestoration/CollectionViewController.cs index b87b80359..bac776638 100644 --- a/StateRestoration/StateRestoration/CollectionViewController.cs +++ b/StateRestoration/StateRestoration/CollectionViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace StateRestoration -{ - public partial class CollectionViewController : UICollectionViewController - { +namespace StateRestoration { + public partial class CollectionViewController : UICollectionViewController { const string DetailedViewControllerID = "DetailView"; const string CellID = "cellID"; @@ -49,7 +47,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (CollectionCell)collectionView.DequeueReusableCell ((NSString)CellID, indexPath); + var cell = (CollectionCell) collectionView.DequeueReusableCell ((NSString) CellID, indexPath); string identifier = DataSource.GetIdentifier (indexPath); cell.Label.Text = DataSource.GetTitle (identifier); @@ -63,7 +61,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) base.PrepareForSegue (segue, sender); if (segue.Identifier == "showDetail") - PrepareForSegue ((DetailViewController)segue.DestinationViewController); + PrepareForSegue ((DetailViewController) segue.DestinationViewController); } void PrepareForSegue (DetailViewController detailViewController) diff --git a/StateRestoration/StateRestoration/DataSource.cs b/StateRestoration/StateRestoration/DataSource.cs index 3690be561..c20ec22ba 100644 --- a/StateRestoration/StateRestoration/DataSource.cs +++ b/StateRestoration/StateRestoration/DataSource.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace StateRestoration -{ - public class DataSource : UIStateRestoring - { +namespace StateRestoration { + public class DataSource : UIStateRestoring { NSDictionary data; public DataSource () @@ -30,7 +28,7 @@ public string GetIdentifier (NSIndexPath indexPath) public string GetTitle (string identifier) { - string title = string.IsNullOrEmpty (identifier) ? null : (NSString)data [identifier]; + string title = string.IsNullOrEmpty (identifier) ? null : (NSString) data [identifier]; return title ?? "Image"; } diff --git a/StateRestoration/StateRestoration/DetailViewController.cs b/StateRestoration/StateRestoration/DetailViewController.cs index e44c6f238..cb1db91c3 100644 --- a/StateRestoration/StateRestoration/DetailViewController.cs +++ b/StateRestoration/StateRestoration/DetailViewController.cs @@ -9,10 +9,8 @@ using ObjCRuntime; using System.Linq; -namespace StateRestoration -{ - public partial class DetailViewController : UIViewController, IUIObjectRestoration - { +namespace StateRestoration { + public partial class DetailViewController : UIViewController, IUIObjectRestoration { const string blurFilterKey = "kBlurFilterKey"; const string modifyFilterKey = "kModifyFilterKey"; const string imageIdentifierKey = "kImageIdentifierKey"; @@ -25,7 +23,7 @@ public partial class DetailViewController : UIViewController, IUIObjectRestorati UIImage image; nfloat lastScale; bool statusBarHidden; - Dictionary<string,ImageFilter> filters; + Dictionary<string, ImageFilter> filters; UITapGestureRecognizer tapGestureRecognizer; UITapGestureRecognizer doubleTapGestureRecognizer; @@ -132,19 +130,19 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (filterKey == null) return; - var filterViewController = (FilterViewController)segue.DestinationViewController; + var filterViewController = (FilterViewController) segue.DestinationViewController; filterViewController.filter = GetImageFilter (filterKey); } string MapToFilterKey (string segueIdentifier) { switch (segueIdentifier) { - case "showBlurInfo": - return blurFilterKey; - case "showModifyInfo": - return modifyFilterKey; - default: - return null; + case "showBlurInfo": + return blurFilterKey; + case "showModifyInfo": + return modifyFilterKey; + default: + return null; } } @@ -171,19 +169,19 @@ static ImageFilter CreateFilter (string key, bool useDefault) static ImageFilter CreateFilterFrom (string key, bool useDefault) { switch (key) { - case blurFilterKey: - return new BlurFilter (useDefault); - case modifyFilterKey: - return new ModifyFilter (useDefault); - default: - throw new NotImplementedException (); + case blurFilterKey: + return new BlurFilter (useDefault); + case modifyFilterKey: + return new ModifyFilter (useDefault); + default: + throw new NotImplementedException (); } } static void Register (ImageFilter filter, string key) { UIApplication.RegisterObjectForStateRestoration (filter, key); - filter.RestorationType = typeof(DetailViewController); + filter.RestorationType = typeof (DetailViewController); } void OnDoubleTapGesture (UITapGestureRecognizer tapGesture) @@ -268,10 +266,10 @@ T GetFilter<T> (string key) where T : ImageFilter { ImageFilter f; filters.TryGetValue (key, out f); - return (T)f; + return (T) f; } - bool IsAnyDirty (params ImageFilter[] filters) + bool IsAnyDirty (params ImageFilter [] filters) { return filters.Where (f => f != null).Any (f => f.Dirty); } @@ -354,7 +352,7 @@ void SetImageViewConstraints (UIInterfaceOrientation orientation) { bool flip = orientation.IsLandscape (); var bounds = UIScreen.MainScreen.Bounds; - NSLayoutConstraint[] constraints = imageView.Constraints; + NSLayoutConstraint [] constraints = imageView.Constraints; foreach (var constraint in constraints) { if (constraint.FirstAttribute == NSLayoutAttribute.Height) @@ -377,7 +375,7 @@ partial void Share (NSObject sender) // State Restoration [Export ("objectWithRestorationIdentifierPath:coder:")] - public static UIStateRestoring GetStateRestorationObjectFromPath (string[] identifierComponents, NSCoder coder) + public static UIStateRestoring GetStateRestorationObjectFromPath (string [] identifierComponents, NSCoder coder) { var key = identifierComponents [identifierComponents.Length - 1]; return CreateFilter (key, false); @@ -387,7 +385,7 @@ public override void EncodeRestorableState (NSCoder coder) { base.EncodeRestorableState (coder); - coder.Encode ((NSString)ImageIdentifier, imageIdentifierKey); + coder.Encode ((NSString) ImageIdentifier, imageIdentifierKey); coder.Encode (DataSource, dataSourceKey); TryEncodeFilters (coder); TryEncodeBarsVisibility (coder); @@ -415,8 +413,8 @@ public override void DecodeRestorableState (NSCoder coder) { base.DecodeRestorableState (coder); - ImageIdentifier = (NSString)coder.DecodeObject (imageIdentifierKey); - DataSource = (DataSource)coder.DecodeObject (dataSourceKey); + ImageIdentifier = (NSString) coder.DecodeObject (imageIdentifierKey); + DataSource = (DataSource) coder.DecodeObject (dataSourceKey); TryDecodeFilters (coder); TryDecodeBarsVisibility (coder); } @@ -426,17 +424,17 @@ void TryDecodeFilters (NSCoder coder) if (!coder.ContainsKey (imageFiltersKey)) return; - var filtersNS = (NSMutableDictionary)coder.DecodeObject (imageFiltersKey); + var filtersNS = (NSMutableDictionary) coder.DecodeObject (imageFiltersKey); if (filtersNS == null) return; filters = new Dictionary<string, ImageFilter> (); - var blurFilter = (ImageFilter)filtersNS [blurFilterKey]; + var blurFilter = (ImageFilter) filtersNS [blurFilterKey]; if (blurFilter != null) filters [blurFilterKey] = blurFilter; - var modifyFilter = (ImageFilter)filtersNS [modifyFilterKey]; + var modifyFilter = (ImageFilter) filtersNS [modifyFilterKey]; if (modifyFilter != null) filters [modifyFilterKey] = modifyFilter; } @@ -454,4 +452,4 @@ public override void ApplicationFinishedRestoringState () UpdateImage (); } } -} \ No newline at end of file +} diff --git a/StateRestoration/StateRestoration/FilterViewController.cs b/StateRestoration/StateRestoration/FilterViewController.cs index 6d4958662..030ba292e 100644 --- a/StateRestoration/StateRestoration/FilterViewController.cs +++ b/StateRestoration/StateRestoration/FilterViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace StateRestoration -{ - public partial class FilterViewController : UIViewController - { +namespace StateRestoration { + public partial class FilterViewController : UIViewController { public ImageFilter filter; public FilterViewController (IntPtr handle) diff --git a/StateRestoration/StateRestoration/Filters/BlurFilter.cs b/StateRestoration/StateRestoration/Filters/BlurFilter.cs index 95c5b9eea..1b61ac0c2 100644 --- a/StateRestoration/StateRestoration/Filters/BlurFilter.cs +++ b/StateRestoration/StateRestoration/Filters/BlurFilter.cs @@ -1,10 +1,8 @@ using System; using Foundation; -namespace StateRestoration -{ - public class BlurFilter : ImageFilter - { +namespace StateRestoration { + public class BlurFilter : ImageFilter { const string BlurRadiusKey = "kImageFilterBlurRadiusKey"; public float BlurRadius { diff --git a/StateRestoration/StateRestoration/Filters/ImageFilter.cs b/StateRestoration/StateRestoration/Filters/ImageFilter.cs index 3ecd187b7..27ed9cfcd 100644 --- a/StateRestoration/StateRestoration/Filters/ImageFilter.cs +++ b/StateRestoration/StateRestoration/Filters/ImageFilter.cs @@ -4,10 +4,8 @@ using UIKit; using ObjCRuntime; -namespace StateRestoration -{ - public class ImageFilter : UIStateRestoring - { +namespace StateRestoration { + public class ImageFilter : UIStateRestoring { const string ActiveKey = "kImageFilterActiveKey"; public bool Active { get; set; } diff --git a/StateRestoration/StateRestoration/Filters/ModifyFilter.cs b/StateRestoration/StateRestoration/Filters/ModifyFilter.cs index 14cbb1163..d635b5af5 100644 --- a/StateRestoration/StateRestoration/Filters/ModifyFilter.cs +++ b/StateRestoration/StateRestoration/Filters/ModifyFilter.cs @@ -1,10 +1,8 @@ using System; using Foundation; -namespace StateRestoration -{ - public class ModifyFilter : ImageFilter - { +namespace StateRestoration { + public class ModifyFilter : ImageFilter { const string IntensityKey = "kImageFilterIntensityKey"; public float Intensity { diff --git a/StateRestoration/StateRestoration/Main.cs b/StateRestoration/StateRestoration/Main.cs index 2659ec73f..63011edb3 100644 --- a/StateRestoration/StateRestoration/Main.cs +++ b/StateRestoration/StateRestoration/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace StateRestoration -{ - public class Application - { +namespace StateRestoration { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/StateRestoration/StateRestoration/Utils.cs b/StateRestoration/StateRestoration/Utils.cs index 68bf9b897..84b9009d4 100644 --- a/StateRestoration/StateRestoration/Utils.cs +++ b/StateRestoration/StateRestoration/Utils.cs @@ -1,10 +1,8 @@ using System; using UIKit; -namespace StateRestoration -{ - public static class Utils - { +namespace StateRestoration { + public static class Utils { // TODO: https://trello.com/c/VURKbJ2M public static bool IsLandscape (this UIInterfaceOrientation orientation) { diff --git a/StoreKit/Consumables/AppDelegate.cs b/StoreKit/Consumables/AppDelegate.cs index 4252e088b..adb9c2406 100644 --- a/StoreKit/Consumables/AppDelegate.cs +++ b/StoreKit/Consumables/AppDelegate.cs @@ -7,7 +7,7 @@ namespace Consumables { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. @@ -26,9 +26,9 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); - viewController = new ConsumableViewController(); + viewController = new ConsumableViewController (); - navigationController = new UINavigationController(); + navigationController = new UINavigationController (); navigationController.PushViewController (viewController, false); // If you have defined a view, add it here: diff --git a/StoreKit/Consumables/ConsumableViewController.cs b/StoreKit/Consumables/ConsumableViewController.cs index c45021866..0b47c462a 100644 --- a/StoreKit/Consumables/ConsumableViewController.cs +++ b/StoreKit/Consumables/ConsumableViewController.cs @@ -8,10 +8,8 @@ using SharedCode; -namespace Consumables -{ - public class ConsumableViewController : UIViewController - { +namespace Consumables { + public class ConsumableViewController : UIViewController { public static string Buy5ProductId = "com.xamarin.storekit.testing.consume5credits"; public static string Buy10ProductId = "com.xamarin.storekit.testing.consume10credits"; @@ -30,33 +28,33 @@ public class ConsumableViewController : UIViewController /// String.Format(Buy, "price"); // "Buy {0}" /// </summary> string Buy { - get {return Foundation.NSBundle.MainBundle.LocalizedString ("Buy {0}", "Buy {0}");} + get { return Foundation.NSBundle.MainBundle.LocalizedString ("Buy {0}", "Buy {0}"); } } /// <summary> /// String.Format(Balance, "balance"); // "{0} monkey credits" /// </summary> string Balance { - get {return Foundation.NSBundle.MainBundle.LocalizedString ("{0} monkey credits", "{0} monkey credits");} + get { return Foundation.NSBundle.MainBundle.LocalizedString ("{0} monkey credits", "{0} monkey credits"); } } /// <summary> /// No placeholders /// </summary> string Footer { - get {return Foundation.NSBundle.MainBundle.LocalizedString ("Notice how you can keep buying the same items over and over. That's what makes these products 'consumable'.", "Notice how you can keep buying the same items over and over. That's what makes these products 'consumable'.");} + get { return Foundation.NSBundle.MainBundle.LocalizedString ("Notice how you can keep buying the same items over and over. That's what makes these products 'consumable'.", "Notice how you can keep buying the same items over and over. That's what makes these products 'consumable'."); } } #endregion public ConsumableViewController () { // two products for sale on this page - products = new List<string>() { Buy5ProductId, Buy10ProductId }; + products = new List<string> () { Buy5ProductId, Buy10ProductId }; - iap = new InAppPurchaseManager(); - theObserver = new CustomPaymentObserver(iap); + iap = new InAppPurchaseManager (); + theObserver = new CustomPaymentObserver (iap); // Call this once upon startup of in-app-purchase activities // This also kicks off the TransactionObserver which handles the various communications - SKPaymentQueue.DefaultQueue.AddTransactionObserver(theObserver); + SKPaymentQueue.DefaultQueue.AddTransactionObserver (theObserver); } public override void ViewDidLoad () @@ -71,30 +69,30 @@ public override void ViewDidLoad () buy5Button = UIButton.FromType (UIButtonType.RoundedRect); buy5Button.SetTitle ("loading...", UIControlState.Disabled); - buy5Button.SetTitleColor(UIColor.Gray, UIControlState.Disabled); + buy5Button.SetTitleColor (UIColor.Gray, UIControlState.Disabled); buy5Button.SetTitle ("Buy...", UIControlState.Normal); buy5Button.Enabled = false; buy10Button = UIButton.FromType (UIButtonType.RoundedRect); buy10Button.SetTitle ("loading...", UIControlState.Disabled); - buy10Button.SetTitleColor(UIColor.Gray, UIControlState.Disabled); + buy10Button.SetTitleColor (UIColor.Gray, UIControlState.Disabled); buy10Button.SetTitle ("Buy...", UIControlState.Normal); buy10Button.Enabled = false; - buy5Title = new UILabel(new CGRect(10, 10, 300, 30)); - buy5Title.Font = UIFont.BoldSystemFontOfSize(18f); - buy5Description = new UILabel(new CGRect(10, 40, 300, 30)); - buy5Button.Frame = new CGRect(10, 80, 200, 40); + buy5Title = new UILabel (new CGRect (10, 10, 300, 30)); + buy5Title.Font = UIFont.BoldSystemFontOfSize (18f); + buy5Description = new UILabel (new CGRect (10, 40, 300, 30)); + buy5Button.Frame = new CGRect (10, 80, 200, 40); - buy10Title = new UILabel(new CGRect(10, 140, 300, 30)); - buy10Title.Font = UIFont.BoldSystemFontOfSize(18f); - buy10Description = new UILabel(new CGRect(10, 170, 300, 30)); - buy10Button.Frame = new CGRect(10, 210, 200, 40); + buy10Title = new UILabel (new CGRect (10, 140, 300, 30)); + buy10Title.Font = UIFont.BoldSystemFontOfSize (18f); + buy10Description = new UILabel (new CGRect (10, 170, 300, 30)); + buy10Button.Frame = new CGRect (10, 210, 200, 40); - balanceLabel = new UILabel(new CGRect(10, 280, 300, 40)); - balanceLabel.Font = UIFont.BoldSystemFontOfSize(24f); + balanceLabel = new UILabel (new CGRect (10, 280, 300, 40)); + balanceLabel.Font = UIFont.BoldSystemFontOfSize (24f); - infoLabel = new UILabel(new CGRect(10, 340, 300, 80)); + infoLabel = new UILabel (new CGRect (10, 340, 300, 80)); infoLabel.Lines = 3; infoLabel.Text = Footer; @@ -114,7 +112,7 @@ public override void ViewDidLoad () public override void ViewWillAppear (bool animated) { - base.ViewWillAppear(animated); + base.ViewWillAppear (animated); // setup the observer to wait for prices to come back from StoreKit <- AppStore priceObserver = NSNotificationCenter.DefaultCenter.AddObserver (InAppPurchaseManager.InAppPurchaseManagerProductsFetchedNotification, @@ -128,7 +126,7 @@ public override void ViewWillAppear (bool animated) if (info.ContainsKey (NSBuy5ProductId)) { pricesLoaded = true; - var product = (SKProduct)info [NSBuy5ProductId]; + var product = (SKProduct) info [NSBuy5ProductId]; Print (product); SetVisualState (buy5Button, buy5Title, buy5Description, product); } @@ -137,28 +135,28 @@ public override void ViewWillAppear (bool animated) if (info.ContainsKey (NSBuy10ProductId)) { pricesLoaded = true; - var product = (SKProduct)info [NSBuy10ProductId]; + var product = (SKProduct) info [NSBuy10ProductId]; Print (product); SetVisualState (buy10Button, buy10Title, buy10Description, product); } }); // only if we can make payments, request the prices - if (iap.CanMakePayments()) { + if (iap.CanMakePayments ()) { // now go get prices, if we don't have them already if (!pricesLoaded) - iap.RequestProductData(products); // async request via StoreKit -> App Store + iap.RequestProductData (products); // async request via StoreKit -> App Store } else { // can't make payments (purchases turned off in Settings?) buy5Button.SetTitle ("AppStore disabled", UIControlState.Disabled); buy10Button.SetTitle ("AppStore disabled", UIControlState.Disabled); } - balanceLabel.Text = String.Format (Balance, CreditManager.Balance());// + " monkey credits"; + balanceLabel.Text = String.Format (Balance, CreditManager.Balance ());// + " monkey credits"; succeededObserver = NSNotificationCenter.DefaultCenter.AddObserver (InAppPurchaseManager.InAppPurchaseManagerTransactionSucceededNotification, (notification) => { - balanceLabel.Text = String.Format (Balance, CreditManager.Balance());// + " monkey credits"; + balanceLabel.Text = String.Format (Balance, CreditManager.Balance ());// + " monkey credits"; }); failedObserver = NSNotificationCenter.DefaultCenter.AddObserver (InAppPurchaseManager.InAppPurchaseManagerTransactionFailedNotification, (notification) => { @@ -167,12 +165,12 @@ public override void ViewWillAppear (bool animated) }); requestObserver = NSNotificationCenter.DefaultCenter.AddObserver (InAppPurchaseManager.InAppPurchaseManagerRequestFailedNotification, - (notification) => { - // TODO: - Console.WriteLine ("Request Failed"); - buy5Button.SetTitle ("Network down?", UIControlState.Disabled); - buy10Button.SetTitle ("Network down?", UIControlState.Disabled); - }); + (notification) => { + // TODO: + Console.WriteLine ("Request Failed"); + buy5Button.SetTitle ("Network down?", UIControlState.Disabled); + buy10Button.SetTitle ("Network down?", UIControlState.Disabled); + }); } public override void ViewWillDisappear (bool animated) @@ -186,19 +184,19 @@ public override void ViewWillDisappear (bool animated) base.ViewWillDisappear (animated); } - void Print(SKProduct product) + void Print (SKProduct product) { - Console.WriteLine("Product id: {0}", product.ProductIdentifier); - Console.WriteLine("Product title: {0}", product.LocalizedTitle); - Console.WriteLine("Product description: {0}", product.LocalizedDescription); - Console.WriteLine("Product price: {0}", product.Price); - Console.WriteLine("Product l10n price: {0}", product.LocalizedPrice()); + Console.WriteLine ("Product id: {0}", product.ProductIdentifier); + Console.WriteLine ("Product title: {0}", product.LocalizedTitle); + Console.WriteLine ("Product description: {0}", product.LocalizedDescription); + Console.WriteLine ("Product price: {0}", product.Price); + Console.WriteLine ("Product l10n price: {0}", product.LocalizedPrice ()); } - void SetVisualState(UIButton buyBtn, UILabel title, UILabel description, SKProduct product) + void SetVisualState (UIButton buyBtn, UILabel title, UILabel description, SKProduct product) { buyBtn.Enabled = true; - buyBtn.SetTitle(String.Format (Buy, product.LocalizedPrice()), UIControlState.Normal); + buyBtn.SetTitle (String.Format (Buy, product.LocalizedPrice ()), UIControlState.Normal); title.Text = product.LocalizedTitle; description.Text = product.LocalizedDescription; diff --git a/StoreKit/Consumables/CreditManager.cs b/StoreKit/Consumables/CreditManager.cs index c6001f489..85d4b82f7 100644 --- a/StoreKit/Consumables/CreditManager.cs +++ b/StoreKit/Consumables/CreditManager.cs @@ -13,26 +13,29 @@ namespace Consumables { // Basically, this is ONLY intended as a demo of the StoreKit code, // NOT how you should build a credits system for iOS. public static class CreditManager { - static NSString defaultKey = new NSString("monkeyDollarsBalance"); + static NSString defaultKey = new NSString ("monkeyDollarsBalance"); static nint monkeyCredits = 0; static CreditManager () { - monkeyCredits = NSUserDefaults.StandardUserDefaults.IntForKey(defaultKey); + monkeyCredits = NSUserDefaults.StandardUserDefaults.IntForKey (defaultKey); } - public static int Balance() { + public static int Balance () + { NSUserDefaults.StandardUserDefaults.Synchronize (); - return (int)NSUserDefaults.StandardUserDefaults.IntForKey(defaultKey); + return (int) NSUserDefaults.StandardUserDefaults.IntForKey (defaultKey); } - public static void Add (int moreDollars) { + public static void Add (int moreDollars) + { monkeyCredits += moreDollars; - NSUserDefaults.StandardUserDefaults.SetInt(monkeyCredits, defaultKey); + NSUserDefaults.StandardUserDefaults.SetInt (monkeyCredits, defaultKey); NSUserDefaults.StandardUserDefaults.Synchronize (); } - public static bool Spend (int lessDollars) { + public static bool Spend (int lessDollars) + { if (monkeyCredits >= lessDollars) { monkeyCredits -= lessDollars; - NSUserDefaults.StandardUserDefaults.SetInt(monkeyCredits, defaultKey); + NSUserDefaults.StandardUserDefaults.SetInt (monkeyCredits, defaultKey); NSUserDefaults.StandardUserDefaults.Synchronize (); return true; } else { diff --git a/StoreKit/Consumables/CustomPaymentObserver.cs b/StoreKit/Consumables/CustomPaymentObserver.cs index b60d797f2..f7b952b60 100644 --- a/StoreKit/Consumables/CustomPaymentObserver.cs +++ b/StoreKit/Consumables/CustomPaymentObserver.cs @@ -8,38 +8,36 @@ namespace Consumables { internal class CustomPaymentObserver : SKPaymentTransactionObserver { private InAppPurchaseManager theManager; - public CustomPaymentObserver(InAppPurchaseManager manager) + public CustomPaymentObserver (InAppPurchaseManager manager) { theManager = manager; } // called when the transaction status is updated - public override void UpdatedTransactions (SKPaymentQueue queue, SKPaymentTransaction[] transactions) + public override void UpdatedTransactions (SKPaymentQueue queue, SKPaymentTransaction [] transactions) { Console.WriteLine ("UpdatedTransactions"); - foreach (SKPaymentTransaction transaction in transactions) - { - switch (transaction.TransactionState) - { - case SKPaymentTransactionState.Purchased: - theManager.CompleteTransaction(transaction); - break; - case SKPaymentTransactionState.Failed: - theManager.FailedTransaction(transaction); - break; -// Consumable products do not get Restored, so this is not implemented in this sample. -// case SKPaymentTransactionState.Restored: -// theManager.RestoreTransaction(transaction); -// break; - default: - break; - } + foreach (SKPaymentTransaction transaction in transactions) { + switch (transaction.TransactionState) { + case SKPaymentTransactionState.Purchased: + theManager.CompleteTransaction (transaction); + break; + case SKPaymentTransactionState.Failed: + theManager.FailedTransaction (transaction); + break; + // Consumable products do not get Restored, so this is not implemented in this sample. + // case SKPaymentTransactionState.Restored: + // theManager.RestoreTransaction(transaction); + // break; + default: + break; + } } } - public override void PaymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue queue) + public override void PaymentQueueRestoreCompletedTransactionsFinished (SKPaymentQueue queue) { - throw new NotImplementedException("Consumable product purchases do not get Restored, so this is not implemented in this sample."); + throw new NotImplementedException ("Consumable product purchases do not get Restored, so this is not implemented in this sample."); } } } diff --git a/StoreKit/Consumables/InAppPurchaseManager.cs b/StoreKit/Consumables/InAppPurchaseManager.cs index 4591eafb8..dbfdd761a 100644 --- a/StoreKit/Consumables/InAppPurchaseManager.cs +++ b/StoreKit/Consumables/InAppPurchaseManager.cs @@ -8,16 +8,14 @@ using SharedCode; -namespace Consumables -{ - public class InAppPurchaseManager : PurchaseManager - { +namespace Consumables { + public class InAppPurchaseManager : PurchaseManager { protected override void CompleteTransaction (string productId) { if (productId == ConsumableViewController.Buy5ProductId) - CreditManager.Add(5); // 5 * qty + CreditManager.Add (5); // 5 * qty else if (productId == ConsumableViewController.Buy10ProductId) - CreditManager.Add(10); // 10 * qty + CreditManager.Add (10); // 10 * qty else Console.WriteLine ("Shouldn't happen, there are only two products"); } diff --git a/StoreKit/HostedNonConsumables/AppDelegate.cs b/StoreKit/HostedNonConsumables/AppDelegate.cs index adf872376..e8ae86bb9 100644 --- a/StoreKit/HostedNonConsumables/AppDelegate.cs +++ b/StoreKit/HostedNonConsumables/AppDelegate.cs @@ -7,7 +7,7 @@ namespace NonConsumables { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. @@ -26,9 +26,9 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); - viewController = new HostedProductsViewController(); + viewController = new HostedProductsViewController (); - navigationController = new UINavigationController(); + navigationController = new UINavigationController (); navigationController.PushViewController (viewController, false); window.RootViewController = navigationController; diff --git a/StoreKit/HostedNonConsumables/CustomPaymentObserver.cs b/StoreKit/HostedNonConsumables/CustomPaymentObserver.cs index 3a7538bc1..bdb8f0dc1 100644 --- a/StoreKit/HostedNonConsumables/CustomPaymentObserver.cs +++ b/StoreKit/HostedNonConsumables/CustomPaymentObserver.cs @@ -8,7 +8,7 @@ namespace NonConsumables { internal class CustomPaymentObserver : SKPaymentTransactionObserver { private InAppPurchaseManager theManager; - public CustomPaymentObserver(InAppPurchaseManager manager) + public CustomPaymentObserver (InAppPurchaseManager manager) { theManager = manager; } @@ -16,7 +16,7 @@ public CustomPaymentObserver(InAppPurchaseManager manager) /// <Docs> /// New iOS 6 method to track downloads of hosted-content /// </Docs> - public override void UpdatedDownloads (SKPaymentQueue queue, SKDownload[] downloads) + public override void UpdatedDownloads (SKPaymentQueue queue, SKDownload [] downloads) { Console.WriteLine (" -- PaymentQueueUpdatedDownloads"); foreach (SKDownload download in downloads) { @@ -51,41 +51,41 @@ public override void UpdatedDownloads (SKPaymentQueue queue, SKDownload[] downlo /// <summary> /// Called when the transaction status is updated /// </summary> - public override void UpdatedTransactions (SKPaymentQueue queue, SKPaymentTransaction[] transactions) + public override void UpdatedTransactions (SKPaymentQueue queue, SKPaymentTransaction [] transactions) { Console.WriteLine ("UpdatedTransactions"); foreach (SKPaymentTransaction transaction in transactions) { - switch (transaction.TransactionState) { - case SKPaymentTransactionState.Purchased: - if (transaction.Downloads != null && transaction.Downloads.Length > 0) { - // complete the transaction AFTER downloading - SKPaymentQueue.DefaultQueue.StartDownloads (transaction.Downloads); - } else { - // complete the transaction now - theManager.CompleteTransaction(transaction); - } - break; - case SKPaymentTransactionState.Failed: - theManager.FailedTransaction(transaction); - break; - case SKPaymentTransactionState.Restored: - theManager.RestoreTransaction(transaction); - break; - default: - break; - } + switch (transaction.TransactionState) { + case SKPaymentTransactionState.Purchased: + if (transaction.Downloads != null && transaction.Downloads.Length > 0) { + // complete the transaction AFTER downloading + SKPaymentQueue.DefaultQueue.StartDownloads (transaction.Downloads); + } else { + // complete the transaction now + theManager.CompleteTransaction (transaction); + } + break; + case SKPaymentTransactionState.Failed: + theManager.FailedTransaction (transaction); + break; + case SKPaymentTransactionState.Restored: + theManager.RestoreTransaction (transaction); + break; + default: + break; + } } } public override void PaymentQueueRestoreCompletedTransactionsFinished (SKPaymentQueue queue) { // Restore succeeded - Console.WriteLine(" ** RESTORE PaymentQueueRestoreCompletedTransactionsFinished "); + Console.WriteLine (" ** RESTORE PaymentQueueRestoreCompletedTransactionsFinished "); } public override void RestoreCompletedTransactionsFailedWithError (SKPaymentQueue queue, NSError error) { // Restore failed somewhere... - Console.WriteLine(" ** RESTORE RestoreCompletedTransactionsFailedWithError " + error.LocalizedDescription); + Console.WriteLine (" ** RESTORE RestoreCompletedTransactionsFailedWithError " + error.LocalizedDescription); } } } diff --git a/StoreKit/HostedNonConsumables/HostedProductManager.cs b/StoreKit/HostedNonConsumables/HostedProductManager.cs index 6e064699c..c96c217ec 100644 --- a/StoreKit/HostedNonConsumables/HostedProductManager.cs +++ b/StoreKit/HostedNonConsumables/HostedProductManager.cs @@ -23,13 +23,15 @@ static HostedProductManager () /// effectively bypassing the payment mechanism (assuming a little bit /// of technical knowledge). /// </remarks> - public static void Purchase (string productId) { - var key = new NSString(productId); - NSUserDefaults.StandardUserDefaults.SetBool(true, key); + public static void Purchase (string productId) + { + var key = new NSString (productId); + NSUserDefaults.StandardUserDefaults.SetBool (true, key); NSUserDefaults.StandardUserDefaults.Synchronize (); } - public static bool HasPurchased (string productId) { - var key = new NSString(productId); + public static bool HasPurchased (string productId) + { + var key = new NSString (productId); return NSUserDefaults.StandardUserDefaults.BoolForKey (key); } @@ -51,10 +53,10 @@ public static void Read (string productId, UITextView view, UIImageView icon) // ... other hosted products that can be added later var textFile = System.IO.Path.Combine (targetfolder, "Chapter.txt"); - view.Text = System.IO.File.ReadAllText(textFile); + view.Text = System.IO.File.ReadAllText (textFile); var iconFile = System.IO.Path.Combine (targetfolder, "icon.png"); - icon.Image = UIImage.FromFile(iconFile); + icon.Image = UIImage.FromFile (iconFile); } } } diff --git a/StoreKit/HostedNonConsumables/HostedProductsViewController.cs b/StoreKit/HostedNonConsumables/HostedProductsViewController.cs index 7dd8faf30..1d5fe2e73 100644 --- a/StoreKit/HostedNonConsumables/HostedProductsViewController.cs +++ b/StoreKit/HostedNonConsumables/HostedProductsViewController.cs @@ -14,10 +14,8 @@ NOTE: Store Kit can be tested in the iOS Simulator, except for hosted content downloads. */ -namespace NonConsumables -{ - public class HostedProductsViewController : UIViewController - { +namespace NonConsumables { + public class HostedProductsViewController : UIViewController { public static string hostedImagesProductId = "com.xamarin.storekit.hosted.monotouchimages"; //"com.xamarin.storekitdoc.monotouchimages", public static string hostedFilesystemProductId = "com.xamarin.storekit.hosted.monotouchfilesystem"; //"com.xamarin.storekitdoc.monotouchfilesystem"; @@ -36,13 +34,13 @@ public class HostedProductsViewController : UIViewController public HostedProductsViewController () { // two products for sale on this page - products = new List<string>() {hostedImagesProductId, hostedFilesystemProductId}; - iap = new InAppPurchaseManager(); - theObserver = new CustomPaymentObserver(iap); + products = new List<string> () { hostedImagesProductId, hostedFilesystemProductId }; + iap = new InAppPurchaseManager (); + theObserver = new CustomPaymentObserver (iap); // Call this once upon startup of in-app-purchase activities // This also kicks off the TransactionObserver which handles the various communications - SKPaymentQueue.DefaultQueue.AddTransactionObserver(theObserver); + SKPaymentQueue.DefaultQueue.AddTransactionObserver (theObserver); } public override void ViewDidLoad () @@ -55,35 +53,35 @@ public override void ViewDidLoad () hostedImagesButton = UIButton.FromType (UIButtonType.RoundedRect); hostedImagesButton.SetTitle ("loading...", UIControlState.Disabled); - hostedImagesButton.SetTitleColor(UIColor.Gray, UIControlState.Disabled); + hostedImagesButton.SetTitleColor (UIColor.Gray, UIControlState.Disabled); hostedImagesButton.SetTitle ("Buy...", UIControlState.Normal); hostedImagesButton.Enabled = false; hostedFilesystemButton = UIButton.FromType (UIButtonType.RoundedRect); hostedFilesystemButton.SetTitle ("loading...", UIControlState.Disabled); - hostedFilesystemButton.SetTitleColor(UIColor.Gray, UIControlState.Disabled); + hostedFilesystemButton.SetTitleColor (UIColor.Gray, UIControlState.Disabled); hostedFilesystemButton.SetTitle ("Buy...", UIControlState.Normal); hostedFilesystemButton.Enabled = false; - hostedImagesTitle = new UILabel(new CGRect(10, 5, 300, 30)); - hostedImagesTitle.Font = UIFont.BoldSystemFontOfSize(18f); - hostedImagesDescription = new UILabel(new CGRect(10, 30, 300, 30)); - hostedImagesButton.Frame = new CGRect(10, 65, 180, 40); + hostedImagesTitle = new UILabel (new CGRect (10, 5, 300, 30)); + hostedImagesTitle.Font = UIFont.BoldSystemFontOfSize (18f); + hostedImagesDescription = new UILabel (new CGRect (10, 30, 300, 30)); + hostedImagesButton.Frame = new CGRect (10, 65, 180, 40); - hostedFilesystemTitle = new UILabel(new CGRect(10, 110, 300, 30)); - hostedFilesystemTitle.Font = UIFont.BoldSystemFontOfSize(18f); - hostedFilesystemDescription = new UILabel(new CGRect(10, 135, 300, 30)); - hostedFilesystemButton.Frame = new CGRect(10, 170, 180, 40); + hostedFilesystemTitle = new UILabel (new CGRect (10, 110, 300, 30)); + hostedFilesystemTitle.Font = UIFont.BoldSystemFontOfSize (18f); + hostedFilesystemDescription = new UILabel (new CGRect (10, 135, 300, 30)); + hostedFilesystemButton.Frame = new CGRect (10, 170, 180, 40); restoreButton = UIButton.FromType (UIButtonType.RoundedRect); restoreButton.SetTitle ("Restore", UIControlState.Normal); - restoreButton.Frame = new CGRect(200, 170, 110, 40); + restoreButton.Frame = new CGRect (200, 170, 110, 40); - bookTextDisplay = new UITextView(new CGRect(10, 215, 300, 200)); + bookTextDisplay = new UITextView (new CGRect (10, 215, 300, 200)); bookTextDisplay.Text = ""; bookTextDisplay.ScrollEnabled = true; bookTextDisplay.Editable = false; - bookIcon = new UIImageView(new CGRect(240, 210, 60, 60)); + bookIcon = new UIImageView (new CGRect (240, 210, 60, 60)); View.AddSubview (hostedImagesButton); View.AddSubview (hostedImagesTitle); @@ -115,13 +113,13 @@ public override void ViewDidLoad () } }; restoreButton.TouchUpInside += (sender, e) => { - iap.Restore(); + iap.Restore (); }; } public override void ViewWillAppear (bool animated) { - base.ViewWillAppear(animated); + base.ViewWillAppear (animated); // setup the observer to wait for prices to come back from StoreKit <- AppStore priceObserver = NSNotificationCenter.DefaultCenter.AddObserver (InAppPurchaseManager.InAppPurchaseManagerProductsFetchedNotification, @@ -143,25 +141,25 @@ public override void ViewWillAppear (bool animated) if (!hostedImagesPurchased && info.ContainsKey (NSimagesProductId)) { pricesLoaded = true; - var product = (SKProduct)info [NSimagesProductId]; + var product = (SKProduct) info [NSimagesProductId]; Print (product); - SetVisualState(hostedImagesButton, hostedImagesTitle, hostedImagesDescription, product); + SetVisualState (hostedImagesButton, hostedImagesTitle, hostedImagesDescription, product); } // we only update the button with a price if the user hasn't already purchased it if (!hostedFilesystemPurchased && info.ContainsKey (NSfilesystemProductId)) { pricesLoaded = true; - var product = (SKProduct)info[NSfilesystemProductId]; + var product = (SKProduct) info [NSfilesystemProductId]; Print (product); - SetVisualState(hostedFilesystemButton, hostedFilesystemTitle, hostedFilesystemDescription, product); + SetVisualState (hostedFilesystemButton, hostedFilesystemTitle, hostedFilesystemDescription, product); } }); // only if we can make payments, request the prices - if (iap.CanMakePayments()) { + if (iap.CanMakePayments ()) { // now go get prices, if we don't have them already if (!pricesLoaded) - iap.RequestProductData(products); // async request via StoreKit -> App Store + iap.RequestProductData (products); // async request via StoreKit -> App Store } else { // can't make payments (purchases turned off in Settings?) hostedImagesButton.SetTitle ("AppStore disabled", UIControlState.Disabled); @@ -177,24 +175,25 @@ public override void ViewWillAppear (bool animated) }); requestObserver = NSNotificationCenter.DefaultCenter.AddObserver (InAppPurchaseManager.InAppPurchaseManagerRequestFailedNotification, - (notification) => { - // TODO: - Console.WriteLine ("Request Failed"); - hostedImagesButton.SetTitle ("Network down?", UIControlState.Disabled); - hostedFilesystemButton.SetTitle ("Network down?", UIControlState.Disabled); - }); + (notification) => { + // TODO: + Console.WriteLine ("Request Failed"); + hostedImagesButton.SetTitle ("Network down?", UIControlState.Disabled); + hostedFilesystemButton.SetTitle ("Network down?", UIControlState.Disabled); + }); } - void UpdateButtons () { + void UpdateButtons () + { // set whether the user already has purchased these products - if (HostedProductManager.HasPurchased(hostedImagesProductId)) { + if (HostedProductManager.HasPurchased (hostedImagesProductId)) { hostedImagesButton.Enabled = true; - hostedImagesButton.SetTitle("Read Images Chapter", UIControlState.Normal); + hostedImagesButton.SetTitle ("Read Images Chapter", UIControlState.Normal); hostedImagesPurchased = true; } - if (HostedProductManager.HasPurchased(hostedFilesystemProductId)) { + if (HostedProductManager.HasPurchased (hostedFilesystemProductId)) { hostedFilesystemButton.Enabled = true; - hostedFilesystemButton.SetTitle("Read FileSystem Chapter ", UIControlState.Normal); + hostedFilesystemButton.SetTitle ("Read FileSystem Chapter ", UIControlState.Normal); hostedFilesystemPurchased = true; } } @@ -208,20 +207,20 @@ public override void ViewWillDisappear (bool animated) base.ViewWillDisappear (animated); } - void Print(SKProduct product) + void Print (SKProduct product) { - Console.WriteLine("Product id: {0}", product.ProductIdentifier); - Console.WriteLine("Product title: {0}", product.LocalizedTitle); - Console.WriteLine("Product description: {0}", product.LocalizedDescription); - Console.WriteLine("Product price: {0}", product.Price); - Console.WriteLine("Product l10n price: {0}", product.LocalizedPrice()); - Console.WriteLine("Product downloadable: {0}", product.Downloadable); // iOS6 - Console.WriteLine("Product version: {0}", product.DownloadContentVersion); // iOS6 + Console.WriteLine ("Product id: {0}", product.ProductIdentifier); + Console.WriteLine ("Product title: {0}", product.LocalizedTitle); + Console.WriteLine ("Product description: {0}", product.LocalizedDescription); + Console.WriteLine ("Product price: {0}", product.Price); + Console.WriteLine ("Product l10n price: {0}", product.LocalizedPrice ()); + Console.WriteLine ("Product downloadable: {0}", product.Downloadable); // iOS6 + Console.WriteLine ("Product version: {0}", product.DownloadContentVersion); // iOS6 if (product.DownloadContentLengths != null) - Console.WriteLine("Product length: {0}", product.DownloadContentLengths[0]); // iOS6 + Console.WriteLine ("Product length: {0}", product.DownloadContentLengths [0]); // iOS6 } - void SetVisualState(UIButton button, UILabel title, UILabel description, SKProduct product) + void SetVisualState (UIButton button, UILabel title, UILabel description, SKProduct product) { button.Enabled = true; button.SetTitle (string.Format ("Buy {0}", product.LocalizedPrice ()), UIControlState.Normal); diff --git a/StoreKit/HostedNonConsumables/InAppPurchaseManager.cs b/StoreKit/HostedNonConsumables/InAppPurchaseManager.cs index 4a5ae60f2..95f8f440e 100644 --- a/StoreKit/HostedNonConsumables/InAppPurchaseManager.cs +++ b/StoreKit/HostedNonConsumables/InAppPurchaseManager.cs @@ -8,19 +8,17 @@ using SharedCode; -namespace NonConsumables -{ - public class InAppPurchaseManager : PurchaseManager - { +namespace NonConsumables { + public class InAppPurchaseManager : PurchaseManager { protected override void CompleteTransaction (string productId) { // Register the purchase, so it is remembered for next time - HostedProductManager.Purchase(productId); + HostedProductManager.Purchase (productId); } protected override void RestoreTransaction (string productId) { - HostedProductManager.Purchase(productId); // it's as though it was purchased again + HostedProductManager.Purchase (productId); // it's as though it was purchased again } /// <summary> @@ -38,13 +36,13 @@ public void SaveDownload (SKDownload download) System.IO.Directory.CreateDirectory (targetfolder); foreach (var file in System.IO.Directory.EnumerateFiles - (System.IO.Path.Combine(download.ContentUrl.Path,"Contents"))) { + (System.IO.Path.Combine (download.ContentUrl.Path, "Contents"))) { Console.WriteLine (" file to copy " + file); var fileName = file.Substring (file.LastIndexOf ("/") + 1); - var newFilePath = System.IO.Path.Combine(targetfolder, fileName); + var newFilePath = System.IO.Path.Combine (targetfolder, fileName); - if (!System.IO.File.Exists(newFilePath)) + if (!System.IO.File.Exists (newFilePath)) System.IO.File.Copy (file, newFilePath); else Console.WriteLine ("already exists " + newFilePath); diff --git a/StoreKit/NonConsumables/AppDelegate.cs b/StoreKit/NonConsumables/AppDelegate.cs index 8bb710d24..3b2b70fa6 100644 --- a/StoreKit/NonConsumables/AppDelegate.cs +++ b/StoreKit/NonConsumables/AppDelegate.cs @@ -7,7 +7,7 @@ namespace NonConsumables { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. @@ -26,9 +26,9 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); - viewController = new NonConsumableViewController(); + viewController = new NonConsumableViewController (); - navigationController = new UINavigationController(); + navigationController = new UINavigationController (); navigationController.PushViewController (viewController, false); // If you have defined a view, add it here: diff --git a/StoreKit/NonConsumables/CustomPaymentObserver.cs b/StoreKit/NonConsumables/CustomPaymentObserver.cs index 9f104182d..0e0001809 100644 --- a/StoreKit/NonConsumables/CustomPaymentObserver.cs +++ b/StoreKit/NonConsumables/CustomPaymentObserver.cs @@ -2,50 +2,46 @@ using StoreKit; using Foundation; -namespace NonConsumables -{ - internal class CustomPaymentObserver : SKPaymentTransactionObserver - { - private InAppPurchaseManager theManager; +namespace NonConsumables { + internal class CustomPaymentObserver : SKPaymentTransactionObserver { + private InAppPurchaseManager theManager; - public CustomPaymentObserver(InAppPurchaseManager manager) - { - theManager = manager; - } + public CustomPaymentObserver (InAppPurchaseManager manager) + { + theManager = manager; + } - // called when the transaction status is updated - public override void UpdatedTransactions(SKPaymentQueue queue, SKPaymentTransaction[] transactions) - { - Console.WriteLine("UpdatedTransactions"); - foreach (SKPaymentTransaction transaction in transactions) - { - switch (transaction.TransactionState) - { - case SKPaymentTransactionState.Purchased: - theManager.CompleteTransaction(transaction); - break; - case SKPaymentTransactionState.Failed: - theManager.FailedTransaction(transaction); - break; - case SKPaymentTransactionState.Restored: - theManager.RestoreTransaction(transaction); - break; - default: - break; - } - } - } + // called when the transaction status is updated + public override void UpdatedTransactions (SKPaymentQueue queue, SKPaymentTransaction [] transactions) + { + Console.WriteLine ("UpdatedTransactions"); + foreach (SKPaymentTransaction transaction in transactions) { + switch (transaction.TransactionState) { + case SKPaymentTransactionState.Purchased: + theManager.CompleteTransaction (transaction); + break; + case SKPaymentTransactionState.Failed: + theManager.FailedTransaction (transaction); + break; + case SKPaymentTransactionState.Restored: + theManager.RestoreTransaction (transaction); + break; + default: + break; + } + } + } - public override void PaymentQueueRestoreCompletedTransactionsFinished(SKPaymentQueue queue) - { - // Restore succeeded - Console.WriteLine(" ** RESTORE PaymentQueueRestoreCompletedTransactionsFinished "); - } + public override void PaymentQueueRestoreCompletedTransactionsFinished (SKPaymentQueue queue) + { + // Restore succeeded + Console.WriteLine (" ** RESTORE PaymentQueueRestoreCompletedTransactionsFinished "); + } - public override void RestoreCompletedTransactionsFailedWithError(SKPaymentQueue queue, NSError error) - { - // Restore failed somewhere... - Console.WriteLine(" ** RESTORE RestoreCompletedTransactionsFailedWithError " + error.LocalizedDescription); - } - } + public override void RestoreCompletedTransactionsFailedWithError (SKPaymentQueue queue, NSError error) + { + // Restore failed somewhere... + Console.WriteLine (" ** RESTORE RestoreCompletedTransactionsFailedWithError " + error.LocalizedDescription); + } + } } diff --git a/StoreKit/NonConsumables/InAppPurchaseManager.cs b/StoreKit/NonConsumables/InAppPurchaseManager.cs index 0e47799d7..51f7f4422 100644 --- a/StoreKit/NonConsumables/InAppPurchaseManager.cs +++ b/StoreKit/NonConsumables/InAppPurchaseManager.cs @@ -8,20 +8,18 @@ using SharedCode; -namespace NonConsumables -{ - public class InAppPurchaseManager : PurchaseManager - { +namespace NonConsumables { + public class InAppPurchaseManager : PurchaseManager { protected override void CompleteTransaction (string productId) { // Register the purchase, so it is remembered for next time - PhotoFilterManager.Purchase(productId); + PhotoFilterManager.Purchase (productId); } protected override void RestoreTransaction (string productId) { // it's as though it was purchased again - PhotoFilterManager.Purchase(productId); + PhotoFilterManager.Purchase (productId); } } } diff --git a/StoreKit/NonConsumables/NonConsumableViewController.cs b/StoreKit/NonConsumables/NonConsumableViewController.cs index 1548613db..4d6f09e3e 100644 --- a/StoreKit/NonConsumables/NonConsumableViewController.cs +++ b/StoreKit/NonConsumables/NonConsumableViewController.cs @@ -8,10 +8,8 @@ using SharedCode; -namespace NonConsumables -{ - public class NonConsumableViewController : UIViewController - { +namespace NonConsumables { + public class NonConsumableViewController : UIViewController { public static string greyscaleProductId = "com.xamarin.storekit.testing.greyscale"; public static string sepiaProductId = "com.xamarin.storekit.testing.sepia"; @@ -30,14 +28,14 @@ public class NonConsumableViewController : UIViewController public NonConsumableViewController () { // two products for sale on this page - products = new List<string>() {greyscaleProductId, sepiaProductId}; + products = new List<string> () { greyscaleProductId, sepiaProductId }; - iap = new InAppPurchaseManager(); - theObserver = new CustomPaymentObserver(iap); + iap = new InAppPurchaseManager (); + theObserver = new CustomPaymentObserver (iap); // Call this once upon startup of in-app-purchase activities // This also kicks off the TransactionObserver which handles the various communications - SKPaymentQueue.DefaultQueue.AddTransactionObserver(theObserver); + SKPaymentQueue.DefaultQueue.AddTransactionObserver (theObserver); } public override void ViewDidLoad () @@ -54,41 +52,41 @@ public override void ViewDidLoad () greyscaleButton = UIButton.FromType (UIButtonType.RoundedRect); greyscaleButton.SetTitle ("loading...", UIControlState.Disabled); - greyscaleButton.SetTitleColor(UIColor.Gray, UIControlState.Disabled); + greyscaleButton.SetTitleColor (UIColor.Gray, UIControlState.Disabled); greyscaleButton.SetTitle ("Buy...", UIControlState.Normal); greyscaleButton.Enabled = false; sepiaButton = UIButton.FromType (UIButtonType.RoundedRect); sepiaButton.SetTitle ("loading...", UIControlState.Disabled); - sepiaButton.SetTitleColor(UIColor.Gray, UIControlState.Disabled); + sepiaButton.SetTitleColor (UIColor.Gray, UIControlState.Disabled); sepiaButton.SetTitle ("Buy...", UIControlState.Normal); sepiaButton.Enabled = false; - greyscaleTitle = new UILabel(new CGRect(10, 5, 300, 30)); - greyscaleTitle.Font = UIFont.BoldSystemFontOfSize(18f); - greyscaleDescription = new UILabel(new CGRect(10, 30, 300, 30)); - greyscaleButton.Frame = new CGRect(10, 65, 180, 40); + greyscaleTitle = new UILabel (new CGRect (10, 5, 300, 30)); + greyscaleTitle.Font = UIFont.BoldSystemFontOfSize (18f); + greyscaleDescription = new UILabel (new CGRect (10, 30, 300, 30)); + greyscaleButton.Frame = new CGRect (10, 65, 180, 40); - sepiaTitle = new UILabel(new CGRect(10, 110, 300, 30)); - sepiaTitle.Font = UIFont.BoldSystemFontOfSize(18f); - sepiaDescription = new UILabel(new CGRect(10, 135, 300, 30)); - sepiaButton.Frame = new CGRect(10, 170, 180, 40); + sepiaTitle = new UILabel (new CGRect (10, 110, 300, 30)); + sepiaTitle.Font = UIFont.BoldSystemFontOfSize (18f); + sepiaDescription = new UILabel (new CGRect (10, 135, 300, 30)); + sepiaButton.Frame = new CGRect (10, 170, 180, 40); clearButton = UIButton.FromType (UIButtonType.RoundedRect); clearButton.SetTitle ("Clear Filter", UIControlState.Normal); - clearButton.Frame = new CGRect(10, 215, 180, 40); - clearButton.TouchUpInside += (sender, args) =>{ + clearButton.Frame = new CGRect (10, 215, 180, 40); + clearButton.TouchUpInside += (sender, args) => { testFilterImage.Image = UIImage.FromFile (testImagePath); }; restoreButton = UIButton.FromType (UIButtonType.RoundedRect); restoreButton.SetTitle ("Restore", UIControlState.Normal); - restoreButton.Frame = new CGRect(200, 215, 110, 40); + restoreButton.Frame = new CGRect (200, 215, 110, 40); - testFilterImage = new UIImageView(new CGRect(10, 265, 300, 100)); + testFilterImage = new UIImageView (new CGRect (10, 265, 300, 100)); testFilterImage.Image = UIImage.FromFile (testImagePath); - infoLabel = new UILabel(new CGRect(10, 370, 300, 80)); + infoLabel = new UILabel (new CGRect (10, 370, 300, 80)); infoLabel.Lines = 3; infoLabel.Text = "Notice how you can only purchase each product once. After that the transaction can't be charged again."; @@ -123,7 +121,7 @@ public override void ViewDidLoad () } }; restoreButton.TouchUpInside += (sender, e) => { - iap.Restore(); + iap.Restore (); }; } @@ -151,7 +149,7 @@ public override void ViewWillAppear (bool animated) if (!greyscalePurchased && info.ContainsKey (NSgreyscaleProductId)) { pricesLoaded = true; - var product = (SKProduct)info [NSgreyscaleProductId]; + var product = (SKProduct) info [NSgreyscaleProductId]; Print (product); SetVisualState (greyscaleButton, greyscaleTitle, greyscaleDescription, product); } @@ -159,7 +157,7 @@ public override void ViewWillAppear (bool animated) if (!sepiaPurchased && info.ContainsKey (NSsepiaProductId)) { pricesLoaded = true; - var product = (SKProduct)info.ObjectForKey (NSsepiaProductId); + var product = (SKProduct) info.ObjectForKey (NSsepiaProductId); Print (product); SetVisualState (sepiaButton, sepiaTitle, sepiaDescription, product); } @@ -193,16 +191,17 @@ public override void ViewWillAppear (bool animated) }); } - void UpdateButtons () { + void UpdateButtons () + { // set whether the user already has purchased these products - if (PhotoFilterManager.HasPurchased(greyscaleProductId)) { + if (PhotoFilterManager.HasPurchased (greyscaleProductId)) { greyscaleButton.Enabled = true; - greyscaleButton.SetTitle("Use Greyscale Filter", UIControlState.Normal); + greyscaleButton.SetTitle ("Use Greyscale Filter", UIControlState.Normal); greyscalePurchased = true; } - if (PhotoFilterManager.HasPurchased(sepiaProductId)) { + if (PhotoFilterManager.HasPurchased (sepiaProductId)) { sepiaButton.Enabled = true; - sepiaButton.SetTitle("Use Sepia Filter ", UIControlState.Normal); + sepiaButton.SetTitle ("Use Sepia Filter ", UIControlState.Normal); sepiaPurchased = true; } } @@ -216,16 +215,16 @@ public override void ViewWillDisappear (bool animated) base.ViewWillDisappear (animated); } - void Print(SKProduct product) + void Print (SKProduct product) { - Console.WriteLine("Product id: {0}", product.ProductIdentifier); - Console.WriteLine("Product title: {0}", product.LocalizedTitle); - Console.WriteLine("Product description: {0}", product.LocalizedDescription); - Console.WriteLine("Product price: {0}", product.Price); - Console.WriteLine("Product l10n price: {0}", product.LocalizedPrice()); + Console.WriteLine ("Product id: {0}", product.ProductIdentifier); + Console.WriteLine ("Product title: {0}", product.LocalizedTitle); + Console.WriteLine ("Product description: {0}", product.LocalizedDescription); + Console.WriteLine ("Product price: {0}", product.Price); + Console.WriteLine ("Product l10n price: {0}", product.LocalizedPrice ()); } - void SetVisualState(UIButton button, UILabel title, UILabel description, SKProduct product) + void SetVisualState (UIButton button, UILabel title, UILabel description, SKProduct product) { var btnTitle = string.Format ("Buy {0}", product.LocalizedPrice ()); button.Enabled = true; diff --git a/StoreKit/NonConsumables/PhotoFilterManager.cs b/StoreKit/NonConsumables/PhotoFilterManager.cs index f11de6ebf..779b01d08 100644 --- a/StoreKit/NonConsumables/PhotoFilterManager.cs +++ b/StoreKit/NonConsumables/PhotoFilterManager.cs @@ -23,13 +23,15 @@ static PhotoFilterManager () /// effectively bypassing the payment mechanism (assuming a little bit /// of technical knowledge). /// </remarks> - public static void Purchase (string productId) { - var key = new NSString(productId); - NSUserDefaults.StandardUserDefaults.SetBool(true, key); + public static void Purchase (string productId) + { + var key = new NSString (productId); + NSUserDefaults.StandardUserDefaults.SetBool (true, key); NSUserDefaults.StandardUserDefaults.Synchronize (); } - public static bool HasPurchased (string productId) { - var key = new NSString(productId); + public static bool HasPurchased (string productId) + { + var key = new NSString (productId); return NSUserDefaults.StandardUserDefaults.BoolForKey (key); } @@ -37,17 +39,17 @@ public static bool HasPurchased (string productId) { /// Purchaseable feature. This function can't be called until the /// user has purchased the Sepia Filter in-app product. /// </summary> - public static void ApplySepia(string imagePath, UIImageView imgview) + public static void ApplySepia (string imagePath, UIImageView imgview) { var uiimage = UIImage.FromFile (imagePath); var ciimage = new CIImage (uiimage); - var sepia = new CISepiaTone(); + var sepia = new CISepiaTone (); sepia.Image = ciimage; sepia.Intensity = 0.8f; var output = sepia.OutputImage; - var context = CIContext.FromOptions(null); + var context = CIContext.FromOptions (null); var cgimage = context.CreateCGImage (output, output.Extent); var ui = UIImage.FromImage (cgimage); @@ -57,17 +59,17 @@ public static void ApplySepia(string imagePath, UIImageView imgview) /// Purchaseable feature. This function can't be called until the /// user has purchased the Greyscale Filter in-app product. /// </summary> - public static void ApplyGreyscale(string imagePath, UIImageView imgview) + public static void ApplyGreyscale (string imagePath, UIImageView imgview) { var uiimage = UIImage.FromFile (imagePath); var ciimage = new CIImage (uiimage); - var greyscale = new CIColorControls(); + var greyscale = new CIColorControls (); greyscale.Image = ciimage; greyscale.Saturation = 0f; var output = greyscale.OutputImage; - var context = CIContext.FromOptions(null); + var context = CIContext.FromOptions (null); var cgimage = context.CreateCGImage (output, output.Extent); var ui = UIImage.FromImage (cgimage); diff --git a/StoreKit/ProductView/AppDelegate.cs b/StoreKit/ProductView/AppDelegate.cs index 3ac157b6f..f599a317a 100644 --- a/StoreKit/ProductView/AppDelegate.cs +++ b/StoreKit/ProductView/AppDelegate.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace ProductView -{ - public class Application - { +namespace ProductView { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. @@ -22,8 +20,7 @@ static void Main (string[] args) // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; UINavigationController navigationController; @@ -41,9 +38,9 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) // create a new window instance based on the screen size window = new UIWindow (UIScreen.MainScreen.Bounds); - viewController = new ProductViewController(); + viewController = new ProductViewController (); - navigationController = new UINavigationController(); + navigationController = new UINavigationController (); navigationController.NavigationBar.Translucent = false; navigationController.PushViewController (viewController, false); diff --git a/StoreKit/ProductView/ProductViewController.cs b/StoreKit/ProductView/ProductViewController.cs index fcf852dbd..83a12aed9 100644 --- a/StoreKit/ProductView/ProductViewController.cs +++ b/StoreKit/ProductView/ProductViewController.cs @@ -40,7 +40,7 @@ public class ProductViewController : UIViewController { UILabel infoLabel; - public ProductViewController () : base() + public ProductViewController () : base () { } @@ -53,38 +53,38 @@ public override void ViewDidLoad () viewButton = UIButton.FromType (UIButtonType.RoundedRect); viewButton.SetTitle ("Download iBooks App", UIControlState.Normal); - viewButton.Frame = new CGRect(10, 10, 200, 40); + viewButton.Frame = new CGRect (10, 10, 200, 40); viewButton.TouchUpInside += (sender, e) => { - Buy(364709193); // iBooks + Buy (364709193); // iBooks }; Add (viewButton); view2Button = UIButton.FromType (UIButtonType.RoundedRect); view2Button.SetTitle ("Download MWC12 App", UIControlState.Normal); - view2Button.Frame = new CGRect(10, 60, 200, 40); + view2Button.Frame = new CGRect (10, 60, 200, 40); view2Button.TouchUpInside += (sender, e) => { - Buy(496963922); // MWC + Buy (496963922); // MWC }; Add (view2Button); view3Button = UIButton.FromType (UIButtonType.RoundedRect); view3Button.SetTitle ("Buy Timomatic Album", UIControlState.Normal); - view3Button.Frame = new CGRect(10, 110, 200, 40); + view3Button.Frame = new CGRect (10, 110, 200, 40); view3Button.TouchUpInside += (sender, e) => { - Buy(553243272); // timomatic + Buy (553243272); // timomatic }; Add (view3Button); view4Button = UIButton.FromType (UIButtonType.RoundedRect); view4Button.SetTitle ("Read Kangaroo Book", UIControlState.Normal); - view4Button.Frame = new CGRect(10, 160, 200, 40); + view4Button.Frame = new CGRect (10, 160, 200, 40); view4Button.TouchUpInside += (sender, e) => { - Buy(510970593); // Dot + Buy (510970593); // Dot }; Add (view4Button); #region The Old Way - infoLabel = new UILabel(new CGRect(10, 220, 300, 40)); + infoLabel = new UILabel (new CGRect (10, 220, 300, 40)); infoLabel.Text = "The Old Way (OpenUrl) exits your app"; // THE OLD WAY, OPENURL TO APPSTORE @@ -95,9 +95,9 @@ public override void ViewDidLoad () oldwayButton = UIButton.FromType (UIButtonType.RoundedRect); oldwayButton.SetTitle ("Open AppStore", UIControlState.Normal); oldwayButton.SetTitleColor (UIColor.DarkTextColor, UIControlState.Normal); - oldwayButton.Frame = new CGRect(10, 270, 200, 40); + oldwayButton.Frame = new CGRect (10, 270, 200, 40); oldwayButton.TouchUpInside += (sender, e) => { - var nsurl = new NSUrl("http://itunes.apple.com/us/app/angry-birds/id343200656?mt=8"); + var nsurl = new NSUrl ("http://itunes.apple.com/us/app/angry-birds/id343200656?mt=8"); UIApplication.SharedApplication.OpenUrl (nsurl); }; Add (oldwayButton); @@ -105,9 +105,9 @@ public override void ViewDidLoad () oldway2Button = UIButton.FromType (UIButtonType.RoundedRect); oldway2Button.SetTitle ("Open iBookstore", UIControlState.Normal); oldway2Button.SetTitleColor (UIColor.DarkTextColor, UIControlState.Normal); - oldway2Button.Frame = new CGRect(10, 320, 200, 40); + oldway2Button.Frame = new CGRect (10, 320, 200, 40); oldway2Button.TouchUpInside += (sender, e) => { - var nsurl = new NSUrl("http://itunes.apple.com/au/book/dot-and-the-kangaroo/id510970593?mt=11"); + var nsurl = new NSUrl ("http://itunes.apple.com/au/book/dot-and-the-kangaroo/id510970593?mt=11"); UIApplication.SharedApplication.OpenUrl (nsurl); }; Add (oldway2Button); @@ -115,9 +115,9 @@ public override void ViewDidLoad () oldway3Button = UIButton.FromType (UIButtonType.RoundedRect); oldway3Button.SetTitle ("Open iTunes", UIControlState.Normal); oldway3Button.SetTitleColor (UIColor.DarkTextColor, UIControlState.Normal); - oldway3Button.Frame = new CGRect(10, 370, 200, 40); + oldway3Button.Frame = new CGRect (10, 370, 200, 40); oldway3Button.TouchUpInside += (sender, e) => { - var nsurl = new NSUrl("http://itunes.apple.com/au/album/incredible/id553243272?i=553243280"); + var nsurl = new NSUrl ("http://itunes.apple.com/au/album/incredible/id553243272?i=553243280"); UIApplication.SharedApplication.OpenUrl (nsurl); }; Add (oldway3Button); @@ -133,7 +133,7 @@ void Buy (int productId) { Console.WriteLine ("Buy " + productId); - var spp = new StoreProductParameters(productId); + var spp = new StoreProductParameters (productId); var productViewController = new SKStoreProductViewController (); productViewController.Finished += (sender, err) => { diff --git a/StoreKit/SharedCode/PurchaseManager.cs b/StoreKit/SharedCode/PurchaseManager.cs index b2d886ac4..527caf972 100644 --- a/StoreKit/SharedCode/PurchaseManager.cs +++ b/StoreKit/SharedCode/PurchaseManager.cs @@ -6,19 +6,17 @@ using StoreKit; using Foundation; -namespace SharedCode -{ - public abstract class PurchaseManager : SKProductsRequestDelegate - { - public static readonly NSString InAppPurchaseManagerProductsFetchedNotification = new NSString("InAppPurchaseManagerProductsFetchedNotification"); - public static readonly NSString InAppPurchaseManagerTransactionFailedNotification = new NSString("InAppPurchaseManagerTransactionFailedNotification"); - public static readonly NSString InAppPurchaseManagerTransactionSucceededNotification = new NSString("InAppPurchaseManagerTransactionSucceededNotification"); - public static readonly NSString InAppPurchaseManagerRequestFailedNotification = new NSString("InAppPurchaseManagerRequestFailedNotification"); +namespace SharedCode { + public abstract class PurchaseManager : SKProductsRequestDelegate { + public static readonly NSString InAppPurchaseManagerProductsFetchedNotification = new NSString ("InAppPurchaseManagerProductsFetchedNotification"); + public static readonly NSString InAppPurchaseManagerTransactionFailedNotification = new NSString ("InAppPurchaseManagerTransactionFailedNotification"); + public static readonly NSString InAppPurchaseManagerTransactionSucceededNotification = new NSString ("InAppPurchaseManagerTransactionSucceededNotification"); + public static readonly NSString InAppPurchaseManagerRequestFailedNotification = new NSString ("InAppPurchaseManagerRequestFailedNotification"); protected SKProductsRequest ProductsRequest { get; set; } // Verify that the iTunes account can make this purchase for this application - public bool CanMakePayments() + public bool CanMakePayments () { return SKPaymentQueue.CanMakePayments; } @@ -26,32 +24,32 @@ public bool CanMakePayments() // request multiple products at once public void RequestProductData (List<string> productIds) { - NSString[] array = productIds.Select (pId => (NSString)pId).ToArray(); - NSSet productIdentifiers = NSSet.MakeNSObjectSet<NSString>(array); + NSString [] array = productIds.Select (pId => (NSString) pId).ToArray (); + NSSet productIdentifiers = NSSet.MakeNSObjectSet<NSString> (array); //set up product request for in-app purchase - ProductsRequest = new SKProductsRequest(productIdentifiers); + ProductsRequest = new SKProductsRequest (productIdentifiers); ProductsRequest.Delegate = this; // SKProductsRequestDelegate.ReceivedResponse - ProductsRequest.Start(); + ProductsRequest.Start (); } // received response to RequestProductData - with price,title,description info public override void ReceivedResponse (SKProductsRequest request, SKProductsResponse response) { - SKProduct[] products = response.Products; + SKProduct [] products = response.Products; NSMutableDictionary userInfo = new NSMutableDictionary (); for (int i = 0; i < products.Length; i++) - userInfo.Add ((NSString)products [i].ProductIdentifier, products [i]); + userInfo.Add ((NSString) products [i].ProductIdentifier, products [i]); NSNotificationCenter.DefaultCenter.PostNotificationName (InAppPurchaseManagerProductsFetchedNotification, this, userInfo); foreach (string invalidProductId in response.InvalidProducts) Console.WriteLine ("Invalid product id: {0}", invalidProductId); } - public void PurchaseProduct(string appStoreProductId) + public void PurchaseProduct (string appStoreProductId) { - Console.WriteLine("PurchaseProduct {0}", appStoreProductId); + Console.WriteLine ("PurchaseProduct {0}", appStoreProductId); SKPayment payment = SKPayment.PaymentWithProduct (appStoreProductId); SKPaymentQueue.DefaultQueue.AddPayment (payment); } @@ -60,9 +58,9 @@ public void FailedTransaction (SKPaymentTransaction transaction) { //SKErrorPaymentCancelled == 2 string errorDescription = transaction.Error.Code == 2 ? "User CANCELLED FailedTransaction" : "FailedTransaction"; - Console.WriteLine("{0} Code={1} {2}", errorDescription, transaction.Error.Code, transaction.Error.LocalizedDescription); + Console.WriteLine ("{0} Code={1} {2}", errorDescription, transaction.Error.Code, transaction.Error.LocalizedDescription); - FinishTransaction(transaction, false); + FinishTransaction (transaction, false); } public void CompleteTransaction (SKPaymentTransaction transaction) @@ -77,11 +75,11 @@ public void CompleteTransaction (SKPaymentTransaction transaction) protected abstract void CompleteTransaction (string productId); - public void FinishTransaction(SKPaymentTransaction transaction, bool wasSuccessful) + public void FinishTransaction (SKPaymentTransaction transaction, bool wasSuccessful) { Console.WriteLine ("FinishTransaction {0}", wasSuccessful); // remove the transaction from the payment queue. - SKPaymentQueue.DefaultQueue.FinishTransaction (transaction); // THIS IS IMPORTANT - LET'S APPLE KNOW WE'RE DONE !!!! + SKPaymentQueue.DefaultQueue.FinishTransaction (transaction); // THIS IS IMPORTANT - LET'S APPLE KNOW WE'RE DONE !!!! NSDictionary userInfo = new NSDictionary ("transaction", transaction); var notificationKey = wasSuccessful ? InAppPurchaseManagerTransactionSucceededNotification : InAppPurchaseManagerTransactionFailedNotification; @@ -104,21 +102,21 @@ public override void RequestFailed (SKRequest request, NSError error) /// Restore any transactions that occurred for this Apple ID, either on /// this device or any other logged in with that account. /// </summary> - public void Restore() + public void Restore () { Console.WriteLine (" ** Restore **"); // theObserver will be notified of when the restored transactions start arriving <- AppStore - SKPaymentQueue.DefaultQueue.RestoreCompletedTransactions(); + SKPaymentQueue.DefaultQueue.RestoreCompletedTransactions (); } public virtual void RestoreTransaction (SKPaymentTransaction transaction) { // Restored Transactions always have an 'original transaction' attached - Console.WriteLine("RestoreTransaction {0}; OriginalTransaction {1}",transaction.TransactionIdentifier, transaction.OriginalTransaction.TransactionIdentifier); + Console.WriteLine ("RestoreTransaction {0}; OriginalTransaction {1}", transaction.TransactionIdentifier, transaction.OriginalTransaction.TransactionIdentifier); string productId = transaction.OriginalTransaction.Payment.ProductIdentifier; // Register the purchase, so it is remembered for next time RestoreTransaction (productId); - FinishTransaction(transaction, true); + FinishTransaction (transaction, true); } protected virtual void RestoreTransaction (string productId) diff --git a/StoreKit/SharedCode/SKProductExtension.cs b/StoreKit/SharedCode/SKProductExtension.cs index e11870b5a..9d6b30eef 100644 --- a/StoreKit/SharedCode/SKProductExtension.cs +++ b/StoreKit/SharedCode/SKProductExtension.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace SharedCode -{ - public static class SKProductExtension - { +namespace SharedCode { + public static class SKProductExtension { public static string LocalizedPrice (this SKProduct product) { var formatter = new NSNumberFormatter { diff --git a/StoryboardIntro/UnifiedStoryboard/AppDelegate.cs b/StoryboardIntro/UnifiedStoryboard/AppDelegate.cs index 3854566e3..72a9f80f7 100644 --- a/StoryboardIntro/UnifiedStoryboard/AppDelegate.cs +++ b/StoryboardIntro/UnifiedStoryboard/AppDelegate.cs @@ -5,39 +5,37 @@ using Foundation; using UIKit; -namespace UnifiedStoryboard -{ +namespace UnifiedStoryboard { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/StoryboardIntro/UnifiedStoryboard/Main.cs b/StoryboardIntro/UnifiedStoryboard/Main.cs index f1bc496f5..2dc0c9af5 100644 --- a/StoryboardIntro/UnifiedStoryboard/Main.cs +++ b/StoryboardIntro/UnifiedStoryboard/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace UnifiedStoryboard -{ - public class Application - { +namespace UnifiedStoryboard { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/StoryboardIntro/UnifiedStoryboard/UnifiedStoryboardViewController.cs b/StoryboardIntro/UnifiedStoryboard/UnifiedStoryboardViewController.cs index 4f5214db1..cb1696fbc 100644 --- a/StoryboardIntro/UnifiedStoryboard/UnifiedStoryboardViewController.cs +++ b/StoryboardIntro/UnifiedStoryboard/UnifiedStoryboardViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; -namespace UnifiedStoryboard -{ - public partial class UnifiedStoryboardViewController : UIViewController - { +namespace UnifiedStoryboard { + public partial class UnifiedStoryboardViewController : UIViewController { public UnifiedStoryboardViewController (IntPtr handle) : base (handle) { } @@ -16,7 +14,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -25,7 +23,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/StoryboardTable/StoryboardTables1/AppDelegate.cs b/StoryboardTable/StoryboardTables1/AppDelegate.cs index 49eee00c0..a22f8c654 100644 --- a/StoryboardTable/StoryboardTables1/AppDelegate.cs +++ b/StoryboardTable/StoryboardTables1/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace StoryboardTables1 -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace StoryboardTables1 { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/StoryboardTable/StoryboardTables1/Chores.cs b/StoryboardTable/StoryboardTables1/Chores.cs index 5e35264c6..18c3ae8d3 100644 --- a/StoryboardTable/StoryboardTables1/Chores.cs +++ b/StoryboardTable/StoryboardTables1/Chores.cs @@ -1,16 +1,14 @@ -using System; +using System; -namespace StoryboardTables1 -{ - public class Chores - { +namespace StoryboardTables1 { + public class Chores { public int Id { get; set; } public string Name { get; set; } public string Notes { get; set; } public bool Done { get; set; } - public Chores() - { - } - } + public Chores () + { + } + } } diff --git a/StoryboardTable/StoryboardTables1/ItemViewController.cs b/StoryboardTable/StoryboardTables1/ItemViewController.cs index 30992d3dc..52064a31f 100644 --- a/StoryboardTable/StoryboardTables1/ItemViewController.cs +++ b/StoryboardTable/StoryboardTables1/ItemViewController.cs @@ -1,75 +1,71 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using System.Collections.Generic; -namespace StoryboardTables1 -{ - public partial class ItemViewController : UITableViewController - { - List<Chores> chores; - - public ItemViewController (IntPtr handle) : base (handle) - { +namespace StoryboardTables1 { + public partial class ItemViewController : UITableViewController { + List<Chores> chores; + + public ItemViewController (IntPtr handle) : base (handle) + { chores = new List<Chores> { - new Chores {Name="Groceries", Notes="Buy bread, cheese, apples", Done=false}, - new Chores {Name="Devices", Notes="Buy Nexus, Galaxy, Droid", Done=false} - }; - } + new Chores {Name="Groceries", Notes="Buy bread, cheese, apples", Done=false}, + new Chores {Name="Devices", Notes="Buy Nexus, Galaxy, Droid", Done=false} + }; + } - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { - if (segue.Identifier == "TaskSegue") - { // set in Storyboard + if (segue.Identifier == "TaskSegue") { // set in Storyboard var navctlr = segue.DestinationViewController as TaskDetailViewController; - if (navctlr != null) - { + if (navctlr != null) { var source = TableView.Source as RootTableSource; var rowPath = TableView.IndexPathForSelectedRow; - var item = source.GetItem(rowPath.Row); - navctlr.SetTask(this, item); // to be defined on the TaskDetailViewController + var item = source.GetItem (rowPath.Row); + navctlr.SetTask (this, item); // to be defined on the TaskDetailViewController } } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - addButton.Clicked += (sender, e) => CreateTask(); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - TableView.Source = new RootTableSource(chores.ToArray()); - } + } - public void SaveTask(Chores chore) + public override void ViewDidLoad () { - var oldTask = chores.Find(t => t.Id == chore.Id); - NavigationController.PopViewController(true); + base.ViewDidLoad (); + + addButton.Clicked += (sender, e) => CreateTask (); } - public void DeleteTask(Chores chore) + public override void ViewWillAppear (bool animated) { - var oldTask = chores.Find(t => t.Id == chore.Id); - chores.Remove(oldTask); - NavigationController.PopViewController(true); + base.ViewWillAppear (animated); + + TableView.Source = new RootTableSource (chores.ToArray ()); } - public void CreateTask() + public void SaveTask (Chores chore) + { + var oldTask = chores.Find (t => t.Id == chore.Id); + NavigationController.PopViewController (true); + } + + public void DeleteTask (Chores chore) + { + var oldTask = chores.Find (t => t.Id == chore.Id); + chores.Remove (oldTask); + NavigationController.PopViewController (true); + } + + public void CreateTask () { // first, add the task to the underlying data - var newId = chores[chores.Count - 1].Id + 1; + var newId = chores [chores.Count - 1].Id + 1; var newChore = new Chores { Id = newId }; - chores.Add(newChore); + chores.Add (newChore); // then open the detail view to edit it - var detail = Storyboard.InstantiateViewController("detail") as TaskDetailViewController; - detail.SetTask(this, newChore); - NavigationController.PushViewController(detail, true); - } - } -} \ No newline at end of file + var detail = Storyboard.InstantiateViewController ("detail") as TaskDetailViewController; + detail.SetTask (this, newChore); + NavigationController.PushViewController (detail, true); + } + } +} diff --git a/StoryboardTable/StoryboardTables1/Main.cs b/StoryboardTable/StoryboardTables1/Main.cs index 22c39d6c8..126173333 100644 --- a/StoryboardTable/StoryboardTables1/Main.cs +++ b/StoryboardTable/StoryboardTables1/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace StoryboardTables1 -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace StoryboardTables1 { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/StoryboardTable/StoryboardTables1/RootTableSource.cs b/StoryboardTable/StoryboardTables1/RootTableSource.cs index 1957a3a37..a6e47412f 100644 --- a/StoryboardTable/StoryboardTables1/RootTableSource.cs +++ b/StoryboardTable/StoryboardTables1/RootTableSource.cs @@ -1,40 +1,38 @@ -using System; +using System; using Foundation; using UIKit; -namespace StoryboardTables1 -{ - public class RootTableSource : UITableViewSource - { +namespace StoryboardTables1 { + public class RootTableSource : UITableViewSource { // there is NO database or storage of Tasks in this example, just an in-memory List<> - Chores[] tableItems; + Chores [] tableItems; string cellIdentifier = "taskcell"; // set in the Storyboard - public RootTableSource(Chores[] items) - { - tableItems = items; - } + public RootTableSource (Chores [] items) + { + tableItems = items; + } - public override nint RowsInSection(UITableView tableview, nint section) + public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Length; } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { // in a Storyboard, Dequeue will ALWAYS return a cell, - var cell = tableView.DequeueReusableCell(cellIdentifier); + var cell = tableView.DequeueReusableCell (cellIdentifier); // now set the properties as normal - cell.TextLabel.Text = tableItems[indexPath.Row].Name; - if (tableItems[indexPath.Row].Done) + cell.TextLabel.Text = tableItems [indexPath.Row].Name; + if (tableItems [indexPath.Row].Done) cell.Accessory = UITableViewCellAccessory.Checkmark; else cell.Accessory = UITableViewCellAccessory.None; return cell; } - public Chores GetItem(int id) + public Chores GetItem (int id) { - return tableItems[id]; + return tableItems [id]; } - } + } } diff --git a/StoryboardTable/StoryboardTables1/TaskDetailViewController.cs b/StoryboardTable/StoryboardTables1/TaskDetailViewController.cs index 1f1e7a9cd..7e826549b 100644 --- a/StoryboardTable/StoryboardTables1/TaskDetailViewController.cs +++ b/StoryboardTable/StoryboardTables1/TaskDetailViewController.cs @@ -1,46 +1,43 @@ -using Foundation; -using System; -using UIKit; - -namespace StoryboardTables1 -{ - public partial class TaskDetailViewController : UITableViewController - { +using Foundation; +using System; +using UIKit; + +namespace StoryboardTables1 { + public partial class TaskDetailViewController : UITableViewController { Chores currentTask { get; set; } - public ItemViewController Delegate { get; set; } - - public TaskDetailViewController (IntPtr handle) : base (handle) - { - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public ItemViewController Delegate { get; set; } + + public TaskDetailViewController (IntPtr handle) : base (handle) + { + } - SaveButton.TouchUpInside += (sender, e) => - { + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + SaveButton.TouchUpInside += (sender, e) => { currentTask.Name = TitleText.Text; currentTask.Notes = NotesText.Text; currentTask.Done = DoneSwitch.On; - Delegate.SaveTask(currentTask); + Delegate.SaveTask (currentTask); }; - DeleteButton.TouchUpInside += (sender, e) => Delegate.DeleteTask(currentTask); - } + DeleteButton.TouchUpInside += (sender, e) => Delegate.DeleteTask (currentTask); + } - public override void ViewWillAppear(bool animated) + public override void ViewWillAppear (bool animated) { - base.ViewWillAppear(animated); + base.ViewWillAppear (animated); TitleText.Text = currentTask.Name; NotesText.Text = currentTask.Notes; DoneSwitch.On = currentTask.Done; } // this will be called before the view is displayed - public void SetTask(ItemViewController d, Chores task) + public void SetTask (ItemViewController d, Chores task) { Delegate = d; currentTask = task; - } - } -} \ No newline at end of file + } + } +} diff --git a/StoryboardTable/StoryboardTables1/ViewController.cs b/StoryboardTable/StoryboardTables1/ViewController.cs index 9ce4c7a29..caa141989 100644 --- a/StoryboardTable/StoryboardTables1/ViewController.cs +++ b/StoryboardTable/StoryboardTables1/ViewController.cs @@ -1,26 +1,24 @@ -using System; +using System; using UIKit; -namespace StoryboardTables1 -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } +namespace StoryboardTables1 { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - // Perform any additional setup after loading the view, typically from a nib. - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + // Perform any additional setup after loading the view, typically from a nib. + } - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - // Release any cached data, images, etc that aren't in use. - } - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + // Release any cached data, images, etc that aren't in use. + } + } } diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/AppDelegate.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/AppDelegate.cs index 2a9c547fd..1727d95f9 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/AppDelegate.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/AppDelegate.cs @@ -1,49 +1,47 @@ -using System; - -using Foundation; -using UIKit; - -namespace StoryboardTable -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window { - get; - set; - } - // - // This method is invoked when the application is about to move from active to inactive state. - // - // OpenGL applications should use this method to pause. - // - - - public override void OnResignActivation (UIApplication application) - { - } - - // This method should be used to release shared resources and it should store the application state. - // If your application supports background exection this method is called instead of WillTerminate - // when the user quits. - public override void DidEnterBackground (UIApplication application) - { - } - - // This method is called as part of the transiton from background to active state. - public override void WillEnterForeground (UIApplication application) - { - } - - // This method is called when the application is about to terminate. Save data, if needed. - public override void WillTerminate (UIApplication application) - { - } - } -} - +using System; + +using Foundation; +using UIKit; + +namespace StoryboardTable { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + // + // This method is invoked when the application is about to move from active to inactive state. + // + // OpenGL applications should use this method to pause. + // + + + public override void OnResignActivation (UIApplication application) + { + } + + // This method should be used to release shared resources and it should store the application state. + // If your application supports background exection this method is called instead of WillTerminate + // when the user quits. + public override void DidEnterBackground (UIApplication application) + { + } + + // This method is called as part of the transiton from background to active state. + public override void WillEnterForeground (UIApplication application) + { + } + + // This method is called when the application is about to terminate. Save data, if needed. + public override void WillTerminate (UIApplication application) + { + } + } +} + diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/AuthenticationViewController.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/AuthenticationViewController.cs index 069ed4270..f01ca7a7c 100644 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/AuthenticationViewController.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/AuthenticationViewController.cs @@ -5,10 +5,8 @@ using LocalAuthentication; using Security; -namespace StoryboardTable -{ - partial class AuthenticationViewController : UIViewController - { +namespace StoryboardTable { + partial class AuthenticationViewController : UIViewController { LAContextReplyHandler replyHandler; public AuthenticationViewController (IntPtr handle) : base (handle) @@ -20,36 +18,35 @@ public override void ViewWillAppear (bool animated) base.ViewWillAppear (animated); // bind every time, to reflect deletion in the Detail view - unAuthenticatedLabel.Text=""; + unAuthenticatedLabel.Text = ""; } partial void AuthenticateMe (UIButton sender) { - var context = new LAContext(); + var context = new LAContext (); NSError AuthError; - var localizedReason = new NSString("To add a new chore"); + var localizedReason = new NSString ("To add a new chore"); //Use canEvaluatePolicy method to test if device is TouchID enabled //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics - if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)){ - replyHandler = new LAContextReplyHandler((success, error) => { + if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)) { + replyHandler = new LAContextReplyHandler ((success, error) => { //Make sure it runs on MainThread, not in Background - this.InvokeOnMainThread(()=>{ - if(success){ - Console.WriteLine("You logged in!"); - PerformSegue("AuthenticationSegue", this); - } - else{ + this.InvokeOnMainThread (() => { + if (success) { + Console.WriteLine ("You logged in!"); + PerformSegue ("AuthenticationSegue", this); + } else { //Show fallback mechanism here - unAuthenticatedLabel.Text="Oh Noes"; - AuthenticateButton.Hidden= true; + unAuthenticatedLabel.Text = "Oh Noes"; + AuthenticateButton.Hidden = true; } }); }); //Use evaluatePolicy to start authentication operation and show the UI as an Alert view //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics - context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler); + context.EvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler); }; } diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/Chore.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/Chore.cs index 7b4361ef9..312714d43 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/Chore.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/Chore.cs @@ -1,21 +1,21 @@ -using System; - -namespace StoryboardTable { - - /// <summary> - /// Represents a Chore. - /// </summary> - /// - public class Chore { - - public Chore () - { - } - - public int Id { get; set; } - public string Name { get; set; } - public string Notes { get; set; } - public bool Done { get; set; } - } -} - +using System; + +namespace StoryboardTable { + + /// <summary> + /// Represents a Chore. + /// </summary> + /// + public class Chore { + + public Chore () + { + } + + public int Id { get; set; } + public string Name { get; set; } + public string Notes { get; set; } + public bool Done { get; set; } + } +} + diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/DetailViewController.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/DetailViewController.cs index bb611e58a..898f87a29 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/DetailViewController.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/DetailViewController.cs @@ -1,52 +1,50 @@ -using System; -using System.Drawing; -using System.Collections.Generic; - -using MonoTouch.Foundation; -using MonoTouch.UIKit; - -namespace StoryboardTable -{ - public partial class DetailViewController : UIViewController - { - object detailItem; - - public DetailViewController (IntPtr handle) : base (handle) - { - } - - public void SetDetailItem (object newDetailItem) - { - if (detailItem != newDetailItem) { - detailItem = newDetailItem; - - // Update the view - ConfigureView (); - } - } - - void ConfigureView () - { - // Update the user interface for the detail item - if (IsViewLoaded && detailItem != null) - detailDescriptionLabel.Text = detailItem.ToString (); - } - - public override void DidReceiveMemoryWarning () - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning (); - - // Release any cached data, images, etc that aren't in use. - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - // Perform any additional setup after loading the view, typically from a nib. - ConfigureView (); - } - } -} - +using System; +using System.Drawing; +using System.Collections.Generic; + +using MonoTouch.Foundation; +using MonoTouch.UIKit; + +namespace StoryboardTable { + public partial class DetailViewController : UIViewController { + object detailItem; + + public DetailViewController (IntPtr handle) : base (handle) + { + } + + public void SetDetailItem (object newDetailItem) + { + if (detailItem != newDetailItem) { + detailItem = newDetailItem; + + // Update the view + ConfigureView (); + } + } + + void ConfigureView () + { + // Update the user interface for the detail item + if (IsViewLoaded && detailItem != null) + detailDescriptionLabel.Text = detailItem.ToString (); + } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Perform any additional setup after loading the view, typically from a nib. + ConfigureView (); + } + } +} + diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/Main.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/Main.cs index f76366a47..8311c04fd 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/Main.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/Main.cs @@ -1,20 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -using Foundation; -using UIKit; - -namespace StoryboardTable -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; + +using Foundation; +using UIKit; + +namespace StoryboardTable { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/MasterViewController.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/MasterViewController.cs index 817b04460..197e4f087 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/MasterViewController.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/MasterViewController.cs @@ -1,185 +1,183 @@ -using System; -using CoreGraphics; -using System.Collections.Generic; - -using Foundation; -using UIKit; - -namespace StoryboardTable -{ - public partial class MasterViewController : UITableViewController - { - List<Chore> chores; - - public MasterViewController (IntPtr handle) : base (handle) - { - Title = "ChoreBoard"; - - // Custom initialization - chores = new List<Chore> { - new Chore() {Name="Groceries", Notes="Buy bread, cheese, apples", Done=false}, - new Chore() {Name="Devices", Notes="Buy Nexus, Galaxy, Droid", Done=false} - }; - - } - - public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "TaskSegue") { // set in Storyboard - var navctlr = segue.DestinationViewController as TaskDetailViewController; - if (navctlr != null) { - var source = TableView.Source as RootTableSource; - var rowPath = TableView.IndexPathForSelectedRow; - var item = source.GetItem(rowPath.Row); - navctlr.SetTask (this, item); // to be defined on the TaskDetailViewController - } - } - } - - public void CreateTask () - { - // first, add the task to the underlying data - var newId = chores[chores.Count - 1].Id + 1; - var newChore = new Chore(){Id=newId}; - chores.Add (newChore); - - // then open the detail view to edit it - var detail = Storyboard.InstantiateViewController("detail") as TaskDetailViewController; - detail.SetTask (this, newChore); - NavigationController.PushViewController (detail, true); - } - - public void SaveTask (Chore chore) - { - //var oldTask = chores.Find(t => t.Id == chore.Id); - NavigationController.PopViewController(true); - } - - public void DeleteTask (Chore chore) - { - var oldTask = chores.Find(t => t.Id == chore.Id); - chores.Remove (oldTask); - NavigationController.PopViewController(true); - } - - public override void DidReceiveMemoryWarning () - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning (); - - // Release any cached data, images, etc that aren't in use. - } - - #region View lifecycle - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - // Perform any additional setup after loading the view, typically from a nib. - AddButton.Clicked += (sender, e) => { - CreateTask (); - }; - } - - - public override void ViewWillAppear (bool animated) - { - base.ViewWillAppear (animated); - - // bind every time, to reflect deletion in the Detail view - TableView.Source = new RootTableSource(chores.ToArray ()); - } - - public override void ViewDidAppear (bool animated) - { - base.ViewDidAppear (animated); - } - - public override void ViewWillDisappear (bool animated) - { - base.ViewWillDisappear (animated); - } - - public override void ViewDidDisappear (bool animated) - { - base.ViewDidDisappear (animated); - } - - #endregion - -// class DataSource : UITableViewSource -// { -// static readonly NSString CellIdentifier = new NSString ("Cell"); -// readonly List<object> objects = new List<object> (); -// readonly MasterViewController controller; -// -// public DataSource (MasterViewController controller) -// { -// this.controller = controller; -// } -// -// public IList<object> Objects { -// get { return objects; } -// } -// -// -// // Customize the number of sections in the table view. -// public override int NumberOfSections (UITableView tableView) -// { -// return 1; -// } -// -// public override int RowsInSection (UITableView tableview, int section) -// { -// return objects.Count; -// } -// -// // Customize the appearance of table view cells. -// public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) -// { -// var cell = (UITableViewCell)tableView.DequeueReusableCell (CellIdentifier, indexPath); -// -// cell.TextLabel.Text = objects [indexPath.Row].ToString (); -// -// return cell; -// } -// -// public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) -// { -// // Return false if you do not want the specified item to be editable. -// return true; -// } -// -// public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) -// { -// if (editingStyle == UITableViewCellEditingStyle.Delete) { -// // Delete the row from the data source. -// objects.RemoveAt (indexPath.Row); -// controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); -// } else if (editingStyle == UITableViewCellEditingStyle.Insert) { -// // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. -// } -// } -// -// /* -// // Override to support rearranging the table view. -// public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) -// { -// } -// */ -// -// /* -// // Override to support conditional rearranging of the table view. -// public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath) -// { -// // Return false if you do not want the item to be re-orderable. -// return true; -// } -// */ -// } - - - } -} - +using System; +using CoreGraphics; +using System.Collections.Generic; + +using Foundation; +using UIKit; + +namespace StoryboardTable { + public partial class MasterViewController : UITableViewController { + List<Chore> chores; + + public MasterViewController (IntPtr handle) : base (handle) + { + Title = "ChoreBoard"; + + // Custom initialization + chores = new List<Chore> { + new Chore() {Name="Groceries", Notes="Buy bread, cheese, apples", Done=false}, + new Chore() {Name="Devices", Notes="Buy Nexus, Galaxy, Droid", Done=false} + }; + + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "TaskSegue") { // set in Storyboard + var navctlr = segue.DestinationViewController as TaskDetailViewController; + if (navctlr != null) { + var source = TableView.Source as RootTableSource; + var rowPath = TableView.IndexPathForSelectedRow; + var item = source.GetItem (rowPath.Row); + navctlr.SetTask (this, item); // to be defined on the TaskDetailViewController + } + } + } + + public void CreateTask () + { + // first, add the task to the underlying data + var newId = chores [chores.Count - 1].Id + 1; + var newChore = new Chore () { Id = newId }; + chores.Add (newChore); + + // then open the detail view to edit it + var detail = Storyboard.InstantiateViewController ("detail") as TaskDetailViewController; + detail.SetTask (this, newChore); + NavigationController.PushViewController (detail, true); + } + + public void SaveTask (Chore chore) + { + //var oldTask = chores.Find(t => t.Id == chore.Id); + NavigationController.PopViewController (true); + } + + public void DeleteTask (Chore chore) + { + var oldTask = chores.Find (t => t.Id == chore.Id); + chores.Remove (oldTask); + NavigationController.PopViewController (true); + } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + #region View lifecycle + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Perform any additional setup after loading the view, typically from a nib. + AddButton.Clicked += (sender, e) => { + CreateTask (); + }; + } + + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + // bind every time, to reflect deletion in the Detail view + TableView.Source = new RootTableSource (chores.ToArray ()); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + } + + #endregion + + // class DataSource : UITableViewSource + // { + // static readonly NSString CellIdentifier = new NSString ("Cell"); + // readonly List<object> objects = new List<object> (); + // readonly MasterViewController controller; + // + // public DataSource (MasterViewController controller) + // { + // this.controller = controller; + // } + // + // public IList<object> Objects { + // get { return objects; } + // } + // + // + // // Customize the number of sections in the table view. + // public override int NumberOfSections (UITableView tableView) + // { + // return 1; + // } + // + // public override int RowsInSection (UITableView tableview, int section) + // { + // return objects.Count; + // } + // + // // Customize the appearance of table view cells. + // public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + // { + // var cell = (UITableViewCell)tableView.DequeueReusableCell (CellIdentifier, indexPath); + // + // cell.TextLabel.Text = objects [indexPath.Row].ToString (); + // + // return cell; + // } + // + // public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) + // { + // // Return false if you do not want the specified item to be editable. + // return true; + // } + // + // public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) + // { + // if (editingStyle == UITableViewCellEditingStyle.Delete) { + // // Delete the row from the data source. + // objects.RemoveAt (indexPath.Row); + // controller.TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); + // } else if (editingStyle == UITableViewCellEditingStyle.Insert) { + // // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. + // } + // } + // + // /* + // // Override to support rearranging the table view. + // public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) + // { + // } + // */ + // + // /* + // // Override to support conditional rearranging of the table view. + // public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath) + // { + // // Return false if you do not want the item to be re-orderable. + // return true; + // } + // */ + // } + + + } +} + diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/RootTableSource.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/RootTableSource.cs index 65876e362..ef0294a16 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/RootTableSource.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/RootTableSource.cs @@ -1,38 +1,38 @@ -using System; -using UIKit; - - -namespace StoryboardTable -{ - public class RootTableSource : UITableViewSource { - - // there is NO database or storage of Tasks in this example, just an in-memory List<> - Chore[] tableItems; - string cellIdentifier = "taskcell"; // set in the Storyboard - - public RootTableSource (Chore[] items) - { - tableItems = items; - } - public override nint RowsInSection (UITableView tableview, nint section) - { - return tableItems.Length; - } - public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath) - { - // in a Storyboard, Dequeue will ALWAYS return a cell, - UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); - // now set the properties as normal - cell.TextLabel.Text = tableItems[indexPath.Row].Name; - if (tableItems[indexPath.Row].Done) - cell.Accessory = UITableViewCellAccessory.Checkmark; - else - cell.Accessory = UITableViewCellAccessory.None; - return cell; - } - public Chore GetItem(int id) { - return tableItems[id]; - } - } -} - +using System; +using UIKit; + + +namespace StoryboardTable { + public class RootTableSource : UITableViewSource { + + // there is NO database or storage of Tasks in this example, just an in-memory List<> + Chore [] tableItems; + string cellIdentifier = "taskcell"; // set in the Storyboard + + public RootTableSource (Chore [] items) + { + tableItems = items; + } + public override nint RowsInSection (UITableView tableview, nint section) + { + return tableItems.Length; + } + public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath) + { + // in a Storyboard, Dequeue will ALWAYS return a cell, + UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); + // now set the properties as normal + cell.TextLabel.Text = tableItems [indexPath.Row].Name; + if (tableItems [indexPath.Row].Done) + cell.Accessory = UITableViewCellAccessory.Checkmark; + else + cell.Accessory = UITableViewCellAccessory.None; + return cell; + } + public Chore GetItem (int id) + { + return tableItems [id]; + } + } +} + diff --git a/StoryboardTable_LocalAuthentication/StoryboardTable/TaskDetailViewController.cs b/StoryboardTable_LocalAuthentication/StoryboardTable/TaskDetailViewController.cs index da4ea7955..2a337c794 100755 --- a/StoryboardTable_LocalAuthentication/StoryboardTable/TaskDetailViewController.cs +++ b/StoryboardTable_LocalAuthentication/StoryboardTable/TaskDetailViewController.cs @@ -1,49 +1,48 @@ -using System; -using Foundation; -using UIKit; -using System.CodeDom.Compiler; - - -namespace StoryboardTable -{ - partial class TaskDetailViewController : UITableViewController - { - Chore currentTask {get;set;} - public MasterViewController Delegate {get;set;} // will be used to Save, Delete later - - public TaskDetailViewController (IntPtr handle) : base (handle) - { - - } - - // when displaying, set-up the properties - public override void ViewDidLoad() - { - base.ViewDidLoad (); - - SaveButton.TouchUpInside += (sender, e) => { - currentTask.Name = TitleText.Text; - currentTask.Notes = NotesText.Text; - currentTask.Done = DoneSwitch.On; - Delegate.SaveTask(currentTask); - }; - DeleteButton.TouchUpInside += (sender, e) => { - Delegate.DeleteTask(currentTask); - }; - } - - public override void ViewWillAppear (bool animated) - { - base.ViewWillAppear (animated); - TitleText.Text = currentTask.Name; - NotesText.Text = currentTask.Notes; - DoneSwitch.On = currentTask.Done; - } - - // this will be called before the view is displayed - public void SetTask (MasterViewController d, Chore task) { - Delegate = d; - currentTask = task; - } - } -} +using System; +using Foundation; +using UIKit; +using System.CodeDom.Compiler; + + +namespace StoryboardTable { + partial class TaskDetailViewController : UITableViewController { + Chore currentTask { get; set; } + public MasterViewController Delegate { get; set; } // will be used to Save, Delete later + + public TaskDetailViewController (IntPtr handle) : base (handle) + { + + } + + // when displaying, set-up the properties + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + SaveButton.TouchUpInside += (sender, e) => { + currentTask.Name = TitleText.Text; + currentTask.Notes = NotesText.Text; + currentTask.Done = DoneSwitch.On; + Delegate.SaveTask (currentTask); + }; + DeleteButton.TouchUpInside += (sender, e) => { + Delegate.DeleteTask (currentTask); + }; + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + TitleText.Text = currentTask.Name; + NotesText.Text = currentTask.Notes; + DoneSwitch.On = currentTask.Done; + } + + // this will be called before the view is displayed + public void SetTask (MasterViewController d, Chore task) + { + Delegate = d; + currentTask = task; + } + } +} diff --git a/StreamingAudio/AppDelegate.cs b/StreamingAudio/AppDelegate.cs index 7bd9f2b38..7746af61c 100644 --- a/StreamingAudio/AppDelegate.cs +++ b/StreamingAudio/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace StreamingAudio -{ +namespace StreamingAudio { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; // @@ -24,7 +22,7 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // create a new window instance based on the screen size - var navigationController = new UINavigationController (new MainViewController()); + var navigationController = new UINavigationController (new MainViewController ()); navigationController.NavigationBar.Translucent = false; window = new UIWindow (UIScreen.MainScreen.Bounds); diff --git a/StreamingAudio/ErrorArg.cs b/StreamingAudio/ErrorArg.cs index ef05d6419..d708ca174 100644 --- a/StreamingAudio/ErrorArg.cs +++ b/StreamingAudio/ErrorArg.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace StreamingAudio -{ - public class ErrorArg : EventArgs - { +namespace StreamingAudio { + public class ErrorArg : EventArgs { public string Description { get; set; } } } diff --git a/StreamingAudio/Main.cs b/StreamingAudio/Main.cs index 8d9c54943..cc5797a5c 100644 --- a/StreamingAudio/Main.cs +++ b/StreamingAudio/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace StreamingAudio -{ - public class Application - { +namespace StreamingAudio { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/StreamingAudio/MainViewController.cs b/StreamingAudio/MainViewController.cs index b31517346..1a1b5d18e 100644 --- a/StreamingAudio/MainViewController.cs +++ b/StreamingAudio/MainViewController.cs @@ -1,16 +1,13 @@ using System; using UIKit; -namespace StreamingAudio -{ - public enum PlayerOption - { +namespace StreamingAudio { + public enum PlayerOption { Stream = 0, StreamAndSave } - public partial class MainViewController : UIViewController - { + public partial class MainViewController : UIViewController { const string LetsStopTheWarUrl = "http://ccmixter.org/content/bradstanfield/bradstanfield_-_People_Let_s_Stop_The_War.mp3"; public MainViewController () : base ("MainViewController", null) diff --git a/StreamingAudio/PlayerViewController.cs b/StreamingAudio/PlayerViewController.cs index cfabf0b57..02b6794d5 100644 --- a/StreamingAudio/PlayerViewController.cs +++ b/StreamingAudio/PlayerViewController.cs @@ -8,10 +8,8 @@ using System.Diagnostics; using AVFoundation; -namespace StreamingAudio -{ - public partial class PlayerViewController : UIViewController - { +namespace StreamingAudio { + public partial class PlayerViewController : UIViewController { NSTimer updatingTimer; StreamingPlayback player; @@ -102,7 +100,7 @@ void PlayPauseButtonClickHandler (object sender, EventArgs e) void StartPlayback () { try { - var request = (HttpWebRequest)WebRequest.Create (SourceUrl); + var request = (HttpWebRequest) WebRequest.Create (SourceUrl); request.BeginGetResponse (StreamDownloadedHandler, request); } catch (Exception e) { string.Format ("Error: {0}", e.ToString ()); @@ -137,12 +135,14 @@ void StreamDownloadedHandler (IAsyncResult result) inputStream = responseStream; using (player = new StreamingPlayback ()) { - player.OutputReady += delegate { + player.OutputReady += delegate + { timeline = player.OutputQueue.CreateTimeline (); sampleRate = player.OutputQueue.SampleRate; }; - InvokeOnMainThread (delegate { + InvokeOnMainThread (delegate + { if (updatingTimer != null) updatingTimer.Invalidate (); @@ -151,10 +151,11 @@ void StreamDownloadedHandler (IAsyncResult result) while ((inputStreamLength = inputStream.Read (buffer, 0, buffer.Length)) != 0 && player != null) { l += inputStreamLength; - player.ParseBytes (buffer, inputStreamLength, false, l == (int)response.ContentLength); + player.ParseBytes (buffer, inputStreamLength, false, l == (int) response.ContentLength); - InvokeOnMainThread (delegate { - progressBar.Progress = l / (float)response.ContentLength; + InvokeOnMainThread (delegate + { + progressBar.Progress = l / (float) response.ContentLength; }); } } @@ -162,7 +163,8 @@ void StreamDownloadedHandler (IAsyncResult result) } catch (Exception e) { RaiseErrorOccurredEvent ("Error fetching response stream\n" + e); Debug.WriteLine (e); - InvokeOnMainThread (delegate { + InvokeOnMainThread (delegate + { if (NavigationController != null) NavigationController.PopToRootViewController (true); }); @@ -187,7 +189,7 @@ string FormatTime (double time) double minutes = time / 60; double seconds = time % 60; - return String.Format ("{0}:{1:D2}", (int)minutes, (int)seconds); + return String.Format ("{0}:{1:D2}", (int) minutes, (int) seconds); } Stream GetQueueStream (Stream responseStream) diff --git a/StreamingAudio/QueueStream.cs b/StreamingAudio/QueueStream.cs index 8bad0d9a9..9d7c347c9 100644 --- a/StreamingAudio/QueueStream.cs +++ b/StreamingAudio/QueueStream.cs @@ -3,10 +3,8 @@ using System.Threading; using System.IO; -namespace StreamingAudio -{ - public class QueueStream : Stream - { +namespace StreamingAudio { + public class QueueStream : Stream { Stream writeStream; Stream readStream; long size; @@ -40,7 +38,7 @@ public override long Position { set { throw new NotImplementedException (); } } - public override int Read (byte[] buffer, int offset, int count) + public override int Read (byte [] buffer, int offset, int count) { lock (plock) { while (true) { @@ -60,7 +58,7 @@ public override int Read (byte[] buffer, int offset, int count) } } - public void Push (byte[] buffer, int offset, int count) + public void Push (byte [] buffer, int offset, int count) { lock (plock) { writeStream.Write (buffer, offset, count); @@ -89,7 +87,7 @@ protected override void Dispose (bool disposing) base.Dispose (disposing); } -#region non implemented abstract members of Stream + #region non implemented abstract members of Stream public override void Flush () { @@ -105,12 +103,12 @@ public override void SetLength (long value) throw new NotImplementedException (); } - public override void Write (byte[] buffer, int offset, int count) + public override void Write (byte [] buffer, int offset, int count) { throw new NotImplementedException (); } -#endregion + #endregion } } diff --git a/StreamingAudio/StreamingPlayback.cs b/StreamingAudio/StreamingPlayback.cs index 480da7448..eefcf7d56 100644 --- a/StreamingAudio/StreamingPlayback.cs +++ b/StreamingAudio/StreamingPlayback.cs @@ -4,13 +4,11 @@ using System.Collections.Generic; using System.Linq; -namespace StreamingAudio -{ +namespace StreamingAudio { /// <summary> /// A Class to hold the AudioBuffer with all setting together /// </summary> - internal class AudioBuffer - { + internal class AudioBuffer { public IntPtr Buffer { get; set; } public List<AudioStreamPacketDescription> PacketDescriptions { get; set; } @@ -23,8 +21,7 @@ internal class AudioBuffer /// <summary> /// Wrapper around OutputQueue and AudioFileStream to allow streaming of various filetypes /// </summary> - public class StreamingPlayback : IDisposable - { + public class StreamingPlayback : IDisposable { public event EventHandler Finished; public event Action<OutputAudioQueue> OutputReady; @@ -44,7 +41,7 @@ public class StreamingPlayback : IDisposable public OutputAudioQueue OutputQueue; - public bool Started { get; private set; } + public bool Started { get; private set; } public float Volume { get { @@ -140,7 +137,7 @@ public void Play () /// <summary> /// Main methode to kick off the streaming, just send the bytes to this method /// </summary> - public void ParseBytes (byte[] buffer, int count, bool discontinuity, bool lastPacket) + public void ParseBytes (byte [] buffer, int count, bool discontinuity, bool lastPacket) { this.lastPacket = lastPacket; fileStream.ParseBytes (buffer, 0, count, discontinuity); @@ -160,7 +157,7 @@ protected virtual void Dispose (bool disposing) if (disposing) { if (OutputQueue != null) - OutputQueue.Stop(true); + OutputQueue.Stop (true); if (outputBuffers != null) { foreach (var b in outputBuffers) @@ -199,7 +196,7 @@ void AudioPacketDecoded (object sender, PacketReceivedEventArgs args) WaitForBuffer (); } - AudioQueue.FillAudioData (currentBuffer.Buffer, currentBuffer.CurrentOffset, args.InputData, (int)pd.StartOffset, pd.DataByteSize); + AudioQueue.FillAudioData (currentBuffer.Buffer, currentBuffer.CurrentOffset, args.InputData, (int) pd.StartOffset, pd.DataByteSize); // Set new offset for this packet pd.StartOffset = currentBuffer.CurrentOffset; // Add the packet to our Buffer diff --git a/SystemSound/SystemSound/AppDelegate.cs b/SystemSound/SystemSound/AppDelegate.cs index 6528baf39..112c6bffc 100644 --- a/SystemSound/SystemSound/AppDelegate.cs +++ b/SystemSound/SystemSound/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace SystemSound -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace SystemSound { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/SystemSound/SystemSound/Main.cs b/SystemSound/SystemSound/Main.cs index 02cc7d60e..58cfd7809 100644 --- a/SystemSound/SystemSound/Main.cs +++ b/SystemSound/SystemSound/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace SystemSound -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace SystemSound { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/SystemSound/SystemSound/ViewController.cs b/SystemSound/SystemSound/ViewController.cs index a22d89d6e..8a428e32a 100644 --- a/SystemSound/SystemSound/ViewController.cs +++ b/SystemSound/SystemSound/ViewController.cs @@ -1,39 +1,37 @@ -using Foundation; +using Foundation; using System; using UIKit; -namespace SystemSound -{ - public partial class ViewController : UIViewController - { - private AudioToolbox.SystemSound systemSound; +namespace SystemSound { + public partial class ViewController : UIViewController { + private AudioToolbox.SystemSound systemSound; - protected ViewController(IntPtr handle) : base(handle) { } + protected ViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - // Generate the SystemSound instance with the NSUrl - systemSound = new AudioToolbox.SystemSound(NSUrl.FromFilename("Sounds/tap.aif")); - } + // Generate the SystemSound instance with the NSUrl + systemSound = new AudioToolbox.SystemSound (NSUrl.FromFilename ("Sounds/tap.aif")); + } - partial void Vibrate(UIButton sender) - { - // Just vibrates the device - AudioToolbox.SystemSound.Vibrate.PlaySystemSound(); - } + partial void Vibrate (UIButton sender) + { + // Just vibrates the device + AudioToolbox.SystemSound.Vibrate.PlaySystemSound (); + } - partial void PlayAlert(UIButton sender) - { - // Plays the sound as well as vibrates - systemSound.PlayAlertSound(); - } + partial void PlayAlert (UIButton sender) + { + // Plays the sound as well as vibrates + systemSound.PlayAlertSound (); + } - partial void PlaySystem(UIButton sender) - { - // Plays the sound - systemSound.PlaySystemSound(); - } - } -} \ No newline at end of file + partial void PlaySystem (UIButton sender) + { + // Plays the sound + systemSound.PlaySystemSound (); + } + } +} diff --git a/TabbedImages/TabbedImages/AppDelegate.cs b/TabbedImages/TabbedImages/AppDelegate.cs index cefa4e980..bbda103fd 100644 --- a/TabbedImages/TabbedImages/AppDelegate.cs +++ b/TabbedImages/TabbedImages/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace TabbedImages -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace TabbedImages { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/TabbedImages/TabbedImages/FirstViewController.cs b/TabbedImages/TabbedImages/FirstViewController.cs index 163c6caeb..5378f0ada 100644 --- a/TabbedImages/TabbedImages/FirstViewController.cs +++ b/TabbedImages/TabbedImages/FirstViewController.cs @@ -1,16 +1,14 @@ using System; using UIKit; -namespace TabbedImages -{ - public partial class FirstViewController : UIViewController - { - public FirstViewController(IntPtr handle) : base(handle) { } +namespace TabbedImages { + public partial class FirstViewController : UIViewController { + public FirstViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.TabBarItem.Image = UIImage.FromBundle("first"); - } - } -} \ No newline at end of file + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.TabBarItem.Image = UIImage.FromBundle ("first"); + } + } +} diff --git a/TabbedImages/TabbedImages/Main.cs b/TabbedImages/TabbedImages/Main.cs index cf0c1b2a6..a60efba77 100644 --- a/TabbedImages/TabbedImages/Main.cs +++ b/TabbedImages/TabbedImages/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TabbedImages -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace TabbedImages { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/TabbedImages/TabbedImages/SecondViewController.cs b/TabbedImages/TabbedImages/SecondViewController.cs index 7a4aa3525..e37e471a9 100644 --- a/TabbedImages/TabbedImages/SecondViewController.cs +++ b/TabbedImages/TabbedImages/SecondViewController.cs @@ -1,16 +1,14 @@ using System; using UIKit; -namespace TabbedImages -{ - public partial class SecondViewController : UIViewController - { - public SecondViewController(IntPtr handle) : base(handle) { } +namespace TabbedImages { + public partial class SecondViewController : UIViewController { + public SecondViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.TabBarItem.Image = UIImage.FromFile("Images/second.png"); - } - } -} \ No newline at end of file + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.TabBarItem.Image = UIImage.FromFile ("Images/second.png"); + } + } +} diff --git a/TableEditing/TableEditing/AppDelegate.cs b/TableEditing/TableEditing/AppDelegate.cs index 97edc5b5e..b808e4811 100644 --- a/TableEditing/TableEditing/AppDelegate.cs +++ b/TableEditing/TableEditing/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace TableEditing -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace TableEditing { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/TableEditing/TableEditing/Main.cs b/TableEditing/TableEditing/Main.cs index b6ad35edb..71bea5db6 100644 --- a/TableEditing/TableEditing/Main.cs +++ b/TableEditing/TableEditing/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TableEditing -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace TableEditing { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/TableEditing/TableEditing/MainViewController.cs b/TableEditing/TableEditing/MainViewController.cs index aeb80fdec..9616072d8 100644 --- a/TableEditing/TableEditing/MainViewController.cs +++ b/TableEditing/TableEditing/MainViewController.cs @@ -4,269 +4,260 @@ using System.Collections.Generic; using UIKit; -namespace TableEditing -{ - public partial class MainViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource - { - private const string CellIdentifier = "CellIdentifier"; - - private readonly List<TableItemGroup> items = new List<TableItemGroup>(); - - public MainViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - FillItems(); - - doneButton.Enabled = false; - - tableView.Delegate = this; - tableView.DataSource = this; - } - - partial void EditClicked(UIBarButtonItem sender) - { - tableView.SetEditing(true, true); - editButton.Enabled = false; - doneButton.Enabled = true; - } - - partial void DoneClicked(UIBarButtonItem sender) - { - tableView.SetEditing(false, true); - editButton.Enabled = true; - doneButton.Enabled = false; - } - - private void FillItems() - { - //---- Section 1 - - var tableGroup = new TableItemGroup { Name = "Places" }; - tableGroup.Items.Add(new TableItem - { - ImageName = "Beach.png", - Heading = "Fiji", - SubHeading = "A nice beach" - }); - - tableGroup.Items.Add(new TableItem - { - ImageName = "Shanghai.png", - Heading = "Beijing", - SubHeading = "AKA Shanghai" - }); - - items.Add(tableGroup); - - //---- Section 2 - - tableGroup = new TableItemGroup { Name = "Other" }; - tableGroup.Items.Add(new TableItem - { - ImageName = "Seeds.png", - Heading = "Seedlings", - SubHeading = "Tiny Plants" - }); - - tableGroup.Items.Add(new TableItem - { - ImageName = "Plants.png", - Heading = "Plants", - SubHeading = "Green plants" - }); - - items.Add(tableGroup); - } - - #region -= data binding/display methods =- - - [Export("numberOfSectionsInTableView:")] - public nint NumberOfSections(UITableView tableView) - { - return items.Count; - } - - public nint RowsInSection(UITableView tableView, nint section) - { - return items[(int)section].Items.Count; - } - - [Export("tableView:titleForHeaderInSection:")] - public string TitleForHeader(UITableView tableView, nint section) - { - return items[(int)section].Name; - } - - #endregion - - #region -= user interaction methods =- - - [Export("tableView:didSelectRowAtIndexPath:")] - public void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var alert = UIAlertController.Create("Row Selected", items[indexPath.Section].Items[indexPath.Row].Heading, UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - PresentViewController(alert, true, null); - } - - [Export("tableView:didDeselectRowAtIndexPath:")] - public void RowDeselected(UITableView tableView, NSIndexPath indexPath) - { - Console.WriteLine($"Row {indexPath.Row} deselected"); - } - - [Export("tableView:accessoryButtonTappedForRowWithIndexPath:")] - public void AccessoryButtonTapped(UITableView tableView, NSIndexPath indexPath) - { - Console.WriteLine($"Accessory for Section, {indexPath.Section} and Row, {indexPath.Row} tapped"); - } - - #endregion - - #region -= editing methods =- - - /// <summary> - /// Called by the table view to determine whether or not the row is editable - /// </summary> - [Export("tableView:canEditRowAtIndexPath:")] - public bool CanEditRow(UITableView tableView, NSIndexPath indexPath) - { - return true; - } - - /// <summary> - /// Called by the table view to determine whether or not the row is moveable - /// </summary> - [Export("tableView:canMoveRowAtIndexPath:")] - public bool CanMoveRow(UITableView tableView, NSIndexPath indexPath) - { - return true; - } - - /// <summary> - /// Called by the table view to determine whether the editing control should be an insert - /// or a delete. - /// </summary> - [Export("tableView:editingStyleForRowAtIndexPath:")] - public UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath) - { - var result = UITableViewCellEditingStyle.Delete; - // WARNING: SPECIAL HANDLING HERE FOR THE SECOND ROW - // ALSO MEANS SWIPE-TO-DELETE DOESN'T WORK ON THAT ROW - if (indexPath.Section == 0 && indexPath.Row == 1) - { - return UITableViewCellEditingStyle.Insert; - } - - return result; - } - - /// <summary> - /// Custom text for delete button - /// </summary> - [Export("tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:")] - public string TitleForDeleteConfirmation(UITableView tableView, NSIndexPath indexPath) - { - return "Trash"; // instead of 'Delete' - } - - /// <summary> - /// Should be called CommitEditingAction or something, is called when a user initiates a specific editing event - /// </summary> - [Export("tableView:commitEditingStyle:forRowAtIndexPath:")] - public void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) - { - switch (editingStyle) - { - case UITableViewCellEditingStyle.Delete: - //---- remove the item from the underlying data source - items[indexPath.Section].Items.RemoveAt(indexPath.Row); - - //---- delete the row from the table - tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - - case UITableViewCellEditingStyle.Insert: - //---- create a new item and add it to our underlying data - items[indexPath.Section].Items.Insert(indexPath.Row, new TableItem { Heading = "(inserted)" }); - - //---- insert a new row in the table - tableView.InsertRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - - case UITableViewCellEditingStyle.None: - Console.WriteLine("CommitEditingStyle:None called"); - break; - } - } - - /// <summary> - /// called by the table view when a row is moved. - /// </summary> - [Export("tableView:moveRowAtIndexPath:toIndexPath:")] - public void MoveRow(UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) - { - //---- get a reference to the item - var item = items[sourceIndexPath.Section].Items[sourceIndexPath.Row]; - int deleteAt = sourceIndexPath.Row; - - //---- if we're moving within the same section, and we're inserting it before - if ((sourceIndexPath.Section == destinationIndexPath.Section) && (destinationIndexPath.Row < sourceIndexPath.Row)) - { - //---- add one to where we delete, because we're increasing the index by inserting - deleteAt = sourceIndexPath.Row + 1; - } - - //---- copy the item to the new location - items[destinationIndexPath.Section].Items.Insert(destinationIndexPath.Row, item); - - //---- remove from the old - items[sourceIndexPath.Section].Items.RemoveAt(deleteAt); - } - - /// <summary> - /// Called when the table goes into edit mode - /// </summary> - [Export("tableView:willBeginEditingRowAtIndexPath:")] - public void WillBeginEditing(UITableView tableView, NSIndexPath indexPath) - { - //---- start animations - tableView.BeginUpdates(); - - //---- do something if you need - - //---- end animations - tableView.EndUpdates(); - } - - /// <summary> - /// Called when the table leaves edit mode - /// </summary> - [Export("tableView:didEndEditingRowAtIndexPath:")] - public void DidEndEditing(UITableView tableView, NSIndexPath indexPath) - { - //---- start animations - tableView.BeginUpdates(); - - //---- do something if you need - - //---- finish animations - tableView.EndUpdates(); - } - - #endregion - - public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(CellIdentifier); - var item = items[indexPath.Section].Items[indexPath.Row]; - - cell.TextLabel.Text = item.Heading; - cell.ImageView.Image = !string.IsNullOrEmpty(item.ImageName) ? UIImage.FromBundle(item.ImageName) : null; - - return cell; - } - } -} \ No newline at end of file +namespace TableEditing { + public partial class MainViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource { + private const string CellIdentifier = "CellIdentifier"; + + private readonly List<TableItemGroup> items = new List<TableItemGroup> (); + + public MainViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + FillItems (); + + doneButton.Enabled = false; + + tableView.Delegate = this; + tableView.DataSource = this; + } + + partial void EditClicked (UIBarButtonItem sender) + { + tableView.SetEditing (true, true); + editButton.Enabled = false; + doneButton.Enabled = true; + } + + partial void DoneClicked (UIBarButtonItem sender) + { + tableView.SetEditing (false, true); + editButton.Enabled = true; + doneButton.Enabled = false; + } + + private void FillItems () + { + //---- Section 1 + + var tableGroup = new TableItemGroup { Name = "Places" }; + tableGroup.Items.Add (new TableItem { + ImageName = "Beach.png", + Heading = "Fiji", + SubHeading = "A nice beach" + }); + + tableGroup.Items.Add (new TableItem { + ImageName = "Shanghai.png", + Heading = "Beijing", + SubHeading = "AKA Shanghai" + }); + + items.Add (tableGroup); + + //---- Section 2 + + tableGroup = new TableItemGroup { Name = "Other" }; + tableGroup.Items.Add (new TableItem { + ImageName = "Seeds.png", + Heading = "Seedlings", + SubHeading = "Tiny Plants" + }); + + tableGroup.Items.Add (new TableItem { + ImageName = "Plants.png", + Heading = "Plants", + SubHeading = "Green plants" + }); + + items.Add (tableGroup); + } + + #region -= data binding/display methods =- + + [Export ("numberOfSectionsInTableView:")] + public nint NumberOfSections (UITableView tableView) + { + return items.Count; + } + + public nint RowsInSection (UITableView tableView, nint section) + { + return items [(int) section].Items.Count; + } + + [Export ("tableView:titleForHeaderInSection:")] + public string TitleForHeader (UITableView tableView, nint section) + { + return items [(int) section].Name; + } + + #endregion + + #region -= user interaction methods =- + + [Export ("tableView:didSelectRowAtIndexPath:")] + public void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var alert = UIAlertController.Create ("Row Selected", items [indexPath.Section].Items [indexPath.Row].Heading, UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + PresentViewController (alert, true, null); + } + + [Export ("tableView:didDeselectRowAtIndexPath:")] + public void RowDeselected (UITableView tableView, NSIndexPath indexPath) + { + Console.WriteLine ($"Row {indexPath.Row} deselected"); + } + + [Export ("tableView:accessoryButtonTappedForRowWithIndexPath:")] + public void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath) + { + Console.WriteLine ($"Accessory for Section, {indexPath.Section} and Row, {indexPath.Row} tapped"); + } + + #endregion + + #region -= editing methods =- + + /// <summary> + /// Called by the table view to determine whether or not the row is editable + /// </summary> + [Export ("tableView:canEditRowAtIndexPath:")] + public bool CanEditRow (UITableView tableView, NSIndexPath indexPath) + { + return true; + } + + /// <summary> + /// Called by the table view to determine whether or not the row is moveable + /// </summary> + [Export ("tableView:canMoveRowAtIndexPath:")] + public bool CanMoveRow (UITableView tableView, NSIndexPath indexPath) + { + return true; + } + + /// <summary> + /// Called by the table view to determine whether the editing control should be an insert + /// or a delete. + /// </summary> + [Export ("tableView:editingStyleForRowAtIndexPath:")] + public UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath) + { + var result = UITableViewCellEditingStyle.Delete; + // WARNING: SPECIAL HANDLING HERE FOR THE SECOND ROW + // ALSO MEANS SWIPE-TO-DELETE DOESN'T WORK ON THAT ROW + if (indexPath.Section == 0 && indexPath.Row == 1) { + return UITableViewCellEditingStyle.Insert; + } + + return result; + } + + /// <summary> + /// Custom text for delete button + /// </summary> + [Export ("tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:")] + public string TitleForDeleteConfirmation (UITableView tableView, NSIndexPath indexPath) + { + return "Trash"; // instead of 'Delete' + } + + /// <summary> + /// Should be called CommitEditingAction or something, is called when a user initiates a specific editing event + /// </summary> + [Export ("tableView:commitEditingStyle:forRowAtIndexPath:")] + public void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) + { + switch (editingStyle) { + case UITableViewCellEditingStyle.Delete: + //---- remove the item from the underlying data source + items [indexPath.Section].Items.RemoveAt (indexPath.Row); + + //---- delete the row from the table + tableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + + case UITableViewCellEditingStyle.Insert: + //---- create a new item and add it to our underlying data + items [indexPath.Section].Items.Insert (indexPath.Row, new TableItem { Heading = "(inserted)" }); + + //---- insert a new row in the table + tableView.InsertRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + + case UITableViewCellEditingStyle.None: + Console.WriteLine ("CommitEditingStyle:None called"); + break; + } + } + + /// <summary> + /// called by the table view when a row is moved. + /// </summary> + [Export ("tableView:moveRowAtIndexPath:toIndexPath:")] + public void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) + { + //---- get a reference to the item + var item = items [sourceIndexPath.Section].Items [sourceIndexPath.Row]; + int deleteAt = sourceIndexPath.Row; + + //---- if we're moving within the same section, and we're inserting it before + if ((sourceIndexPath.Section == destinationIndexPath.Section) && (destinationIndexPath.Row < sourceIndexPath.Row)) { + //---- add one to where we delete, because we're increasing the index by inserting + deleteAt = sourceIndexPath.Row + 1; + } + + //---- copy the item to the new location + items [destinationIndexPath.Section].Items.Insert (destinationIndexPath.Row, item); + + //---- remove from the old + items [sourceIndexPath.Section].Items.RemoveAt (deleteAt); + } + + /// <summary> + /// Called when the table goes into edit mode + /// </summary> + [Export ("tableView:willBeginEditingRowAtIndexPath:")] + public void WillBeginEditing (UITableView tableView, NSIndexPath indexPath) + { + //---- start animations + tableView.BeginUpdates (); + + //---- do something if you need + + //---- end animations + tableView.EndUpdates (); + } + + /// <summary> + /// Called when the table leaves edit mode + /// </summary> + [Export ("tableView:didEndEditingRowAtIndexPath:")] + public void DidEndEditing (UITableView tableView, NSIndexPath indexPath) + { + //---- start animations + tableView.BeginUpdates (); + + //---- do something if you need + + //---- finish animations + tableView.EndUpdates (); + } + + #endregion + + public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (CellIdentifier); + var item = items [indexPath.Section].Items [indexPath.Row]; + + cell.TextLabel.Text = item.Heading; + cell.ImageView.Image = !string.IsNullOrEmpty (item.ImageName) ? UIImage.FromBundle (item.ImageName) : null; + + return cell; + } + } +} diff --git a/TableEditing/TableEditing/Models/TableItem.cs b/TableEditing/TableEditing/Models/TableItem.cs index 2342fa6c6..28e5bf498 100755 --- a/TableEditing/TableEditing/Models/TableItem.cs +++ b/TableEditing/TableEditing/Models/TableItem.cs @@ -1,15 +1,13 @@ -namespace TableEditing.Models -{ - /// <summary> - /// Represents our item in the table - /// </summary> - public class TableItem - { - public string Heading { get; set; } +namespace TableEditing.Models { + /// <summary> + /// Represents our item in the table + /// </summary> + public class TableItem { + public string Heading { get; set; } - public string SubHeading { get; set; } + public string SubHeading { get; set; } - public string ImageName { get; set; } - } -} \ No newline at end of file + public string ImageName { get; set; } + } +} diff --git a/TableEditing/TableEditing/Models/TableItemGroup.cs b/TableEditing/TableEditing/Models/TableItemGroup.cs index 83c870694..35d7b536a 100755 --- a/TableEditing/TableEditing/Models/TableItemGroup.cs +++ b/TableEditing/TableEditing/Models/TableItemGroup.cs @@ -1,16 +1,14 @@ using System.Collections.Generic; -namespace TableEditing.Models -{ - /// <summary> - /// A group that contains table items - /// </summary> - public class TableItemGroup - { - public string Name { get; set; } +namespace TableEditing.Models { + /// <summary> + /// A group that contains table items + /// </summary> + public class TableItemGroup { + public string Name { get; set; } - public string Footer { get; set; } + public string Footer { get; set; } - public List<TableItem> Items { get; private set; } = new List<TableItem>(); - } -} \ No newline at end of file + public List<TableItem> Items { get; private set; } = new List<TableItem> (); + } +} diff --git a/TableParts/TableParts/AppDelegate.cs b/TableParts/TableParts/AppDelegate.cs index 7037484ad..5130c63c2 100644 --- a/TableParts/TableParts/AppDelegate.cs +++ b/TableParts/TableParts/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace TableParts -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace TableParts { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/TableParts/TableParts/Main.cs b/TableParts/TableParts/Main.cs index 33d9d15a1..99ce78bee 100644 --- a/TableParts/TableParts/Main.cs +++ b/TableParts/TableParts/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TableParts -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace TableParts { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/TableParts/TableParts/MainViewController.cs b/TableParts/TableParts/MainViewController.cs index 3764022d8..56b500931 100644 --- a/TableParts/TableParts/MainViewController.cs +++ b/TableParts/TableParts/MainViewController.cs @@ -4,86 +4,84 @@ using System.Collections.Generic; using UIKit; -namespace TableParts -{ - public partial class MainViewController : UITableViewController - { - private const string CellIdentifier = "TableCell"; - - private readonly List<TableItemGroup> items = new List<TableItemGroup>(); - - public MainViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - CreateTableItems(); - } - - protected void CreateTableItems() - { - // Section 1 - var group = new TableItemGroup() { Name = "Section 0 Header", Footer = "Section 0 Footer" }; - group.Items.Add("Row 0"); - group.Items.Add("Row 1"); - group.Items.Add("Row 2"); - items.Add(group); - - // Section 2 - group = new TableItemGroup() { Name = "Section 1 Header", Footer = "Section 1 Footer" }; - group.Items.Add("Row 0"); - group.Items.Add("Row 1"); - group.Items.Add("Row 2"); - items.Add(group); - - // Section 3 - group = new TableItemGroup() { Name = "Section 2 Header", Footer = "Section 2 Footer" }; - group.Items.Add("Row 0"); - group.Items.Add("Row 1"); - group.Items.Add("Row 2"); - items.Add(group); - } - - public override nint NumberOfSections(UITableView tableView) - { - return items.Count; - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return items[(int)section].Items.Count; - } - - public override string TitleForHeader(UITableView tableView, nint section) - { - return items[(int)section].Name; - } - - public override string TitleForFooter(UITableView tableView, nint section) - { - return items[(int)section].Footer; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var alert = UIAlertController.Create("Row Selected", items[indexPath.Section].Items[indexPath.Row], UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - PresentViewController(alert, true, null); - } - - public override void RowDeselected(UITableView tableView, NSIndexPath indexPath) - { - Console.WriteLine($"Row {indexPath.Row} deselected"); - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - Console.WriteLine($"Calling 'GetCell', 'isEditing': {tableView.Editing}"); - - var cell = tableView.DequeueReusableCell(CellIdentifier); - cell.TextLabel.Text = items[indexPath.Section].Items[indexPath.Row]; - - return cell; - } - } -} \ No newline at end of file +namespace TableParts { + public partial class MainViewController : UITableViewController { + private const string CellIdentifier = "TableCell"; + + private readonly List<TableItemGroup> items = new List<TableItemGroup> (); + + public MainViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + CreateTableItems (); + } + + protected void CreateTableItems () + { + // Section 1 + var group = new TableItemGroup () { Name = "Section 0 Header", Footer = "Section 0 Footer" }; + group.Items.Add ("Row 0"); + group.Items.Add ("Row 1"); + group.Items.Add ("Row 2"); + items.Add (group); + + // Section 2 + group = new TableItemGroup () { Name = "Section 1 Header", Footer = "Section 1 Footer" }; + group.Items.Add ("Row 0"); + group.Items.Add ("Row 1"); + group.Items.Add ("Row 2"); + items.Add (group); + + // Section 3 + group = new TableItemGroup () { Name = "Section 2 Header", Footer = "Section 2 Footer" }; + group.Items.Add ("Row 0"); + group.Items.Add ("Row 1"); + group.Items.Add ("Row 2"); + items.Add (group); + } + + public override nint NumberOfSections (UITableView tableView) + { + return items.Count; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return items [(int) section].Items.Count; + } + + public override string TitleForHeader (UITableView tableView, nint section) + { + return items [(int) section].Name; + } + + public override string TitleForFooter (UITableView tableView, nint section) + { + return items [(int) section].Footer; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var alert = UIAlertController.Create ("Row Selected", items [indexPath.Section].Items [indexPath.Row], UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + PresentViewController (alert, true, null); + } + + public override void RowDeselected (UITableView tableView, NSIndexPath indexPath) + { + Console.WriteLine ($"Row {indexPath.Row} deselected"); + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + Console.WriteLine ($"Calling 'GetCell', 'isEditing': {tableView.Editing}"); + + var cell = tableView.DequeueReusableCell (CellIdentifier); + cell.TextLabel.Text = items [indexPath.Section].Items [indexPath.Row]; + + return cell; + } + } +} diff --git a/TableParts/TableParts/Models/TableItemGroup.cs b/TableParts/TableParts/Models/TableItemGroup.cs index 4841f31b0..91c1f49bb 100755 --- a/TableParts/TableParts/Models/TableItemGroup.cs +++ b/TableParts/TableParts/Models/TableItemGroup.cs @@ -1,17 +1,15 @@ using System; using System.Collections.Generic; -namespace TableParts.Models -{ - /// <summary> - /// A group that contains table items - /// </summary> - public class TableItemGroup - { - public string Name { get; set; } +namespace TableParts.Models { + /// <summary> + /// A group that contains table items + /// </summary> + public class TableItemGroup { + public string Name { get; set; } - public string Footer { get; set; } + public string Footer { get; set; } - public List<string> Items { get; private set; } = new List<string>(); - } -} \ No newline at end of file + public List<string> Items { get; private set; } = new List<string> (); + } +} diff --git a/TableSwipeActions/TableRowActions/AppDelegate.cs b/TableSwipeActions/TableRowActions/AppDelegate.cs index d685ffa06..41d98ec55 100644 --- a/TableSwipeActions/TableRowActions/AppDelegate.cs +++ b/TableSwipeActions/TableRowActions/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace TableRowActions -{ +namespace TableRowActions { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/TableSwipeActions/TableRowActions/DisplayViewController.cs b/TableSwipeActions/TableRowActions/DisplayViewController.cs index 5a079aa28..511677a2d 100644 --- a/TableSwipeActions/TableRowActions/DisplayViewController.cs +++ b/TableSwipeActions/TableRowActions/DisplayViewController.cs @@ -1,127 +1,123 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using System.IO; using System.Collections.Generic; -namespace TableRowActions -{ - public partial class DisplayViewController : UITableViewController - { - public DisplayViewController (IntPtr handle) : base (handle) - { - } - - List<string> words = new List<string>(); - bool hasViewedAlert = false; - - public override void ViewDidLoad() +namespace TableRowActions { + public partial class DisplayViewController : UITableViewController { + public DisplayViewController (IntPtr handle) : base (handle) { - base.ViewDidLoad(); - - var lines = File.ReadLines("word-list.txt"); - - foreach (var l in lines) - { - words.Add(l); - } - } - - public override nint RowsInSection(UITableView tableView, nint section) + } + + List<string> words = new List<string> (); + bool hasViewedAlert = false; + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var lines = File.ReadLines ("word-list.txt"); + + foreach (var l in lines) { + words.Add (l); + } + } + + public override nint RowsInSection (UITableView tableView, nint section) { return words.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - string item = words[indexPath.Row]; - - UITableViewCell cell = tableView.DequeueReusableCell("displaycell"); - cell = cell ?? new UITableViewCell(UITableViewCellStyle.Default, "displaycell"); - - cell.TextLabel.Text = item; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + string item = words [indexPath.Row]; + + UITableViewCell cell = tableView.DequeueReusableCell ("displaycell"); + cell = cell ?? new UITableViewCell (UITableViewCellStyle.Default, "displaycell"); + + cell.TextLabel.Text = item; return cell; - } - - public override void CommitEditingStyle(UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) + } + + public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { - switch (editingStyle) - { - case UITableViewCellEditingStyle.Delete: - // remove the item from the underlying data source - words.RemoveAt(indexPath.Row); - // delete the row from the table - tableView.DeleteRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - case UITableViewCellEditingStyle.None: - Console.WriteLine("CommitEditingStyle:None called"); - break; + switch (editingStyle) { + case UITableViewCellEditingStyle.Delete: + // remove the item from the underlying data source + words.RemoveAt (indexPath.Row); + // delete the row from the table + tableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + case UITableViewCellEditingStyle.None: + Console.WriteLine ("CommitEditingStyle:None called"); + break; } - } - - public override bool CanEditRow(UITableView tableView, NSIndexPath indexPath) + } + + public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { return true; - } - - public override string TitleForDeleteConfirmation(UITableView tableView, NSIndexPath indexPath) + } + + public override string TitleForDeleteConfirmation (UITableView tableView, NSIndexPath indexPath) { return "I know this word."; } - public override UISwipeActionsConfiguration GetLeadingSwipeActionsConfiguration(UITableView tableView, NSIndexPath indexPath) - { - var definitionAction = ContextualDefinitionAction(indexPath.Row); - var flagAction = ContextualFlagAction(indexPath.Row); - var leadingSwipe = UISwipeActionsConfiguration.FromActions(new UIContextualAction[] { flagAction, definitionAction }); - - leadingSwipe.PerformsFirstActionWithFullSwipe = false; - return leadingSwipe; - } - - public UIContextualAction ContextualDefinitionAction(int row) - { - string word = words[row]; - - var action = UIContextualAction.FromContextualActionStyle(UIContextualActionStyle.Normal, + public override UISwipeActionsConfiguration GetLeadingSwipeActionsConfiguration (UITableView tableView, NSIndexPath indexPath) + { + var definitionAction = ContextualDefinitionAction (indexPath.Row); + var flagAction = ContextualFlagAction (indexPath.Row); + var leadingSwipe = UISwipeActionsConfiguration.FromActions (new UIContextualAction [] { flagAction, definitionAction }); + + leadingSwipe.PerformsFirstActionWithFullSwipe = false; + return leadingSwipe; + } + + public UIContextualAction ContextualDefinitionAction (int row) + { + string word = words [row]; + + var action = UIContextualAction.FromContextualActionStyle (UIContextualActionStyle.Normal, "Definition", (ReadLaterAction, view, success) => { - var def = new UIReferenceLibraryViewController(word); + var def = new UIReferenceLibraryViewController (word); - var alertController = UIAlertController.Create("No Dictionary Installed", "To install a Dictionary, Select Definition again, click `Manage` on the next screen and select a dictionary to download", UIAlertControllerStyle.Alert); - alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + var alertController = UIAlertController.Create ("No Dictionary Installed", "To install a Dictionary, Select Definition again, click `Manage` on the next screen and select a dictionary to download", UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); - if (UIReferenceLibraryViewController.DictionaryHasDefinitionForTerm(word) || hasViewedAlert == true){ - PresentViewController(def, true, null); - success(true); - }else{ - PresentViewController(alertController, true, null); + if (UIReferenceLibraryViewController.DictionaryHasDefinitionForTerm (word) || hasViewedAlert == true) { + PresentViewController (def, true, null); + success (true); + } else { + PresentViewController (alertController, true, null); hasViewedAlert = true; - success(false); - } - }); - action.BackgroundColor = UIColor.Orange; - return action; - } - - public UIContextualAction ContextualFlagAction(int row) - { - var action = UIContextualAction.FromContextualActionStyle(UIContextualActionStyle.Normal, + success (false); + } + }); + action.BackgroundColor = UIColor.Orange; + return action; + } + + public UIContextualAction ContextualFlagAction (int row) + { + var action = UIContextualAction.FromContextualActionStyle (UIContextualActionStyle.Normal, "Flag", (FlagAction, view, success) => { - var alertController = UIAlertController.Create($"Report {words[row]}?", "", UIAlertControllerStyle.Alert); - alertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null)); - alertController.AddAction(UIAlertAction.Create("Yes", UIAlertActionStyle.Destructive, null)); - PresentViewController(alertController, true, null); - - success(true); - }); - - action.Image = UIImage.FromFile("feedback.png"); - action.BackgroundColor = UIColor.Blue; - - return action; - } - } -} \ No newline at end of file + var alertController = UIAlertController.Create ($"Report {words [row]}?", "", UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null)); + alertController.AddAction (UIAlertAction.Create ("Yes", UIAlertActionStyle.Destructive, null)); + PresentViewController (alertController, true, null); + + success (true); + }); + + action.Image = UIImage.FromFile ("feedback.png"); + action.BackgroundColor = UIColor.Blue; + + return action; + } + } +} diff --git a/TableSwipeActions/TableRowActions/Main.cs b/TableSwipeActions/TableRowActions/Main.cs index 33aa7e4f4..c02460317 100644 --- a/TableSwipeActions/TableRowActions/Main.cs +++ b/TableSwipeActions/TableRowActions/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TableRowActions -{ - public class Application - { +namespace TableRowActions { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/TextKitDemo/TextKitDemo/AppDelegate.cs b/TextKitDemo/TextKitDemo/AppDelegate.cs index 6144939ed..1098c49d0 100644 --- a/TextKitDemo/TextKitDemo/AppDelegate.cs +++ b/TextKitDemo/TextKitDemo/AppDelegate.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ +namespace TextKitDemo { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -16,7 +14,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/TextKitDemo/TextKitDemo/BasicInteractionViewController.cs b/TextKitDemo/TextKitDemo/BasicInteractionViewController.cs index 88faf3314..7c1b81adf 100644 --- a/TextKitDemo/TextKitDemo/BasicInteractionViewController.cs +++ b/TextKitDemo/TextKitDemo/BasicInteractionViewController.cs @@ -3,14 +3,12 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ +namespace TextKitDemo { /* * Provides the basic interaction (respond to tapping on the apple.com url and * updating the font size in response to changes in the UI). */ - public partial class BasicInteractionViewController : TextViewController - { + public partial class BasicInteractionViewController : TextViewController { public BasicInteractionViewController (IntPtr handle) : base (handle) { } @@ -30,8 +28,9 @@ public override void ViewDidLoad () bool ShouldInteractWithUrl (UITextView textView, NSUrl url, NSRange characterRange) { if (url.Host == "www.xamarin.com") { - var webViewController = (WebViewController)Storyboard.InstantiateViewController ("WebViewController"); - PresentViewController (webViewController, true, delegate { + var webViewController = (WebViewController) Storyboard.InstantiateViewController ("WebViewController"); + PresentViewController (webViewController, true, delegate + { webViewController.webView.LoadRequest (NSUrlRequest.FromUrl (url)); }); return false; diff --git a/TextKitDemo/TextKitDemo/CollectionViewCell.cs b/TextKitDemo/TextKitDemo/CollectionViewCell.cs index b78405fd2..f17e3a3ca 100644 --- a/TextKitDemo/TextKitDemo/CollectionViewCell.cs +++ b/TextKitDemo/TextKitDemo/CollectionViewCell.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ - public partial class CollectionViewCell : UICollectionViewCell - { +namespace TextKitDemo { + public partial class CollectionViewCell : UICollectionViewCell { public CollectionViewCell (IntPtr handle) : base (handle) { Initialize (); @@ -24,7 +22,8 @@ void Initialize () BackgroundColor = UIColor.DarkGray; Layer.CornerRadius = 5; - UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate { + UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate + { CalculateAndSetFonts (); }); } diff --git a/TextKitDemo/TextKitDemo/CollectionViewController.cs b/TextKitDemo/TextKitDemo/CollectionViewController.cs index d624a4419..8a7e04b15 100644 --- a/TextKitDemo/TextKitDemo/CollectionViewController.cs +++ b/TextKitDemo/TextKitDemo/CollectionViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ - public partial class CollectionViewController : UICollectionViewController - { +namespace TextKitDemo { + public partial class CollectionViewController : UICollectionViewController { NSString key = new NSString ("collectionViewCell"); public CollectionViewController (IntPtr handle) : base (handle) @@ -27,7 +25,7 @@ public override void ViewWillAppear (bool animated) foreach (CollectionViewCell cell in CollectionView.VisibleCells) { var indexPath = CollectionView.IndexPathForCell (cell); - cell.FormatCell (DemoModel.GetDemo(indexPath)); + cell.FormatCell (DemoModel.GetDemo (indexPath)); } } diff --git a/TextKitDemo/TextKitDemo/DemoModel.cs b/TextKitDemo/TextKitDemo/DemoModel.cs index a1c36cff6..c70044107 100644 --- a/TextKitDemo/TextKitDemo/DemoModel.cs +++ b/TextKitDemo/TextKitDemo/DemoModel.cs @@ -5,13 +5,11 @@ using UIKit; using CoreText; -namespace TextKitDemo -{ +namespace TextKitDemo { /* * Our simple data model, contains the various demos that we will display. */ - public class DemoModel - { + public class DemoModel { public static List<DemoModel> Demos = new List<DemoModel> () { new DemoModel ("Basic Interaction", "BasicInteractionViewController", "Basic Interaction.rtf"), new DemoModel ("Exclusion Paths", "ExclusionPathsViewController", "Exclusion Paths.rtf"), @@ -20,7 +18,7 @@ public class DemoModel }; public string Title { get; set; } - public string ViewControllerIdentifier { get; set;} + public string ViewControllerIdentifier { get; set; } string TextStoragePath; NSAttributedString AttributedText; @@ -35,7 +33,7 @@ public DemoModel (string title, string identifier, string path) public static DemoModel GetDemo (NSIndexPath indexPath) { - return Demos[indexPath.Row]; + return Demos [indexPath.Row]; } public NSAttributedString GetAttributedText () @@ -60,7 +58,7 @@ public NSAttributedString GetAttributedText () attributedTextHolder.AddAttributes (new UIStringAttributes () { Font = UIFont.PreferredBody }, new NSRange (0, attributedTextHolder.Length)); - AttributedText = (NSAttributedString)attributedTextHolder.Copy (); + AttributedText = (NSAttributedString) attributedTextHolder.Copy (); } else { string newFlatText = new NSAttributedString (new NSUrl (path, false), null, ref error).Value; AttributedText = new NSAttributedString (newFlatText, font: UIFont.PreferredBody); diff --git a/TextKitDemo/TextKitDemo/ExclusionPathsViewController.cs b/TextKitDemo/TextKitDemo/ExclusionPathsViewController.cs index d5e5d25f7..0e69827d0 100644 --- a/TextKitDemo/TextKitDemo/ExclusionPathsViewController.cs +++ b/TextKitDemo/TextKitDemo/ExclusionPathsViewController.cs @@ -5,15 +5,13 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ +namespace TextKitDemo { /* * Implements the ExclusionPaths view, which shows how a bezier can be used * to alter the flow of the rendered text. */ - public partial class ExclusionPathsViewController : TextViewController - { - UIBezierPath originalButterflyPath = (UIBezierPath)NSKeyedUnarchiver.UnarchiveFile ("butterflyPath.plist"); + public partial class ExclusionPathsViewController : TextViewController { + UIBezierPath originalButterflyPath = (UIBezierPath) NSKeyedUnarchiver.UnarchiveFile ("butterflyPath.plist"); CGPoint gestureStartingPoint; CGPoint gestureStartingCenter; @@ -51,9 +49,8 @@ void HandlePanGesture (UIPanGestureRecognizer gesture) if (gesture.State == UIGestureRecognizerState.Began) { gestureStartingPoint = gesture.TranslationInView (textView); gestureStartingCenter = imageView.Center; - } - else if (gesture.State == UIGestureRecognizerState.Changed) { - CGPoint currentPoint = gesture.TranslationInView(textView); + } else if (gesture.State == UIGestureRecognizerState.Changed) { + CGPoint currentPoint = gesture.TranslationInView (textView); nfloat distanceX = currentPoint.X - gestureStartingPoint.X; nfloat distanceY = currentPoint.Y - gestureStartingPoint.Y; @@ -65,18 +62,17 @@ void HandlePanGesture (UIPanGestureRecognizer gesture) imageView.Center = newCenter; textView.TextContainer.ExclusionPaths = TranslatedBezierPath (); - } - else if (gesture.State == UIGestureRecognizerState.Ended) { - gestureStartingPoint = new CGPoint (0, 0); + } else if (gesture.State == UIGestureRecognizerState.Ended) { + gestureStartingPoint = new CGPoint (0, 0); gestureStartingCenter = new CGPoint (0, 0); } } - UIBezierPath[] TranslatedBezierPath () + UIBezierPath [] TranslatedBezierPath () { CGRect butterflyImageRect = textView.ConvertRectFromView (imageView.Frame, View); - UIBezierPath[] newButterflyPath = new UIBezierPath[1]; - newButterflyPath [0] = (UIBezierPath)((NSObject)originalButterflyPath).Copy (); + UIBezierPath [] newButterflyPath = new UIBezierPath [1]; + newButterflyPath [0] = (UIBezierPath) ((NSObject) originalButterflyPath).Copy (); newButterflyPath [0].ApplyTransform (CGAffineTransform.MakeTranslation (butterflyImageRect.X, butterflyImageRect.Y)); return newButterflyPath; } diff --git a/TextKitDemo/TextKitDemo/Font.cs b/TextKitDemo/TextKitDemo/Font.cs index a9a2234f0..e9bc6520c 100644 --- a/TextKitDemo/TextKitDemo/Font.cs +++ b/TextKitDemo/TextKitDemo/Font.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ - public static class Font - { +namespace TextKitDemo { + public static class Font { public static UIFont GetPreferredFont (NSString textStyle, float scale) { UIFontDescriptor tmp = UIFontDescriptor.GetPreferredDescriptorForTextStyle (textStyle); diff --git a/TextKitDemo/TextKitDemo/InteractiveTextColoringTextStorage.cs b/TextKitDemo/TextKitDemo/InteractiveTextColoringTextStorage.cs index f3c00b74f..0cf1b11d1 100644 --- a/TextKitDemo/TextKitDemo/InteractiveTextColoringTextStorage.cs +++ b/TextKitDemo/TextKitDemo/InteractiveTextColoringTextStorage.cs @@ -5,13 +5,11 @@ using UIKit; using CoreText; -namespace TextKitDemo -{ +namespace TextKitDemo { /* * Shows how to use color specific portions of a buffer. */ - public class InteractiveTextColoringTextStorage : NSTextStorage - { + public class InteractiveTextColoringTextStorage : NSTextStorage { public Dictionary<string, NSDictionary> Tokens; NSMutableAttributedString backingStore; bool dynamicTextNeedsUpdate; @@ -54,27 +52,27 @@ void PerformReplacementsForCharacterChange (NSRange changeRange) if (changeRange.Location == 0 && changeRange.Length == 0) return; - var searchRange = new NSRange (0,Value.Length); - int startLoc = Value.Substring (0, (int)changeRange.Location).LastIndexOfAny (" \n\t.".ToCharArray ()); - int endLoc = Value.Substring ((int)(changeRange.Location + changeRange.Length)).IndexOfAny (" \n\t.".ToCharArray ()); - if(startLoc != -1) + var searchRange = new NSRange (0, Value.Length); + int startLoc = Value.Substring (0, (int) changeRange.Location).LastIndexOfAny (" \n\t.".ToCharArray ()); + int endLoc = Value.Substring ((int) (changeRange.Location + changeRange.Length)).IndexOfAny (" \n\t.".ToCharArray ()); + if (startLoc != -1) searchRange.Location = startLoc; if (endLoc != -1) searchRange.Length = changeRange.Location + endLoc + 1 - startLoc; else searchRange.Length = searchRange.Length - searchRange.Location; - searchRange.Location = Math.Min ((int)searchRange.Location, (int)changeRange.Location); - searchRange.Length = Math.Max ((int)searchRange.Length, (int)changeRange.Length); + searchRange.Location = Math.Min ((int) searchRange.Location, (int) changeRange.Location); + searchRange.Length = Math.Max ((int) searchRange.Length, (int) changeRange.Length); ApplyTokenAttributes (searchRange); } void ApplyTokenAttributes (NSRange searchRange) { NSDictionary attributesForToken = Tokens ["DefaultTokenName"]; - int startPos = (int)searchRange.Location; + int startPos = (int) searchRange.Location; - string text = backingStore.Value.Substring ((int)searchRange.Location,(int)searchRange.Length); + string text = backingStore.Value.Substring ((int) searchRange.Location, (int) searchRange.Length); int nextSpace = text.IndexOfAny (" \n\t.".ToCharArray ()); int lastPos = 0; string token; diff --git a/TextKitDemo/TextKitDemo/InteractiveTextColoringViewController.cs b/TextKitDemo/TextKitDemo/InteractiveTextColoringViewController.cs index 92308f0e9..168c1f95c 100644 --- a/TextKitDemo/TextKitDemo/InteractiveTextColoringViewController.cs +++ b/TextKitDemo/TextKitDemo/InteractiveTextColoringViewController.cs @@ -6,13 +6,11 @@ using UIKit; using CoreText; -namespace TextKitDemo -{ +namespace TextKitDemo { /* * The view controller for the inteactive color sample. */ - public partial class InteractiveTextColoringViewController : TextViewController - { + public partial class InteractiveTextColoringViewController : TextViewController { InteractiveTextColoringTextStorage textStorage; public InteractiveTextColoringViewController (IntPtr handle) : base (handle) @@ -36,7 +34,7 @@ public override void ViewDidLoad () var newTextView = new UITextView (newTextViewRect, container); newTextView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth; - newTextView.ScrollEnabled = true; + newTextView.ScrollEnabled = true; newTextView.KeyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag; View.Add (newTextView); @@ -50,7 +48,7 @@ public override void ViewDidLoad () SetText (); } - void SetText() + void SetText () { textStorage.BeginEditing (); if (model != null) @@ -58,7 +56,7 @@ void SetText() else textStorage.SetString (new NSAttributedString ("Alice was beginning to get very tired of sitting " + "by her sister on the bank, and of having nothing to do: once or twice she had peeped into the " + - "book her sister was reading, but it had no pictures or conversations in it, 'and what is the " + + "book her sister was reading, but it had no pictures or conversations in it, 'and what is the " + "use of a book,' thought Alice 'without pictures or conversation?'\n\nSo she was considering " + "in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), " + "whether the pleasure of making a daisy-chain would be worth the trouble of getting up and " + diff --git a/TextKitDemo/TextKitDemo/Main.cs b/TextKitDemo/TextKitDemo/Main.cs index dd1bbd4b5..b2574a301 100644 --- a/TextKitDemo/TextKitDemo/Main.cs +++ b/TextKitDemo/TextKitDemo/Main.cs @@ -4,10 +4,8 @@ using MonoTouch.Foundation; using MonoTouch.UIKit; -namespace TextKitDemo -{ - public class Application - { +namespace TextKitDemo { + public class Application { // This is the main entry point of the application. } } diff --git a/TextKitDemo/TextKitDemo/PersonViewController.cs b/TextKitDemo/TextKitDemo/PersonViewController.cs index f94519e29..42c06efe6 100644 --- a/TextKitDemo/TextKitDemo/PersonViewController.cs +++ b/TextKitDemo/TextKitDemo/PersonViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ - public partial class PersonViewController : TextViewController - { +namespace TextKitDemo { + public partial class PersonViewController : TextViewController { public PersonViewController (IntPtr handle) : base (handle) { } diff --git a/TextKitDemo/TextKitDemo/TextViewController.cs b/TextKitDemo/TextKitDemo/TextViewController.cs index 8898d4b94..df612d550 100644 --- a/TextKitDemo/TextKitDemo/TextViewController.cs +++ b/TextKitDemo/TextKitDemo/TextViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ - public class TextViewController : UIViewController - { +namespace TextKitDemo { + public class TextViewController : UIViewController { public DemoModel model; NSObject notification; @@ -25,7 +23,8 @@ public override void ViewDidAppear (bool animated) if (notification != null) notification.Dispose (); - notification = UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate { + notification = UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate + { PreferredContentSizeChanged (); }); } diff --git a/TextKitDemo/TextKitDemo/WebViewController.cs b/TextKitDemo/TextKitDemo/WebViewController.cs index 6fea7b0ea..407c14ff6 100644 --- a/TextKitDemo/TextKitDemo/WebViewController.cs +++ b/TextKitDemo/TextKitDemo/WebViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace TextKitDemo -{ - public partial class WebViewController : UIViewController - { +namespace TextKitDemo { + public partial class WebViewController : UIViewController { public WebViewController (IntPtr handle) : base (handle) { } @@ -26,15 +24,14 @@ public override void ViewDidLoad () }; doneButton.Clicked += (sender, e) => { - DismissViewController(true,null); + DismissViewController (true, null); }; toolBar.Delegate = new MyUIToolbarDelegate (); } } - public class MyUIToolbarDelegate : UIToolbarDelegate - { + public class MyUIToolbarDelegate : UIToolbarDelegate { public MyUIToolbarDelegate () : base () { } diff --git a/ThreadedCoreData/ThreadedCoreData/APLEarthquakeTableViewCell.cs b/ThreadedCoreData/ThreadedCoreData/APLEarthquakeTableViewCell.cs index 4159f439f..d7a45952a 100644 --- a/ThreadedCoreData/ThreadedCoreData/APLEarthquakeTableViewCell.cs +++ b/ThreadedCoreData/ThreadedCoreData/APLEarthquakeTableViewCell.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace ThreadedCoreData -{ +namespace ThreadedCoreData { [Register ("APLEarthquakeTableViewCell")] - public partial class APLEarthquakeTableViewCell : UITableViewCell - { + public partial class APLEarthquakeTableViewCell : UITableViewCell { public static readonly NSString Key = new NSString ("EarthquakeCellID"); public static readonly UINib Nib; NSDateFormatter dateFormatter; @@ -38,14 +36,14 @@ public APLEarthquakeTableViewCell (IntPtr handle) : base (handle) public static APLEarthquakeTableViewCell Create () { - return (APLEarthquakeTableViewCell)Nib.Instantiate (null, null) [0]; + return (APLEarthquakeTableViewCell) Nib.Instantiate (null, null) [0]; } - public void ConfigureWithEarthquake(ManagedEarthquake earthquake) + public void ConfigureWithEarthquake (ManagedEarthquake earthquake) { locationLabel.Text = earthquake.Location; dateLabel.Text = DateFormatter.StringFor (earthquake.Date); - magnitudeLabel.Text = string.Format("{0:#.#}", earthquake.Magnitude); + magnitudeLabel.Text = string.Format ("{0:#.#}", earthquake.Magnitude); magnitudeImage.Image = ImageForMagnitude (earthquake.Magnitude.FloatValue); } diff --git a/ThreadedCoreData/ThreadedCoreData/APLParseOperation.cs b/ThreadedCoreData/ThreadedCoreData/APLParseOperation.cs index 7032663ac..7686f1456 100644 --- a/ThreadedCoreData/ThreadedCoreData/APLParseOperation.cs +++ b/ThreadedCoreData/ThreadedCoreData/APLParseOperation.cs @@ -7,10 +7,8 @@ using UIKit; using System.Linq; -namespace ThreadedCoreData -{ - public class APLParseOperation : NSOperation - { +namespace ThreadedCoreData { + public class APLParseOperation : NSOperation { public const string EarthquakesErrorNotificationName = "EarthquakeErrorNotif"; public const string EarthquakesMessageErrorKey = "EarthquakesMsgErrorKey"; const int MaximumNumberOfEarthquakesToParse = 50; @@ -57,12 +55,12 @@ void Parse (NSData data) var earthquake = featureCollection [i] as JsonObject; JsonValue earthquakeProperties = earthquake ["properties"]; - currentEarthquake.Magnitude = NSNumber.FromFloat ((float)earthquakeProperties ["mag"]); - currentEarthquake.USGSWebLink = new NSString ((string)earthquakeProperties ["url"]); - currentEarthquake.Location = new NSString ((string)earthquakeProperties ["place"]); + currentEarthquake.Magnitude = NSNumber.FromFloat ((float) earthquakeProperties ["mag"]); + currentEarthquake.USGSWebLink = new NSString ((string) earthquakeProperties ["url"]); + currentEarthquake.Location = new NSString ((string) earthquakeProperties ["place"]); //date and time in milliseconds since epoch - var seconds = (Int64)earthquakeProperties ["time"]; + var seconds = (Int64) earthquakeProperties ["time"]; var date = new DateTime (1970, 1, 1, 0, 0, 0).AddMilliseconds (seconds); string str = date.ToString ("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"); currentEarthquake.Date = dateFormatter.Parse (str); @@ -92,7 +90,7 @@ void Parse (NSData data) } } - [Export("HandleEarthquakesError:")] + [Export ("HandleEarthquakesError:")] public void HandleEarthquakesError (NSError parserError) { var userInfo = new NSDictionary (EarthquakesMessageErrorKey, parserError); @@ -105,16 +103,16 @@ void AddEarthquakesToList (List<Earthquake> earthquakes) var fetchRequest = new NSFetchRequest (); fetchRequest.Entity = entity; - var date = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("date")); - var location = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("location")); + var date = (NSPropertyDescription) entity.PropertiesByName.ValueForKey (new NSString ("date")); + var location = (NSPropertyDescription) entity.PropertiesByName.ValueForKey (new NSString ("location")); - fetchRequest.PropertiesToFetch = new NSPropertyDescription[] { date, location }; + fetchRequest.PropertiesToFetch = new NSPropertyDescription [] { date, location }; fetchRequest.ResultType = NSFetchRequestResultType.DictionaryResultType; NSError error; foreach (var earthquake in earthquakes) { - var arguments = new NSObject[] { earthquake.Location, earthquake.Date }; + var arguments = new NSObject [] { earthquake.Location, earthquake.Date }; fetchRequest.Predicate = NSPredicate.FromFormat ("location = %@ AND date = %@", arguments); var fetchedItems = NSArray.FromNSObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error)); @@ -142,7 +140,7 @@ void AddEarthquakesToList (List<Earthquake> earthquakes) // use the same fetchrequest instance but switch back to NSManagedObjectResultType fetchRequest.ResultType = NSFetchRequestResultType.ManagedObject; - fetchRequest.Predicate = NSPredicate.FromFormat ("date < %@", new NSObject[] { twoWeeksAgo }); + fetchRequest.Predicate = NSPredicate.FromFormat ("date < %@", new NSObject [] { twoWeeksAgo }); var olderEarthquakes = NSArray.FromObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error)); diff --git a/ThreadedCoreData/ThreadedCoreData/APLViewController.cs b/ThreadedCoreData/ThreadedCoreData/APLViewController.cs index 12a05bb66..45c432aa0 100644 --- a/ThreadedCoreData/ThreadedCoreData/APLViewController.cs +++ b/ThreadedCoreData/ThreadedCoreData/APLViewController.cs @@ -5,10 +5,8 @@ using ObjCRuntime; using UIKit; -namespace ThreadedCoreData -{ - public partial class APLViewController : UITableViewController - { +namespace ThreadedCoreData { + public partial class APLViewController : UITableViewController { NSManagedObjectContext managedObjectContext; NSFetchedResultsController fetchedResultsController; FecthResultsControllerDelegate fecthResultsControllerDelegate; @@ -19,7 +17,7 @@ public partial class APLViewController : UITableViewController string ApplicationDocumentsDirectory { get { - string[] directories = NSSearchPath.GetDirectories (NSSearchPathDirectory.DocumentDirectory, + string [] directories = NSSearchPath.GetDirectories (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true); return directories.Length != 0 ? directories [directories.Length - 1] : string.Empty; } @@ -47,7 +45,7 @@ NSManagedObjectContext ManagedObjectContext { }; NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("MergeChanges:"), - NSManagedObjectContext.DidSaveNotification, null); + NSManagedObjectContext.DidSaveNotification, null); return managedObjectContext; } @@ -65,7 +63,7 @@ NSPersistentStoreCoordinator PersistentStoreCoordinator { NSError error; persistentStoreCoordinator.AddPersistentStoreWithType (NSPersistentStoreCoordinator.SQLiteStoreType, - null, storeUrl, null, out error); + null, storeUrl, null, out error); if (error != null) Console.WriteLine (string.Format ("Unresolved error {0}", error.LocalizedDescription)); @@ -80,7 +78,7 @@ NSFetchedResultsController FetchedResultsController { var entity = NSEntityDescription.EntityForName ("Earthquake", ManagedObjectContext); fetchRequest.Entity = entity; - fetchRequest.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor ("date", false) }; + fetchRequest.SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor ("date", false) }; fetchedResultsController = new NSFetchedResultsController (fetchRequest, ManagedObjectContext, null, null); fetchedResultsController.Delegate = fecthResultsControllerDelegate; @@ -117,8 +115,8 @@ public override void ViewDidLoad () parseQueue.AddObserver (this, new NSString ("operationCount"), NSKeyValueObservingOptions.New, IntPtr.Zero); //HACK: Parsed strings to NSString - NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("EarthquakesError:"), (NSString)APLParseOperation.EarthquakesErrorNotificationName, null); - NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("LocaleChanged:"), (NSString)NSLocale.CurrentLocaleDidChangeNotification, null); + NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("EarthquakesError:"), (NSString) APLParseOperation.EarthquakesErrorNotificationName, null); + NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("LocaleChanged:"), (NSString) NSLocale.CurrentLocaleDidChangeNotification, null); var spinner = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.White); spinner.StartAnimating (); @@ -147,47 +145,47 @@ public override nint RowsInSection (UITableView tableview, nint section) // HACK: Parsed the Count to int if (FetchedResultsController.Sections.Length > 0) - numberOfRows = (int)FetchedResultsController.Sections [section].Count; + numberOfRows = (int) FetchedResultsController.Sections [section].Count; return numberOfRows; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (APLEarthquakeTableViewCell)tableView.DequeueReusableCell (APLEarthquakeTableViewCell.Key); + var cell = (APLEarthquakeTableViewCell) tableView.DequeueReusableCell (APLEarthquakeTableViewCell.Key); cell.SelectionStyle = UITableViewCellSelectionStyle.None; var earthquake = new ManagedEarthquake (FetchedResultsController.ObjectAt (indexPath).Handle); cell.ConfigureWithEarthquake (earthquake); return cell; } - [Export("EarthquakesError:")] + [Export ("EarthquakesError:")] public void EarthquakesError (NSNotification notification) { if (notification.Name == APLParseOperation.EarthquakesErrorNotificationName) - HandleError ((NSError)notification.UserInfo.ValueForKey (new NSString (APLParseOperation.EarthquakesMessageErrorKey))); + HandleError ((NSError) notification.UserInfo.ValueForKey (new NSString (APLParseOperation.EarthquakesMessageErrorKey))); } - [Export("MergeChanges:")] + [Export ("MergeChanges:")] public void MergeChanges (NSNotification notification) { if (notification.Object != ManagedObjectContext) InvokeOnMainThread (new Selector ("UpdateMainContext:"), notification); } - [Export("LocaleChanged:")] + [Export ("LocaleChanged:")] public void LocaleChanged (NSNotification notification) { TableView.ReloadData (); } - [Export("UpdateMainContext:")] + [Export ("UpdateMainContext:")] public void UpdateMainContext (NSNotification notification) { ManagedObjectContext.MergeChangesFromContextDidSaveNotification (notification); } - [Export("HandleError:")] + [Export ("HandleError:")] public void HandleError (NSError error) { string errorMessage = error.LocalizedDescription; @@ -196,10 +194,10 @@ public void HandleError (NSError error) alert.Show (); } - [Export("HideActivityIndicator")] + [Export ("HideActivityIndicator")] public void HideActivityIndicator () { - var indicator = (UIActivityIndicatorView)activityIndicator.CustomView; + var indicator = (UIActivityIndicatorView) activityIndicator.CustomView; indicator.StopAnimating (); NavigationItem.RightBarButtonItem = null; } @@ -217,20 +215,19 @@ void RequestCompletionHandler (NSUrlResponse responce, NSData data, NSError erro if (error != null) { HandleError (error); } else { - var httpResponse = (NSHttpUrlResponse)responce; + var httpResponse = (NSHttpUrlResponse) responce; if (httpResponse.StatusCode / 100 == 2 && responce.MimeType == "application/json") { var parseOperation = new APLParseOperation (data, PersistentStoreCoordinator); parseQueue.AddOperation (parseOperation); } else { - var userInfo = new NSDictionary(NSError.LocalizedDescriptionKey, "Problems with connection."); + var userInfo = new NSDictionary (NSError.LocalizedDescriptionKey, "Problems with connection."); var reportError = new NSError (new NSString ("HTTP"), httpResponse.StatusCode, userInfo); HandleError (reportError); } } } - class FecthResultsControllerDelegate : NSFetchedResultsControllerDelegate - { + class FecthResultsControllerDelegate : NSFetchedResultsControllerDelegate { public UITableView TableView { get; set; } public override void DidChangeContent (NSFetchedResultsController controller) diff --git a/ThreadedCoreData/ThreadedCoreData/AppDelegate.cs b/ThreadedCoreData/ThreadedCoreData/AppDelegate.cs index 1cb2d4442..22e3034a6 100644 --- a/ThreadedCoreData/ThreadedCoreData/AppDelegate.cs +++ b/ThreadedCoreData/ThreadedCoreData/AppDelegate.cs @@ -4,14 +4,12 @@ using Foundation; using UIKit; -namespace ThreadedCoreData -{ +namespace ThreadedCoreData { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/ThreadedCoreData/ThreadedCoreData/Earthquake.cs b/ThreadedCoreData/ThreadedCoreData/Earthquake.cs index fde30ca0a..8101e11cc 100644 --- a/ThreadedCoreData/ThreadedCoreData/Earthquake.cs +++ b/ThreadedCoreData/ThreadedCoreData/Earthquake.cs @@ -3,13 +3,11 @@ using Foundation; using ObjCRuntime; -namespace ThreadedCoreData -{ - public class ManagedEarthquake : NSManagedObject - { +namespace ThreadedCoreData { + public class ManagedEarthquake : NSManagedObject { public NSNumber Magnitude { get { - return (NSNumber)Runtime.GetNSObject (ValueForKey (new NSString ("magnitude"))); + return (NSNumber) Runtime.GetNSObject (ValueForKey (new NSString ("magnitude"))); } set { SetValueForKey (value, new NSString ("magnitude")); @@ -18,7 +16,7 @@ public NSNumber Magnitude { public NSString Location { get { - return (NSString)Runtime.GetNSObject (ValueForKey (new NSString ("location"))); + return (NSString) Runtime.GetNSObject (ValueForKey (new NSString ("location"))); } set { SetValueForKey (value, new NSString ("location")); @@ -27,7 +25,7 @@ public NSString Location { public NSDate Date { get { - return (NSDate)Runtime.GetNSObject (ValueForKey (new NSString ("date"))); + return (NSDate) Runtime.GetNSObject (ValueForKey (new NSString ("date"))); } set { SetValueForKey (value, new NSString ("date")); @@ -36,7 +34,7 @@ public NSDate Date { public NSString USGSWebLink { get { - return (NSString)Runtime.GetNSObject (ValueForKey (new NSString ("USGSWebLink"))); + return (NSString) Runtime.GetNSObject (ValueForKey (new NSString ("USGSWebLink"))); } set { SetValueForKey (value, new NSString ("USGSWebLink")); @@ -45,7 +43,7 @@ public NSString USGSWebLink { public NSNumber Latitude { get { - return (NSNumber)Runtime.GetNSObject (ValueForKey (new NSString ("latitude"))); + return (NSNumber) Runtime.GetNSObject (ValueForKey (new NSString ("latitude"))); } set { SetValueForKey (value, new NSString ("latitude")); @@ -54,25 +52,24 @@ public NSNumber Latitude { public NSNumber Longitude { get { - return (NSNumber)Runtime.GetNSObject (ValueForKey (new NSString ("longitude"))); + return (NSNumber) Runtime.GetNSObject (ValueForKey (new NSString ("longitude"))); } set { SetValueForKey (value, new NSString ("longitude")); } } - public ManagedEarthquake (NSEntityDescription description, NSManagedObjectContext context) : base(description, context) + public ManagedEarthquake (NSEntityDescription description, NSManagedObjectContext context) : base (description, context) { this.IsDirectBinding = true; } - public ManagedEarthquake (IntPtr handle): base(handle) + public ManagedEarthquake (IntPtr handle) : base (handle) { } } - public class Earthquake - { + public class Earthquake { public NSNumber Magnitude { get; set; } public NSString Location { get; set; } diff --git a/ThreadedCoreData/ThreadedCoreData/Main.cs b/ThreadedCoreData/ThreadedCoreData/Main.cs index b3dd0ee1e..6b58ebe28 100644 --- a/ThreadedCoreData/ThreadedCoreData/Main.cs +++ b/ThreadedCoreData/ThreadedCoreData/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace ThreadedCoreData -{ - public class Application - { +namespace ThreadedCoreData { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/TicTacToe/TicTacToe/AppDelegate.cs b/TicTacToe/TicTacToe/AppDelegate.cs index 42ca612e3..75b947b94 100644 --- a/TicTacToe/TicTacToe/AppDelegate.cs +++ b/TicTacToe/TicTacToe/AppDelegate.cs @@ -5,15 +5,13 @@ using UIKit; using System.IO; -namespace TicTacToe -{ +namespace TicTacToe { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; TTTProfile profile; - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } @@ -43,8 +41,8 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.MakeKeyAndVisible (); - NSNotificationCenter.DefaultCenter.AddObserver ((NSString)TTTProfile.IconDidChangeNotification, - iconDidChange); + NSNotificationCenter.DefaultCenter.AddObserver ((NSString) TTTProfile.IconDidChangeNotification, + iconDidChange); return true; } @@ -52,7 +50,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) string profilePath { get { return Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), - "Profile.ttt"); + "Profile.ttt"); } } diff --git a/TicTacToe/TicTacToe/Controller/TTTGameHistoryViewController.cs b/TicTacToe/TicTacToe/Controller/TTTGameHistoryViewController.cs index ebdac2d14..779feaf10 100644 --- a/TicTacToe/TicTacToe/Controller/TTTGameHistoryViewController.cs +++ b/TicTacToe/TicTacToe/Controller/TTTGameHistoryViewController.cs @@ -3,10 +3,8 @@ using CoreGraphics; using Foundation; -namespace TicTacToe -{ - public class TTTGameHistoryViewController : UIViewController - { +namespace TicTacToe { + public class TTTGameHistoryViewController : UIViewController { const float Margin = 20f; TTTGameView gameView; @@ -23,8 +21,8 @@ public TTTGameHistoryViewController () ratingControl.ValueChanged += ChangeRating; NavigationItem.TitleView = ratingControl; - NSNotificationCenter.DefaultCenter.AddObserver ((NSString)TTTProfile.IconDidChangeNotification, - IconDidChange); + NSNotificationCenter.DefaultCenter.AddObserver ((NSString) TTTProfile.IconDidChangeNotification, + IconDidChange); } public override void LoadView () @@ -46,12 +44,12 @@ public override void LoadView () NavigationController.NavigationBar.Frame.Size.Height; view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-margin-[gameView]-margin-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "margin", Margin, "gameView", gameView)); view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-topHeight-[gameView]-bottomHeight-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "topHeight", topHeight + Margin, "gameView", gameView, "bottomHeight", Margin)); @@ -61,7 +59,7 @@ public override void LoadView () void ChangeRating (object sender, EventArgs e) { - Game.Rating = ((TTTRatingControl)sender).Rating; + Game.Rating = ((TTTRatingControl) sender).Rating; } #region Game View diff --git a/TicTacToe/TicTacToe/Controller/TTTHistoryListViewController.cs b/TicTacToe/TicTacToe/Controller/TTTHistoryListViewController.cs index fe94821f2..0a37ecf42 100644 --- a/TicTacToe/TicTacToe/Controller/TTTHistoryListViewController.cs +++ b/TicTacToe/TicTacToe/Controller/TTTHistoryListViewController.cs @@ -2,10 +2,8 @@ using UIKit; using Foundation; -namespace TicTacToe -{ - public class TTTHistoryListViewController : UITableViewController - { +namespace TicTacToe { + public class TTTHistoryListViewController : UITableViewController { public TTTProfile Profile; NSString CellIdentifier = new NSString ("Cell"); @@ -17,7 +15,7 @@ public TTTHistoryListViewController () : base (UITableViewStyle.Plain) public override void LoadView () { base.LoadView (); - TableView.RegisterClassForCellReuse (typeof(TTTHistoryListTableViewCell), CellIdentifier); + TableView.RegisterClassForCellReuse (typeof (TTTHistoryListTableViewCell), CellIdentifier); } #region Table View @@ -61,8 +59,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) #endregion } - public class TTTHistoryListTableViewCell : UITableViewCell - { + public class TTTHistoryListTableViewCell : UITableViewCell { [Export ("initWithStyle:reuseIdentifier:")] public TTTHistoryListTableViewCell (UITableViewCellStyle style, string reuseIdentifier) : base (UITableViewCellStyle.Subtitle, reuseIdentifier) diff --git a/TicTacToe/TicTacToe/Controller/TTTMessagesViewController.cs b/TicTacToe/TicTacToe/Controller/TTTMessagesViewController.cs index b11b62c9e..0483f9461 100644 --- a/TicTacToe/TicTacToe/Controller/TTTMessagesViewController.cs +++ b/TicTacToe/TicTacToe/Controller/TTTMessagesViewController.cs @@ -4,10 +4,8 @@ using System.Collections.Generic; using System.Linq; -namespace TicTacToe -{ - public class TTTMessagesViewController : UITableViewController - { +namespace TicTacToe { + public class TTTMessagesViewController : UITableViewController { readonly NSString cellIdentifier = new NSString ("Cell"); TTTProfile profile; @@ -50,7 +48,7 @@ public static UIViewController FromProfile (TTTProfile profile, string profilePa public override void ViewDidLoad () { base.ViewDidLoad (); - TableView.RegisterClassForCellReuse (typeof(TTTMessageTableViewCell), cellIdentifier); + TableView.RegisterClassForCellReuse (typeof (TTTMessageTableViewCell), cellIdentifier); } void NewMessage (object sender, EventArgs e) @@ -62,7 +60,7 @@ void NewMessage (object sender, EventArgs e) void OnMessagesAdded (object sender, MessageEvenArg e) { - NSIndexPath[] paths = e.Indexes.Select (index => NSIndexPath.FromRowSection (index, 0)).ToArray (); + NSIndexPath [] paths = e.Indexes.Select (index => NSIndexPath.FromRowSection (index, 0)).ToArray (); TableView.InsertRows (paths, UITableViewRowAnimation.Automatic); } @@ -76,7 +74,7 @@ void Favorite (object sender, EventArgs e) void UpdateFavoriteButton () { bool isFavorite = selectedMessage != null - && TTTMessageServer.SharedMessageServer.IsFavoriteMessage (selectedMessage); + && TTTMessageServer.SharedMessageServer.IsFavoriteMessage (selectedMessage); UIImage image = isFavorite ? FavoriteImage : UnselectedFavoriteImage; @@ -98,7 +96,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { - TTTMessageTableViewCell messageCell = (TTTMessageTableViewCell)cell; + TTTMessageTableViewCell messageCell = (TTTMessageTableViewCell) cell; TTTMessage message = TTTMessageServer.SharedMessageServer.MessageAtIndex (indexPath.Row); cell.TextLabel.Text = message.Text; cell.ImageView.Image = TTTProfile.SmallImageForIcon (message.Icon); @@ -118,14 +116,14 @@ public override void WillDisplay (UITableView tableView, UITableViewCell cell, N public override void RowDeselected (UITableView tableView, NSIndexPath indexPath) { - TTTMessageTableViewCell cell = (TTTMessageTableViewCell)tableView.CellAt (indexPath); + TTTMessageTableViewCell cell = (TTTMessageTableViewCell) tableView.CellAt (indexPath); cell.SetShowReplyButton (false); } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { TTTMessage message = TTTMessageServer.SharedMessageServer.MessageAtIndex (indexPath.Row); - TTTMessageTableViewCell cell = (TTTMessageTableViewCell)tableView.CellAt (indexPath); + TTTMessageTableViewCell cell = (TTTMessageTableViewCell) tableView.CellAt (indexPath); if (selectedMessage == message) { tableView.DeselectRow (indexPath, true); @@ -140,8 +138,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) #endregion } - public class TTTMessageTableViewCell : UITableViewCell - { + public class TTTMessageTableViewCell : UITableViewCell { bool showReplyButton; public UIButton ReplyButton { get; set; } diff --git a/TicTacToe/TicTacToe/Controller/TTTNewMessageViewController.cs b/TicTacToe/TicTacToe/Controller/TTTNewMessageViewController.cs index dd9c180df..0be6c66b3 100644 --- a/TicTacToe/TicTacToe/Controller/TTTNewMessageViewController.cs +++ b/TicTacToe/TicTacToe/Controller/TTTNewMessageViewController.cs @@ -3,10 +3,8 @@ using CoreGraphics; using Foundation; -namespace TicTacToe -{ - public class TTTNewMessageViewController : UIViewController - { +namespace TicTacToe { + public class TTTNewMessageViewController : UIViewController { public TTTProfile Profile; UITextView messageTextView; UIWindow currentMessageWindow; @@ -51,18 +49,18 @@ public override void LoadView () view.AddSubview (messageTextView); baseView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-8-[messageTextView]-8-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "messageTextView", messageTextView)); baseView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-8-[cancelButton]->=20-[postButton]-8-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "cancelButton", cancelButton, "postButton", postButton)); baseView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-8-[messageTextView]-[cancelButton]-8-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "messageTextView", messageTextView, "cancelButton", cancelButton)); baseView.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-8-[messageTextView]-[postButton]-8-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "messageTextView", messageTextView, "postButton", postButton)); @@ -82,7 +80,8 @@ public void PresentFromViewController (UIViewController controller) messageTextView.BecomeFirstResponder (); View.Alpha = 0f; - UIView.Animate (0.3f, delegate { + UIView.Animate (0.3f, delegate + { View.Alpha = 1f; currentMessageSourceWindow.TintAdjustmentMode = UIViewTintAdjustmentMode.Dimmed; }); @@ -91,19 +90,21 @@ public void PresentFromViewController (UIViewController controller) void close (object sender, EventArgs e) { messageTextView.ResignFirstResponder (); - UIView.Animate (0.3f, delegate { + UIView.Animate (0.3f, delegate + { View.Alpha = 0f; currentMessageSourceWindow.TintAdjustmentMode = UIViewTintAdjustmentMode.Automatic; }, - delegate { - currentMessageWindow = null; - currentMessageSourceWindow.MakeKeyAndVisible (); - }); + delegate + { + currentMessageWindow = null; + currentMessageSourceWindow.MakeKeyAndVisible (); + }); } void post (object sender, EventArgs e) { - TTTMessage message = new TTTMessage (){ + TTTMessage message = new TTTMessage () { Icon = Profile.Icon, Text = messageTextView.Text }; diff --git a/TicTacToe/TicTacToe/Controller/TTTPlayViewController.cs b/TicTacToe/TicTacToe/Controller/TTTPlayViewController.cs index e40446a0a..f11dac4de 100644 --- a/TicTacToe/TicTacToe/Controller/TTTPlayViewController.cs +++ b/TicTacToe/TicTacToe/Controller/TTTPlayViewController.cs @@ -2,10 +2,8 @@ using UIKit; using Foundation; -namespace TicTacToe -{ - public class TTTPlayViewController : UIViewController - { +namespace TicTacToe { + public class TTTPlayViewController : UIViewController { const float ControllerMargin = 20f; public TTTProfile Profile; public string ProfilePath; @@ -17,7 +15,7 @@ public TTTPlayViewController () TabBarItem.Image = UIImage.FromBundle ("playTab"); TabBarItem.SelectedImage = UIImage.FromBundle ("playTabSelected"); - NSNotificationCenter.DefaultCenter.AddObserver ((NSString)TTTProfile.IconDidChangeNotification, iconDidChange); + NSNotificationCenter.DefaultCenter.AddObserver ((NSString) TTTProfile.IconDidChangeNotification, iconDidChange); } public static TTTPlayViewController FromProfile (TTTProfile profile, string profilePath) @@ -67,16 +65,16 @@ public override void LoadView () var mMargin = new NSNumber (ControllerMargin); view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-margin-[gameView]-margin-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "margin", mMargin, "gameView", gameView)); view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-margin-[pauseButton(==newButton)]-[newButton]-margin-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "margin", mMargin, "pauseButton", pauseButton, "newButton", newButton)); view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-topHeight-[gameView]-margin-[newButton]-bottomHeight-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "topHeight", mTopHeight, "gameView", gameView, "margin", mMargin, @@ -104,7 +102,8 @@ void saveProfile () void newGame (object sender, EventArgs e) { - UIView.Animate (0.3f, delegate { + UIView.Animate (0.3f, delegate + { gameView.Game = Profile.StartNewGame (); saveProfile (); updateBackground (); @@ -113,11 +112,12 @@ void newGame (object sender, EventArgs e) void togglePause (object sender, EventArgs e) { - UIButton button = (UIButton)sender; + UIButton button = (UIButton) sender; bool paused = !button.Selected; button.Selected = paused; gameView.UserInteractionEnabled = !paused; - UIView.Animate (0.3f, delegate { + UIView.Animate (0.3f, delegate + { gameView.Alpha = (paused ? 0.25f : 1f); }); } @@ -144,14 +144,15 @@ public UIColor ColorForPlayer (TTTGameView gameView, TTTMovePlayer player) } public bool CanSelect (TTTGameView gameView, TTTMoveXPosition xPosition, - TTTMoveYPosition yPosition) + TTTMoveYPosition yPosition) { return gameView.Game.CanAddMove (xPosition, yPosition); } public void DidSelect (TTTGameView gameView, TTTMoveXPosition xPosition, TTTMoveYPosition yPosition) { - UIView.Animate (0.3, delegate { + UIView.Animate (0.3, delegate + { gameView.Game.AddMove (xPosition, yPosition); gameView.UpdateGameState (); saveProfile (); diff --git a/TicTacToe/TicTacToe/Controller/TTTProfileViewController.cs b/TicTacToe/TicTacToe/Controller/TTTProfileViewController.cs index 51b82c30a..7f1054b99 100644 --- a/TicTacToe/TicTacToe/Controller/TTTProfileViewController.cs +++ b/TicTacToe/TicTacToe/Controller/TTTProfileViewController.cs @@ -5,12 +5,9 @@ using CoreGraphics; using ObjCRuntime; -namespace TicTacToe -{ - public class TTTProfileViewController : UITableViewController - { - public enum Section - { +namespace TicTacToe { + public class TTTProfileViewController : UITableViewController { + public enum Section { Icon, Statistics, History, @@ -43,44 +40,44 @@ public static UIViewController FromProfile (TTTProfile profile, string profilePa public override void LoadView () { base.LoadView (); - TableView.RegisterClassForCellReuse (typeof(TTTProfileIconTableViewCell), - IconIdentifier); - TableView.RegisterClassForCellReuse (typeof(TTTProfileStatisticsTableViewCell), - StatisticsIdentifier); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), - HistoryIdentifier); + TableView.RegisterClassForCellReuse (typeof (TTTProfileIconTableViewCell), + IconIdentifier); + TableView.RegisterClassForCellReuse (typeof (TTTProfileStatisticsTableViewCell), + StatisticsIdentifier); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), + HistoryIdentifier); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); - int rowCount = (int)TableView.NumberOfRowsInSection ((nint)(int)Section.Statistics); + int rowCount = (int) TableView.NumberOfRowsInSection ((nint) (int) Section.Statistics); List<NSIndexPath> indexPaths = new List<NSIndexPath> (); for (int row = 0; row < rowCount; row++) - indexPaths.Add (NSIndexPath.FromRowSection (row, (int)Section.Statistics)); + indexPaths.Add (NSIndexPath.FromRowSection (row, (int) Section.Statistics)); TableView.ReloadRows (indexPaths.ToArray (), UITableViewRowAnimation.None); } public void ChangeIcon (object sender, EventArgs e) { - Profile.Icon = (TTTProfileIcon)(int)((UISegmentedControl)sender).SelectedSegment; + Profile.Icon = (TTTProfileIcon) (int) ((UISegmentedControl) sender).SelectedSegment; } #region Table View public override nint NumberOfSections (UITableView tableView) { - return (int)Section.Count; + return (int) Section.Count; } public override nint RowsInSection (UITableView tableview, nint section) { switch (section) { - case (int)Section.Icon: - case (int)Section.History: + case (int) Section.Icon: + case (int) Section.History: return 1; - case (int)Section.Statistics: + case (int) Section.Statistics: return 3; } @@ -90,11 +87,11 @@ public override nint RowsInSection (UITableView tableview, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Section) { - case (int)Section.Icon: + case (int) Section.Icon: return tableView.DequeueReusableCell (IconIdentifier, indexPath); - case (int)Section.Statistics: + case (int) Section.Statistics: return tableView.DequeueReusableCell (StatisticsIdentifier, indexPath); - case (int)Section.History: + case (int) Section.History: return tableView.DequeueReusableCell (HistoryIdentifier, indexPath); } @@ -107,38 +104,38 @@ public override void WillDisplay (UITableView tableView, UITableViewCell cell, N int row = indexPath.Row; switch (section) { - case (int)Section.Icon: + case (int) Section.Icon: if (iconCell == null) { - iconCell = (TTTProfileIconTableViewCell)cell; + iconCell = (TTTProfileIconTableViewCell) cell; iconCell.SegmentedControl.ValueChanged += ChangeIcon; } iconCell.SelectionStyle = UITableViewCellSelectionStyle.None; - iconCell.SegmentedControl.SelectedSegment = (int)Profile.Icon; + iconCell.SegmentedControl.SelectedSegment = (int) Profile.Icon; break; - case (int)Section.Statistics: + case (int) Section.Statistics: cell.SelectionStyle = UITableViewCellSelectionStyle.None; if (row == 0) { cell.TextLabel.Text = "Victories"; cell.ImageView.Image = UIImage.FromBundle ("victory"). ImageWithRenderingMode (UIImageRenderingMode.AlwaysTemplate); - ((TTTProfileStatisticsTableViewCell)cell).CountView.Count = + ((TTTProfileStatisticsTableViewCell) cell).CountView.Count = Profile.NumberOfGamesWithResult (TTTGameResult.Victory); } else if (row == 1) { cell.TextLabel.Text = "Defeats"; cell.ImageView.Image = UIImage.FromBundle ("defeat"). ImageWithRenderingMode (UIImageRenderingMode.AlwaysTemplate); - ((TTTProfileStatisticsTableViewCell)cell).CountView.Count = + ((TTTProfileStatisticsTableViewCell) cell).CountView.Count = Profile.NumberOfGamesWithResult (TTTGameResult.Defeat); } else if (row == 2) { cell.TextLabel.Text = "Draws"; cell.ImageView.Image = UIImage.FromBundle ("draw"). ImageWithRenderingMode (UIImageRenderingMode.AlwaysTemplate); - ((TTTProfileStatisticsTableViewCell)cell).CountView.Count = + ((TTTProfileStatisticsTableViewCell) cell).CountView.Count = Profile.NumberOfGamesWithResult (TTTGameResult.Draw); } break; - case (int)Section.History: + case (int) Section.History: cell.TextLabel.Text = "Show History"; cell.TextLabel.TextAlignment = UITextAlignment.Center; break; @@ -147,7 +144,7 @@ public override void WillDisplay (UITableView tableView, UITableViewCell cell, N public override string TitleForHeader (UITableView tableView, nint section) { - if (section == (int)Section.Statistics) + if (section == (int) Section.Statistics) return "Statistics"; return null; @@ -155,7 +152,7 @@ public override string TitleForHeader (UITableView tableView, nint section) public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { - if (indexPath.Section == (int)Section.Icon) + if (indexPath.Section == (int) Section.Icon) return 100f; return tableView.RowHeight; @@ -163,7 +160,7 @@ public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath index public override NSIndexPath WillSelectRow (UITableView tableView, NSIndexPath indexPath) { - if (indexPath.Section == (int)Section.History) + if (indexPath.Section == (int) Section.History) return indexPath; return null; @@ -189,8 +186,7 @@ void closeHistory (object sender, EventArgs e) } } - public class TTTProfileIconTableViewCell : UITableViewCell - { + public class TTTProfileIconTableViewCell : UITableViewCell { public UISegmentedControl SegmentedControl; [Export ("initWithStyle:reuseIdentifier:")] @@ -202,7 +198,7 @@ public TTTProfileIconTableViewCell (UITableViewCellStyle style, string reuseIden UIImage o = TTTProfile.ImageForIcon (TTTProfileIcon.O). ImageWithRenderingMode (UIImageRenderingMode.AlwaysOriginal); - SegmentedControl = new UISegmentedControl (new object[] { x, o }) { + SegmentedControl = new UISegmentedControl (new object [] { x, o }) { Frame = new CGRect (UIScreen.MainScreen.Bounds.Width / 2 - 120, 0, 240, 80), AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin @@ -233,8 +229,7 @@ public TTTProfileIconTableViewCell (UITableViewCellStyle style, string reuseIden } } - public class TTTProfileStatisticsTableViewCell : UITableViewCell - { + public class TTTProfileStatisticsTableViewCell : UITableViewCell { public TTTCountView CountView; [Export ("initWithStyle:reuseIdentifier:")] diff --git a/TicTacToe/TicTacToe/Model/MessageEvenArg.cs b/TicTacToe/TicTacToe/Model/MessageEvenArg.cs index 4e7b68146..09d00e1da 100644 --- a/TicTacToe/TicTacToe/Model/MessageEvenArg.cs +++ b/TicTacToe/TicTacToe/Model/MessageEvenArg.cs @@ -1,12 +1,10 @@ -using System; +using System; -namespace TicTacToe -{ - public class MessageEvenArg : EventArgs - { - public nint[] Indexes { get; set; } +namespace TicTacToe { + public class MessageEvenArg : EventArgs { + public nint [] Indexes { get; set; } - public MessageEvenArg (params nint[] indexes) + public MessageEvenArg (params nint [] indexes) { Indexes = indexes; } diff --git a/TicTacToe/TicTacToe/Model/TTTGame.cs b/TicTacToe/TicTacToe/Model/TTTGame.cs index d87c13c0a..710bc041d 100644 --- a/TicTacToe/TicTacToe/Model/TTTGame.cs +++ b/TicTacToe/TicTacToe/Model/TTTGame.cs @@ -2,10 +2,8 @@ using Foundation; using System.Collections.Generic; -namespace TicTacToe -{ - public enum TTTGameResult - { +namespace TicTacToe { + public enum TTTGameResult { InProgress, Victory, Defeat, @@ -13,8 +11,7 @@ public enum TTTGameResult } [Serializable] - public class TTTGame - { + public class TTTGame { const string EncodingKeyResult = "result"; const string EncodingKeyRating = "rating"; const string EncodingKeyDate = "date"; @@ -57,7 +54,7 @@ public void AddMove (TTTMoveXPosition xPosition, TTTMoveYPosition yPosition) } bool hasMove (TTTMoveXPosition xPosition, TTTMoveYPosition yPosition, - ref TTTMovePlayer player) + ref TTTMovePlayer player) { foreach (var move in Moves) { if (move.XPosition == xPosition && move.YPosition == yPosition) { @@ -70,9 +67,9 @@ bool hasMove (TTTMoveXPosition xPosition, TTTMoveYPosition yPosition, } bool GetWinningPlayer (out TTTMovePlayer playerOut, out TTTMoveXPosition startXPosition, - out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, - out TTTMoveYPosition endYPosition, TTTMoveXPosition[] xPositions, - TTTMoveYPosition[] yPositions) + out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, + out TTTMoveYPosition endYPosition, TTTMoveXPosition [] xPositions, + TTTMoveYPosition [] yPositions) { bool moveExists = false; TTTMovePlayer player = TTTMovePlayer.None; @@ -115,85 +112,85 @@ bool GetWinningPlayer (out TTTMovePlayer playerOut, out TTTMoveXPosition startXP } bool GetWinningPlayer (out TTTMovePlayer player, out TTTMoveXPosition startXPosition, - out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, - out TTTMoveYPosition endYPosition, TTTMoveXPosition xPosition) + out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, + out TTTMoveYPosition endYPosition, TTTMoveXPosition xPosition) { - TTTMoveXPosition[] xPositions = new TTTMoveXPosition[TTTMove.SidePositionsCount]; + TTTMoveXPosition [] xPositions = new TTTMoveXPosition [TTTMove.SidePositionsCount]; for (int n = 0; n < TTTMove.SidePositionsCount; n++) xPositions [n] = xPosition; - TTTMoveYPosition[] yPositions = new TTTMoveYPosition[TTTMove.SidePositionsCount]; + TTTMoveYPosition [] yPositions = new TTTMoveYPosition [TTTMove.SidePositionsCount]; yPositions [0] = TTTMoveYPosition.Top; yPositions [1] = TTTMoveYPosition.Center; yPositions [2] = TTTMoveYPosition.Bottom; return GetWinningPlayer (out player, out startXPosition, out startYPosition, out endXPosition, - out endYPosition, xPositions, yPositions); + out endYPosition, xPositions, yPositions); } bool GetWinningPlayer (out TTTMovePlayer player, out TTTMoveXPosition startXPosition, - out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, - out TTTMoveYPosition endYPosition, TTTMoveYPosition yPosition) + out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, + out TTTMoveYPosition endYPosition, TTTMoveYPosition yPosition) { - TTTMoveYPosition[] yPositions = new TTTMoveYPosition[TTTMove.SidePositionsCount]; + TTTMoveYPosition [] yPositions = new TTTMoveYPosition [TTTMove.SidePositionsCount]; for (int n = 0; n < TTTMove.SidePositionsCount; n++) yPositions [n] = yPosition; - TTTMoveXPosition[] xPositions = new TTTMoveXPosition[TTTMove.SidePositionsCount]; + TTTMoveXPosition [] xPositions = new TTTMoveXPosition [TTTMove.SidePositionsCount]; xPositions [0] = TTTMoveXPosition.Left; xPositions [1] = TTTMoveXPosition.Center; xPositions [2] = TTTMoveXPosition.Right; return GetWinningPlayer (out player, out startXPosition, out startYPosition, - out endXPosition, out endYPosition, xPositions, yPositions); + out endXPosition, out endYPosition, xPositions, yPositions); } bool GetWinningPlayer (out TTTMovePlayer player, out TTTMoveXPosition startXPosition, - out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, - out TTTMoveYPosition endYPosition, int direction) + out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, + out TTTMoveYPosition endYPosition, int direction) { - TTTMoveXPosition[] xPositions = new TTTMoveXPosition[TTTMove.SidePositionsCount]; - TTTMoveYPosition[] yPositions = new TTTMoveYPosition[TTTMove.SidePositionsCount]; + TTTMoveXPosition [] xPositions = new TTTMoveXPosition [TTTMove.SidePositionsCount]; + TTTMoveYPosition [] yPositions = new TTTMoveYPosition [TTTMove.SidePositionsCount]; int n = 0; for (var xPosition = TTTMoveXPosition.Left; xPosition <= TTTMoveXPosition.Right; xPosition++) { xPositions [n] = xPosition; - yPositions [n] = (TTTMoveYPosition)((int)xPosition * direction); + yPositions [n] = (TTTMoveYPosition) ((int) xPosition * direction); n++; } return GetWinningPlayer (out player, out startXPosition, out startYPosition, - out endXPosition, out endYPosition, xPositions, yPositions); + out endXPosition, out endYPosition, xPositions, yPositions); } public bool GetWinningPlayer (out TTTMovePlayer player, out TTTMoveXPosition startXPosition, - out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, - out TTTMoveYPosition endYPosition) + out TTTMoveYPosition startYPosition, out TTTMoveXPosition endXPosition, + out TTTMoveYPosition endYPosition) { bool hasWinner; for (var xPosition = TTTMoveXPosition.Left; xPosition <= TTTMoveXPosition.Right; xPosition++) { hasWinner = GetWinningPlayer (out player, out startXPosition, out startYPosition, - out endXPosition, out endYPosition, xPosition); + out endXPosition, out endYPosition, xPosition); if (hasWinner) return hasWinner; } for (var yPosition = TTTMoveYPosition.Top; yPosition <= TTTMoveYPosition.Bottom; yPosition++) { hasWinner = GetWinningPlayer (out player, out startXPosition, out startYPosition, - out endXPosition, out endYPosition, yPosition); + out endXPosition, out endYPosition, yPosition); if (hasWinner) return hasWinner; } hasWinner = GetWinningPlayer (out player, out startXPosition, out startYPosition, - out endXPosition, out endYPosition, 1); + out endXPosition, out endYPosition, 1); if (hasWinner) return hasWinner; hasWinner = GetWinningPlayer (out player, out startXPosition, out startYPosition, - out endXPosition, out endYPosition, -1); + out endXPosition, out endYPosition, -1); return hasWinner; } @@ -205,8 +202,8 @@ TTTGameResult calculateGameResult () TTTMoveYPosition startYPosition, endYPosition; bool hasWinner = GetWinningPlayer (out player, out startXPosition, - out startYPosition, out endXPosition, - out endYPosition); + out startYPosition, out endXPosition, + out endYPosition); if (hasWinner) return player == TTTMovePlayer.Me ? TTTGameResult.Victory : TTTGameResult.Defeat; diff --git a/TicTacToe/TicTacToe/Model/TTTMessage.cs b/TicTacToe/TicTacToe/Model/TTTMessage.cs index 6d8eed95b..4909d26d3 100644 --- a/TicTacToe/TicTacToe/Model/TTTMessage.cs +++ b/TicTacToe/TicTacToe/Model/TTTMessage.cs @@ -1,11 +1,9 @@ using System; using Foundation; -namespace TicTacToe -{ +namespace TicTacToe { [Serializable] - public class TTTMessage - { + public class TTTMessage { const string EncodingKeyText = "text"; const string EncodingKeyIcon = "icon"; public string Text; diff --git a/TicTacToe/TicTacToe/Model/TTTMessageServer.cs b/TicTacToe/TicTacToe/Model/TTTMessageServer.cs index 74762c85e..a0abe7a40 100644 --- a/TicTacToe/TicTacToe/Model/TTTMessageServer.cs +++ b/TicTacToe/TicTacToe/Model/TTTMessageServer.cs @@ -3,10 +3,8 @@ using System.Collections.Generic; using System.Linq; -namespace TicTacToe -{ - public class TTTMessageServer - { +namespace TicTacToe { + public class TTTMessageServer { public event EventHandler<MessageEvenArg> MessagesAdded; List<TTTMessage> messages; @@ -35,7 +33,7 @@ public NSUrl MessagesUrl { get { NSError error; return NSFileManager.DefaultManager.GetUrl (NSSearchPathDirectory.DocumentDirectory, - NSSearchPathDomain.User, null, true, out error); + NSSearchPathDomain.User, null, true, out error); } } @@ -43,14 +41,14 @@ public void ReadMessages () { NSData data = NSData.FromUrl (MessagesUrl); if (data != null) - messages = (List<TTTMessage>)TTTProfile.ByteArrayToObject (data.ToArray ()); + messages = (List<TTTMessage>) TTTProfile.ByteArrayToObject (data.ToArray ()); } public void WriteMessages () { NSError error; - byte[] bytes = TTTProfile.ObjectToByteArray (messages); + byte [] bytes = TTTProfile.ObjectToByteArray (messages); NSData data = NSData.FromArray (bytes); data.Save (MessagesUrl, false, out error); } diff --git a/TicTacToe/TicTacToe/Model/TTTMove.cs b/TicTacToe/TicTacToe/Model/TTTMove.cs index 9563888af..4454b6f2e 100644 --- a/TicTacToe/TicTacToe/Model/TTTMove.cs +++ b/TicTacToe/TicTacToe/Model/TTTMove.cs @@ -1,32 +1,27 @@ using System; using Foundation; -namespace TicTacToe -{ - public enum TTTMovePlayer - { +namespace TicTacToe { + public enum TTTMovePlayer { Me, Enemy, None } - public enum TTTMoveXPosition - { + public enum TTTMoveXPosition { Left = -1, Center = 0, Right = 1 } - public enum TTTMoveYPosition - { + public enum TTTMoveYPosition { Top = -1, Center = 0, Bottom = 1 } [Serializable] - public class TTTMove - { + public class TTTMove { public const int SidePositionsCount = 3; public TTTMovePlayer Player; public TTTMoveXPosition XPosition; @@ -36,12 +31,12 @@ public class TTTMove const string EncodingKeyYPosition = "yPosition"; public TTTMove () : this (TTTMovePlayer.Me, TTTMoveXPosition.Center, - TTTMoveYPosition.Center) + TTTMoveYPosition.Center) { } public TTTMove (TTTMovePlayer player, TTTMoveXPosition xPosition, - TTTMoveYPosition yPosition) + TTTMoveYPosition yPosition) { Player = player; XPosition = xPosition; @@ -51,9 +46,9 @@ public TTTMove (TTTMovePlayer player, TTTMoveXPosition xPosition, public override int GetHashCode () { int hash = 1; - hash = 31 * hash + (int)Player; - hash = 31 * hash + (int)XPosition + 1; - hash = 31 * hash + (int)YPosition + 1; + hash = 31 * hash + (int) Player; + hash = 31 * hash + (int) XPosition + 1; + hash = 31 * hash + (int) YPosition + 1; return hash; } @@ -62,7 +57,7 @@ public override bool Equals (object obj) if (obj is TTTMove) return false; - TTTMove move = (TTTMove)obj; + TTTMove move = (TTTMove) obj; return (Player == move.Player && XPosition == move.XPosition && YPosition == move.YPosition); } diff --git a/TicTacToe/TicTacToe/Model/TTTProfile.cs b/TicTacToe/TicTacToe/Model/TTTProfile.cs index 0edca35f4..bd7a327ef 100644 --- a/TicTacToe/TicTacToe/Model/TTTProfile.cs +++ b/TicTacToe/TicTacToe/Model/TTTProfile.cs @@ -6,17 +6,14 @@ using System.IO; using System.Linq; -namespace TicTacToe -{ - public enum TTTProfileIcon - { +namespace TicTacToe { + public enum TTTProfileIcon { X, O } [Serializable] - public class TTTProfile - { + public class TTTProfile { const string EncodingKeyIcon = "icon"; const string EncodingKeyCurrentGame = "currentGame"; const string EncodingKeygames = "games"; @@ -47,8 +44,8 @@ public TTTProfile () public static TTTProfile FromPath (string path) { if (File.Exists (path)) { - byte[] bytes = File.ReadAllBytes (path); - return (TTTProfile)ByteArrayToObject (bytes); + byte [] bytes = File.ReadAllBytes (path); + return (TTTProfile) ByteArrayToObject (bytes); } return null; @@ -56,7 +53,7 @@ public static TTTProfile FromPath (string path) public bool WriteToPath (string path) { - byte[] bytes = ObjectToByteArray (this); + byte [] bytes = ObjectToByteArray (this); File.WriteAllBytes (path, bytes); return true; @@ -134,7 +131,7 @@ UIColor colorForIcon (TTTProfileIcon icon) #region Serialization // Convert an object to a byte array - public static byte[] ObjectToByteArray (Object obj) + public static byte [] ObjectToByteArray (Object obj) { if (obj == null) return null; @@ -145,7 +142,7 @@ public static byte[] ObjectToByteArray (Object obj) } // Convert a byte array to an Object - public static Object ByteArrayToObject (byte[] arrBytes) + public static Object ByteArrayToObject (byte [] arrBytes) { MemoryStream memStream = new MemoryStream (); BinaryFormatter binForm = new BinaryFormatter (); diff --git a/TicTacToe/TicTacToe/Resources/TTTRatingControl.cs b/TicTacToe/TicTacToe/Resources/TTTRatingControl.cs index 59fbcc5a9..4dcb80f21 100644 --- a/TicTacToe/TicTacToe/Resources/TTTRatingControl.cs +++ b/TicTacToe/TicTacToe/Resources/TTTRatingControl.cs @@ -2,10 +2,8 @@ using MonoTouch.UIKit; using System.Drawing; -namespace TicTacToe -{ - public class TTTRatingControl : UIControl - { +namespace TicTacToe { + public class TTTRatingControl : UIControl { const int MinimumRating = 0; const int MaximumRating = 0; int rating; diff --git a/TicTacToe/TicTacToe/View/TTTCountView.cs b/TicTacToe/TicTacToe/View/TTTCountView.cs index 99dd95d84..e11c373a8 100644 --- a/TicTacToe/TicTacToe/View/TTTCountView.cs +++ b/TicTacToe/TicTacToe/View/TTTCountView.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace TicTacToe -{ - public class TTTCountView : UIView - { +namespace TicTacToe { + public class TTTCountView : UIView { const float LineWidth = 1f; const float LineMargin = 4f; const int LineGroupCount = 5; @@ -33,7 +31,7 @@ public override void Draw (CGRect rect) { TintColor.SetColor (); CGRect bounds = Bounds; - float x = (float)bounds.Right - LineWidth; + float x = (float) bounds.Right - LineWidth; for (int n = 0; n < Count; n++) { x -= LineMargin; @@ -41,10 +39,10 @@ public override void Draw (CGRect rect) UIBezierPath path = new UIBezierPath (); path.MoveTo ( new CGPoint (x + 0.5f * LineWidth, - bounds.Top + 0.5f * LineWidth)); + bounds.Top + 0.5f * LineWidth)); path.AddLineTo ( new CGPoint (x + 0.5f * LineWidth + LineGroupCount * LineMargin, - bounds.Bottom - 0.5f * LineWidth)); + bounds.Bottom - 0.5f * LineWidth)); path.Stroke (); } else { CGRect lineRect = bounds; diff --git a/TicTacToe/TicTacToe/View/TTTGameView.cs b/TicTacToe/TicTacToe/View/TTTGameView.cs index 40324924d..0d1fc0b42 100644 --- a/TicTacToe/TicTacToe/View/TTTGameView.cs +++ b/TicTacToe/TicTacToe/View/TTTGameView.cs @@ -7,14 +7,12 @@ using Foundation; using ObjCRuntime; -namespace TicTacToe -{ - public class TTTGameView : UIView - { - public Func <TTTGameView, TTTMovePlayer, UIImage> ImageForPlayer; - public Func <TTTGameView, TTTMovePlayer, UIColor> ColorForPlayer; - public Func <TTTGameView, TTTMoveXPosition, TTTMoveYPosition, bool> CanSelect; - public Action <TTTGameView, TTTMoveXPosition, TTTMoveYPosition> DidSelect; +namespace TicTacToe { + public class TTTGameView : UIView { + public Func<TTTGameView, TTTMovePlayer, UIImage> ImageForPlayer; + public Func<TTTGameView, TTTMovePlayer, UIColor> ColorForPlayer; + public Func<TTTGameView, TTTMoveXPosition, TTTMoveYPosition, bool> CanSelect; + public Action<TTTGameView, TTTMoveXPosition, TTTMoveYPosition> DidSelect; TTTGame game; public TTTGame Game { @@ -37,8 +35,8 @@ public UIColor GridColor { } } - UIView[] horizontalLineViews; - UIView[] verticalLineViews; + UIView [] horizontalLineViews; + UIView [] verticalLineViews; List<UIImageView> moveImageViews; List<UIImageView> moveImageViewReuseQueue; TTTGameLineView lineView; @@ -47,18 +45,18 @@ public UIColor GridColor { public TTTGameView () : base () { gridColor = UIColor.Black; - horizontalLineViews = new UIView[] { + horizontalLineViews = new UIView [] { newLineView (), newLineView () }; - verticalLineViews = new UIView[] { + verticalLineViews = new UIView [] { newLineView (), newLineView () }; updateGridColor (); - moveImageViews = new List <UIImageView> (); - moveImageViewReuseQueue = new List <UIImageView> (); + moveImageViews = new List<UIImageView> (); + moveImageViewReuseQueue = new List<UIImageView> (); lineView = new TTTGameLineView (); lineView.Alpha = 0f; @@ -84,17 +82,17 @@ void tapGame (UITapGestureRecognizer gestureRecognizer) CGPoint normalizedPoint = point; normalizedPoint.X -= bounds.X + bounds.Size.Width / 2; normalizedPoint.X *= 3 / bounds.Size.Width; - normalizedPoint.X = (float)Math.Round (normalizedPoint.X); - normalizedPoint.X = (float)Math.Max (normalizedPoint.X, -1); - normalizedPoint.X = (float)Math.Min (normalizedPoint.X, 1); - TTTMoveXPosition xPosition = (TTTMoveXPosition)(int)normalizedPoint.X; + normalizedPoint.X = (float) Math.Round (normalizedPoint.X); + normalizedPoint.X = (float) Math.Max (normalizedPoint.X, -1); + normalizedPoint.X = (float) Math.Min (normalizedPoint.X, 1); + TTTMoveXPosition xPosition = (TTTMoveXPosition) (int) normalizedPoint.X; normalizedPoint.Y -= bounds.Y + bounds.Size.Height / 2; normalizedPoint.Y *= 3 / bounds.Size.Height; - normalizedPoint.Y = (float)Math.Round (normalizedPoint.Y); - normalizedPoint.Y = (float)Math.Max (normalizedPoint.Y, -1); - normalizedPoint.Y = (float)Math.Min (normalizedPoint.Y, 1); - TTTMoveYPosition yPosition = (TTTMoveYPosition)(int)normalizedPoint.Y; + normalizedPoint.Y = (float) Math.Round (normalizedPoint.Y); + normalizedPoint.Y = (float) Math.Max (normalizedPoint.Y, -1); + normalizedPoint.Y = (float) Math.Min (normalizedPoint.Y, 1); + TTTMoveYPosition yPosition = (TTTMoveYPosition) (int) normalizedPoint.Y; if (CanSelect == null || CanSelect (this, xPosition, yPosition)) DidSelect (this, xPosition, yPosition); @@ -119,9 +117,9 @@ CGPoint pointForPosition (TTTMoveXPosition xPosition, TTTMoveYPosition yPosition { CGRect bounds = Bounds; CGPoint point = new CGPoint (bounds.X + bounds.Size.Width / 2, - bounds.Y + bounds.Size.Height / 2); - point.X += (int)xPosition * bounds.Size.Width / 3; - point.Y += (int)yPosition * bounds.Size.Height / 3; + bounds.Y + bounds.Size.Height / 2); + point.X += (int) xPosition * bounds.Size.Width / 3; + point.Y += (int) yPosition * bounds.Size.Height / 3; return point; } @@ -144,10 +142,10 @@ void setVisible (bool visible, UIImageView moveView) public void UpdateGameState () { - TTTMove[] moves = Game.Moves.ToArray (); + TTTMove [] moves = Game.Moves.ToArray (); int moveCount = moves.Length; - UIImageView[] moveViews = new UIImageView[moveImageViews.Count]; + UIImageView [] moveViews = new UIImageView [moveImageViews.Count]; moveImageViews.CopyTo (moveViews); @@ -168,7 +166,8 @@ public void UpdateGameState () for (int moveIndex = moveImageViews.Count; moveIndex < moveCount; moveIndex++) { TTTMove move = moves [moveIndex]; UIImageView moveView = moveImageView (); - UIView.PerformWithoutAnimation (delegate { + UIView.PerformWithoutAnimation (delegate + { setMove (move, moveView); setVisible (false, moveView); }); @@ -181,10 +180,10 @@ public void UpdateGameState () TTTMoveYPosition startYPosition, endYPosition; bool hasWinner = Game.GetWinningPlayer (out winningPlayer, - out startXPosition, - out startYPosition, - out endXPosition, - out endYPosition); + out startXPosition, + out startYPosition, + out endXPosition, + out endYPosition); if (hasWinner) { UIBezierPath path = new UIBezierPath (); path.LineWidth = LineWidth; @@ -207,13 +206,13 @@ public override void LayoutSubviews () UIView view = horizontalLineViews [i]; view.Bounds = new CGRect (0, 0, bounds.Size.Width, LineWidth); view.Center = new CGPoint (bounds.X + bounds.Size.Width / 2, - (float)Math.Round (bounds.Size.Height * (i + 1) / 3)); + (float) Math.Round (bounds.Size.Height * (i + 1) / 3)); } for (int i = 0; i < verticalLineViews.Length; i++) { UIView view = verticalLineViews [i]; view.Bounds = new CGRect (0, 0, LineWidth, bounds.Size.Height); - view.Center = new CGPoint ((float)Math.Round (bounds.Size.Width * (i + 1) / 3), - bounds.Y + bounds.Size.Height / 2); + view.Center = new CGPoint ((float) Math.Round (bounds.Size.Width * (i + 1) / 3), + bounds.Y + bounds.Size.Height / 2); } UpdateGameState (); } @@ -227,8 +226,7 @@ void updateGridColor () } } - public class TTTGameLineView : UIView - { + public class TTTGameLineView : UIView { UIBezierPath path; public UIBezierPath Path { @@ -257,12 +255,12 @@ public TTTGameLineView () [ExportAttribute ("layerClass")] public static Class LayerClass () { - return new Class (typeof(CAShapeLayer)); + return new Class (typeof (CAShapeLayer)); } CAShapeLayer shapeLayer { get { - return (CAShapeLayer)Layer; + return (CAShapeLayer) Layer; } } } diff --git a/TicTacToe/TicTacToe/View/TTTRatingControl.cs b/TicTacToe/TicTacToe/View/TTTRatingControl.cs index f19ed2f3c..0c202847b 100644 --- a/TicTacToe/TicTacToe/View/TTTRatingControl.cs +++ b/TicTacToe/TicTacToe/View/TTTRatingControl.cs @@ -3,10 +3,8 @@ using CoreGraphics; using System.Collections.Generic; -namespace TicTacToe -{ - public class TTTRatingControl : UIControl - { +namespace TicTacToe { + public class TTTRatingControl : UIControl { const int MinimumRating = 0; const int MaximumRating = 4; int rating; @@ -49,7 +47,7 @@ public static UIImage BackgroundImage { UIImage image = UIGraphics.GetImageFromCurrentImageContext (); image = image.CreateResizableImage (new UIEdgeInsets (capSize, capSize, - capSize, capSize)); + capSize, capSize)); image = image.ImageWithRenderingMode (UIImageRenderingMode.AlwaysTemplate); UIGraphics.EndImageContext (); @@ -77,13 +75,13 @@ public override void LayoutSubviews () for (var rating = MinimumRating; rating <= MaximumRating; rating++) { UIButton button = UIButton.FromType (UIButtonType.Custom); button.SetImage (UIImage.FromBundle ("unselectedButton"), - UIControlState.Normal); + UIControlState.Normal); button.SetImage (UIImage.FromBundle ("unselectedButton"), - UIControlState.Highlighted); + UIControlState.Highlighted); button.SetImage (UIImage.FromBundle ("favoriteButton"), - UIControlState.Selected); + UIControlState.Selected); button.SetImage (UIImage.FromBundle ("favoriteButton"), - UIControlState.Highlighted | UIControlState.Selected); + UIControlState.Highlighted | UIControlState.Selected); button.Tag = rating; button.TouchUpInside += touchButton; button.AccessibilityLabel = String.Format ("{0} stars", rating + 1); @@ -95,10 +93,10 @@ public override void LayoutSubviews () } CGRect buttonFrame = Bounds; - float width = (float)buttonFrame.Size.Width / (MaximumRating - MinimumRating + 1); + float width = (float) buttonFrame.Size.Width / (MaximumRating - MinimumRating + 1); for (int index = 0; index < buttons.Count; index++) { UIButton button = buttons [index]; - buttonFrame.Width = (float)Math.Round (width * (index + 1) - buttonFrame.X); + buttonFrame.Width = (float) Math.Round (width * (index + 1) - buttonFrame.X); button.Frame = buttonFrame; buttonFrame.X += buttonFrame.Size.Width; } @@ -106,8 +104,8 @@ public override void LayoutSubviews () void touchButton (object sender, EventArgs e) { - UIButton button = (UIButton)sender; - Rating = (int)button.Tag; + UIButton button = (UIButton) sender; + Rating = (int) button.Tag; SendActionForControlEvents (UIControlEvent.ValueChanged); } diff --git a/Touch/AppDelegate.cs b/Touch/AppDelegate.cs index c7009fad8..c3f707a66 100644 --- a/Touch/AppDelegate.cs +++ b/Touch/AppDelegate.cs @@ -2,11 +2,9 @@ using UIKit; using Foundation; -namespace Example_Touch -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace Example_Touch { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { #region -= declarations and properties =- protected UIWindow window; diff --git a/Touch/Application.cs b/Touch/Application.cs index 8e3b23b02..4ca328847 100644 --- a/Touch/Application.cs +++ b/Touch/Application.cs @@ -1,18 +1,13 @@ using System; using UIKit; -namespace Example_Touch -{ - public class Application - { - public static void Main (string[] args) +namespace Example_Touch { + public class Application { + public static void Main (string [] args) { - try - { + try { UIApplication.Main (args, null, "AppDelegate"); - } - catch (Exception e) - { + } catch (Exception e) { Console.WriteLine (e.ToString ()); } } diff --git a/Touch/Code/CheckmarkGestureRecognizer.cs b/Touch/Code/CheckmarkGestureRecognizer.cs index f9dca03cb..d645c20ae 100644 --- a/Touch/Code/CheckmarkGestureRecognizer.cs +++ b/Touch/Code/CheckmarkGestureRecognizer.cs @@ -2,10 +2,8 @@ using UIKit; using CoreGraphics; -namespace Example_Touch.Code -{ - public class CheckmarkGestureRecognizer : UIGestureRecognizer - { +namespace Example_Touch.Code { + public class CheckmarkGestureRecognizer : UIGestureRecognizer { // declarations protected bool strokeUp = false; protected CGPoint midpoint = CGPoint.Empty; @@ -34,14 +32,14 @@ public override void TouchesMoved (Foundation.NSSet touches, UIEvent evt) base.TouchesMoved (touches, evt); // if we haven't already failed - if(base.State != UIGestureRecognizerState.Failed) { + if (base.State != UIGestureRecognizerState.Failed) { // get the current and previous touch point CGPoint newPoint = (touches.AnyObject as UITouch).LocationInView (View); CGPoint previousPoint = (touches.AnyObject as UITouch).PreviousLocationInView (View); // if we're not already on the upstroke - if(!strokeUp) { + if (!strokeUp) { // if we're moving down, just continue to set the midpoint at // whatever point we're at. when we start to stroke up, it'll stick diff --git a/Touch/Screens/iPhone/GestureRecognizers/CustomCheckmarkGestureRecognizer_iPhone.xib.cs b/Touch/Screens/iPhone/GestureRecognizers/CustomCheckmarkGestureRecognizer_iPhone.xib.cs index dcbb2b149..8edf0f140 100644 --- a/Touch/Screens/iPhone/GestureRecognizers/CustomCheckmarkGestureRecognizer_iPhone.xib.cs +++ b/Touch/Screens/iPhone/GestureRecognizers/CustomCheckmarkGestureRecognizer_iPhone.xib.cs @@ -6,10 +6,8 @@ using Example_Touch.Code; using ObjCRuntime; -namespace Example_Touch.Screens.iPhone.GestureRecognizers -{ - public partial class CustomCheckmarkGestureRecognizer_iPhone : UIViewController - { +namespace Example_Touch.Screens.iPhone.GestureRecognizers { + public partial class CustomCheckmarkGestureRecognizer_iPhone : UIViewController { CheckmarkGestureRecognizer checkmarkGesture; protected bool isChecked = false; @@ -18,18 +16,18 @@ public partial class CustomCheckmarkGestureRecognizer_iPhone : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public CustomCheckmarkGestureRecognizer_iPhone (IntPtr handle) : base(handle) + public CustomCheckmarkGestureRecognizer_iPhone (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public CustomCheckmarkGestureRecognizer_iPhone (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public CustomCheckmarkGestureRecognizer_iPhone (NSCoder coder) : base (coder) { Initialize (); } - public CustomCheckmarkGestureRecognizer_iPhone () : base("CustomCheckmarkGestureRecognizer_iPhone", null) + public CustomCheckmarkGestureRecognizer_iPhone () : base ("CustomCheckmarkGestureRecognizer_iPhone", null) { Initialize (); } @@ -46,15 +44,15 @@ public override void ViewDidLoad () imgCheckmark.Image = UIImage.FromBundle ("Images/CheckBox_Start.png"); - WireUpCheckmarkGestureRecognizer(); + WireUpCheckmarkGestureRecognizer (); } - protected void WireUpCheckmarkGestureRecognizer() + protected void WireUpCheckmarkGestureRecognizer () { // create the recognizer - checkmarkGesture = new CheckmarkGestureRecognizer(); + checkmarkGesture = new CheckmarkGestureRecognizer (); // wire up the event handler - checkmarkGesture.AddTarget ( () => { + checkmarkGesture.AddTarget (() => { if (checkmarkGesture.State == (UIGestureRecognizerState.Recognized | UIGestureRecognizerState.Ended)) { if (isChecked) diff --git a/Touch/Screens/iPhone/GestureRecognizers/GestureRecognizers_iPhone.xib.cs b/Touch/Screens/iPhone/GestureRecognizers/GestureRecognizers_iPhone.xib.cs index ef6944cc9..54623966e 100644 --- a/Touch/Screens/iPhone/GestureRecognizers/GestureRecognizers_iPhone.xib.cs +++ b/Touch/Screens/iPhone/GestureRecognizers/GestureRecognizers_iPhone.xib.cs @@ -5,10 +5,8 @@ using UIKit; using ObjCRuntime; -namespace Example_Touch.Screens.iPhone.GestureRecognizers -{ - public partial class GestureRecognizers_iPhone : UIViewController - { +namespace Example_Touch.Screens.iPhone.GestureRecognizers { + public partial class GestureRecognizers_iPhone : UIViewController { CoreGraphics.CGRect originalImageFrame = System.Drawing.RectangleF.Empty; #region Constructors @@ -16,18 +14,18 @@ public partial class GestureRecognizers_iPhone : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public GestureRecognizers_iPhone (IntPtr handle) : base(handle) + public GestureRecognizers_iPhone (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public GestureRecognizers_iPhone (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public GestureRecognizers_iPhone (NSCoder coder) : base (coder) { Initialize (); } - public GestureRecognizers_iPhone () : base("GestureRecognizers_iPhone", null) + public GestureRecognizers_iPhone () : base ("GestureRecognizers_iPhone", null) { Initialize (); } @@ -81,7 +79,7 @@ protected void WireUpDragGestureRecognizer () // create a new tap gesture UIPanGestureRecognizer gesture = new UIPanGestureRecognizer (); // wire up the event handler (have to use a selector) - gesture.AddTarget ( () => { HandleDrag (gesture); }); + gesture.AddTarget (() => { HandleDrag (gesture); }); // add the gesture recognizer to the view imgDragMe.AddGestureRecognizer (gesture); } diff --git a/Touch/Screens/iPhone/Home/Home_iPhone.xib.cs b/Touch/Screens/iPhone/Home/Home_iPhone.xib.cs index 2555b820c..67344ba98 100644 --- a/Touch/Screens/iPhone/Home/Home_iPhone.xib.cs +++ b/Touch/Screens/iPhone/Home/Home_iPhone.xib.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Example_Touch.Screens.iPhone.Home -{ - public partial class Home_iPhone : UIViewController - { +namespace Example_Touch.Screens.iPhone.Home { + public partial class Home_iPhone : UIViewController { GestureRecognizers.GestureRecognizers_iPhone gestureScreen; GestureRecognizers.CustomCheckmarkGestureRecognizer_iPhone customGestureScreen; SimpleTouch.Touches_iPhone touchScreen; @@ -18,18 +16,18 @@ public partial class Home_iPhone : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public Home_iPhone (IntPtr handle) : base(handle) + public Home_iPhone (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public Home_iPhone (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public Home_iPhone (NSCoder coder) : base (coder) { Initialize (); } - public Home_iPhone () : base("Home_iPhone", null) + public Home_iPhone () : base ("Home_iPhone", null) { Initialize (); } @@ -54,13 +52,13 @@ public override void ViewDidLoad () this.btnGestureRecognizers.TouchUpInside += (s, e) => { if (gestureScreen == null) - gestureScreen = new Example_Touch.Screens.iPhone.GestureRecognizers.GestureRecognizers_iPhone(); + gestureScreen = new Example_Touch.Screens.iPhone.GestureRecognizers.GestureRecognizers_iPhone (); this.NavigationController.PushViewController (gestureScreen, true); }; this.btnCustomGestureRecognizer.TouchUpInside += (s, e) => { if (customGestureScreen == null) - customGestureScreen = new Example_Touch.Screens.iPhone.GestureRecognizers.CustomCheckmarkGestureRecognizer_iPhone(); + customGestureScreen = new Example_Touch.Screens.iPhone.GestureRecognizers.CustomCheckmarkGestureRecognizer_iPhone (); this.NavigationController.PushViewController (customGestureScreen, true); }; diff --git a/Touch/Screens/iPhone/SimpleTouch/Touches_iPhone.xib.cs b/Touch/Screens/iPhone/SimpleTouch/Touches_iPhone.xib.cs index 85ff637f3..e67ab3a7a 100644 --- a/Touch/Screens/iPhone/SimpleTouch/Touches_iPhone.xib.cs +++ b/Touch/Screens/iPhone/SimpleTouch/Touches_iPhone.xib.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Example_Touch.Screens.iPhone.SimpleTouch -{ - public partial class Touches_iPhone : UIViewController - { +namespace Example_Touch.Screens.iPhone.SimpleTouch { + public partial class Touches_iPhone : UIViewController { protected bool touchStartedInside; protected bool imageHighlighted = false; @@ -17,18 +15,18 @@ public partial class Touches_iPhone : UIViewController // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code - public Touches_iPhone (IntPtr handle) : base(handle) + public Touches_iPhone (IntPtr handle) : base (handle) { Initialize (); } - [Export("initWithCoder:")] - public Touches_iPhone (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public Touches_iPhone (NSCoder coder) : base (coder) { Initialize (); } - public Touches_iPhone () : base("Touches_iPhone", null) + public Touches_iPhone () : base ("Touches_iPhone", null) { Initialize (); } @@ -55,20 +53,20 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) base.TouchesBegan (touches, evt); // we can get the number of fingers from the touch count, but Multitouch must be enabled - lblNumberOfFingers.Text = "Number of fingers: " + touches.Count.ToString(); + lblNumberOfFingers.Text = "Number of fingers: " + touches.Count.ToString (); // get the touch UITouch touch = touches.AnyObject as UITouch; if (touch != null) { - Console.WriteLine("screen touched"); + Console.WriteLine ("screen touched"); //==== IMAGE TOUCH if (imgTouchMe.Frame.Contains (touch.LocationInView (View))) lblTouchStatus.Text = "TouchesBegan"; //==== IMAGE DOUBLE TAP - if(touch.TapCount == 2 && imgTapMe.Frame.Contains (touch.LocationInView (View))) { + if (touch.TapCount == 2 && imgTapMe.Frame.Contains (touch.LocationInView (View))) { if (imageHighlighted) imgTapMe.Image = UIImage.FromBundle ("Images/DoubleTapMe.png"); else @@ -99,8 +97,8 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) if (touchStartedInside) { // move the shape - nfloat offsetX = touch.PreviousLocationInView (View).X - touch.LocationInView(View).X; - nfloat offsetY = touch.PreviousLocationInView (View).Y - touch.LocationInView(View).Y; + nfloat offsetX = touch.PreviousLocationInView (View).X - touch.LocationInView (View).X; + nfloat offsetY = touch.PreviousLocationInView (View).Y - touch.LocationInView (View).Y; imgDragMe.Frame = new CGRect (new CGPoint (imgDragMe.Frame.X - offsetX, imgDragMe.Frame.Y - offsetY), imgDragMe.Frame.Size); } } diff --git a/TouchesClassic/Classes/AppDelegate.cs b/TouchesClassic/Classes/AppDelegate.cs index d2e17eaeb..ad2e9bbaf 100644 --- a/TouchesClassic/Classes/AppDelegate.cs +++ b/TouchesClassic/Classes/AppDelegate.cs @@ -1,4 +1,4 @@ -// +// // AppDelegate.cs // // Author: @@ -30,11 +30,9 @@ using Foundation; using UIKit; -namespace TouchesClassic -{ +namespace TouchesClassic { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; TouchesClassicViewController viewController; diff --git a/TouchesClassic/Classes/TouchesClassicViewController.cs b/TouchesClassic/Classes/TouchesClassicViewController.cs index a23bc0ab4..2993bc066 100644 --- a/TouchesClassic/Classes/TouchesClassicViewController.cs +++ b/TouchesClassic/Classes/TouchesClassicViewController.cs @@ -1,4 +1,4 @@ - + // // TouchesClassicViewController.cs // @@ -31,10 +31,8 @@ using UIKit; using Foundation; -namespace TouchesClassic -{ - public partial class TouchesClassicViewController : UIViewController - { +namespace TouchesClassic { + public partial class TouchesClassicViewController : UIViewController { private float padding = 10f; public TouchesClassicViewController (UIWindow window, string nibName, NSBundle bundle) : base (nibName, bundle) @@ -72,7 +70,7 @@ public override void TouchesBegan (NSSet touchesSet, UIEvent evt) touchInfoLabel.Text = ""; var numTaps = touches.Sum (t => t.TapCount); - if (numTaps >= 2){ + if (numTaps >= 2) { touchInfoLabel.Text = string.Format ("{0} taps", numTaps); if (numTaps == 2 && piecesOnTop) { // recieved double tap -> align the three pieces diagonal. diff --git a/TouchesClassic/OtherSources/Main.cs b/TouchesClassic/OtherSources/Main.cs index ef66ef327..f8b085723 100644 --- a/TouchesClassic/OtherSources/Main.cs +++ b/TouchesClassic/OtherSources/Main.cs @@ -1,4 +1,4 @@ -// +// // Main.cs // // Author: @@ -30,11 +30,9 @@ using Foundation; using UIKit; -namespace TouchesClassic -{ - public class Application - { - static void Main (string[] args) +namespace TouchesClassic { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/Touches_GestureRecognizers/Classes/AppDelegate.cs b/Touches_GestureRecognizers/Classes/AppDelegate.cs index bbeeae756..e593588ad 100644 --- a/Touches_GestureRecognizers/Classes/AppDelegate.cs +++ b/Touches_GestureRecognizers/Classes/AppDelegate.cs @@ -30,11 +30,9 @@ using Foundation; using UIKit; -namespace Touches_GestureRecognizers -{ +namespace Touches_GestureRecognizers { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; Touches_GestureRecognizersViewController viewController; diff --git a/Touches_GestureRecognizers/Classes/Touches_GestureRecognizersViewController.cs b/Touches_GestureRecognizers/Classes/Touches_GestureRecognizersViewController.cs index 03c8d3c1f..676bb37ea 100644 --- a/Touches_GestureRecognizers/Classes/Touches_GestureRecognizersViewController.cs +++ b/Touches_GestureRecognizers/Classes/Touches_GestureRecognizersViewController.cs @@ -31,10 +31,8 @@ using Foundation; using ObjCRuntime; -namespace Touches_GestureRecognizers -{ - public partial class Touches_GestureRecognizersViewController : UIViewController - { +namespace Touches_GestureRecognizers { + public partial class Touches_GestureRecognizersViewController : UIViewController { public Touches_GestureRecognizersViewController (UIWindow window, string nibName, NSBundle bundle) : base (nibName, bundle) { @@ -59,8 +57,7 @@ protected override void Dispose (bool disposing) #endregion #region Set up - class GestureDelegate : UIGestureRecognizerDelegate - { + class GestureDelegate : UIGestureRecognizerDelegate { Touches_GestureRecognizersViewController controller; public GestureDelegate (Touches_GestureRecognizersViewController controller) @@ -68,7 +65,7 @@ public GestureDelegate (Touches_GestureRecognizersViewController controller) this.controller = controller; } - public override bool ShouldReceiveTouch(UIGestureRecognizer aRecogniser, UITouch aTouch) + public override bool ShouldReceiveTouch (UIGestureRecognizer aRecogniser, UITouch aTouch) { return true; } @@ -139,13 +136,13 @@ void AdjustAnchorPointForGestureRecognizer (UIGestureRecognizer gestureRecognize } // Reset image to the default anchor point and transform - [Export("ResetImage:")] + [Export ("ResetImage:")] void ResetImage (UIMenuController controller) { var mid = new CGPoint ((imageForReset.Bounds.Left + imageForReset.Bounds.Right) / 2, (imageForReset.Bounds.Top + imageForReset.Bounds.Bottom) / 2); var locationInSuperview = imageForReset.ConvertPointToView (mid, imageForReset.Superview); imageForReset.Layer.AnchorPoint = new CGPoint (0.5f, 0.5f); - imageForReset.Center =locationInSuperview; + imageForReset.Center = locationInSuperview; UIView.BeginAnimations (null, IntPtr.Zero); imageForReset.Transform = CoreGraphics.CGAffineTransform.MakeIdentity (); @@ -198,7 +195,7 @@ void ScaleImage (UIPinchGestureRecognizer gestureRecognizer) UIView imageForReset; // Display a menu with a single item to allow the piece's transform to be reset - [Export("ShowResetMenu:")] + [Export ("ShowResetMenu:")] void ShowResetMenu (UILongPressGestureRecognizer gestureRecognizer) { if (gestureRecognizer.State == UIGestureRecognizerState.Began) { @@ -209,7 +206,7 @@ void ShowResetMenu (UILongPressGestureRecognizer gestureRecognizer) menuController.MenuItems = new [] { resetMenuItem }; menuController.SetTargetRect (new CGRect (location.X, location.Y, 0, 0), gestureRecognizer.View); menuController.MenuVisible = true; -// menuController.Animated = true; + // menuController.Animated = true; imageForReset = gestureRecognizer.View; } } diff --git a/Touches_GestureRecognizers/Other Sources/Main.cs b/Touches_GestureRecognizers/Other Sources/Main.cs index eb7ee60ad..b729e0444 100644 --- a/Touches_GestureRecognizers/Other Sources/Main.cs +++ b/Touches_GestureRecognizers/Other Sources/Main.cs @@ -30,11 +30,9 @@ using Foundation; using UIKit; -namespace Touches_GestureRecognizers -{ - public class Application - { - static void Main (string[] args) +namespace Touches_GestureRecognizers { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CECardsAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CECardsAnimationController.cs index 7e5efa061..08ac5d7e0 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CECardsAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CECardsAnimationController.cs @@ -4,13 +4,11 @@ using Foundation; using UIKit; -namespace TransitionsDemo.AnimationControllers -{ - public class CECardsAnimationController : CEReversibleAnimationController - { +namespace TransitionsDemo.AnimationControllers { + public class CECardsAnimationController : CEReversibleAnimationController { public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { if (Reverse) { ExecuteReverseAnimation (transitionContext, fromViewController, toViewController, fromView, toView); @@ -20,8 +18,8 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr } private void ExecuteReverseAnimation (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { UIView containerView = transitionContext.ContainerView; @@ -67,8 +65,8 @@ private void ExecuteReverseAnimation (IUIViewControllerContextTransitioning tran } private void ExecuteForwardAnimation (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { UIView containerView = transitionContext.ContainerView; @@ -94,7 +92,7 @@ private void ExecuteForwardAnimation (IUIViewControllerContextTransitioning tran UIView.AddKeyframeWithRelativeStartTime (0.6, 0.2, () => { toView.Frame = new CGRect (toView.Frame.X, containerView.Frame.Y - 30f, - toView.Frame.Width, toView.Frame.Height); + toView.Frame.Width, toView.Frame.Height); }); UIView.AddKeyframeWithRelativeStartTime (0.8, 0.2, () => { @@ -113,7 +111,7 @@ private CATransform3D GetFirstTransform () var firstTransform = CATransform3D.Identity; firstTransform.m34 = 1f / -900f; firstTransform = firstTransform.Scale (0.95f, 0.95f, 1f); - firstTransform = firstTransform.Rotate (15.0f * (float)Math.PI / 180f, 1f, 0f, 0f); + firstTransform = firstTransform.Rotate (15.0f * (float) Math.PI / 180f, 1f, 0f, 0f); return firstTransform; } diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CECrossfadeAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CECrossfadeAnimationController.cs index 38c380c19..8d0e74e8c 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CECrossfadeAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CECrossfadeAnimationController.cs @@ -2,17 +2,15 @@ using UIKit; using Foundation; -namespace TransitionsDemo.AnimationControllers -{ - public class CECrossfadeAnimationController : CEReversibleAnimationController - { +namespace TransitionsDemo.AnimationControllers { + public class CECrossfadeAnimationController : CEReversibleAnimationController { public CECrossfadeAnimationController () { } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { UIView containerView = transitionContext.ContainerView; containerView.AddSubview (toView); diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEExplosionAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEExplosionAnimationController.cs index fa01c9411..4f2022e97 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEExplosionAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEExplosionAnimationController.cs @@ -4,17 +4,15 @@ using Foundation; using UIKit; -namespace TransitionsDemo.AnimationControllers -{ - public class CEExplosionAnimationController : CEReversibleAnimationController - { +namespace TransitionsDemo.AnimationControllers { + public class CEExplosionAnimationController : CEReversibleAnimationController { public CEExplosionAnimationController () { } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { UIView containerView = transitionContext.ContainerView; containerView.AddSubview (toView); diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFlipAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFlipAnimationController.cs index 4e5526852..98f2e7978 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFlipAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFlipAnimationController.cs @@ -5,17 +5,15 @@ using System.Collections.Generic; using CoreGraphics; -namespace TransitionsDemo.AnimationControllers -{ - public class CEFlipAnimationController : CEReversibleAnimationController - { +namespace TransitionsDemo.AnimationControllers { + public class CEFlipAnimationController : CEReversibleAnimationController { public CEFlipAnimationController () { } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { UIView containerView = transitionContext.ContainerView; containerView.AddSubview (toView); @@ -47,12 +45,12 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr UpdateAnchorPointAndOffset (new CGPoint (Reverse ? 0f : 1f, 0.5f), flippedSectionOfFromView); UpdateAnchorPointAndOffset (new CGPoint (Reverse ? 1f : 0f, 0.5f), flippedSectionOfToView); - flippedSectionOfToView.Layer.Transform = Rotate (Reverse ? (float)Math.PI / 2 : -(float)Math.PI / 2); + flippedSectionOfToView.Layer.Transform = Rotate (Reverse ? (float) Math.PI / 2 : -(float) Math.PI / 2); double duration = TransitionDuration (transitionContext); Action animations = () => { UIView.AddKeyframeWithRelativeStartTime (0.0, 0.5, () => { - flippedSectionOfFromView.Layer.Transform = Rotate (Reverse ? -(float)Math.PI / 2 : (float)Math.PI / 2); + flippedSectionOfFromView.Layer.Transform = Rotate (Reverse ? -(float) Math.PI / 2 : (float) Math.PI / 2); flippedSectionOfFromViewShadow.Alpha = 1f; }); @@ -92,14 +90,14 @@ private UIView AddShadowToView (UIView view, bool reverse) var shadowView = new UIView (viewWithShadow.Bounds); - var colors = new CGColor[] { + var colors = new CGColor [] { UIColor.FromWhiteAlpha(0f, 0f).CGColor, UIColor.FromWhiteAlpha(0f, 0.5f).CGColor }; var gradient = new CAGradientLayer () { Frame = shadowView.Bounds, - Colors = colors + Colors = colors }; gradient.StartPoint = new CGPoint (reverse ? 0f : 1f, 0f); @@ -134,7 +132,7 @@ private List<UIView> CreateSnapshots (UIView view, bool afterScreenUpdates) private void UpdateAnchorPointAndOffset (CGPoint anchorPoint, UIView view) { view.Layer.AnchorPoint = anchorPoint; - float newX = (float)(view.Frame.X + (anchorPoint.X - 0.5f) * view.Frame.Width); + float newX = (float) (view.Frame.X + (anchorPoint.X - 0.5f) * view.Frame.Width); view.Frame = new CGRect (newX, view.Frame.Y, view.Frame.Width, view.Frame.Height); } diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFoldAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFoldAnimationController.cs index 8e9905e1c..52c2cf954 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFoldAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEFoldAnimationController.cs @@ -5,10 +5,8 @@ using CoreGraphics; using Foundation; -namespace TransitionsDemo.AnimationControllers -{ - public class CEFoldAnimationController : CEReversibleAnimationController - { +namespace TransitionsDemo.AnimationControllers { + public class CEFoldAnimationController : CEReversibleAnimationController { public int Folds { get; private set; } public CEFoldAnimationController () @@ -17,8 +15,8 @@ public CEFoldAnimationController () } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { // Add the toView to the container UIView containerView = transitionContext.ContainerView; @@ -33,7 +31,7 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr CGSize size = toView.Frame.Size; - float foldWidth = (float)(size.Width * 0.5f / Folds); + float foldWidth = (float) (size.Width * 0.5f / Folds); // arrays that hold the snapshot views var fromViewFolds = new List<UIView> (); @@ -58,12 +56,12 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr // on the shadow, with each view positioned at the very edge of the screen UIView leftToViewFold = CreateSnapshot (toView, true, offset, true); leftToViewFold.Layer.Position = new CGPoint (Reverse ? size.Width : 0f, size.Height / 2f); - leftToViewFold.Layer.Transform = CATransform3D.MakeRotation ((float)Math.PI / 2f, 0f, 1f, 0f); + leftToViewFold.Layer.Transform = CATransform3D.MakeRotation ((float) Math.PI / 2f, 0f, 1f, 0f); toViewFolds.Add (leftToViewFold); UIView rightToViewFold = CreateSnapshot (toView, true, offset + foldWidth, false); rightToViewFold.Layer.Position = new CGPoint (Reverse ? size.Width : 0f, size.Height / 2f); - rightToViewFold.Layer.Transform = CATransform3D.MakeRotation (-(float)Math.PI / 2f, 0f, 1f, 0f); + rightToViewFold.Layer.Transform = CATransform3D.MakeRotation (-(float) Math.PI / 2f, 0f, 1f, 0f); toViewFolds.Add (rightToViewFold); } @@ -82,12 +80,12 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr // on the shadow, with each view positioned at the edge of thw screen. UIView leftFromView = fromViewFolds [i * 2]; leftFromView.Layer.Position = new CGPoint (Reverse ? 0f : size.Width, size.Height / 2f); - leftFromView.Layer.Transform = transform.Rotate ((float)Math.PI / 2f, 0f, 1f, 0f); + leftFromView.Layer.Transform = transform.Rotate ((float) Math.PI / 2f, 0f, 1f, 0f); leftFromView.Subviews [1].Alpha = 1f; UIView rightFromView = fromViewFolds [i * 2 + 1]; rightFromView.Layer.Position = new CGPoint (Reverse ? 0f : size.Width, size.Height / 2f); - rightFromView.Layer.Transform = transform.Rotate (-(float)Math.PI / 2f, 0f, 1f, 0f); + rightFromView.Layer.Transform = transform.Rotate (-(float) Math.PI / 2f, 0f, 1f, 0f); rightFromView.Subviews [1].Alpha = 1f; // the left and right side of the fold for the to- view, with identity transform and 0.0 alpha @@ -126,7 +124,7 @@ private UIView CreateSnapshot (UIView view, bool afterUpdates, float offset, boo { CGSize size = view.Frame.Size; UIView containerView = view.Superview; - float foldWidth = (float)(size.Width * 0.5f / Folds); + float foldWidth = (float) (size.Width * 0.5f / Folds); UIView snapshotView; @@ -164,7 +162,7 @@ private UIView AddShadowToView (UIView view, bool left) // create a shadow var shadowView = new UIView (viewWithShadow.Bounds); - var colors = new CGColor[] { + var colors = new CGColor [] { UIColor.FromWhiteAlpha(0f, 0f).CGColor, UIColor.FromWhiteAlpha(0f, 1f).CGColor }; diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEReversibleAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEReversibleAnimationController.cs index fcc6fab34..e85e1b116 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CEReversibleAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CEReversibleAnimationController.cs @@ -2,10 +2,8 @@ using UIKit; using Foundation; -namespace TransitionsDemo.AnimationControllers -{ - public class CEReversibleAnimationController : UIViewControllerAnimatedTransitioning - { +namespace TransitionsDemo.AnimationControllers { + public class CEReversibleAnimationController : UIViewControllerAnimatedTransitioning { public bool Reverse { get; set; } public float Duration { get; private set; } @@ -32,8 +30,8 @@ public override double TransitionDuration (IUIViewControllerContextTransitioning } public virtual void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { } } diff --git a/TransitionsDemo/TransitionsDemo/AnimationControllers/CETurnAnimationController.cs b/TransitionsDemo/TransitionsDemo/AnimationControllers/CETurnAnimationController.cs index 221c6f18b..acb0f776f 100644 --- a/TransitionsDemo/TransitionsDemo/AnimationControllers/CETurnAnimationController.cs +++ b/TransitionsDemo/TransitionsDemo/AnimationControllers/CETurnAnimationController.cs @@ -4,16 +4,13 @@ using CoreAnimation; using Foundation; -namespace TransitionsDemo.AnimationControllers -{ - public enum CEDirection - { +namespace TransitionsDemo.AnimationControllers { + public enum CEDirection { Horizontal = 0, Vertical } - public class CETurnAnimationController : CEReversibleAnimationController - { + public class CETurnAnimationController : CEReversibleAnimationController { public CEDirection TurnDiresction { get; private set; } public CETurnAnimationController () @@ -22,8 +19,8 @@ public CETurnAnimationController () } public override void AnimateTransition (IUIViewControllerContextTransitioning transitionContext, - UIViewController fromViewController, UIViewController toViewController, - UIView fromView, UIView toView) + UIViewController fromViewController, UIViewController toViewController, + UIView fromView, UIView toView) { UIView containerView = transitionContext.ContainerView; containerView.AddSubview (toView); @@ -41,12 +38,12 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr float factor = Reverse ? 1f : -1f; // flip the to VC halfway round - hiding it - toView.Layer.Transform = Rotate (factor * -(float)Math.PI / 2); + toView.Layer.Transform = Rotate (factor * -(float) Math.PI / 2); double duration = TransitionDuration (transitionContext); Action animations = () => { UIView.AddKeyframeWithRelativeStartTime (0.0, 0.5, () => { - fromView.Layer.Transform = Rotate (factor * (float)Math.PI / 2); + fromView.Layer.Transform = Rotate (factor * (float) Math.PI / 2); }); UIView.AddKeyframeWithRelativeStartTime (0.5, 0.5, () => { @@ -62,9 +59,9 @@ public override void AnimateTransition (IUIViewControllerContextTransitioning tr private CATransform3D Rotate (float angle) { if (TurnDiresction == CEDirection.Horizontal) { - return CATransform3D.MakeRotation (angle, 1f, 0f, 0f); + return CATransform3D.MakeRotation (angle, 1f, 0f, 0f); } else { - return CATransform3D.MakeRotation (angle, 0f, 1f, 0f); + return CATransform3D.MakeRotation (angle, 0f, 1f, 0f); } } } diff --git a/TransitionsDemo/TransitionsDemo/AppDelegate.cs b/TransitionsDemo/TransitionsDemo/AppDelegate.cs index 4a652a391..b0137b13a 100644 --- a/TransitionsDemo/TransitionsDemo/AppDelegate.cs +++ b/TransitionsDemo/TransitionsDemo/AppDelegate.cs @@ -6,14 +6,12 @@ using TransitionsDemo.AnimationControllers; using TransitionsDemo.InteractionControllers; -namespace TransitionsDemo -{ +namespace TransitionsDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } diff --git a/TransitionsDemo/TransitionsDemo/CEHorizontalSwipeInteractionController.cs b/TransitionsDemo/TransitionsDemo/CEHorizontalSwipeInteractionController.cs index 1f61147df..61ce9a020 100644 --- a/TransitionsDemo/TransitionsDemo/CEHorizontalSwipeInteractionController.cs +++ b/TransitionsDemo/TransitionsDemo/CEHorizontalSwipeInteractionController.cs @@ -1,9 +1,7 @@ using System; -namespace TransitionsDemo -{ - public class CEHorizontalSwipeInteractionController - { +namespace TransitionsDemo { + public class CEHorizontalSwipeInteractionController { public CEHorizontalSwipeInteractionController () { } diff --git a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEBaseInteractionController.cs b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEBaseInteractionController.cs index cfd20126f..dad3d940a 100644 --- a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEBaseInteractionController.cs +++ b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEBaseInteractionController.cs @@ -1,17 +1,14 @@ using System; using UIKit; -namespace TransitionsDemo.InteractionControllers -{ - public enum CEInteractionOperation - { +namespace TransitionsDemo.InteractionControllers { + public enum CEInteractionOperation { Pop = 0, Dismiss, Tab } - public class CEBaseInteractionController : UIPercentDrivenInteractiveTransition - { + public class CEBaseInteractionController : UIPercentDrivenInteractiveTransition { protected bool shouldCompleteTransition; protected UIViewController viewController; protected UIGestureRecognizer gestureRecognizer; @@ -19,7 +16,7 @@ public class CEBaseInteractionController : UIPercentDrivenInteractiveTransition public bool InteractionInProgress { get; set; } - public virtual void WireToViewController(UIViewController viewController, CEInteractionOperation operation) + public virtual void WireToViewController (UIViewController viewController, CEInteractionOperation operation) { } } diff --git a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEHorizontalSwipeInteractionController.cs b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEHorizontalSwipeInteractionController.cs index 7683f01d9..68fd92bb6 100644 --- a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEHorizontalSwipeInteractionController.cs +++ b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEHorizontalSwipeInteractionController.cs @@ -4,10 +4,8 @@ using ObjCRuntime; using UIKit; -namespace TransitionsDemo.InteractionControllers -{ - public class CEHorizontalSwipeInteractionController : CEBaseInteractionController - { +namespace TransitionsDemo.InteractionControllers { + public class CEHorizontalSwipeInteractionController : CEBaseInteractionController { public override nfloat CompletionSpeed { get { return 1 - PercentComplete; @@ -15,7 +13,7 @@ public override nfloat CompletionSpeed { } public override void WireToViewController (UIKit.UIViewController viewController, - CEInteractionOperation operation) + CEInteractionOperation operation) { this.operation = operation; this.viewController = viewController; @@ -28,7 +26,7 @@ private void PrepareGestureRecognizer (UIView view) view.AddGestureRecognizer (gestureRecognizer); } - [Export("HandleGesture:")] + [Export ("HandleGesture:")] public void HandleGesture (UIPanGestureRecognizer panGestureRecognizer) { CGPoint translation = panGestureRecognizer.TranslationInView (panGestureRecognizer.View.Superview); @@ -72,7 +70,7 @@ private void TrackGestureBegan (CGPoint translation) private void TrackGestureChaged (CGPoint translation) { if (InteractionInProgress) { - float fraction = (float)translation.X / 200f; + float fraction = (float) translation.X / 200f; fraction = Math.Min (Math.Max (fraction, 0f), 1f); shouldCompleteTransition = (fraction > 0.5f); diff --git a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEPinchInteractionController.cs b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEPinchInteractionController.cs index 862d926aa..b40c5ba17 100644 --- a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEPinchInteractionController.cs +++ b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEPinchInteractionController.cs @@ -4,10 +4,8 @@ using Foundation; using CoreGraphics; -namespace TransitionsDemo.InteractionControllers -{ - public class CEPinchInteractionController : CEBaseInteractionController - { +namespace TransitionsDemo.InteractionControllers { + public class CEPinchInteractionController : CEBaseInteractionController { private nfloat startScale; public override nfloat CompletionSpeed { @@ -58,7 +56,7 @@ private void TrackGestureEnded (UIPinchGestureRecognizer pinchGestureRecognizer) private void TrackGestureChaged (UIPinchGestureRecognizer pinchGestureRecognizer) { // compute the current pinch fraction - float fraction = (float)(1f - pinchGestureRecognizer.Scale / startScale); + float fraction = (float) (1f - pinchGestureRecognizer.Scale / startScale); shouldCompleteTransition = (fraction > 0.5); UpdateInteractiveTransition (fraction); } diff --git a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEVerticalSwipeInteractionController.cs b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEVerticalSwipeInteractionController.cs index 53b733be0..2ab6a3dfe 100644 --- a/TransitionsDemo/TransitionsDemo/InteractionControllers/CEVerticalSwipeInteractionController.cs +++ b/TransitionsDemo/TransitionsDemo/InteractionControllers/CEVerticalSwipeInteractionController.cs @@ -4,10 +4,8 @@ using ObjCRuntime; using UIKit; -namespace TransitionsDemo.InteractionControllers -{ - public class CEVerticalSwipeInteractionController : CEBaseInteractionController - { +namespace TransitionsDemo.InteractionControllers { + public class CEVerticalSwipeInteractionController : CEBaseInteractionController { public override nfloat CompletionSpeed { get { return 1 - PercentComplete; @@ -30,7 +28,7 @@ private void PrepareGestureRecognizerInView (UIView view) view.AddGestureRecognizer (gestureRecognizer); } - [Export("HandleGesture:")] + [Export ("HandleGesture:")] public void HandleGesture (UIPanGestureRecognizer gestureRecognizer) { CGPoint translation = gestureRecognizer.TranslationInView (gestureRecognizer.View.Superview); @@ -51,7 +49,7 @@ public void HandleGesture (UIPanGestureRecognizer gestureRecognizer) case UIGestureRecognizerState.Changed: if (InteractionInProgress) { // compute the current position - float fraction = (float)translation.Y / 200f; + float fraction = (float) translation.Y / 200f; fraction = Math.Min (Math.Max (fraction, 0f), 1f); shouldCompleteTransition = (fraction > 0.5f); diff --git a/TransitionsDemo/TransitionsDemo/Main.cs b/TransitionsDemo/TransitionsDemo/Main.cs index 4f9314ee5..a3be99088 100644 --- a/TransitionsDemo/TransitionsDemo/Main.cs +++ b/TransitionsDemo/TransitionsDemo/Main.cs @@ -4,12 +4,10 @@ using Foundation; using UIKit; -namespace TransitionsDemo -{ - public class Application - { +namespace TransitionsDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/TransitionsDemo/TransitionsDemo/NavigationController.cs b/TransitionsDemo/TransitionsDemo/NavigationController.cs index 26e29d2ce..7ac968c6a 100644 --- a/TransitionsDemo/TransitionsDemo/NavigationController.cs +++ b/TransitionsDemo/TransitionsDemo/NavigationController.cs @@ -6,10 +6,8 @@ using ObjCRuntime; using System.Runtime.CompilerServices; -namespace TransitionsDemo -{ - public partial class NavigationController : UINavigationController - { +namespace TransitionsDemo { + public partial class NavigationController : UINavigationController { [Export ("initWithCoder:")] public NavigationController (NSCoder coder) : base (coder) { @@ -18,13 +16,13 @@ public NavigationController (NSCoder coder) : base (coder) [Export ("navigationController:animationControllerForOperation:fromViewController:toViewController:")] public IUIViewControllerAnimatedTransitioning GetAnimationControllerForOperation (UINavigationController navigationController, - UINavigationControllerOperation operation, - UIViewController fromViewController, - UIViewController toViewController) + UINavigationControllerOperation operation, + UIViewController fromViewController, + UIViewController toViewController) { if (AppDelegate.NavigationControllerInteractionController != null) { AppDelegate.NavigationControllerInteractionController.WireToViewController (toViewController, - CEInteractionOperation.Pop); + CEInteractionOperation.Pop); } if (AppDelegate.NavigationControllerAnimationController != null) { diff --git a/TransitionsDemo/TransitionsDemo/SettingsViewController.cs b/TransitionsDemo/TransitionsDemo/SettingsViewController.cs index 1cba0e2ab..314fa5b9d 100644 --- a/TransitionsDemo/TransitionsDemo/SettingsViewController.cs +++ b/TransitionsDemo/TransitionsDemo/SettingsViewController.cs @@ -6,10 +6,8 @@ using TransitionsDemo.AnimationControllers; using TransitionsDemo.InteractionControllers; -namespace TransitionsDemo -{ - public partial class SettingsViewController : UITableViewController - { +namespace TransitionsDemo { + public partial class SettingsViewController : UITableViewController { private List<KeyValuePair<string, Type>> animationControllers; private List<KeyValuePair<string, Type>> interactionControllers; @@ -41,7 +39,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) CEReversibleAnimationController transitionInstance = null; if (transitionType != null) - transitionInstance = (CEReversibleAnimationController)Activator.CreateInstance (transitionType); + transitionInstance = (CEReversibleAnimationController) Activator.CreateInstance (transitionType); if (indexPath.Section == 0) { AppDelegate.NavigationControllerAnimationController = transitionInstance; @@ -54,7 +52,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) CEBaseInteractionController transitionInstance = null; if (interactionType != null) - transitionInstance = (CEBaseInteractionController)Activator.CreateInstance (interactionType); + transitionInstance = (CEBaseInteractionController) Activator.CreateInstance (interactionType); if (indexPath.Section == 2) { AppDelegate.NavigationControllerInteractionController = transitionInstance; @@ -135,7 +133,7 @@ partial void doneButtonPresses (UIBarButtonItem sender) private string ClassToTransitionName (object instance) { - if (instance == null || instance.GetType () == typeof(CEReversibleAnimationController)) + if (instance == null || instance.GetType () == typeof (CEReversibleAnimationController)) return "None"; string animationClass = instance.GetType ().Name; diff --git a/TransitionsDemo/TransitionsDemo/ViewController.cs b/TransitionsDemo/TransitionsDemo/ViewController.cs index 6576e58a8..09a8b765c 100644 --- a/TransitionsDemo/TransitionsDemo/ViewController.cs +++ b/TransitionsDemo/TransitionsDemo/ViewController.cs @@ -5,15 +5,13 @@ using TransitionsDemo.AnimationControllers; using TransitionsDemo.InteractionControllers; -namespace TransitionsDemo -{ - public partial class ViewController : UIViewController, IUIViewControllerTransitioningDelegate - { +namespace TransitionsDemo { + public partial class ViewController : UIViewController, IUIViewControllerTransitioningDelegate { private static nuint colorIndex = 0; private NSArray colors; [Export ("initWithCoder:")] - public ViewController (NSCoder coder) : base(coder) + public ViewController (NSCoder coder) : base (coder) { WeakTransitioningDelegate = this; } @@ -21,7 +19,7 @@ public ViewController (NSCoder coder) : base(coder) public override void ViewDidLoad () { colors = NSArray.FromNSObjects (UIColor.Red, UIColor.Orange, UIColor.Yellow, - UIColor.Green, UIColor.Blue, UIColor.Purple); + UIColor.Green, UIColor.Blue, UIColor.Purple); View.BackgroundColor = colors.GetItem<UIColor> (colorIndex); colorIndex = (colorIndex + 1) % colors.Count; @@ -39,12 +37,12 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) [Export ("animationControllerForPresentedController:presentingController:sourceController:")] public IUIViewControllerAnimatedTransitioning PresentingController (UIViewController presented, - UIViewController presenting, - UIViewController source) + UIViewController presenting, + UIViewController source) { if (AppDelegate.SettingsInteractionController != null) { AppDelegate.SettingsInteractionController.WireToViewController (presented, - CEInteractionOperation.Dismiss); + CEInteractionOperation.Dismiss); } if (AppDelegate.SettingsAnimationController != null) diff --git a/UICatalog/UICatalog/AppDelegate.cs b/UICatalog/UICatalog/AppDelegate.cs index 310f37c46..b42fd3f86 100644 --- a/UICatalog/UICatalog/AppDelegate.cs +++ b/UICatalog/UICatalog/AppDelegate.cs @@ -1,24 +1,22 @@ -using Foundation; +using Foundation; using UIKit; -namespace UICatalog -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace UICatalog { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - var splitViewController = this.Window.RootViewController as UISplitViewController; - splitViewController.PreferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible; + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + var splitViewController = this.Window.RootViewController as UISplitViewController; + splitViewController.PreferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible; - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/UICatalog/UICatalog/Controllers/ActivityIndicatorViewController.cs b/UICatalog/UICatalog/Controllers/ActivityIndicatorViewController.cs index 40a52d262..2394e5d4d 100644 --- a/UICatalog/UICatalog/Controllers/ActivityIndicatorViewController.cs +++ b/UICatalog/UICatalog/Controllers/ActivityIndicatorViewController.cs @@ -1,16 +1,14 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class ActivityIndicatorViewController : UITableViewController - { - public ActivityIndicatorViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class ActivityIndicatorViewController : UITableViewController { + public ActivityIndicatorViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.tintedActivityIndicatorView.Color = UIColor.Purple; - } - } -} \ No newline at end of file + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.tintedActivityIndicatorView.Color = UIColor.Purple; + } + } +} diff --git a/UICatalog/UICatalog/Controllers/AlertControllerViewController.cs b/UICatalog/UICatalog/Controllers/AlertControllerViewController.cs index 268955fc0..40c1b4381 100644 --- a/UICatalog/UICatalog/Controllers/AlertControllerViewController.cs +++ b/UICatalog/UICatalog/Controllers/AlertControllerViewController.cs @@ -2,242 +2,232 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class AlertControllerViewController : UITableViewController - { - // Alert style alerts. - private readonly Action[] alertActions; - - // Action sheet style alerts. - private readonly Action[] sheetActions; - - public AlertControllerViewController(IntPtr handle) : base(handle) - { - alertActions = new Action[] - { - ShowSimpleAlert, - ShowOkayCancelAlert, - ShowOtherAlert, - ShowTextEntryAlert, - ShowSecureTextEntryAlert - }; - - sheetActions = new Action[] - { - ShowOkayCancelActionSheet, - ShowOtherActionSheet - }; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - if (indexPath.Section == 0) - { - alertActions[indexPath.Row].Invoke(); - } - else - { - sheetActions[indexPath.Row].Invoke(); - } - - tableView.DeselectRow(indexPath, true); - } - - #region actions - - /// <summary> - /// Show an alert with an "Okay" button. - /// </summary> - private void ShowSimpleAlert() - { - var title = "A Short Title is Best"; - var message = "A message should be a short, complete sentence."; - var cancelButtonTitle = "OK"; - - const string msg = "The simple alert's cancel action occured."; - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - var cancelAction = UIAlertAction.Create(cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => Console.WriteLine(msg)); - - // Add the action. - alertController.AddAction(cancelAction); - PresentViewController(alertController, true, null); - } - - /// <summary> - /// Show an alert with an "Okay" and "Cancel" button. - /// </summary> - private void ShowOkayCancelAlert() - { - const string title = "A Short Title is Best"; - const string message = "A message should be a short, complete sentence."; - - var alertCotroller = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - // Create the actions. - var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine("The 'Cancel' alert's cancel action occured.")); - - var otherAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default, alertAction => Console.WriteLine("The 'OK' alert's other action occured.")); - - // Add the actions. - alertCotroller.AddAction(cancelAction); - alertCotroller.AddAction(otherAction); - - PresentViewController(alertCotroller, true, null); - } - - /// <summary> - /// Show an alert with two custom buttons. - /// </summary> - private void ShowOtherAlert() - { - const string title = "A Short Title is Best"; - const string message = "A message should be a short, complete sentence."; - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - - // Create the actions. - var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine("The 'Other' alert's cancel action occured.")); - var otherButtonOneAction = UIAlertAction.Create("Choice One", UIAlertActionStyle.Default, alertAction => Console.WriteLine("The 'Other' alert's other button one action occured.")); - var otherButtonTwoAction = UIAlertAction.Create("Choice Two", UIAlertActionStyle.Default, alertAction => Console.WriteLine("The 'Other' alert's other button two action occured.")); - - // Add the actions. - alertController.AddAction(cancelAction); - alertController.AddAction(otherButtonOneAction); - alertController.AddAction(otherButtonTwoAction); - - PresentViewController(alertController, true, null); - } - - /// <summary> - /// Show a text entry alert with two custom buttons. - /// </summary> - private void ShowTextEntryAlert() - { - const string title = "A Short Title is Best"; - const string message = "A message should be a short, complete sentence."; - - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - - // Add the text field for text entry. - alertController.AddTextField(textField => { /* If you need to customize the text field, you can do so here. */ }); - - // Create the actions. - var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine("The 'Text Entry' alert's cancel action occured.")); - var otherAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default, alertAction => Console.WriteLine("The 'Text Entry' alert's other action occured.")); - - // Add the actions. - alertController.AddAction(cancelAction); - alertController.AddAction(otherAction); - - PresentViewController(alertController, true, null); - } - - /// <summary> - /// Show a secure text entry alert with two custom buttons. - /// </summary> - private void ShowSecureTextEntryAlert() - { - NSObject observer = null; - const string title = "A Short Title is Best"; - const string message = "A message should be a short, complete sentence."; - - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - - // Create the actions. - var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alertAction => - { - Console.WriteLine("The 'Secure Text Entry' alert's cancel action occured."); - RemoveObserver(); - }); - - var otherAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default, alertAction => - { - Console.WriteLine("The 'Secure Text Entry' alert's other action occured."); - RemoveObserver(); - }); - - // The text field initially has no text in the text field, so we'll disable it. - otherAction.Enabled = false; - - // Add the text field for the secure text entry. - alertController.AddTextField(textField => - { - // Listen for changes to the text field's text so that we can toggle the current - // action's enabled property based on whether the user has entered a sufficiently - // secure entry. - observer = UITextField.Notifications.ObserveTextFieldTextDidChange(textField, (sender, e) => - { - otherAction.Enabled = textField.Text.Length >= 5; - }); - textField.SecureTextEntry = true; - }); - - // Add the actions. - alertController.AddAction(cancelAction); - alertController.AddAction(otherAction); - - PresentViewController(alertController, true, null); - - void RemoveObserver() - { - // Stop listening for text change notifications on the text field. - NSNotificationCenter.DefaultCenter.RemoveObserver(observer); - observer.Dispose(); - observer = null; - } - } - - #endregion - - #region sheet actions - - /// <summary> - /// Show a dialog with an "Okay" and "Cancel" button. - /// </summary> - private void ShowOkayCancelActionSheet() - { - var alertController = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet); - - // Create the actions. - var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Default, _ => Console.WriteLine("The 'Okay-Cancel' alert action sheet's cancel action occured.")); - var destructiveAction = UIAlertAction.Create("OK", UIAlertActionStyle.Destructive, _ => Console.WriteLine("The 'Okay-Cancel' alert action sheet's destructive action occured.")); - - // Add the actions. - alertController.AddAction(cancelAction); - alertController.AddAction(destructiveAction); - - SetupPopover(alertController, okayActionSheetCell); - PresentViewController(alertController, true, null); - } - - /// <summary> - /// Show a dialog with two custom buttons. - /// </summary> - private void ShowOtherActionSheet() - { - var alertController = UIAlertController.Create(null, null, UIAlertControllerStyle.ActionSheet); - - // Create the actions. - var destructiveAction = UIAlertAction.Create("Destructive Choice", UIAlertActionStyle.Destructive, _ => Console.WriteLine("The 'Other' alert action sheet's destructive action occured.")); - var otherAction = UIAlertAction.Create("Safe Choice", UIAlertActionStyle.Default, _ => Console.WriteLine("The 'Other' alert action sheet's other action occured.")); - - // Add the actions. - alertController.AddAction(destructiveAction); - alertController.AddAction(otherAction); - - SetupPopover(alertController, otherActionSheetCell); - PresentViewController(alertController, true, null); - } - - private static void SetupPopover(UIAlertController alertController, UIView sourceView) - { - var popover = alertController.PopoverPresentationController; - if (popover != null) - { - popover.SourceView = sourceView; - popover.SourceRect = sourceView.Bounds; - } - } - - #endregion - } -} \ No newline at end of file +namespace UICatalog { + public partial class AlertControllerViewController : UITableViewController { + // Alert style alerts. + private readonly Action [] alertActions; + + // Action sheet style alerts. + private readonly Action [] sheetActions; + + public AlertControllerViewController (IntPtr handle) : base (handle) + { + alertActions = new Action [] + { + ShowSimpleAlert, + ShowOkayCancelAlert, + ShowOtherAlert, + ShowTextEntryAlert, + ShowSecureTextEntryAlert + }; + + sheetActions = new Action [] + { + ShowOkayCancelActionSheet, + ShowOtherActionSheet + }; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + if (indexPath.Section == 0) { + alertActions [indexPath.Row].Invoke (); + } else { + sheetActions [indexPath.Row].Invoke (); + } + + tableView.DeselectRow (indexPath, true); + } + + #region actions + + /// <summary> + /// Show an alert with an "Okay" button. + /// </summary> + private void ShowSimpleAlert () + { + var title = "A Short Title is Best"; + var message = "A message should be a short, complete sentence."; + var cancelButtonTitle = "OK"; + + const string msg = "The simple alert's cancel action occured."; + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, alertAction => Console.WriteLine (msg)); + + // Add the action. + alertController.AddAction (cancelAction); + PresentViewController (alertController, true, null); + } + + /// <summary> + /// Show an alert with an "Okay" and "Cancel" button. + /// </summary> + private void ShowOkayCancelAlert () + { + const string title = "A Short Title is Best"; + const string message = "A message should be a short, complete sentence."; + + var alertCotroller = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + // Create the actions. + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine ("The 'Cancel' alert's cancel action occured.")); + + var otherAction = UIAlertAction.Create ("OK", UIAlertActionStyle.Default, alertAction => Console.WriteLine ("The 'OK' alert's other action occured.")); + + // Add the actions. + alertCotroller.AddAction (cancelAction); + alertCotroller.AddAction (otherAction); + + PresentViewController (alertCotroller, true, null); + } + + /// <summary> + /// Show an alert with two custom buttons. + /// </summary> + private void ShowOtherAlert () + { + const string title = "A Short Title is Best"; + const string message = "A message should be a short, complete sentence."; + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + + // Create the actions. + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine ("The 'Other' alert's cancel action occured.")); + var otherButtonOneAction = UIAlertAction.Create ("Choice One", UIAlertActionStyle.Default, alertAction => Console.WriteLine ("The 'Other' alert's other button one action occured.")); + var otherButtonTwoAction = UIAlertAction.Create ("Choice Two", UIAlertActionStyle.Default, alertAction => Console.WriteLine ("The 'Other' alert's other button two action occured.")); + + // Add the actions. + alertController.AddAction (cancelAction); + alertController.AddAction (otherButtonOneAction); + alertController.AddAction (otherButtonTwoAction); + + PresentViewController (alertController, true, null); + } + + /// <summary> + /// Show a text entry alert with two custom buttons. + /// </summary> + private void ShowTextEntryAlert () + { + const string title = "A Short Title is Best"; + const string message = "A message should be a short, complete sentence."; + + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + + // Add the text field for text entry. + alertController.AddTextField (textField => { /* If you need to customize the text field, you can do so here. */ }); + + // Create the actions. + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine ("The 'Text Entry' alert's cancel action occured.")); + var otherAction = UIAlertAction.Create ("OK", UIAlertActionStyle.Default, alertAction => Console.WriteLine ("The 'Text Entry' alert's other action occured.")); + + // Add the actions. + alertController.AddAction (cancelAction); + alertController.AddAction (otherAction); + + PresentViewController (alertController, true, null); + } + + /// <summary> + /// Show a secure text entry alert with two custom buttons. + /// </summary> + private void ShowSecureTextEntryAlert () + { + NSObject observer = null; + const string title = "A Short Title is Best"; + const string message = "A message should be a short, complete sentence."; + + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + + // Create the actions. + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alertAction => { + Console.WriteLine ("The 'Secure Text Entry' alert's cancel action occured."); + RemoveObserver (); + }); + + var otherAction = UIAlertAction.Create ("OK", UIAlertActionStyle.Default, alertAction => { + Console.WriteLine ("The 'Secure Text Entry' alert's other action occured."); + RemoveObserver (); + }); + + // The text field initially has no text in the text field, so we'll disable it. + otherAction.Enabled = false; + + // Add the text field for the secure text entry. + alertController.AddTextField (textField => { + // Listen for changes to the text field's text so that we can toggle the current + // action's enabled property based on whether the user has entered a sufficiently + // secure entry. + observer = UITextField.Notifications.ObserveTextFieldTextDidChange (textField, (sender, e) => { + otherAction.Enabled = textField.Text.Length >= 5; + }); + textField.SecureTextEntry = true; + }); + + // Add the actions. + alertController.AddAction (cancelAction); + alertController.AddAction (otherAction); + + PresentViewController (alertController, true, null); + + void RemoveObserver () + { + // Stop listening for text change notifications on the text field. + NSNotificationCenter.DefaultCenter.RemoveObserver (observer); + observer.Dispose (); + observer = null; + } + } + + #endregion + + #region sheet actions + + /// <summary> + /// Show a dialog with an "Okay" and "Cancel" button. + /// </summary> + private void ShowOkayCancelActionSheet () + { + var alertController = UIAlertController.Create (null, null, UIAlertControllerStyle.ActionSheet); + + // Create the actions. + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Default, _ => Console.WriteLine ("The 'Okay-Cancel' alert action sheet's cancel action occured.")); + var destructiveAction = UIAlertAction.Create ("OK", UIAlertActionStyle.Destructive, _ => Console.WriteLine ("The 'Okay-Cancel' alert action sheet's destructive action occured.")); + + // Add the actions. + alertController.AddAction (cancelAction); + alertController.AddAction (destructiveAction); + + SetupPopover (alertController, okayActionSheetCell); + PresentViewController (alertController, true, null); + } + + /// <summary> + /// Show a dialog with two custom buttons. + /// </summary> + private void ShowOtherActionSheet () + { + var alertController = UIAlertController.Create (null, null, UIAlertControllerStyle.ActionSheet); + + // Create the actions. + var destructiveAction = UIAlertAction.Create ("Destructive Choice", UIAlertActionStyle.Destructive, _ => Console.WriteLine ("The 'Other' alert action sheet's destructive action occured.")); + var otherAction = UIAlertAction.Create ("Safe Choice", UIAlertActionStyle.Default, _ => Console.WriteLine ("The 'Other' alert action sheet's other action occured.")); + + // Add the actions. + alertController.AddAction (destructiveAction); + alertController.AddAction (otherAction); + + SetupPopover (alertController, otherActionSheetCell); + PresentViewController (alertController, true, null); + } + + private static void SetupPopover (UIAlertController alertController, UIView sourceView) + { + var popover = alertController.PopoverPresentationController; + if (popover != null) { + popover.SourceView = sourceView; + popover.SourceRect = sourceView.Bounds; + } + } + + #endregion + } +} diff --git a/UICatalog/UICatalog/Controllers/ButtonsViewController.cs b/UICatalog/UICatalog/Controllers/ButtonsViewController.cs index ee2dae711..763ac282f 100644 --- a/UICatalog/UICatalog/Controllers/ButtonsViewController.cs +++ b/UICatalog/UICatalog/Controllers/ButtonsViewController.cs @@ -1,63 +1,59 @@ -using Foundation; -using System; -using UIKit; - -namespace UICatalog -{ - public partial class ButtonsViewController : UITableViewController - { - public ButtonsViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ConfigureAttributedTextSystemButton(); - } - - private void ConfigureAttributedTextSystemButton() - { - var attributes = new UIStringAttributes - { - ForegroundColor = UIColor.Blue, - StrikethroughStyle = NSUnderlineStyle.Single, - }; - - var titleAttributes = new NSAttributedString("Button", attributes); - attributedButton.SetAttributedTitle(titleAttributes, UIControlState.Normal); - - var highlightedTitleAttributes = new UIStringAttributes - { - ForegroundColor = UIColor.Green, - StrikethroughStyle = NSUnderlineStyle.Thick - }; - - var highlightedAttributedTitle = new NSAttributedString("Button", highlightedTitleAttributes); - attributedButton.SetAttributedTitle(highlightedAttributedTitle, UIControlState.Highlighted); - } - - partial void AttributedButtonTouched(NSObject sender) - { - Console.WriteLine("'Attributed' button was clicked"); - } - - partial void ImageButtonTouched(NSObject sender) - { - Console.WriteLine("'Image' button was clicked"); - } - - partial void SystemButtonTouched(NSObject sender) - { - Console.WriteLine("'System' button was clicked"); - } - - partial void SystemDetailsButtonTouched(NSObject sender) - { - Console.WriteLine("'System Details' button was clicked"); - } - - partial void SystemContactButtonTouched(NSObject sender) - { - Console.WriteLine("'System Contact' button was clicked"); - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace UICatalog { + public partial class ButtonsViewController : UITableViewController { + public ButtonsViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ConfigureAttributedTextSystemButton (); + } + + private void ConfigureAttributedTextSystemButton () + { + var attributes = new UIStringAttributes { + ForegroundColor = UIColor.Blue, + StrikethroughStyle = NSUnderlineStyle.Single, + }; + + var titleAttributes = new NSAttributedString ("Button", attributes); + attributedButton.SetAttributedTitle (titleAttributes, UIControlState.Normal); + + var highlightedTitleAttributes = new UIStringAttributes { + ForegroundColor = UIColor.Green, + StrikethroughStyle = NSUnderlineStyle.Thick + }; + + var highlightedAttributedTitle = new NSAttributedString ("Button", highlightedTitleAttributes); + attributedButton.SetAttributedTitle (highlightedAttributedTitle, UIControlState.Highlighted); + } + + partial void AttributedButtonTouched (NSObject sender) + { + Console.WriteLine ("'Attributed' button was clicked"); + } + + partial void ImageButtonTouched (NSObject sender) + { + Console.WriteLine ("'Image' button was clicked"); + } + + partial void SystemButtonTouched (NSObject sender) + { + Console.WriteLine ("'System' button was clicked"); + } + + partial void SystemDetailsButtonTouched (NSObject sender) + { + Console.WriteLine ("'System Details' button was clicked"); + } + + partial void SystemContactButtonTouched (NSObject sender) + { + Console.WriteLine ("'System Contact' button was clicked"); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/DatePickerController.cs b/UICatalog/UICatalog/Controllers/DatePickerController.cs index 36674bc02..0b9640620 100644 --- a/UICatalog/UICatalog/Controllers/DatePickerController.cs +++ b/UICatalog/UICatalog/Controllers/DatePickerController.cs @@ -2,32 +2,29 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class DatePickerController : UIViewController - { - private readonly NSDateFormatter dateFormater = new NSDateFormatter - { - DateStyle = NSDateFormatterStyle.Medium, - TimeStyle = NSDateFormatterStyle.Short, - }; +namespace UICatalog { + public partial class DatePickerController : UIViewController { + private readonly NSDateFormatter dateFormater = new NSDateFormatter { + DateStyle = NSDateFormatterStyle.Medium, + TimeStyle = NSDateFormatterStyle.Short, + }; - public DatePickerController(IntPtr handle) : base(handle) { } + public DatePickerController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.UpdateLabel(); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.UpdateLabel (); + } - partial void PickerValurChanged(NSObject sender) - { - this.UpdateLabel(); - } + partial void PickerValurChanged (NSObject sender) + { + this.UpdateLabel (); + } - private void UpdateLabel() - { - dateLabel.Text = this.dateFormater.ToString(this.datePicker.Date); - } - } -} \ No newline at end of file + private void UpdateLabel () + { + dateLabel.Text = this.dateFormater.ToString (this.datePicker.Date); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/ImageViewController.cs b/UICatalog/UICatalog/Controllers/ImageViewController.cs index 89bd906c8..265840632 100644 --- a/UICatalog/UICatalog/Controllers/ImageViewController.cs +++ b/UICatalog/UICatalog/Controllers/ImageViewController.cs @@ -1,30 +1,28 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class ImageViewController : UIViewController - { - public ImageViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class ImageViewController : UIViewController { + public ImageViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - imageView.AnimationImages = new UIImage[] - { - UIImage.FromBundle("image_animal_1"), - UIImage.FromBundle("image_animal_2"), - UIImage.FromBundle("image_animal_3"), - UIImage.FromBundle("image_animal_4"), - UIImage.FromBundle("image_animal_5") - }; + imageView.AnimationImages = new UIImage [] + { + UIImage.FromBundle("image_animal_1"), + UIImage.FromBundle("image_animal_2"), + UIImage.FromBundle("image_animal_3"), + UIImage.FromBundle("image_animal_4"), + UIImage.FromBundle("image_animal_5") + }; - // We want the image to be scaled to the correct aspect ratio within imageView's bounds. - imageView.ContentMode = UIViewContentMode.ScaleAspectFit; + // We want the image to be scaled to the correct aspect ratio within imageView's bounds. + imageView.ContentMode = UIViewContentMode.ScaleAspectFit; - imageView.AnimationDuration = 5; - imageView.StartAnimating(); - } - } -} \ No newline at end of file + imageView.AnimationDuration = 5; + imageView.StartAnimating (); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/PageControlViewController.cs b/UICatalog/UICatalog/Controllers/PageControlViewController.cs index d63287fb1..0136a2989 100644 --- a/UICatalog/UICatalog/Controllers/PageControlViewController.cs +++ b/UICatalog/UICatalog/Controllers/PageControlViewController.cs @@ -1,41 +1,39 @@ -using Foundation; -using System; -using UIKit; - -namespace UICatalog -{ - public partial class PageControlViewController : UIViewController - { - // Colors that correspond to the selected page. Used as the background color for "colorView". - private readonly UIColor[] colors = - { - UIColor.Black, - UIColor.Gray, - UIColor.Red, - UIColor.Green, - UIColor.Blue, - UIColor.Cyan, - UIColor.Yellow, - UIColor.Magenta, - UIColor.Orange, - UIColor.Purple - }; - - public PageControlViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // The total number of pages that are available is based on how many available colors we have. - pageControl.Pages = colors.Length; - pageControl.CurrentPage = 2; - } - - partial void PageControlValueChanged(NSObject sender) - { - Console.WriteLine($"The page control changed its current page to {pageControl.CurrentPage}."); - colorView.BackgroundColor = colors[pageControl.CurrentPage]; - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace UICatalog { + public partial class PageControlViewController : UIViewController { + // Colors that correspond to the selected page. Used as the background color for "colorView". + private readonly UIColor [] colors = + { + UIColor.Black, + UIColor.Gray, + UIColor.Red, + UIColor.Green, + UIColor.Blue, + UIColor.Cyan, + UIColor.Yellow, + UIColor.Magenta, + UIColor.Orange, + UIColor.Purple + }; + + public PageControlViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // The total number of pages that are available is based on how many available colors we have. + pageControl.Pages = colors.Length; + pageControl.CurrentPage = 2; + } + + partial void PageControlValueChanged (NSObject sender) + { + Console.WriteLine ($"The page control changed its current page to {pageControl.CurrentPage}."); + colorView.BackgroundColor = colors [pageControl.CurrentPage]; + } + } +} diff --git a/UICatalog/UICatalog/Controllers/PickerViewController.cs b/UICatalog/UICatalog/Controllers/PickerViewController.cs index d7c5894b6..4b3eb1154 100644 --- a/UICatalog/UICatalog/Controllers/PickerViewController.cs +++ b/UICatalog/UICatalog/Controllers/PickerViewController.cs @@ -1,138 +1,131 @@ -using Foundation; -using System; +using Foundation; +using System; using System.Collections.Generic; -using UIKit; - -namespace UICatalog -{ - public partial class PickerViewController : UIViewController, IUIPickerViewDataSource, IUIPickerViewDelegate - { - public PickerViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Show that a given row is selected. This is off by default. - pickerView.ShowSelectionIndicator = true; - ConfigurePickerView(); - } - - private void ConfigurePickerView() - { - // Set the default selected rows (the desired rows to initially select will vary from app to app). - var selectedRows = new Dictionary<ColorComponent, int> - { - { ColorComponent.Red, 13 }, - { ColorComponent.Green, 41 }, - { ColorComponent.Blue, 24 } - }; - - // kvp - means KeyValuePair - foreach (var kvp in selectedRows) - { - var selectedRow = kvp.Value; - var colorComponent = (int)kvp.Key; - - // Note that the delegate method on UIPickerViewDelegate is not triggered when manually - // calling UIPickerView.selectRow(:inComponent:animated:). To do this, we fire off delegate - // method manually. - pickerView.Select(selectedRow, colorComponent, true); - Selected(pickerView, selectedRow, colorComponent); - } - } - - #region IUIPickerViewDelegate - - [Export("pickerView:attributedTitleForRow:forComponent:")] - public NSAttributedString GetAttributedTitle(UIPickerView pickerView, nint row, nint component) - { - var colorValue = row * RGB.Offset; - - var value = colorValue / RGB.Max; - var redColorComponent = RGB.Min; - var greenColorComponent = RGB.Min; - var blueColorComponent = RGB.Min; - - switch ((ColorComponent)(int)component) - { - case ColorComponent.Red: - redColorComponent = value; - break; - - case ColorComponent.Green: - greenColorComponent = value; - break; - - case ColorComponent.Blue: - blueColorComponent = value; - break; - - default: - throw new InvalidOperationException("Invalid row/component combination for picker view."); - } - - // Set the foreground color for the entire attributed string. - var foregroundColor = new UIColor(redColorComponent, greenColorComponent, blueColorComponent, 1f); - var attributes = new UIStringAttributes { ForegroundColor = foregroundColor}; - return new NSAttributedString($"{colorValue}", attributes); - } - - [Export("pickerView:didSelectRow:inComponent:")] - public void Selected(UIPickerView pickerView, nint row, nint component) - { - var colorComponentValue = RGB.Offset * row / RGB.Max; - var color = colorView.BackgroundColor; - color.GetRGBA(out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha); - - switch ((ColorComponent)(int)component) - { - case ColorComponent.Red: - color = new UIColor(colorComponentValue, green, blue, alpha); - break; - - case ColorComponent.Green: - color = new UIColor(red, colorComponentValue, blue, alpha); - break; - - case ColorComponent.Blue: - color = new UIColor(red, green, colorComponentValue, alpha); - break; - } - - colorView.BackgroundColor = color; - } - - #endregion - - #region IUIPickerViewDataSource - - public nint GetComponentCount(UIPickerView pickerView) - { - return Enum.GetValues(typeof(ColorComponent)).Length; - } - - public nint GetRowsInComponent(UIPickerView pickerView, nint component) - { - return (int)RGB.Max / (int)RGB.Offset + 1; - } - - #endregion - - /* helpers */ - - enum ColorComponent - { - Red, - Green, - Blue - } - - struct RGB - { - public const float Max = 255f; - public const float Min = 0f; - public const float Offset = 5f; - } - } -} \ No newline at end of file +using UIKit; + +namespace UICatalog { + public partial class PickerViewController : UIViewController, IUIPickerViewDataSource, IUIPickerViewDelegate { + public PickerViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Show that a given row is selected. This is off by default. + pickerView.ShowSelectionIndicator = true; + ConfigurePickerView (); + } + + private void ConfigurePickerView () + { + // Set the default selected rows (the desired rows to initially select will vary from app to app). + var selectedRows = new Dictionary<ColorComponent, int> + { + { ColorComponent.Red, 13 }, + { ColorComponent.Green, 41 }, + { ColorComponent.Blue, 24 } + }; + + // kvp - means KeyValuePair + foreach (var kvp in selectedRows) { + var selectedRow = kvp.Value; + var colorComponent = (int) kvp.Key; + + // Note that the delegate method on UIPickerViewDelegate is not triggered when manually + // calling UIPickerView.selectRow(:inComponent:animated:). To do this, we fire off delegate + // method manually. + pickerView.Select (selectedRow, colorComponent, true); + Selected (pickerView, selectedRow, colorComponent); + } + } + + #region IUIPickerViewDelegate + + [Export ("pickerView:attributedTitleForRow:forComponent:")] + public NSAttributedString GetAttributedTitle (UIPickerView pickerView, nint row, nint component) + { + var colorValue = row * RGB.Offset; + + var value = colorValue / RGB.Max; + var redColorComponent = RGB.Min; + var greenColorComponent = RGB.Min; + var blueColorComponent = RGB.Min; + + switch ((ColorComponent) (int) component) { + case ColorComponent.Red: + redColorComponent = value; + break; + + case ColorComponent.Green: + greenColorComponent = value; + break; + + case ColorComponent.Blue: + blueColorComponent = value; + break; + + default: + throw new InvalidOperationException ("Invalid row/component combination for picker view."); + } + + // Set the foreground color for the entire attributed string. + var foregroundColor = new UIColor (redColorComponent, greenColorComponent, blueColorComponent, 1f); + var attributes = new UIStringAttributes { ForegroundColor = foregroundColor }; + return new NSAttributedString ($"{colorValue}", attributes); + } + + [Export ("pickerView:didSelectRow:inComponent:")] + public void Selected (UIPickerView pickerView, nint row, nint component) + { + var colorComponentValue = RGB.Offset * row / RGB.Max; + var color = colorView.BackgroundColor; + color.GetRGBA (out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha); + + switch ((ColorComponent) (int) component) { + case ColorComponent.Red: + color = new UIColor (colorComponentValue, green, blue, alpha); + break; + + case ColorComponent.Green: + color = new UIColor (red, colorComponentValue, blue, alpha); + break; + + case ColorComponent.Blue: + color = new UIColor (red, green, colorComponentValue, alpha); + break; + } + + colorView.BackgroundColor = color; + } + + #endregion + + #region IUIPickerViewDataSource + + public nint GetComponentCount (UIPickerView pickerView) + { + return Enum.GetValues (typeof (ColorComponent)).Length; + } + + public nint GetRowsInComponent (UIPickerView pickerView, nint component) + { + return (int) RGB.Max / (int) RGB.Offset + 1; + } + + #endregion + + /* helpers */ + + enum ColorComponent { + Red, + Green, + Blue + } + + struct RGB { + public const float Max = 255f; + public const float Min = 0f; + public const float Offset = 5f; + } + } +} diff --git a/UICatalog/UICatalog/Controllers/ProgressViewController.cs b/UICatalog/UICatalog/Controllers/ProgressViewController.cs index bab3e94da..7a92ff909 100644 --- a/UICatalog/UICatalog/Controllers/ProgressViewController.cs +++ b/UICatalog/UICatalog/Controllers/ProgressViewController.cs @@ -1,59 +1,55 @@ -using System; +using System; using System.Timers; -using UIKit; - -namespace UICatalog -{ - public partial class ProgressViewController : UITableViewController - { - private Timer timer = new Timer(500); - - public ProgressViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - defaultProgressView.SetProgress(0f, false); - tintedProgressView.SetProgress(0f, false); - barProgressView.SetProgress(0f, false); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - timer.Elapsed += OnTick; - timer.Start(); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - timer.Stop(); - timer.Elapsed -= OnTick; - } - - private void OnTick(object sender, ElapsedEventArgs e) - { - UpdateProgress(); - } - - private void UpdateProgress() - { - InvokeOnMainThread(() => - { - var value = (new Random()).Next(1, 10) / 100f; - var nextValue = defaultProgressView.Progress + value; - if (nextValue > 1f) - { - nextValue = 1f; - timer.Stop(); - timer.Elapsed -= OnTick; - } - - defaultProgressView.SetProgress(nextValue, true); - tintedProgressView.SetProgress(nextValue, true); - barProgressView.SetProgress(nextValue, true); - }); - } - } -} \ No newline at end of file +using UIKit; + +namespace UICatalog { + public partial class ProgressViewController : UITableViewController { + private Timer timer = new Timer (500); + + public ProgressViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + defaultProgressView.SetProgress (0f, false); + tintedProgressView.SetProgress (0f, false); + barProgressView.SetProgress (0f, false); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + timer.Elapsed += OnTick; + timer.Start (); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + timer.Stop (); + timer.Elapsed -= OnTick; + } + + private void OnTick (object sender, ElapsedEventArgs e) + { + UpdateProgress (); + } + + private void UpdateProgress () + { + InvokeOnMainThread (() => { + var value = (new Random ()).Next (1, 10) / 100f; + var nextValue = defaultProgressView.Progress + value; + if (nextValue > 1f) { + nextValue = 1f; + timer.Stop (); + timer.Elapsed -= OnTick; + } + + defaultProgressView.SetProgress (nextValue, true); + tintedProgressView.SetProgress (nextValue, true); + barProgressView.SetProgress (nextValue, true); + }); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/Search/SearchBar/CustomSearchBarViewController.cs b/UICatalog/UICatalog/Controllers/Search/SearchBar/CustomSearchBarViewController.cs index 27058b2cb..95bec5c8d 100644 --- a/UICatalog/UICatalog/Controllers/Search/SearchBar/CustomSearchBarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Search/SearchBar/CustomSearchBarViewController.cs @@ -1,57 +1,55 @@ -using Foundation; -using System; -using UIKit; - -namespace UICatalog -{ - public partial class CustomSearchBarViewController : UIViewController, IUISearchBarDelegate - { - public CustomSearchBarViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ConfigureSearchBar(); - } - - private void ConfigureSearchBar() - { - searchBar.ShowsCancelButton = true; - searchBar.ShowsBookmarkButton = true; - - searchBar.TintColor = UIColor.Purple; - searchBar.BackgroundImage = UIImage.FromBundle("search_bar_background"); - - // Set the bookmark image for both normal and highlighted states. - var bookmarkImage = UIImage.FromBundle("bookmark_icon"); - searchBar.SetImageforSearchBarIcon(bookmarkImage, UISearchBarIcon.Bookmark, UIControlState.Normal); - - var bookmarkHighlightedImage = UIImage.FromBundle("bookmark_icon_highlighted"); - searchBar.SetImageforSearchBarIcon(bookmarkHighlightedImage, UISearchBarIcon.Bookmark, UIControlState.Highlighted); - } - - #region IUISearchBarDelegate - - [Export("searchBarSearchButtonClicked:")] - public void SearchButtonClicked(UISearchBar searchBar) - { - Console.WriteLine("The custom search bar keyboard search button was tapped."); - searchBar.ResignFirstResponder(); - } - - [Export("searchBarCancelButtonClicked:")] - public void CancelButtonClicked(UISearchBar searchBar) - { - Console.WriteLine("The custom search bar cancel button was tapped."); - searchBar.ResignFirstResponder(); - } - - [Export("searchBarBookmarkButtonClicked:")] - public void BookmarkButtonClicked(UISearchBar searchBar) - { - Console.WriteLine("The custom bookmark button inside the search bar was tapped."); - } - - #endregion - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace UICatalog { + public partial class CustomSearchBarViewController : UIViewController, IUISearchBarDelegate { + public CustomSearchBarViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ConfigureSearchBar (); + } + + private void ConfigureSearchBar () + { + searchBar.ShowsCancelButton = true; + searchBar.ShowsBookmarkButton = true; + + searchBar.TintColor = UIColor.Purple; + searchBar.BackgroundImage = UIImage.FromBundle ("search_bar_background"); + + // Set the bookmark image for both normal and highlighted states. + var bookmarkImage = UIImage.FromBundle ("bookmark_icon"); + searchBar.SetImageforSearchBarIcon (bookmarkImage, UISearchBarIcon.Bookmark, UIControlState.Normal); + + var bookmarkHighlightedImage = UIImage.FromBundle ("bookmark_icon_highlighted"); + searchBar.SetImageforSearchBarIcon (bookmarkHighlightedImage, UISearchBarIcon.Bookmark, UIControlState.Highlighted); + } + + #region IUISearchBarDelegate + + [Export ("searchBarSearchButtonClicked:")] + public void SearchButtonClicked (UISearchBar searchBar) + { + Console.WriteLine ("The custom search bar keyboard search button was tapped."); + searchBar.ResignFirstResponder (); + } + + [Export ("searchBarCancelButtonClicked:")] + public void CancelButtonClicked (UISearchBar searchBar) + { + Console.WriteLine ("The custom search bar cancel button was tapped."); + searchBar.ResignFirstResponder (); + } + + [Export ("searchBarBookmarkButtonClicked:")] + public void BookmarkButtonClicked (UISearchBar searchBar) + { + Console.WriteLine ("The custom bookmark button inside the search bar was tapped."); + } + + #endregion + } +} diff --git a/UICatalog/UICatalog/Controllers/Search/SearchBar/DefaultSearchBarViewController.cs b/UICatalog/UICatalog/Controllers/Search/SearchBar/DefaultSearchBarViewController.cs index ae9efba6f..33a827b1c 100644 --- a/UICatalog/UICatalog/Controllers/Search/SearchBar/DefaultSearchBarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Search/SearchBar/DefaultSearchBarViewController.cs @@ -2,30 +2,28 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class DefaultSearchBarViewController : UIViewController, IUISearchBarDelegate - { - public DefaultSearchBarViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class DefaultSearchBarViewController : UIViewController, IUISearchBarDelegate { + public DefaultSearchBarViewController (IntPtr handle) : base (handle) { } - [Export("searchBar:selectedScopeButtonIndexDidChange:")] - public void SelectedScopeButtonIndexChanged(UISearchBar searchBar, nint selectedScope) - { - Console.WriteLine($"The default search selected scope button index changed to {selectedScope}."); - } + [Export ("searchBar:selectedScopeButtonIndexDidChange:")] + public void SelectedScopeButtonIndexChanged (UISearchBar searchBar, nint selectedScope) + { + Console.WriteLine ($"The default search selected scope button index changed to {selectedScope}."); + } - [Export("searchBarSearchButtonClicked:")] - public void SearchButtonClicked(UISearchBar searchBar) - { - Console.WriteLine("The default search bar keyboard search button was tapped"); - searchBar.ResignFirstResponder(); - } + [Export ("searchBarSearchButtonClicked:")] + public void SearchButtonClicked (UISearchBar searchBar) + { + Console.WriteLine ("The default search bar keyboard search button was tapped"); + searchBar.ResignFirstResponder (); + } - [Export("searchBarCancelButtonClicked:")] - public void CancelButtonClicked(UISearchBar searchBar) - { - Console.WriteLine("The default search bar cancel button was tapped."); - searchBar.ResignFirstResponder(); - } - } -} \ No newline at end of file + [Export ("searchBarCancelButtonClicked:")] + public void CancelButtonClicked (UISearchBar searchBar) + { + Console.WriteLine ("The default search bar cancel button was tapped."); + searchBar.ResignFirstResponder (); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/Search/SearchControllers/BaseSearchController.cs b/UICatalog/UICatalog/Controllers/Search/SearchControllers/BaseSearchController.cs index 3fcabe656..a951e9204 100644 --- a/UICatalog/UICatalog/Controllers/Search/SearchControllers/BaseSearchController.cs +++ b/UICatalog/UICatalog/Controllers/Search/SearchControllers/BaseSearchController.cs @@ -3,72 +3,69 @@ using System.Linq; using UIKit; -namespace UICatalog -{ - public partial class BaseSearchController : UITableViewController, IUISearchResultsUpdating - { - private const string CellIdentifier = "searchResultsCell"; +namespace UICatalog { + public partial class BaseSearchController : UITableViewController, IUISearchResultsUpdating { + private const string CellIdentifier = "searchResultsCell"; - private readonly string[] allItems = - { - "Here's", "to", "the", "crazy", "ones.", "The", "misfits.", "The", "rebels.", - "The", "troublemakers.", "The", "round", "pegs", "in", "the", "square", "holes.", "The", "ones", "who", - "see", "things", "differently.", "They're", "not", "fond", "of", @"rules.", "And", "they", "have", "no", - "respect", "for", "the", "status", "quo.", "You", "can", "quote", "them,", "disagree", "with", "them,", - "glorify", "or", "vilify", "them.", "About", "the", "only", "thing", "you", "can't", "do", "is", "ignore", - "them.", "Because", "they", "change", "things.", "They", "push", "the", "human", "race", "forward.", - "And", "while", "some", "may", "see", "them", "as", "the", "crazy", "ones,", "we", "see", "genius.", - "Because", "the", "people", "who", "are", "crazy", "enough", "to", "think", "they", "can", "change", - "the", "world,", "are", "the", "ones", "who", "do." - }; + private readonly string [] allItems = + { + "Here's", "to", "the", "crazy", "ones.", "The", "misfits.", "The", "rebels.", + "The", "troublemakers.", "The", "round", "pegs", "in", "the", "square", "holes.", "The", "ones", "who", + "see", "things", "differently.", "They're", "not", "fond", "of", @"rules.", "And", "they", "have", "no", + "respect", "for", "the", "status", "quo.", "You", "can", "quote", "them,", "disagree", "with", "them,", + "glorify", "or", "vilify", "them.", "About", "the", "only", "thing", "you", "can't", "do", "is", "ignore", + "them.", "Because", "they", "change", "things.", "They", "push", "the", "human", "race", "forward.", + "And", "while", "some", "may", "see", "them", "as", "the", "crazy", "ones,", "we", "see", "genius.", + "Because", "the", "people", "who", "are", "crazy", "enough", "to", "think", "they", "can", "change", + "the", "world,", "are", "the", "ones", "who", "do." + }; - private string[] items; + private string [] items; - private string query; + private string query; - public BaseSearchController(IntPtr handle) : base(handle) { } + public BaseSearchController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - items = allItems; - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + items = allItems; + } - protected void ApplyFilter(string filter) - { - query = filter; - items = string.IsNullOrEmpty(query) ? allItems : allItems.Where(s => s.Contains(query)).ToArray(); + protected void ApplyFilter (string filter) + { + query = filter; + items = string.IsNullOrEmpty (query) ? allItems : allItems.Where (s => s.Contains (query)).ToArray (); - TableView.ReloadData(); - } + TableView.ReloadData (); + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return items.Length; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return items.Length; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(CellIdentifier, indexPath); - cell.TextLabel.Text = items[indexPath.Row]; + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (CellIdentifier, indexPath); + cell.TextLabel.Text = items [indexPath.Row]; - return cell; - } + return cell; + } - #region IUISearchResultsUpdating + #region IUISearchResultsUpdating - [Export("updateSearchResultsForSearchController:")] - public void UpdateSearchResultsForSearchController(UISearchController searchController) - { - // UpdateSearchResultsForSearchController is called when the controller is being dismissed - // to allow those who are using the controller they are search as the results controller a chance to reset their state. - // No need to update anything if we're being dismissed. - if (searchController.Active) - { - ApplyFilter(searchController.SearchBar.Text); - } - } + [Export ("updateSearchResultsForSearchController:")] + public void UpdateSearchResultsForSearchController (UISearchController searchController) + { + // UpdateSearchResultsForSearchController is called when the controller is being dismissed + // to allow those who are using the controller they are search as the results controller a chance to reset their state. + // No need to update anything if we're being dismissed. + if (searchController.Active) { + ApplyFilter (searchController.SearchBar.Text); + } + } - #endregion - } -} \ No newline at end of file + #endregion + } +} diff --git a/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchBarEmbeddedInNavigationBarViewController.cs b/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchBarEmbeddedInNavigationBarViewController.cs index 1a6fce0aa..8d442f6b0 100644 --- a/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchBarEmbeddedInNavigationBarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchBarEmbeddedInNavigationBarViewController.cs @@ -1,47 +1,44 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class SearchBarEmbeddedInNavigationBarViewController : BaseSearchController - { - private UISearchController searchController; - - public SearchBarEmbeddedInNavigationBarViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Create the search results view controller and use it for the UISearchController. - //var searchResultsController = (SearchResultsViewController)Storyboard.InstantiateViewController(SearchResultsViewController.StoryboardIdentifier); - - // Create the search controller and make it perform the results updating. - //var searchController = new UISearchController(searchResultsController); - searchController = new UISearchController((UIViewController)null); - searchController.SetSearchResultsUpdater(UpdateSearchResultsForSearchController); - searchController.HidesNavigationBarDuringPresentation = false; - - // Configure the search controller's search bar. For more information on how to configure - // search bars, see the "Search Bar" group under "Search". - searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Minimal; - searchController.SearchBar.ShowsCancelButton = false; - searchController.SearchBar.Placeholder = "Search"; - - // Include the search bar within the navigation bar. - NavigationItem.TitleView = searchController.SearchBar; - - DefinesPresentationContext = true; - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (searchController != null) - { - searchController.Dispose(); - searchController = null; - } - } - } -} \ No newline at end of file +namespace UICatalog { + public partial class SearchBarEmbeddedInNavigationBarViewController : BaseSearchController { + private UISearchController searchController; + + public SearchBarEmbeddedInNavigationBarViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Create the search results view controller and use it for the UISearchController. + //var searchResultsController = (SearchResultsViewController)Storyboard.InstantiateViewController(SearchResultsViewController.StoryboardIdentifier); + + // Create the search controller and make it perform the results updating. + //var searchController = new UISearchController(searchResultsController); + searchController = new UISearchController ((UIViewController) null); + searchController.SetSearchResultsUpdater (UpdateSearchResultsForSearchController); + searchController.HidesNavigationBarDuringPresentation = false; + + // Configure the search controller's search bar. For more information on how to configure + // search bars, see the "Search Bar" group under "Search". + searchController.SearchBar.SearchBarStyle = UISearchBarStyle.Minimal; + searchController.SearchBar.ShowsCancelButton = false; + searchController.SearchBar.Placeholder = "Search"; + + // Include the search bar within the navigation bar. + NavigationItem.TitleView = searchController.SearchBar; + + DefinesPresentationContext = true; + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (searchController != null) { + searchController.Dispose (); + searchController = null; + } + } + } +} diff --git a/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchPresentOverNavigationBarViewController.cs b/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchPresentOverNavigationBarViewController.cs index c462658b3..0b99aba3a 100644 --- a/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchPresentOverNavigationBarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchPresentOverNavigationBarViewController.cs @@ -2,21 +2,19 @@ using Foundation; using UIKit; -namespace UICatalog -{ - public partial class SearchPresentOverNavigationBarViewController : BaseSearchController - { - public SearchPresentOverNavigationBarViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class SearchPresentOverNavigationBarViewController : BaseSearchController { + public SearchPresentOverNavigationBarViewController (IntPtr handle) : base (handle) { } - partial void SearchButtonClicked(NSObject sender) - { - // Create the search controller and make it perform the results updating. - var searchController = new UISearchController((UIViewController)null); - searchController.SetSearchResultsUpdater(UpdateSearchResultsForSearchController); - searchController.HidesNavigationBarDuringPresentation = false; + partial void SearchButtonClicked (NSObject sender) + { + // Create the search controller and make it perform the results updating. + var searchController = new UISearchController ((UIViewController) null); + searchController.SetSearchResultsUpdater (UpdateSearchResultsForSearchController); + searchController.HidesNavigationBarDuringPresentation = false; - // Present the view controller. - PresentViewController(searchController, true, null); - } - } -} \ No newline at end of file + // Present the view controller. + PresentViewController (searchController, true, null); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchShowResultsInSourceViewController.cs b/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchShowResultsInSourceViewController.cs index 6d23e9672..942460c87 100644 --- a/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchShowResultsInSourceViewController.cs +++ b/UICatalog/UICatalog/Controllers/Search/SearchControllers/SearchShowResultsInSourceViewController.cs @@ -1,41 +1,38 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class SearchShowResultsInSourceViewController : BaseSearchController - { - private UISearchController searchController; - - public SearchShowResultsInSourceViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Create the search controller, but we'll make sure that this SearchShowResultsInSourceViewController - // performs the results updating. - - searchController = new UISearchController((UIViewController)null); - searchController.SetSearchResultsUpdater(UpdateSearchResultsForSearchController); - searchController.DimsBackgroundDuringPresentation = false; - - // Make sure the that the search bar is visible within the navigation bar. - searchController.SearchBar.SizeToFit(); - - // Include the search controller's search bar within the table's header view. - TableView.TableHeaderView = searchController.SearchBar; - DefinesPresentationContext = true; - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if (searchController != null) - { - searchController.Dispose(); - searchController = null; - } - } - } -} \ No newline at end of file +namespace UICatalog { + public partial class SearchShowResultsInSourceViewController : BaseSearchController { + private UISearchController searchController; + + public SearchShowResultsInSourceViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Create the search controller, but we'll make sure that this SearchShowResultsInSourceViewController + // performs the results updating. + + searchController = new UISearchController ((UIViewController) null); + searchController.SetSearchResultsUpdater (UpdateSearchResultsForSearchController); + searchController.DimsBackgroundDuringPresentation = false; + + // Make sure the that the search bar is visible within the navigation bar. + searchController.SearchBar.SizeToFit (); + + // Include the search controller's search bar within the table's header view. + TableView.TableHeaderView = searchController.SearchBar; + DefinesPresentationContext = true; + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (searchController != null) { + searchController.Dispose (); + searchController = null; + } + } + } +} diff --git a/UICatalog/UICatalog/Controllers/SegmentedControlViewController.cs b/UICatalog/UICatalog/Controllers/SegmentedControlViewController.cs index 269a1bc24..06a1d1d85 100644 --- a/UICatalog/UICatalog/Controllers/SegmentedControlViewController.cs +++ b/UICatalog/UICatalog/Controllers/SegmentedControlViewController.cs @@ -1,33 +1,31 @@ -using System; -using UIKit; - -namespace UICatalog -{ - public partial class SegmentedControlViewController : UITableViewController - { - public SegmentedControlViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ConfigureCustomBackgroundSegmentedControl(); - } - - private void ConfigureCustomBackgroundSegmentedControl() - { - customSegmentControl.SelectedSegment = 2; - customSegmentControl.SetBackgroundImage(UIImage.FromBundle("stepper_and_segment_background"), UIControlState.Normal, UIBarMetrics.Default); - customSegmentControl.SetBackgroundImage(UIImage.FromBundle("stepper_and_segment_background_disabled"), UIControlState.Disabled, UIBarMetrics.Default); - customSegmentControl.SetBackgroundImage(UIImage.FromBundle("stepper_and_segment_background_highlighted"), UIControlState.Highlighted, UIBarMetrics.Default); - customSegmentControl.SetDividerImage(UIImage.FromBundle("stepper_and_segment_divider"), UIControlState.Normal, UIControlState.Normal, UIBarMetrics.Default); - - var font = UIFont.FromDescriptor(UIFontDescriptor.PreferredCaption1, 0f); - - var normalTextAttributes = new UITextAttributes { TextColor = UIColor.Purple, Font = font }; - customSegmentControl.SetTitleTextAttributes(normalTextAttributes, UIControlState.Normal); - - var highlightedTextAttributes = new UITextAttributes { TextColor = UIColor.Green, Font = font }; - customSegmentControl.SetTitleTextAttributes(highlightedTextAttributes, UIControlState.Highlighted); - } - } -} \ No newline at end of file +using System; +using UIKit; + +namespace UICatalog { + public partial class SegmentedControlViewController : UITableViewController { + public SegmentedControlViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ConfigureCustomBackgroundSegmentedControl (); + } + + private void ConfigureCustomBackgroundSegmentedControl () + { + customSegmentControl.SelectedSegment = 2; + customSegmentControl.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background"), UIControlState.Normal, UIBarMetrics.Default); + customSegmentControl.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background_disabled"), UIControlState.Disabled, UIBarMetrics.Default); + customSegmentControl.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background_highlighted"), UIControlState.Highlighted, UIBarMetrics.Default); + customSegmentControl.SetDividerImage (UIImage.FromBundle ("stepper_and_segment_divider"), UIControlState.Normal, UIControlState.Normal, UIBarMetrics.Default); + + var font = UIFont.FromDescriptor (UIFontDescriptor.PreferredCaption1, 0f); + + var normalTextAttributes = new UITextAttributes { TextColor = UIColor.Purple, Font = font }; + customSegmentControl.SetTitleTextAttributes (normalTextAttributes, UIControlState.Normal); + + var highlightedTextAttributes = new UITextAttributes { TextColor = UIColor.Green, Font = font }; + customSegmentControl.SetTitleTextAttributes (highlightedTextAttributes, UIControlState.Highlighted); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/SliderViewController.cs b/UICatalog/UICatalog/Controllers/SliderViewController.cs index 6be762ce6..0c5ec1be6 100644 --- a/UICatalog/UICatalog/Controllers/SliderViewController.cs +++ b/UICatalog/UICatalog/Controllers/SliderViewController.cs @@ -1,39 +1,37 @@ -using Foundation; -using System; -using UIKit; - -namespace UICatalog -{ - public partial class SliderViewController : UITableViewController - { - public SliderViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ConfigureCustomSlider(); - } - - private void ConfigureCustomSlider() - { - customSlider.SetMinTrackImage(UIImage.FromBundle("slider_blue_track"), UIControlState.Normal); - customSlider.SetMaxTrackImage(UIImage.FromBundle("slider_green_track"), UIControlState.Normal); - customSlider.SetThumbImage(UIImage.FromBundle("slider_thumb"), UIControlState.Normal); - } - - partial void CustomSliderValueChanged(NSObject sender) - { - Console.WriteLine($"A 'Custom' slider changed its value: {customSlider.Value}"); - } - - partial void DefaultSliderValueChanged(NSObject sender) - { - Console.WriteLine($"A 'Default' slider changed its value: {defaultSlider.Value}"); - } - - partial void TintedSliderValueChanged(NSObject sender) - { - Console.WriteLine($"A 'Tinted' slider changed its value: {tintedSlider.Value}"); - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace UICatalog { + public partial class SliderViewController : UITableViewController { + public SliderViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ConfigureCustomSlider (); + } + + private void ConfigureCustomSlider () + { + customSlider.SetMinTrackImage (UIImage.FromBundle ("slider_blue_track"), UIControlState.Normal); + customSlider.SetMaxTrackImage (UIImage.FromBundle ("slider_green_track"), UIControlState.Normal); + customSlider.SetThumbImage (UIImage.FromBundle ("slider_thumb"), UIControlState.Normal); + } + + partial void CustomSliderValueChanged (NSObject sender) + { + Console.WriteLine ($"A 'Custom' slider changed its value: {customSlider.Value}"); + } + + partial void DefaultSliderValueChanged (NSObject sender) + { + Console.WriteLine ($"A 'Default' slider changed its value: {defaultSlider.Value}"); + } + + partial void TintedSliderValueChanged (NSObject sender) + { + Console.WriteLine ($"A 'Tinted' slider changed its value: {tintedSlider.Value}"); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/StepperViewController.cs b/UICatalog/UICatalog/Controllers/StepperViewController.cs index 8cdecde05..ea4fb0968 100644 --- a/UICatalog/UICatalog/Controllers/StepperViewController.cs +++ b/UICatalog/UICatalog/Controllers/StepperViewController.cs @@ -1,68 +1,66 @@ -using Foundation; -using System; -using UIKit; - -namespace UICatalog -{ - public partial class StepperViewController : UITableViewController - { - public StepperViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ConfigureCustomStepper(); +using Foundation; +using System; +using UIKit; - UpdateDefaultLabel(); - UpdateTintedLabel(); - UpdateCustomLabel(); - } - - private void ConfigureCustomStepper() - { - // Set the background image. - customStepper.SetBackgroundImage(UIImage.FromBundle("stepper_and_segment_background"), UIControlState.Normal); - customStepper.SetBackgroundImage(UIImage.FromBundle("stepper_and_segment_background_highlighted"), UIControlState.Highlighted); - customStepper.SetBackgroundImage(UIImage.FromBundle("stepper_and_segment_background_disabled"), UIControlState.Disabled); - - // Set the image which will be painted in between the two stepper segments (depends on the states of both segments). - customStepper.SetDividerImage(UIImage.FromBundle("stepper_and_segment_divider"), UIControlState.Normal, UIControlState.Normal); - - // Set the image for the + button. - customStepper.SetIncrementImage(UIImage.FromBundle("stepper_increment"), UIControlState.Normal); - - // Set the image for the - button. - customStepper.SetDecrementImage(UIImage.FromBundle("stepper_decrement"), UIControlState.Normal); - } - - partial void CustomValueChanged(NSObject sender) - { - UpdateCustomLabel(); - } - - partial void DefaultValueChanged(NSObject sender) - { - UpdateDefaultLabel(); - } +namespace UICatalog { + public partial class StepperViewController : UITableViewController { + public StepperViewController (IntPtr handle) : base (handle) { } - partial void TintedValueChanged(NSObject sender) - { - UpdateTintedLabel(); - } - - private void UpdateDefaultLabel() - { - defaultLabel.Text = defaultStepper.Value.ToString(); - } - - private void UpdateTintedLabel() - { - tintedLabel.Text = tintedStepper.Value.ToString(); - } - - private void UpdateCustomLabel() - { - customLabel.Text = customStepper.Value.ToString(); - } - } -} \ No newline at end of file + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ConfigureCustomStepper (); + + UpdateDefaultLabel (); + UpdateTintedLabel (); + UpdateCustomLabel (); + } + + private void ConfigureCustomStepper () + { + // Set the background image. + customStepper.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background"), UIControlState.Normal); + customStepper.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background_highlighted"), UIControlState.Highlighted); + customStepper.SetBackgroundImage (UIImage.FromBundle ("stepper_and_segment_background_disabled"), UIControlState.Disabled); + + // Set the image which will be painted in between the two stepper segments (depends on the states of both segments). + customStepper.SetDividerImage (UIImage.FromBundle ("stepper_and_segment_divider"), UIControlState.Normal, UIControlState.Normal); + + // Set the image for the + button. + customStepper.SetIncrementImage (UIImage.FromBundle ("stepper_increment"), UIControlState.Normal); + + // Set the image for the - button. + customStepper.SetDecrementImage (UIImage.FromBundle ("stepper_decrement"), UIControlState.Normal); + } + + partial void CustomValueChanged (NSObject sender) + { + UpdateCustomLabel (); + } + + partial void DefaultValueChanged (NSObject sender) + { + UpdateDefaultLabel (); + } + + partial void TintedValueChanged (NSObject sender) + { + UpdateTintedLabel (); + } + + private void UpdateDefaultLabel () + { + defaultLabel.Text = defaultStepper.Value.ToString (); + } + + private void UpdateTintedLabel () + { + tintedLabel.Text = tintedStepper.Value.ToString (); + } + + private void UpdateCustomLabel () + { + customLabel.Text = customStepper.Value.ToString (); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/SwitchesViewController.cs b/UICatalog/UICatalog/Controllers/SwitchesViewController.cs index f9daaad98..ace229bcd 100644 --- a/UICatalog/UICatalog/Controllers/SwitchesViewController.cs +++ b/UICatalog/UICatalog/Controllers/SwitchesViewController.cs @@ -2,20 +2,18 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class SwitchesViewController : UITableViewController - { - public SwitchesViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class SwitchesViewController : UITableViewController { + public SwitchesViewController (IntPtr handle) : base (handle) { } - partial void DefaultValueChanged(NSObject sender) - { - Console.WriteLine($"A 'default' switch changed its value: {defaultSwitch.On}."); - } + partial void DefaultValueChanged (NSObject sender) + { + Console.WriteLine ($"A 'default' switch changed its value: {defaultSwitch.On}."); + } - partial void TintedValueChanged(NSObject sender) - { - Console.WriteLine($"A 'tinted' switch changed its value: {tintedSwitch.On}."); - } - } -} \ No newline at end of file + partial void TintedValueChanged (NSObject sender) + { + Console.WriteLine ($"A 'tinted' switch changed its value: {tintedSwitch.On}."); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/TextFieldsViewController.cs b/UICatalog/UICatalog/Controllers/TextFieldsViewController.cs index fc0add4e8..437b37dd2 100644 --- a/UICatalog/UICatalog/Controllers/TextFieldsViewController.cs +++ b/UICatalog/UICatalog/Controllers/TextFieldsViewController.cs @@ -1,54 +1,51 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; using System; using System.Drawing; using UIKit; -namespace UICatalog -{ - public partial class TextFieldsViewController : UITableViewController, IUITextFieldDelegate - { - public TextFieldsViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class TextFieldsViewController : UITableViewController, IUITextFieldDelegate { + public TextFieldsViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.ConfigureCustomTextField(); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.ConfigureCustomTextField (); + } - private void ConfigureCustomTextField() - { - // Text fields with custom image backgrounds must have no border. - customTextField.BorderStyle = UITextBorderStyle.None; - customTextField.Background = UIImage.FromBundle("text_field_background"); + private void ConfigureCustomTextField () + { + // Text fields with custom image backgrounds must have no border. + customTextField.BorderStyle = UITextBorderStyle.None; + customTextField.Background = UIImage.FromBundle ("text_field_background"); - // Create a purple button that, when selected, turns the custom text field's text color to purple. - var purpleImage = UIImage.FromBundle("text_field_purple_right_view"); - var purpleImageButton = new UIButton(UIButtonType.Custom); - purpleImageButton.Bounds = new CGRect(PointF.Empty, purpleImage.Size); - purpleImageButton.ImageEdgeInsets = new UIEdgeInsets(0, 0, 0, 5); - purpleImageButton.SetImage(purpleImage, UIControlState.Normal); - purpleImageButton.TouchUpInside += (sender, e) => - { - customTextField.TextColor = UIColor.Purple; - Console.WriteLine("The custom text field's purple right view button was clicked."); - }; + // Create a purple button that, when selected, turns the custom text field's text color to purple. + var purpleImage = UIImage.FromBundle ("text_field_purple_right_view"); + var purpleImageButton = new UIButton (UIButtonType.Custom); + purpleImageButton.Bounds = new CGRect (PointF.Empty, purpleImage.Size); + purpleImageButton.ImageEdgeInsets = new UIEdgeInsets (0, 0, 0, 5); + purpleImageButton.SetImage (purpleImage, UIControlState.Normal); + purpleImageButton.TouchUpInside += (sender, e) => { + customTextField.TextColor = UIColor.Purple; + Console.WriteLine ("The custom text field's purple right view button was clicked."); + }; - customTextField.RightView = purpleImageButton; - customTextField.RightViewMode = UITextFieldViewMode.Always; + customTextField.RightView = purpleImageButton; + customTextField.RightViewMode = UITextFieldViewMode.Always; - // Add an empty view as the left view to ensure inset between the text and the bounding rectangle. - var leftPaddingView = new UIView(new RectangleF(0, 0, 10, 0)); - leftPaddingView.BackgroundColor = UIColor.Clear; - customTextField.LeftView = leftPaddingView; - customTextField.LeftViewMode = UITextFieldViewMode.Always; - } - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - textField.ResignFirstResponder(); - return true; - } - } -} \ No newline at end of file + // Add an empty view as the left view to ensure inset between the text and the bounding rectangle. + var leftPaddingView = new UIView (new RectangleF (0, 0, 10, 0)); + leftPaddingView.BackgroundColor = UIColor.Clear; + customTextField.LeftView = leftPaddingView; + customTextField.LeftViewMode = UITextFieldViewMode.Always; + } + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + textField.ResignFirstResponder (); + return true; + } + } +} diff --git a/UICatalog/UICatalog/Controllers/TextViewController.cs b/UICatalog/UICatalog/Controllers/TextViewController.cs index eb7fb1b22..b50f001a5 100644 --- a/UICatalog/UICatalog/Controllers/TextViewController.cs +++ b/UICatalog/UICatalog/Controllers/TextViewController.cs @@ -1,171 +1,164 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; -using System; -using System.Drawing; -using UIKit; - -namespace UICatalog -{ - public partial class TextViewController : UIViewController, IUITextViewDelegate - { - public TextViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ConfigureTextView(); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - // Listen for changes to keyboard visibility so that we can adjust the text view accordingly. - willShowObserver = UIKeyboard.Notifications.ObserveWillShow(OnKeyboardWillChangeFrame); - willHideObserver = UIKeyboard.Notifications.ObserveWillHide(OnKeyboardWillChangeFrame); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - - if (willShowObserver != null) - { - NSNotificationCenter.DefaultCenter.RemoveObserver(willShowObserver); - willShowObserver.Dispose(); - willShowObserver = null; - } - - if (willHideObserver != null) - { - NSNotificationCenter.DefaultCenter.RemoveObserver(willHideObserver); - willHideObserver.Dispose(); - willHideObserver = null; - } - } - - #region Keyboard - - private NSObject willShowObserver; - private NSObject willHideObserver; - - private void OnKeyboardWillChangeFrame(object sender, UIKeyboardEventArgs args) - { - // Convert the keyboard frame from screen to view coordinates. - var keyboardViewBeginFrame = View.ConvertRectFromView(args.FrameBegin, View.Window); - var keyboardViewEndFrame = View.ConvertRectFromView(args.FrameEnd, View.Window); - var originDelta = keyboardViewEndFrame.Y - keyboardViewBeginFrame.Y; - - // The text view should be adjusted, update the constant for this constraint. - textBottomConstraint.Constant -= originDelta; - View.SetNeedsUpdateConstraints(); - - UIView.Animate(args.AnimationDuration, 0, UIViewAnimationOptions.BeginFromCurrentState, View.LayoutIfNeeded, null); - - // Scroll to the selected text once the keyboard frame changes. - var selectedRange = textView.SelectedRange; - textView.ScrollRangeToVisible(selectedRange); - } - - #endregion - - private void ConfigureTextView() - { - textView.Font = UIFont.FromDescriptor(UIFontDescriptor.PreferredBody, 0); - - textView.TextColor = UIColor.Black; - textView.BackgroundColor = UIColor.White; - textView.ScrollEnabled = true; - - // Let's modify some of the attributes of the attributed string. - // You can modify these attributes yourself to get a better feel for what they do. - // Note that the initial text is visible in the storyboard. - var attributedText = new NSMutableAttributedString(textView.AttributedText); - - // Find the range of each element to modify. - var text = textView.Text; - var boldRange = GetRangeFor(text, "bold"); - var highlightedRange = GetRangeFor(text, "highlighted"); - var underlinedRange = GetRangeFor(text, "underlined"); - var tintedRange = GetRangeFor(text, "tinted"); - - // Add bold. Take the current font descriptor and create a new font descriptor with an additional bold trait. - var boldFontDescriptor = textView.Font.FontDescriptor.CreateWithTraits(UIFontDescriptorSymbolicTraits.Bold); - var boldFont = UIFont.FromDescriptor(boldFontDescriptor, 0); - attributedText.AddAttribute(UIStringAttributeKey.Font, boldFont, boldRange); - - // Add highlight. - attributedText.AddAttribute(UIStringAttributeKey.BackgroundColor, UIColor.Green, highlightedRange); - - // Add underline. - attributedText.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), underlinedRange); - - // Add tint. - attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Blue, tintedRange); - - // Add image attachment. - var image = UIImage.FromBundle("text_view_attachment"); - var textAttachment = new NSTextAttachment - { - Image = image, - Bounds = new CGRect(PointF.Empty, image.Size), - }; - - var textAttachmentString = NSAttributedString.CreateFrom(textAttachment); - attributedText.Append(new NSAttributedString(Environment.NewLine)); - attributedText.Append(textAttachmentString); - - textView.AttributedText = attributedText; - - image.Dispose(); - attributedText.Dispose(); - image = null; - attributedText = null; - - NSRange GetRangeFor(string source, string substring) - { - return new NSRange - { - Location = source.IndexOf(substring, StringComparison.OrdinalIgnoreCase), - Length = substring.Length - }; - } - } - - #region IUITextViewDelegate - - [Export("textViewDidBeginEditing:")] - public void EditingStarted(UITextView textView) - { - // Provide a "Done" button for the user to select to signify completion with writing text in the text view. - var doneBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Done, (sender, e)=> - { - // Dismiss the keyboard by removing it as the first responder. - textView.ResignFirstResponder(); - NavigationItem.SetRightBarButtonItem(null, true); - }); - - NavigationItem.SetRightBarButtonItem(doneBarButtonItem, true); - AdjustTextViewSelection(textView); - } - - [Export("textViewDidEndEditing:")] - public void EditingEnded(UITextView textView) - { - AdjustTextViewSelection(textView); - } - - private static void AdjustTextViewSelection(UITextView textView) - { - // Ensure that the text view is visible by making the text view frame smaller as text can be slightly cropped at the bottom. - // Note that this is a workwaround to a bug in iOS. - textView.LayoutIfNeeded(); - - var caretRect = textView.GetCaretRectForPosition(textView.SelectedTextRange.End); - caretRect.Height += textView.TextContainerInset.Bottom; - textView.ScrollRectToVisible(caretRect, false); - } - - #endregion - } -} \ No newline at end of file +using System; +using System.Drawing; +using UIKit; + +namespace UICatalog { + public partial class TextViewController : UIViewController, IUITextViewDelegate { + public TextViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ConfigureTextView (); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + // Listen for changes to keyboard visibility so that we can adjust the text view accordingly. + willShowObserver = UIKeyboard.Notifications.ObserveWillShow (OnKeyboardWillChangeFrame); + willHideObserver = UIKeyboard.Notifications.ObserveWillHide (OnKeyboardWillChangeFrame); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + + if (willShowObserver != null) { + NSNotificationCenter.DefaultCenter.RemoveObserver (willShowObserver); + willShowObserver.Dispose (); + willShowObserver = null; + } + + if (willHideObserver != null) { + NSNotificationCenter.DefaultCenter.RemoveObserver (willHideObserver); + willHideObserver.Dispose (); + willHideObserver = null; + } + } + + #region Keyboard + + private NSObject willShowObserver; + private NSObject willHideObserver; + + private void OnKeyboardWillChangeFrame (object sender, UIKeyboardEventArgs args) + { + // Convert the keyboard frame from screen to view coordinates. + var keyboardViewBeginFrame = View.ConvertRectFromView (args.FrameBegin, View.Window); + var keyboardViewEndFrame = View.ConvertRectFromView (args.FrameEnd, View.Window); + var originDelta = keyboardViewEndFrame.Y - keyboardViewBeginFrame.Y; + + // The text view should be adjusted, update the constant for this constraint. + textBottomConstraint.Constant -= originDelta; + View.SetNeedsUpdateConstraints (); + + UIView.Animate (args.AnimationDuration, 0, UIViewAnimationOptions.BeginFromCurrentState, View.LayoutIfNeeded, null); + + // Scroll to the selected text once the keyboard frame changes. + var selectedRange = textView.SelectedRange; + textView.ScrollRangeToVisible (selectedRange); + } + + #endregion + + private void ConfigureTextView () + { + textView.Font = UIFont.FromDescriptor (UIFontDescriptor.PreferredBody, 0); + + textView.TextColor = UIColor.Black; + textView.BackgroundColor = UIColor.White; + textView.ScrollEnabled = true; + + // Let's modify some of the attributes of the attributed string. + // You can modify these attributes yourself to get a better feel for what they do. + // Note that the initial text is visible in the storyboard. + var attributedText = new NSMutableAttributedString (textView.AttributedText); + + // Find the range of each element to modify. + var text = textView.Text; + var boldRange = GetRangeFor (text, "bold"); + var highlightedRange = GetRangeFor (text, "highlighted"); + var underlinedRange = GetRangeFor (text, "underlined"); + var tintedRange = GetRangeFor (text, "tinted"); + + // Add bold. Take the current font descriptor and create a new font descriptor with an additional bold trait. + var boldFontDescriptor = textView.Font.FontDescriptor.CreateWithTraits (UIFontDescriptorSymbolicTraits.Bold); + var boldFont = UIFont.FromDescriptor (boldFontDescriptor, 0); + attributedText.AddAttribute (UIStringAttributeKey.Font, boldFont, boldRange); + + // Add highlight. + attributedText.AddAttribute (UIStringAttributeKey.BackgroundColor, UIColor.Green, highlightedRange); + + // Add underline. + attributedText.AddAttribute (UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32 ((int) NSUnderlineStyle.Single), underlinedRange); + + // Add tint. + attributedText.AddAttribute (UIStringAttributeKey.ForegroundColor, UIColor.Blue, tintedRange); + + // Add image attachment. + var image = UIImage.FromBundle ("text_view_attachment"); + var textAttachment = new NSTextAttachment { + Image = image, + Bounds = new CGRect (PointF.Empty, image.Size), + }; + + var textAttachmentString = NSAttributedString.CreateFrom (textAttachment); + attributedText.Append (new NSAttributedString (Environment.NewLine)); + attributedText.Append (textAttachmentString); + + textView.AttributedText = attributedText; + + image.Dispose (); + attributedText.Dispose (); + image = null; + attributedText = null; + + NSRange GetRangeFor (string source, string substring) + { + return new NSRange { + Location = source.IndexOf (substring, StringComparison.OrdinalIgnoreCase), + Length = substring.Length + }; + } + } + + #region IUITextViewDelegate + + [Export ("textViewDidBeginEditing:")] + public void EditingStarted (UITextView textView) + { + // Provide a "Done" button for the user to select to signify completion with writing text in the text view. + var doneBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, (sender, e) => { + // Dismiss the keyboard by removing it as the first responder. + textView.ResignFirstResponder (); + NavigationItem.SetRightBarButtonItem (null, true); + }); + + NavigationItem.SetRightBarButtonItem (doneBarButtonItem, true); + AdjustTextViewSelection (textView); + } + + [Export ("textViewDidEndEditing:")] + public void EditingEnded (UITextView textView) + { + AdjustTextViewSelection (textView); + } + + private static void AdjustTextViewSelection (UITextView textView) + { + // Ensure that the text view is visible by making the text view frame smaller as text can be slightly cropped at the bottom. + // Note that this is a workwaround to a bug in iOS. + textView.LayoutIfNeeded (); + + var caretRect = textView.GetCaretRectForPosition (textView.SelectedTextRange.End); + caretRect.Height += textView.TextContainerInset.Bottom; + textView.ScrollRectToVisible (caretRect, false); + } + + #endregion + } +} diff --git a/UICatalog/UICatalog/Controllers/Toolbars/CustomToolbarViewController.cs b/UICatalog/UICatalog/Controllers/Toolbars/CustomToolbarViewController.cs index e00591e3f..431337cb8 100644 --- a/UICatalog/UICatalog/Controllers/Toolbars/CustomToolbarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Toolbars/CustomToolbarViewController.cs @@ -1,43 +1,41 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class CustomToolbarViewController : UIViewController - { - public CustomToolbarViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - ConfigureToolbar(); - } - - private void ConfigureToolbar() - { - toolbar.SetBackgroundImage(UIImage.FromBundle("toolbar_background"), UIToolbarPosition.Bottom, UIBarMetrics.Default); - - // add buttons - - var leftButton = new UIBarButtonItem(UIImage.FromBundle("tools_icon"), UIBarButtonItemStyle.Plain, OnBarButtonItemClicked); - leftButton.TintColor = UIColor.Purple; - - var rightButton = new UIBarButtonItem("Button", UIBarButtonItemStyle.Plain, OnBarButtonItemClicked); - rightButton.SetTitleTextAttributes(new UITextAttributes { TextColor = UIColor.Purple }, UIControlState.Normal); - - var toolbarButtonItems = new[] - { - leftButton, - new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, (EventHandler) null), - rightButton - }; - toolbar.SetItems(toolbarButtonItems, true); - } - - private void OnBarButtonItemClicked(object sender, EventArgs e) - { - Console.WriteLine("A bar button item was clicked"); - } - } -} \ No newline at end of file +namespace UICatalog { + public partial class CustomToolbarViewController : UIViewController { + public CustomToolbarViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + ConfigureToolbar (); + } + + private void ConfigureToolbar () + { + toolbar.SetBackgroundImage (UIImage.FromBundle ("toolbar_background"), UIToolbarPosition.Bottom, UIBarMetrics.Default); + + // add buttons + + var leftButton = new UIBarButtonItem (UIImage.FromBundle ("tools_icon"), UIBarButtonItemStyle.Plain, OnBarButtonItemClicked); + leftButton.TintColor = UIColor.Purple; + + var rightButton = new UIBarButtonItem ("Button", UIBarButtonItemStyle.Plain, OnBarButtonItemClicked); + rightButton.SetTitleTextAttributes (new UITextAttributes { TextColor = UIColor.Purple }, UIControlState.Normal); + + var toolbarButtonItems = new [] + { + leftButton, + new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, (EventHandler) null), + rightButton + }; + toolbar.SetItems (toolbarButtonItems, true); + } + + private void OnBarButtonItemClicked (object sender, EventArgs e) + { + Console.WriteLine ("A bar button item was clicked"); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/Toolbars/DefaultToolbarViewController.cs b/UICatalog/UICatalog/Controllers/Toolbars/DefaultToolbarViewController.cs index 624281149..f2ffc24a2 100644 --- a/UICatalog/UICatalog/Controllers/Toolbars/DefaultToolbarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Toolbars/DefaultToolbarViewController.cs @@ -2,20 +2,18 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class DefaultToolbarViewController : UIViewController - { - public DefaultToolbarViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class DefaultToolbarViewController : UIViewController { + public DefaultToolbarViewController (IntPtr handle) : base (handle) { } - partial void ActionTapped(NSObject sender) - { - Console.WriteLine("'Action' bar button item was clicked"); - } + partial void ActionTapped (NSObject sender) + { + Console.WriteLine ("'Action' bar button item was clicked"); + } - partial void TrashTapped(NSObject sender) - { - Console.WriteLine("'Trash' bar button item was clicked"); - } - } -} \ No newline at end of file + partial void TrashTapped (NSObject sender) + { + Console.WriteLine ("'Trash' bar button item was clicked"); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/Toolbars/TintedToolbarViewController.cs b/UICatalog/UICatalog/Controllers/Toolbars/TintedToolbarViewController.cs index abf8c2417..1fd031dfc 100644 --- a/UICatalog/UICatalog/Controllers/Toolbars/TintedToolbarViewController.cs +++ b/UICatalog/UICatalog/Controllers/Toolbars/TintedToolbarViewController.cs @@ -2,20 +2,18 @@ using System; using UIKit; -namespace UICatalog -{ - public partial class TintedToolbarViewController : UIViewController - { - public TintedToolbarViewController(IntPtr handle) : base(handle) { } +namespace UICatalog { + public partial class TintedToolbarViewController : UIViewController { + public TintedToolbarViewController (IntPtr handle) : base (handle) { } - partial void ActionTapped(NSObject sender) - { - Console.WriteLine("'Action' bar button item was clicked"); - } + partial void ActionTapped (NSObject sender) + { + Console.WriteLine ("'Action' bar button item was clicked"); + } - partial void RefreshTapped(NSObject sender) - { - Console.WriteLine("'Refresh' bar button item was clicked"); - } - } -} \ No newline at end of file + partial void RefreshTapped (NSObject sender) + { + Console.WriteLine ("'Refresh' bar button item was clicked"); + } + } +} diff --git a/UICatalog/UICatalog/Controllers/WebViewController.cs b/UICatalog/UICatalog/Controllers/WebViewController.cs index 9c3330b2f..28b0f8b44 100644 --- a/UICatalog/UICatalog/Controllers/WebViewController.cs +++ b/UICatalog/UICatalog/Controllers/WebViewController.cs @@ -3,72 +3,70 @@ using UIKit; using WebKit; -namespace UICatalog -{ - public partial class WebViewController : UIViewController, IUITextFieldDelegate, IWKNavigationDelegate - { - public WebViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - webView.NavigationDelegate = this; - LoadAddressUrl(); - } - - public override void ViewWillDisappear(bool animated) - { - base.ViewWillDisappear(animated); - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - } - - private void LoadAddressUrl() - { - var requestURL = NSUrl.FromString(addressTextField.Text); - var request = new NSUrlRequest(requestURL); - var navigation = webView.LoadRequest(request); - } - - #region IUIWebViewDelegate - - [Export("webView:didCommitNavigation:")] - public void DidCommitNavigation(WKWebView webView, WKNavigation navigation) - { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - } - - [Export("webView:didFinishNavigation:")] - public void DidFinishNavigation(WKWebView webView, WKNavigation navigation) - { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - } - - [Export("webView:didFailNavigation:withError:")] - public void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error) - { - UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - - // Report the error inside the web view. - var localizedErrorMessage = "An error occured:"; - var errorHTML = string.Format("<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">{0} {1}</div></body></html>", localizedErrorMessage, error.Description); - - webView.LoadHtmlString(errorHTML, null); - } - - #endregion - - #region IUITextFieldDelegate - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - textField.ResignFirstResponder(); - LoadAddressUrl(); - - return true; - } - - #endregion - } -} \ No newline at end of file +namespace UICatalog { + public partial class WebViewController : UIViewController, IUITextFieldDelegate, IWKNavigationDelegate { + public WebViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + webView.NavigationDelegate = this; + LoadAddressUrl (); + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + } + + private void LoadAddressUrl () + { + var requestURL = NSUrl.FromString (addressTextField.Text); + var request = new NSUrlRequest (requestURL); + var navigation = webView.LoadRequest (request); + } + + #region IUIWebViewDelegate + + [Export ("webView:didCommitNavigation:")] + public void DidCommitNavigation (WKWebView webView, WKNavigation navigation) + { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; + } + + [Export ("webView:didFinishNavigation:")] + public void DidFinishNavigation (WKWebView webView, WKNavigation navigation) + { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + } + + [Export ("webView:didFailNavigation:withError:")] + public void DidFailNavigation (WKWebView webView, WKNavigation navigation, NSError error) + { + UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; + + // Report the error inside the web view. + var localizedErrorMessage = "An error occured:"; + var errorHTML = string.Format ("<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">{0} {1}</div></body></html>", localizedErrorMessage, error.Description); + + webView.LoadHtmlString (errorHTML, null); + } + + #endregion + + #region IUITextFieldDelegate + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + textField.ResignFirstResponder (); + LoadAddressUrl (); + + return true; + } + + #endregion + } +} diff --git a/UICatalog/UICatalog/Main.cs b/UICatalog/UICatalog/Main.cs index 596701db8..7c271bc8f 100644 --- a/UICatalog/UICatalog/Main.cs +++ b/UICatalog/UICatalog/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace UICatalog -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace UICatalog { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/UIImageEffects/UIImageEffects/AppDelegate.cs b/UIImageEffects/UIImageEffects/AppDelegate.cs index 0f1b62ee6..afc1860d7 100644 --- a/UIImageEffects/UIImageEffects/AppDelegate.cs +++ b/UIImageEffects/UIImageEffects/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace UIImageEffects -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace UIImageEffects { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/UIImageEffects/UIImageEffects/Main.cs b/UIImageEffects/UIImageEffects/Main.cs index f14ce5d0d..491848937 100644 --- a/UIImageEffects/UIImageEffects/Main.cs +++ b/UIImageEffects/UIImageEffects/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace UIImageEffects -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace UIImageEffects { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/UIImageEffects/UIImageEffects/UIImageEffects.cs b/UIImageEffects/UIImageEffects/UIImageEffects.cs index d881c7f50..06dfbed5b 100644 --- a/UIImageEffects/UIImageEffects/UIImageEffects.cs +++ b/UIImageEffects/UIImageEffects/UIImageEffects.cs @@ -4,190 +4,166 @@ using System.Diagnostics; using UIKit; -namespace UIImageEffects -{ - public static class UIImageEffects - { - public static UIImage ApplyLightEffect(this UIImage self) - { - var tintColor = UIColor.FromWhiteAlpha(1.0f, 0.3f); - return ApplyBlur(self, blurRadius: 30, tintColor: tintColor, saturationDeltaFactor: 1.8f, maskImage: null); - } - - public static UIImage ApplyExtraLightEffect(this UIImage self) - { - var tintColor = UIColor.FromWhiteAlpha(0.97f, 0.82f); - return ApplyBlur(self, blurRadius: 20, tintColor: tintColor, saturationDeltaFactor: 1.8f, maskImage: null); - } - - public static UIImage ApplyDarkEffect(this UIImage self) - { - var tintColor = UIColor.FromWhiteAlpha(0.11f, 0.73f); - return ApplyBlur(self, blurRadius: 20, tintColor: tintColor, saturationDeltaFactor: 1.8f, maskImage: null); - } - - public static UIImage ApplyTintEffect(this UIImage self, UIColor tintColor) - { - const float EffectColorAlpha = 0.6f; - var effectColor = tintColor; - nfloat alpha; - - var componentCount = tintColor.CGColor.NumberOfComponents; - if (componentCount == 2) - { - if (tintColor.GetWhite(out nfloat white, out alpha)) - effectColor = UIColor.FromWhiteAlpha(white, EffectColorAlpha); - } - else - { - try - { - tintColor.GetRGBA(out nfloat r, out nfloat g, out nfloat b, out alpha); - effectColor = UIColor.FromRGBA(r, g, b, EffectColorAlpha); - } - catch { /* ignore */ } - } - - return ApplyBlur(self, blurRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1, maskImage: null); - } - - public static unsafe UIImage ApplyBlur(UIImage image, float blurRadius, UIColor tintColor, float saturationDeltaFactor, UIImage maskImage) - { - if (image.Size.Width < 1 || image.Size.Height < 1) - { - Debug.WriteLine(@"*** error: invalid size: ({0} x {1}). Both dimensions must be >= 1: {2}", image.Size.Width, image.Size.Height, image); - return null; - } - if (image.CGImage == null) - { - Debug.WriteLine(@"*** error: image must be backed by a CGImage: {0}", image); - return null; - } - if (maskImage != null && maskImage.CGImage == null) - { - Debug.WriteLine(@"*** error: maskImage must be backed by a CGImage: {0}", maskImage); - return null; - } - - var imageRect = new CGRect(CGPoint.Empty, image.Size); - var effectImage = image; - - bool hasBlur = blurRadius > float.Epsilon; - bool hasSaturationChange = Math.Abs(saturationDeltaFactor - 1) > float.Epsilon; - - if (hasBlur || hasSaturationChange) - { - UIGraphics.BeginImageContextWithOptions(image.Size, false, UIScreen.MainScreen.Scale); - var contextIn = UIGraphics.GetCurrentContext(); - contextIn.ScaleCTM(1.0f, -1.0f); - contextIn.TranslateCTM(0, -image.Size.Height); - contextIn.DrawImage(imageRect, image.CGImage); - var effectInContext = contextIn.AsBitmapContext() as CGBitmapContext; - - var effectInBuffer = new vImageBuffer() - { - Data = effectInContext.Data, - Width = (int)effectInContext.Width, - Height = (int)effectInContext.Height, - BytesPerRow = (int)effectInContext.BytesPerRow - }; - - UIGraphics.BeginImageContextWithOptions(image.Size, false, UIScreen.MainScreen.Scale); - var effectOutContext = UIGraphics.GetCurrentContext().AsBitmapContext() as CGBitmapContext; - var effectOutBuffer = new vImageBuffer() - { - Data = effectOutContext.Data, - Width = (int)effectOutContext.Width, - Height = (int)effectOutContext.Height, - BytesPerRow = (int)effectOutContext.BytesPerRow - }; - - if (hasBlur) - { - var inputRadius = blurRadius * UIScreen.MainScreen.Scale; - uint radius = (uint)(Math.Floor(inputRadius * 3 * Math.Sqrt(2 * Math.PI) / 4 + 0.5)); - if ((radius % 2) != 1) - radius += 1; - vImage.BoxConvolveARGB8888(ref effectInBuffer, ref effectOutBuffer, IntPtr.Zero, 0, 0, radius, radius, Pixel8888.Zero, vImageFlags.EdgeExtend); - vImage.BoxConvolveARGB8888(ref effectOutBuffer, ref effectInBuffer, IntPtr.Zero, 0, 0, radius, radius, Pixel8888.Zero, vImageFlags.EdgeExtend); - vImage.BoxConvolveARGB8888(ref effectInBuffer, ref effectOutBuffer, IntPtr.Zero, 0, 0, radius, radius, Pixel8888.Zero, vImageFlags.EdgeExtend); - } - bool effectImageBuffersAreSwapped = false; - if (hasSaturationChange) - { - var s = saturationDeltaFactor; - var floatingPointSaturationMatrix = new float[] - { - 0.0722f + 0.9278f * s, 0.0722f - 0.0722f * s, 0.0722f - 0.0722f * s, 0, - 0.7152f - 0.7152f * s, 0.7152f + 0.2848f * s, 0.7152f - 0.7152f * s, 0, - 0.2126f - 0.2126f * s, 0.2126f - 0.2126f * s, 0.2126f + 0.7873f * s, 0, - 0, 0, 0, 1, - }; - - const int divisor = 256; - var saturationMatrix = new short[floatingPointSaturationMatrix.Length]; - for (int i = 0; i < saturationMatrix.Length; i++) - { - saturationMatrix[i] = (short)Math.Round(floatingPointSaturationMatrix[i] * divisor); - } - - if (hasBlur) - { - vImage.MatrixMultiplyARGB8888(ref effectOutBuffer, ref effectInBuffer, saturationMatrix, divisor, null, null, vImageFlags.NoFlags); - effectImageBuffersAreSwapped = true; - } - else - { - vImage.MatrixMultiplyARGB8888(ref effectInBuffer, ref effectOutBuffer, saturationMatrix, divisor, null, null, vImageFlags.NoFlags); - } - } - - if (!effectImageBuffersAreSwapped) - { - effectImage = UIGraphics.GetImageFromCurrentImageContext(); - } - - UIGraphics.EndImageContext(); - if (effectImageBuffersAreSwapped) - { - effectImage = UIGraphics.GetImageFromCurrentImageContext(); - } - - UIGraphics.EndImageContext(); - } - - // Setup up output context - UIGraphics.BeginImageContextWithOptions(image.Size, false, UIScreen.MainScreen.Scale); - - var outputContext = UIGraphics.GetCurrentContext(); - outputContext.ScaleCTM(1, -1); - outputContext.TranslateCTM(0, -image.Size.Height); - - // Draw base image - if (hasBlur) - { - outputContext.SaveState(); - if (maskImage != null) - { - outputContext.ClipToMask(imageRect, maskImage.CGImage); - } - - outputContext.DrawImage(imageRect, effectImage.CGImage); - outputContext.RestoreState(); - } - - if (tintColor != null) - { - outputContext.SaveState(); - outputContext.SetFillColor(tintColor.CGColor); - outputContext.FillRect(imageRect); - outputContext.RestoreState(); - } - - var outputImage = UIGraphics.GetImageFromCurrentImageContext(); - UIGraphics.EndImageContext(); - - return outputImage; - } - } -} \ No newline at end of file +namespace UIImageEffects { + public static class UIImageEffects { + public static UIImage ApplyLightEffect (this UIImage self) + { + var tintColor = UIColor.FromWhiteAlpha (1.0f, 0.3f); + return ApplyBlur (self, blurRadius: 30, tintColor: tintColor, saturationDeltaFactor: 1.8f, maskImage: null); + } + + public static UIImage ApplyExtraLightEffect (this UIImage self) + { + var tintColor = UIColor.FromWhiteAlpha (0.97f, 0.82f); + return ApplyBlur (self, blurRadius: 20, tintColor: tintColor, saturationDeltaFactor: 1.8f, maskImage: null); + } + + public static UIImage ApplyDarkEffect (this UIImage self) + { + var tintColor = UIColor.FromWhiteAlpha (0.11f, 0.73f); + return ApplyBlur (self, blurRadius: 20, tintColor: tintColor, saturationDeltaFactor: 1.8f, maskImage: null); + } + + public static UIImage ApplyTintEffect (this UIImage self, UIColor tintColor) + { + const float EffectColorAlpha = 0.6f; + var effectColor = tintColor; + nfloat alpha; + + var componentCount = tintColor.CGColor.NumberOfComponents; + if (componentCount == 2) { + if (tintColor.GetWhite (out nfloat white, out alpha)) + effectColor = UIColor.FromWhiteAlpha (white, EffectColorAlpha); + } else { + try { + tintColor.GetRGBA (out nfloat r, out nfloat g, out nfloat b, out alpha); + effectColor = UIColor.FromRGBA (r, g, b, EffectColorAlpha); + } catch { /* ignore */ } + } + + return ApplyBlur (self, blurRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1, maskImage: null); + } + + public static unsafe UIImage ApplyBlur (UIImage image, float blurRadius, UIColor tintColor, float saturationDeltaFactor, UIImage maskImage) + { + if (image.Size.Width < 1 || image.Size.Height < 1) { + Debug.WriteLine (@"*** error: invalid size: ({0} x {1}). Both dimensions must be >= 1: {2}", image.Size.Width, image.Size.Height, image); + return null; + } + if (image.CGImage == null) { + Debug.WriteLine (@"*** error: image must be backed by a CGImage: {0}", image); + return null; + } + if (maskImage != null && maskImage.CGImage == null) { + Debug.WriteLine (@"*** error: maskImage must be backed by a CGImage: {0}", maskImage); + return null; + } + + var imageRect = new CGRect (CGPoint.Empty, image.Size); + var effectImage = image; + + bool hasBlur = blurRadius > float.Epsilon; + bool hasSaturationChange = Math.Abs (saturationDeltaFactor - 1) > float.Epsilon; + + if (hasBlur || hasSaturationChange) { + UIGraphics.BeginImageContextWithOptions (image.Size, false, UIScreen.MainScreen.Scale); + var contextIn = UIGraphics.GetCurrentContext (); + contextIn.ScaleCTM (1.0f, -1.0f); + contextIn.TranslateCTM (0, -image.Size.Height); + contextIn.DrawImage (imageRect, image.CGImage); + var effectInContext = contextIn.AsBitmapContext () as CGBitmapContext; + + var effectInBuffer = new vImageBuffer () { + Data = effectInContext.Data, + Width = (int) effectInContext.Width, + Height = (int) effectInContext.Height, + BytesPerRow = (int) effectInContext.BytesPerRow + }; + + UIGraphics.BeginImageContextWithOptions (image.Size, false, UIScreen.MainScreen.Scale); + var effectOutContext = UIGraphics.GetCurrentContext ().AsBitmapContext () as CGBitmapContext; + var effectOutBuffer = new vImageBuffer () { + Data = effectOutContext.Data, + Width = (int) effectOutContext.Width, + Height = (int) effectOutContext.Height, + BytesPerRow = (int) effectOutContext.BytesPerRow + }; + + if (hasBlur) { + var inputRadius = blurRadius * UIScreen.MainScreen.Scale; + uint radius = (uint) (Math.Floor (inputRadius * 3 * Math.Sqrt (2 * Math.PI) / 4 + 0.5)); + if ((radius % 2) != 1) + radius += 1; + vImage.BoxConvolveARGB8888 (ref effectInBuffer, ref effectOutBuffer, IntPtr.Zero, 0, 0, radius, radius, Pixel8888.Zero, vImageFlags.EdgeExtend); + vImage.BoxConvolveARGB8888 (ref effectOutBuffer, ref effectInBuffer, IntPtr.Zero, 0, 0, radius, radius, Pixel8888.Zero, vImageFlags.EdgeExtend); + vImage.BoxConvolveARGB8888 (ref effectInBuffer, ref effectOutBuffer, IntPtr.Zero, 0, 0, radius, radius, Pixel8888.Zero, vImageFlags.EdgeExtend); + } + bool effectImageBuffersAreSwapped = false; + if (hasSaturationChange) { + var s = saturationDeltaFactor; + var floatingPointSaturationMatrix = new float [] + { + 0.0722f + 0.9278f * s, 0.0722f - 0.0722f * s, 0.0722f - 0.0722f * s, 0, + 0.7152f - 0.7152f * s, 0.7152f + 0.2848f * s, 0.7152f - 0.7152f * s, 0, + 0.2126f - 0.2126f * s, 0.2126f - 0.2126f * s, 0.2126f + 0.7873f * s, 0, + 0, 0, 0, 1, + }; + + const int divisor = 256; + var saturationMatrix = new short [floatingPointSaturationMatrix.Length]; + for (int i = 0; i < saturationMatrix.Length; i++) { + saturationMatrix [i] = (short) Math.Round (floatingPointSaturationMatrix [i] * divisor); + } + + if (hasBlur) { + vImage.MatrixMultiplyARGB8888 (ref effectOutBuffer, ref effectInBuffer, saturationMatrix, divisor, null, null, vImageFlags.NoFlags); + effectImageBuffersAreSwapped = true; + } else { + vImage.MatrixMultiplyARGB8888 (ref effectInBuffer, ref effectOutBuffer, saturationMatrix, divisor, null, null, vImageFlags.NoFlags); + } + } + + if (!effectImageBuffersAreSwapped) { + effectImage = UIGraphics.GetImageFromCurrentImageContext (); + } + + UIGraphics.EndImageContext (); + if (effectImageBuffersAreSwapped) { + effectImage = UIGraphics.GetImageFromCurrentImageContext (); + } + + UIGraphics.EndImageContext (); + } + + // Setup up output context + UIGraphics.BeginImageContextWithOptions (image.Size, false, UIScreen.MainScreen.Scale); + + var outputContext = UIGraphics.GetCurrentContext (); + outputContext.ScaleCTM (1, -1); + outputContext.TranslateCTM (0, -image.Size.Height); + + // Draw base image + if (hasBlur) { + outputContext.SaveState (); + if (maskImage != null) { + outputContext.ClipToMask (imageRect, maskImage.CGImage); + } + + outputContext.DrawImage (imageRect, effectImage.CGImage); + outputContext.RestoreState (); + } + + if (tintColor != null) { + outputContext.SaveState (); + outputContext.SetFillColor (tintColor.CGColor); + outputContext.FillRect (imageRect); + outputContext.RestoreState (); + } + + var outputImage = UIGraphics.GetImageFromCurrentImageContext (); + UIGraphics.EndImageContext (); + + return outputImage; + } + } +} diff --git a/UIImageEffects/UIImageEffects/ViewController.cs b/UIImageEffects/UIImageEffects/ViewController.cs index 5d74561f8..dee1bcde0 100644 --- a/UIImageEffects/UIImageEffects/ViewController.cs +++ b/UIImageEffects/UIImageEffects/ViewController.cs @@ -1,99 +1,94 @@ -using Foundation; +using Foundation; using System; using UIKit; -namespace UIImageEffects -{ - public partial class ViewController : UIViewController - { - private const string IsFirstRunKey = "IsFirstRun"; - - private EffectType currentEffect = EffectType.None; - - private UIImage image; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - effectLabel.Text = string.Empty; - image = imageView.Image; - ShowAlertForFirstRun(); - } - - partial void Update(UITapGestureRecognizer sender) - { - UIImage effectImage = null; - var effectText = string.Empty; - var effectColor = UIColor.White; - - switch (currentEffect) - { - case EffectType.None: - currentEffect = EffectType.Light; - - effectImage = image.ApplyLightEffect(); - effectText = "Light"; - break; - - case EffectType.Light: - currentEffect = EffectType.ExtraLight; - - effectImage = image.ApplyExtraLightEffect(); - effectText = "Extra Light"; - effectColor = UIColor.LightGray; - break; - - case EffectType.ExtraLight: - currentEffect = EffectType.Dark; - - effectImage = image.ApplyDarkEffect(); - effectText = "Dark"; - effectColor = UIColor.DarkGray; - break; - - case EffectType.Dark: - currentEffect = EffectType.ColorTint; - - effectImage = image.ApplyTintEffect(UIColor.Blue); - effectText = "Color tint"; - effectColor = UIColor.DarkGray; - break; - - case EffectType.ColorTint: - currentEffect = EffectType.None; - - effectImage = image; - break; - } - - imageView.Image = effectImage; - effectLabel.Text = effectText; - effectLabel.TextColor = effectColor; - } - - private void ShowAlertForFirstRun() - { - var isFirstRun = NSUserDefaults.StandardUserDefaults.BoolForKey(IsFirstRunKey); - if (!isFirstRun) - { - var alert = UIAlertController.Create("Tap to change image effect", "", UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("Dismiss", UIAlertActionStyle.Default, null)); - PresentViewController(alert, true, null); - - NSUserDefaults.StandardUserDefaults.SetBool(true, IsFirstRunKey); - } - } - } - - enum EffectType - { - None, - Light, - ExtraLight, - Dark, - ColorTint - } -} \ No newline at end of file +namespace UIImageEffects { + public partial class ViewController : UIViewController { + private const string IsFirstRunKey = "IsFirstRun"; + + private EffectType currentEffect = EffectType.None; + + private UIImage image; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + effectLabel.Text = string.Empty; + image = imageView.Image; + ShowAlertForFirstRun (); + } + + partial void Update (UITapGestureRecognizer sender) + { + UIImage effectImage = null; + var effectText = string.Empty; + var effectColor = UIColor.White; + + switch (currentEffect) { + case EffectType.None: + currentEffect = EffectType.Light; + + effectImage = image.ApplyLightEffect (); + effectText = "Light"; + break; + + case EffectType.Light: + currentEffect = EffectType.ExtraLight; + + effectImage = image.ApplyExtraLightEffect (); + effectText = "Extra Light"; + effectColor = UIColor.LightGray; + break; + + case EffectType.ExtraLight: + currentEffect = EffectType.Dark; + + effectImage = image.ApplyDarkEffect (); + effectText = "Dark"; + effectColor = UIColor.DarkGray; + break; + + case EffectType.Dark: + currentEffect = EffectType.ColorTint; + + effectImage = image.ApplyTintEffect (UIColor.Blue); + effectText = "Color tint"; + effectColor = UIColor.DarkGray; + break; + + case EffectType.ColorTint: + currentEffect = EffectType.None; + + effectImage = image; + break; + } + + imageView.Image = effectImage; + effectLabel.Text = effectText; + effectLabel.TextColor = effectColor; + } + + private void ShowAlertForFirstRun () + { + var isFirstRun = NSUserDefaults.StandardUserDefaults.BoolForKey (IsFirstRunKey); + if (!isFirstRun) { + var alert = UIAlertController.Create ("Tap to change image effect", "", UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("Dismiss", UIAlertActionStyle.Default, null)); + PresentViewController (alert, true, null); + + NSUserDefaults.StandardUserDefaults.SetBool (true, IsFirstRunKey); + } + } + } + + enum EffectType { + None, + Light, + ExtraLight, + Dark, + ColorTint + } +} diff --git a/ViewTransitions/Classes/AppDelegate.cs b/ViewTransitions/Classes/AppDelegate.cs index f13b1f758..f5db84784 100644 --- a/ViewTransitions/Classes/AppDelegate.cs +++ b/ViewTransitions/Classes/AppDelegate.cs @@ -29,11 +29,9 @@ using Foundation; using UIKit; -namespace ViewTransitions -{ +namespace ViewTransitions { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; ViewTransitionsViewController viewController; diff --git a/ViewTransitions/Classes/ViewTransitionsViewController.cs b/ViewTransitions/Classes/ViewTransitionsViewController.cs index 7d6be34be..f32705d54 100644 --- a/ViewTransitions/Classes/ViewTransitionsViewController.cs +++ b/ViewTransitions/Classes/ViewTransitionsViewController.cs @@ -29,10 +29,8 @@ using Foundation; using CoreAnimation; -namespace ViewTransitions -{ - public partial class ViewTransitionsViewController : UIViewController - { +namespace ViewTransitions { + public partial class ViewTransitionsViewController : UIViewController { UIImageView view1, view2, view3; bool transitioning; @@ -65,8 +63,8 @@ public override void ViewDidLoad () nextTransitionButton.Clicked += PerformTransition; } - NSString[] types = new NSString[] { CATransition.TransitionMoveIn, CATransition.TransitionPush, CATransition.TransitionReveal, CATransition.TransitionFade }; - NSString[] supTypes = new NSString[] { CATransition.TransitionFromLeft, CATransition.TransitionFromRight, CATransition.TransitionFromTop, CATransition.TransitionFromBottom }; + NSString [] types = new NSString [] { CATransition.TransitionMoveIn, CATransition.TransitionPush, CATransition.TransitionReveal, CATransition.TransitionFade }; + NSString [] supTypes = new NSString [] { CATransition.TransitionFromLeft, CATransition.TransitionFromRight, CATransition.TransitionFromTop, CATransition.TransitionFromBottom }; Random random = new Random (); @@ -86,9 +84,9 @@ void PerformTransition (object sender, EventArgs e) // Now to set the type of transition int rnd = random.Next (types.Length); - transition.Type = types[rnd].ToString (); + transition.Type = types [rnd].ToString (); if (rnd < 3) // no fade transition -> randomly choose a subtype - transition.Subtype = supTypes[random.Next (supTypes.Length)].ToString (); + transition.Subtype = supTypes [random.Next (supTypes.Length)].ToString (); // Assign a delegate that sets transitioning to false, after the animation stopped. this.transitioning = true; @@ -106,8 +104,7 @@ void PerformTransition (object sender, EventArgs e) Swap (ref view2, ref view3); } - class AnimationDelegate : CAAnimationDelegate - { + class AnimationDelegate : CAAnimationDelegate { ViewTransitionsViewController ctrl; public AnimationDelegate (ViewTransitionsViewController ctrl) diff --git a/ViewTransitions/Other Sources/Main.cs b/ViewTransitions/Other Sources/Main.cs index ff1d23bf7..119386fb4 100644 --- a/ViewTransitions/Other Sources/Main.cs +++ b/ViewTransitions/Other Sources/Main.cs @@ -29,11 +29,9 @@ using Foundation; using UIKit; -namespace ViewTransitions -{ - public class Application - { - static void Main (string[] args) +namespace ViewTransitions { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/WalkingGameCompleteiOS/WalkingGame.iOS/AppDelegate.cs b/WalkingGameCompleteiOS/WalkingGame.iOS/AppDelegate.cs index 3d73e61f9..048aa9414 100644 --- a/WalkingGameCompleteiOS/WalkingGame.iOS/AppDelegate.cs +++ b/WalkingGameCompleteiOS/WalkingGame.iOS/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace WalkingGame.iOS { diff --git a/WalkingGameCompleteiOS/WalkingGame.iOS/Main.cs b/WalkingGameCompleteiOS/WalkingGame.iOS/Main.cs index bac02afeb..3e227575e 100644 --- a/WalkingGameCompleteiOS/WalkingGame.iOS/Main.cs +++ b/WalkingGameCompleteiOS/WalkingGame.iOS/Main.cs @@ -1,9 +1,9 @@ -using UIKit; +using UIKit; namespace WalkingGame.iOS { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WalkingGameCompleteiOS/WalkingGame/Animation.cs b/WalkingGameCompleteiOS/WalkingGame/Animation.cs index 2a1febbfa..808829268 100644 --- a/WalkingGameCompleteiOS/WalkingGame/Animation.cs +++ b/WalkingGameCompleteiOS/WalkingGame/Animation.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -64,7 +64,7 @@ public void AddFrame (Rectangle rectangle, TimeSpan duration) // frame time as obtained from gameTime public void Update (GameTime gameTime) { - double secondsIntoAnimation = + double secondsIntoAnimation = timeIntoAnimation.TotalSeconds + gameTime.ElapsedGameTime.TotalSeconds; @@ -72,4 +72,4 @@ public void Update (GameTime gameTime) timeIntoAnimation = TimeSpan.FromSeconds (remainder); } } -} \ No newline at end of file +} diff --git a/WalkingGameCompleteiOS/WalkingGame/AnimationFrame.cs b/WalkingGameCompleteiOS/WalkingGame/AnimationFrame.cs index 529f8e32c..c189a38a2 100644 --- a/WalkingGameCompleteiOS/WalkingGame/AnimationFrame.cs +++ b/WalkingGameCompleteiOS/WalkingGame/AnimationFrame.cs @@ -1,4 +1,4 @@ -using System; +using System; using Microsoft.Xna.Framework; diff --git a/WalkingGameCompleteiOS/WalkingGame/CharacterEntity.cs b/WalkingGameCompleteiOS/WalkingGame/CharacterEntity.cs index ac071a671..efec385f1 100644 --- a/WalkingGameCompleteiOS/WalkingGame/CharacterEntity.cs +++ b/WalkingGameCompleteiOS/WalkingGame/CharacterEntity.cs @@ -1,4 +1,4 @@ -using System; +using System; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; @@ -18,7 +18,7 @@ public class CharacterEntity { Animation standLeft; Animation standRight; - Animation currentAnimation; + Animation currentAnimation; public float X { get; set; } @@ -80,7 +80,7 @@ Vector2 GetDesiredVelocityFromInput () desiredVelocity.X = touchCollection [0].Position.X - X; desiredVelocity.Y = touchCollection [0].Position.Y - Y; - if (Math.Abs(desiredVelocity.X) > float.Epsilon || Math.Abs (desiredVelocity.Y) > float.Epsilon) { + if (Math.Abs (desiredVelocity.X) > float.Epsilon || Math.Abs (desiredVelocity.Y) > float.Epsilon) { desiredVelocity.Normalize (); const float desiredSpeed = 200; desiredVelocity *= desiredSpeed; @@ -94,8 +94,8 @@ public void Update (GameTime gameTime) { var velocity = GetDesiredVelocityFromInput (); - X += velocity.X * (float)gameTime.ElapsedGameTime.TotalSeconds; - Y += velocity.Y * (float)gameTime.ElapsedGameTime.TotalSeconds; + X += velocity.X * (float) gameTime.ElapsedGameTime.TotalSeconds; + Y += velocity.Y * (float) gameTime.ElapsedGameTime.TotalSeconds; // We can use the velocity variable to determine if the // character is moving or standing still @@ -153,4 +153,4 @@ public void Draw (SpriteBatch spriteBatch) spriteBatch.Draw (characterSheetTexture, topLeftOfSprite, sourceRectangle, Color.White); } } -} \ No newline at end of file +} diff --git a/WalkingGameCompleteiOS/WalkingGame/MainGame.cs b/WalkingGameCompleteiOS/WalkingGame/MainGame.cs index 9eeefb4b6..eb86264c1 100644 --- a/WalkingGameCompleteiOS/WalkingGame/MainGame.cs +++ b/WalkingGameCompleteiOS/WalkingGame/MainGame.cs @@ -1,4 +1,4 @@ -using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace WalkingGame { @@ -10,7 +10,7 @@ public class MainGame : Game { public MainGame () { - graphics = new GraphicsDeviceManager(this); + graphics = new GraphicsDeviceManager (this); graphics.IsFullScreen = true; Content.RootDirectory = "Content"; @@ -20,14 +20,14 @@ protected override void Initialize () { character = new CharacterEntity (GraphicsDevice); - base.Initialize(); - } + base.Initialize (); + } protected override void LoadContent () { // Create a new SpriteBatch, which can be used to draw textures. - spriteBatch = new SpriteBatch(GraphicsDevice); + spriteBatch = new SpriteBatch (GraphicsDevice); } protected override void Update (GameTime gameTime) @@ -49,7 +49,7 @@ protected override void Draw (GameTime gameTime) spriteBatch.End (); base.Draw (gameTime); - } + } } } diff --git a/WalkingGameCompleteiOS/WalkingGame/Properties/AssemblyInfo.cs b/WalkingGameCompleteiOS/WalkingGame/Properties/AssemblyInfo.cs index e0eff6a34..c156d76b4 100644 --- a/WalkingGameCompleteiOS/WalkingGame/Properties/AssemblyInfo.cs +++ b/WalkingGameCompleteiOS/WalkingGame/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/WalkingGameEmptyiOS/WalkingGame.iOS/AppDelegate.cs b/WalkingGameEmptyiOS/WalkingGame.iOS/AppDelegate.cs index 35514f1ad..e28965302 100644 --- a/WalkingGameEmptyiOS/WalkingGame.iOS/AppDelegate.cs +++ b/WalkingGameEmptyiOS/WalkingGame.iOS/AppDelegate.cs @@ -1,17 +1,15 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace WalkingGame.iOS -{ +namespace WalkingGame.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { private WalkingGame.MainGame game; @@ -23,9 +21,9 @@ public partial class AppDelegate : UIApplicationDelegate // You have 17 seconds to return from this method, or iOS will terminate your application. // public override void FinishedLaunching (UIApplication application) - { - game = new WalkingGame.MainGame(); - game.Run(); + { + game = new WalkingGame.MainGame (); + game.Run (); } } } diff --git a/WalkingGameEmptyiOS/WalkingGame.iOS/Main.cs b/WalkingGameEmptyiOS/WalkingGame.iOS/Main.cs index 67a8433e8..886ebad9d 100644 --- a/WalkingGameEmptyiOS/WalkingGame.iOS/Main.cs +++ b/WalkingGameEmptyiOS/WalkingGame.iOS/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace WalkingGame.iOS -{ - public class Application - { +namespace WalkingGame.iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WalkingGameEmptyiOS/WalkingGame/MainGame.cs b/WalkingGameEmptyiOS/WalkingGame/MainGame.cs index 8270d866e..ce4ed14b2 100644 --- a/WalkingGameEmptyiOS/WalkingGame/MainGame.cs +++ b/WalkingGameEmptyiOS/WalkingGame/MainGame.cs @@ -1,43 +1,41 @@ -using System; +using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; -namespace WalkingGame -{ - public class MainGame : Game - { +namespace WalkingGame { + public class MainGame : Game { GraphicsDeviceManager graphics; - public MainGame() + public MainGame () { - graphics = new GraphicsDeviceManager(this); + graphics = new GraphicsDeviceManager (this); graphics.IsFullScreen = true; Content.RootDirectory = "Content"; } - protected override void Initialize() + protected override void Initialize () { - base.Initialize(); - } + base.Initialize (); + } - protected override void LoadContent() + protected override void LoadContent () { - - } + + } - protected override void Update(GameTime gameTime) - { - base.Update(gameTime); - } + protected override void Update (GameTime gameTime) + { + base.Update (gameTime); + } - protected override void Draw(GameTime gameTime) + protected override void Draw (GameTime gameTime) { - GraphicsDevice.Clear(Color.CornflowerBlue); + GraphicsDevice.Clear (Color.CornflowerBlue); - base.Draw(gameTime); - } + base.Draw (gameTime); + } } } diff --git a/WalkingGameEmptyiOS/WalkingGame/Properties/AssemblyInfo.cs b/WalkingGameEmptyiOS/WalkingGame/Properties/AssemblyInfo.cs index e0eff6a34..c156d76b4 100644 --- a/WalkingGameEmptyiOS/WalkingGame/Properties/AssemblyInfo.cs +++ b/WalkingGameEmptyiOS/WalkingGame/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/ExtensionDelegate.cs b/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/ExtensionDelegate.cs index 5bdebda83..a9620fb04 100644 --- a/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/ExtensionDelegate.cs +++ b/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/ExtensionDelegate.cs @@ -1,32 +1,30 @@ -using System; +using System; using Foundation; using WatchKit; -namespace WatchContainer.WatchAppExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - public override void ApplicationDidFinishLaunching() - { - // Perform any final initialization of your application. - } +namespace WatchContainer.WatchAppExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + public override void ApplicationDidFinishLaunching () + { + // Perform any final initialization of your application. + } - public override void ApplicationDidBecomeActive() - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } + public override void ApplicationDidBecomeActive () + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } - public override void ApplicationWillResignActive() - { - // Sent when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions - // (such as an incoming phone call or SMS message) or when the user quits the application - // and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, etc. - } - } + public override void ApplicationWillResignActive () + { + // Sent when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions + // (such as an incoming phone call or SMS message) or when the user quits the application + // and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, etc. + } + } } diff --git a/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/InterfaceController.cs b/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/InterfaceController.cs index e21cdd1a7..69daa7905 100644 --- a/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/InterfaceController.cs +++ b/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/InterfaceController.cs @@ -1,42 +1,40 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchContainer.WatchAppExtension -{ - public partial class InterfaceController : WKInterfaceController - { - int clickCount = 0; - partial void OnButtonPress() - { - var msg = String.Format("Clicked {0} times", ++clickCount); - myLabel.SetText(msg); - } +namespace WatchContainer.WatchAppExtension { + public partial class InterfaceController : WKInterfaceController { + int clickCount = 0; + partial void OnButtonPress () + { + var msg = String.Format ("Clicked {0} times", ++clickCount); + myLabel.SetText (msg); + } - protected InterfaceController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } + protected InterfaceController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } - public override void Awake(NSObject context) - { - base.Awake(context); + public override void Awake (NSObject context) + { + base.Awake (context); - // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); - } + // Configure interface objects here. + Console.WriteLine ("{0} awake with context", this); + } - public override void WillActivate() - { - // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); - } + public override void WillActivate () + { + // This method is called when the watch view controller is about to be visible to the user. + Console.WriteLine ("{0} will activate", this); + } - public override void DidDeactivate() - { - // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); - } - } + public override void DidDeactivate () + { + // This method is called when the watch view controller is no longer visible to the user. + Console.WriteLine ("{0} did deactivate", this); + } + } } diff --git a/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/NotificationController.cs b/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/NotificationController.cs index c9b3e4a38..fc4af0617 100644 --- a/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/NotificationController.cs +++ b/WatchKit/GettingStarted/WatchContainer.WatchAppExtension/NotificationController.cs @@ -1,53 +1,51 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchContainer.WatchAppExtension -{ - public partial class NotificationController : WKUserNotificationInterfaceController - { - protected NotificationController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } +namespace WatchContainer.WatchAppExtension { + public partial class NotificationController : WKUserNotificationInterfaceController { + protected NotificationController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } - public NotificationController() - { - // Initialize variables here. - // Configure interface objects here. - } + public NotificationController () + { + // Initialize variables here. + // Configure interface objects here. + } - // public override void DidReceiveLocalNotification (UIKit.UILocalNotification localNotification, Action<WKUserNotificationInterfaceType> completionHandler) - // { - // // This method is called when a local notification needs to be presented. - // // Implement it if you use a dynamic notification interface. - // // Populate your dynamic notification interface as quickly as possible. - // // - // // After populating your dynamic notification interface call the completion block. - // completionHandler.Invoke (WKUserNotificationInterfaceType.Custom); - // } - // - // public override void DidReceiveRemoteNotification (NSDictionary remoteNotification, Action<WKUserNotificationInterfaceType> completionHandler) - // { - // // This method is called when a remote notification needs to be presented. - // // Implement it if you use a dynamic notification interface. - // // Populate your dynamic notification interface as quickly as possible. - // // - // // After populating your dynamic notification interface call the completion block. - // completionHandler.Invoke (WKUserNotificationInterfaceType.Custom); - // } + // public override void DidReceiveLocalNotification (UIKit.UILocalNotification localNotification, Action<WKUserNotificationInterfaceType> completionHandler) + // { + // // This method is called when a local notification needs to be presented. + // // Implement it if you use a dynamic notification interface. + // // Populate your dynamic notification interface as quickly as possible. + // // + // // After populating your dynamic notification interface call the completion block. + // completionHandler.Invoke (WKUserNotificationInterfaceType.Custom); + // } + // + // public override void DidReceiveRemoteNotification (NSDictionary remoteNotification, Action<WKUserNotificationInterfaceType> completionHandler) + // { + // // This method is called when a remote notification needs to be presented. + // // Implement it if you use a dynamic notification interface. + // // Populate your dynamic notification interface as quickly as possible. + // // + // // After populating your dynamic notification interface call the completion block. + // completionHandler.Invoke (WKUserNotificationInterfaceType.Custom); + // } - public override void WillActivate() - { - // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); - } + public override void WillActivate () + { + // This method is called when the watch view controller is about to be visible to the user. + Console.WriteLine ("{0} will activate", this); + } - public override void DidDeactivate() - { - // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); - } - } + public override void DidDeactivate () + { + // This method is called when the watch view controller is no longer visible to the user. + Console.WriteLine ("{0} did deactivate", this); + } + } } diff --git a/WatchKit/GettingStarted/WatchKitCatalog/AppDelegate.cs b/WatchKit/GettingStarted/WatchKitCatalog/AppDelegate.cs index ae4bcf23c..f8a64d386 100644 --- a/WatchKit/GettingStarted/WatchKitCatalog/AppDelegate.cs +++ b/WatchKit/GettingStarted/WatchKitCatalog/AppDelegate.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; using Foundation; -namespace WK2 -{ +namespace WK2 { //Minimal app delegate [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; diff --git a/WatchKit/GettingStarted/WatchKitCatalog/Main.cs b/WatchKit/GettingStarted/WatchKitCatalog/Main.cs index fb59e45bc..333948a73 100644 --- a/WatchKit/GettingStarted/WatchKitCatalog/Main.cs +++ b/WatchKit/GettingStarted/WatchKitCatalog/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace WK2 -{ - public class Application - { +namespace WK2 { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WatchKit/GettingStarted/WatchKitCatalog/WatchKitCatalogViewController.cs b/WatchKit/GettingStarted/WatchKitCatalog/WatchKitCatalogViewController.cs index 41dc390be..a2b63c0b3 100644 --- a/WatchKit/GettingStarted/WatchKitCatalog/WatchKitCatalogViewController.cs +++ b/WatchKit/GettingStarted/WatchKitCatalog/WatchKitCatalogViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace WK2 -{ +namespace WK2 { //Minimal custom controller - public partial class WatchKitCatalogViewController : UIViewController - { + public partial class WatchKitCatalogViewController : UIViewController { public WatchKitCatalogViewController (IntPtr handle) : base (handle) { } diff --git a/WatchKit/GpsWatch/GpsWatch/AppDelegate.cs b/WatchKit/GpsWatch/GpsWatch/AppDelegate.cs index a5305f489..177c62739 100644 --- a/WatchKit/GpsWatch/GpsWatch/AppDelegate.cs +++ b/WatchKit/GpsWatch/GpsWatch/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; @@ -6,14 +6,12 @@ using UIKit; using CoreLocation; -namespace GpsWatch -{ +namespace GpsWatch { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { CLLocationManager locationManager; CLLocationCoordinate2D locationCoordinate; CLAuthorizationStatus status; @@ -40,7 +38,7 @@ public override void WillEnterForeground (UIApplication application) SetupLocationManager (); } - void SetupLocationManager() + void SetupLocationManager () { if (locationManager != null) return; @@ -56,16 +54,16 @@ void OnAuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e) status = e.Status; switch (status) { - case CLAuthorizationStatus.AuthorizedAlways: - locationManager.StartUpdatingLocation (); - break; + case CLAuthorizationStatus.AuthorizedAlways: + locationManager.StartUpdatingLocation (); + break; - case CLAuthorizationStatus.NotDetermined: - locationManager.RequestAlwaysAuthorization (); - break; + case CLAuthorizationStatus.NotDetermined: + locationManager.RequestAlwaysAuthorization (); + break; - default: - break; + default: + break; } } @@ -76,7 +74,7 @@ void OnLocationsUpdated (object sender, CLLocationsUpdatedEventArgs e) public override void HandleWatchKitExtensionRequest (UIApplication application, NSDictionary userInfo, Action<NSDictionary> reply) { - reply (new NSDictionary ("status", NSNumber.FromUInt32 ((uint)status), + reply (new NSDictionary ("status", NSNumber.FromUInt32 ((uint) status), "lon", NSNumber.FromDouble (locationCoordinate.Longitude), "lat", NSNumber.FromDouble (locationCoordinate.Latitude))); } diff --git a/WatchKit/GpsWatch/GpsWatch/GpsWatchViewController.cs b/WatchKit/GpsWatch/GpsWatch/GpsWatchViewController.cs index ac6d526b7..014809b8b 100644 --- a/WatchKit/GpsWatch/GpsWatch/GpsWatchViewController.cs +++ b/WatchKit/GpsWatch/GpsWatch/GpsWatchViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using UIKit; @@ -6,10 +6,8 @@ using CoreGraphics; using System.Linq; -namespace GpsWatch -{ - public partial class GpsWatchViewController : UIViewController - { +namespace GpsWatch { + public partial class GpsWatchViewController : UIViewController { UILabel lbl; static bool UserInterfaceIdiomIsPhone { @@ -24,7 +22,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -38,7 +36,7 @@ public override void ViewDidLoad () ShowDescription (); } - void ShowDescription() + void ShowDescription () { lbl = new UILabel { Lines = 0, diff --git a/WatchKit/GpsWatch/GpsWatch/Main.cs b/WatchKit/GpsWatch/GpsWatch/Main.cs index 403a38f9e..1f52cb750 100644 --- a/WatchKit/GpsWatch/GpsWatch/Main.cs +++ b/WatchKit/GpsWatch/GpsWatch/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace GpsWatch -{ - public class Application - { +namespace GpsWatch { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WatchKit/GpsWatch/WatchAppExtension/GlanceController.cs b/WatchKit/GpsWatch/WatchAppExtension/GlanceController.cs index 3940e1827..a9abff1c7 100644 --- a/WatchKit/GpsWatch/WatchAppExtension/GlanceController.cs +++ b/WatchKit/GpsWatch/WatchAppExtension/GlanceController.cs @@ -1,12 +1,10 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchAppExtension -{ - public partial class GlanceController : WKInterfaceController - { +namespace WatchAppExtension { + public partial class GlanceController : WKInterfaceController { public GlanceController (IntPtr handle) : base (handle) { } diff --git a/WatchKit/GpsWatch/WatchAppExtension/InterfaceController.cs b/WatchKit/GpsWatch/WatchAppExtension/InterfaceController.cs index 55a8a54ad..58eaf54e0 100644 --- a/WatchKit/GpsWatch/WatchAppExtension/InterfaceController.cs +++ b/WatchKit/GpsWatch/WatchAppExtension/InterfaceController.cs @@ -1,13 +1,11 @@ -using System; +using System; using WatchKit; using Foundation; using CoreLocation; -namespace WatchAppExtension -{ - public partial class InterfaceController : WKInterfaceController - { +namespace WatchAppExtension { + public partial class InterfaceController : WKInterfaceController { NSTimer timer; public InterfaceController (IntPtr handle) : base (handle) @@ -37,60 +35,60 @@ public override void DidDeactivate () Console.WriteLine ("{0} did deactivate", this); } - void UpdateUserInterface(NSTimer t) + void UpdateUserInterface (NSTimer t) { WKInterfaceController.OpenParentApplication (new NSDictionary (), (replyInfo, error) => { - if(error != null) { + if (error != null) { Console.WriteLine (error); return; } - var status = (CLAuthorizationStatus)((NSNumber)replyInfo["status"]).UInt32Value; - var longitude = ((NSNumber)replyInfo["lon"]).DoubleValue; - var latitude = ((NSNumber)replyInfo["lat"]).DoubleValue; + var status = (CLAuthorizationStatus) ((NSNumber) replyInfo ["status"]).UInt32Value; + var longitude = ((NSNumber) replyInfo ["lon"]).DoubleValue; + var latitude = ((NSNumber) replyInfo ["lat"]).DoubleValue; Console.WriteLine ("authorization status {0}", status); - switch(status) { - case CLAuthorizationStatus.AuthorizedAlways: - SetCooridinate(longitude, latitude); - HideWarning(); - break; - - case CLAuthorizationStatus.NotDetermined: - SetNotAvailable(); - ShowWarning("Launch the iOS app first"); - break; - - case CLAuthorizationStatus.Denied: - SetNotAvailable(); - ShowWarning("Enable Location Service on iPhone"); - break; - - default: - throw new NotImplementedException(); + switch (status) { + case CLAuthorizationStatus.AuthorizedAlways: + SetCooridinate (longitude, latitude); + HideWarning (); + break; + + case CLAuthorizationStatus.NotDetermined: + SetNotAvailable (); + ShowWarning ("Launch the iOS app first"); + break; + + case CLAuthorizationStatus.Denied: + SetNotAvailable (); + ShowWarning ("Enable Location Service on iPhone"); + break; + + default: + throw new NotImplementedException (); } }); } - void SetCooridinate(double longitude, double latitude) + void SetCooridinate (double longitude, double latitude) { LongitudeValueLbl.SetText (longitude.ToString ()); LatitudeValueLbl.SetText (latitude.ToString ()); } - void SetNotAvailable() + void SetNotAvailable () { LongitudeValueLbl.SetText ("not available"); LatitudeValueLbl.SetText ("not available"); } - void ShowWarning(string warning) + void ShowWarning (string warning) { WarningLbl.SetText (warning); WarningLbl.SetHidden (false); } - void HideWarning() + void HideWarning () { WarningLbl.SetHidden (true); } diff --git a/WatchKit/GpsWatch/WatchAppExtension/NotificationController.cs b/WatchKit/GpsWatch/WatchAppExtension/NotificationController.cs index a3bb18fa8..b51cd8e5c 100644 --- a/WatchKit/GpsWatch/WatchAppExtension/NotificationController.cs +++ b/WatchKit/GpsWatch/WatchAppExtension/NotificationController.cs @@ -1,12 +1,10 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchAppExtension -{ - public partial class NotificationController : WKUserNotificationInterfaceController - { +namespace WatchAppExtension { + public partial class NotificationController : WKUserNotificationInterfaceController { public NotificationController (IntPtr handle) : base (handle) { } diff --git a/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/InterfaceController.cs b/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/InterfaceController.cs index 6bad5246a..ce6446be5 100644 --- a/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/InterfaceController.cs +++ b/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/InterfaceController.cs @@ -1,12 +1,10 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchNotifications_iOSWatchKitExtension -{ - public partial class InterfaceController : WKInterfaceController - { +namespace WatchNotifications_iOSWatchKitExtension { + public partial class InterfaceController : WKInterfaceController { public InterfaceController (IntPtr handle) : base (handle) { } @@ -23,7 +21,7 @@ public override void HandleRemoteNotificationAction (string identifier, NSDictio { base.HandleRemoteNotificationAction (identifier, remoteNotification); - Console.WriteLine ("HandleRemoteNotificationAction count:" + remoteNotification.Count); + Console.WriteLine ("HandleRemoteNotificationAction count:" + remoteNotification.Count); } diff --git a/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/NotificationController.cs b/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/NotificationController.cs index b99af0d9c..ff57cb5f6 100644 --- a/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/NotificationController.cs +++ b/WatchKit/WatchNotifications/WatchNotifications_WatchKitExtension/NotificationController.cs @@ -1,12 +1,10 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchNotifications_iOSWatchKitExtension -{ - public partial class NotificationController : WKUserNotificationInterfaceController - { +namespace WatchNotifications_iOSWatchKitExtension { + public partial class NotificationController : WKUserNotificationInterfaceController { public NotificationController (IntPtr handle) : base (handle) { } diff --git a/WatchKit/WatchNotifications/WatchNotifications_iOS/AppDelegate.cs b/WatchKit/WatchNotifications/WatchNotifications_iOS/AppDelegate.cs index f6db4b64f..5e046c127 100644 --- a/WatchKit/WatchNotifications/WatchNotifications_iOS/AppDelegate.cs +++ b/WatchKit/WatchNotifications/WatchNotifications_iOS/AppDelegate.cs @@ -1,19 +1,17 @@ -using Foundation; +using Foundation; using UIKit; using System; -namespace WatchNotifications_iOS -{ +namespace WatchNotifications_iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { - public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification) + public override void ReceivedLocalNotification (UIApplication application, UILocalNotification notification) { // show an alert - new UIAlertView(notification.AlertAction, "!" + notification.AlertBody, null, "OK", null).Show(); + new UIAlertView (notification.AlertAction, "!" + notification.AlertBody, null, "OK", null).Show (); // reset our badge UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; @@ -26,7 +24,7 @@ public override void HandleAction (UIApplication application, string actionIdent public override void HandleAction (UIApplication application, string actionIdentifier, UILocalNotification localNotification, Action completionHandler) { // show an alert - new UIAlertView(localNotification.AlertAction, "?" + localNotification.AlertBody, null, "OK", null).Show(); + new UIAlertView (localNotification.AlertAction, "?" + localNotification.AlertBody, null, "OK", null).Show (); // reset our badge UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; @@ -35,15 +33,12 @@ public override void HandleAction (UIApplication application, string actionIdent public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // check for a notification - if (launchOptions != null) - { + if (launchOptions != null) { // check for a local notification - if (launchOptions.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey)) - { - var localNotification = launchOptions[UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; - if (localNotification != null) - { - new UIAlertView(localNotification.AlertAction, localNotification.AlertBody, null, "OK", null).Show(); + if (launchOptions.ContainsKey (UIApplication.LaunchOptionsLocalNotificationKey)) { + var localNotification = launchOptions [UIApplication.LaunchOptionsLocalNotificationKey] as UILocalNotification; + if (localNotification != null) { + new UIAlertView (localNotification.AlertAction, localNotification.AlertBody, null, "OK", null).Show (); // reset our badge UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0; } @@ -54,7 +49,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary //UIApplication.SharedApplication.RegisterForRemoteNotificationTypes (UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge); // iOS 8 - var settings = UIUserNotificationSettings.GetSettingsForTypes( + var settings = UIUserNotificationSettings.GetSettingsForTypes ( UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound , null); UIApplication.SharedApplication.RegisterUserNotificationSettings (settings); diff --git a/WatchKit/WatchNotifications/WatchNotifications_iOS/Main.cs b/WatchKit/WatchNotifications/WatchNotifications_iOS/Main.cs index 4f24fa285..5169dd12c 100644 --- a/WatchKit/WatchNotifications/WatchNotifications_iOS/Main.cs +++ b/WatchKit/WatchNotifications/WatchNotifications_iOS/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace WatchNotifications_iOS -{ - public class Application - { +namespace WatchNotifications_iOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WatchKit/WatchNotifications/WatchNotifications_iOS/ViewController.cs b/WatchKit/WatchNotifications/WatchNotifications_iOS/ViewController.cs index 6ff1eaa97..9a6f98e18 100644 --- a/WatchKit/WatchNotifications/WatchNotifications_iOS/ViewController.cs +++ b/WatchKit/WatchNotifications/WatchNotifications_iOS/ViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace WatchNotifications_iOS -{ - public partial class ViewController : UIViewController - { +namespace WatchNotifications_iOS { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } @@ -17,17 +15,17 @@ public ViewController (IntPtr handle) : base (handle) partial void UIButton7_TouchUpInside (UIButton sender) { // create the notification - var notification = new UILocalNotification(); + var notification = new UILocalNotification (); // set the fire date (the date time in which it will fire) - notification.FireDate = NSDate.Now.AddSeconds(10); //DateTime.Now.AddSeconds(10)); + notification.FireDate = NSDate.Now.AddSeconds (10); //DateTime.Now.AddSeconds(10)); notification.TimeZone = NSTimeZone.DefaultTimeZone; // configure the alert stuff notification.AlertTitle = "Alert Title"; notification.AlertAction = "Alert Action"; notification.AlertBody = "Alert Body: 10 sec alert fired!"; - notification.UserInfo = NSDictionary.FromObjectAndKey (new NSString("UserInfo for notification"), new NSString("Notification")); + notification.UserInfo = NSDictionary.FromObjectAndKey (new NSString ("UserInfo for notification"), new NSString ("Notification")); // modify the badge - has no effect on the Watch //notification.ApplicationIconBadgeNumber = 1; @@ -36,7 +34,7 @@ partial void UIButton7_TouchUpInside (UIButton sender) //notification.SoundName = UILocalNotification.DefaultSoundName; // schedule it - UIApplication.SharedApplication.ScheduleLocalNotification(notification); + UIApplication.SharedApplication.ScheduleLocalNotification (notification); } public override void ViewDidLoad () diff --git a/WayUpSample/Main.cs b/WayUpSample/Main.cs index 2a91fc948..eedd7307a 100644 --- a/WayUpSample/Main.cs +++ b/WayUpSample/Main.cs @@ -4,18 +4,15 @@ using Foundation; using UIKit; -namespace WayUp -{ - public class Application - { - static void Main (string[] args) +namespace WayUp { + public class Application { + static void Main (string [] args) { UIApplication.Main (args); } } - public partial class WhichWayIsUpAppDelegate : UIApplicationDelegate - { + public partial class WhichWayIsUpAppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { @@ -28,7 +25,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) public partial class CrateViewController : UIViewController { - public CrateViewController (IntPtr handle) : base (handle) {} + public CrateViewController (IntPtr handle) : base (handle) { } public override bool ShouldAutorotate () { diff --git a/WeatherMap/AppDelegate.cs b/WeatherMap/AppDelegate.cs index aa76ee841..c17fdc993 100644 --- a/WeatherMap/AppDelegate.cs +++ b/WeatherMap/AppDelegate.cs @@ -4,16 +4,14 @@ using Foundation; using UIKit; -namespace WeatherMap -{ +namespace WeatherMap { /// <summary> /// The UIApplicationDelegate for the application. This class is responsible for launching the /// User Interface of the application, as well as listening (and optionally responding) to /// application events from iOS. /// </summary> [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations WeatherMapViewController viewController; UIWindow window; diff --git a/WeatherMap/Main.cs b/WeatherMap/Main.cs index f3fdec3e0..f9fc9d5e3 100644 --- a/WeatherMap/Main.cs +++ b/WeatherMap/Main.cs @@ -30,14 +30,12 @@ using Foundation; using UIKit; -namespace WeatherMap -{ - public class Application - { +namespace WeatherMap { + public class Application { /// <summary> /// This is the main entry point of the application. /// </summary> - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WeatherMap/SQLite.cs b/WeatherMap/SQLite.cs index 1bcdc63f3..2dd429127 100644 --- a/WeatherMap/SQLite.cs +++ b/WeatherMap/SQLite.cs @@ -26,13 +26,11 @@ using System.Linq; using System.Linq.Expressions; -namespace SQLite -{ - public class SQLiteException : System.Exception - { +namespace SQLite { + public class SQLiteException : System.Exception { public SQLite3.Result Result { get; private set; } - protected SQLiteException (SQLite3.Result r,string message) : base(message) + protected SQLiteException (SQLite3.Result r, string message) : base (message) { Result = r; } @@ -46,8 +44,7 @@ public static SQLiteException New (SQLite3.Result r, string message) /// <summary> /// Represents an open connection to a SQLite database. /// </summary> - public class SQLiteConnection : IDisposable - { + public class SQLiteConnection : IDisposable { private bool _open; private TimeSpan _busyTimeout; private Dictionary<string, TableMapping> _mappings = null; @@ -106,7 +103,7 @@ public TimeSpan BusyTimeout { set { _busyTimeout = value; if (Handle != IntPtr.Zero) { - SQLite3.BusyTimeout (Handle, (int)_busyTimeout.TotalMilliseconds); + SQLite3.BusyTimeout (Handle, (int) _busyTimeout.TotalMilliseconds); } } } @@ -159,7 +156,7 @@ public TableMapping GetMapping (Type type) /// </returns> public int CreateTable<T> () { - var ty = typeof(T); + var ty = typeof (T); if (_tables == null) { _tables = new Dictionary<string, TableMapping> (); @@ -181,8 +178,7 @@ public int CreateTable<T> () try { Execute (query); count = 1; - } - catch (SQLiteException) { + } catch (SQLiteException) { } if (count == 0) { @@ -199,8 +195,7 @@ public int CreateTable<T> () return count; } - class TableInfo - { + class TableInfo { public int cid { get; set; } public string name { get; set; } @@ -253,7 +248,7 @@ void MigrateTable (TableMapping map) /// <returns> /// A <see cref="SQLiteCommand"/> /// </returns> - public SQLiteCommand CreateCommand (string cmdText, params object[] ps) + public SQLiteCommand CreateCommand (string cmdText, params object [] ps) { if (!_open) { throw SQLiteException.New (SQLite3.Result.Error, "Cannot create commands from unopened database"); @@ -284,7 +279,7 @@ public SQLiteCommand CreateCommand (string cmdText, params object[] ps) /// <returns> /// The number of rows modified in the database as a result of this execution. /// </returns> - public int Execute (string query, params object[] args) + public int Execute (string query, params object [] args) { var cmd = CreateCommand (query, args); @@ -322,7 +317,7 @@ public int Execute (string query, params object[] args) /// <returns> /// An enumerable with one result for each row returned by the query. /// </returns> - public List<T> Query<T> (string query, params object[] args) where T : new() + public List<T> Query<T> (string query, params object [] args) where T : new() { var cmd = CreateCommand (query, args); return cmd.ExecuteQuery<T> (); @@ -348,7 +343,7 @@ public int Execute (string query, params object[] args) /// <returns> /// An enumerable with one result for each row returned by the query. /// </returns> - public List<object> Query (TableMapping map, string query, params object[] args) + public List<object> Query (TableMapping map, string query, params object [] args) { var cmd = CreateCommand (query, args); return cmd.ExecuteQuery<object> (map); @@ -380,7 +375,7 @@ public List<object> Query (TableMapping map, string query, params object[] args) /// </returns> public T Get<T> (object pk) where T : new() { - var map = GetMapping (typeof(T)); + var map = GetMapping (typeof (T)); string query = string.Format ("select * from \"{0}\" where \"{1}\" = ?", map.TableName, map.PK.Name); return Query<T> (query, pk).First (); } @@ -520,7 +515,7 @@ public int Insert (object obj, string extra, Type objType) var map = GetMapping (objType); var cols = map.InsertColumns; - var vals = new object[cols.Length]; + var vals = new object [cols.Length]; for (var i = 0; i < vals.Length; i++) { vals [i] = cols [i].GetValue (obj); } @@ -570,14 +565,14 @@ public int Update (object obj, Type objType) } var cols = from p in map.Columns - where p != pk - select p; + where p != pk + select p; var vals = from c in cols - select c.GetValue (obj); + select c.GetValue (obj); var ps = new List<object> (vals); ps.Add (pk.GetValue (obj)); var q = string.Format ("update \"{0}\" set {1} where {2} = ? ", map.TableName, string.Join (",", (from c in cols - select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); + select "\"" + c.Name + "\" = ? ").ToArray ()), pk.Name); return Execute (q, ps.ToArray ()); } @@ -616,24 +611,19 @@ public void Close () } } - public class PrimaryKeyAttribute : Attribute - { + public class PrimaryKeyAttribute : Attribute { } - public class AutoIncrementAttribute : Attribute - { + public class AutoIncrementAttribute : Attribute { } - public class IndexedAttribute : Attribute - { + public class IndexedAttribute : Attribute { } - public class IgnoreAttribute : Attribute - { + public class IgnoreAttribute : Attribute { } - public class MaxLengthAttribute : Attribute - { + public class MaxLengthAttribute : Attribute { public int Value { get; private set; } public MaxLengthAttribute (int length) @@ -642,8 +632,7 @@ public MaxLengthAttribute (int length) } } - public class CollationAttribute: Attribute - { + public class CollationAttribute : Attribute { public string Value { get; private set; } public CollationAttribute (string collation) @@ -652,18 +641,17 @@ public CollationAttribute (string collation) } } - public class TableMapping - { + public class TableMapping { public Type MappedType { get; private set; } public string TableName { get; private set; } - public Column[] Columns { get; private set; } + public Column [] Columns { get; private set; } public Column PK { get; private set; } Column _autoPk = null; - Column[] _insertColumns = null; + Column [] _insertColumns = null; string _insertSql = null; public TableMapping (Type type) @@ -673,7 +661,7 @@ public TableMapping (Type type) var props = MappedType.GetProperties (BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty); var cols = new List<Column> (); foreach (var p in props) { - var ignore = p.GetCustomAttributes (typeof(IgnoreAttribute), true).Length > 0; + var ignore = p.GetCustomAttributes (typeof (IgnoreAttribute), true).Length > 0; if (p.CanWrite && !ignore) { cols.Add (new PropColumn (p)); } @@ -700,7 +688,7 @@ public void SetAutoIncPK (object obj, long id) } } - public Column[] InsertColumns { + public Column [] InsertColumns { get { if (_insertColumns == null) { _insertColumns = Columns.Where (c => !c.IsAutoInc).ToArray (); @@ -720,8 +708,8 @@ public string InsertSql (string extra) if (_insertSql == null) { var cols = InsertColumns; _insertSql = string.Format ("insert {3} into \"{0}\"({1}) values ({2})", TableName, string.Join (",", (from c in cols - select "\"" + c.Name + "\"").ToArray ()), string.Join (",", (from c in cols - select "?").ToArray ()), extra); + select "\"" + c.Name + "\"").ToArray ()), string.Join (",", (from c in cols + select "?").ToArray ()), extra); } return _insertSql; } @@ -740,8 +728,7 @@ public PreparedSqlLiteInsertCommand GetInsertCommand (SQLiteConnection conn, str return _insertCommand; } - public abstract class Column - { + public abstract class Column { public string Name { get; protected set; } public Type ColumnType { get; protected set; } @@ -763,8 +750,7 @@ public abstract class Column public abstract object GetValue (object obj); } - public class PropColumn : Column - { + public class PropColumn : Column { PropertyInfo _prop; public PropColumn (PropertyInfo prop) @@ -772,7 +758,7 @@ public PropColumn (PropertyInfo prop) _prop = prop; Name = prop.Name; //If this type is Nullable<T> then Nullable.GetUnderlyingType returns the T, otherwise it returns null, so get the the actual type instead - ColumnType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType; + ColumnType = Nullable.GetUnderlyingType (prop.PropertyType) ?? prop.PropertyType; Collation = Orm.Collation (prop); IsAutoInc = Orm.IsAutoInc (prop); IsPK = Orm.IsPK (prop); @@ -793,8 +779,7 @@ public override object GetValue (object obj) } } - public static class Orm - { + public static class Orm { public const int DefaultMaxStringLength = 140; public static string SqlDecl (TableMapping.Column p) @@ -820,20 +805,20 @@ public static string SqlDecl (TableMapping.Column p) public static string SqlType (TableMapping.Column p) { var clrType = p.ColumnType; - if (clrType == typeof(Boolean) || clrType == typeof(Byte) || clrType == typeof(UInt16) || clrType == typeof(SByte) || clrType == typeof(Int16) || clrType == typeof(Int32)) { + if (clrType == typeof (Boolean) || clrType == typeof (Byte) || clrType == typeof (UInt16) || clrType == typeof (SByte) || clrType == typeof (Int16) || clrType == typeof (Int32)) { return "integer"; - } else if (clrType == typeof(UInt32) || clrType == typeof(Int64)) { + } else if (clrType == typeof (UInt32) || clrType == typeof (Int64)) { return "bigint"; - } else if (clrType == typeof(Single) || clrType == typeof(Double) || clrType == typeof(Decimal)) { + } else if (clrType == typeof (Single) || clrType == typeof (Double) || clrType == typeof (Decimal)) { return "float"; - } else if (clrType == typeof(String)) { + } else if (clrType == typeof (String)) { int len = p.MaxStringLength; return "varchar(" + len + ")"; - } else if (clrType == typeof(DateTime)) { + } else if (clrType == typeof (DateTime)) { return "datetime"; } else if (clrType.IsEnum) { return "integer"; - } else if (clrType == typeof(byte[])) { + } else if (clrType == typeof (byte [])) { return "blob"; } else { throw new NotSupportedException ("Don't know about " + clrType); @@ -842,15 +827,15 @@ public static string SqlType (TableMapping.Column p) public static bool IsPK (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(PrimaryKeyAttribute), true); + var attrs = p.GetCustomAttributes (typeof (PrimaryKeyAttribute), true); return attrs.Length > 0; } public static string Collation (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(CollationAttribute), true); + var attrs = p.GetCustomAttributes (typeof (CollationAttribute), true); if (attrs.Length > 0) { - return ((CollationAttribute)attrs [0]).Value; + return ((CollationAttribute) attrs [0]).Value; } else { return string.Empty; } @@ -858,29 +843,28 @@ public static string Collation (MemberInfo p) public static bool IsAutoInc (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(AutoIncrementAttribute), true); + var attrs = p.GetCustomAttributes (typeof (AutoIncrementAttribute), true); return attrs.Length > 0; } public static bool IsIndexed (MemberInfo p) { - var attrs = p.GetCustomAttributes (typeof(IndexedAttribute), true); + var attrs = p.GetCustomAttributes (typeof (IndexedAttribute), true); return attrs.Length > 0; } public static int MaxStringLength (PropertyInfo p) { - var attrs = p.GetCustomAttributes (typeof(MaxLengthAttribute), true); + var attrs = p.GetCustomAttributes (typeof (MaxLengthAttribute), true); if (attrs.Length > 0) { - return ((MaxLengthAttribute)attrs [0]).Value; + return ((MaxLengthAttribute) attrs [0]).Value; } else { return DefaultMaxStringLength; } } } - public class SQLiteCommand - { + public class SQLiteCommand { SQLiteConnection _conn; private List<Binding> _bindings; @@ -916,7 +900,7 @@ public int ExecuteNonQuery () public List<T> ExecuteQuery<T> () where T : new() { - return ExecuteQuery<T> (_conn.GetMapping (typeof(T))); + return ExecuteQuery<T> (_conn.GetMapping (typeof (T))); } public List<T> ExecuteQuery<T> (TableMapping map) @@ -929,7 +913,7 @@ public List<T> ExecuteQuery<T> (TableMapping map) var stmt = Prepare (); - var cols = new TableMapping.Column[SQLite3.ColumnCount (stmt)]; + var cols = new TableMapping.Column [SQLite3.ColumnCount (stmt)]; for (int i = 0; i < cols.Length; i++) { var name = Marshal.PtrToStringUni (SQLite3.ColumnName16 (stmt, i)); @@ -945,7 +929,7 @@ public List<T> ExecuteQuery<T> (TableMapping map) var val = ReadCol (stmt, i, colType, cols [i].ColumnType); cols [i].SetValue (obj, val); } - r.Add ((T)obj); + r.Add ((T) obj); } Finalize (stmt); @@ -958,12 +942,12 @@ public T ExecuteScalar<T> () Console.WriteLine ("Executing Query: " + this); } - T val = default(T); + T val = default (T); var stmt = Prepare (); if (SQLite3.Step (stmt) == SQLite3.Result.Row) { var colType = SQLite3.ColumnType (stmt, 0); - val = (T)ReadCol (stmt, 0, colType, typeof(T)); + val = (T) ReadCol (stmt, 0, colType, typeof (T)); } Finalize (stmt); @@ -985,7 +969,7 @@ public void Bind (object val) public override string ToString () { - var parts = new string[1 + _bindings.Count]; + var parts = new string [1 + _bindings.Count]; parts [0] = CommandText; var i = 1; foreach (var b in _bindings) { @@ -1030,31 +1014,30 @@ internal static void BindParameter (IntPtr stmt, int index, object value) SQLite3.BindNull (stmt, index); } else { if (value is Int32) { - SQLite3.BindInt (stmt, index, (int)value); + SQLite3.BindInt (stmt, index, (int) value); } else if (value is String) { - SQLite3.BindText (stmt, index, (string)value, -1, NegativePointer); + SQLite3.BindText (stmt, index, (string) value, -1, NegativePointer); } else if (value is Byte || value is UInt16 || value is SByte || value is Int16) { SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); } else if (value is Boolean) { - SQLite3.BindInt (stmt, index, (bool)value ? 1 : 0); + SQLite3.BindInt (stmt, index, (bool) value ? 1 : 0); } else if (value is UInt32 || value is Int64) { SQLite3.BindInt64 (stmt, index, Convert.ToInt64 (value)); } else if (value is Single || value is Double || value is Decimal) { SQLite3.BindDouble (stmt, index, Convert.ToDouble (value)); } else if (value is DateTime) { - SQLite3.BindText (stmt, index, ((DateTime)value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); + SQLite3.BindText (stmt, index, ((DateTime) value).ToString ("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer); } else if (value.GetType ().IsEnum) { SQLite3.BindInt (stmt, index, Convert.ToInt32 (value)); - } else if (value is byte[]) { - SQLite3.BindBlob (stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer); + } else if (value is byte []) { + SQLite3.BindBlob (stmt, index, (byte []) value, ((byte []) value).Length, NegativePointer); } else { throw new NotSupportedException ("Cannot store type: " + value.GetType ()); } } } - class Binding - { + class Binding { public string Name { get; set; } public object Value { get; set; } @@ -1067,36 +1050,36 @@ object ReadCol (IntPtr stmt, int index, SQLite3.ColType type, Type clrType) if (type == SQLite3.ColType.Null) { return null; } else { - if (clrType == typeof(String)) { + if (clrType == typeof (String)) { return SQLite3.ColumnString (stmt, index); - } else if (clrType == typeof(Int32)) { - return (int)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Boolean)) { + } else if (clrType == typeof (Int32)) { + return (int) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (Boolean)) { return SQLite3.ColumnInt (stmt, index) == 1; - } else if (clrType == typeof(double)) { + } else if (clrType == typeof (double)) { return SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(float)) { - return (float)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(DateTime)) { + } else if (clrType == typeof (float)) { + return (float) SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof (DateTime)) { var text = SQLite3.ColumnString (stmt, index); return DateTime.Parse (text); } else if (clrType.IsEnum) { return SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int64)) { + } else if (clrType == typeof (Int64)) { return SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(UInt32)) { - return (uint)SQLite3.ColumnInt64 (stmt, index); - } else if (clrType == typeof(decimal)) { - return (decimal)SQLite3.ColumnDouble (stmt, index); - } else if (clrType == typeof(Byte)) { - return (byte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(UInt16)) { - return (ushort)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(Int16)) { - return (short)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(sbyte)) { - return (sbyte)SQLite3.ColumnInt (stmt, index); - } else if (clrType == typeof(byte[])) { + } else if (clrType == typeof (UInt32)) { + return (uint) SQLite3.ColumnInt64 (stmt, index); + } else if (clrType == typeof (decimal)) { + return (decimal) SQLite3.ColumnDouble (stmt, index); + } else if (clrType == typeof (Byte)) { + return (byte) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (UInt16)) { + return (ushort) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (Int16)) { + return (short) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (sbyte)) { + return (sbyte) SQLite3.ColumnInt (stmt, index); + } else if (clrType == typeof (byte [])) { return SQLite3.ColumnByteArray (stmt, index); } else { throw new NotSupportedException ("Don't know how to read " + clrType); @@ -1108,8 +1091,7 @@ object ReadCol (IntPtr stmt, int index, SQLite3.ColType type, Type clrType) /// <summary> /// Since the insert never changed, we only need to prepare once. /// </summary> - public class PreparedSqlLiteInsertCommand : IDisposable - { + public class PreparedSqlLiteInsertCommand : IDisposable { public bool Initialized { get; set; } protected SQLiteConnection Connection { get; set; } @@ -1123,7 +1105,7 @@ internal PreparedSqlLiteInsertCommand (SQLiteConnection conn) Connection = conn; } - public int ExecuteNonQuery (object[] source) + public int ExecuteNonQuery (object [] source) { if (Connection.Trace) { Console.WriteLine ("Executing: " + CommandText); @@ -1188,8 +1170,7 @@ private void Dispose (bool disposing) } } - public class TableQuery<T> : IEnumerable<T> where T : new() - { + public class TableQuery<T> : IEnumerable<T> where T : new() { public SQLiteConnection Connection { get; private set; } public TableMapping Table { get; private set; } @@ -1199,8 +1180,7 @@ private void Dispose (bool disposing) int? _limit; int? _offset; - class Ordering - { + class Ordering { public string ColumnName { get; set; } public bool Ascending { get; set; } @@ -1215,7 +1195,7 @@ class Ordering public TableQuery (SQLiteConnection conn) { Connection = conn; - Table = Connection.GetMapping (typeof(T)); + Table = Connection.GetMapping (typeof (T)); } public TableQuery<T> Clone () @@ -1233,7 +1213,7 @@ public TableQuery<T> Clone () public TableQuery<T> Where (Expression<Func<T, bool>> predExpr) { if (predExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)predExpr; + var lambda = (LambdaExpression) predExpr; var pred = lambda.Body; var q = Clone (); q.AddWhere (pred); @@ -1270,7 +1250,7 @@ public TableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr) private TableQuery<T> AddOrderBy<U> (Expression<Func<T, U>> orderExpr, bool asc) { if (orderExpr.NodeType == ExpressionType.Lambda) { - var lambda = (LambdaExpression)orderExpr; + var lambda = (LambdaExpression) orderExpr; var mem = lambda.Body as MemberExpression; if (mem != null && (mem.Expression.NodeType == ExpressionType.Parameter)) { var q = Clone (); @@ -1323,8 +1303,7 @@ private SQLiteCommand GenerateCommand (string selectionList) return Connection.CreateCommand (cmdText, args.ToArray ()); } - class CompileResult - { + class CompileResult { public string CommandText { get; set; } public object Value { get; set; } @@ -1335,7 +1314,7 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) if (expr == null) { throw new NotSupportedException ("Expression is NULL"); } else if (expr is BinaryExpression) { - var bin = (BinaryExpression)expr; + var bin = (BinaryExpression) expr; var leftr = CompileExpr (bin.Left, queryArgs); var rightr = CompileExpr (bin.Right, queryArgs); @@ -1343,16 +1322,16 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) //If either side is a parameter and is null, then handle the other side specially (for "is null"/"is not null") string text; if (leftr.CommandText == "?" && leftr.Value == null) - text = CompileNullBinaryExpression(bin, rightr); + text = CompileNullBinaryExpression (bin, rightr); else if (rightr.CommandText == "?" && rightr.Value == null) - text = CompileNullBinaryExpression(bin, leftr); + text = CompileNullBinaryExpression (bin, leftr); else - text = "(" + leftr.CommandText + " " + GetSqlName(bin) + " " + rightr.CommandText + ")"; + text = "(" + leftr.CommandText + " " + GetSqlName (bin) + " " + rightr.CommandText + ")"; return new CompileResult { CommandText = text }; } else if (expr.NodeType == ExpressionType.Call) { - var call = (MethodCallExpression)expr; - var args = new CompileResult[call.Arguments.Count]; + var call = (MethodCallExpression) expr; + var args = new CompileResult [call.Arguments.Count]; for (var i = 0; i < args.Length; i++) { args [i] = CompileExpr (call.Arguments [i], queryArgs); @@ -1370,14 +1349,14 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) return new CompileResult { CommandText = sqlCall }; } else if (expr.NodeType == ExpressionType.Constant) { - var c = (ConstantExpression)expr; + var c = (ConstantExpression) expr; queryArgs.Add (c.Value); return new CompileResult { CommandText = "?", Value = c.Value }; } else if (expr.NodeType == ExpressionType.Convert) { - var u = (UnaryExpression)expr; + var u = (UnaryExpression) expr; var ty = u.Type; var valr = CompileExpr (u.Operand, queryArgs); return new CompileResult { @@ -1385,7 +1364,7 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) Value = valr.Value != null ? Convert.ChangeType (valr.Value, ty) : null }; } else if (expr.NodeType == ExpressionType.MemberAccess) { - var mem = (MemberExpression)expr; + var mem = (MemberExpression) expr; if (mem.Expression.NodeType == ExpressionType.Parameter) { // @@ -1411,10 +1390,10 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) object val = null; if (mem.Member.MemberType == MemberTypes.Property) { - var m = (PropertyInfo)mem.Member; + var m = (PropertyInfo) mem.Member; val = m.GetValue (obj, null); } else if (mem.Member.MemberType == MemberTypes.Field) { - var m = (FieldInfo)mem.Member; + var m = (FieldInfo) mem.Member; val = m.GetValue (obj); } else { throw new NotSupportedException ("MemberExpr: " + mem.Member.MemberType.ToString ()); @@ -1424,22 +1403,21 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) // Work special magic for enumerables // if (val != null && val is System.Collections.IEnumerable && !(val is string)) { - var sb = new System.Text.StringBuilder(); - sb.Append("("); + var sb = new System.Text.StringBuilder (); + sb.Append ("("); var head = ""; - foreach (var a in (System.Collections.IEnumerable)val) { - queryArgs.Add(a); - sb.Append(head); - sb.Append("?"); + foreach (var a in (System.Collections.IEnumerable) val) { + queryArgs.Add (a); + sb.Append (head); + sb.Append ("?"); head = ","; } - sb.Append(")"); + sb.Append (")"); return new CompileResult { - CommandText = sb.ToString(), + CommandText = sb.ToString (), Value = val }; - } - else { + } else { queryArgs.Add (val); return new CompileResult { CommandText = "?", @@ -1455,21 +1433,22 @@ private CompileResult CompileExpr (Expression expr, List<object> queryArgs) /// Compiles a BinaryExpression where one of the parameters is null. /// </summary> /// <param name="parameter">The non-null parameter</param> - private string CompileNullBinaryExpression(BinaryExpression expression, CompileResult parameter) + private string CompileNullBinaryExpression (BinaryExpression expression, CompileResult parameter) { if (expression.NodeType == ExpressionType.Equal) return "(" + parameter.CommandText + " is ?)"; else if (expression.NodeType == ExpressionType.NotEqual) return "(" + parameter.CommandText + " is not ?)"; else - throw new NotSupportedException("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString()); + throw new NotSupportedException ("Cannot compile Null-BinaryExpression with type " + expression.NodeType.ToString ()); } string GetSqlName (Expression expr) { var n = expr.NodeType; if (n == ExpressionType.GreaterThan) - return ">"; else if (n == ExpressionType.GreaterThanOrEqual) { + return ">"; + else if (n == ExpressionType.GreaterThanOrEqual) { return ">="; } else if (n == ExpressionType.LessThan) { return "<"; @@ -1494,7 +1473,7 @@ string GetSqlName (Expression expr) public int Count () { - return GenerateCommand("count(*)").ExecuteScalar<int> (); + return GenerateCommand ("count(*)").ExecuteScalar<int> (); } public IEnumerator<T> GetEnumerator () @@ -1508,10 +1487,8 @@ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () } } - public static class SQLite3 - { - public enum Result : int - { + public static class SQLite3 { + public enum Result : int { OK = 0, Error = 1, Internal = 2, @@ -1531,29 +1508,28 @@ public enum Result : int Done = 101 } - public enum ConfigOption : int - { + public enum ConfigOption : int { SingleThread = 1, MultiThread = 2, Serialized = 3 } - [DllImport("sqlite3", EntryPoint = "sqlite3_open")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_open")] public static extern Result Open (string filename, out IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_close")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_close")] public static extern Result Close (IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_config")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_config")] public static extern Result Config (ConfigOption option); - [DllImport("sqlite3", EntryPoint = "sqlite3_busy_timeout")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_busy_timeout")] public static extern Result BusyTimeout (IntPtr db, int milliseconds); - [DllImport("sqlite3", EntryPoint = "sqlite3_changes")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_changes")] public static extern int Changes (IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_prepare_v2")] public static extern Result Prepare2 (IntPtr db, string sql, int numBytes, out IntPtr stmt, IntPtr pzTail); public static IntPtr Prepare2 (IntPtr db, string query) @@ -1566,19 +1542,19 @@ public static IntPtr Prepare2 (IntPtr db, string query) return stmt; } - [DllImport("sqlite3", EntryPoint = "sqlite3_step")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_step")] public static extern Result Step (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_reset")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_reset")] public static extern Result Reset (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_finalize")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_finalize")] public static extern Result Finalize (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_last_insert_rowid")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_last_insert_rowid")] public static extern long LastInsertRowid (IntPtr db); - [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg16")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_errmsg16")] public static extern IntPtr Errmsg (IntPtr db); public static string GetErrmsg (IntPtr db) @@ -1586,58 +1562,58 @@ public static string GetErrmsg (IntPtr db) return Marshal.PtrToStringUni (Errmsg (db)); } - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_parameter_index")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_parameter_index")] public static extern int BindParameterIndex (IntPtr stmt, string name); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_null")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_null")] public static extern int BindNull (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_int")] public static extern int BindInt (IntPtr stmt, int index, int val); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_int64")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_int64")] public static extern int BindInt64 (IntPtr stmt, int index, long val); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_double")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_double")] public static extern int BindDouble (IntPtr stmt, int index, double val); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_text")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_text")] public static extern int BindText (IntPtr stmt, int index, string val, int n, IntPtr free); - [DllImport("sqlite3", EntryPoint = "sqlite3_bind_blob")] - public static extern int BindBlob (IntPtr stmt, int index, byte[] val, int n, IntPtr free); + [DllImport ("sqlite3", EntryPoint = "sqlite3_bind_blob")] + public static extern int BindBlob (IntPtr stmt, int index, byte [] val, int n, IntPtr free); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_count")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_count")] public static extern int ColumnCount (IntPtr stmt); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_name")] public static extern IntPtr ColumnName (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_name16")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_name16")] public static extern IntPtr ColumnName16 (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_type")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_type")] public static extern ColType ColumnType (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_int")] public static extern int ColumnInt (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_int64")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_int64")] public static extern long ColumnInt64 (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_double")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_double")] public static extern double ColumnDouble (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_text")] public static extern IntPtr ColumnText (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_text16")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_text16")] public static extern IntPtr ColumnText16 (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_blob")] public static extern IntPtr ColumnBlob (IntPtr stmt, int index); - [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes")] + [DllImport ("sqlite3", EntryPoint = "sqlite3_column_bytes")] public static extern int ColumnBytes (IntPtr stmt, int index); public static string ColumnString (IntPtr stmt, int index) @@ -1645,17 +1621,16 @@ public static string ColumnString (IntPtr stmt, int index) return Marshal.PtrToStringUni (SQLite3.ColumnText16 (stmt, index)); } - public static byte[] ColumnByteArray (IntPtr stmt, int index) + public static byte [] ColumnByteArray (IntPtr stmt, int index) { int length = ColumnBytes (stmt, index); - byte[] result = new byte[length]; + byte [] result = new byte [length]; if (length > 0) Marshal.Copy (ColumnBlob (stmt, index), result, 0, length); return result; } - public enum ColType : int - { + public enum ColType : int { Integer = 1, Float = 2, Text = 3, diff --git a/WeatherMap/WeatherAnnotationView.cs b/WeatherMap/WeatherAnnotationView.cs index 2b6a2416e..b1586d6c6 100644 --- a/WeatherMap/WeatherAnnotationView.cs +++ b/WeatherMap/WeatherAnnotationView.cs @@ -31,10 +31,8 @@ using MapKit; using Foundation; -namespace WeatherMap -{ - public class WeatherAnnotationView : MKAnnotationView - { +namespace WeatherMap { + public class WeatherAnnotationView : MKAnnotationView { public WeatherAnnotationView (IMKAnnotation annotation, string reuseIdentifier) : base (annotation, reuseIdentifier) { CGRect frame = Frame; @@ -96,7 +94,7 @@ public override void Draw (CGRect rect) // Draw the icon for the weather condition string imageName = string.Format ("WeatherMap.WeatherIcons.{0}.png", forecast.Condition); - UIImage image = UIImage.FromResource (typeof(WeatherAnnotationView).Assembly, imageName); + UIImage image = UIImage.FromResource (typeof (WeatherAnnotationView).Assembly, imageName); image.Draw (new CGRect (12.5f, 28.0f, 45.0f, 45.0f)); image.Dispose (); } diff --git a/WeatherMap/WeatherConditions.cs b/WeatherMap/WeatherConditions.cs index 5773e6536..3285a80a9 100644 --- a/WeatherMap/WeatherConditions.cs +++ b/WeatherMap/WeatherConditions.cs @@ -26,8 +26,7 @@ using System; -namespace WeatherMap -{ +namespace WeatherMap { public enum WeatherConditions { Sunny, PartlyCloudy, diff --git a/WeatherMap/WeatherForecast.cs b/WeatherMap/WeatherForecast.cs index 411a2fe86..1d69021ea 100644 --- a/WeatherMap/WeatherForecast.cs +++ b/WeatherMap/WeatherForecast.cs @@ -26,10 +26,8 @@ using System; -namespace WeatherMap -{ - public class WeatherForecast - { +namespace WeatherMap { + public class WeatherForecast { public WeatherForecast () { } diff --git a/WeatherMap/WeatherForecastAnnotation.cs b/WeatherMap/WeatherForecastAnnotation.cs index 1c64bb6c4..dc46c75f1 100644 --- a/WeatherMap/WeatherForecastAnnotation.cs +++ b/WeatherMap/WeatherForecastAnnotation.cs @@ -29,10 +29,8 @@ using CoreLocation; using MapKit; -namespace WeatherMap -{ - public class WeatherForecastAnnotation : MKAnnotation - { +namespace WeatherMap { + public class WeatherForecastAnnotation : MKAnnotation { public WeatherForecastAnnotation (WeatherForecast forecast) { Forecast = forecast; diff --git a/WeatherMap/WeatherMapViewController.cs b/WeatherMap/WeatherMapViewController.cs index fc17d591c..6338fd141 100644 --- a/WeatherMap/WeatherMapViewController.cs +++ b/WeatherMap/WeatherMapViewController.cs @@ -31,11 +31,9 @@ using Foundation; using CoreLocation; -namespace WeatherMap -{ - public partial class WeatherMapViewController : UIViewController - { - WeatherForecastAnnotation[] annotations; +namespace WeatherMap { + public partial class WeatherMapViewController : UIViewController { + WeatherForecastAnnotation [] annotations; WeatherServer weatherServer; public WeatherMapViewController (string nibName, NSBundle bundle) : base (nibName, bundle) @@ -99,8 +97,8 @@ public override void ViewDidUnload () // e.g. myOutlet = null; if (annotations != null) { for (int i = 0; i < annotations.Length; i++) { - annotations[i].Dispose (); - annotations[i] = null; + annotations [i].Dispose (); + annotations [i] = null; } annotations = null; diff --git a/WeatherMap/WeatherServer.cs b/WeatherMap/WeatherServer.cs index 25c5d15ae..455bc05b8 100644 --- a/WeatherMap/WeatherServer.cs +++ b/WeatherMap/WeatherServer.cs @@ -30,10 +30,8 @@ using MapKit; using SQLite; -namespace WeatherMap -{ - public class WeatherServer : IDisposable - { +namespace WeatherMap { + public class WeatherServer : IDisposable { SQLiteConnection store; public WeatherServer () @@ -105,7 +103,7 @@ public WeatherServer () } } - public WeatherForecastAnnotation[] GetForecastAnnotations (MKCoordinateRegion region, int maxCount) + public WeatherForecastAnnotation [] GetForecastAnnotations (MKCoordinateRegion region, int maxCount) { double longMin = region.Center.Longitude - region.Span.LongitudeDelta / 2.0; double longMax = region.Center.Longitude + region.Span.LongitudeDelta / 2.0; @@ -114,10 +112,10 @@ public WeatherForecastAnnotation[] GetForecastAnnotations (MKCoordinateRegion re // Query for WeatherForecasts within our specified region var results = from item in store.Table<WeatherForecast> () - where (item.Latitude > latMin && item.Latitude < latMax && item.Longitude > longMin && item.Longitude < longMax) - orderby item.Latitude - orderby item.Longitude - select item; + where (item.Latitude > latMin && item.Latitude < latMax && item.Longitude > longMin && item.Longitude < longMax) + orderby item.Latitude + orderby item.Longitude + select item; // Iterate over the results and add them to a list var list = new List<WeatherForecastAnnotation> (); @@ -134,7 +132,7 @@ orderby item.Longitude var annotations = new WeatherForecastAnnotation [maxCount]; for (int i = 0; i < maxCount && (int) index < list.Count; i++, index += stride) - annotations[i] = list[(int) index]; + annotations [i] = list [(int) index]; return annotations; } diff --git a/WebView/WebView/AppDelegate.cs b/WebView/WebView/AppDelegate.cs index da509b065..7c7bb3900 100644 --- a/WebView/WebView/AppDelegate.cs +++ b/WebView/WebView/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace WebView -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } - } -} \ No newline at end of file +namespace WebView { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } + } +} diff --git a/WebView/WebView/Main.cs b/WebView/WebView/Main.cs index 2648b1d9a..03c2fd197 100644 --- a/WebView/WebView/Main.cs +++ b/WebView/WebView/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace WebView -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace WebView { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/WebView/WebView/ViewController.cs b/WebView/WebView/ViewController.cs index 1240ec462..19c117b19 100644 --- a/WebView/WebView/ViewController.cs +++ b/WebView/WebView/ViewController.cs @@ -1,34 +1,32 @@ -using Foundation; +using Foundation; using SafariServices; using System; using UIKit; using WebKit; -namespace WebView -{ - public partial class ViewController : UIViewController - { - private readonly NSUrl url = new NSUrl("https://visualstudio.microsoft.com/xamarin/"); +namespace WebView { + public partial class ViewController : UIViewController { + private readonly NSUrl url = new NSUrl ("https://visualstudio.microsoft.com/xamarin/"); - protected ViewController(IntPtr handle) : base(handle) { } + protected ViewController (IntPtr handle) : base (handle) { } - partial void OpenWebView(UIButton sender) - { - var webView = new WKWebView(View.Frame, new WKWebViewConfiguration()); - View.AddSubview(webView); + partial void OpenWebView (UIButton sender) + { + var webView = new WKWebView (View.Frame, new WKWebViewConfiguration ()); + View.AddSubview (webView); - webView.LoadRequest(new NSUrlRequest(url)); - } + webView.LoadRequest (new NSUrlRequest (url)); + } - partial void OpenSafari(UIButton sender) - { - UIApplication.SharedApplication.OpenUrl(url); - } + partial void OpenSafari (UIButton sender) + { + UIApplication.SharedApplication.OpenUrl (url); + } - partial void OpenSafariViewController(UIButton sender) - { - var viewController = new SFSafariViewController(url); - PresentViewController(viewController, true, null); - } - } -} \ No newline at end of file + partial void OpenSafariViewController (UIButton sender) + { + var viewController = new SFSafariViewController (url); + PresentViewController (viewController, true, null); + } + } +} diff --git a/WorkingWithImages/AppDelegate.cs b/WorkingWithImages/AppDelegate.cs index 3cec50ee7..e4285be14 100644 --- a/WorkingWithImages/AppDelegate.cs +++ b/WorkingWithImages/AppDelegate.cs @@ -1,43 +1,41 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace WorkingWithImages -{ +namespace WorkingWithImages { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/WorkingWithImages/FirstViewController.cs b/WorkingWithImages/FirstViewController.cs index 61b03ffe3..d8b33f42d 100644 --- a/WorkingWithImages/FirstViewController.cs +++ b/WorkingWithImages/FirstViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace WorkingWithImages -{ - public partial class FirstViewController : UIViewController - { +namespace WorkingWithImages { + public partial class FirstViewController : UIViewController { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } @@ -22,7 +20,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -31,7 +29,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Set image in code // MonkeyImage.Image = UIImage.FromFile ("Images/Red/RedMonkey.png"); // MonkeyImage.Image = UIImage.FromBundle ("PurpleMonkey"); diff --git a/WorkingWithImages/Main.cs b/WorkingWithImages/Main.cs index 7bbd3a7c9..eef5342d7 100644 --- a/WorkingWithImages/Main.cs +++ b/WorkingWithImages/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace WorkingWithImages -{ - public class Application - { +namespace WorkingWithImages { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WorkingWithImages/SecondViewController.cs b/WorkingWithImages/SecondViewController.cs index 4cf20ef14..1cbd0b46d 100644 --- a/WorkingWithImages/SecondViewController.cs +++ b/WorkingWithImages/SecondViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace WorkingWithImages -{ - public partial class SecondViewController : UIViewController - { +namespace WorkingWithImages { + public partial class SecondViewController : UIViewController { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } @@ -22,7 +20,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -31,7 +29,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/AppDelegate.cs b/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/AppDelegate.cs index 201f35223..63ef72c8c 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/AppDelegate.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,26 +13,25 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected HomeScreen iPhoneHome; - + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + + iPhoneHome = new HomeScreen (); + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - + window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/HomeScreen.cs b/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/HomeScreen.cs index 6a70862bf..d23d0fab8 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/HomeScreen.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/HomeScreen.cs @@ -8,7 +8,7 @@ public class HomeScreen : UIViewController { UITableView table; public HomeScreen () - { + { } public override void ViewDidLoad () @@ -17,9 +17,9 @@ public override void ViewDidLoad () var width = View.Bounds.Width; var height = View.Bounds.Height; - table = new UITableView(new CGRect(0, 0, width, height)); + table = new UITableView (new CGRect (0, 0, width, height)); table.AutoresizingMask = UIViewAutoresizing.All; - CreateTableItems(); + CreateTableItems (); Add (table); } @@ -32,7 +32,7 @@ protected void CreateTableItems () tableItems.Add ("Legumes"); tableItems.Add ("Bulbs"); tableItems.Add ("Tubers"); - table.Source = new TableSource(tableItems.ToArray(), this); + table.Source = new TableSource (tableItems.ToArray (), this); } public override bool PrefersStatusBarHidden () @@ -40,4 +40,4 @@ public override bool PrefersStatusBarHidden () return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/TableSource.cs b/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/TableSource.cs index 86e439108..2e3d14440 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/TableSource.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/1 - BasicTable/TableSource.cs @@ -6,18 +6,18 @@ namespace BasicTable { public class TableSource : UITableViewSource { - - protected string[] tableItems; + + protected string [] tableItems; protected string cellIdentifier = "TableCell"; HomeScreen owner; - public TableSource (string[] items, HomeScreen owner) + public TableSource (string [] items, HomeScreen owner) { tableItems = items; this.owner = owner; } - + /// <summary> /// Called by the TableView to determine how many sections(groups) there are. /// </summary> @@ -33,40 +33,39 @@ public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Length; } - + /// <summary> /// Called when a row is touched /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems[indexPath.Row], UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems [indexPath.Row], UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); - string item = tableItems[indexPath.Row]; - + string item = tableItems [indexPath.Row]; + //---- if there are no cells to reuse, create a new one - if (cell == null) - { cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier); } - + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier); } + cell.TextLabel.Text = item; - + return cell; } - -// public override string TitleForHeader (UITableView tableView, nint section) -// { -// return " "; -// } - + + // public override string TitleForHeader (UITableView tableView, nint section) + // { + // return " "; + // } + } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/AppDelegate.cs b/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/AppDelegate.cs index 201f35223..63ef72c8c 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/AppDelegate.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,26 +13,25 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected HomeScreen iPhoneHome; - + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + + iPhoneHome = new HomeScreen (); + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - + window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/HomeScreen.cs b/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/HomeScreen.cs index a08a03dfc..67011d8a4 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/HomeScreen.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/HomeScreen.cs @@ -10,28 +10,28 @@ public class HomeScreen : UIViewController { UITableView table; public HomeScreen () - { + { } public override void ViewDidLoad () { base.ViewDidLoad (); - table = new UITableView(View.Bounds); // defaults to Plain style + table = new UITableView (View.Bounds); // defaults to Plain style table.AutoresizingMask = UIViewAutoresizing.All; - + // Credit for test data to // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - var lines = File.ReadLines("VegeData.txt"); - List<string> veges = new List<string>(); + var lines = File.ReadLines ("VegeData.txt"); + List<string> veges = new List<string> (); foreach (var l in lines) { veges.Add (l); } - veges.Sort ((x,y) => {return x.CompareTo (y);}); - string[] tableItems = veges.ToArray(); + veges.Sort ((x, y) => { return x.CompareTo (y); }); + string [] tableItems = veges.ToArray (); - table.Source = new TableSource(tableItems,this); + table.Source = new TableSource (tableItems, this); Add (table); } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/TableSource.cs b/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/TableSource.cs index 43c7792de..9459797e2 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/TableSource.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/2 - BasicTableIndex/TableSource.cs @@ -10,24 +10,24 @@ public class TableSource : UITableViewSource { string cellIdentifier = "TableCell"; Dictionary<string, List<string>> indexedTableItems; - string[] keys; + string [] keys; HomeScreen owner; - public TableSource (string[] items, HomeScreen owner) + public TableSource (string [] items, HomeScreen owner) { this.owner = owner; - indexedTableItems = new Dictionary<string, List<string>>(); + indexedTableItems = new Dictionary<string, List<string>> (); foreach (var t in items) { - if (indexedTableItems.ContainsKey (t[0].ToString ())) { - indexedTableItems[t[0].ToString ()].Add(t); + if (indexedTableItems.ContainsKey (t [0].ToString ())) { + indexedTableItems [t [0].ToString ()].Add (t); } else { - indexedTableItems.Add (t[0].ToString (), new List<string>() {t}); + indexedTableItems.Add (t [0].ToString (), new List<string> () { t }); } } keys = indexedTableItems.Keys.ToArray (); } - + /// <summary> /// Called by the TableView to determine how many sections(groups) there are. /// </summary> @@ -41,13 +41,13 @@ public override nint NumberOfSections (UITableView tableView) /// </summary> public override nint RowsInSection (UITableView tableview, nint section) { - return indexedTableItems[keys[section]].Count; + return indexedTableItems [keys [section]].Count; } - + /// <summary> /// Sections the index titles. /// </summary> - public override String[] SectionIndexTitles (UITableView tableView) + public override String [] SectionIndexTitles (UITableView tableView) { return indexedTableItems.Keys.ToArray (); } @@ -57,12 +57,12 @@ public override String[] SectionIndexTitles (UITableView tableView) /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - UIAlertController okAlertController = UIAlertController.Create ("Row Selected", indexedTableItems[keys[indexPath.Section]][indexPath.Row], UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + UIAlertController okAlertController = UIAlertController.Create ("Row Selected", indexedTableItems [keys [indexPath.Section]] [indexPath.Row], UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> @@ -73,10 +73,10 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde // if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Default, cellIdentifier); - - cell.TextLabel.Text = indexedTableItems[keys[indexPath.Section]][indexPath.Row]; - + + cell.TextLabel.Text = indexedTableItems [keys [indexPath.Section]] [indexPath.Row]; + return cell; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/AppDelegate.cs b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/AppDelegate.cs index 6ac9122c6..e036ec894 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/AppDelegate.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/AppDelegate.cs @@ -3,26 +3,25 @@ using Foundation; namespace BasicTable { - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected HomeScreen iPhoneHome; - + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + + iPhoneHome = new HomeScreen (); + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - + window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Application.cs b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Application.cs index 8ad7f02af..f61719e48 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Application.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Application.cs @@ -1,18 +1,14 @@ using System; using UIKit; -namespace Example_EditableTable -{ +namespace Example_EditableTable { public class Application// : UIApplication { - public static void Main (string[] args) + public static void Main (string [] args) { - try - { + try { UIApplication.Main (args, null, "AppDelegate"); - } - catch (Exception e) - { + } catch (Exception e) { Console.WriteLine (e.ToString ()); } } diff --git a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItem.cs b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItem.cs index 79e97b6b5..bc1a80fd0 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItem.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItem.cs @@ -4,28 +4,26 @@ namespace BasicTable { public class TableItem { public string Heading { get; set; } - + public string SubHeading { get; set; } - + public string ImageName { get; set; } - - public UITableViewCellStyle CellStyle - { + + public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; - - public UITableViewCellAccessory CellAccessory - { + + public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItem () { } - + public TableItem (string heading) { Heading = heading; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItemGroup.cs b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItemGroup.cs index a6aa2434c..10aadf863 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItemGroup.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableItemGroup.cs @@ -8,14 +8,13 @@ namespace BasicTable { /// </summary> public class TableItemGroup { public string Name { get; set; } - + public string Footer { get; set; } - - public List<TableItem> Items - { + + public List<TableItem> Items { get { return items; } set { items = value; } } protected List<TableItem> items = new List<TableItem> (); } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableSource.cs b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableSource.cs index f5e6e140b..7bcc1685b 100755 --- a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableSource.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Code/TableSource.cs @@ -8,26 +8,26 @@ namespace BasicTable { public class TableSource : UITableViewSource { protected string cellIdentifier = "TableCell"; - + Dictionary<string, List<TableItem>> indexedTableItems; - string[] keys; + string [] keys; HomeScreen owner; public TableSource (List<TableItem> items, HomeScreen owner) { this.owner = owner; - indexedTableItems = new Dictionary<string, List<TableItem>>(); + indexedTableItems = new Dictionary<string, List<TableItem>> (); foreach (var t in items) { if (indexedTableItems.ContainsKey (t.SubHeading)) { - indexedTableItems[t.SubHeading].Add(t); + indexedTableItems [t.SubHeading].Add (t); } else { - indexedTableItems.Add (t.SubHeading, new List<TableItem>() {t}); + indexedTableItems.Add (t.SubHeading, new List<TableItem> () { t }); } } keys = indexedTableItems.Keys.ToArray (); } - + /// <summary> /// Called by the TableView to determine how many sections(groups) there are. /// </summary> @@ -41,43 +41,43 @@ public override nint NumberOfSections (UITableView tableView) /// </summary> public override nint RowsInSection (UITableView tableview, nint section) { - return indexedTableItems[keys[section]].Count; + return indexedTableItems [keys [section]].Count; } - + /// <summary> /// Sections the index titles. /// </summary> -// public override string[] SectionIndexTitles (UITableView tableView) -// { -// return indexedTableItems.Keys.ToArray (); -// } - + // public override string[] SectionIndexTitles (UITableView tableView) + // { + // return indexedTableItems.Keys.ToArray (); + // } + /// <summary> /// The string to show in the section header /// </summary> public override string TitleForHeader (UITableView tableView, nint section) { - return keys[section]; + return keys [section]; } - + /// <summary> /// The string to show in the section footer /// </summary> public override string TitleForFooter (UITableView tableView, nint section) { - return indexedTableItems[keys[section]].Count + " items"; + return indexedTableItems [keys [section]].Count + " items"; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - UIAlertController okAlertController = UIAlertController.Create ("Row Selected", indexedTableItems[keys[indexPath.Section]][indexPath.Row].Heading, UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + UIAlertController okAlertController = UIAlertController.Create ("Row Selected", indexedTableItems [keys [indexPath.Section]] [indexPath.Row].Heading, UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); } - - + + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular section and row /// </summary> @@ -85,26 +85,23 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde { //---- declare vars UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); - TableItem item = indexedTableItems[keys[indexPath.Section]][indexPath.Row]; - + TableItem item = indexedTableItems [keys [indexPath.Section]] [indexPath.Row]; + //---- if there are no cells to reuse, create a new one - if (cell == null) - { cell = new UITableViewCell (item.CellStyle, cellIdentifier); } - + if (cell == null) { cell = new UITableViewCell (item.CellStyle, cellIdentifier); } + //---- set the item text cell.TextLabel.Text = item.Heading; - + //---- if the item has a valid image, and it's not the contact style (doesn't support images) - if(!string.IsNullOrEmpty(item.ImageName) && item.CellStyle != UITableViewCellStyle.Value2) - { - if(File.Exists(item.ImageName)) - { cell.ImageView.Image = UIImage.FromBundle(item.ImageName); } + if (!string.IsNullOrEmpty (item.ImageName) && item.CellStyle != UITableViewCellStyle.Value2) { + if (File.Exists (item.ImageName)) { cell.ImageView.Image = UIImage.FromBundle (item.ImageName); } } - + //---- set the accessory cell.Accessory = item.CellAccessory; - + return cell; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Screens/HomeScreen.cs b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Screens/HomeScreen.cs index 9bba0603e..49b0db26e 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Screens/HomeScreen.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/3 - BasicTableHeaderFooter/Screens/HomeScreen.cs @@ -10,7 +10,7 @@ public class HomeScreen : UIViewController { public HomeScreen () { - + } public override void ViewDidLoad () @@ -18,23 +18,23 @@ public override void ViewDidLoad () base.ViewDidLoad (); table = new UITableView (View.Bounds, UITableViewStyle.Grouped); table.AutoresizingMask = UIViewAutoresizing.All; - CreateTableItems(); + CreateTableItems (); Add (table); } protected void CreateTableItems () { - List<TableItem> veges = new List<TableItem>(); - + List<TableItem> veges = new List<TableItem> (); + // Credit for test data to // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - var lines = File.ReadLines("VegeData2.txt"); + var lines = File.ReadLines ("VegeData2.txt"); foreach (var line in lines) { - var vege = line.Split(','); - veges.Add (new TableItem(vege[1]) {SubHeading=vege[0]} ); + var vege = line.Split (','); + veges.Add (new TableItem (vege [1]) { SubHeading = vege [0] }); } - table.Source = new TableSource(veges, this); + table.Source = new TableSource (veges, this); } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/AppDelegate.cs b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/AppDelegate.cs index eb5529223..41038fed1 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/AppDelegate.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace PopulatingATable -{ +namespace PopulatingATable { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/Main.cs b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/Main.cs index e1e1a0cd1..a8d2dabe5 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/Main.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace PopulatingATable -{ - public class Application - { +namespace PopulatingATable { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/TableSource.cs b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/TableSource.cs index 4fc60934b..cfcce6b6e 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/TableSource.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/TableSource.cs @@ -1,23 +1,20 @@ -using System; +using System; using UIKit; using Foundation; -namespace PopulatingATable -{ - public class RowArgs : EventArgs - { +namespace PopulatingATable { + public class RowArgs : EventArgs { public string Content { get; set; } } - public class TableSource : UITableViewSource - { + public class TableSource : UITableViewSource { const string CellIdentifier = "TableCell"; public event EventHandler<RowArgs> Selected; - readonly string[] tableItems; + readonly string [] tableItems; - public TableSource (string[] items) + public TableSource (string [] items) { tableItems = items; } @@ -58,7 +55,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde // if there are no cells to reuse, create a new one cell = cell ?? new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); - cell.TextLabel.Text = tableItems[indexPath.Row]; + cell.TextLabel.Text = tableItems [indexPath.Row]; return cell; } @@ -68,4 +65,4 @@ public override string TitleForHeader (UITableView tableView, nint section) return " "; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/ViewController.cs b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/ViewController.cs index bb967341f..1bee5d11b 100644 --- a/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/ViewController.cs +++ b/WorkingWithTables/Part 2 - Populating a table with data/PopulatingATable/PopulatingATable/ViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using System.Collections.Generic; using Foundation; -namespace PopulatingATable -{ - public partial class ViewController : UIViewController - { +namespace PopulatingATable { + public partial class ViewController : UIViewController { UITableView table; TableSource source; @@ -21,13 +19,13 @@ public override void ViewDidLoad () table = new UITableView (View.Bounds); table.AutoresizingMask = UIViewAutoresizing.All; - CreateTableItems(); + CreateTableItems (); Add (table); } void CreateTableItems () { - var tableItems = new string[] { + var tableItems = new string [] { "Vegetables", "Fruits", "Flower Buds", @@ -41,10 +39,10 @@ void CreateTableItems () var alert = UIAlertController.Create ("Row Selected", e.Content, UIAlertControllerStyle.Alert); alert.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); - PresentViewController(alert, true, null); + PresentViewController (alert, true, null); }; table.Source = source; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/AppDelegate.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/AppDelegate.cs index 201f35223..63ef72c8c 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/AppDelegate.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,26 +13,25 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected HomeScreen iPhoneHome; - + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + + iPhoneHome = new HomeScreen (); + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - + window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableItem.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableItem.cs index 79e97b6b5..bc1a80fd0 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableItem.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableItem.cs @@ -4,28 +4,26 @@ namespace BasicTable { public class TableItem { public string Heading { get; set; } - + public string SubHeading { get; set; } - + public string ImageName { get; set; } - - public UITableViewCellStyle CellStyle - { + + public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; - - public UITableViewCellAccessory CellAccessory - { + + public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItem () { } - + public TableItem (string heading) { Heading = heading; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableSource.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableSource.cs index 18ad98c97..e25e67ba5 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableSource.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/Code/TableSource.cs @@ -7,16 +7,16 @@ namespace BasicTable { public class TableSource : UITableViewSource { List<TableItem> tableItems; - string cellIdentifier = "TableCell"; + string cellIdentifier = "TableCell"; HomeScreen owner; - + public TableSource (List<TableItem> items, HomeScreen owner) { tableItems = items; this.owner = owner; } - + /// <summary> /// Called by the TableView to determine how many cells to create for that particular section. /// </summary> @@ -24,21 +24,21 @@ public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Count; } - + /// <summary> /// Called when a row is touched /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - - UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems[indexPath.Row].Heading, UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + + UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems [indexPath.Row].Heading, UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> @@ -48,9 +48,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); // TODO: UNCOMMENT one of these to use that style -// var cellStyle = UITableViewCellStyle.Default; -// var cellStyle = UITableViewCellStyle.Subtitle; -// var cellStyle = UITableViewCellStyle.Value1; + // var cellStyle = UITableViewCellStyle.Default; + // var cellStyle = UITableViewCellStyle.Subtitle; + // var cellStyle = UITableViewCellStyle.Value1; var cellStyle = UITableViewCellStyle.Value2; // if there are no cells to reuse, create a new one @@ -58,20 +58,20 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde cell = new UITableViewCell (cellStyle, cellIdentifier); } - cell.TextLabel.Text = tableItems[indexPath.Row].Heading; - + cell.TextLabel.Text = tableItems [indexPath.Row].Heading; + // Default style doesn't support Subtitle - if (cellStyle == UITableViewCellStyle.Subtitle + if (cellStyle == UITableViewCellStyle.Subtitle || cellStyle == UITableViewCellStyle.Value1 || cellStyle == UITableViewCellStyle.Value2) { - cell.DetailTextLabel.Text = tableItems[indexPath.Row].SubHeading; + cell.DetailTextLabel.Text = tableItems [indexPath.Row].SubHeading; } - + // Value2 style doesn't support an image if (cellStyle != UITableViewCellStyle.Value2) - cell.ImageView.Image = UIImage.FromFile ("Images/" +tableItems[indexPath.Row].ImageName); - + cell.ImageView.Image = UIImage.FromFile ("Images/" + tableItems [indexPath.Row].ImageName); + return cell; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/HomeScreen.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/HomeScreen.cs index 6a0dd3059..6ef21d2d8 100644 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/HomeScreen.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/1 - CellDefaultTable/HomeScreen.cs @@ -8,26 +8,26 @@ public class HomeScreen : UIViewController { UITableView table; public HomeScreen () - { + { } public override void ViewDidLoad () { base.ViewDidLoad (); - table = new UITableView(View.Bounds); // defaults to Plain style + table = new UITableView (View.Bounds); // defaults to Plain style table.AutoresizingMask = UIViewAutoresizing.All; - List<TableItem> tableItems = new List<TableItem>(); - + List<TableItem> tableItems = new List<TableItem> (); + // credit for images // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - tableItems.Add (new TableItem("Vegetables") { SubHeading="65 items", ImageName="Vegetables.jpg"}); - tableItems.Add (new TableItem("Fruits") { SubHeading="17 items", ImageName="Fruits.jpg"}); - tableItems.Add (new TableItem("Flower Buds") { SubHeading="5 items", ImageName="Flower Buds.jpg"}); - tableItems.Add (new TableItem("Legumes") { SubHeading="33 items", ImageName="Legumes.jpg"}); - tableItems.Add (new TableItem("Bulbs") { SubHeading="18 items", ImageName="Bulbs.jpg"}); - tableItems.Add (new TableItem("Tubers") { SubHeading="43 items", ImageName="Tubers.jpg"}); - table.Source = new TableSource(tableItems, this); + tableItems.Add (new TableItem ("Vegetables") { SubHeading = "65 items", ImageName = "Vegetables.jpg" }); + tableItems.Add (new TableItem ("Fruits") { SubHeading = "17 items", ImageName = "Fruits.jpg" }); + tableItems.Add (new TableItem ("Flower Buds") { SubHeading = "5 items", ImageName = "Flower Buds.jpg" }); + tableItems.Add (new TableItem ("Legumes") { SubHeading = "33 items", ImageName = "Legumes.jpg" }); + tableItems.Add (new TableItem ("Bulbs") { SubHeading = "18 items", ImageName = "Bulbs.jpg" }); + tableItems.Add (new TableItem ("Tubers") { SubHeading = "43 items", ImageName = "Tubers.jpg" }); + table.Source = new TableSource (tableItems, this); Add (table); } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/AppDelegate.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/AppDelegate.cs index 201f35223..63ef72c8c 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/AppDelegate.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,26 +13,25 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected HomeScreen iPhoneHome; - + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + + iPhoneHome = new HomeScreen (); + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - + window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableItem.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableItem.cs index 79e97b6b5..bc1a80fd0 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableItem.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableItem.cs @@ -4,28 +4,26 @@ namespace BasicTable { public class TableItem { public string Heading { get; set; } - + public string SubHeading { get; set; } - + public string ImageName { get; set; } - - public UITableViewCellStyle CellStyle - { + + public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; - - public UITableViewCellAccessory CellAccessory - { + + public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItem () { } - + public TableItem (string heading) { Heading = heading; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableSource.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableSource.cs index 4e3212a0a..fa39639d8 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableSource.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/Code/TableSource.cs @@ -7,15 +7,15 @@ namespace BasicTable { public class TableSource : UITableViewSource { List<TableItem> tableItems; - string cellIdentifier = "TableCell"; + string cellIdentifier = "TableCell"; HomeScreen owner; - + public TableSource (List<TableItem> items, HomeScreen owner) { tableItems = items; this.owner = owner; } - + /// <summary> /// Called by the TableView to determine how many cells to create for that particular section. /// </summary> @@ -23,27 +23,27 @@ public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Count; } - + /// <summary> /// Called when a row is touched /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems[indexPath.Row].Heading, UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems [indexPath.Row].Heading, UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called when the DetailDisclosureButton is touched. /// Does nothing if DetailDisclosureButton isn't in the cell /// </summary> public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath) { - UIAlertController okAlertController = UIAlertController.Create ("DetailDisclosureButton Touched", tableItems[indexPath.Row].Heading, UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + UIAlertController okAlertController = UIAlertController.Create ("DetailDisclosureButton Touched", tableItems [indexPath.Row].Heading, UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); @@ -59,9 +59,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde // UNCOMMENT one of these to use that style var cellStyle = UITableViewCellStyle.Default; -// var cellStyle = UITableViewCellStyle.Subtitle; -// var cellStyle = UITableViewCellStyle.Value1; -// var cellStyle = UITableViewCellStyle.Value2; + // var cellStyle = UITableViewCellStyle.Subtitle; + // var cellStyle = UITableViewCellStyle.Value1; + // var cellStyle = UITableViewCellStyle.Value2; // if there are no cells to reuse, create a new one if (cell == null) { @@ -69,28 +69,28 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde } - + // UNCOMMENT one of these to see that accessory -// cell.Accessory = UITableViewCellAccessory.Checkmark; -// cell.Accessory = UITableViewCellAccessory.DetailButton; -// cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; -// cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton; // implement AccessoryButtonTapped + // cell.Accessory = UITableViewCellAccessory.Checkmark; + // cell.Accessory = UITableViewCellAccessory.DetailButton; + // cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; + // cell.Accessory = UITableViewCellAccessory.DetailDisclosureButton; // implement AccessoryButtonTapped cell.Accessory = UITableViewCellAccessory.None; // to clear the accessory - - cell.TextLabel.Text = tableItems[indexPath.Row].Heading; - + + cell.TextLabel.Text = tableItems [indexPath.Row].Heading; + // Default style doesn't support Subtitle - if (cellStyle == UITableViewCellStyle.Subtitle + if (cellStyle == UITableViewCellStyle.Subtitle || cellStyle == UITableViewCellStyle.Value1 || cellStyle == UITableViewCellStyle.Value2) { - cell.DetailTextLabel.Text = tableItems[indexPath.Row].SubHeading; + cell.DetailTextLabel.Text = tableItems [indexPath.Row].SubHeading; } - + // Value2 style doesn't support an image if (cellStyle != UITableViewCellStyle.Value2) - cell.ImageView.Image = UIImage.FromFile ("Images/" +tableItems[indexPath.Row].ImageName); - + cell.ImageView.Image = UIImage.FromFile ("Images/" + tableItems [indexPath.Row].ImageName); + return cell; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/HomeScreen.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/HomeScreen.cs index 6a0dd3059..6ef21d2d8 100644 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/HomeScreen.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/2 - CellAccessoryTable/HomeScreen.cs @@ -8,26 +8,26 @@ public class HomeScreen : UIViewController { UITableView table; public HomeScreen () - { + { } public override void ViewDidLoad () { base.ViewDidLoad (); - table = new UITableView(View.Bounds); // defaults to Plain style + table = new UITableView (View.Bounds); // defaults to Plain style table.AutoresizingMask = UIViewAutoresizing.All; - List<TableItem> tableItems = new List<TableItem>(); - + List<TableItem> tableItems = new List<TableItem> (); + // credit for images // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - tableItems.Add (new TableItem("Vegetables") { SubHeading="65 items", ImageName="Vegetables.jpg"}); - tableItems.Add (new TableItem("Fruits") { SubHeading="17 items", ImageName="Fruits.jpg"}); - tableItems.Add (new TableItem("Flower Buds") { SubHeading="5 items", ImageName="Flower Buds.jpg"}); - tableItems.Add (new TableItem("Legumes") { SubHeading="33 items", ImageName="Legumes.jpg"}); - tableItems.Add (new TableItem("Bulbs") { SubHeading="18 items", ImageName="Bulbs.jpg"}); - tableItems.Add (new TableItem("Tubers") { SubHeading="43 items", ImageName="Tubers.jpg"}); - table.Source = new TableSource(tableItems, this); + tableItems.Add (new TableItem ("Vegetables") { SubHeading = "65 items", ImageName = "Vegetables.jpg" }); + tableItems.Add (new TableItem ("Fruits") { SubHeading = "17 items", ImageName = "Fruits.jpg" }); + tableItems.Add (new TableItem ("Flower Buds") { SubHeading = "5 items", ImageName = "Flower Buds.jpg" }); + tableItems.Add (new TableItem ("Legumes") { SubHeading = "33 items", ImageName = "Legumes.jpg" }); + tableItems.Add (new TableItem ("Bulbs") { SubHeading = "18 items", ImageName = "Bulbs.jpg" }); + tableItems.Add (new TableItem ("Tubers") { SubHeading = "43 items", ImageName = "Tubers.jpg" }); + table.Source = new TableSource (tableItems, this); Add (table); } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/AppDelegate.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/AppDelegate.cs index 201f35223..63ef72c8c 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/AppDelegate.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,26 +13,25 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { protected UIWindow window; protected HomeScreen iPhoneHome; - + public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + + iPhoneHome = new HomeScreen (); + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - + window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableItem.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableItem.cs index 79e97b6b5..bc1a80fd0 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableItem.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableItem.cs @@ -4,28 +4,26 @@ namespace BasicTable { public class TableItem { public string Heading { get; set; } - + public string SubHeading { get; set; } - + public string ImageName { get; set; } - - public UITableViewCellStyle CellStyle - { + + public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; - - public UITableViewCellAccessory CellAccessory - { + + public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItem () { } - + public TableItem (string heading) { Heading = heading; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableSource.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableSource.cs index 00c6908f5..560bd496f 100755 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableSource.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/Code/TableSource.cs @@ -7,13 +7,13 @@ namespace BasicTable { public class TableSource : UITableViewSource { List<TableItem> tableItems; - NSString cellIdentifier = new NSString("TableCell"); - + NSString cellIdentifier = new NSString ("TableCell"); + public TableSource (List<TableItem> items) { tableItems = items; } - + /// <summary> /// Called by the TableView to determine how many cells to create for that particular section. /// </summary> @@ -21,17 +21,17 @@ public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Count; } - + /// <summary> /// Called when a row is touched /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - new UIAlertView("Row Selected" - , tableItems[indexPath.Row].Heading, null, "OK", null).Show(); + new UIAlertView ("Row Selected" + , tableItems [indexPath.Row].Heading, null, "OK", null).Show (); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> @@ -45,11 +45,11 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde cell = new CustomVegeCell (cellIdentifier); } - cell.UpdateCell (tableItems[indexPath.Row].Heading - , tableItems[indexPath.Row].SubHeading - , UIImage.FromFile ("Images/" +tableItems[indexPath.Row].ImageName) ); - + cell.UpdateCell (tableItems [indexPath.Row].Heading + , tableItems [indexPath.Row].SubHeading + , UIImage.FromFile ("Images/" + tableItems [indexPath.Row].ImageName)); + return cell; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/CustomVegeCell.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/CustomVegeCell.cs index b2ef44b12..e772caa5f 100644 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/CustomVegeCell.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/CustomVegeCell.cs @@ -5,32 +5,32 @@ namespace BasicTable { - public class CustomVegeCell: UITableViewCell { - + public class CustomVegeCell : UITableViewCell { + UILabel headingLabel, subheadingLabel; UIImageView imageView; public CustomVegeCell (NSString cellId) : base (UITableViewCellStyle.Default, cellId) { SelectionStyle = UITableViewCellSelectionStyle.Gray; - + ContentView.BackgroundColor = UIColor.FromRGB (218, 255, 127); - - imageView = new UIImageView(); + + imageView = new UIImageView (); headingLabel = new UILabel () { - Font = UIFont.FromName("Cochin-BoldItalic", 22f), + Font = UIFont.FromName ("Cochin-BoldItalic", 22f), TextColor = UIColor.FromRGB (127, 51, 0), BackgroundColor = UIColor.Clear }; - + subheadingLabel = new UILabel () { - Font = UIFont.FromName("AmericanTypewriter", 12f), + Font = UIFont.FromName ("AmericanTypewriter", 12f), TextColor = UIColor.FromRGB (38, 127, 0), TextAlignment = UITextAlignment.Center, BackgroundColor = UIColor.Clear }; - + ContentView.Add (headingLabel); ContentView.Add (subheadingLabel); ContentView.Add (imageView); @@ -46,10 +46,10 @@ public void UpdateCell (string caption, string subtitle, UIImage image) public override void LayoutSubviews () { base.LayoutSubviews (); - - imageView.Frame = new CGRect(ContentView.Bounds.Width - 63, 5, 33, 33); - headingLabel.Frame = new CGRect(5, 4, ContentView.Bounds.Width - 63, 25); - subheadingLabel.Frame = new CGRect(100, 18, 100, 20); + + imageView.Frame = new CGRect (ContentView.Bounds.Width - 63, 5, 33, 33); + headingLabel.Frame = new CGRect (5, 4, ContentView.Bounds.Width - 63, 25); + subheadingLabel.Frame = new CGRect (100, 18, 100, 20); } } } diff --git a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/HomeScreen.cs b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/HomeScreen.cs index 9b1860557..04186c755 100644 --- a/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/HomeScreen.cs +++ b/WorkingWithTables/Part 3 - Customizing a Table's appearance/3 - CellCustomTable/HomeScreen.cs @@ -8,30 +8,30 @@ public class HomeScreen : UIViewController { UITableView table; public HomeScreen () - { + { } public override void ViewDidLoad () { base.ViewDidLoad (); - table = new UITableView(View.Bounds); // defaults to Plain style + table = new UITableView (View.Bounds); // defaults to Plain style table.AutoresizingMask = UIViewAutoresizing.All; -//table.BackgroundColor = UIColor.FromRGB (218, 255, 127); -table.SeparatorColor = UIColor.FromRGB (127,106,0); + //table.BackgroundColor = UIColor.FromRGB (218, 255, 127); + table.SeparatorColor = UIColor.FromRGB (127, 106, 0); + + List<TableItem> tableItems = new List<TableItem> (); - List<TableItem> tableItems = new List<TableItem>(); - // credit for images // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - tableItems.Add (new TableItem("Vegetables") { SubHeading="65 items", ImageName="Vegetables.jpg"}); - tableItems.Add (new TableItem("Fruits") { SubHeading="17 items", ImageName="Fruits.jpg"}); - tableItems.Add (new TableItem("Flower Buds") { SubHeading="5 items", ImageName="Flower Buds.jpg"}); - tableItems.Add (new TableItem("Legumes") { SubHeading="33 items", ImageName="Legumes.jpg"}); - tableItems.Add (new TableItem("Bulbs") { SubHeading="18 items", ImageName="Bulbs.jpg"}); - tableItems.Add (new TableItem("Tubers") { SubHeading="43 items", ImageName="Tubers.jpg"}); - table.Source = new TableSource(tableItems); + tableItems.Add (new TableItem ("Vegetables") { SubHeading = "65 items", ImageName = "Vegetables.jpg" }); + tableItems.Add (new TableItem ("Fruits") { SubHeading = "17 items", ImageName = "Fruits.jpg" }); + tableItems.Add (new TableItem ("Flower Buds") { SubHeading = "5 items", ImageName = "Flower Buds.jpg" }); + tableItems.Add (new TableItem ("Legumes") { SubHeading = "33 items", ImageName = "Legumes.jpg" }); + tableItems.Add (new TableItem ("Bulbs") { SubHeading = "18 items", ImageName = "Bulbs.jpg" }); + tableItems.Add (new TableItem ("Tubers") { SubHeading = "43 items", ImageName = "Tubers.jpg" }); + table.Source = new TableSource (tableItems); Add (table); } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/AppDelegate.cs b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/AppDelegate.cs index 5bbbe9fe8..12b6cd095 100755 --- a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/AppDelegate.cs +++ b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,32 +13,31 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { UIWindow window; HomeScreen iPhoneHome; - UINavigationController navController; + UINavigationController navController; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); + + iPhoneHome = new HomeScreen (); iPhoneHome.Title = "Table Editing"; - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - - navController = new UINavigationController(); + + navController = new UINavigationController (); navController.PushViewController (iPhoneHome, false); window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableDelegate.cs b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableDelegate.cs index 4b16ac313..a02085136 100644 --- a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableDelegate.cs +++ b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableDelegate.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace BasicTable -{ - public class TableDelegate : UITableViewDelegate - { +namespace BasicTable { + public class TableDelegate : UITableViewDelegate { #region Constructors public TableDelegate () { @@ -20,7 +18,7 @@ public TableDelegate (IntPtr handle) : base (handle) public TableDelegate (NSObjectFlag t) : base (t) { } - + #endregion #region Override Methods @@ -31,15 +29,16 @@ public TableDelegate (NSObjectFlag t) : base (t) /// <returns>The actions for row.</returns> /// <param name="tableView">Table view.</param> /// <param name="indexPath">Index path.</param> - public override UITableViewRowAction[] EditActionsForRow (UITableView tableView, NSIndexPath indexPath) + public override UITableViewRowAction [] EditActionsForRow (UITableView tableView, NSIndexPath indexPath) { UITableViewRowAction hiButton = UITableViewRowAction.Create ( - UITableViewRowActionStyle.Default, + UITableViewRowActionStyle.Default, "Hi", - delegate { + delegate + { Console.WriteLine ("Hello World!"); }); - return new UITableViewRowAction[] { hiButton }; + return new UITableViewRowAction [] { hiButton }; } #endregion } diff --git a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableItem.cs b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableItem.cs index 79e97b6b5..bc1a80fd0 100755 --- a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableItem.cs +++ b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableItem.cs @@ -4,28 +4,26 @@ namespace BasicTable { public class TableItem { public string Heading { get; set; } - + public string SubHeading { get; set; } - + public string ImageName { get; set; } - - public UITableViewCellStyle CellStyle - { + + public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; - - public UITableViewCellAccessory CellAccessory - { + + public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItem () { } - + public TableItem (string heading) { Heading = heading; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableSource.cs b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableSource.cs index a713505da..a5ea56b53 100755 --- a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableSource.cs +++ b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/Code/TableSource.cs @@ -7,15 +7,15 @@ namespace BasicTable { public class TableSource : UITableViewSource { List<TableItem> tableItems; - string cellIdentifier = "TableCell"; + string cellIdentifier = "TableCell"; HomeScreen owner; - + public TableSource (List<TableItem> items, HomeScreen owner) { tableItems = items; this.owner = owner; } - + /// <summary> /// Called by the TableView to determine how many cells to create for that particular section. /// </summary> @@ -23,19 +23,19 @@ public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Count; } - + /// <summary> /// Called when a row is touched /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems[indexPath.Row].Heading, UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + UIAlertController okAlertController = UIAlertController.Create ("Row Selected", tableItems [indexPath.Row].Heading, UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); owner.PresentViewController (okAlertController, true, null); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> @@ -45,29 +45,29 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); // UNCOMMENT one of these to use that style -// var cellStyle = UITableViewCellStyle.Default; + // var cellStyle = UITableViewCellStyle.Default; var cellStyle = UITableViewCellStyle.Subtitle; -// var cellStyle = UITableViewCellStyle.Value1; -// var cellStyle = UITableViewCellStyle.Value2; + // var cellStyle = UITableViewCellStyle.Value1; + // var cellStyle = UITableViewCellStyle.Value2; // if there are no cells to reuse, create a new one if (cell == null) { cell = new UITableViewCell (cellStyle, cellIdentifier); } - cell.TextLabel.Text = tableItems[indexPath.Row].Heading; - + cell.TextLabel.Text = tableItems [indexPath.Row].Heading; + // Default style doesn't support Subtitle - if (cellStyle == UITableViewCellStyle.Subtitle + if (cellStyle == UITableViewCellStyle.Subtitle || cellStyle == UITableViewCellStyle.Value1 || cellStyle == UITableViewCellStyle.Value2) { - cell.DetailTextLabel.Text = tableItems[indexPath.Row].SubHeading; + cell.DetailTextLabel.Text = tableItems [indexPath.Row].SubHeading; } - + // Value2 style doesn't support an image if (cellStyle != UITableViewCellStyle.Value2) - cell.ImageView.Image = UIImage.FromFile ("Images/" +tableItems[indexPath.Row].ImageName); - + cell.ImageView.Image = UIImage.FromFile ("Images/" + tableItems [indexPath.Row].ImageName); + return cell; } @@ -76,26 +76,26 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { switch (editingStyle) { - case UITableViewCellEditingStyle.Delete: - // remove the item from the underlying data source - tableItems.RemoveAt(indexPath.Row); - // delete the row from the table - tableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - - case UITableViewCellEditingStyle.Insert: - //---- create a new item and add it to our underlying data - tableItems.Insert (indexPath.Row, new TableItem ("(inserted)")); - //---- insert a new row in the table - tableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - - case UITableViewCellEditingStyle.None: - Console.WriteLine ("CommitEditingStyle:None called"); - break; + case UITableViewCellEditingStyle.Delete: + // remove the item from the underlying data source + tableItems.RemoveAt (indexPath.Row); + // delete the row from the table + tableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + + case UITableViewCellEditingStyle.Insert: + //---- create a new item and add it to our underlying data + tableItems.Insert (indexPath.Row, new TableItem ("(inserted)")); + //---- insert a new row in the table + tableView.InsertRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + + case UITableViewCellEditingStyle.None: + Console.WriteLine ("CommitEditingStyle:None called"); + break; } } - + /// <summary> /// Called by the table view to determine whether or not the row is editable /// </summary> @@ -103,7 +103,7 @@ public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { return true; // return false if you wish to disable editing for a specific indexPath or for all rows } - + /// <summary> /// Called by the table view to determine whether or not the row is moveable /// </summary> @@ -117,9 +117,9 @@ public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath) /// </summary> public override string TitleForDeleteConfirmation (UITableView tableView, NSIndexPath indexPath) { - return "Trash (" + tableItems[indexPath.Row].SubHeading + ")"; + return "Trash (" + tableItems [indexPath.Row].SubHeading + ")"; } - + /// <summary> /// Called by the table view to determine whether the editing control should be an insert /// or a delete. @@ -128,17 +128,17 @@ public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tabl { return UITableViewCellEditingStyle.Delete; } - + /// <summary> /// called by the table view when a row is moved. /// </summary> public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) { //---- get a reference to the item - var item = tableItems[sourceIndexPath.Row]; + var item = tableItems [sourceIndexPath.Row]; var deleteAt = sourceIndexPath.Row; var insertAt = destinationIndexPath.Row; - + //---- if we're inserting it before, the one to delete will have a higher index if (destinationIndexPath.Row < sourceIndexPath.Row) { //---- add one to where we delete, because we're increasing the index by inserting @@ -147,14 +147,14 @@ public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath //---- add one to where we insert, because we haven't deleted the original yet insertAt += 1; } - + //---- copy the item to the new location tableItems.Insert (insertAt, item); - + //---- remove from the old tableItems.RemoveAt (deleteAt); } #endregion } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/HomeScreen.cs b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/HomeScreen.cs index ae90feb96..07b204318 100644 --- a/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/HomeScreen.cs +++ b/WorkingWithTables/Part 4 - Editing/1 - TableEditMode/HomeScreen.cs @@ -11,62 +11,62 @@ public class HomeScreen : UIViewController { TableDelegate tableDelegate; public HomeScreen () - { + { } - + UIBarButtonItem edit, done, @add; public override void ViewDidLoad () { base.ViewDidLoad (); - table = new UITableView(View.Bounds); // defaults to Plain style + table = new UITableView (View.Bounds); // defaults to Plain style table.AutoresizingMask = UIViewAutoresizing.All; - List<TableItem> tableItems = new List<TableItem>(); - + List<TableItem> tableItems = new List<TableItem> (); + // credit for images and content // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - tableItems.Add (new TableItem("Vegetables") { SubHeading="65 items", ImageName="Vegetables.jpg"}); - tableItems.Add (new TableItem("Fruits") { SubHeading="17 items", ImageName="Fruits.jpg"}); - tableItems.Add (new TableItem("Flower Buds") { SubHeading="5 items", ImageName="Flower Buds.jpg"}); - tableItems.Add (new TableItem("Legumes") { SubHeading="33 items", ImageName="Legumes.jpg"}); - tableItems.Add (new TableItem("Bulbs") { SubHeading="18 items", ImageName="Bulbs.jpg"}); - tableItems.Add (new TableItem("Tubers") { SubHeading="43 items", ImageName="Tubers.jpg"}); - tableSource = new TableSource(tableItems, this); + tableItems.Add (new TableItem ("Vegetables") { SubHeading = "65 items", ImageName = "Vegetables.jpg" }); + tableItems.Add (new TableItem ("Fruits") { SubHeading = "17 items", ImageName = "Fruits.jpg" }); + tableItems.Add (new TableItem ("Flower Buds") { SubHeading = "5 items", ImageName = "Flower Buds.jpg" }); + tableItems.Add (new TableItem ("Legumes") { SubHeading = "33 items", ImageName = "Legumes.jpg" }); + tableItems.Add (new TableItem ("Bulbs") { SubHeading = "18 items", ImageName = "Bulbs.jpg" }); + tableItems.Add (new TableItem ("Tubers") { SubHeading = "43 items", ImageName = "Tubers.jpg" }); + tableSource = new TableSource (tableItems, this); table.Source = tableSource; // To replace the standard edit button with a "Hi" button, uncomment out // these lines - tableDelegate = new TableDelegate (); - table.Delegate = tableDelegate; + tableDelegate = new TableDelegate (); + table.Delegate = tableDelegate; - - @add = new UIBarButtonItem(UIBarButtonSystemItem.Add, (s,e)=>{ - tableItems.Insert (0, new TableItem ("(inserted)") { SubHeading="0 items"}); // default new row - table.InsertRows (new NSIndexPath[] { NSIndexPath.FromRowSection(0,0) }, UITableViewRowAnimation.Fade); + + @add = new UIBarButtonItem (UIBarButtonSystemItem.Add, (s, e) => { + tableItems.Insert (0, new TableItem ("(inserted)") { SubHeading = "0 items" }); // default new row + table.InsertRows (new NSIndexPath [] { NSIndexPath.FromRowSection (0, 0) }, UITableViewRowAnimation.Fade); }); - done = new UIBarButtonItem(UIBarButtonSystemItem.Done, (s,e)=>{ + done = new UIBarButtonItem (UIBarButtonSystemItem.Done, (s, e) => { table.SetEditing (false, true); NavigationItem.LeftBarButtonItem = @add; NavigationItem.RightBarButtonItem = edit; }); - edit = new UIBarButtonItem(UIBarButtonSystemItem.Edit, (s,e)=>{ + edit = new UIBarButtonItem (UIBarButtonSystemItem.Edit, (s, e) => { if (table.Editing) table.SetEditing (false, true); // if we've half-swiped a row table.SetEditing (true, true); NavigationItem.LeftBarButtonItem = null; NavigationItem.RightBarButtonItem = done; - + }); NavigationItem.RightBarButtonItem = edit; NavigationItem.LeftBarButtonItem = @add; - + Add (table); } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/AppDelegate.cs b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/AppDelegate.cs index 5bbbe9fe8..12b6cd095 100755 --- a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/AppDelegate.cs +++ b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/AppDelegate.cs @@ -4,7 +4,7 @@ namespace BasicTable { public class Application { - public static void Main (string[] args) + public static void Main (string [] args) { try { UIApplication.Main (args, null, "AppDelegate"); @@ -13,32 +13,31 @@ public static void Main (string[] args) } } } - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { UIWindow window; HomeScreen iPhoneHome; - UINavigationController navController; + UINavigationController navController; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { window = new UIWindow (UIScreen.MainScreen.Bounds); window.MakeKeyAndVisible (); - - iPhoneHome = new HomeScreen(); + + iPhoneHome = new HomeScreen (); iPhoneHome.Title = "Table Editing"; - iPhoneHome.View.Frame = new CoreGraphics.CGRect(0 + iPhoneHome.View.Frame = new CoreGraphics.CGRect (0 , UIApplication.SharedApplication.StatusBarFrame.Height , UIScreen.MainScreen.ApplicationFrame.Width , UIScreen.MainScreen.ApplicationFrame.Height); - - navController = new UINavigationController(); + + navController = new UINavigationController (); navController.PushViewController (iPhoneHome, false); window.RootViewController = iPhoneHome; - + return true; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableItem.cs b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableItem.cs index 79e97b6b5..bc1a80fd0 100755 --- a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableItem.cs +++ b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableItem.cs @@ -4,28 +4,26 @@ namespace BasicTable { public class TableItem { public string Heading { get; set; } - + public string SubHeading { get; set; } - + public string ImageName { get; set; } - - public UITableViewCellStyle CellStyle - { + + public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; - - public UITableViewCellAccessory CellAccessory - { + + public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItem () { } - + public TableItem (string heading) { Heading = heading; } } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableSource.cs b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableSource.cs index 75131fc6b..3ce666fb2 100755 --- a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableSource.cs +++ b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/Code/TableSource.cs @@ -7,13 +7,13 @@ namespace BasicTable { public class TableSource : UITableViewSource { List<TableItem> tableItems; - string cellIdentifier = "TableCell"; - + string cellIdentifier = "TableCell"; + public TableSource (List<TableItem> items) { tableItems = items; } - + /// <summary> /// Called by the TableView to determine how many cells to create for that particular section. /// </summary> @@ -21,17 +21,17 @@ public override nint RowsInSection (UITableView tableview, nint section) { return tableItems.Count; } - + /// <summary> /// Called when a row is touched /// </summary> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - new UIAlertView("Row Selected" - , tableItems[indexPath.Row].Heading, null, "OK", null).Show(); + new UIAlertView ("Row Selected" + , tableItems [indexPath.Row].Heading, null, "OK", null).Show (); tableView.DeselectRow (indexPath, true); } - + /// <summary> /// Called by the TableView to get the actual UITableViewCell to render for the particular row /// </summary> @@ -41,29 +41,29 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); // UNCOMMENT one of these to use that style -// var cellStyle = UITableViewCellStyle.Default; + // var cellStyle = UITableViewCellStyle.Default; var cellStyle = UITableViewCellStyle.Subtitle; -// var cellStyle = UITableViewCellStyle.Value1; -// var cellStyle = UITableViewCellStyle.Value2; + // var cellStyle = UITableViewCellStyle.Value1; + // var cellStyle = UITableViewCellStyle.Value2; // if there are no cells to reuse, create a new one if (cell == null) { cell = new UITableViewCell (cellStyle, cellIdentifier); } - cell.TextLabel.Text = tableItems[indexPath.Row].Heading; - + cell.TextLabel.Text = tableItems [indexPath.Row].Heading; + // Default style doesn't support Subtitle - if (cellStyle == UITableViewCellStyle.Subtitle + if (cellStyle == UITableViewCellStyle.Subtitle || cellStyle == UITableViewCellStyle.Value1 || cellStyle == UITableViewCellStyle.Value2) { - cell.DetailTextLabel.Text = tableItems[indexPath.Row].SubHeading; + cell.DetailTextLabel.Text = tableItems [indexPath.Row].SubHeading; } - + // Value2 style doesn't support an image if (cellStyle != UITableViewCellStyle.Value2) - cell.ImageView.Image = UIImage.FromFile ("Images/" +tableItems[indexPath.Row].ImageName); - + cell.ImageView.Image = UIImage.FromFile ("Images/" + tableItems [indexPath.Row].ImageName); + return cell; } @@ -72,26 +72,26 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { switch (editingStyle) { - case UITableViewCellEditingStyle.Delete: - // remove the item from the underlying data source - tableItems.RemoveAt(indexPath.Row); - // delete the row from the table - tableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - - case UITableViewCellEditingStyle.Insert: - //---- create a new item and add it to our underlying data - tableItems.Insert (indexPath.Row, new TableItem ("(inserted)")); - //---- insert a new row in the table - tableView.InsertRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Fade); - break; - - case UITableViewCellEditingStyle.None: - Console.WriteLine ("CommitEditingStyle:None called"); - break; + case UITableViewCellEditingStyle.Delete: + // remove the item from the underlying data source + tableItems.RemoveAt (indexPath.Row); + // delete the row from the table + tableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + + case UITableViewCellEditingStyle.Insert: + //---- create a new item and add it to our underlying data + tableItems.Insert (indexPath.Row, new TableItem ("(inserted)")); + //---- insert a new row in the table + tableView.InsertRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Fade); + break; + + case UITableViewCellEditingStyle.None: + Console.WriteLine ("CommitEditingStyle:None called"); + break; } } - + /// <summary> /// Called by the table view to determine whether or not the row is editable /// </summary> @@ -99,7 +99,7 @@ public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { return true; // return false if you wish to disable editing for a specific indexPath or for all rows } - + /// <summary> /// Called by the table view to determine whether or not the row is moveable /// </summary> @@ -113,9 +113,9 @@ public override bool CanMoveRow (UITableView tableView, NSIndexPath indexPath) /// </summary> public override string TitleForDeleteConfirmation (UITableView tableView, NSIndexPath indexPath) { - return "Trash (" + tableItems[indexPath.Row].SubHeading + ")"; + return "Trash (" + tableItems [indexPath.Row].SubHeading + ")"; } - + /// <summary> /// Called by the table view to determine whether the editing control should be an insert /// or a delete. @@ -123,7 +123,7 @@ public override string TitleForDeleteConfirmation (UITableView tableView, NSInde public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath) { if (tableView.Editing) { - if (indexPath.Row == tableView.NumberOfRowsInSection (0)-1) + if (indexPath.Row == tableView.NumberOfRowsInSection (0) - 1) return UITableViewCellEditingStyle.Insert; else return UITableViewCellEditingStyle.Delete; @@ -135,7 +135,7 @@ public override NSIndexPath CustomizeMoveTarget (UITableView tableView, NSIndexP var numRows = tableView.NumberOfRowsInSection (0) - 1; // less the (add new) one Console.WriteLine (proposedIndexPath.Row + " " + numRows); if (proposedIndexPath.Row >= numRows) - return NSIndexPath.FromRowSection(numRows-1, 0); + return NSIndexPath.FromRowSection (numRows - 1, 0); else return proposedIndexPath; } @@ -145,22 +145,21 @@ public override NSIndexPath CustomizeMoveTarget (UITableView tableView, NSIndexP public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) { //---- get a reference to the item - var item = tableItems[sourceIndexPath.Row]; + var item = tableItems [sourceIndexPath.Row]; var deleteAt = sourceIndexPath.Row; var insertAt = destinationIndexPath.Row; - + //---- if we're moving within the same section, and we're inserting it before - if ((sourceIndexPath.Section == destinationIndexPath.Section) && (destinationIndexPath.Row < sourceIndexPath.Row)) - { + if ((sourceIndexPath.Section == destinationIndexPath.Section) && (destinationIndexPath.Row < sourceIndexPath.Row)) { //---- add one to where we delete, because we're increasing the index by inserting deleteAt += 1; } else { insertAt += 1; } - + //---- copy the item to the new location tableItems.Insert (destinationIndexPath.Row, item); - + //---- remove from the old tableItems.RemoveAt (deleteAt); } @@ -171,18 +170,18 @@ public void WillBeginTableEditing (UITableView tableView) { //---- start animations tableView.BeginUpdates (); - + //---- insert a new row in the table - tableView.InsertRows (new NSIndexPath[] { - NSIndexPath.FromRowSection (tableView.NumberOfRowsInSection (0), 0) + tableView.InsertRows (new NSIndexPath [] { + NSIndexPath.FromRowSection (tableView.NumberOfRowsInSection (0), 0) }, UITableViewRowAnimation.Fade); //---- create a new item and add it to our underlying data tableItems.Add (new TableItem ("(add new)")); - + //---- end animations tableView.EndUpdates (); } - + /// <summary> /// Called manually when the table leaves edit mode /// </summary> @@ -191,13 +190,13 @@ public void DidFinishTableEditing (UITableView tableView) //---- start animations tableView.BeginUpdates (); //---- remove our row from the underlying data - tableItems.RemoveAt ((int)tableView.NumberOfRowsInSection (0) - 1); // zero based :) - //---- remove the row from the table - tableView.DeleteRows (new NSIndexPath[] { NSIndexPath.FromRowSection (tableView.NumberOfRowsInSection (0) - 1, 0) }, UITableViewRowAnimation.Fade); + tableItems.RemoveAt ((int) tableView.NumberOfRowsInSection (0) - 1); // zero based :) + //---- remove the row from the table + tableView.DeleteRows (new NSIndexPath [] { NSIndexPath.FromRowSection (tableView.NumberOfRowsInSection (0) - 1, 0) }, UITableViewRowAnimation.Fade); //---- finish animations tableView.EndUpdates (); } #endregion } -} \ No newline at end of file +} diff --git a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/HomeScreen.cs b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/HomeScreen.cs index 0e91526ac..4807c2d9d 100644 --- a/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/HomeScreen.cs +++ b/WorkingWithTables/Part 4 - Editing/2 - TableEditModeAdd/HomeScreen.cs @@ -10,39 +10,39 @@ public class HomeScreen : UIViewController { TableSource tableSource; public HomeScreen () - { + { } - + UIBarButtonItem edit, done; public override void ViewDidLoad () { base.ViewDidLoad (); - table = new UITableView(View.Bounds); // defaults to Plain style + table = new UITableView (View.Bounds); // defaults to Plain style table.AutoresizingMask = UIViewAutoresizing.All; - List<TableItem> tableItems = new List<TableItem>(); - + List<TableItem> tableItems = new List<TableItem> (); + // credit for images and content // http://en.wikipedia.org/wiki/List_of_culinary_vegetables - tableItems.Add (new TableItem("Vegetables") { SubHeading="65 items", ImageName="Vegetables.jpg"}); - tableItems.Add (new TableItem("Fruits") { SubHeading="17 items", ImageName="Fruits.jpg"}); - tableItems.Add (new TableItem("Flower Buds") { SubHeading="5 items", ImageName="Flower Buds.jpg"}); - tableItems.Add (new TableItem("Legumes") { SubHeading="33 items", ImageName="Legumes.jpg"}); - tableItems.Add (new TableItem("Bulbs") { SubHeading="18 items", ImageName="Bulbs.jpg"}); - tableItems.Add (new TableItem("Tubers") { SubHeading="43 items", ImageName="Tubers.jpg"}); - tableSource = new TableSource(tableItems); + tableItems.Add (new TableItem ("Vegetables") { SubHeading = "65 items", ImageName = "Vegetables.jpg" }); + tableItems.Add (new TableItem ("Fruits") { SubHeading = "17 items", ImageName = "Fruits.jpg" }); + tableItems.Add (new TableItem ("Flower Buds") { SubHeading = "5 items", ImageName = "Flower Buds.jpg" }); + tableItems.Add (new TableItem ("Legumes") { SubHeading = "33 items", ImageName = "Legumes.jpg" }); + tableItems.Add (new TableItem ("Bulbs") { SubHeading = "18 items", ImageName = "Bulbs.jpg" }); + tableItems.Add (new TableItem ("Tubers") { SubHeading = "43 items", ImageName = "Tubers.jpg" }); + tableSource = new TableSource (tableItems); table.Source = tableSource; - - done = new UIBarButtonItem(UIBarButtonSystemItem.Done, (s,e)=>{ + + done = new UIBarButtonItem (UIBarButtonSystemItem.Done, (s, e) => { table.SetEditing (false, true); NavigationItem.RightBarButtonItem = edit; - tableSource.DidFinishTableEditing(table); + tableSource.DidFinishTableEditing (table); }); - edit = new UIBarButtonItem(UIBarButtonSystemItem.Edit, (s,e)=>{ + edit = new UIBarButtonItem (UIBarButtonSystemItem.Edit, (s, e) => { if (table.Editing) table.SetEditing (false, true); // if we've half-swiped a row - tableSource.WillBeginTableEditing(table); + tableSource.WillBeginTableEditing (table); table.SetEditing (true, true); NavigationItem.LeftBarButtonItem = null; NavigationItem.RightBarButtonItem = done; @@ -51,8 +51,8 @@ public override void ViewDidLoad () NavigationItem.RightBarButtonItem = edit; - + Add (table); } } -} \ No newline at end of file +} diff --git a/Working_with_images/AppDelegate.cs b/Working_with_images/AppDelegate.cs index bd11d9412..71b5224ca 100644 --- a/Working_with_images/AppDelegate.cs +++ b/Working_with_images/AppDelegate.cs @@ -4,53 +4,51 @@ using Foundation; using UIKit; -namespace Working_with_images -{ - /// <summary> - /// The UIApplicationDelegate for the application. This class is responsible for launching the - /// User Interface of the application, as well as listening (and optionally responding) to - /// application events from iOS. - /// </summary> - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - UIWindow window; - - // Added controller. As of MonoTouch 5.0.2, applications are expected to - // have a root view controller at the end of application launch - - UIViewController controller; - UILabel label; - - /// <summary> - /// This method is invoked when the application has loaded and is ready to run. In this - /// method you should instantiate the window, load the UI into it and then make the window - /// visible. - /// </summary> - /// <remarks> - /// You have 5 seconds to return from this method, or iOS will terminate your application. - /// </remarks> - public override bool FinishedLaunching (UIApplication app, NSDictionary options) - { - // create a new window instance based on the screen size - window = new UIWindow (UIScreen.MainScreen.Bounds); - - controller = new UIViewController (); - controller.View.BackgroundColor = UIColor.White; - - label = new UILabel(); - label.Frame = new CoreGraphics.CGRect(10 ,10, UIScreen.MainScreen.Bounds.Width, 50); - label.Text = "Hello, Working with Images"; - - controller.View.AddSubview(label); - - window.RootViewController = controller; - - // make the window visible - window.MakeKeyAndVisible (); - - return true; - } - } +namespace Working_with_images { + /// <summary> + /// The UIApplicationDelegate for the application. This class is responsible for launching the + /// User Interface of the application, as well as listening (and optionally responding) to + /// application events from iOS. + /// </summary> + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + UIWindow window; + + // Added controller. As of MonoTouch 5.0.2, applications are expected to + // have a root view controller at the end of application launch + + UIViewController controller; + UILabel label; + + /// <summary> + /// This method is invoked when the application has loaded and is ready to run. In this + /// method you should instantiate the window, load the UI into it and then make the window + /// visible. + /// </summary> + /// <remarks> + /// You have 5 seconds to return from this method, or iOS will terminate your application. + /// </remarks> + public override bool FinishedLaunching (UIApplication app, NSDictionary options) + { + // create a new window instance based on the screen size + window = new UIWindow (UIScreen.MainScreen.Bounds); + + controller = new UIViewController (); + controller.View.BackgroundColor = UIColor.White; + + label = new UILabel (); + label.Frame = new CoreGraphics.CGRect (10, 10, UIScreen.MainScreen.Bounds.Width, 50); + label.Text = "Hello, Working with Images"; + + controller.View.AddSubview (label); + + window.RootViewController = controller; + + // make the window visible + window.MakeKeyAndVisible (); + + return true; + } + } } diff --git a/Working_with_images/Main.cs b/Working_with_images/Main.cs index 86a4d638f..f125518fe 100644 --- a/Working_with_images/Main.cs +++ b/Working_with_images/Main.cs @@ -4,18 +4,16 @@ using Foundation; using UIKit; -namespace Working_with_images -{ - public class Application - { - /// <summary> - /// This is the main entry point of the application. - /// </summary> - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } +namespace Working_with_images { + public class Application { + /// <summary> + /// This is the main entry point of the application. + /// </summary> + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/WorldCities/WorldCities/AppDelegate.cs b/WorldCities/WorldCities/AppDelegate.cs index 571ecde07..bad77147c 100644 --- a/WorldCities/WorldCities/AppDelegate.cs +++ b/WorldCities/WorldCities/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace WorldCities -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace WorldCities { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/WorldCities/WorldCities/CitiesViewController.cs b/WorldCities/WorldCities/CitiesViewController.cs index 8ad9aedde..a5d1f110e 100644 --- a/WorldCities/WorldCities/CitiesViewController.cs +++ b/WorldCities/WorldCities/CitiesViewController.cs @@ -1,54 +1,51 @@ -using Foundation; -using System; +using Foundation; +using System; using System.Collections.Generic; -using UIKit; - -namespace WorldCities -{ - public partial class CitiesViewController : UITableViewController - { - private const string CellIdentifier = "cellIdentifier"; - - private readonly List<WorldCity> cities = new List<WorldCity>(); - - public event EventHandler<CityEventArgs> CityChanged; - - public CitiesViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - var path = NSBundle.MainBundle.PathForResource("CityList", "plist"); - var citiesArray = NSArray.FromFile(path); - foreach (var city in NSArray.FromArray<NSDictionary>(citiesArray)) - { - cities.Add(new WorldCity(city[(NSString)"cityNameKey"].ToString(), - double.Parse(city[(NSString)"latitudeKey"].ToString()), - double.Parse(city[(NSString)"longitudeKey"].ToString()))); - } - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return cities.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(CellIdentifier); - var city = cities[indexPath.Row]; - - cell.TextLabel.Text = city.Name; - cell.DetailTextLabel.Text = $"{city.Latitude} {city.Longitude}"; - - return cell; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - CityChanged?.Invoke(this, new CityEventArgs(cities[indexPath.Row])); - DismissViewController(true, null); - } - } -} \ No newline at end of file +using UIKit; + +namespace WorldCities { + public partial class CitiesViewController : UITableViewController { + private const string CellIdentifier = "cellIdentifier"; + + private readonly List<WorldCity> cities = new List<WorldCity> (); + + public event EventHandler<CityEventArgs> CityChanged; + + public CitiesViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var path = NSBundle.MainBundle.PathForResource ("CityList", "plist"); + var citiesArray = NSArray.FromFile (path); + foreach (var city in NSArray.FromArray<NSDictionary> (citiesArray)) { + cities.Add (new WorldCity (city [(NSString) "cityNameKey"].ToString (), + double.Parse (city [(NSString) "latitudeKey"].ToString ()), + double.Parse (city [(NSString) "longitudeKey"].ToString ()))); + } + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return cities.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (CellIdentifier); + var city = cities [indexPath.Row]; + + cell.TextLabel.Text = city.Name; + cell.DetailTextLabel.Text = $"{city.Latitude} {city.Longitude}"; + + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + CityChanged?.Invoke (this, new CityEventArgs (cities [indexPath.Row])); + DismissViewController (true, null); + } + } +} diff --git a/WorldCities/WorldCities/Main.cs b/WorldCities/WorldCities/Main.cs index 4cf05ad28..2b70d09b2 100644 --- a/WorldCities/WorldCities/Main.cs +++ b/WorldCities/WorldCities/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace WorldCities -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace WorldCities { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/WorldCities/WorldCities/Models/CityEventArgs.cs b/WorldCities/WorldCities/Models/CityEventArgs.cs index 145d2366b..7cbf72a38 100644 --- a/WorldCities/WorldCities/Models/CityEventArgs.cs +++ b/WorldCities/WorldCities/Models/CityEventArgs.cs @@ -1,13 +1,11 @@ -namespace WorldCities -{ - public class CityEventArgs : System.EventArgs - { - public WorldCity City { get; private set; } +namespace WorldCities { + public class CityEventArgs : System.EventArgs { + public WorldCity City { get; private set; } - public CityEventArgs(WorldCity city) - { - City = city; - } - } -} \ No newline at end of file + public CityEventArgs (WorldCity city) + { + City = city; + } + } +} diff --git a/WorldCities/WorldCities/Models/WorldCity.cs b/WorldCities/WorldCities/Models/WorldCity.cs index 260c1b6aa..64357c96c 100644 --- a/WorldCities/WorldCities/Models/WorldCity.cs +++ b/WorldCities/WorldCities/Models/WorldCity.cs @@ -1,19 +1,17 @@ -namespace WorldCities -{ - public class WorldCity - { - public WorldCity(string name, double latitude, double longitude) - { - this.Name = name; - this.Latitude = latitude; - this.Longitude = longitude; - } +namespace WorldCities { + public class WorldCity { + public WorldCity (string name, double latitude, double longitude) + { + this.Name = name; + this.Latitude = latitude; + this.Longitude = longitude; + } - public string Name { get; private set; } + public string Name { get; private set; } - public double Latitude { get; private set; } + public double Latitude { get; private set; } - public double Longitude { get; private set; } - } -} \ No newline at end of file + public double Longitude { get; private set; } + } +} diff --git a/WorldCities/WorldCities/ViewController.cs b/WorldCities/WorldCities/ViewController.cs index 77f1b678d..7ae3ce736 100644 --- a/WorldCities/WorldCities/ViewController.cs +++ b/WorldCities/WorldCities/ViewController.cs @@ -1,84 +1,77 @@ -using CoreLocation; +using CoreLocation; using Foundation; using MapKit; using ObjCRuntime; using System; using UIKit; -namespace WorldCities -{ - public partial class ViewController : UIViewController - { - private WorldCity selectedCity; +namespace WorldCities { + public partial class ViewController : UIViewController { + private WorldCity selectedCity; - protected ViewController(IntPtr handle) : base(handle) { } + protected ViewController (IntPtr handle) : base (handle) { } - partial void SelectorChanged(UISegmentedControl sender) - { - switch (sender.SelectedSegment) - { - case 1: - mapView.MapType = MapKit.MKMapType.Satellite; - break; - case 2: - mapView.MapType = MapKit.MKMapType.Hybrid; - break; - default: - mapView.MapType = MapKit.MKMapType.Standard; - break; - } - } + partial void SelectorChanged (UISegmentedControl sender) + { + switch (sender.SelectedSegment) { + case 1: + mapView.MapType = MapKit.MKMapType.Satellite; + break; + case 2: + mapView.MapType = MapKit.MKMapType.Hybrid; + break; + default: + mapView.MapType = MapKit.MKMapType.Standard; + break; + } + } - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue?.DestinationViewController is CitiesViewController controller) - { - controller.CityChanged += OnCityChanged; - } - } + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue?.DestinationViewController is CitiesViewController controller) { + controller.CityChanged += OnCityChanged; + } + } - private void OnCityChanged(object sender, CityEventArgs e) - { - (sender as CitiesViewController).CityChanged -= OnCityChanged; - selectedCity = e.City; - ChooseWorldCity(); - } + private void OnCityChanged (object sender, CityEventArgs e) + { + (sender as CitiesViewController).CityChanged -= OnCityChanged; + selectedCity = e.City; + ChooseWorldCity (); + } - private void ChooseWorldCity() - { - var place = selectedCity; - Title = place.Name; + private void ChooseWorldCity () + { + var place = selectedCity; + Title = place.Name; - var current = mapView.Region; - if (current.Span.LatitudeDelta < 10) - { - PerformSelector(new Selector("AnimateToWorld"), null, 0.3f); - PerformSelector(new Selector("AnimateToPlace"), null, 1.7f); - } - else - { - PerformSelector(new Selector("AnimateToPlace"), null, 0.3f); - } - } + var current = mapView.Region; + if (current.Span.LatitudeDelta < 10) { + PerformSelector (new Selector ("AnimateToWorld"), null, 0.3f); + PerformSelector (new Selector ("AnimateToPlace"), null, 1.7f); + } else { + PerformSelector (new Selector ("AnimateToPlace"), null, 0.3f); + } + } - [Export("AnimateToWorld")] - private void AnimateToWorld() - { - var city = selectedCity; - var region = mapView.Region; - var zoomOut = new MKCoordinateRegion(new CLLocationCoordinate2D((region.Center.Latitude + city.Latitude) / 2d, - (region.Center.Longitude + city.Longitude) / 2d), - new MKCoordinateSpan(90, 90)); - mapView.SetRegion(zoomOut, true); - } + [Export ("AnimateToWorld")] + private void AnimateToWorld () + { + var city = selectedCity; + var region = mapView.Region; + var zoomOut = new MKCoordinateRegion (new CLLocationCoordinate2D ((region.Center.Latitude + city.Latitude) / 2d, + (region.Center.Longitude + city.Longitude) / 2d), + new MKCoordinateSpan (90, 90)); + mapView.SetRegion (zoomOut, true); + } - [Export("AnimateToPlace")] - private void AnimateToPlace() - { - var city = selectedCity; - var region = new MKCoordinateRegion(new CLLocationCoordinate2D(city.Latitude, city.Longitude), - new MKCoordinateSpan(0.4, 0.4)); - mapView.SetRegion(region, true); - } - } -} \ No newline at end of file + [Export ("AnimateToPlace")] + private void AnimateToPlace () + { + var city = selectedCity; + var region = new MKCoordinateRegion (new CLLocationCoordinate2D (city.Latitude, city.Longitude), + new MKCoordinateSpan (0.4, 0.4)); + mapView.SetRegion (region, true); + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/AppDelegate.cs b/ZoomingPdfViewer/ZoomingPdfViewer/AppDelegate.cs index d6f679bc1..181013d96 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/AppDelegate.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace ZoomingPdfViewer -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace ZoomingPdfViewer { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/DataViewController.cs b/ZoomingPdfViewer/ZoomingPdfViewer/DataViewController.cs index b73467e1b..161846adf 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/DataViewController.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/DataViewController.cs @@ -2,63 +2,60 @@ using System; using UIKit; -namespace ZoomingPdfViewer -{ - public partial class DataViewController : UIViewController - { - private CGPDFPage page; - - private nfloat myScale; - - public DataViewController(IntPtr handle) : base(handle) { } - - public CGPDFDocument Pdf { get; set; } - - public nint PageNumber { get; set; } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Do any additional setup after loading the view, typically from a nib. - page = Pdf.GetPage(PageNumber); - ScrollView.SetPDFPage(page); - - // Disable zooming if our pages are currently shown in landscape, for new views - ScrollView.UserInteractionEnabled = UIApplication.SharedApplication.StatusBarOrientation.IsPortrait(); - } - - public override void ViewDidLayoutSubviews() - { - RestoreScale(); - } - - public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) - { - base.ViewWillTransitionToSize(toSize, coordinator); - coordinator.AnimateAlongsideTransition((param) => { }, (context) => - { - // Disable zooming if our pages are currently shown in landscape after orientation changes - ScrollView.UserInteractionEnabled = UIApplication.SharedApplication.StatusBarOrientation.IsPortrait(); - }); - } - - private void RestoreScale() - { - // Called on orientation change. - // We need to zoom out and basically reset the scrollview to look right in two-page spline view. - var pageRect = page.GetBoxRect(CGPDFBox.Media); - var yScale = View.Frame.Height / pageRect.Height; - var xScale = View.Frame.Width / pageRect.Width; - myScale = NMath.Min(xScale, yScale); - - ScrollView.Bounds = View.Bounds; - ScrollView.ZoomScale = 1f; - ScrollView.PdfScale = myScale; - - ScrollView.TiledPdfView.Bounds = View.Bounds; - ScrollView.TiledPdfView.MyScale = myScale; - ScrollView.TiledPdfView.Layer.SetNeedsDisplay(); - } - } -} \ No newline at end of file +namespace ZoomingPdfViewer { + public partial class DataViewController : UIViewController { + private CGPDFPage page; + + private nfloat myScale; + + public DataViewController (IntPtr handle) : base (handle) { } + + public CGPDFDocument Pdf { get; set; } + + public nint PageNumber { get; set; } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Do any additional setup after loading the view, typically from a nib. + page = Pdf.GetPage (PageNumber); + ScrollView.SetPDFPage (page); + + // Disable zooming if our pages are currently shown in landscape, for new views + ScrollView.UserInteractionEnabled = UIApplication.SharedApplication.StatusBarOrientation.IsPortrait (); + } + + public override void ViewDidLayoutSubviews () + { + RestoreScale (); + } + + public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) + { + base.ViewWillTransitionToSize (toSize, coordinator); + coordinator.AnimateAlongsideTransition ((param) => { }, (context) => { + // Disable zooming if our pages are currently shown in landscape after orientation changes + ScrollView.UserInteractionEnabled = UIApplication.SharedApplication.StatusBarOrientation.IsPortrait (); + }); + } + + private void RestoreScale () + { + // Called on orientation change. + // We need to zoom out and basically reset the scrollview to look right in two-page spline view. + var pageRect = page.GetBoxRect (CGPDFBox.Media); + var yScale = View.Frame.Height / pageRect.Height; + var xScale = View.Frame.Width / pageRect.Width; + myScale = NMath.Min (xScale, yScale); + + ScrollView.Bounds = View.Bounds; + ScrollView.ZoomScale = 1f; + ScrollView.PdfScale = myScale; + + ScrollView.TiledPdfView.Bounds = View.Bounds; + ScrollView.TiledPdfView.MyScale = myScale; + ScrollView.TiledPdfView.Layer.SetNeedsDisplay (); + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/Main.cs b/ZoomingPdfViewer/ZoomingPdfViewer/Main.cs index 13ff7bdd0..e1c276f4d 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/Main.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace ZoomingPdfViewer -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace ZoomingPdfViewer { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/ModelController.cs b/ZoomingPdfViewer/ZoomingPdfViewer/ModelController.cs index 4c69bc28c..95b64f8f3 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/ModelController.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/ModelController.cs @@ -1,83 +1,74 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; using System; using UIKit; -namespace ZoomingPdfViewer -{ - /// <summary> - /// This view controller manages the display of a set of view controllers by way of implementing the UIPageViewControllerDataSource protocol. - /// </summary> - public class ModelController : NSObject, IUIPageViewControllerDataSource - { - private readonly nint numberOfPages; +namespace ZoomingPdfViewer { + /// <summary> + /// This view controller manages the display of a set of view controllers by way of implementing the UIPageViewControllerDataSource protocol. + /// </summary> + public class ModelController : NSObject, IUIPageViewControllerDataSource { + private readonly nint numberOfPages; - private CGPDFDocument pdf; + private CGPDFDocument pdf; - public ModelController() - { - var pdfUrl = NSBundle.MainBundle.GetUrlForResource("Tamarin", "pdf"); - if (pdfUrl != null) - { - pdf = CGPDFDocument.FromUrl(pdfUrl.AbsoluteString); - numberOfPages = pdf.Pages; - if (numberOfPages % 2 != 0) - { - numberOfPages++; - } - } - else - { - // missing pdf file, cannot proceed. - Console.WriteLine("Missing pdf file 'Tamarin.pdf'"); - } - } + public ModelController () + { + var pdfUrl = NSBundle.MainBundle.GetUrlForResource ("Tamarin", "pdf"); + if (pdfUrl != null) { + pdf = CGPDFDocument.FromUrl (pdfUrl.AbsoluteString); + numberOfPages = pdf.Pages; + if (numberOfPages % 2 != 0) { + numberOfPages++; + } + } else { + // missing pdf file, cannot proceed. + Console.WriteLine ("Missing pdf file 'Tamarin.pdf'"); + } + } - public DataViewController GetViewController(nint index, UIStoryboard storyboard) - { - var dataViewController = storyboard.InstantiateViewController("DataViewController") as DataViewController; - dataViewController.PageNumber = index + 1; - dataViewController.Pdf = pdf; + public DataViewController GetViewController (nint index, UIStoryboard storyboard) + { + var dataViewController = storyboard.InstantiateViewController ("DataViewController") as DataViewController; + dataViewController.PageNumber = index + 1; + dataViewController.Pdf = pdf; - return dataViewController; - } + return dataViewController; + } - public nint IndexOfViewController(DataViewController viewController) - { - // Return the index of the given data view controller. - // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. - return viewController.PageNumber - 1; - } + public nint IndexOfViewController (DataViewController viewController) + { + // Return the index of the given data view controller. + // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. + return viewController.PageNumber - 1; + } - public UIViewController GetPreviousViewController(UIPageViewController pageViewController, UIViewController referenceViewController) - { - UIViewController result = null; + public UIViewController GetPreviousViewController (UIPageViewController pageViewController, UIViewController referenceViewController) + { + UIViewController result = null; - var index = IndexOfViewController(referenceViewController as DataViewController); - if (index > 0) - { - index--; - result = GetViewController(index, referenceViewController.Storyboard); - } + var index = IndexOfViewController (referenceViewController as DataViewController); + if (index > 0) { + index--; + result = GetViewController (index, referenceViewController.Storyboard); + } - return result; - } + return result; + } - public UIViewController GetNextViewController(UIPageViewController pageViewController, UIViewController referenceViewController) - { - UIViewController result = null; + public UIViewController GetNextViewController (UIPageViewController pageViewController, UIViewController referenceViewController) + { + UIViewController result = null; - var index = IndexOfViewController(referenceViewController as DataViewController); - if (index >= 0) - { - index++; - if (index != numberOfPages) - { - result = GetViewController(index, referenceViewController.Storyboard); - } - } + var index = IndexOfViewController (referenceViewController as DataViewController); + if (index >= 0) { + index++; + if (index != numberOfPages) { + result = GetViewController (index, referenceViewController.Storyboard); + } + } - return result; - } - } -} \ No newline at end of file + return result; + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/PdfScrollView.cs b/ZoomingPdfViewer/ZoomingPdfViewer/PdfScrollView.cs index d24c8ae3d..92b9d3245 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/PdfScrollView.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/PdfScrollView.cs @@ -3,137 +3,132 @@ using System; using UIKit; -namespace ZoomingPdfViewer -{ - /// <summary> - /// UIScrollView subclass that handles the user input to zoom the PDF page. This class handles swapping the TiledPDFViews when the zoom level changes. - /// </summary> - [Register("PdfScrollView")] - public class PdfScrollView : UIScrollView, IUIScrollViewDelegate - { - // The old TiledPDFView that we draw on top of when the zooming stops. - private TiledPdfView oldPdfView; - - // a reference to the page being drawn - private CGPDFPage page; - - // Frame of the PDF - private CGRect pageRect; - - public PdfScrollView(IntPtr handle) : base(handle) - { - Initialize(); - } - - public PdfScrollView(CGRect frame) : base(frame) - { - Initialize(); - } - - /// <summary> - /// Current PDF zoom scale. - /// </summary> - public nfloat PdfScale { get; set; } - - /// <summary> - /// The TiledPDFView that is currently front most. - /// </summary> - public TiledPdfView TiledPdfView { get; private set; } - - private void Initialize() - { - DecelerationRate = UIScrollView.DecelerationRateFast; - Delegate = this; - - Layer.BorderColor = UIColor.LightGray.CGColor; - Layer.BorderWidth = 5f; - - MaximumZoomScale = 5f; - MinimumZoomScale = 0.25f; - - oldPdfView = new TiledPdfView(pageRect, PdfScale); - } - - public void SetPDFPage(CGPDFPage pdfPage) - { - page = pdfPage; - - // PDFPage is null if we're requested to draw a padded blank page by the parent UIPageViewController - if (page == null) - { - pageRect = Bounds; - } - else - { - pageRect = page.GetBoxRect(CGPDFBox.Media); - - PdfScale = Frame.Size.Width / pageRect.Size.Width; - pageRect = new CGRect(pageRect.X, pageRect.Y, pageRect.Width * PdfScale, pageRect.Height * PdfScale); - } - - // Create the TiledPDFView based on the size of the PDF page and scale it to fit the view. - ReplaceTiledPdfViewWithFrame(pageRect); - } - - public override void LayoutSubviews() - { - // Use layoutSubviews to center the PDF page in the view. - base.LayoutSubviews(); - - // Center the image as it becomes smaller than the size of the screen. - var boundsSize = Bounds.Size; - var frameToCenter = TiledPdfView.Frame; - - // Center horizontally. - frameToCenter.X = frameToCenter.Width < boundsSize.Width ? (boundsSize.Width - frameToCenter.Width) / 2f : 0f; - frameToCenter.Y = frameToCenter.Height < boundsSize.Height ? (boundsSize.Height - frameToCenter.Height) / 2f : 0f; - - TiledPdfView.Frame = frameToCenter; - - /* +namespace ZoomingPdfViewer { + /// <summary> + /// UIScrollView subclass that handles the user input to zoom the PDF page. This class handles swapping the TiledPDFViews when the zoom level changes. + /// </summary> + [Register ("PdfScrollView")] + public class PdfScrollView : UIScrollView, IUIScrollViewDelegate { + // The old TiledPDFView that we draw on top of when the zooming stops. + private TiledPdfView oldPdfView; + + // a reference to the page being drawn + private CGPDFPage page; + + // Frame of the PDF + private CGRect pageRect; + + public PdfScrollView (IntPtr handle) : base (handle) + { + Initialize (); + } + + public PdfScrollView (CGRect frame) : base (frame) + { + Initialize (); + } + + /// <summary> + /// Current PDF zoom scale. + /// </summary> + public nfloat PdfScale { get; set; } + + /// <summary> + /// The TiledPDFView that is currently front most. + /// </summary> + public TiledPdfView TiledPdfView { get; private set; } + + private void Initialize () + { + DecelerationRate = UIScrollView.DecelerationRateFast; + Delegate = this; + + Layer.BorderColor = UIColor.LightGray.CGColor; + Layer.BorderWidth = 5f; + + MaximumZoomScale = 5f; + MinimumZoomScale = 0.25f; + + oldPdfView = new TiledPdfView (pageRect, PdfScale); + } + + public void SetPDFPage (CGPDFPage pdfPage) + { + page = pdfPage; + + // PDFPage is null if we're requested to draw a padded blank page by the parent UIPageViewController + if (page == null) { + pageRect = Bounds; + } else { + pageRect = page.GetBoxRect (CGPDFBox.Media); + + PdfScale = Frame.Size.Width / pageRect.Size.Width; + pageRect = new CGRect (pageRect.X, pageRect.Y, pageRect.Width * PdfScale, pageRect.Height * PdfScale); + } + + // Create the TiledPDFView based on the size of the PDF page and scale it to fit the view. + ReplaceTiledPdfViewWithFrame (pageRect); + } + + public override void LayoutSubviews () + { + // Use layoutSubviews to center the PDF page in the view. + base.LayoutSubviews (); + + // Center the image as it becomes smaller than the size of the screen. + var boundsSize = Bounds.Size; + var frameToCenter = TiledPdfView.Frame; + + // Center horizontally. + frameToCenter.X = frameToCenter.Width < boundsSize.Width ? (boundsSize.Width - frameToCenter.Width) / 2f : 0f; + frameToCenter.Y = frameToCenter.Height < boundsSize.Height ? (boundsSize.Height - frameToCenter.Height) / 2f : 0f; + + TiledPdfView.Frame = frameToCenter; + + /* * To handle the interaction between CATiledLayer and high resolution screens, set the tiling view's contentScaleFactor to 1.0. * If this step were omitted, the content scale factor would be 2.0 on high resolution screens, which would cause the CATiledLayer to ask for tiles of the wrong scale. */ - TiledPdfView.ContentScaleFactor = 1f; - } - - [Export("viewForZoomingInScrollView:")] - public new UIView ViewForZoomingInScrollView(UIScrollView scrollView) - { - return TiledPdfView; - } - - [Export("scrollViewWillBeginZooming:withView:")] - public new void ZoomingStarted(UIScrollView scrollView, UIView view) - { - // Remove back tiled view. - oldPdfView.RemoveFromSuperview(); - oldPdfView.Dispose(); - - // Set the current TiledPDFView to be the old view. - oldPdfView = TiledPdfView; - } - - /// <summary> - /// A UIScrollView delegate callback, called when the user begins zooming. - /// When the user begins zooming, remove the old TiledPDFView and set the current TiledPDFView to be the old view so we can create a new TiledPDFView when the zooming ends. - /// </summary> - [Export("scrollViewDidEndZooming:withView:atScale:")] - public new void ZoomingEnded(UIScrollView scrollView, UIView withView, nfloat atScale) - { - // Set the new scale factor for the TiledPDFView. - PdfScale *= atScale; - ReplaceTiledPdfViewWithFrame(oldPdfView.Frame); - } - - private void ReplaceTiledPdfViewWithFrame(CGRect frame) - { - // Create a new tiled PDF View at the new scale - var tiledPDFView = new TiledPdfView(frame, PdfScale) { PdfPage = page }; - - // Add the new TiledPDFView to the PDFScrollView. - AddSubview(tiledPDFView); - TiledPdfView = tiledPDFView; - } - } -} \ No newline at end of file + TiledPdfView.ContentScaleFactor = 1f; + } + + [Export ("viewForZoomingInScrollView:")] + public new UIView ViewForZoomingInScrollView (UIScrollView scrollView) + { + return TiledPdfView; + } + + [Export ("scrollViewWillBeginZooming:withView:")] + public new void ZoomingStarted (UIScrollView scrollView, UIView view) + { + // Remove back tiled view. + oldPdfView.RemoveFromSuperview (); + oldPdfView.Dispose (); + + // Set the current TiledPDFView to be the old view. + oldPdfView = TiledPdfView; + } + + /// <summary> + /// A UIScrollView delegate callback, called when the user begins zooming. + /// When the user begins zooming, remove the old TiledPDFView and set the current TiledPDFView to be the old view so we can create a new TiledPDFView when the zooming ends. + /// </summary> + [Export ("scrollViewDidEndZooming:withView:atScale:")] + public new void ZoomingEnded (UIScrollView scrollView, UIView withView, nfloat atScale) + { + // Set the new scale factor for the TiledPDFView. + PdfScale *= atScale; + ReplaceTiledPdfViewWithFrame (oldPdfView.Frame); + } + + private void ReplaceTiledPdfViewWithFrame (CGRect frame) + { + // Create a new tiled PDF View at the new scale + var tiledPDFView = new TiledPdfView (frame, PdfScale) { PdfPage = page }; + + // Add the new TiledPDFView to the PDFScrollView. + AddSubview (tiledPDFView); + TiledPdfView = tiledPDFView; + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/RootViewController.cs b/ZoomingPdfViewer/ZoomingPdfViewer/RootViewController.cs index fee7ba7e1..fe011d16b 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/RootViewController.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/RootViewController.cs @@ -2,95 +2,87 @@ using System; using UIKit; -namespace ZoomingPdfViewer -{ - /// <summary> - /// This view controller manages the display of a set of view controllers by way of implementing the UIPageViewControllerDelegate protocol. - /// </summary> - public partial class RootViewController : UIViewController, IUIPageViewControllerDelegate - { - private UIPageViewController pageViewController; - - private ModelController modelController; - - public RootViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // insantiate our ModelController - modelController = new ModelController(); - - // Do any additional setup after loading the view, typically from a nib. - // Configure the page view controller and add it as a child view controller. - - pageViewController = new UIPageViewController(UIPageViewControllerTransitionStyle.PageCurl, - UIPageViewControllerNavigationOrientation.Horizontal, - new NSDictionary()); - pageViewController.Delegate = this; - - var startingViewController = modelController.GetViewController(0, Storyboard); - pageViewController.SetViewControllers(new[] { startingViewController }, - UIPageViewControllerNavigationDirection.Forward, - false, - null); - - pageViewController.DataSource = modelController; - - AddChildViewController(pageViewController); - View.AddSubview(pageViewController.View); - - // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. - var pageViewRect = View.Bounds; - pageViewController.View.Frame = pageViewRect; - pageViewController.DidMoveToParentViewController(this); - - // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. - View.GestureRecognizers = pageViewController.GestureRecognizers; - } - - [Export("pageViewController:spineLocationForInterfaceOrientation:")] - public UIPageViewControllerSpineLocation GetSpineLocation(UIPageViewController pageViewController, UIInterfaceOrientation orientation) - { - var result = UIPageViewControllerSpineLocation.None; - if (orientation == UIInterfaceOrientation.Portrait || UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) - { - // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. - // Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here. - var currentViewController = pageViewController.ViewControllers[0]; - pageViewController.SetViewControllers(new[] { currentViewController }, - UIPageViewControllerNavigationDirection.Forward, - true, - null); - - pageViewController.DoubleSided = false; - result = UIPageViewControllerSpineLocation.Min; - } - else - { - // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. - // If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. - var dataViewController = pageViewController.ViewControllers[0] as DataViewController; - var indexOfCurrentViewController = modelController.IndexOfViewController(dataViewController); - UIViewController[] viewControllers = null; - - if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) - { - var nextViewController = modelController.GetNextViewController(pageViewController, dataViewController); - viewControllers = new[] { dataViewController, nextViewController }; - } - else - { - var previousViewController = modelController.GetPreviousViewController(pageViewController, dataViewController); - viewControllers = new[] { dataViewController, previousViewController }; - } - - pageViewController.SetViewControllers(viewControllers, UIPageViewControllerNavigationDirection.Forward, true, null); - result = UIPageViewControllerSpineLocation.Mid; - } - - return result; - } - } -} \ No newline at end of file +namespace ZoomingPdfViewer { + /// <summary> + /// This view controller manages the display of a set of view controllers by way of implementing the UIPageViewControllerDelegate protocol. + /// </summary> + public partial class RootViewController : UIViewController, IUIPageViewControllerDelegate { + private UIPageViewController pageViewController; + + private ModelController modelController; + + public RootViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // insantiate our ModelController + modelController = new ModelController (); + + // Do any additional setup after loading the view, typically from a nib. + // Configure the page view controller and add it as a child view controller. + + pageViewController = new UIPageViewController (UIPageViewControllerTransitionStyle.PageCurl, + UIPageViewControllerNavigationOrientation.Horizontal, + new NSDictionary ()); + pageViewController.Delegate = this; + + var startingViewController = modelController.GetViewController (0, Storyboard); + pageViewController.SetViewControllers (new [] { startingViewController }, + UIPageViewControllerNavigationDirection.Forward, + false, + null); + + pageViewController.DataSource = modelController; + + AddChildViewController (pageViewController); + View.AddSubview (pageViewController.View); + + // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages. + var pageViewRect = View.Bounds; + pageViewController.View.Frame = pageViewRect; + pageViewController.DidMoveToParentViewController (this); + + // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily. + View.GestureRecognizers = pageViewController.GestureRecognizers; + } + + [Export ("pageViewController:spineLocationForInterfaceOrientation:")] + public UIPageViewControllerSpineLocation GetSpineLocation (UIPageViewController pageViewController, UIInterfaceOrientation orientation) + { + var result = UIPageViewControllerSpineLocation.None; + if (orientation == UIInterfaceOrientation.Portrait || UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) { + // In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. + // Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to YES, so set it to NO here. + var currentViewController = pageViewController.ViewControllers [0]; + pageViewController.SetViewControllers (new [] { currentViewController }, + UIPageViewControllerNavigationDirection.Forward, + true, + null); + + pageViewController.DoubleSided = false; + result = UIPageViewControllerSpineLocation.Min; + } else { + // In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. + // If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers. + var dataViewController = pageViewController.ViewControllers [0] as DataViewController; + var indexOfCurrentViewController = modelController.IndexOfViewController (dataViewController); + UIViewController [] viewControllers = null; + + if (indexOfCurrentViewController == 0 || indexOfCurrentViewController % 2 == 0) { + var nextViewController = modelController.GetNextViewController (pageViewController, dataViewController); + viewControllers = new [] { dataViewController, nextViewController }; + } else { + var previousViewController = modelController.GetPreviousViewController (pageViewController, dataViewController); + viewControllers = new [] { dataViewController, previousViewController }; + } + + pageViewController.SetViewControllers (viewControllers, UIPageViewControllerNavigationDirection.Forward, true, null); + result = UIPageViewControllerSpineLocation.Mid; + } + + return result; + } + } +} diff --git a/ZoomingPdfViewer/ZoomingPdfViewer/TiledPdfView.cs b/ZoomingPdfViewer/ZoomingPdfViewer/TiledPdfView.cs index 12e60192b..f89b11198 100644 --- a/ZoomingPdfViewer/ZoomingPdfViewer/TiledPdfView.cs +++ b/ZoomingPdfViewer/ZoomingPdfViewer/TiledPdfView.cs @@ -5,75 +5,71 @@ using System; using UIKit; -namespace ZoomingPdfViewer -{ - /// <summary> - /// This view is backed by a CATiledLayer into which the PDF page is rendered into. - /// </summary> - public class TiledPdfView : UIView - { - private CATiledLayer tiledLayer; +namespace ZoomingPdfViewer { + /// <summary> + /// This view is backed by a CATiledLayer into which the PDF page is rendered into. + /// </summary> + public class TiledPdfView : UIView { + private CATiledLayer tiledLayer; - /// <summary> - /// Create a new TiledPDFView with the desired frame and scale. - /// </summary> - public TiledPdfView(CGRect frame, nfloat scale) : base(frame) - { - tiledLayer = Layer as CATiledLayer; + /// <summary> + /// Create a new TiledPDFView with the desired frame and scale. + /// </summary> + public TiledPdfView (CGRect frame, nfloat scale) : base (frame) + { + tiledLayer = Layer as CATiledLayer; - // levelsOfDetail and levelsOfDetailBias determine how the layer is rendered at different zoom levels. - // This only matters while the view is zooming, because once the the view is done zooming a new TiledPDFView is created at the correct size and scale. - tiledLayer.LevelsOfDetail = 4; - tiledLayer.LevelsOfDetailBias = 3; - tiledLayer.TileSize = new CGSize(512f, 512f); + // levelsOfDetail and levelsOfDetailBias determine how the layer is rendered at different zoom levels. + // This only matters while the view is zooming, because once the the view is done zooming a new TiledPDFView is created at the correct size and scale. + tiledLayer.LevelsOfDetail = 4; + tiledLayer.LevelsOfDetailBias = 3; + tiledLayer.TileSize = new CGSize (512f, 512f); - MyScale = scale; - Layer.BorderColor = UIColor.LightGray.CGColor; - Layer.BorderWidth = 5; - } + MyScale = scale; + Layer.BorderColor = UIColor.LightGray.CGColor; + Layer.BorderWidth = 5; + } - public nfloat MyScale { get; set; } + public nfloat MyScale { get; set; } - public CGPDFPage PdfPage { get; set; } + public CGPDFPage PdfPage { get; set; } - [Export("layerClass")] - public static Class LayerClass() - { - // instruct that we want a CATileLayer (not the default CALayer) for the Layer property - return new Class(typeof(CATiledLayer)); - } + [Export ("layerClass")] + public static Class LayerClass () + { + // instruct that we want a CATileLayer (not the default CALayer) for the Layer property + return new Class (typeof (CATiledLayer)); + } - public override void DrawLayer(CALayer layer, CGContext context) - { - // Fill the background with white. - context.SetFillColor(1f, 1f, 1f, 1f); - context.FillRect(Bounds); + public override void DrawLayer (CALayer layer, CGContext context) + { + // Fill the background with white. + context.SetFillColor (1f, 1f, 1f, 1f); + context.FillRect (Bounds); - // Print a blank page and return if our page is nil. - if (PdfPage != null) - { - context.SaveState(); + // Print a blank page and return if our page is nil. + if (PdfPage != null) { + context.SaveState (); - // Flip page so we render it as it's meant to be read - context.TranslateCTM(0f, Bounds.Height); - context.ScaleCTM(1f, -1f); + // Flip page so we render it as it's meant to be read + context.TranslateCTM (0f, Bounds.Height); + context.ScaleCTM (1f, -1f); - // Scale page at the view-zoom level - context.ScaleCTM(MyScale, MyScale); + // Scale page at the view-zoom level + context.ScaleCTM (MyScale, MyScale); - // draw the page, restore and exit - context.DrawPDFPage(PdfPage); - context.RestoreState(); - } - } + // draw the page, restore and exit + context.DrawPDFPage (PdfPage); + context.RestoreState (); + } + } - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if(disposing) - { - tiledLayer.Dispose(); - } - } - } -} \ No newline at end of file + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (disposing) { + tiledLayer.Dispose (); + } + } + } +} diff --git a/iOS7-ui-updates/ImageViewController.cs b/iOS7-ui-updates/ImageViewController.cs index fd0295959..ae68f581b 100644 --- a/iOS7-ui-updates/ImageViewController.cs +++ b/iOS7-ui-updates/ImageViewController.cs @@ -24,4 +24,4 @@ public override void ViewDidLayoutSubviews () View.AddSubview (imageView); } } -} \ No newline at end of file +} diff --git a/iOS7-ui-updates/Main.cs b/iOS7-ui-updates/Main.cs index 495be8575..9920143e6 100644 --- a/iOS7-ui-updates/Main.cs +++ b/iOS7-ui-updates/Main.cs @@ -2,9 +2,9 @@ namespace ImageView { public class Application { - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/intro-to-extensions/ContainerApp/AppDelegate.cs b/intro-to-extensions/ContainerApp/AppDelegate.cs index 6ebb18bef..104bd7bc2 100644 --- a/intro-to-extensions/ContainerApp/AppDelegate.cs +++ b/intro-to-extensions/ContainerApp/AppDelegate.cs @@ -1,43 +1,41 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace ContainerApp -{ +namespace ContainerApp { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/intro-to-extensions/ContainerApp/ContainerAppViewController.cs b/intro-to-extensions/ContainerApp/ContainerAppViewController.cs index 0779eeace..029fddcf6 100644 --- a/intro-to-extensions/ContainerApp/ContainerAppViewController.cs +++ b/intro-to-extensions/ContainerApp/ContainerAppViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace ContainerApp -{ - public partial class ContainerAppViewController : UIViewController - { +namespace ContainerApp { + public partial class ContainerAppViewController : UIViewController { public ContainerAppViewController (IntPtr handle) : base (handle) { } @@ -16,7 +14,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -25,7 +23,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/intro-to-extensions/ContainerApp/Main.cs b/intro-to-extensions/ContainerApp/Main.cs index 3ac9fc6b6..6108916da 100644 --- a/intro-to-extensions/ContainerApp/Main.cs +++ b/intro-to-extensions/ContainerApp/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace ContainerApp -{ - public class Application - { +namespace ContainerApp { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/intro-to-extensions/DayCountExtension/CodeViewController.cs b/intro-to-extensions/DayCountExtension/CodeViewController.cs index 8a23a46bf..b3eed5587 100644 --- a/intro-to-extensions/DayCountExtension/CodeViewController.cs +++ b/intro-to-extensions/DayCountExtension/CodeViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; using NotificationCenter; using CoreGraphics; using Foundation; -namespace DayCountExtension -{ +namespace DayCountExtension { [Register ("CodeViewController")] - public class CodeViewController : UIViewController, INCWidgetProviding - { + public class CodeViewController : UIViewController, INCWidgetProviding { public CodeViewController () { } diff --git a/intro-to-extensions/DayCountExtension/TodayViewController.cs b/intro-to-extensions/DayCountExtension/TodayViewController.cs index 7e1fda8ee..458d2efcb 100644 --- a/intro-to-extensions/DayCountExtension/TodayViewController.cs +++ b/intro-to-extensions/DayCountExtension/TodayViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using NotificationCenter; @@ -7,10 +7,8 @@ using UIKit; using CoreGraphics; -namespace DayCountExtension -{ - public partial class TodayViewController : SLComposeServiceViewController, INCWidgetProviding - { +namespace DayCountExtension { + public partial class TodayViewController : SLComposeServiceViewController, INCWidgetProviding { public TodayViewController (IntPtr handle) : base (handle) { } diff --git a/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController.cs b/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController.cs index ad6d63225..78d395e33 100644 --- a/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController.cs +++ b/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController.cs @@ -12,24 +12,20 @@ using Photos; using UIKit; -namespace AVCamManual -{ - public enum SetupResult - { +namespace AVCamManual { + public enum SetupResult { Success, CameraNotAuthorized, SessionConfigurationFailed }; - public enum CaptureMode - { + public enum CaptureMode { Photo, Movie } [Register ("AVCamManualCameraViewController")] - public partial class AVCamManualCameraViewController : UIViewController, IAVCapturePhotoCaptureDelegate, IAVCaptureFileOutputRecordingDelegate - { + public partial class AVCamManualCameraViewController : UIViewController, IAVCapturePhotoCaptureDelegate, IAVCaptureFileOutputRecordingDelegate { IDisposable focusModeToken; IDisposable lensPositionToken; IDisposable exposureModeToken; @@ -189,10 +185,10 @@ public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerT UIDeviceOrientation deviceOrientation = UIDevice.CurrentDevice.Orientation; if (deviceOrientation.IsPortrait () || deviceOrientation.IsLandscape ()) { - var previewLayer = (AVCaptureVideoPreviewLayer)PreviewView.Layer; + var previewLayer = (AVCaptureVideoPreviewLayer) PreviewView.Layer; var connection = PreviewLayer.Connection; - if(connection != null) - connection.VideoOrientation = (AVCaptureVideoOrientation)deviceOrientation; + if (connection != null) + connection.VideoOrientation = (AVCaptureVideoOrientation) deviceOrientation; } } @@ -251,7 +247,7 @@ void ConfigureManualHUD () double maxExposureDurationSeconds = VideoDevice.ActiveFormat.MaxExposureDuration.Seconds; // Map from duration to non-linear UI range 0-1 double p = (exposureDurationSeconds - minExposureDurationSeconds) / (maxExposureDurationSeconds - minExposureDurationSeconds); // Scale to 0-1 - ExposureDurationSlider.Value = (float)Math.Pow (p, 1 / ExposureDurationPower); // Apply inverse power + ExposureDurationSlider.Value = (float) Math.Pow (p, 1 / ExposureDurationPower); // Apply inverse power ExposureDurationSlider.Enabled = (VideoDevice != null && VideoDevice.ExposureMode == AVCaptureExposureMode.Custom); ISOSlider.MinValue = VideoDevice.ActiveFormat.MinISO; @@ -310,7 +306,7 @@ void ToggleHUD (NSObject sender) [Action ("changeManualHUD:")] void ChangeManualHUD (NSObject sender) { - var control = (UISegmentedControl)sender; + var control = (UISegmentedControl) sender; ManualHUDPhotoView.Hidden = control.SelectedSegment != 0; ManualHUDFocusView.Hidden = control.SelectedSegment != 1; @@ -340,14 +336,14 @@ void SetColorFor (UISlider slider, UIColor color) [Action ("sliderTouchBegan:")] void SliderTouchBegan (NSObject sender) { - var slider = (UISlider)sender; + var slider = (UISlider) sender; SetColorFor (slider, UIColor.FromRGBA (0, 122, 1, 1)); } [Action ("sliderTouchEnded:")] void SliderTouchEnded (NSObject sender) { - var slider = (UISlider)sender; + var slider = (UISlider) sender; SetColorFor (slider, UIColor.Yellow); } @@ -436,10 +432,10 @@ AVCapturePhotoSettings GetCurrentPhotoSettings () photoSettings = AVCapturePhotoBracketSettings.FromRawPixelFormatType (photoOutput.AvailableRawPhotoPixelFormatTypes [0].UInt32Value, null, bracketedSettings); } else { // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=44111 - photoSettings = AVCapturePhotoBracketSettings.FromRawPixelFormatType (0, new NSDictionary<NSString, NSObject> (AVVideo.CodecKey, new NSNumber ((int)AVVideoCodec.JPEG)), bracketedSettings); + photoSettings = AVCapturePhotoBracketSettings.FromRawPixelFormatType (0, new NSDictionary<NSString, NSObject> (AVVideo.CodecKey, new NSNumber ((int) AVVideoCodec.JPEG)), bracketedSettings); } - ((AVCapturePhotoBracketSettings)photoSettings).IsLensStabilizationEnabled = true; + ((AVCapturePhotoBracketSettings) photoSettings).IsLensStabilizationEnabled = true; } else { if (rawEnabled && photoOutput.AvailableRawPhotoPixelFormatTypes.Length > 0) { photoSettings = AVCapturePhotoSettings.FromRawPixelFormatType (photoOutput.AvailableRawPhotoPixelFormatTypes [0].UInt32Value); @@ -451,7 +447,7 @@ AVCapturePhotoSettings GetCurrentPhotoSettings () if (VideoDevice.ExposureMode == AVCaptureExposureMode.Custom) { photoSettings.FlashMode = AVCaptureFlashMode.Off; } else { - photoSettings.FlashMode = photoOutput.SupportedFlashModes.Contains (new NSNumber ((long)AVCaptureFlashMode.Auto)) ? AVCaptureFlashMode.Auto : AVCaptureFlashMode.Off; + photoSettings.FlashMode = photoOutput.SupportedFlashModes.Contains (new NSNumber ((long) AVCaptureFlashMode.Auto)) ? AVCaptureFlashMode.Auto : AVCaptureFlashMode.Off; } } @@ -493,7 +489,7 @@ void ResumeInterruptedSession (NSObject sender) [Action ("changeCaptureMode:")] void ChangeCaptureMode (UISegmentedControl captureModeControl) { - if (captureModeControl.SelectedSegment == (int)CaptureMode.Photo) { + if (captureModeControl.SelectedSegment == (int) CaptureMode.Photo) { RecordButton.Enabled = false; // Remove the AVCaptureMovieFileOutput from the session because movie recording is not supported with AVCaptureSessionPresetPhoto. Additionally, Live Photo @@ -506,7 +502,7 @@ void ChangeCaptureMode (UISegmentedControl captureModeControl) movieFileOutput = null; }); - } else if (captureModeControl.SelectedSegment == (int)CaptureMode.Movie) { + } else if (captureModeControl.SelectedSegment == (int) CaptureMode.Movie) { sessionQueue.DispatchAsync (() => { var mfo = new AVCaptureMovieFileOutput (); if (Session.CanAddOutput (mfo)) { @@ -583,7 +579,7 @@ void OnCameraChangeClicked (NSObject sender) DispatchQueue.MainQueue.DispatchAsync (() => { ConfigureManualHUD (); CameraButton.Enabled = true; - RecordButton.Enabled = (CaptureModeControl.SelectedSegment == (int)CaptureMode.Movie); + RecordButton.Enabled = (CaptureModeControl.SelectedSegment == (int) CaptureMode.Movie); PhotoButton.Enabled = true; CaptureModeControl.Enabled = true; HUDButton.Enabled = true; @@ -602,7 +598,7 @@ static AVCaptureDevice GetDeviceFrom (string mediaType, AVCaptureDevicePosition [Export ("changeFocusMode:")] public void OnChangeFocusModeClicked (NSObject sender) { - var control = (UISegmentedControl)sender; + var control = (UISegmentedControl) sender; AVCaptureFocusMode mode = focusModes [control.SelectedSegment]; NSError error = null; @@ -626,7 +622,7 @@ public void OnChangeFocusModeClicked (NSObject sender) [Export ("changeLensPosition:")] public void OnChangeLensPositionClicked (NSObject sender) { - var control = (UISlider)sender; + var control = (UISlider) sender; NSError error = null; if (VideoDevice.LockForConfiguration (out error)) { @@ -664,14 +660,14 @@ void SetFocusAndMode (AVCaptureFocusMode focusMode, AVCaptureExposureMode exposu [Export ("focusAndExposeTap:")] void OnFocusAndExposeClicked (UIGestureRecognizer gestureRecognizer) { - CGPoint devicePoint = ((AVCaptureVideoPreviewLayer)PreviewView.Layer).CaptureDevicePointOfInterestForPoint (gestureRecognizer.LocationInView (gestureRecognizer.View)); + CGPoint devicePoint = ((AVCaptureVideoPreviewLayer) PreviewView.Layer).CaptureDevicePointOfInterestForPoint (gestureRecognizer.LocationInView (gestureRecognizer.View)); SetFocusAndMode (VideoDevice.FocusMode, VideoDevice.ExposureMode, devicePoint, true); } [Export ("changeExposureMode:")] public void OnChangeExposureModeClicked (NSObject sender) { - var control = (UISegmentedControl)sender; + var control = (UISegmentedControl) sender; AVCaptureExposureMode mode = exposureModes [control.SelectedSegment]; NSError error = null; @@ -693,7 +689,7 @@ public void OnChangeExposureModeClicked (NSObject sender) [Export ("changeExposureDuration:")] void OnChangeExposureDurationClicked (NSObject sender) { - var control = (UISlider)sender; + var control = (UISlider) sender; NSError error = null; double p = Math.Pow (control.Value, ExposureDurationPower); // Apply power function to expand slider's low-end range @@ -712,7 +708,7 @@ void OnChangeExposureDurationClicked (NSObject sender) [Export ("changeISO:")] public void OnChangeISOClicked (NSObject sender) { - var control = (UISlider)sender; + var control = (UISlider) sender; NSError error = null; if (VideoDevice.LockForConfiguration (out error)) { @@ -726,7 +722,7 @@ public void OnChangeISOClicked (NSObject sender) [Export ("changeExposureTargetBias:")] public void OnChangeExposureTargetBiasClicked (NSObject sender) { - var control = (UISlider)sender; + var control = (UISlider) sender; NSError error = null; if (VideoDevice.LockForConfiguration (out error)) { @@ -740,7 +736,7 @@ public void OnChangeExposureTargetBiasClicked (NSObject sender) [Export ("changeWhiteBalanceMode:")] public void OnChangeWhiteBalanceModeClicked (NSObject sender) { - var control = (UISegmentedControl)sender; + var control = (UISegmentedControl) sender; AVCaptureWhiteBalanceMode mode = whiteBalanceModes [control.SelectedSegment]; NSError error = null; @@ -823,7 +819,7 @@ void CapturePhoto (NSObject sender) { // Retrieve the video preview layer's video orientation on the main queue before entering the session queue // We do this to ensure UI elements are accessed on the main thread and session configuration is done on the session queue - var previewLayer = (AVCaptureVideoPreviewLayer)PreviewView.Layer; + var previewLayer = (AVCaptureVideoPreviewLayer) PreviewView.Layer; AVCaptureVideoOrientation videoPreviewLayerVideoOrientation = previewLayer.Connection.VideoOrientation; AVCapturePhotoSettings settings = GetCurrentPhotoSettings (); @@ -897,7 +893,7 @@ void DidFinishProcessingRawPhoto (AVCapturePhotoOutput captureOutput, // This avoids using double the disk space during save, which can make a difference on devices with limited free disk space. var options = new PHAssetResourceCreationOptions (); options.ShouldMoveFile = true; - PHAssetCreationRequest.CreationRequestForAsset ().AddResource (PHAssetResourceType.Photo, new NSUrl(filePath), options); // Add move (not copy) option + PHAssetCreationRequest.CreationRequestForAsset ().AddResource (PHAssetResourceType.Photo, new NSUrl (filePath), options); // Add move (not copy) option }, (success, err) => { if (!success) Console.WriteLine ($"Error occurred while saving raw photo to photo library: {err}"); @@ -928,7 +924,7 @@ public void OnRecordClicked (NSObject sender) // Retrieve the video preview layer's video orientation on the main queue before entering the session queue. We do this to ensure UI // elements are accessed on the main thread and session configuration is done on the session queue. - var previewLayer = (AVCaptureVideoPreviewLayer)PreviewView.Layer; + var previewLayer = (AVCaptureVideoPreviewLayer) PreviewView.Layer; AVCaptureVideoOrientation previewLayerVideoOrientation = previewLayer.Connection.VideoOrientation; sessionQueue.DispatchAsync (() => { @@ -1016,7 +1012,7 @@ public void FinishedRecording (AVCaptureFileOutput captureOutput, NSUrl outputFi DispatchQueue.MainQueue.DispatchAsync (() => { // Only enable the ability to change camera if the device has more than one camera CameraButton.Enabled = (AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video).Length > 1); - RecordButton.Enabled = CaptureModeControl.SelectedSegment == (int)CaptureMode.Movie; + RecordButton.Enabled = CaptureModeControl.SelectedSegment == (int) CaptureMode.Movie; RecordButton.SetTitle ("Record", UIControlState.Normal); CaptureModeControl.Enabled = true; }); @@ -1034,7 +1030,7 @@ void AddObservers () focusModeToken = AddObserver ("videoDevice.focusMode", NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, FocusModeChanged); lensPositionToken = AddObserver ("videoDevice.lensPosition", NSKeyValueObservingOptions.New, LensPositionChanged); exposureModeToken = AddObserver ("videoDevice.exposureMode", NSKeyValueObservingOptions.Old | NSKeyValueObservingOptions.New, ExposureModeChanged); - exposureDurationToken = AddObserver ("videoDevice.exposureDuration", NSKeyValueObservingOptions.New, ExposureDurationChanged); + exposureDurationToken = AddObserver ("videoDevice.exposureDuration", NSKeyValueObservingOptions.New, ExposureDurationChanged); isoToken = AddObserver ("videoDevice.ISO", NSKeyValueObservingOptions.New, ISOChanged); exposureTargetBiasToken = AddObserver ("videoDevice.exposureTargetBias", NSKeyValueObservingOptions.New, ExposureTargetBiasChanged); exposureTargetOffsetToken = AddObserver ("videoDevice.exposureTargetOffset", NSKeyValueObservingOptions.New, ExposureTargetOffsetChanged); @@ -1048,8 +1044,8 @@ void AddObservers () // see also the documentation of AVCaptureSessionInterruptionReason. Add observers to handle these session interruptions // and show a preview is paused message. See the documentation of AVCaptureSessionWasInterruptedNotification for other // interruption reasons. - wasInterruptedToken = NSNotificationCenter.DefaultCenter.AddObserver (AVCaptureSession.WasInterruptedNotification, SessionWasInterrupted, Session); - interruptionEndedToken = NSNotificationCenter.DefaultCenter.AddObserver (AVCaptureSession.InterruptionEndedNotification, SessionInterruptionEnded, Session); + wasInterruptedToken = NSNotificationCenter.DefaultCenter.AddObserver (AVCaptureSession.WasInterruptedNotification, SessionWasInterrupted, Session); + interruptionEndedToken = NSNotificationCenter.DefaultCenter.AddObserver (AVCaptureSession.InterruptionEndedNotification, SessionInterruptionEnded, Session); } void RemoveObservers () @@ -1079,7 +1075,7 @@ void SessionRunningChanged (NSObservedChange obj) DispatchQueue.MainQueue.DispatchAsync (() => { CameraButton.Enabled = isRunning && (AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video).Length > 1); - RecordButton.Enabled = isRunning && (CaptureModeControl.SelectedSegment == (int)CaptureMode.Movie); + RecordButton.Enabled = isRunning && (CaptureModeControl.SelectedSegment == (int) CaptureMode.Movie); PhotoButton.Enabled = isRunning; HUDButton.Enabled = isRunning; CaptureModeControl.Enabled = isRunning; @@ -1092,13 +1088,13 @@ void FocusModeChanged (NSObservedChange obj) var oldValue = obj.OldValue; if (newValue != null && newValue != NSNull.Null) { - var newMode = (AVCaptureFocusMode)newValue.AsInt (); + var newMode = (AVCaptureFocusMode) newValue.AsInt (); DispatchQueue.MainQueue.DispatchAsync (() => { FocusModeControl.SelectedSegment = Array.IndexOf (focusModes, newMode); LensPositionSlider.Enabled = (newMode == AVCaptureFocusMode.Locked); if (oldValue != null && oldValue != NSNull.Null) { - var oldMode = (AVCaptureFocusMode)oldValue.AsInt (); + var oldMode = (AVCaptureFocusMode) oldValue.AsInt (); Console.WriteLine ($"focus mode: {StringFromFocusMode (oldMode)} -> {StringFromFocusMode (newMode)}"); } else { Console.WriteLine ($"focus mode: {StringFromFocusMode (newMode)}"); @@ -1127,9 +1123,9 @@ void ExposureModeChanged (NSObservedChange obj) var oldValue = obj.OldValue; if (newValue != null && newValue != NSNull.Null) { - var newMode = (AVCaptureExposureMode)newValue.AsInt (); + var newMode = (AVCaptureExposureMode) newValue.AsInt (); if (oldValue != null && oldValue != NSNull.Null) { - var oldMode = (AVCaptureExposureMode)oldValue.AsInt (); + var oldMode = (AVCaptureExposureMode) oldValue.AsInt (); // It’s important to understand the relationship between ExposureDuration and the minimum frame rate as represented by ActiveVideoMaxFrameDuration. // In manual mode, if ExposureDuration is set to a value that's greater than ActiveVideoMaxFrameDuration, then ActiveVideoMaxFrameDuration will @@ -1153,7 +1149,7 @@ void ExposureModeChanged (NSObservedChange obj) ISOSlider.Enabled = (newMode == AVCaptureExposureMode.Custom); if (oldValue != null && oldValue != NSNull.Null) { - var oldMode = (AVCaptureExposureMode)oldValue.AsInt (); + var oldMode = (AVCaptureExposureMode) oldValue.AsInt (); Console.WriteLine ($"exposure mode: {StringFromExposureMode (oldMode)} -> {StringFromExposureMode (newMode)}"); } else { Console.WriteLine ($"exposure mode: {StringFromExposureMode (newMode)}"); @@ -1177,7 +1173,7 @@ void ExposureDurationChanged (NSObservedChange obj) double p = (newDurationSeconds - minDurationSeconds) / (maxDurationSeconds - minDurationSeconds); // Scale to 0-1 DispatchQueue.MainQueue.DispatchAsync (() => { if (exposureMode != AVCaptureExposureMode.Custom) - ExposureDurationSlider.Value = (float)Math.Pow(p ,1 / ExposureDurationPower); // Apply inverse power + ExposureDurationSlider.Value = (float) Math.Pow (p, 1 / ExposureDurationPower); // Apply inverse power ExposureDurationValueLabel.Text = FormatDuration (newDurationSeconds); }); } @@ -1193,7 +1189,7 @@ void ISOChanged (NSObservedChange obj) DispatchQueue.MainQueue.DispatchAsync (() => { if (exposureMode != AVCaptureExposureMode.Custom) ISOSlider.Value = newISO; - ISOValueLabel.Text = ((int)newISO).ToString (CultureInfo.InvariantCulture); + ISOValueLabel.Text = ((int) newISO).ToString (CultureInfo.InvariantCulture); }); } } @@ -1227,14 +1223,14 @@ void WhiteBalanceModeChange (NSObservedChange obj) var oldValue = obj.OldValue; if (newValue != null && newValue != NSNull.Null) { - var newMode = (AVCaptureWhiteBalanceMode)newValue.AsInt (); + var newMode = (AVCaptureWhiteBalanceMode) newValue.AsInt (); DispatchQueue.MainQueue.DispatchAsync (() => { WhiteBalanceModeControl.SelectedSegment = Array.IndexOf (whiteBalanceModes, newMode); TemperatureSlider.Enabled = (newMode == AVCaptureWhiteBalanceMode.Locked); TintSlider.Enabled = (newMode == AVCaptureWhiteBalanceMode.Locked); if (oldValue != null && oldValue != NSNull.Null) { - var oldMode = (AVCaptureWhiteBalanceMode)oldValue.AsInt (); + var oldMode = (AVCaptureWhiteBalanceMode) oldValue.AsInt (); Console.WriteLine ($"white balance mode: {StringFromWhiteBalanceMode (oldMode)} -> {StringFromWhiteBalanceMode (newMode)}"); } }); @@ -1243,10 +1239,10 @@ void WhiteBalanceModeChange (NSObservedChange obj) unsafe void DeviceWhiteBalanceGainsChange (NSObservedChange obj) { - var gains = (NSValue)obj.NewValue; + var gains = (NSValue) obj.NewValue; if (gains != null) { AVCaptureWhiteBalanceGains newGains; - gains.StoreValueAtAddress ((IntPtr)(void*)&newGains); + gains.StoreValueAtAddress ((IntPtr) (void*) &newGains); AVCaptureWhiteBalanceTemperatureAndTintValues newTemperatureAndTint = VideoDevice.GetTemperatureAndTintValues (newGains); AVCaptureWhiteBalanceMode whiteBalanceMode = VideoDevice.WhiteBalanceMode; @@ -1257,8 +1253,8 @@ unsafe void DeviceWhiteBalanceGainsChange (NSObservedChange obj) } var ci = CultureInfo.InvariantCulture; - TemperatureValueLabel.Text = ((int)newTemperatureAndTint.Temperature).ToString (ci); - TintValueLabel.Text = ((int)newTemperatureAndTint.Tint).ToString (ci); + TemperatureValueLabel.Text = ((int) newTemperatureAndTint.Temperature).ToString (ci); + TintValueLabel.Text = ((int) newTemperatureAndTint.Tint).ToString (ci); }); } } @@ -1271,10 +1267,10 @@ void SubjectAreaDidChange (NSNotification obj) void SessionRuntimeError (NSNotification notification) { - var error = (NSError)notification.UserInfo [AVCaptureSession.ErrorKey]; + var error = (NSError) notification.UserInfo [AVCaptureSession.ErrorKey]; Console.WriteLine ($"Capture session runtime error: {error}"); - if (error.Code == (long)AVError.MediaServicesWereReset) { + if (error.Code == (long) AVError.MediaServicesWereReset) { sessionQueue.DispatchAsync (() => { // If we aren't trying to resume the session, try to restart it, since it must have been stopped due to an error (see -[resumeInterruptedSession:]) if (sessionRunning) { @@ -1299,7 +1295,7 @@ void SessionWasInterrupted (NSNotification notification) // Note that stopping music playback in Control Center will not automatically resume the session. // Also note that it is not always possible to resume, see ResumeInterruptedSession method. // In iOS 9 and later, the notification's UserInfo dictionary contains information about why the session was interrupted - var reason = (AVCaptureSessionInterruptionReason)notification.UserInfo [AVCaptureSession.InterruptionReasonKey].AsInt (); + var reason = (AVCaptureSessionInterruptionReason) notification.UserInfo [AVCaptureSession.InterruptionReasonKey].AsInt (); Console.WriteLine ($"Capture session was interrupted with reason {reason}"); if (reason == AVCaptureSessionInterruptionReason.AudioDeviceInUseByAnotherClient || @@ -1335,7 +1331,7 @@ string FormatDuration (double duration) if (duration < 1) { // e.x. 1/1000 1/350 etc - var digits = (int)Math.Max (0, 2 + Math.Floor (Math.Log10 (duration))); + var digits = (int) Math.Max (0, 2 + Math.Floor (Math.Log10 (duration))); string pattern = "1/{0:####." + new string ('0', digits) + "}"; return string.Format (pattern, 1.0 / duration, ci); } diff --git a/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController_Properties.cs b/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController_Properties.cs index ebb8a8d75..cbce40408 100644 --- a/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController_Properties.cs +++ b/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualCameraViewController_Properties.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; using Foundation; using AVFoundation; -namespace AVCamManual -{ - public partial class AVCamManualCameraViewController - { +namespace AVCamManual { + public partial class AVCamManualCameraViewController { // Higher numbers will give the slider more sensitivity at shorter durations const float ExposureDurationPower = 5; @@ -133,20 +131,20 @@ public partial class AVCamManualCameraViewController UISegmentedControl RawControl { get; set; } public AVCaptureSession Session { - [Export("session")] + [Export ("session")] get; - [Export("setSession:")] + [Export ("setSession:")] set; } AVCaptureDeviceInput videoDeviceInput; public AVCaptureDeviceInput VideoDeviceInput { - [Export("videoDeviceInput")] + [Export ("videoDeviceInput")] get { return videoDeviceInput; } - [Export("setVideoDeviceInput:")] + [Export ("setVideoDeviceInput:")] set { WillChangeValue ("videoDeviceInput"); videoDeviceInput = value; @@ -170,7 +168,7 @@ AVCaptureDevice VideoDevice { AVCaptureVideoPreviewLayer PreviewLayer { get { - return (AVCaptureVideoPreviewLayer)PreviewView.Layer; + return (AVCaptureVideoPreviewLayer) PreviewView.Layer; } } } diff --git a/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualPreviewView.cs b/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualPreviewView.cs index 16b454613..5c8b8f524 100644 --- a/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualPreviewView.cs +++ b/ios10/AVCamManual/AVCamManual/AVCamManual/AVCamManualPreviewView.cs @@ -5,11 +5,9 @@ using ObjCRuntime; using UIKit; -namespace AVCamManual -{ +namespace AVCamManual { [Register ("AVCamManualPreviewView")] - public class AVCamManualPreviewView : UIView - { + public class AVCamManualPreviewView : UIView { public static Class LayerClass { [Export ("layerClass")] get { @@ -19,10 +17,10 @@ public static Class LayerClass { public AVCaptureSession Session { get { - return ((AVCaptureVideoPreviewLayer)Layer).Session; + return ((AVCaptureVideoPreviewLayer) Layer).Session; } set { - ((AVCaptureVideoPreviewLayer)Layer).Session = value; + ((AVCaptureVideoPreviewLayer) Layer).Session = value; } } diff --git a/ios10/AVCamManual/AVCamManual/AppDelegate.cs b/ios10/AVCamManual/AVCamManual/AppDelegate.cs index 8bf9d1365..5d77a1760 100644 --- a/ios10/AVCamManual/AVCamManual/AppDelegate.cs +++ b/ios10/AVCamManual/AVCamManual/AppDelegate.cs @@ -1,11 +1,9 @@ using Foundation; using UIKit; -namespace AVCamManual -{ +namespace AVCamManual { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) diff --git a/ios10/AVCamManual/AVCamManual/Extensions/AVCaptureDeviceExtensions.cs b/ios10/AVCamManual/AVCamManual/Extensions/AVCaptureDeviceExtensions.cs index a87af3196..581627dc6 100644 --- a/ios10/AVCamManual/AVCamManual/Extensions/AVCaptureDeviceExtensions.cs +++ b/ios10/AVCamManual/AVCamManual/Extensions/AVCaptureDeviceExtensions.cs @@ -1,9 +1,7 @@ using AVFoundation; -namespace AVCamManual -{ - public static class AVCaptureDeviceExtensions - { +namespace AVCamManual { + public static class AVCaptureDeviceExtensions { public static bool TrySetFocusMode (this AVCaptureDevice device, AVCaptureFocusMode mode) { bool isSupported = device.IsFocusModeSupported (mode); diff --git a/ios10/AVCamManual/AVCamManual/Extensions/NSObjectExtensions.cs b/ios10/AVCamManual/AVCamManual/Extensions/NSObjectExtensions.cs index e2e00f7f0..285215da5 100644 --- a/ios10/AVCamManual/AVCamManual/Extensions/NSObjectExtensions.cs +++ b/ios10/AVCamManual/AVCamManual/Extensions/NSObjectExtensions.cs @@ -1,30 +1,28 @@ using CoreMedia; using Foundation; -namespace AVCamManual -{ - public static class NSObjectExtensions - { - public static int AsInt(this NSObject nsObj) +namespace AVCamManual { + public static class NSObjectExtensions { + public static int AsInt (this NSObject nsObj) { - var num = (NSNumber)nsObj; + var num = (NSNumber) nsObj; return num.Int32Value; } - public static float AsFloat(this NSObject nsObj) + public static float AsFloat (this NSObject nsObj) { - var num = (NSNumber)nsObj; + var num = (NSNumber) nsObj; return num.FloatValue; } - public static bool AsBool(this NSObject nsObj) + public static bool AsBool (this NSObject nsObj) { - return ((NSNumber)nsObj).BoolValue; + return ((NSNumber) nsObj).BoolValue; } public static CMTime AsCMTime (this NSObject nsObj) { - return ((NSValue)nsObj).CMTimeValue; + return ((NSValue) nsObj).CMTimeValue; } } } diff --git a/ios10/AVCamManual/AVCamManual/Main.cs b/ios10/AVCamManual/AVCamManual/Main.cs index 81d5afd72..84608e3ca 100644 --- a/ios10/AVCamManual/AVCamManual/Main.cs +++ b/ios10/AVCamManual/AVCamManual/Main.cs @@ -1,10 +1,8 @@ using UIKit; -namespace AVCamManual -{ - public class Application - { - static void Main (string[] args) +namespace AVCamManual { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios10/AutoWait/AutoWait/AppDelegate.cs b/ios10/AutoWait/AutoWait/AppDelegate.cs index 349c2a4a9..9c43b55ed 100644 --- a/ios10/AutoWait/AutoWait/AppDelegate.cs +++ b/ios10/AutoWait/AutoWait/AppDelegate.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; using Foundation; -namespace AutoWait -{ +namespace AutoWait { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) diff --git a/ios10/AutoWait/AutoWait/Main.cs b/ios10/AutoWait/AutoWait/Main.cs index c74be170a..500d5b236 100644 --- a/ios10/AutoWait/AutoWait/Main.cs +++ b/ios10/AutoWait/AutoWait/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace AutoWait -{ - public class Application - { +namespace AutoWait { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/AutoWait/AutoWait/UserInterface/MediaSelectionTableViewController.cs b/ios10/AutoWait/AutoWait/UserInterface/MediaSelectionTableViewController.cs index 1d885a82a..0cd7c6e08 100644 --- a/ios10/AutoWait/AutoWait/UserInterface/MediaSelectionTableViewController.cs +++ b/ios10/AutoWait/AutoWait/UserInterface/MediaSelectionTableViewController.cs @@ -2,16 +2,13 @@ using Foundation; using UIKit; -namespace AutoWait -{ - public struct MediaItem - { +namespace AutoWait { + public struct MediaItem { public string Name; public NSUrl Url; } - public partial class MediaSelectionTableViewController : UITableViewController - { + public partial class MediaSelectionTableViewController : UITableViewController { readonly MediaItem [] mediaItems = { new MediaItem { Name = "In the Woods", diff --git a/ios10/AutoWait/AutoWait/UserInterface/MediaViewController.cs b/ios10/AutoWait/AutoWait/UserInterface/MediaViewController.cs index db9da9334..a29835e74 100644 --- a/ios10/AutoWait/AutoWait/UserInterface/MediaViewController.cs +++ b/ios10/AutoWait/AutoWait/UserInterface/MediaViewController.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace AutoWait -{ - public partial class MediaViewController : UIViewController - { - [Outlet("stackView")] +namespace AutoWait { + public partial class MediaViewController : UIViewController { + [Outlet ("stackView")] UIStackView stackView { get; set; } PlaybackViewController playbackViewController; @@ -41,11 +39,11 @@ public override void ViewDidLoad () // Setup sub-view controllers. // 1) A PlaybackViewController for the video and playback controls. - playbackViewController = (PlaybackViewController)Storyboard.InstantiateViewController ("Playback"); + playbackViewController = (PlaybackViewController) Storyboard.InstantiateViewController ("Playback"); playbackViewController.Player = player; // 2) A PlaybackDetailsViewController for property values. - playbackDetailsViewController = (PlaybackDetailsViewController)Storyboard.InstantiateViewController ("PlaybackDetails"); + playbackDetailsViewController = (PlaybackDetailsViewController) Storyboard.InstantiateViewController ("PlaybackDetails"); playbackDetailsViewController.Player = player; // Add both new views to our stackView. diff --git a/ios10/AutoWait/AutoWait/UserInterface/PlaybackDetailsViewController.cs b/ios10/AutoWait/AutoWait/UserInterface/PlaybackDetailsViewController.cs index 98dceac50..95bff7cb6 100644 --- a/ios10/AutoWait/AutoWait/UserInterface/PlaybackDetailsViewController.cs +++ b/ios10/AutoWait/AutoWait/UserInterface/PlaybackDetailsViewController.cs @@ -8,10 +8,8 @@ using Foundation; using UIKit; -namespace AutoWait -{ - public partial class PlaybackDetailsViewController : UIViewController - { +namespace AutoWait { + public partial class PlaybackDetailsViewController : UIViewController { [Outlet ("rateLabel")] UILabel RateLabel { get; set; } @@ -182,7 +180,7 @@ IEnumerable<CMTimeRange> TimeRanges (NSValue [] values) static string Descr (IEnumerable<CMTimeRange> ranges) { // CMTimeRange -> [0.5s, 9.7s] - return string.Join (", ", ranges.Select (r => $"[{Seconds(r.Start)}, {Seconds(r.Start + r.Duration)}]")); + return string.Join (", ", ranges.Select (r => $"[{Seconds (r.Start)}, {Seconds (r.Start + r.Duration)}]")); } static string Seconds (CMTime time) diff --git a/ios10/AutoWait/AutoWait/UserInterface/PlaybackViewController.cs b/ios10/AutoWait/AutoWait/UserInterface/PlaybackViewController.cs index a0806c424..2d63948a5 100644 --- a/ios10/AutoWait/AutoWait/UserInterface/PlaybackViewController.cs +++ b/ios10/AutoWait/AutoWait/UserInterface/PlaybackViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace AutoWait -{ - public partial class PlaybackViewController : UIViewController - { +namespace AutoWait { + public partial class PlaybackViewController : UIViewController { [Outlet ("playerView")] PlayerView PlayerView { get; set; } @@ -56,7 +54,7 @@ public override void ViewDidLoad () // Load value for the automatic waiting switch from user defaults. AutomaticWaitingSwitch.On = NSUserDefaults.StandardUserDefaults.BoolForKey ("disableAutomaticWaiting"); - if(Player != null) + if (Player != null) Player.AutomaticallyWaitsToMinimizeStalling = AutomaticWaitingSwitch.On; var playerView = PlayerView; @@ -79,7 +77,7 @@ public override void ViewWillDisappear (bool animated) void toggleAutomaticWaiting (UISwitch sender) { // Check for the new value of the switch and update AVPlayer property and user defaults - if(Player != null) + if (Player != null) Player.AutomaticallyWaitsToMinimizeStalling = AutomaticWaitingSwitch.On; NSUserDefaults.StandardUserDefaults.SetBool (AutomaticWaitingSwitch.On, "disableAutomaticWaiting"); } @@ -96,10 +94,10 @@ void Play (NSObject sender) Player?.Play (); } - [Action("playImmediately:")] + [Action ("playImmediately:")] void playImmediately (NSObject sender) { - Player?.PlayImmediatelyAtRate(1); + Player?.PlayImmediatelyAtRate (1); } #endregion diff --git a/ios10/AutoWait/AutoWait/UserInterface/PlayerView.cs b/ios10/AutoWait/AutoWait/UserInterface/PlayerView.cs index a8e106b6a..209f3e501 100644 --- a/ios10/AutoWait/AutoWait/UserInterface/PlayerView.cs +++ b/ios10/AutoWait/AutoWait/UserInterface/PlayerView.cs @@ -5,10 +5,8 @@ using ObjCRuntime; using UIKit; -namespace AutoWait -{ - public partial class PlayerView : UIView - { +namespace AutoWait { + public partial class PlayerView : UIView { static Class layerClass; public static Class LayerClass { @@ -20,10 +18,10 @@ public static Class LayerClass { public AVPlayer Player { set { - ((AVPlayerLayer)Layer).Player = value; + ((AVPlayerLayer) Layer).Player = value; } get { - return ((AVPlayerLayer)Layer).Player; + return ((AVPlayerLayer) Layer).Player; } } diff --git a/ios10/DigitDetection/DigitDetection/AppDelegate.cs b/ios10/DigitDetection/DigitDetection/AppDelegate.cs index 7b18f339d..cde269be4 100644 --- a/ios10/DigitDetection/DigitDetection/AppDelegate.cs +++ b/ios10/DigitDetection/DigitDetection/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace DigitDetection -{ +namespace DigitDetection { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -13,4 +11,4 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } } -} \ No newline at end of file +} diff --git a/ios10/DigitDetection/DigitDetection/Atomics.cs b/ios10/DigitDetection/DigitDetection/Atomics.cs index 7414c6cf5..445b5c92f 100644 --- a/ios10/DigitDetection/DigitDetection/Atomics.cs +++ b/ios10/DigitDetection/DigitDetection/Atomics.cs @@ -1,9 +1,7 @@ -using System.Threading; +using System.Threading; -namespace DigitDetection -{ - public static class Atomics - { +namespace DigitDetection { + public static class Atomics { static int cnt; public static void Increment () diff --git a/ios10/DigitDetection/DigitDetection/DrawView.cs b/ios10/DigitDetection/DigitDetection/DrawView.cs index 005767ccb..5163f0b03 100644 --- a/ios10/DigitDetection/DigitDetection/DrawView.cs +++ b/ios10/DigitDetection/DigitDetection/DrawView.cs @@ -6,11 +6,9 @@ using Foundation; using CoreGraphics; -namespace DigitDetection -{ +namespace DigitDetection { // 2 points can give a line and this class is just for that purpose, it keeps a record of a lin - public class Line - { + public class Line { public CGPoint Start { get; } public CGPoint End { get; } @@ -22,8 +20,7 @@ public Line (CGPoint start, CGPoint end) } [Register ("DrawView")] - public class DrawView : UIView - { + public class DrawView : UIView { // some parameters of how thick a line to draw 15 seems to work // and we have white drawings on black background just like MNIST needs its input float lineWidth = 15f; @@ -59,12 +56,12 @@ public DrawView (IntPtr handle) public override void TouchesBegan (NSSet touches, UIEvent evt) { - lastPoint = ((UITouch)touches.First ()).LocationInView (this); + lastPoint = ((UITouch) touches.First ()).LocationInView (this); } public override void TouchesMoved (NSSet touches, UIEvent evt) { - var newPoint = ((UITouch)touches.First ()).LocationInView (this); + var newPoint = ((UITouch) touches.First ()).LocationInView (this); // keep all lines drawn by user as touch in record so we can draw them in view Lines.Add (new Line (lastPoint, newPoint)); @@ -112,4 +109,4 @@ public CGBitmapContext GetViewContext () return context; } } -} \ No newline at end of file +} diff --git a/ios10/DigitDetection/DigitDetection/MNISTData.cs b/ios10/DigitDetection/DigitDetection/MNISTData.cs index 15d3e9c7f..6683764a6 100644 --- a/ios10/DigitDetection/DigitDetection/MNISTData.cs +++ b/ios10/DigitDetection/DigitDetection/MNISTData.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.IO; using System.IO.MemoryMappedFiles; using Foundation; -namespace DigitDetection -{ - public class MNISTData : IDisposable - { +namespace DigitDetection { + public class MNISTData : IDisposable { public IntPtr Labels { get; private set; } public int LabelsCount { get; private set; } @@ -34,12 +32,12 @@ public MNISTData () byte* i = null; wView.SafeMemoryMappedViewHandle.AcquirePointer (ref i); // remove first 16 bytes that contain info data from array - Images = ((IntPtr)i) + 16; + Images = ((IntPtr) i) + 16; byte* l = null; bView.SafeMemoryMappedViewHandle.AcquirePointer (ref l); // remove first 8 bytes that contain file data from our labels array - Labels = (IntPtr)l + 8; + Labels = (IntPtr) l + 8; } } diff --git a/ios10/DigitDetection/DigitDetection/Main.cs b/ios10/DigitDetection/DigitDetection/Main.cs index e4a841eb8..3403e65d1 100644 --- a/ios10/DigitDetection/DigitDetection/Main.cs +++ b/ios10/DigitDetection/DigitDetection/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace DigitDetection -{ - public class Application - { +namespace DigitDetection { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCNNFullyConnected.cs b/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCNNFullyConnected.cs index b920c0851..6bb46f82a 100644 --- a/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCNNFullyConnected.cs +++ b/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCNNFullyConnected.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime.InteropServices; @@ -8,16 +8,14 @@ using MetalPerformanceShaders; using ObjCRuntime; -namespace DigitDetection -{ +namespace DigitDetection { /// <summary> /// The SlimMPSCnnFullyConnected is a wrapper class around MPSCnnFullyConnected used to encapsulate: /// - making an MPSCnnConvolutionDescriptor, /// - adding network parameters (weights and bias binaries by memory mapping the binaries) /// - getting our fullyConnected layer /// </summary> - public class SlimMPSCnnFullyConnected : MPSCnnFullyConnected - { + public class SlimMPSCnnFullyConnected : MPSCnnFullyConnected { // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=44938 [DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")] static extern IntPtr IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_UInt64 (IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2, IntPtr arg3, IntPtr arg4, ulong arg5); @@ -27,7 +25,7 @@ public class SlimMPSCnnFullyConnected : MPSCnnFullyConnected { var sel = "initWithDevice:convolutionDescriptor:kernelWeights:biasTerms:flags:"; var selector = Selector.GetHandle (sel); - InitializeHandle (IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_UInt64 (Handle, selector, device.Handle, convolutionDescriptor.Handle, kernelWeights, biasTerms, (ulong)flags), sel); + InitializeHandle (IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_UInt64 (Handle, selector, device.Handle, convolutionDescriptor.Handle, kernelWeights, biasTerms, (ulong) flags), sel); } public static SlimMPSCnnFullyConnected Create (uint kernelWidth, uint kernelHeight, @@ -40,8 +38,7 @@ public static SlimMPSCnnFullyConnected Create (uint kernelWidth, uint kernelHeig var wtPath = NSBundle.MainBundle.PathForResource ($"weights_{kernelParamsBinaryName}", "dat"); var bsPath = NSBundle.MainBundle.PathForResource ($"bias_{kernelParamsBinaryName}", "dat"); - unsafe - { + unsafe { using (var mmfW = MemoryMappedFile.CreateFromFile (wtPath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)) using (var mmfB = MemoryMappedFile.CreateFromFile (bsPath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)) using (var wView = mmfW.CreateViewAccessor (0, 0, MemoryMappedFileAccess.Read)) @@ -57,7 +54,7 @@ public static SlimMPSCnnFullyConnected Create (uint kernelWidth, uint kernelHeig inputFeatureChannels, outputFeatureChannels, neuronFilter); - return new SlimMPSCnnFullyConnected (device, convDesc, (IntPtr)w, (IntPtr)b, MPSCnnConvolutionFlags.None) { + return new SlimMPSCnnFullyConnected (device, convDesc, (IntPtr) w, (IntPtr) b, MPSCnnConvolutionFlags.None) { DestinationFeatureChannelOffset = destinationFeatureChannelOffset }; } diff --git a/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCnnConvolution.cs b/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCnnConvolution.cs index 5eece9d13..dde01fd8c 100644 --- a/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCnnConvolution.cs +++ b/ios10/DigitDetection/DigitDetection/MetalPerformanceShaders/SlimMPSCnnConvolution.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.IO.MemoryMappedFiles; using System.Runtime.InteropServices; @@ -8,16 +8,14 @@ using MetalPerformanceShaders; using ObjCRuntime; -namespace DigitDetection -{ +namespace DigitDetection { /// <summary> /// The SlimMPSCNNConvolution is a wrapper class around MPSCNNConvolution used to encapsulate: /// - making an MPSCNNConvolutionDescriptor, /// - adding network parameters (weights and bias binaries by memory mapping the binaries) /// - getting our convolution layer /// </summary> - public class SlimMPSCnnConvolution : MPSCnnConvolution - { + public class SlimMPSCnnConvolution : MPSCnnConvolution { // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=44938 [DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")] static extern IntPtr IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_UInt64 (IntPtr receiver, IntPtr selector, IntPtr arg1, IntPtr arg2, IntPtr arg3, IntPtr arg4, ulong arg5); @@ -29,7 +27,7 @@ unsafe SlimMPSCnnConvolution (IMTLDevice device, MPSCnnConvolutionDescriptor con : base (NSObjectFlag.Empty) { const string sel = "initWithDevice:convolutionDescriptor:kernelWeights:biasTerms:flags:"; - InitializeHandle (IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_UInt64 (Handle, Selector.GetHandle (sel), device.Handle, convolutionDescriptor.Handle, kernelWeights, biasTerms, (ulong)flags), sel); + InitializeHandle (IntPtr_objc_msgSend_IntPtr_IntPtr_IntPtr_IntPtr_UInt64 (Handle, Selector.GetHandle (sel), device.Handle, convolutionDescriptor.Handle, kernelWeights, biasTerms, (ulong) flags), sel); } /// <summary> @@ -52,7 +50,7 @@ public static SlimMPSCnnConvolution Create (uint kernelWidth, uint kernelHeight, uint inputFeatureChannels, uint outputFeatureChannels, MPSCnnNeuron neuronFilter, IMTLDevice device, string kernelParamsBinaryName, bool padding, - uint strideX, uint strideY, + uint strideX, uint strideY, uint destinationFeatureChannelOffset, uint groupNum) { // get the url to this layer's weights and bias @@ -71,8 +69,7 @@ public static SlimMPSCnnConvolution Create (uint kernelWidth, uint kernelHeight, throw new ArgumentException ("Group size can't be less than 1"); convDesc.Groups = groupNum; - unsafe - { + unsafe { using (var mmfW = MemoryMappedFile.CreateFromFile (wtPath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)) using (var mmfB = MemoryMappedFile.CreateFromFile (bsPath, FileMode.Open, null, 0, MemoryMappedFileAccess.Read)) using (var wView = mmfW.CreateViewAccessor (0, 0, MemoryMappedFileAccess.Read)) @@ -83,7 +80,7 @@ public static SlimMPSCnnConvolution Create (uint kernelWidth, uint kernelHeight, byte* b = null; bView.SafeMemoryMappedViewHandle.AcquirePointer (ref b); - return new SlimMPSCnnConvolution (device, convDesc, (IntPtr)w, (IntPtr)b, MPSCnnConvolutionFlags.None) { + return new SlimMPSCnnConvolution (device, convDesc, (IntPtr) w, (IntPtr) b, MPSCnnConvolutionFlags.None) { DestinationFeatureChannelOffset = destinationFeatureChannelOffset, padding = padding }; @@ -109,14 +106,14 @@ public override void EncodeToCommandBuffer (IMTLCommandBuffer commandBuffer, MPS var pad_left = pad_along_width / 2; Offset = new MPSOffset { - X = (nint)(KernelWidth / 2 - pad_left), - Y = (nint)(KernelHeight / 2 - pad_top), + X = (nint) (KernelWidth / 2 - pad_left), + Y = (nint) (KernelHeight / 2 - pad_top), Z = 0 }; } else { Offset = new MPSOffset { - X = (nint)(KernelWidth / 2), - Y = (nint)(KernelHeight / 2), + X = (nint) (KernelWidth / 2), + Y = (nint) (KernelHeight / 2), Z = 0 }; } diff --git a/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistDeepConvNeuralNetwork.cs b/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistDeepConvNeuralNetwork.cs index 533792b7f..8894eaf31 100644 --- a/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistDeepConvNeuralNetwork.cs +++ b/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistDeepConvNeuralNetwork.cs @@ -1,10 +1,8 @@ -using Metal; +using Metal; using MetalPerformanceShaders; -namespace DigitDetection -{ - public class MnistDeepConvNeuralNetwork : MnistFullLayerNeuralNetwork - { +namespace DigitDetection { + public class MnistDeepConvNeuralNetwork : MnistFullLayerNeuralNetwork { // MPSImageDescriptors for different layers outputs to be put in readonly MPSImageDescriptor c1id = MPSImageDescriptor.GetImageDescriptor (MPSImageFeatureChannelFormat.Float16, 28, 28, 32); readonly MPSImageDescriptor p1id = MPSImageDescriptor.GetImageDescriptor (MPSImageFeatureChannelFormat.Float16, 14, 14, 32); diff --git a/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistFullLayerNeuralNetwork.cs b/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistFullLayerNeuralNetwork.cs index be9ce6f92..ce094d8bc 100644 --- a/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistFullLayerNeuralNetwork.cs +++ b/ios10/DigitDetection/DigitDetection/NeuralNetworkLayers/MnistFullLayerNeuralNetwork.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Runtime.InteropServices; using Accelerate; @@ -6,19 +6,17 @@ using MetalPerformanceShaders; using ObjCRuntime; -namespace DigitDetection -{ +namespace DigitDetection { // This class has our entire network with all layers to getting the final label // Resources // https://www.tensorflow.org/versions/r0.8/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners to run this network on TensorFlow. - public class MnistFullLayerNeuralNetwork - { + public class MnistFullLayerNeuralNetwork { // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=45009 [DllImport (Constants.AccelerateImageLibrary)] extern static nint vImageConvert_Planar16FtoPlanarF (ref vImageBuffer src, ref vImageBuffer dest, vImageFlags flags); unsafe public static vImageError Planar16FtoPlanarF (ref vImageBuffer src, ref vImageBuffer dest, vImageFlags flags) { - return (vImageError)(long)vImageConvert_Planar16FtoPlanarF (ref src, ref dest, flags); + return (vImageError) (long) vImageConvert_Planar16FtoPlanarF (ref src, ref dest, flags); } // MPSImageDescriptors for different layers outputs to be put in @@ -103,7 +101,7 @@ public virtual uint Forward (MPSImage inputImage = null, int imageNum = 9999, in public uint GetLabel (MPSImage finalLayer) { // even though we have 10 labels outputed the MTLTexture format used is RGBAFloat16 thus 3 slices will have 3*4 = 12 outputs - var resultHalfArray = Enumerable.Repeat ((ushort)6, 12).ToArray (); + var resultHalfArray = Enumerable.Repeat ((ushort) 6, 12).ToArray (); var resultHalfArrayHandle = GCHandle.Alloc (resultHalfArray, GCHandleType.Pinned); var resultHalfArrayPtr = resultHalfArrayHandle.AddrOfPinnedObject (); @@ -112,7 +110,7 @@ public uint GetLabel (MPSImage finalLayer) var resultFloatArrayPtr = resultFloatArrayHandle.AddrOfPinnedObject (); for (uint i = 0; i <= 2; i++) { - finalLayer.Texture.GetBytes (resultHalfArrayPtr + 4 * (int)i * sizeof (ushort), + finalLayer.Texture.GetBytes (resultHalfArrayPtr + 4 * (int) i * sizeof (ushort), sizeof (ushort) * 1 * 4, sizeof (ushort) * 1 * 1 * 4, new MTLRegion (new MTLOrigin (0, 0, 0), new MTLSize (1, 1, 1)), 0, i); diff --git a/ios10/DigitDetection/DigitDetection/ViewController.cs b/ios10/DigitDetection/DigitDetection/ViewController.cs index 74ff5788c..a90da8937 100644 --- a/ios10/DigitDetection/DigitDetection/ViewController.cs +++ b/ios10/DigitDetection/DigitDetection/ViewController.cs @@ -5,10 +5,8 @@ using Metal; using MetalPerformanceShaders; -namespace DigitDetection -{ - public partial class ViewController : UIViewController - { +namespace DigitDetection { + public partial class ViewController : UIViewController { // some properties used to control the app and store appropriate values // we will start with the simple 1 layer bool deep; @@ -118,7 +116,7 @@ partial void TappedDetectDigit (UIButton sender) throw new InvalidProgramException (); // putting input into MTLTexture in the MPSImage - var region = new MTLRegion (new MTLOrigin (0, 0, 0), new MTLSize ((nint)mnistInputWidth, mnistInputHeight, 1)); + var region = new MTLRegion (new MTLOrigin (0, 0, 0), new MTLSize ((nint) mnistInputWidth, mnistInputHeight, 1)); runningNet.SrcImage.Texture.ReplaceRegion (region, level: 0, slice: 0, @@ -147,7 +145,7 @@ void Inference (int imageNum, int correctLabel) var inputImage = new MPSImage (device, runningNet.SID); // put image in source texture (input layer) - inputImage.Texture.ReplaceRegion (region: new MTLRegion (new MTLOrigin (0, 0, 0), new MTLSize ((nint)mnistInputWidth, mnistInputHeight, 1)), + inputImage.Texture.ReplaceRegion (region: new MTLRegion (new MTLOrigin (0, 0, 0), new MTLSize ((nint) mnistInputWidth, mnistInputHeight, 1)), level: 0, slice: 0, pixelBytes: Mnistdata.Images + startIndex, @@ -158,4 +156,4 @@ void Inference (int imageNum, int correctLabel) runningNet.Forward (inputImage, imageNum, correctLabel); } } -} \ No newline at end of file +} diff --git a/ios10/ElizaChat/ElizaChat/AppDelegate.cs b/ios10/ElizaChat/ElizaChat/AppDelegate.cs index 06c7dc7a2..eb76ffabe 100644 --- a/ios10/ElizaChat/ElizaChat/AppDelegate.cs +++ b/ios10/ElizaChat/ElizaChat/AppDelegate.cs @@ -1,17 +1,15 @@ -using Foundation; +using Foundation; using UIKit; using Intents; using System; using ElizaCore; using UserNotifications; -namespace ElizaChat -{ +namespace ElizaChat { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { #region Computed Properties public override UIWindow Window { get; set; } public ViewController Controller { get; set; } @@ -62,7 +60,7 @@ public override bool ContinueUserActivity (UIApplication application, NSUserActi switch (userActivity.ActivityType) { case "com.appracatappra.askquestion": // Pass question to Eliza to answer - Controller.AskQuestion (userActivity.UserInfo.ValueForKey (new NSString ("question")).ToString(), true); + Controller.AskQuestion (userActivity.UserInfo.ValueForKey (new NSString ("question")).ToString (), true); break; } diff --git a/ios10/ElizaChat/ElizaChat/Main.cs b/ios10/ElizaChat/ElizaChat/Main.cs index c0f856af7..9dad7265e 100644 --- a/ios10/ElizaChat/ElizaChat/Main.cs +++ b/ios10/ElizaChat/ElizaChat/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace ElizaChat -{ - public class Application - { +namespace ElizaChat { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/ElizaChat/ElizaChat/ViewController.cs b/ios10/ElizaChat/ElizaChat/ViewController.cs index e2998c5b0..4c484c710 100644 --- a/ios10/ElizaChat/ElizaChat/ViewController.cs +++ b/ios10/ElizaChat/ElizaChat/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using ElizaCore; using Foundation; @@ -6,13 +6,11 @@ using System.Threading; using UserNotifications; -namespace ElizaChat -{ - public partial class ViewController : UIViewController - { +namespace ElizaChat { + public partial class ViewController : UIViewController { #region AppDelegate Access public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -105,18 +103,21 @@ public override void ViewDidLoad () }); // Wireup events - ChatInput.ShouldBeginEditing = delegate (UITextField field) { + ChatInput.ShouldBeginEditing = delegate (UITextField field) + { //Placeholder return true; }; - ChatInput.ShouldReturn = delegate (UITextField field) { + ChatInput.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); AskQuestion (field.Text, false); return true; }; - ChatInput.ShouldEndEditing = delegate (UITextField field) { + ChatInput.ShouldEndEditing = delegate (UITextField field) + { AskQuestion (field.Text, false); return true; }; diff --git a/ios10/ElizaChat/ElizaChatIntent/IntentHandler.cs b/ios10/ElizaChat/ElizaChatIntent/IntentHandler.cs index c622c53fb..15d9e962c 100644 --- a/ios10/ElizaChat/ElizaChatIntent/IntentHandler.cs +++ b/ios10/ElizaChat/ElizaChatIntent/IntentHandler.cs @@ -1,11 +1,10 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using Intents; using ElizaCore; -namespace ElizaChatIntent -{ +namespace ElizaChatIntent { // As an example, this class is set up to handle Message intents. // You will want to replace this or add other intents as appropriate. // The intents you wish to handle must be declared in the extension's Info.plist. @@ -15,8 +14,7 @@ namespace ElizaChatIntent // "<myApp> John saying hello" // "Search for messages in <myApp>" [Register ("IntentHandler")] - public class IntentHandler : INExtension, IINSendMessageIntentHandling, IINSearchForMessagesIntentHandling, IINSetMessageAttributeIntentHandling - { + public class IntentHandler : INExtension, IINSendMessageIntentHandling, IINSearchForMessagesIntentHandling, IINSetMessageAttributeIntentHandling { #region Computed Properties public ElizaAddressBook AddressBook { get; set; } = new ElizaAddressBook (); public ElizaMain Eliza { get; set; } = new ElizaMain (); @@ -67,7 +65,7 @@ public void ResolveRecipients (INSendMessageIntent intent, Action<INPersonResolu break; case 1: // We have exactly one matching contact - resolutionResults.Add (INPersonResolutionResult.GetSuccess (matchingContacts[0])); + resolutionResults.Add (INPersonResolutionResult.GetSuccess (matchingContacts [0])); break; default: // We need Siri's help to ask user to pick one from the matches. diff --git a/ios10/ElizaChat/ElizaChatIntentUI/IntentViewController.cs b/ios10/ElizaChat/ElizaChatIntentUI/IntentViewController.cs index 6189ccf36..e85b75ac3 100644 --- a/ios10/ElizaChat/ElizaChatIntentUI/IntentViewController.cs +++ b/ios10/ElizaChat/ElizaChatIntentUI/IntentViewController.cs @@ -1,20 +1,18 @@ -using System; +using System; using CoreGraphics; using Intents; using IntentsUI; using UIKit; -namespace ElizaChatIntentUI -{ +namespace ElizaChatIntentUI { // As an example, this extension's Info.plist has been configured to handle interactions for INSendMessageIntent. // You will want to replace this or add other intents as appropriate. // The intents whose interactions you wish to handle must be declared in the extension's Info.plist. // You can test this example integration by saying things to Siri like: // "Send a message using <myApp>" - public partial class IntentViewController : UIViewController, IINUIHostedViewControlling - { + public partial class IntentViewController : UIViewController, IINUIHostedViewControlling { protected IntentViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. diff --git a/ios10/ElizaChat/ElizaCore/Classes/Decomp.cs b/ios10/ElizaChat/ElizaCore/Classes/Decomp.cs index 38d1d4232..ffe547bf7 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/Decomp.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/Decomp.cs @@ -3,11 +3,9 @@ using System; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza decomposition rule</summary> - public class Decomp - { + public class Decomp { /// <summary>The decomp pattern</summary> internal string pattern; @@ -21,7 +19,7 @@ public class Decomp internal int currReasmb; /// <summary>Initialize the decomp rule</summary> - internal Decomp(string pattern, bool mem, ReasembList reasemb) + internal Decomp (string pattern, bool mem, ReasembList reasemb) { this.pattern = pattern; this.mem = mem; @@ -31,41 +29,39 @@ internal Decomp(string pattern, bool mem, ReasembList reasemb) /// <summary>Print out the decomp rule.</summary> /// <remarks>Print out the decomp rule.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { string m = mem ? "true" : "false"; - for (int i = 0; i < indent; i++) - { - ConsoleSurrogate.Write(" "); + for (int i = 0; i < indent; i++) { + ConsoleSurrogate.Write (" "); } - ConsoleSurrogate.WriteLine("decomp: " + pattern + " " + m); - reasemb.Print(indent + 2); + ConsoleSurrogate.WriteLine ("decomp: " + pattern + " " + m); + reasemb.Print (indent + 2); } /// <summary>Get the pattern.</summary> /// <remarks>Get the pattern.</remarks> - public virtual string Pattern() + public virtual string Pattern () { return pattern; } /// <summary>Get the mem flag.</summary> /// <remarks>Get the mem flag.</remarks> - public virtual bool Mem() + public virtual bool Mem () { return mem; } /// <summary>Get the next reassembly rule.</summary> /// <remarks>Get the next reassembly rule.</remarks> - public virtual string NextRule() + public virtual string NextRule () { - if (reasemb.Count == 0) - { - ConsoleSurrogate.WriteLine("No reassembly rule."); + if (reasemb.Count == 0) { + ConsoleSurrogate.WriteLine ("No reassembly rule."); return null; } - return (string)reasemb[currReasmb]; + return (string) reasemb [currReasmb]; } /// <summary>Step to the next reassembly rule.</summary> @@ -73,17 +69,15 @@ public virtual string NextRule() /// Step to the next reassembly rule. /// If mem is true, pick a random rule. /// </remarks> - public virtual void StepRule() + public virtual void StepRule () { int size = reasemb.Count; - if (mem) - { - currReasmb = (int)(new Random().Next() * size); + if (mem) { + currReasmb = (int) (new Random ().Next () * size); } // Increment and make sure it is within range. currReasmb++; - if (currReasmb >= size) - { + if (currReasmb >= size) { currReasmb = 0; } } diff --git a/ios10/ElizaChat/ElizaCore/Classes/DecompList.cs b/ios10/ElizaChat/ElizaCore/Classes/DecompList.cs index a3ca510fd..a83cebee7 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/DecompList.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/DecompList.cs @@ -3,30 +3,27 @@ using System.Collections.Generic; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza decomp list.</summary> /// <remarks> /// Eliza decomp list. /// This stores all the decompositions of a single key. /// </remarks> - public class DecompList : List<Decomp> - { + public class DecompList : List<Decomp> { /// <summary>Add another decomp rule to the list.</summary> /// <remarks>Add another decomp rule to the list.</remarks> - public virtual void Add(string word, bool mem, ReasembList reasmb) + public virtual void Add (string word, bool mem, ReasembList reasmb) { - Add(new Decomp(word, mem, reasmb)); + Add (new Decomp (word, mem, reasmb)); } /// <summary>Print the whole decomp list.</summary> /// <remarks>Print the whole decomp list.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < Count; i++) - { - Decomp d = (Decomp)this[i]; - d.Print(indent); + for (int i = 0; i < Count; i++) { + Decomp d = (Decomp) this [i]; + d.Print (indent); } } } diff --git a/ios10/ElizaChat/ElizaCore/Classes/ElizaMain.cs b/ios10/ElizaChat/ElizaCore/Classes/ElizaMain.cs index 7fc27c9ed..de7bdb8d1 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/ElizaMain.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/ElizaMain.cs @@ -3,15 +3,13 @@ using System; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza main class.</summary> /// <remarks> /// Eliza main class. Stores the processed script. Does the input /// transformations. /// </remarks> - public class ElizaMain - { + public class ElizaMain { internal readonly bool echoInput = false; internal readonly bool printData = false; @@ -25,16 +23,16 @@ public class ElizaMain internal readonly bool printInitialFinal = false; /// <summary>The key list</summary> - internal KeyList keys = new KeyList(); + internal KeyList keys = new KeyList (); /// <summary>The syn list</summary> - internal SynList syns = new SynList(); + internal SynList syns = new SynList (); /// <summary>The pre list</summary> - internal PrePostList pre = new PrePostList(); + internal PrePostList pre = new PrePostList (); /// <summary>The post list</summary> - internal PrePostList post = new PrePostList(); + internal PrePostList post = new PrePostList (); /// <summary>Initial string</summary> internal string initial = "Hello."; @@ -43,13 +41,13 @@ public class ElizaMain internal string finl = "Goodbye."; /// <summary>Quit list</summary> - internal WordList quit = new WordList(); + internal WordList quit = new WordList (); /// <summary>Key stack</summary> - internal KeyStack keyStack = new KeyStack(); + internal KeyStack keyStack = new KeyStack (); /// <summary>Memory</summary> - internal Mem mem = new Mem(); + internal Mem mem = new Mem (); internal DecompList lastDecomp; @@ -63,130 +61,91 @@ public class ElizaMain internal const int gotoRule = 2; - public ElizaMain() : this(new LineSourceFromAssembly("ElizaScript.txt")){ + public ElizaMain () : this (new LineSourceFromAssembly ("ElizaScript.txt")) + { } - public ElizaMain(ILineSource linesource) + public ElizaMain (ILineSource linesource) { - ReadScript(linesource); + ReadScript (linesource); } - public virtual bool IsFinished() + public virtual bool IsFinished () { return finished; } /// <summary>Process a line of script input.</summary> /// <remarks>Process a line of script input.</remarks> - private void Collect(string s) + private void Collect (string s) { - string[] lines = new string[4]; - if (EString.Match(s, "*reasmb: *", lines)) - { - if (lastReasemb == null) - { - ConsoleSurrogate.WriteLine("Error: no last reasemb"); + string [] lines = new string [4]; + if (EString.Match (s, "*reasmb: *", lines)) { + if (lastReasemb == null) { + ConsoleSurrogate.WriteLine ("Error: no last reasemb"); return; } - lastReasemb.Add(lines[1]); - } - else - { - if (EString.Match(s, "*decomp: *", lines)) - { - if (lastDecomp == null) - { - ConsoleSurrogate.WriteLine("Error: no last decomp"); + lastReasemb.Add (lines [1]); + } else { + if (EString.Match (s, "*decomp: *", lines)) { + if (lastDecomp == null) { + ConsoleSurrogate.WriteLine ("Error: no last decomp"); return; } - lastReasemb = new ReasembList(); - string temp = lines[1]; - if (EString.Match(temp, "$ *", lines)) - { - lastDecomp.Add(lines[0], true, lastReasemb); + lastReasemb = new ReasembList (); + string temp = lines [1]; + if (EString.Match (temp, "$ *", lines)) { + lastDecomp.Add (lines [0], true, lastReasemb); + } else { + lastDecomp.Add (temp, false, lastReasemb); } - else - { - lastDecomp.Add(temp, false, lastReasemb); - } - } - else - { - if (EString.Match(s, "*key: * #*", lines)) - { - lastDecomp = new DecompList(); + } else { + if (EString.Match (s, "*key: * #*", lines)) { + lastDecomp = new DecompList (); lastReasemb = null; int n = 0; - if (lines[2].Length != 0) - { - try - { - n = int.Parse(lines[2]); - } - catch (FormatException) - { - ConsoleSurrogate.WriteLine("Number is wrong in key: " + lines[2]); + if (lines [2].Length != 0) { + try { + n = int.Parse (lines [2]); + } catch (FormatException) { + ConsoleSurrogate.WriteLine ("Number is wrong in key: " + lines [2]); } } - keys.Add(lines[1], n, lastDecomp); - } - else - { - if (EString.Match(s, "*key: *", lines)) - { - lastDecomp = new DecompList(); + keys.Add (lines [1], n, lastDecomp); + } else { + if (EString.Match (s, "*key: *", lines)) { + lastDecomp = new DecompList (); lastReasemb = null; - keys.Add(lines[1], 0, lastDecomp); - } - else - { - if (EString.Match(s, "*synon: * *", lines)) - { - WordList words = new WordList(); - words.Add(lines[1]); - s = lines[2]; - while (EString.Match(s, "* *", lines)) - { - words.Add(lines[0]); - s = lines[1]; + keys.Add (lines [1], 0, lastDecomp); + } else { + if (EString.Match (s, "*synon: * *", lines)) { + WordList words = new WordList (); + words.Add (lines [1]); + s = lines [2]; + while (EString.Match (s, "* *", lines)) { + words.Add (lines [0]); + s = lines [1]; } - words.Add(s); - syns.Add(words); - } - else - { - if (EString.Match(s, "*pre: * *", lines)) - { - pre.Add(lines[1], lines[2]); - } - else - { - if (EString.Match(s, "*post: * *", lines)) - { - post.Add(lines[1], lines[2]); - } - else - { - if (EString.Match(s, "*initial: *", lines)) - { - initial = lines[1]; - } - else - { - if (EString.Match(s, "*final: *", lines)) - { - finl = lines[1]; - } - else - { - if (EString.Match(s, "*quit: *", lines)) - { - quit.Add(" " + lines[1] + " "); - } - else - { - ConsoleSurrogate.WriteLine("Unrecognized input: " + s); + words.Add (s); + syns.Add (words); + } else { + if (EString.Match (s, "*pre: * *", lines)) { + pre.Add (lines [1], lines [2]); + } else { + if (EString.Match (s, "*post: * *", lines)) { + post.Add (lines [1], lines [2]); + } else { + if (EString.Match (s, "*initial: *", lines)) { + initial = lines [1]; + } else { + if (EString.Match (s, "*final: *", lines)) { + finl = lines [1]; + } else { + if (EString.Match (s, "*quit: *", lines)) { + quit.Add (" " + lines [1] + " "); + } else { + ConsoleSurrogate.WriteLine ("Unrecognized input: " + s); } } } @@ -201,50 +160,43 @@ private void Collect(string s) /// <summary>Process a line of input.</summary> /// <remarks>Process a line of input.</remarks> - public virtual string ProcessInput(string s) + public virtual string ProcessInput (string s) { string reply; // Do some input transformations first. - s = EString.Translate(s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" + s = EString.Translate (s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" ); - s = EString.Translate(s, "@#$%^&*()_-+=~`{[}]|:;<>\\\"", " " + s = EString.Translate (s, "@#$%^&*()_-+=~`{[}]|:;<>\\\"", " " ); - s = EString.Translate(s, ",?!", "..."); + s = EString.Translate (s, ",?!", "..."); // Compress out multiple speace. - s = EString.Compress(s); - string[] lines = new string[2]; + s = EString.Compress (s); + string [] lines = new string [2]; // Break apart sentences, and do each separately. - while (EString.Match(s, "*.*", lines)) - { - reply = Sentence(lines[0]); - if (reply != null) - { + while (EString.Match (s, "*.*", lines)) { + reply = Sentence (lines [0]); + if (reply != null) { return reply; } - s = EString.Trim(lines[1]); + s = EString.Trim (lines [1]); } - if (s.Length != 0) - { - reply = Sentence(s); - if (reply != null) - { + if (s.Length != 0) { + reply = Sentence (s); + if (reply != null) { return reply; } } // Nothing matched, so try memory. - string m = mem.Get(); - if (m != null) - { + string m = mem.Get (); + if (m != null) { return m; } // No memory, reply with xnone. - Key key = keys.GetKey("xnone"); - if (key != null) - { + Key key = keys.GetKey ("xnone"); + if (key != null) { Key dummy = null; - reply = Decompose(key, s, dummy); - if (reply != null) - { + reply = Decompose (key, s, dummy); + if (reply != null) { return reply; } } @@ -258,30 +210,25 @@ public virtual string ProcessInput(string s) /// word. (3) Scan sentence for keys, build key stack. (4) Try decompositions /// for each key. /// </remarks> - private string Sentence(string s) + private string Sentence (string s) { - s = pre.Translate(s); - s = EString.Pad(s); - if (quit.Find(s)) - { + s = pre.Translate (s); + s = EString.Pad (s); + if (quit.Find (s)) { finished = true; return finl; } - keys.BuildKeyStack(keyStack, s); - for (int i = 0; i < keyStack.KeyTop(); i++) - { - Key gotoKey = new Key(); - string reply = Decompose(keyStack.Key(i), s, gotoKey); - if (reply != null) - { + keys.BuildKeyStack (keyStack, s); + for (int i = 0; i < keyStack.KeyTop (); i++) { + Key gotoKey = new Key (); + string reply = Decompose (keyStack.Key (i), s, gotoKey); + if (reply != null) { return reply; } // If decomposition returned gotoKey, try it - while (gotoKey.GetKey() != null) - { - reply = Decompose(gotoKey, s, gotoKey); - if (reply != null) - { + while (gotoKey.GetKey () != null) { + reply = Decompose (gotoKey, s, gotoKey); + if (reply != null) { return reply; } } @@ -296,22 +243,18 @@ private string Sentence(string s) /// fails, try another decomposition rule. If assembly is a goto rule, return /// null and give the key. If assembly succeeds, return the reply; /// </remarks> - private string Decompose(Key key, string s, Key gotoKey) + private string Decompose (Key key, string s, Key gotoKey) { - string[] reply = new string[10]; - for (int i = 0; i < key.Decomp().Count; i++) - { - Decomp d = (Decomp)key.Decomp()[i]; - string pat = d.Pattern(); - if (syns.MatchDecomp(s, pat, reply)) - { - string rep = Assemble(d, reply, gotoKey); - if (rep != null) - { + string [] reply = new string [10]; + for (int i = 0; i < key.Decomp ().Count; i++) { + Decomp d = (Decomp) key.Decomp () [i]; + string pat = d.Pattern (); + if (syns.MatchDecomp (s, pat, reply)) { + string rep = Assemble (d, reply, gotoKey); + if (rep != null) { return rep; } - if (gotoKey.GetKey() != null) - { + if (gotoKey.GetKey () != null) { return null; } } @@ -325,73 +268,60 @@ private string Decompose(Key key, string s, Key gotoKey) /// is goto, return null and give the gotoKey to use. Otherwise return the /// response. /// </remarks> - private string Assemble(Decomp d, string[] reply, Key gotoKey) + private string Assemble (Decomp d, string [] reply, Key gotoKey) { - string[] lines = new string[3]; - d.StepRule(); - string rule = d.NextRule(); - if (EString.Match(rule, "goto *", lines)) - { + string [] lines = new string [3]; + d.StepRule (); + string rule = d.NextRule (); + if (EString.Match (rule, "goto *", lines)) { // goto rule -- set gotoKey and return false. - gotoKey.Copy(keys.GetKey(lines[0])); - if (gotoKey.GetKey() != null) - { + gotoKey.Copy (keys.GetKey (lines [0])); + if (gotoKey.GetKey () != null) { return null; } - ConsoleSurrogate.WriteLine("Goto rule did not match key: " + lines[0]); + ConsoleSurrogate.WriteLine ("Goto rule did not match key: " + lines [0]); return null; } string work = string.Empty; - while (EString.Match(rule, "* (#)*", lines)) - { + while (EString.Match (rule, "* (#)*", lines)) { // reassembly rule with number substitution - rule = lines[2]; + rule = lines [2]; // there might be more int n = 0; - try - { - n = int.Parse(lines[1]) - 1; - } - catch (FormatException) - { - ConsoleSurrogate.WriteLine("Number is wrong in reassembly rule " + lines[1]); + try { + n = int.Parse (lines [1]) - 1; + } catch (FormatException) { + ConsoleSurrogate.WriteLine ("Number is wrong in reassembly rule " + lines [1]); } - if (n < 0 || n >= reply.Length) - { - ConsoleSurrogate.WriteLine("Substitution number is bad " + lines[1]); + if (n < 0 || n >= reply.Length) { + ConsoleSurrogate.WriteLine ("Substitution number is bad " + lines [1]); return null; } - reply[n] = post.Translate(reply[n]); - work += lines[0] + " " + reply[n]; + reply [n] = post.Translate (reply [n]); + work += lines [0] + " " + reply [n]; } work += rule; - if (d.Mem()) - { - mem.Save(work); + if (d.Mem ()) { + mem.Save (work); return null; } return work; } - private int ReadScript(ILineSource linesource) + private int ReadScript (ILineSource linesource) { - try - { - while (true) - { + try { + while (true) { string s; - s = linesource.ReadLine(); - if (s == null) - { + s = linesource.ReadLine (); + if (s == null) { break; } - Collect(s); + Collect (s); } - } - catch (Exception) - { - ConsoleSurrogate.WriteLine("There was a problem reading the script file."); - ConsoleSurrogate.WriteLine("Tried " + linesource.ToString()); + } catch (Exception) { + ConsoleSurrogate.WriteLine ("There was a problem reading the script file."); + ConsoleSurrogate.WriteLine ("Tried " + linesource.ToString ()); return 1; } return 0; diff --git a/ios10/ElizaChat/ElizaCore/Classes/Key.cs b/ios10/ElizaChat/ElizaCore/Classes/Key.cs index 6c3709536..def156fdb 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/Key.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/Key.cs @@ -3,15 +3,13 @@ using System; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza key.</summary> /// <remarks> /// Eliza key. /// A key has the key itself, a rank, and a list of decompositon rules. /// </remarks> - public class Key - { + public class Key { /// <summary>The key itself</summary> internal string key; @@ -23,7 +21,7 @@ public class Key /// <summary>Initialize the key.</summary> /// <remarks>Initialize the key.</remarks> - internal Key(string key, int rank, DecompList decomp) + internal Key (string key, int rank, DecompList decomp) { this.key = key; this.rank = rank; @@ -32,60 +30,58 @@ internal Key(string key, int rank, DecompList decomp) /// <summary>Another initialization for gotoKey.</summary> /// <remarks>Another initialization for gotoKey.</remarks> - internal Key() + internal Key () { key = null; rank = 0; decomp = null; } - public virtual void Copy(Key k) + public virtual void Copy (Key k) { - key = k.GetKey(); - rank = k.Rank(); - decomp = k.Decomp(); + key = k.GetKey (); + rank = k.Rank (); + decomp = k.Decomp (); } /// <summary>Print the key and all under it.</summary> /// <remarks>Print the key and all under it.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < indent; i++) - { - ConsoleSurrogate.Write(" "); + for (int i = 0; i < indent; i++) { + ConsoleSurrogate.Write (" "); } - ConsoleSurrogate.WriteLine("key: " + key + " " + rank); - decomp.Print(indent + 2); + ConsoleSurrogate.WriteLine ("key: " + key + " " + rank); + decomp.Print (indent + 2); } /// <summary>Print the key and rank only, not the rest.</summary> /// <remarks>Print the key and rank only, not the rest.</remarks> - public virtual void PrintKey(int indent) + public virtual void PrintKey (int indent) { - for (int i = 0; i < indent; i++) - { - ConsoleSurrogate.Write(" "); + for (int i = 0; i < indent; i++) { + ConsoleSurrogate.Write (" "); } - ConsoleSurrogate.WriteLine("key: " + key + " " + rank); + ConsoleSurrogate.WriteLine ("key: " + key + " " + rank); } /// <summary>Get the key value.</summary> /// <remarks>Get the key value.</remarks> - public virtual string GetKey() + public virtual string GetKey () { return key; } /// <summary>Get the rank.</summary> /// <remarks>Get the rank.</remarks> - public virtual int Rank() + public virtual int Rank () { return rank; } /// <summary>Get the decomposition list.</summary> /// <remarks>Get the decomposition list.</remarks> - public virtual DecompList Decomp() + public virtual DecompList Decomp () { return decomp; } diff --git a/ios10/ElizaChat/ElizaCore/Classes/KeyList.cs b/ios10/ElizaChat/ElizaCore/Classes/KeyList.cs index 0e2784aab..f77271b86 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/KeyList.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/KeyList.cs @@ -4,32 +4,29 @@ using System; using System.Collections.Generic; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza key list.</summary> /// <remarks> /// Eliza key list. /// This stores all the keys. /// </remarks> - public class KeyList : List<Key> - { + public class KeyList : List<Key> { private const long serialVersionUID = 1L; /// <summary>Add a new key.</summary> /// <remarks>Add a new key.</remarks> - public virtual void Add(string key, int rank, DecompList decomp) + public virtual void Add (string key, int rank, DecompList decomp) { - Add(new Key(key, rank, decomp)); + Add (new Key (key, rank, decomp)); } /// <summary>Print all the keys.</summary> /// <remarks>Print all the keys.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < Count; i++) - { - Key k = (Key)this[i]; - k.Print(indent); + for (int i = 0; i < Count; i++) { + Key k = (Key) this [i]; + k.Print (indent); } } @@ -38,13 +35,11 @@ public virtual void Print(int indent) /// Search the key list for a given key. /// Return the Key if found, else null. /// </remarks> - internal virtual Key GetKey(string s) + internal virtual Key GetKey (string s) { - for (int i = 0; i < Count; i++) - { - Key key = (Key)this[i]; - if (s.Equals(key.GetKey())) - { + for (int i = 0; i < Count; i++) { + Key key = (Key) this [i]; + if (s.Equals (key.GetKey ())) { return key; } } @@ -57,25 +52,22 @@ internal virtual Key GetKey(string s) /// For each word, if isKey is true, then push the key /// into the stack. /// </remarks> - public virtual void BuildKeyStack(KeyStack stack, string s) + public virtual void BuildKeyStack (KeyStack stack, string s) { - stack.Reset(); - s = EString.Trim(s); - string[] lines = new string[2]; + stack.Reset (); + s = EString.Trim (s); + string [] lines = new string [2]; Key k; - while (EString.Match(s, "* *", lines)) - { - k = GetKey(lines[0]); - if (k != null) - { - stack.PushKey(k); + while (EString.Match (s, "* *", lines)) { + k = GetKey (lines [0]); + if (k != null) { + stack.PushKey (k); } - s = lines[1]; + s = lines [1]; } - k = GetKey(s); - if (k != null) - { - stack.PushKey(k); + k = GetKey (s); + if (k != null) { + stack.PushKey (k); } } //stack.print(); diff --git a/ios10/ElizaChat/ElizaCore/Classes/KeyStack.cs b/ios10/ElizaChat/ElizaCore/Classes/KeyStack.cs index e1fc61d91..0f1f46f72 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/KeyStack.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/KeyStack.cs @@ -1,58 +1,54 @@ // class translated from Java // Credit goes to Charles Hayden http://www.chayden.net/eliza/Eliza.html -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>A stack of keys.</summary> /// <remarks> /// A stack of keys. /// The keys are kept in rank order. /// </remarks> - public class KeyStack - { + public class KeyStack { /// <summary>The stack size</summary> internal static readonly int stackSize = 20; /// <summary>The key stack</summary> - internal Key[] keyStack = new Key[stackSize]; + internal Key [] keyStack = new Key [stackSize]; /// <summary>The top of the key stack</summary> internal int keyTop = 0; /// <summary>Prints the key stack.</summary> /// <remarks>Prints the key stack.</remarks> - public virtual void Print() + public virtual void Print () { - ConsoleSurrogate.WriteLine("Key stack " + keyTop); - for (int i = 0; i < keyTop; i++) - { - keyStack[i].PrintKey(0); + ConsoleSurrogate.WriteLine ("Key stack " + keyTop); + for (int i = 0; i < keyTop; i++) { + keyStack [i].PrintKey (0); } } /// <summary>Get the stack size.</summary> /// <remarks>Get the stack size.</remarks> - public virtual int KeyTop() + public virtual int KeyTop () { return keyTop; } /// <summary>Reset the key stack.</summary> /// <remarks>Reset the key stack.</remarks> - public virtual void Reset() + public virtual void Reset () { keyTop = 0; } /// <summary>Get a key from the stack.</summary> /// <remarks>Get a key from the stack.</remarks> - public virtual Key Key(int n) + public virtual Key Key (int n) { - if (n < 0 || n >= keyTop) - { + if (n < 0 || n >= keyTop) { return null; } - return keyStack[n]; + return keyStack [n]; } /// <summary>Push a key in the stack.</summary> @@ -60,26 +56,21 @@ public virtual Key Key(int n) /// Push a key in the stack. /// Keep the highest rank keys at the bottom. /// </remarks> - public virtual void PushKey(Key key) + public virtual void PushKey (Key key) { - if (key == null) - { - ConsoleSurrogate.WriteLine("push null key"); + if (key == null) { + ConsoleSurrogate.WriteLine ("push null key"); return; } int i; - for (i = keyTop; i > 0; i--) - { - if (key.rank > keyStack[i - 1].rank) - { - keyStack[i] = keyStack[i - 1]; - } - else - { + for (i = keyTop; i > 0; i--) { + if (key.rank > keyStack [i - 1].rank) { + keyStack [i] = keyStack [i - 1]; + } else { break; } } - keyStack[i] = key; + keyStack [i] = key; keyTop++; } } diff --git a/ios10/ElizaChat/ElizaCore/Classes/Mem.cs b/ios10/ElizaChat/ElizaCore/Classes/Mem.cs index e12ab98f4..9a74516e0 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/Mem.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/Mem.cs @@ -1,38 +1,33 @@ // class translated from Java // Credit goes to Charles Hayden http://www.chayden.net/eliza/Eliza.html -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza memory class</summary> - public class Mem - { + public class Mem { /// <summary>The memory size</summary> internal static readonly int memMax = 20; /// <summary>The memory</summary> - internal string[] memory = new string[memMax]; + internal string [] memory = new string [memMax]; /// <summary>The memory top</summary> internal int memTop = 0; - public virtual void Save(string str) + public virtual void Save (string str) { - if (memTop < memMax) - { - memory[memTop++] = str; + if (memTop < memMax) { + memory [memTop++] = str; } } - public virtual string Get() + public virtual string Get () { - if (memTop == 0) - { + if (memTop == 0) { return null; } - string m = memory[0]; - for (int i = 0; i < memTop - 1; i++) - { - memory[i] = memory[i + 1]; + string m = memory [0]; + for (int i = 0; i < memTop - 1; i++) { + memory [i] = memory [i + 1]; } memTop--; return m; diff --git a/ios10/ElizaChat/ElizaCore/Classes/PrePost.cs b/ios10/ElizaChat/ElizaCore/Classes/PrePost.cs index ff56ac895..144f48c71 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/PrePost.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/PrePost.cs @@ -1,15 +1,13 @@ // class translated from Java // Credit goes to Charles Hayden http://www.chayden.net/eliza/Eliza.html -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza pre-post entry (two words).</summary> /// <remarks> /// Eliza pre-post entry (two words). /// This is used to store pre transforms or post transforms. /// </remarks> - public class PrePost - { + public class PrePost { /// <summary>The words</summary> internal string src; @@ -17,7 +15,7 @@ public class PrePost /// <summary>Initialize the pre-post entry.</summary> /// <remarks>Initialize the pre-post entry.</remarks> - internal PrePost(string src, string dest) + internal PrePost (string src, string dest) { this.src = src; this.dest = dest; @@ -25,25 +23,24 @@ internal PrePost(string src, string dest) /// <summary>Print the pre-post entry.</summary> /// <remarks>Print the pre-post entry.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < indent; i++) - { - ConsoleSurrogate.Write(" "); + for (int i = 0; i < indent; i++) { + ConsoleSurrogate.Write (" "); } - ConsoleSurrogate.WriteLine("pre-post: " + src + " " + dest); + ConsoleSurrogate.WriteLine ("pre-post: " + src + " " + dest); } /// <summary>Get src.</summary> /// <remarks>Get src.</remarks> - public virtual string Src() + public virtual string Src () { return src; } /// <summary>Get dest.</summary> /// <remarks>Get dest.</remarks> - public virtual string Dest() + public virtual string Dest () { return dest; } diff --git a/ios10/ElizaChat/ElizaCore/Classes/PrePostList.cs b/ios10/ElizaChat/ElizaCore/Classes/PrePostList.cs index 59c4ad39d..11560e87b 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/PrePostList.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/PrePostList.cs @@ -4,33 +4,30 @@ using System; using System.Collections.Generic; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza prePost list.</summary> /// <remarks> /// Eliza prePost list. /// This list of pre-post entries is used to perform word transformations /// prior to or after other processing. /// </remarks> - public class PrePostList : List<PrePost> - { + public class PrePostList : List<PrePost> { private const long serialVersionUID = 1L; /// <summary>Add another entry to the list.</summary> /// <remarks>Add another entry to the list.</remarks> - public virtual void Add(string src, string dest) + public virtual void Add (string src, string dest) { - Add(new PrePost(src, dest)); + Add (new PrePost (src, dest)); } /// <summary>Prnt the pre-post list.</summary> /// <remarks>Prnt the pre-post list.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < Count; i++) - { - PrePost p = (PrePost)this[i]; - p.Print(indent); + for (int i = 0; i < Count; i++) { + PrePost p = (PrePost) this [i]; + p.Print (indent); } } @@ -41,14 +38,12 @@ public virtual void Print(int indent) /// return he corresponding dest. /// If no match, return the input. /// </remarks> - internal virtual string Xlate(string str) + internal virtual string Xlate (string str) { - for (int i = 0; i < Count; i++) - { - PrePost p = (PrePost)this[i]; - if (str.Equals(p.Src())) - { - return p.Dest(); + for (int i = 0; i < Count; i++) { + PrePost p = (PrePost) this [i]; + if (str.Equals (p.Src ())) { + return p.Dest (); } } return str; @@ -61,17 +56,16 @@ internal virtual string Xlate(string str) /// (2) Break s into words. /// (3) For each word, substitute matching src word with dest. /// </remarks> - public virtual string Translate(string s) + public virtual string Translate (string s) { - string[] lines = new string[2]; - string work = EString.Trim(s); + string [] lines = new string [2]; + string work = EString.Trim (s); s = string.Empty; - while (EString.Match(work, "* *", lines)) - { - s += Xlate(lines[0]) + " "; - work = EString.Trim(lines[1]); + while (EString.Match (work, "* *", lines)) { + s += Xlate (lines [0]) + " "; + work = EString.Trim (lines [1]); } - s += Xlate(work); + s += Xlate (work); return s; } } diff --git a/ios10/ElizaChat/ElizaCore/Classes/ReasembList.cs b/ios10/ElizaChat/ElizaCore/Classes/ReasembList.cs index 172d40486..28b0d872b 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/ReasembList.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/ReasembList.cs @@ -4,26 +4,22 @@ using System.Collections.Generic; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza reassembly list.</summary> /// <remarks>Eliza reassembly list.</remarks> - public class ReasembList : List<string> - { + public class ReasembList : List<string> { private const long serialVersionUID = 1L; /// <summary>Print the reassembly list.</summary> /// <remarks>Print the reassembly list.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < Count; i++) - { - for (int j = 0; j < indent; j++) - { - ConsoleSurrogate.Write(" "); + for (int i = 0; i < Count; i++) { + for (int j = 0; j < indent; j++) { + ConsoleSurrogate.Write (" "); } - string s = (string)this[i]; - ConsoleSurrogate.WriteLine("reasemb: " + s); + string s = (string) this [i]; + ConsoleSurrogate.WriteLine ("reasemb: " + s); } } } diff --git a/ios10/ElizaChat/ElizaCore/Classes/SynList.cs b/ios10/ElizaChat/ElizaCore/Classes/SynList.cs index fa9543852..7afab90b4 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/SynList.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/SynList.cs @@ -5,42 +5,36 @@ using System.Collections.Generic; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza synonym list.</summary> /// <remarks> /// Eliza synonym list. /// Collection of all the synonym elements. /// </remarks> - public class SynList : List<WordList> - { + public class SynList : List<WordList> { private const long serialVersionUID = 1L; /// <summary>Prnt the synonym lists.</summary> /// <remarks>Prnt the synonym lists.</remarks> - public virtual void Print(int indent) + public virtual void Print (int indent) { - for (int i = 0; i < Count; i++) - { - for (int j = 0; j < indent; j++) - { - ConsoleSurrogate.Write(" "); + for (int i = 0; i < Count; i++) { + for (int j = 0; j < indent; j++) { + ConsoleSurrogate.Write (" "); } - ConsoleSurrogate.Write("synon: "); - WordList w = (WordList)this[i]; - w.Print(indent); + ConsoleSurrogate.Write ("synon: "); + WordList w = (WordList) this [i]; + w.Print (indent); } } /// <summary>Find a synonym word list given the any word in it.</summary> /// <remarks>Find a synonym word list given the any word in it.</remarks> - public virtual WordList Find(string s) + public virtual WordList Find (string s) { - for (int i = 0; i < Count; i++) - { - WordList w = (WordList)this[i]; - if (w.Find(s)) - { + for (int i = 0; i < Count; i++) { + WordList w = (WordList) this [i]; + if (w.Find (s)) { return w; } } @@ -56,39 +50,34 @@ public virtual WordList Find(string s) /// If decomp has no synonyms, do a regular match. /// Otherwise, try all synonyms. /// </remarks> - internal virtual bool MatchDecomp(string str, string pat, string[] lines) + internal virtual bool MatchDecomp (string str, string pat, string [] lines) { - if (!EString.Match(pat, "*@* *", lines)) - { + if (!EString.Match (pat, "*@* *", lines)) { // no synonyms in decomp pattern - return EString.Match(str, pat, lines); + return EString.Match (str, pat, lines); } // Decomp pattern has synonym -- isolate the synonym - string first = lines[0]; - string synWord = lines[1]; - string theRest = " " + lines[2]; + string first = lines [0]; + string synWord = lines [1]; + string theRest = " " + lines [2]; // Look up the synonym - WordList syn = Find(synWord); - if (syn == null) - { - ConsoleSurrogate.WriteLine("Could not fnd syn list for " + synWord); + WordList syn = Find (synWord); + if (syn == null) { + ConsoleSurrogate.WriteLine ("Could not fnd syn list for " + synWord); return false; } // Try each synonym individually - for (int i = 0; i < syn.Count; i++) - { + for (int i = 0; i < syn.Count; i++) { // Make a modified pattern - pat = first + (string)syn[i] + theRest; - if (EString.Match(str, pat, lines)) - { - int n = EString.Count(first, '*'); + pat = first + (string) syn [i] + theRest; + if (EString.Match (str, pat, lines)) { + int n = EString.Count (first, '*'); // Make room for the synonym in the match list. - for (int j = lines.Length - 2; j >= n; j--) - { - lines[j + 1] = lines[j]; + for (int j = lines.Length - 2; j >= n; j--) { + lines [j + 1] = lines [j]; } // The synonym goes in the match list. - lines[n] = (string)syn[i]; + lines [n] = (string) syn [i]; return true; } } diff --git a/ios10/ElizaChat/ElizaCore/Classes/WordList.cs b/ios10/ElizaChat/ElizaCore/Classes/WordList.cs index 8ed722328..79a4c8ac6 100755 --- a/ios10/ElizaChat/ElizaCore/Classes/WordList.cs +++ b/ios10/ElizaChat/ElizaCore/Classes/WordList.cs @@ -3,12 +3,10 @@ using System.Collections.Generic; -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza word list.</summary> /// <remarks>Eliza word list.</remarks> - public class WordList : List<string> - { + public class WordList : List<string> { private const long serialVersionUID = 1L; /// <summary>Print a word list on one line.</summary> @@ -16,7 +14,7 @@ public class WordList : List<string> public virtual void Print (int indent) { for (int i = 0; i < Count; i++) { - string s = (string)this [i]; + string s = (string) this [i]; ConsoleSurrogate.Write (s + " "); } ConsoleSurrogate.WriteLine (); @@ -30,7 +28,7 @@ public virtual void Print (int indent) internal virtual bool Find (string s) { for (int i = 0; i < Count; i++) { - if (s.Equals ((string)this [i])) { + if (s.Equals ((string) this [i])) { return true; } } diff --git a/ios10/ElizaChat/ElizaCore/DataModels/ElizaAddressBook.cs b/ios10/ElizaChat/ElizaCore/DataModels/ElizaAddressBook.cs index f955af255..e5cd3aefb 100644 --- a/ios10/ElizaChat/ElizaCore/DataModels/ElizaAddressBook.cs +++ b/ios10/ElizaChat/ElizaCore/DataModels/ElizaAddressBook.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using Intents; -namespace ElizaCore -{ - public class ElizaAddressBook : NSObject - { +namespace ElizaCore { + public class ElizaAddressBook : NSObject { #region Computed Properties public List<ElizaUser> Contacts { get; set; } = new List<ElizaUser> (); #endregion diff --git a/ios10/ElizaChat/ElizaCore/DataModels/ElizaUser.cs b/ios10/ElizaChat/ElizaCore/DataModels/ElizaUser.cs index 0a783472d..cc883e083 100644 --- a/ios10/ElizaChat/ElizaCore/DataModels/ElizaUser.cs +++ b/ios10/ElizaChat/ElizaCore/DataModels/ElizaUser.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; -namespace ElizaCore -{ - public class ElizaUser : NSObject - { +namespace ElizaCore { + public class ElizaUser : NSObject { #region Computed Properties public string ScreenName { get; set; } public string FirstName { get; set; } diff --git a/ios10/ElizaChat/ElizaCore/Extensions/String.cs b/ios10/ElizaChat/ElizaCore/Extensions/String.cs index 98b7a074c..7adf54c8a 100755 --- a/ios10/ElizaChat/ElizaCore/Extensions/String.cs +++ b/ios10/ElizaChat/ElizaCore/Extensions/String.cs @@ -8,16 +8,15 @@ // using System; -namespace ElizaCore -{ - public class String - { +namespace ElizaCore { + public class String { public String () { } - public static string Sub(string s, int beginIndex, int endIndex) { - return s.Substring(beginIndex, endIndex - beginIndex); + public static string Sub (string s, int beginIndex, int endIndex) + { + return s.Substring (beginIndex, endIndex - beginIndex); } } } diff --git a/ios10/ElizaChat/ElizaCore/Properties/AssemblyInfo.cs b/ios10/ElizaChat/ElizaCore/Properties/AssemblyInfo.cs index 783b88903..369bea23d 100644 --- a/ios10/ElizaChat/ElizaCore/Properties/AssemblyInfo.cs +++ b/ios10/ElizaChat/ElizaCore/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/ios10/ElizaChat/ElizaCore/SupportingClasses/ConsoleSurrogate.cs b/ios10/ElizaChat/ElizaCore/SupportingClasses/ConsoleSurrogate.cs index 54d89d0db..968ed867e 100755 --- a/ios10/ElizaChat/ElizaCore/SupportingClasses/ConsoleSurrogate.cs +++ b/ios10/ElizaChat/ElizaCore/SupportingClasses/ConsoleSurrogate.cs @@ -8,19 +8,20 @@ // using System; -namespace ElizaCore -{ - public static class ConsoleSurrogate - { - public static void WriteLine() { +namespace ElizaCore { + public static class ConsoleSurrogate { + public static void WriteLine () + { Console.WriteLine ("\n"); } - public static void WriteLine(string s) { + public static void WriteLine (string s) + { Console.WriteLine (s); } - public static void Write(string s) { + public static void Write (string s) + { Console.Write (s); } diff --git a/ios10/ElizaChat/ElizaCore/SupportingClasses/EString.cs b/ios10/ElizaChat/ElizaCore/SupportingClasses/EString.cs index 30a0fe4f1..25ad7a976 100755 --- a/ios10/ElizaChat/ElizaCore/SupportingClasses/EString.cs +++ b/ios10/ElizaChat/ElizaCore/SupportingClasses/EString.cs @@ -1,12 +1,10 @@ // class translated from Java // Credit goes to Charles Hayden http://www.chayden.net/eliza/Eliza.html -namespace ElizaCore -{ +namespace ElizaCore { /// <summary>Eliza string functions.</summary> /// <remarks>Eliza string functions.</remarks> - public class EString - { + public class EString { /// <summary>The digits.</summary> /// <remarks>The digits.</remarks> internal static readonly string num = "0123456789"; @@ -17,23 +15,20 @@ public class EString /// Return count of maching characters before * or #. /// Return -1 if strings do not match. /// </remarks> - public static int Amatch(string str, string pat) + public static int Amatch (string str, string pat) { int count = 0; int i = 0; // march through str int j = 0; // march through pat - while (i < str.Length && j < pat.Length) - { - char p = pat[j]; + while (i < str.Length && j < pat.Length) { + char p = pat [j]; // stop if pattern is * or # - if (p == '*' || p == '#') - { + if (p == '*' || p == '#') { return count; } - if (str[i] != p) - { + if (str [i] != p) { return -1; } // they are still equal @@ -54,13 +49,11 @@ public static int Amatch(string str, string pat) /// Return the string position in str of the match, /// or -1 for no match. /// </remarks> - public static int FindPat(string str, string pat) + public static int FindPat (string str, string pat) { int count = 0; - for (int i = 0; i < str.Length; i++) - { - if (Amatch(str.Substring( i), pat) >= 0) - { + for (int i = 0; i < str.Length; i++) { + if (Amatch (str.Substring (i), pat) >= 0) { return count; } count++; @@ -73,13 +66,11 @@ public static int FindPat(string str, string pat) /// Look for a number in the string. /// Return the number of digits at the beginning. /// </remarks> - public static int FindNum(string str) + public static int FindNum (string str) { int count = 0; - for (int i = 0; i < str.Length; i++) - { - if (num.IndexOf(str[i]) == -1) - { + for (int i = 0; i < str.Length; i++) { + if (num.IndexOf (str [i]) == -1) { return count; } count++; @@ -91,7 +82,7 @@ public static int FindNum(string str) /// Match the string against a pattern and fills in /// matches array with the pieces that matched * and # /// </summary> - internal static bool MatchA(string str, string pat, string[] matches) + internal static bool MatchA (string str, string pat, string [] matches) { int i = 0; // move through str @@ -99,46 +90,34 @@ internal static bool MatchA(string str, string pat, string[] matches) // move through matches int pos = 0; // move through pat - while (pos < pat.Length && j < matches.Length) - { - char p = pat[pos]; - if (p == '*') - { + while (pos < pat.Length && j < matches.Length) { + char p = pat [pos]; + if (p == '*') { int n; - if (pos + 1 == pat.Length) - { + if (pos + 1 == pat.Length) { // * is the last thing in pat // n is remaining string length n = str.Length - i; - } - else - { + } else { // * is not last in pat // find using remaining pat - n = FindPat(str.Substring( i), pat.Substring( pos + 1)); + n = FindPat (str.Substring (i), pat.Substring (pos + 1)); } - if (n < 0) - { + if (n < 0) { return false; } - matches[j++] = String.Sub(str, i, i + n); + matches [j++] = String.Sub (str, i, i + n); i += n; pos++; - } - else - { - if (p == '#') - { - int n = FindNum(str.Substring( i)); - matches[j++] = String.Sub(str, i, i + n); + } else { + if (p == '#') { + int n = FindNum (str.Substring (i)); + matches [j++] = String.Sub (str, i, i + n); i += n; pos++; - } - else - { - int n = Amatch(str.Substring( i), pat.Substring( pos)); - if (n <= 0) - { + } else { + int n = Amatch (str.Substring (i), pat.Substring (pos)); + if (n <= 0) { return false; } i += n; @@ -146,89 +125,73 @@ internal static bool MatchA(string str, string pat, string[] matches) } } } - if (i >= str.Length && pos >= pat.Length) - { + if (i >= str.Length && pos >= pat.Length) { return true; } return false; } - internal static bool MatchB(string strIn, string patIn, string[] matches) + internal static bool MatchB (string strIn, string patIn, string [] matches) { string str = strIn; string pat = patIn; int j = 0; // move through matches - while (pat.Length > 0 && str.Length >= 0 && j < matches.Length) - { - char p = pat[0]; - if (p == '*') - { + while (pat.Length > 0 && str.Length >= 0 && j < matches.Length) { + char p = pat [0]; + if (p == '*') { int n; - if (pat.Length == 1) - { + if (pat.Length == 1) { // * is the last thing in pat // n is remaining string length n = str.Length; - } - else - { + } else { // * is not last in pat // find using remaining pat - n = FindPat(str, pat.Substring( 1)); + n = FindPat (str, pat.Substring (1)); } - if (n < 0) - { + if (n < 0) { return false; } - matches[j++] = String.Sub(str, 0, n); - str = str.Substring( n); - pat = pat.Substring( 1); - } - else - { - if (p == '#') - { - int n = FindNum(str); - matches[j++] = String.Sub(str, 0, n); - str = str.Substring( n); - pat = pat.Substring( 1); - } - else - { + matches [j++] = String.Sub (str, 0, n); + str = str.Substring (n); + pat = pat.Substring (1); + } else { + if (p == '#') { + int n = FindNum (str); + matches [j++] = String.Sub (str, 0, n); + str = str.Substring (n); + pat = pat.Substring (1); + } else { // } else if (p == ' ' && str.length() > 0 && str.charAt(0) != ' ') { // pat = pat.substring(1); - int n = Amatch(str, pat); - if (n <= 0) - { + int n = Amatch (str, pat); + if (n <= 0) { return false; } - str = str.Substring( n); - pat = pat.Substring( n); + str = str.Substring (n); + pat = pat.Substring (n); } } } - if (str.Length == 0 && pat.Length == 0) - { + if (str.Length == 0 && pat.Length == 0) { return true; } return false; } - public static bool Match(string str, string pat, string[] matches) + public static bool Match (string str, string pat, string [] matches) { - return MatchA(str, pat, matches); + return MatchA (str, pat, matches); } - public static string Translate(string str, string src, string dest) + public static string Translate (string str, string src, string dest) { - if (src.Length != dest.Length) - { + if (src.Length != dest.Length) { } // impossible error - for (int i = 0; i < src.Length; i++) - { - str = str.Replace(src[i], dest[i]); + for (int i = 0; i < src.Length; i++) { + str = str.Replace (src [i], dest [i]); } return str; } @@ -239,45 +202,35 @@ public static string Translate(string str, string src, string dest) /// adding space before question, if char before is not a space; and /// copying all others /// </summary> - public static string Compress(string s) + public static string Compress (string s) { string dest = string.Empty; - if (s.Length == 0) - { + if (s.Length == 0) { return s; } - char c = s[0]; - for (int i = 1; i < s.Length; i++) - { - if (c == ' ' && ((s[i] == ' ') || (s[i] == ',') || (s[i] == '.'))) - { - } - else - { + char c = s [0]; + for (int i = 1; i < s.Length; i++) { + if (c == ' ' && ((s [i] == ' ') || (s [i] == ',') || (s [i] == '.'))) { + } else { // nothing - if (c != ' ' && s[i] == '?') - { + if (c != ' ' && s [i] == '?') { dest += c + " "; - } - else - { + } else { dest += c; } } - c = s[i]; + c = s [i]; } dest += c; return dest; } /// <summary>Trim off leading space</summary> - public static string Trim(string s) + public static string Trim (string s) { - for (int i = 0; i < s.Length; i++) - { - if (s[i] != ' ') - { - return s.Substring( i); + for (int i = 0; i < s.Length; i++) { + if (s [i] != ' ') { + return s.Substring (i); } } return string.Empty; @@ -285,28 +238,23 @@ public static string Trim(string s) /// <summary>Pad by ensuring there are spaces before and after the sentence.</summary> /// <remarks>Pad by ensuring there are spaces before and after the sentence.</remarks> - public static string Pad(string s) + public static string Pad (string s) { - if (s.Length == 0) - { + if (s.Length == 0) { return " "; } - char first = s[0]; - char last = s[s.Length - 1]; - if (first == ' ' && last == ' ') - { + char first = s [0]; + char last = s [s.Length - 1]; + if (first == ' ' && last == ' ') { return s; } - if (first == ' ' && last != ' ') - { + if (first == ' ' && last != ' ') { return s + " "; } - if (first != ' ' && last == ' ') - { + if (first != ' ' && last == ' ') { return " " + s; } - if (first != ' ' && last != ' ') - { + if (first != ' ' && last != ' ') { return " " + s + " "; } // impossible @@ -314,13 +262,11 @@ public static string Pad(string s) } /// <summary>Count number of occurrances of c in str</summary> - public static int Count(string s, char c) + public static int Count (string s, char c) { int count = 0; - for (int i = 0; i < s.Length; i++) - { - if (s[i] == c) - { + for (int i = 0; i < s.Length; i++) { + if (s [i] == c) { count++; } } diff --git a/ios10/ElizaChat/ElizaCore/SupportingClasses/ILineSource.cs b/ios10/ElizaChat/ElizaCore/SupportingClasses/ILineSource.cs index defb0faba..af08f63f5 100755 --- a/ios10/ElizaChat/ElizaCore/SupportingClasses/ILineSource.cs +++ b/ios10/ElizaChat/ElizaCore/SupportingClasses/ILineSource.cs @@ -1,9 +1,7 @@ -namespace ElizaCore -{ - public interface ILineSource - { - string ReadLine(); +namespace ElizaCore { + public interface ILineSource { + string ReadLine (); - void Close(); + void Close (); } } diff --git a/ios10/ElizaChat/ElizaCore/SupportingClasses/LineSourceFromAssembly.cs b/ios10/ElizaChat/ElizaCore/SupportingClasses/LineSourceFromAssembly.cs index 42b2042f9..9b910ae6c 100755 --- a/ios10/ElizaChat/ElizaCore/SupportingClasses/LineSourceFromAssembly.cs +++ b/ios10/ElizaChat/ElizaCore/SupportingClasses/LineSourceFromAssembly.cs @@ -3,13 +3,12 @@ using System.Linq; using Foundation; -namespace ElizaCore -{ - public class LineSourceFromAssembly :ILineSource - { +namespace ElizaCore { + public class LineSourceFromAssembly : ILineSource { private readonly StreamReader reader; - public LineSourceFromAssembly(string script){ + public LineSourceFromAssembly (string script) + { //var documents = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData); var documents = NSBundle.MainBundle.BundlePath; diff --git a/ios10/Flags/Flags/AppDelegate.cs b/ios10/Flags/Flags/AppDelegate.cs index 66aecd853..4818df839 100644 --- a/ios10/Flags/Flags/AppDelegate.cs +++ b/ios10/Flags/Flags/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace Flags -{ +namespace Flags { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } } diff --git a/ios10/Flags/Flags/DataViewController.cs b/ios10/Flags/Flags/DataViewController.cs index 6e62c7b64..1e3338d88 100644 --- a/ios10/Flags/Flags/DataViewController.cs +++ b/ios10/Flags/Flags/DataViewController.cs @@ -3,15 +3,13 @@ using Foundation; using UIKit; -namespace Flags -{ - public partial class DataViewController : UIViewController - { +namespace Flags { + public partial class DataViewController : UIViewController { // For more info https://en.wikipedia.org/wiki/Regional_Indicator_Symbol const int RegionalIndicatorSymbolLetterA = 0x1F1E6; const int BaseOffset = RegionalIndicatorSymbolLetterA - 'A'; - [Outlet("answerLabel")] + [Outlet ("answerLabel")] UILabel answerLabel { get; set; } [Outlet ("flagLabel")] diff --git a/ios10/Flags/Flags/Main.cs b/ios10/Flags/Flags/Main.cs index 8d485d3f1..faf2f2415 100644 --- a/ios10/Flags/Flags/Main.cs +++ b/ios10/Flags/Flags/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace Flags -{ - public class Application - { +namespace Flags { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/Flags/Flags/RootViewController.cs b/ios10/Flags/Flags/RootViewController.cs index f36dc169e..41bdc8d4b 100644 --- a/ios10/Flags/Flags/RootViewController.cs +++ b/ios10/Flags/Flags/RootViewController.cs @@ -5,10 +5,8 @@ using static UIKit.UIPageViewControllerNavigationDirection; -namespace Flags -{ - public partial class RootViewController : UIViewController - { +namespace Flags { + public partial class RootViewController : UIViewController { int currentIndex; UIPageViewController pageViewController; @@ -37,7 +35,7 @@ public override void ViewDidLoad () if (startingViewController == null) return; - DataViewController[] viewControllers = { startingViewController }; + DataViewController [] viewControllers = { startingViewController }; pageViewController.SetViewControllers (viewControllers, Forward, false, null); diff --git a/ios10/Flags/Flags/RootViewControllerDataSource.cs b/ios10/Flags/Flags/RootViewControllerDataSource.cs index 0bcfd57fa..a169fe895 100644 --- a/ios10/Flags/Flags/RootViewControllerDataSource.cs +++ b/ios10/Flags/Flags/RootViewControllerDataSource.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace Flags -{ - public class RootViewControllerDataSource : UIPageViewControllerDataSource - { +namespace Flags { + public class RootViewControllerDataSource : UIPageViewControllerDataSource { readonly string [] regionCodes; readonly UIStoryboard storyboard; @@ -63,16 +61,16 @@ public DataViewController GetViewControllerAt (int index) var regionCode = regionCodes [index]; // Return the data view controller for the given index. - var dataViewController = (DataViewController)cachedDataViewControllers.ObjectForKey ((NSString)regionCode); + var dataViewController = (DataViewController) cachedDataViewControllers.ObjectForKey ((NSString) regionCode); if (dataViewController != null) return dataViewController; // Create a new view controller and pass suitable data. - dataViewController = (DataViewController)storyboard.InstantiateViewController ("DataViewController"); + dataViewController = (DataViewController) storyboard.InstantiateViewController ("DataViewController"); dataViewController.RegionCode = regionCodes [index]; // Cache the view controller before returning it. - cachedDataViewControllers.SetObjectforKey (dataViewController, (NSString)regionCode); + cachedDataViewControllers.SetObjectforKey (dataViewController, (NSString) regionCode); return dataViewController; } @@ -86,8 +84,7 @@ int IndexOfViewController (DataViewController viewController) } } - public static class Utils - { + public static class Utils { // For more info https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle public static void Shuffle<T> (this T [] array, Random rng) { diff --git a/ios10/HapticFeedback/HapticFeedback/AppDelegate.cs b/ios10/HapticFeedback/HapticFeedback/AppDelegate.cs index 77b6da070..f45497c34 100644 --- a/ios10/HapticFeedback/HapticFeedback/AppDelegate.cs +++ b/ios10/HapticFeedback/HapticFeedback/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace HapticFeedback -{ +namespace HapticFeedback { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios10/HapticFeedback/HapticFeedback/Main.cs b/ios10/HapticFeedback/HapticFeedback/Main.cs index 5d32de5e0..9270f94d2 100644 --- a/ios10/HapticFeedback/HapticFeedback/Main.cs +++ b/ios10/HapticFeedback/HapticFeedback/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace HapticFeedback -{ - public class Application - { +namespace HapticFeedback { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios10/HapticFeedback/HapticFeedback/ViewController.cs b/ios10/HapticFeedback/HapticFeedback/ViewController.cs index 0a32510ea..373ed42c4 100644 --- a/ios10/HapticFeedback/HapticFeedback/ViewController.cs +++ b/ios10/HapticFeedback/HapticFeedback/ViewController.cs @@ -1,55 +1,53 @@ -using System; +using System; using UIKit; -namespace HapticFeedback -{ - public partial class ViewController : UIViewController - { +namespace HapticFeedback { + public partial class ViewController : UIViewController { #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. } #endregion #region Custom Actions - partial void ImpactAction(Foundation.NSObject sender) + partial void ImpactAction (Foundation.NSObject sender) { // Initialize feedback - var impact = new UIImpactFeedbackGenerator(UIImpactFeedbackStyle.Heavy); - impact.Prepare(); + var impact = new UIImpactFeedbackGenerator (UIImpactFeedbackStyle.Heavy); + impact.Prepare (); // Trigger feedback - impact.ImpactOccurred(); + impact.ImpactOccurred (); } - partial void NotificationAction(Foundation.NSObject sender) + partial void NotificationAction (Foundation.NSObject sender) { // Initialize feedback - var notification = new UINotificationFeedbackGenerator(); - notification.Prepare(); + var notification = new UINotificationFeedbackGenerator (); + notification.Prepare (); // Trigger feedback - notification.NotificationOccurred(UINotificationFeedbackType.Error); + notification.NotificationOccurred (UINotificationFeedbackType.Error); } - partial void SelectionAction(Foundation.NSObject sender) + partial void SelectionAction (Foundation.NSObject sender) { // Initialize feedback - var selection = new UISelectionFeedbackGenerator(); - selection.Prepare(); + var selection = new UISelectionFeedbackGenerator (); + selection.Prepare (); // Trigger feedback - selection.SelectionChanged(); + selection.SelectionChanged (); } #endregion } diff --git a/ios10/IceCreamBuilder/IceCreamBuilder/AppDelegate.cs b/ios10/IceCreamBuilder/IceCreamBuilder/AppDelegate.cs index 2dec93a78..54563e252 100644 --- a/ios10/IceCreamBuilder/IceCreamBuilder/AppDelegate.cs +++ b/ios10/IceCreamBuilder/IceCreamBuilder/AppDelegate.cs @@ -1,8 +1,8 @@ -using Foundation; +using Foundation; using UIKit; namespace IceCreamBuilder { - [Register("AppDelegate")] + [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } diff --git a/ios10/IceCreamBuilder/IceCreamBuilder/Main.cs b/ios10/IceCreamBuilder/IceCreamBuilder/Main.cs index 9d2015a53..62a90599d 100644 --- a/ios10/IceCreamBuilder/IceCreamBuilder/Main.cs +++ b/ios10/IceCreamBuilder/IceCreamBuilder/Main.cs @@ -1,10 +1,10 @@ -using UIKit; +using UIKit; namespace IceCreamBuilder { public class Application { - static void Main(string[] args) + static void Main (string [] args) { - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios10/IceCreamBuilder/IceCreamBuilder/ViewController.cs b/ios10/IceCreamBuilder/IceCreamBuilder/ViewController.cs index 66f363e4e..9eb66533f 100644 --- a/ios10/IceCreamBuilder/IceCreamBuilder/ViewController.cs +++ b/ios10/IceCreamBuilder/IceCreamBuilder/ViewController.cs @@ -1,10 +1,10 @@ -using System; +using System; using UIKit; namespace IceCreamBuilder { public partial class ViewController : UIViewController { - protected ViewController (IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { } diff --git a/ios10/IceCreamBuilder/MessagesExtension/BuildIceCreamViewController.cs b/ios10/IceCreamBuilder/MessagesExtension/BuildIceCreamViewController.cs index d127b53c0..2d4fa31bd 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/BuildIceCreamViewController.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/BuildIceCreamViewController.cs @@ -12,8 +12,8 @@ public partial class BuildIceCreamViewController : UIViewController, IUICollecti public IBuildIceCreamViewControllerDelegate Builder { get; set; } string promt; - IceCreamPart[] iceCreamParts; - IceCreamPart[] IceCreamParts { + IceCreamPart [] iceCreamParts; + IceCreamPart [] IceCreamParts { get { return iceCreamParts; } @@ -96,7 +96,7 @@ public override void ViewDidLayoutSubviews () CollectionView.ContentInset = contentInset; // Calculate the ideal height of the ice cream view. - var iceCreamViewContentHeight = IceCreamView.ArrangedSubviews.Sum (v => (float)v.IntrinsicContentSize.Height); + var iceCreamViewContentHeight = IceCreamView.ArrangedSubviews.Sum (v => (float) v.IntrinsicContentSize.Height); var iceCreamPartImageScale = layout.ItemSize.Height / iceCreamPartImageSize.Height; IceCreamViewHeightConstraint.Constant = iceCreamViewContentHeight * iceCreamPartImageScale; } diff --git a/ios10/IceCreamBuilder/MessagesExtension/IBuildIceCreamViewControllerDelegate.cs b/ios10/IceCreamBuilder/MessagesExtension/IBuildIceCreamViewControllerDelegate.cs index 823ba2805..388202c64 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/IBuildIceCreamViewControllerDelegate.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/IBuildIceCreamViewControllerDelegate.cs @@ -1,4 +1,4 @@ -namespace MessagesExtension { +namespace MessagesExtension { public interface IBuildIceCreamViewControllerDelegate { void Build (BuildIceCreamViewController controller, IceCreamPart iceCreamPart); } diff --git a/ios10/IceCreamBuilder/MessagesExtension/IIceCreamsViewControllerDelegate.cs b/ios10/IceCreamBuilder/MessagesExtension/IIceCreamsViewControllerDelegate.cs index af71c3d85..4b2a508ef 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/IIceCreamsViewControllerDelegate.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/IIceCreamsViewControllerDelegate.cs @@ -1,4 +1,4 @@ -namespace MessagesExtension { +namespace MessagesExtension { public interface IIceCreamsViewControllerDelegate { void DidSelectAdd (IceCreamsViewController controller); } diff --git a/ios10/IceCreamBuilder/MessagesExtension/IceCreamPartCollectionViewLayout.cs b/ios10/IceCreamBuilder/MessagesExtension/IceCreamPartCollectionViewLayout.cs index 39c2774c4..dba676293 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/IceCreamPartCollectionViewLayout.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/IceCreamPartCollectionViewLayout.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using CoreGraphics; @@ -9,7 +9,7 @@ namespace MessagesExtension { [Register ("IceCreamPartCollectionViewLayout")] public class IceCreamPartCollectionViewLayout : UICollectionViewFlowLayout { - public IceCreamPartCollectionViewLayout (IntPtr handle) : base(handle) + public IceCreamPartCollectionViewLayout (IntPtr handle) : base (handle) { } diff --git a/ios10/IceCreamBuilder/MessagesExtension/IceCreamView.cs b/ios10/IceCreamBuilder/MessagesExtension/IceCreamView.cs index eeb4c10cd..fd9441f91 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/IceCreamView.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/IceCreamView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using UIKit; @@ -24,9 +24,9 @@ public IceCream IceCream { // Add a `UIImageView` for each of the ice cream's valid parts. var views = Parts ().Where (part => part != null) - .Select (part => new UIImageView (part.Image) { - ContentMode = UIViewContentMode.ScaleAspectFit - }); + .Select (part => new UIImageView (part.Image) { + ContentMode = UIViewContentMode.ScaleAspectFit + }); foreach (var v in views) AddArrangedSubview (v); diff --git a/ios10/IceCreamBuilder/MessagesExtension/IceCreamsViewController.cs b/ios10/IceCreamBuilder/MessagesExtension/IceCreamsViewController.cs index b104141fb..4c4ca5011 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/IceCreamsViewController.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/IceCreamsViewController.cs @@ -22,36 +22,36 @@ public IceCreamsViewController (IntPtr handle) : base (handle) var history = IceCreamHistory.Load (); items = history.Reverse () - .Select (s => KeyValue (CollectionViewItem.IceCream, s)) - .ToList (); - items.Insert (0, KeyValue (CollectionViewItem.Create, (IceCream)null)); + .Select (s => KeyValue (CollectionViewItem.IceCream, s)) + .ToList (); + items.Insert (0, KeyValue (CollectionViewItem.Create, (IceCream) null)); } - [Export("collectionView:numberOfItemsInSection:")] + [Export ("collectionView:numberOfItemsInSection:")] public override nint GetItemsCount (UICollectionView collectionView, nint section) { return items.Count; } - [Export("collectionView:cellForItemAtIndexPath:")] + [Export ("collectionView:cellForItemAtIndexPath:")] public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { UICollectionViewCell cell = null; var item = items [indexPath.Row]; switch (item.Key) { - case CollectionViewItem.IceCream: - cell = DequeueIceCreamCell (item.Value, indexPath); - break; - case CollectionViewItem.Create: - cell = DequeueIceCreamOutlineCell (indexPath); - break; + case CollectionViewItem.IceCream: + cell = DequeueIceCreamCell (item.Value, indexPath); + break; + case CollectionViewItem.Create: + cell = DequeueIceCreamOutlineCell (indexPath); + break; } return cell; } - [Export("collectionView:didSelectItemAtIndexPath:")] + [Export ("collectionView:didSelectItemAtIndexPath:")] public override void ItemSelected (UICollectionView collectionView, NSIndexPath indexPath) { var item = items [indexPath.Row]; diff --git a/ios10/IceCreamBuilder/MessagesExtension/MessagesViewController.cs b/ios10/IceCreamBuilder/MessagesExtension/MessagesViewController.cs index ac1673f04..53e51694f 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/MessagesViewController.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/MessagesViewController.cs @@ -90,7 +90,7 @@ public UIViewController InstantiateCompletedIceCreamController (IceCream iceCrea var controller = Storyboard.InstantiateViewController (CompletedIceCreamViewController.StoryboardIdentifier) as CompletedIceCreamViewController; if (controller == null) throw new Exception ("Unable to instantiate an CompletedIceCreamViewController from the storyboard"); - + controller.IceCream = iceCream; return controller; } @@ -155,7 +155,7 @@ MSMessage ComposeMessage (IceCream iceCream, string caption, MSSession session = Caption = caption }; - var message = new MSMessage (session ?? new MSSession()) { + var message = new MSMessage (session ?? new MSSession ()) { Url = components.Url, Layout = layout }; diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/Base.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/Base.cs index b82f72f90..f14faf18a 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/Base.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/Base.cs @@ -1,4 +1,4 @@ -namespace MessagesExtension { +namespace MessagesExtension { public enum BaseType { base01, base02, @@ -7,7 +7,7 @@ public enum BaseType { } public class Base : IceCreamPart { - public static Base[] All { get; } = { + public static Base [] All { get; } = { new Base (BaseType.base01), new Base (BaseType.base02), new Base (BaseType.base03), diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/IQueryItemRepresentable.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/IQueryItemRepresentable.cs index 6b2d8c1c3..fae924cca 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/IQueryItemRepresentable.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/IQueryItemRepresentable.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; namespace MessagesExtension { public interface IQueryItemRepresentable { diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCream.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCream.cs index c85595000..39399ecd8 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCream.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCream.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -8,8 +8,7 @@ using UIKit; namespace MessagesExtension { - public class IceCream : IEquatable<IceCream> - { + public class IceCream : IEquatable<IceCream> { CGSize size = new CGSize (300f, 300f); CGSize opaquePadding = new CGSize (60f, 10f); @@ -25,8 +24,7 @@ public bool IsComplete { } } - public NSUrlQueryItem[] QueryItems - { + public NSUrlQueryItem [] QueryItems { get { var items = new List<NSUrlQueryItem> (); if (Base != null) @@ -48,10 +46,10 @@ public IceCream (BaseType baseType, ScoopsType scoopsType, ToppingType toppingTy var iceCreamScoops = new NSUrlQueryItem ("Scoops", scoopsType.ToString ()); var iceCreamTopping = new NSUrlQueryItem ("Topping", toppingType.ToString ()); - CheckQueryItems (new[] { iceCreamBase, iceCreamScoops, iceCreamTopping }); + CheckQueryItems (new [] { iceCreamBase, iceCreamScoops, iceCreamTopping }); } - public IceCream (NSUrlQueryItem[] queryItems) + public IceCream (NSUrlQueryItem [] queryItems) { CheckQueryItems (queryItems); } @@ -94,9 +92,9 @@ public override int GetHashCode () { unchecked { var hashCode = 13; - hashCode = (hashCode * 397) ^ Base.GetHashCode(); - hashCode = (hashCode * 397) ^ Scoops.GetHashCode(); - hashCode = (hashCode * 397) ^ Topping.GetHashCode(); + hashCode = (hashCode * 397) ^ Base.GetHashCode (); + hashCode = (hashCode * 397) ^ Scoops.GetHashCode (); + hashCode = (hashCode * 397) ^ Topping.GetHashCode (); return hashCode; } } @@ -148,13 +146,13 @@ public UIImage RenderSticker (bool opaque) public UIImage RenderParts () { // Determine which parts to draw. - IceCreamPart[] allParts = { Topping, Scoops, Base }; + IceCreamPart [] allParts = { Topping, Scoops, Base }; var partImages = allParts.Where (p => p != null && p.Image != null).Select (p => p.StickerImage); // Calculate the size of the composited ice cream parts image. var outputImageSize = CGSize.Empty; outputImageSize.Width = partImages.OrderByDescending (i => i.Size.Width).FirstOrDefault ().Size.Width; - outputImageSize.Height = (nfloat)partImages.Sum (i => i.Size.Height); + outputImageSize.Height = (nfloat) partImages.Sum (i => i.Size.Height); // Render the part images into a single composite image. var renderer = new UIGraphicsImageRenderer (outputImageSize); @@ -172,25 +170,25 @@ public UIImage RenderParts () return image; } - void CheckQueryItems (NSUrlQueryItem[] queryItems) + void CheckQueryItems (NSUrlQueryItem [] queryItems) { foreach (var queryItem in queryItems) { if (string.IsNullOrEmpty (queryItem.Value)) continue; switch (queryItem.Name) { - case "Base": - var baseType = (BaseType)Enum.Parse (typeof (BaseType), queryItem.Value, true); - Base = new Base (baseType); - break; - case "Scoops": - var scoopsType = (ScoopsType)Enum.Parse(typeof(ScoopsType), queryItem.Value, true); - Scoops = new Scoops (scoopsType); - break; - case "Topping": - var toppingType = (ToppingType)Enum.Parse (typeof (ToppingType), queryItem.Value, true); - Topping = new Topping (toppingType); - break; + case "Base": + var baseType = (BaseType) Enum.Parse (typeof (BaseType), queryItem.Value, true); + Base = new Base (baseType); + break; + case "Scoops": + var scoopsType = (ScoopsType) Enum.Parse (typeof (ScoopsType), queryItem.Value, true); + Scoops = new Scoops (scoopsType); + break; + case "Topping": + var toppingType = (ToppingType) Enum.Parse (typeof (ToppingType), queryItem.Value, true); + Topping = new Topping (toppingType); + break; } } } diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamHistory.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamHistory.cs index 18729a2d0..17a4edc67 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamHistory.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamHistory.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using System.Linq; using Foundation; @@ -50,7 +50,7 @@ public void Append (IceCream item) public void Save () { var iceCreamUrls = iceCreams.Select (ic => new NSUrlComponents { QueryItems = ic.QueryItems }.Url.AbsoluteString) - .ToArray (); + .ToArray (); SaveIceCreams (iceCreamUrls); } @@ -64,7 +64,7 @@ static string [] GetSavedIceCreams () : JsonConvert.DeserializeObject<string []> (serializedList); } - static void SaveIceCreams (string[] iceCreamUrls) + static void SaveIceCreams (string [] iceCreamUrls) { var serializedList = JsonConvert.SerializeObject (iceCreamUrls); var defaults = NSUserDefaults.StandardUserDefaults; diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamPart.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamPart.cs index a63d7958d..151f40c51 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamPart.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamPart.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamStickerCache.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamStickerCache.cs index 3f9078c59..e6552935e 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamStickerCache.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/IceCreamStickerCache.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using Foundation; @@ -42,7 +42,7 @@ public MSSticker PlaceholderSticker { cacheURL = Path.GetTempPath (); NSError error; - fileManager.CreateDirectory (cacheURL, true, (NSFileAttributes)null, out error); + fileManager.CreateDirectory (cacheURL, true, (NSFileAttributes) null, out error); if (error != null) throw new Exception ($"Unable to create cache URL: {cacheURL}"); } @@ -58,7 +58,7 @@ public void GetSticker (IceCream iceCream, Action<MSSticker> completion) // Check if the sticker already exists at the URL if (!NSFileManager.DefaultManager.FileExists (url)) { - + // Create the sticker image and write it to disk. var image = iceCream.RenderSticker (false); var imageData = image?.AsPNG (); diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/Scoops.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/Scoops.cs index 5667f32df..118967c5e 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/Scoops.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/Scoops.cs @@ -1,4 +1,4 @@ -namespace MessagesExtension { +namespace MessagesExtension { public enum ScoopsType { scoops01, scoops02, @@ -13,7 +13,7 @@ public enum ScoopsType { } public class Scoops : IceCreamPart { - public static Scoops[] All { get; } = { + public static Scoops [] All { get; } = { new Scoops (ScoopsType.scoops01), new Scoops (ScoopsType.scoops02), new Scoops (ScoopsType.scoops03), diff --git a/ios10/IceCreamBuilder/MessagesExtension/Model/Topping.cs b/ios10/IceCreamBuilder/MessagesExtension/Model/Topping.cs index 226fafa09..531bc3888 100644 --- a/ios10/IceCreamBuilder/MessagesExtension/Model/Topping.cs +++ b/ios10/IceCreamBuilder/MessagesExtension/Model/Topping.cs @@ -1,4 +1,4 @@ -namespace MessagesExtension { +namespace MessagesExtension { public enum ToppingType { topping01, topping02, @@ -14,9 +14,8 @@ public enum ToppingType { topping12 } - public class Topping : IceCreamPart - { - public static Topping[] All { get; } = { + public class Topping : IceCreamPart { + public static Topping [] All { get; } = { new Topping (ToppingType.topping01), new Topping (ToppingType.topping02), new Topping (ToppingType.topping03), diff --git a/ios10/MonkeyNotify/MonkeyNotify/AppDelegate.cs b/ios10/MonkeyNotify/MonkeyNotify/AppDelegate.cs index 33f16eee8..b598fc1fc 100644 --- a/ios10/MonkeyNotify/MonkeyNotify/AppDelegate.cs +++ b/ios10/MonkeyNotify/MonkeyNotify/AppDelegate.cs @@ -1,14 +1,12 @@ -using Foundation; +using Foundation; using UIKit; using UserNotifications; -namespace MonkeyNotify -{ +namespace MonkeyNotify { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios10/MonkeyNotify/MonkeyNotify/Classes/UserNotificationCenterDelegate.cs b/ios10/MonkeyNotify/MonkeyNotify/Classes/UserNotificationCenterDelegate.cs index 4f6143aaf..0f7453561 100644 --- a/ios10/MonkeyNotify/MonkeyNotify/Classes/UserNotificationCenterDelegate.cs +++ b/ios10/MonkeyNotify/MonkeyNotify/Classes/UserNotificationCenterDelegate.cs @@ -1,10 +1,8 @@ -using System; +using System; using UserNotifications; -namespace MonkeyNotify -{ - public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate - { +namespace MonkeyNotify { + public class UserNotificationCenterDelegate : UNUserNotificationCenterDelegate { #region Constructors public UserNotificationCenterDelegate () { @@ -17,38 +15,34 @@ public override void WillPresentNotification (UNUserNotificationCenter center, U // Do something with the notification Console.WriteLine ("Active Notification: {0}", notification); - // Tell system to display the notification anyway or use + // Tell system to display the notification anyway or use // `None` to say we have handled the display locally. - completionHandler (UNNotificationPresentationOptions.Alert); + completionHandler (UNNotificationPresentationOptions.Alert); } - public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler) + public override void DidReceiveNotificationResponse (UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler) { // Take action based on Action ID - switch (response.ActionIdentifier) - { - case "reply": - // Do something - Console.WriteLine("Received the REPLY custom action."); - break; - default: - // Take action based on identifier - if (response.IsDefaultAction) - { - // Handle default action... - Console.WriteLine("Handling the default action."); - } - else if (response.IsDismissAction) - { - // Handle dismiss action - Console.WriteLine("Handling a custom dismiss action."); - } - break; + switch (response.ActionIdentifier) { + case "reply": + // Do something + Console.WriteLine ("Received the REPLY custom action."); + break; + default: + // Take action based on identifier + if (response.IsDefaultAction) { + // Handle default action... + Console.WriteLine ("Handling the default action."); + } else if (response.IsDismissAction) { + // Handle dismiss action + Console.WriteLine ("Handling a custom dismiss action."); + } + break; } // Inform caller it has been handled - completionHandler(); + completionHandler (); } #endregion } -} \ No newline at end of file +} diff --git a/ios10/MonkeyNotify/MonkeyNotify/Main.cs b/ios10/MonkeyNotify/MonkeyNotify/Main.cs index 10f8b16ee..76dea9f2d 100644 --- a/ios10/MonkeyNotify/MonkeyNotify/Main.cs +++ b/ios10/MonkeyNotify/MonkeyNotify/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace MonkeyNotify -{ - public class Application - { +namespace MonkeyNotify { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/MonkeyNotify/MonkeyNotify/ViewController.cs b/ios10/MonkeyNotify/MonkeyNotify/ViewController.cs index 819db8b29..e138679ff 100644 --- a/ios10/MonkeyNotify/MonkeyNotify/ViewController.cs +++ b/ios10/MonkeyNotify/MonkeyNotify/ViewController.cs @@ -1,77 +1,71 @@ -using System; +using System; using UserNotifications; using UIKit; using Foundation; -namespace MonkeyNotify -{ - public partial class ViewController : UIViewController - { +namespace MonkeyNotify { + public partial class ViewController : UIViewController { #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); } #endregion #region Custom Actions - partial void SimpleNotificationTapped(Foundation.NSObject sender) + partial void SimpleNotificationTapped (Foundation.NSObject sender) { // Create content - var content = new UNMutableNotificationContent(); + var content = new UNMutableNotificationContent (); content.Title = "Notification Title"; content.Subtitle = "Notification Subtitle"; content.Body = "This is the message body of the notification."; // Fire trigger in twenty seconds - var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(20, false); + var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (20, false); var requestID = "sampleRequest"; - var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger); + var request = UNNotificationRequest.FromIdentifier (requestID, content, trigger); - UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => - { - if (err != null) - { + UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => { + if (err != null) { // Report error - Console.WriteLine("Error: {0}", err); - } - else - { + Console.WriteLine ("Error: {0}", err); + } else { // Report Success - Console.WriteLine("Notification Scheduled: {0}", request); + Console.WriteLine ("Notification Scheduled: {0}", request); } }); } - partial void CustomActionTapped(Foundation.NSObject sender) + partial void CustomActionTapped (Foundation.NSObject sender) { // Create action var actionID = "reply"; var title = "Reply"; - var action = UNNotificationAction.FromIdentifier(actionID, title, UNNotificationActionOptions.None); + var action = UNNotificationAction.FromIdentifier (actionID, title, UNNotificationActionOptions.None); // Create category var categoryID = "message"; - var actions = new UNNotificationAction[] { action }; - var intentIDs = new string[] { }; + var actions = new UNNotificationAction [] { action }; + var intentIDs = new string [] { }; //var categoryOptions = new UNNotificationCategoryOptions[] { }; - var category = UNNotificationCategory.FromIdentifier(categoryID, actions, intentIDs, UNNotificationCategoryOptions.None); + var category = UNNotificationCategory.FromIdentifier (categoryID, actions, intentIDs, UNNotificationCategoryOptions.None); // Register category - var categories = new UNNotificationCategory[] { category }; - UNUserNotificationCenter.Current.SetNotificationCategories(new NSSet<UNNotificationCategory>(categories)); + var categories = new UNNotificationCategory [] { category }; + UNUserNotificationCenter.Current.SetNotificationCategories (new NSSet<UNNotificationCategory> (categories)); // Create content - var content = new UNMutableNotificationContent(); + var content = new UNMutableNotificationContent (); content.Title = "Custom Action"; content.Subtitle = "Notification Subtitle"; content.Body = "This is the message body of the notification."; @@ -79,22 +73,18 @@ partial void CustomActionTapped(Foundation.NSObject sender) content.CategoryIdentifier = "message"; // Fire trigger in twenty seconds - var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(20, false); + var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (20, false); var requestID = "sampleRequest"; - var request = UNNotificationRequest.FromIdentifier(requestID, content, trigger); + var request = UNNotificationRequest.FromIdentifier (requestID, content, trigger); - UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) => - { - if (err != null) - { + UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => { + if (err != null) { // Report error - Console.WriteLine("Error: {0}", err); - } - else - { + Console.WriteLine ("Error: {0}", err); + } else { // Report Success - Console.WriteLine("Notification Scheduled: {0}", request); + Console.WriteLine ("Notification Scheduled: {0}", request); } }); } diff --git a/ios10/MonkeyNotify/MonkeyNotifyServiceExtension/NotificationService.cs b/ios10/MonkeyNotify/MonkeyNotifyServiceExtension/NotificationService.cs index d464eaa2b..ac73995de 100644 --- a/ios10/MonkeyNotify/MonkeyNotifyServiceExtension/NotificationService.cs +++ b/ios10/MonkeyNotify/MonkeyNotifyServiceExtension/NotificationService.cs @@ -1,43 +1,41 @@ -using System; +using System; using Foundation; using UIKit; using UserNotifications; -namespace MonkeyNotifyServiceExtension -{ - [Register("NotificationService")] - public class NotificationService : UNNotificationServiceExtension - { +namespace MonkeyNotifyServiceExtension { + [Register ("NotificationService")] + public class NotificationService : UNNotificationServiceExtension { #region Computed Properties Action<UNNotificationContent> ContentHandler { get; set; } UNMutableNotificationContent BestAttemptContent { get; set; } #endregion #region Constructors - protected NotificationService(IntPtr handle) : base(handle) + protected NotificationService (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void DidReceiveNotificationRequest(UNNotificationRequest request, Action<UNNotificationContent> contentHandler) + public override void DidReceiveNotificationRequest (UNNotificationRequest request, Action<UNNotificationContent> contentHandler) { ContentHandler = contentHandler; - BestAttemptContent = (UNMutableNotificationContent)request.Content.MutableCopy(); + BestAttemptContent = (UNMutableNotificationContent) request.Content.MutableCopy (); // Modify the notification content here... BestAttemptContent.Title = $"{BestAttemptContent.Title}[modified]"; - ContentHandler(BestAttemptContent); + ContentHandler (BestAttemptContent); } - public override void TimeWillExpire() + public override void TimeWillExpire () { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. - ContentHandler(BestAttemptContent); + ContentHandler (BestAttemptContent); } #endregion } diff --git a/ios10/RawExpose/AlbumCollectionViewCell.cs b/ios10/RawExpose/AlbumCollectionViewCell.cs index 87415eafd..0360c75ba 100644 --- a/ios10/RawExpose/AlbumCollectionViewCell.cs +++ b/ios10/RawExpose/AlbumCollectionViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace RawExpose -{ - public partial class AlbumCollectionViewCell : UICollectionViewCell - { +namespace RawExpose { + public partial class AlbumCollectionViewCell : UICollectionViewCell { public static new readonly string ReuseIdentifier = "AlbumCollectionViewCell"; [Outlet ("imageView")] diff --git a/ios10/RawExpose/AlbumCollectionViewController.cs b/ios10/RawExpose/AlbumCollectionViewController.cs index 27c64259a..9341d8e87 100644 --- a/ios10/RawExpose/AlbumCollectionViewController.cs +++ b/ios10/RawExpose/AlbumCollectionViewController.cs @@ -6,11 +6,9 @@ using Photos; using UIKit; -namespace RawExpose -{ +namespace RawExpose { // This UICollectionViewController displayes all albums from the Photos library. - public partial class AlbumCollectionViewController : UICollectionViewController - { + public partial class AlbumCollectionViewController : UICollectionViewController { const string lightboxSegueName = "LightboxSegue"; // Array of albums displayed in this UICollectionView @@ -65,7 +63,7 @@ public override UICollectionViewCell GetCell (UICollectionView collectionView, N cell.ImageView.Image = null; cell.Label.Text = collection.LocalizedTitle; - var firstAsset = (PHAsset)PHAsset.FetchAssets (collection, new PHFetchOptions ()).firstObject; + var firstAsset = (PHAsset) PHAsset.FetchAssets (collection, new PHFetchOptions ()).firstObject; if (firstAsset != null) { var options = new PHImageRequestOptions { Synchronous = true diff --git a/ios10/RawExpose/AppDelegate.cs b/ios10/RawExpose/AppDelegate.cs index 883e6c19f..c5cf863a3 100644 --- a/ios10/RawExpose/AppDelegate.cs +++ b/ios10/RawExpose/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace RawExpose -{ +namespace RawExpose { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } } diff --git a/ios10/RawExpose/ImageViewController.cs b/ios10/RawExpose/ImageViewController.cs index f43cf30ec..6e12b878e 100644 --- a/ios10/RawExpose/ImageViewController.cs +++ b/ios10/RawExpose/ImageViewController.cs @@ -13,12 +13,10 @@ using static OpenTK.Graphics.ES30.GL; using static CoreGraphics.CGAffineTransform; -namespace RawExpose -{ +namespace RawExpose { // This UIViewController displays an image processed using the CoreImage CIRawFilter in a GLKView. // It also allows the user to perform simple edit, like adjusting exposure, temperature and tint. - public partial class ImageViewController : UIViewController, IGLKViewDelegate - { + public partial class ImageViewController : UIViewController, IGLKViewDelegate { // Outlet to sliders used to edit the image. [Outlet ("exposureSlider")] UISlider ExposureSlider { get; set; } @@ -30,7 +28,7 @@ public partial class ImageViewController : UIViewController, IGLKViewDelegate UISlider TintSlider { get; set; } // View used to display the CoreImage output produced by the CIRawFilter. - [Outlet("imageView")] + [Outlet ("imageView")] public GLKView ImageView { get; set; } // Asset containing the image to render. @@ -92,14 +90,14 @@ public override void ViewDidLoad () imageNativeSize = new CGSize (sizeValue.X, sizeValue.Y); // Record the original value of the temperature, and setup the editing slider. - var tempValue = (NSNumber)ciRawFilter.ValueForKey (Keys.kCIInputNeutralTemperatureKey); + var tempValue = (NSNumber) ciRawFilter.ValueForKey (Keys.kCIInputNeutralTemperatureKey); if (tempValue != null) { originalTemp = tempValue.FloatValue; TempSlider.SetValue (tempValue.FloatValue, animated: false); } // Record the original value of the tint, and setup the editing slider. - var tintValue = (NSNumber)ciRawFilter.ValueForKey (Keys.kCIInputNeutralTintKey); + var tintValue = (NSNumber) ciRawFilter.ValueForKey (Keys.kCIInputNeutralTintKey); if (tintValue != null) { originalTint = tintValue.FloatValue; TintSlider.SetValue (tintValue.FloatValue, animated: false); @@ -146,7 +144,7 @@ void exposureAdjusted (UISlider sender) } // Adjust the temperature of the image - [Action("temperatureAdjustedWithSender:")] + [Action ("temperatureAdjustedWithSender:")] void temperatureAdjusted (UISlider sender) { var filter = ciRawFilter; @@ -201,7 +199,7 @@ public void DrawInRect (GLKView view, CGRect rect) // Calculate scale to show the image at. var scaleTransform = MakeScale (view.ContentScaleFactor, view.ContentScaleFactor); var contentScaledRect = CGRectApplyAffineTransform (rect, scaleTransform); - var scale = (float)Math.Min (contentScaledRect.Width / nativeSize.Value.Width, contentScaledRect.Height / nativeSize.Value.Height); + var scale = (float) Math.Min (contentScaledRect.Width / nativeSize.Value.Width, contentScaledRect.Height / nativeSize.Value.Height); // Set scale factor of the CIRawFilter to size it correctly for display. filter.SetValueForKey (NSNumber.FromFloat (scale), Keys.kCIInputScaleFactorKey); @@ -225,11 +223,10 @@ public void DrawInRect (GLKView view, CGRect rect) } // TODO: https://trello.com/c/cKoavtdL - public static class Keys - { + public static class Keys { static readonly IntPtr CoreImageLibrary = Dlfcn.dlopen ("/System/Library/Frameworks/CoreImage.framework/CoreImage", 0); - public static NSString kCIOutputNativeSizeKey = Dlfcn.GetStringConstant (CoreImageLibrary, "kCIOutputNativeSizeKey"); + public static NSString kCIOutputNativeSizeKey = Dlfcn.GetStringConstant (CoreImageLibrary, "kCIOutputNativeSizeKey"); public static NSString kCIInputNeutralTemperatureKey = Dlfcn.GetStringConstant (CoreImageLibrary, "kCIInputNeutralTemperatureKey"); public static NSString kCIInputNeutralTintKey = Dlfcn.GetStringConstant (CoreImageLibrary, "kCIInputNeutralTintKey"); public static NSString kCIInputScaleFactorKey = Dlfcn.GetStringConstant (CoreImageLibrary, "kCIInputScaleFactorKey"); diff --git a/ios10/RawExpose/LightboxCollectionViewCell.cs b/ios10/RawExpose/LightboxCollectionViewCell.cs index 05c2990db..db391c51b 100644 --- a/ios10/RawExpose/LightboxCollectionViewCell.cs +++ b/ios10/RawExpose/LightboxCollectionViewCell.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace RawExpose -{ - public partial class LightboxCollectionViewCell : UICollectionViewCell - { +namespace RawExpose { + public partial class LightboxCollectionViewCell : UICollectionViewCell { public static new readonly string ReuseIdentifier = "LightboxCollectionViewCell"; [Outlet ("imageView")] diff --git a/ios10/RawExpose/LightboxCollectionViewController.cs b/ios10/RawExpose/LightboxCollectionViewController.cs index 72a1426fe..90b9641c9 100644 --- a/ios10/RawExpose/LightboxCollectionViewController.cs +++ b/ios10/RawExpose/LightboxCollectionViewController.cs @@ -6,10 +6,8 @@ using Photos; using UIKit; -namespace RawExpose -{ - public partial class LightboxCollectionViewController : UICollectionViewController - { +namespace RawExpose { + public partial class LightboxCollectionViewController : UICollectionViewController { const string imageSegueName = "ImageSegue"; readonly List<PHAsset> assets = new List<PHAsset> (); diff --git a/ios10/RawExpose/Main.cs b/ios10/RawExpose/Main.cs index d14f68471..305d20640 100644 --- a/ios10/RawExpose/Main.cs +++ b/ios10/RawExpose/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace RawExpose -{ - public class Application - { +namespace RawExpose { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/RawExpose/ViewController.cs b/ios10/RawExpose/ViewController.cs index 0c99e3adf..821ddc7e2 100644 --- a/ios10/RawExpose/ViewController.cs +++ b/ios10/RawExpose/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace RawExpose -{ - public partial class ViewController : UIViewController - { +namespace RawExpose { + public partial class ViewController : UIViewController { protected ViewController (IntPtr handle) : base (handle) { diff --git a/ios10/SpeakToMe/SpeakToMe/AppDelegate.cs b/ios10/SpeakToMe/SpeakToMe/AppDelegate.cs index fd683f36b..12af94b38 100644 --- a/ios10/SpeakToMe/SpeakToMe/AppDelegate.cs +++ b/ios10/SpeakToMe/SpeakToMe/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace SpeakToMe -{ +namespace SpeakToMe { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } } diff --git a/ios10/SpeakToMe/SpeakToMe/Main.cs b/ios10/SpeakToMe/SpeakToMe/Main.cs index 38882f00a..6afe82e11 100644 --- a/ios10/SpeakToMe/SpeakToMe/Main.cs +++ b/ios10/SpeakToMe/SpeakToMe/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace SpeakToMe -{ - public class Application - { +namespace SpeakToMe { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/SpeakToMe/SpeakToMe/ViewController.cs b/ios10/SpeakToMe/SpeakToMe/ViewController.cs index 9b74edf77..93a452439 100644 --- a/ios10/SpeakToMe/SpeakToMe/ViewController.cs +++ b/ios10/SpeakToMe/SpeakToMe/ViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using AVFoundation; using Foundation; using Speech; using UIKit; -namespace SpeakToMe -{ - public partial class ViewController : UIViewController, ISFSpeechRecognizerDelegate - { +namespace SpeakToMe { + public partial class ViewController : UIViewController, ISFSpeechRecognizerDelegate { readonly SFSpeechRecognizer speechRecognizer = new SFSpeechRecognizer (new NSLocale ("en-US")); readonly AVAudioEngine audioEngine = new AVAudioEngine (); SFSpeechAudioBufferRecognitionRequest recognitionRequest; diff --git a/ios10/SpeedSketch/SpeedSketch/AppDelegate.cs b/ios10/SpeedSketch/SpeedSketch/AppDelegate.cs index d44c4f105..f07ddeb58 100644 --- a/ios10/SpeedSketch/SpeedSketch/AppDelegate.cs +++ b/ios10/SpeedSketch/SpeedSketch/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace SpeedSketch -{ +namespace SpeedSketch { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) diff --git a/ios10/SpeedSketch/SpeedSketch/Controls/RingControl.cs b/ios10/SpeedSketch/SpeedSketch/Controls/RingControl.cs index 1770f93f0..059bf0b5c 100644 --- a/ios10/SpeedSketch/SpeedSketch/Controls/RingControl.cs +++ b/ios10/SpeedSketch/SpeedSketch/Controls/RingControl.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; @@ -8,10 +8,8 @@ using static SpeedSketch.RingControlState; using static CoreGraphics.CGAffineTransform; -namespace SpeedSketch -{ - public class RingControl : UIView - { +namespace SpeedSketch { + public class RingControl : UIView { RingView selectedView; nfloat RingRadius { @@ -76,7 +74,7 @@ void SetupRings (int itemCount) view.StateClosures [Selected] = selectedGenerator (view); view.StateClosures [Normal] = normalGenerator (view); - nfloat angle = index / (nfloat)(itemCount - 1) * absoluteRingSegment; + nfloat angle = index / (nfloat) (itemCount - 1) * absoluteRingSegment; var fan = normalDistance.Apply (MakeRotation (angle)).RoundTo (scale); view.StateClosures [LocationFan] = locationFanGenerator (view, fan); diff --git a/ios10/SpeedSketch/SpeedSketch/Controls/RingView.cs b/ios10/SpeedSketch/SpeedSketch/Controls/RingView.cs index 5fd8fdd94..22c45d823 100644 --- a/ios10/SpeedSketch/SpeedSketch/Controls/RingView.cs +++ b/ios10/SpeedSketch/SpeedSketch/Controls/RingView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; @@ -7,18 +7,15 @@ using static SpeedSketch.RingControlState; using static SpeedSketch.CGMathExtensions; -namespace SpeedSketch -{ - public enum RingControlState - { +namespace SpeedSketch { + public enum RingControlState { Selected, Normal, LocationFan, LocationOrigin } - public class RingView : UIView - { + public class RingView : UIView { // Closures that configure the view for the corresponding state. public Dictionary<RingControlState, Action> StateClosures { get; } = new Dictionary<RingControlState, Action> (); @@ -63,7 +60,7 @@ public RingView (CGRect frame) public override bool PointInside (CGPoint point, UIEvent uievent) { // Quadrance as the square of the length requires less computation and cases - var quadrance = Vector(Bounds.GetCenter (), point).Quadrance (); + var quadrance = Vector (Bounds.GetCenter (), point).Quadrance (); var maxQuadrance = NMath.Pow (Bounds.Width / 2, 2); return quadrance < maxQuadrance; diff --git a/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGContextExtensions.cs b/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGContextExtensions.cs index 886eea5b5..38bf5038c 100644 --- a/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGContextExtensions.cs +++ b/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGContextExtensions.cs @@ -1,9 +1,7 @@ -using CoreGraphics; +using CoreGraphics; -namespace SpeedSketch -{ - public static class CGContextExtensions - { +namespace SpeedSketch { + public static class CGContextExtensions { public static void Move (this CGContext context, CGPoint point) { context.MoveTo (point.X, point.Y); diff --git a/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGDrawingEngine.cs b/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGDrawingEngine.cs index 18c77b006..dce3ebe9b 100644 --- a/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGDrawingEngine.cs +++ b/ios10/SpeedSketch/SpeedSketch/DrawingEngine/CGDrawingEngine.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using CoreGraphics; @@ -6,23 +6,19 @@ using static SpeedSketch.CGMathExtensions; -namespace SpeedSketch -{ - public enum StrokeViewDisplayOptions - { +namespace SpeedSketch { + public enum StrokeViewDisplayOptions { Debug, Calligraphy, Ink } - class EstimatedSample - { + class EstimatedSample { public int Index { get; set; } public StrokeSample Sample { get; set; } } - class StrokeCGView : UIView - { + class StrokeCGView : UIView { StrokeViewDisplayOptions displayOptions; public StrokeViewDisplayOptions DisplayOptions { get { @@ -81,7 +77,7 @@ Stroke StrokeToDraw { EstimatedSample lastEstimatedSample; public StrokeCGView (CGRect frame) - : base(frame) + : base (frame) { Layer.DrawsAsynchronously = true; @@ -319,7 +315,7 @@ void Draw (Stroke stroke) var toUnitVector = segment.ToSampleUnitNormal.Mult (forceAccessBlock (toSample)); var isForceEstimated = fromSample.EstimatedProperties.HasFlag (UITouchProperties.Force) - || toSample.EstimatedProperties.HasFlag (UITouchProperties.Force); + || toSample.EstimatedProperties.HasFlag (UITouchProperties.Force); if (isForceEstimated) { if (lastEstimatedSample == null) diff --git a/ios10/SpeedSketch/SpeedSketch/Helpers/CGMathExtensions.cs b/ios10/SpeedSketch/SpeedSketch/Helpers/CGMathExtensions.cs index 9519c6f7d..ef802b023 100644 --- a/ios10/SpeedSketch/SpeedSketch/Helpers/CGMathExtensions.cs +++ b/ios10/SpeedSketch/SpeedSketch/Helpers/CGMathExtensions.cs @@ -1,11 +1,9 @@ -using System; +using System; using CoreGraphics; -namespace SpeedSketch -{ - public static class CGMathExtensions - { +namespace SpeedSketch { + public static class CGMathExtensions { public static CGPoint GetCenter (this CGRect rect) { return Add (rect.Location, new CGVector (rect.Width, rect.Height).Divide (2)); @@ -49,8 +47,7 @@ public static nfloat Distance (CGPoint? point1, CGPoint? point2) } } - public static class CGVectorExtensions - { + public static class CGVectorExtensions { public static CGPoint CreatePoint (this CGVector self) { return new CGPoint (self.dx, self.dy); @@ -66,13 +63,13 @@ public static CGVector RoundTo (this CGVector self, nfloat scale) public static CGVector? Normalize (this CGVector self) { var quadrance = self.Quadrance (); - return (quadrance > 0) ? self.Divide (NMath.Sqrt(quadrance)) : (CGVector?)null; + return (quadrance > 0) ? self.Divide (NMath.Sqrt (quadrance)) : (CGVector?) null; } public static CGVector? Normal (this CGVector self) { bool isZero = (self.dx == 0 && self.dy == 0); - return isZero ? (CGVector?)null : new CGVector (-self.dy, self.dx); + return isZero ? (CGVector?) null : new CGVector (-self.dy, self.dx); } public static CGVector Divide (this CGVector left, nfloat right) @@ -96,8 +93,7 @@ public static CGVector Mult (this CGVector left, nfloat right) } } - public static class CGPointExtensions - { + public static class CGPointExtensions { public static CGVector CreateVector (this CGPoint self) { return new CGVector (self.X, self.Y); @@ -114,8 +110,7 @@ public static CGRect ToRect (this CGPoint location) } } - public static class CGSizeExtensions - { + public static class CGSizeExtensions { public static CGSize Add (this CGSize left, nfloat right) { return new CGSize (left.Width + right, left.Height + right); diff --git a/ios10/SpeedSketch/SpeedSketch/Helpers/CountableClosedRange.cs b/ios10/SpeedSketch/SpeedSketch/Helpers/CountableClosedRange.cs index 788c58fda..a8562cd3f 100644 --- a/ios10/SpeedSketch/SpeedSketch/Helpers/CountableClosedRange.cs +++ b/ios10/SpeedSketch/SpeedSketch/Helpers/CountableClosedRange.cs @@ -1,10 +1,8 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; -namespace SpeedSketch -{ - public class CountableClosedRange : IEnumerable<int> - { +namespace SpeedSketch { + public class CountableClosedRange : IEnumerable<int> { public int LowerBound { get; } public int UpperBound { get; } diff --git a/ios10/SpeedSketch/SpeedSketch/Helpers/Helpers.cs b/ios10/SpeedSketch/SpeedSketch/Helpers/Helpers.cs index f8f24a928..e6daeaec2 100644 --- a/ios10/SpeedSketch/SpeedSketch/Helpers/Helpers.cs +++ b/ios10/SpeedSketch/SpeedSketch/Helpers/Helpers.cs @@ -1,13 +1,11 @@ -using UIKit; +using UIKit; using Foundation; -namespace SpeedSketch -{ - public static class Helpers - { +namespace SpeedSketch { + public static class Helpers { public static NSNumber [] TouchTypes (UITouchType type) { - return new NSNumber [] { new NSNumber ((long)type) }; + return new NSNumber [] { new NSNumber ((long) type) }; } } } diff --git a/ios10/SpeedSketch/SpeedSketch/Main.cs b/ios10/SpeedSketch/SpeedSketch/Main.cs index 91f9f3da3..b067683f6 100644 --- a/ios10/SpeedSketch/SpeedSketch/Main.cs +++ b/ios10/SpeedSketch/SpeedSketch/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace SpeedSketch -{ - public class Application - { +namespace SpeedSketch { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/SpeedSketch/SpeedSketch/StrokeModel/Stroke.cs b/ios10/SpeedSketch/SpeedSketch/StrokeModel/Stroke.cs index 1ea761dcc..62b8d1129 100644 --- a/ios10/SpeedSketch/SpeedSketch/StrokeModel/Stroke.cs +++ b/ios10/SpeedSketch/SpeedSketch/StrokeModel/Stroke.cs @@ -1,19 +1,16 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using CoreGraphics; -namespace SpeedSketch -{ - public enum StrokeState - { +namespace SpeedSketch { + public enum StrokeState { Active, Done, Cancelled } - public class Stroke : IEnumerable<StrokeSegment> - { + public class Stroke : IEnumerable<StrokeSegment> { public static CGVector CalligraphyFallbackAzimuthUnitVector = new CGVector (1, 1).Normalize ().Value; public List<StrokeSample> Samples { get; } = new List<StrokeSample> (); diff --git a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeCollection.cs b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeCollection.cs index 726b379e4..0245b118f 100644 --- a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeCollection.cs +++ b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeCollection.cs @@ -1,9 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; -namespace SpeedSketch -{ - public class StrokeCollection - { +namespace SpeedSketch { + public class StrokeCollection { public Stroke ActiveStroke { get; set; } public List<Stroke> Strokes { get; } = new List<Stroke> (); diff --git a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeGestureRecognizer.cs b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeGestureRecognizer.cs index 3c48e5114..a8c7d9cc6 100644 --- a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeGestureRecognizer.cs +++ b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeGestureRecognizer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; @@ -10,14 +10,11 @@ using static SpeedSketch.Helpers; using static SpeedSketch.CGMathExtensions; -namespace SpeedSketch -{ - public class StrokeGestureRecognizer : UIGestureRecognizer - { +namespace SpeedSketch { + public class StrokeGestureRecognizer : UIGestureRecognizer { [Register ("__StrokeGestureRecognizer")] [Preserve (Conditional = true)] - class Callback : Token - { + class Callback : Token { readonly Action<StrokeGestureRecognizer> action; internal Callback (Action<StrokeGestureRecognizer> action) @@ -33,8 +30,7 @@ public void Activated (StrokeGestureRecognizer sender) } } - class StrokeIndex - { + class StrokeIndex { public Stroke Stroke { get; set; } public int Index { get; set; } } @@ -171,14 +167,14 @@ void Collect (Stroke stroke, UITouch touch, UIView view, bool coalesced, bool pr public override void TouchesBegan (NSSet touches, UIEvent evt) { if (trackedTouch == null) { - trackedTouch = (UITouch)touches.FirstOrDefault (); + trackedTouch = (UITouch) touches.FirstOrDefault (); initialTimestamp = trackedTouch.Timestamp; if (!IsForPencil) BeginIfNeeded (null); - fingerStartTimer = NSTimer.CreateScheduledTimer (cancellationTimeInterval, BeginIfNeeded); + fingerStartTimer = NSTimer.CreateScheduledTimer (cancellationTimeInterval, BeginIfNeeded); } - if (Append (Touches(touches), evt)) { + if (Append (Touches (touches), evt)) { if (IsForPencil) State = Began; } @@ -193,7 +189,7 @@ void BeginIfNeeded (NSTimer timer) public override void TouchesMoved (NSSet touches, UIEvent evt) { - if (Append (Touches(touches), evt)) { + if (Append (Touches (touches), evt)) { if (State == Began) State = Changed; } diff --git a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSample.cs b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSample.cs index c185a5280..a4c5b54c9 100644 --- a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSample.cs +++ b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSample.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; using CoreGraphics; using static CoreGraphics.CGAffineTransform; -namespace SpeedSketch -{ - public class StrokeSample - { +namespace SpeedSketch { + public class StrokeSample { // From the Apple's doc: // A touch object persists throughout a multi-touch sequence. // Never retain a touch object when handling an event. diff --git a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSegment.cs b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSegment.cs index ed9f7d8e4..58a20707b 100644 --- a/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSegment.cs +++ b/ios10/SpeedSketch/SpeedSketch/StrokeModel/StrokeSegment.cs @@ -1,11 +1,9 @@ -using CoreGraphics; +using CoreGraphics; using static SpeedSketch.CGMathExtensions; -namespace SpeedSketch -{ - public class StrokeSegment - { +namespace SpeedSketch { + public class StrokeSegment { public StrokeSample SampleBefore { get; private set; } public StrokeSample FromSample { get; private set; } public StrokeSample ToSample { get; private set; } @@ -16,7 +14,7 @@ CGVector PreviousSegmentStrokeVector { get { var start = SampleBefore?.Location; var end = FromSample.Location; - return start.HasValue ? Vector(start.Value, end) : SegmentStrokeVector; + return start.HasValue ? Vector (start.Value, end) : SegmentStrokeVector; } } @@ -24,7 +22,7 @@ CGVector NextSegmentStrokeVector { get { var start = ToSample.Location; var end = SampleAfter?.Location; - return end.HasValue ? Vector(start, end.Value) : SegmentStrokeVector; + return end.HasValue ? Vector (start, end.Value) : SegmentStrokeVector; } } diff --git a/ios10/SpeedSketch/SpeedSketch/UI/CanvasContainerView.cs b/ios10/SpeedSketch/SpeedSketch/UI/CanvasContainerView.cs index aeada8cb3..b14c28064 100644 --- a/ios10/SpeedSketch/SpeedSketch/UI/CanvasContainerView.cs +++ b/ios10/SpeedSketch/SpeedSketch/UI/CanvasContainerView.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace SpeedSketch -{ - public class CanvasContainerView : UIView - { +namespace SpeedSketch { + public class CanvasContainerView : UIView { UIView canvasView; UIView documentView; diff --git a/ios10/SpeedSketch/SpeedSketch/UI/CanvasMainViewController.cs b/ios10/SpeedSketch/SpeedSketch/UI/CanvasMainViewController.cs index 7931683fb..a6efbcd98 100644 --- a/ios10/SpeedSketch/SpeedSketch/UI/CanvasMainViewController.cs +++ b/ios10/SpeedSketch/SpeedSketch/UI/CanvasMainViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; @@ -10,10 +10,8 @@ using static UIKit.UIGestureRecognizerState; using static SpeedSketch.Helpers; -namespace SpeedSketch -{ - public class CanvasMainViewController : UIViewController, IUIScrollViewDelegate, IUIGestureRecognizerDelegate - { +namespace SpeedSketch { + public class CanvasMainViewController : UIViewController, IUIScrollViewDelegate, IUIGestureRecognizerDelegate { readonly List<UIButton> buttons = new List<UIButton> (); readonly List<NSObject> observers = new List<NSObject> (); @@ -270,7 +268,7 @@ void SetupPencilUI () NSObject observer = UIApplication.Notifications.ObserveWillEnterForeground ((sender, e) => { if (PencilMode - && (!LastSeenPencilInteraction.HasValue || (DateTime.Now.Ticks - LastSeenPencilInteraction.Value) > pencilResetInterval)) + && (!LastSeenPencilInteraction.HasValue || (DateTime.Now.Ticks - LastSeenPencilInteraction.Value) > pencilResetInterval)) StopPencilButtonAction (this, EventArgs.Empty); }); observers.Add (observer); @@ -301,7 +299,7 @@ public bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch) if (leftRingControl.HitTest (touch.LocationInView (leftRingControl), null) != null) return false; - foreach(var button in buttons) { + foreach (var button in buttons) { if (button.HitTest (touch.LocationInView (clearButton), null) != null) return false; } diff --git a/ios10/iOSTenThree/iOSTenThree/AppDelegate.cs b/ios10/iOSTenThree/iOSTenThree/AppDelegate.cs index 6fc5ec7c6..79e8d9882 100644 --- a/ios10/iOSTenThree/iOSTenThree/AppDelegate.cs +++ b/ios10/iOSTenThree/iOSTenThree/AppDelegate.cs @@ -1,14 +1,12 @@ -using Foundation; +using Foundation; using StoreKit; using UIKit; -namespace iOSTenThree -{ +namespace iOSTenThree { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios10/iOSTenThree/iOSTenThree/Main.cs b/ios10/iOSTenThree/iOSTenThree/Main.cs index c3c6a0f80..13b1ea504 100644 --- a/ios10/iOSTenThree/iOSTenThree/Main.cs +++ b/ios10/iOSTenThree/iOSTenThree/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace iOSTenThree -{ - public class Application - { +namespace iOSTenThree { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios10/iOSTenThree/iOSTenThree/ViewController.cs b/ios10/iOSTenThree/iOSTenThree/ViewController.cs index 0f31ebfad..588d2d651 100644 --- a/ios10/iOSTenThree/iOSTenThree/ViewController.cs +++ b/ios10/iOSTenThree/iOSTenThree/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace iOSTenThree -{ - public partial class ViewController : UIViewController - { +namespace iOSTenThree { + public partial class ViewController : UIViewController { #region Constructors protected ViewController (IntPtr handle) : base (handle) { diff --git a/ios11/ARKitAudio/ARKitAudio/AppDelegate.cs b/ios11/ARKitAudio/ARKitAudio/AppDelegate.cs index 576d164c3..b9f40c8b8 100644 --- a/ios11/ARKitAudio/ARKitAudio/AppDelegate.cs +++ b/ios11/ARKitAudio/ARKitAudio/AppDelegate.cs @@ -1,15 +1,13 @@ - -namespace ARKitAudio -{ - using Foundation; - using UIKit; - - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + +namespace ARKitAudio { + using Foundation; + using UIKit; + + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { @@ -49,4 +47,4 @@ public override void WillTerminate (UIApplication application) { } } -} \ No newline at end of file +} diff --git a/ios11/ARKitAudio/ARKitAudio/Extensions/ARSCNViewExtensions.cs b/ios11/ARKitAudio/ARKitAudio/Extensions/ARSCNViewExtensions.cs index 2165d65c2..8f605594b 100644 --- a/ios11/ARKitAudio/ARKitAudio/Extensions/ARSCNViewExtensions.cs +++ b/ios11/ARKitAudio/ARKitAudio/Extensions/ARSCNViewExtensions.cs @@ -1,228 +1,205 @@ - -namespace ARKitAudio -{ - using ARKit; - using CoreGraphics; - using OpenTK; - using SceneKit; - using System; - using System.Collections.Generic; - using System.Linq; - - /// <summary> - /// Convenience extensions on ARSCNView for hit testing - /// </summary> - public static class ARSCNViewExtensions - { - public static HitTestRay? HitTestRayFromScreenPosition(this ARSCNView view, CGPoint point) - { - HitTestRay? result = null; - using (var frame = view.Session.CurrentFrame) - { - if (frame != null) - { - var cameraPosition = frame.Camera.Transform.GetTranslation(); - - // Note: z: 1.0 will unproject() the screen position to the far clipping plane. - var positionVector = new SCNVector3((float)point.X, (float)point.Y, 1f); - - var screenPositionOnFarClippingPlane = view.UnprojectPoint(positionVector); - var rayDirection = SCNVector3.Normalize(screenPositionOnFarClippingPlane - cameraPosition); - - result = new HitTestRay { Origin = cameraPosition, Direction = rayDirection }; - } - } - - return result; - } - - public static SCNVector3? HitTestWithInfiniteHorizontalPlane(this ARSCNView view, CGPoint point, SCNVector3 pointOnPlane) - { - SCNVector3? result = null; - - var ray = view.HitTestRayFromScreenPosition(point); - if (ray.HasValue) - { - // Do not intersect with planes above the camera or if the ray is almost parallel to the plane. - if (ray.Value.Direction.Y <= -0.03f) - { - // Return the intersection of a ray from the camera through the screen position with a horizontal plane - // at height (Y axis). - result = Utilities.RayIntersectionWithHorizontalPlane(ray.Value.Origin, ray.Value.Direction, pointOnPlane.Y); - } - } - - return result; - } - - public static IList<FeatureHitTestResult> HitTestWithFeatures(this ARSCNView view, - CGPoint point, - float coneOpeningAngleInDegrees, - float minDistance = 0, - float maxDistance = float.MaxValue, - int maxResults = 1) - { - - var results = new List<FeatureHitTestResult>(); - - ARPointCloud features = null; - using(var frame = view.Session.CurrentFrame) - { - features = frame?.RawFeaturePoints; - } - - if (features != null) - { - var ray = view.HitTestRayFromScreenPosition(point); - if (ray.HasValue) - { - var maxAngleInDegrees = Math.Min(coneOpeningAngleInDegrees, 360f) / 2f; - var maxAngle = (maxAngleInDegrees / 180f) * Math.PI; - - var points = features.Points; - for (nuint j = 0; j < features.Count; j++) - { - var feature = points[j]; - - var featurePosition = new SCNVector3((Vector3)feature); - var originToFeature = featurePosition - ray.Value.Origin; - - var crossProduct = SCNVector3.Cross(originToFeature, ray.Value.Direction); - var featureDistanceFromResult = crossProduct.Length; - - var hitTestResult = ray.Value.Origin + (ray.Value.Direction * SCNVector3.Dot(ray.Value.Direction, originToFeature)); - var hitTestResultDistance = (hitTestResult - ray.Value.Origin).Length; - - if (hitTestResultDistance < minDistance || hitTestResultDistance > maxDistance) - { - // Skip this feature - it is too close or too far away. - continue; - } - - var originToFeatureNormalized = SCNVector3.Normalize(originToFeature); - var angleBetweenRayAndFeature = Math.Acos(SCNVector3.Dot(ray.Value.Direction, originToFeatureNormalized)); - - if (angleBetweenRayAndFeature > maxAngle) - { - // Skip this feature - is outside of the hit test cone. - continue; - } - - // All tests passed: Add the hit against this feature to the results. - results.Add(new FeatureHitTestResult - { - Position = hitTestResult, - DistanceToRayOrigin = hitTestResultDistance, - FeatureHit = featurePosition, - FeatureDistanceToHitResult = featureDistanceFromResult - }); - } - - // Sort the results by feature distance to the ray. - results = results.OrderBy(result => result.DistanceToRayOrigin).ToList(); - - // Cap the list to maxResults. - var cappedResults = new List<FeatureHitTestResult>(); - var i = 0; - - while (i < maxResults && i < results.Count) - { - cappedResults.Add(results[i]); - i += 1; - } - - results = cappedResults; - } - } - - return results; - } - - public static IList<FeatureHitTestResult> HitTestWithFeatures(this ARSCNView view, CGPoint point) - { - var results = new List<FeatureHitTestResult>(); - - var ray = view.HitTestRayFromScreenPosition(point); - if (ray.HasValue) - { - var result = view.HitTestFromOrigin(ray.Value.Origin, ray.Value.Direction); - if (result.HasValue) - { - results.Add(result.Value); - } - } - - return results; - } - - public static FeatureHitTestResult? HitTestFromOrigin(this ARSCNView view, SCNVector3 origin, SCNVector3 direction) - { - FeatureHitTestResult? result = null; - - ARPointCloud features = null; - using (var frame = view.Session.CurrentFrame) - { - features = frame?.RawFeaturePoints; - } - - if (features != null) - { - var points = features.Points; - - // Determine the point from the whole point cloud which is closest to the hit test ray. - var closestFeaturePoint = origin; - var minDistance = float.MaxValue; // Float.greatestFiniteMagnitude - - for (nuint i = 0; i < features.Count; i++) - { - var feature = points[i]; - - var featurePosition = new SCNVector3((Vector3)feature); - var originVector = origin - featurePosition; - - var crossProduct = SCNVector3.Cross(originVector, direction); - var featureDistanceFromResult = crossProduct.Length; - - if (featureDistanceFromResult < minDistance) - { - closestFeaturePoint = featurePosition; - minDistance = featureDistanceFromResult; - } - } - - // Compute the point along the ray that is closest to the selected feature. - var originToFeature = closestFeaturePoint - origin; - var hitTestResult = origin + (direction * SCNVector3.Dot(direction, originToFeature)); - var hitTestResultDistance = (hitTestResult - origin).Length; - - result = new FeatureHitTestResult - { - Position = hitTestResult, - DistanceToRayOrigin = hitTestResultDistance, - FeatureHit = closestFeaturePoint, - FeatureDistanceToHitResult = minDistance - }; - } - - return result; - } - } - - public struct HitTestRay - { - public SCNVector3 Origin { get; set; } - - public SCNVector3 Direction { get; set; } - } - - public struct FeatureHitTestResult - { - public SCNVector3 Position { get; set; } - - public float DistanceToRayOrigin { get; set; } - - public SCNVector3 FeatureHit { get; set; } - - public float FeatureDistanceToHitResult { get; set; } - } -} \ No newline at end of file + +namespace ARKitAudio { + using ARKit; + using CoreGraphics; + using OpenTK; + using SceneKit; + using System; + using System.Collections.Generic; + using System.Linq; + + /// <summary> + /// Convenience extensions on ARSCNView for hit testing + /// </summary> + public static class ARSCNViewExtensions { + public static HitTestRay? HitTestRayFromScreenPosition (this ARSCNView view, CGPoint point) + { + HitTestRay? result = null; + using (var frame = view.Session.CurrentFrame) { + if (frame != null) { + var cameraPosition = frame.Camera.Transform.GetTranslation (); + + // Note: z: 1.0 will unproject() the screen position to the far clipping plane. + var positionVector = new SCNVector3 ((float) point.X, (float) point.Y, 1f); + + var screenPositionOnFarClippingPlane = view.UnprojectPoint (positionVector); + var rayDirection = SCNVector3.Normalize (screenPositionOnFarClippingPlane - cameraPosition); + + result = new HitTestRay { Origin = cameraPosition, Direction = rayDirection }; + } + } + + return result; + } + + public static SCNVector3? HitTestWithInfiniteHorizontalPlane (this ARSCNView view, CGPoint point, SCNVector3 pointOnPlane) + { + SCNVector3? result = null; + + var ray = view.HitTestRayFromScreenPosition (point); + if (ray.HasValue) { + // Do not intersect with planes above the camera or if the ray is almost parallel to the plane. + if (ray.Value.Direction.Y <= -0.03f) { + // Return the intersection of a ray from the camera through the screen position with a horizontal plane + // at height (Y axis). + result = Utilities.RayIntersectionWithHorizontalPlane (ray.Value.Origin, ray.Value.Direction, pointOnPlane.Y); + } + } + + return result; + } + + public static IList<FeatureHitTestResult> HitTestWithFeatures (this ARSCNView view, + CGPoint point, + float coneOpeningAngleInDegrees, + float minDistance = 0, + float maxDistance = float.MaxValue, + int maxResults = 1) + { + + var results = new List<FeatureHitTestResult> (); + + ARPointCloud features = null; + using (var frame = view.Session.CurrentFrame) { + features = frame?.RawFeaturePoints; + } + + if (features != null) { + var ray = view.HitTestRayFromScreenPosition (point); + if (ray.HasValue) { + var maxAngleInDegrees = Math.Min (coneOpeningAngleInDegrees, 360f) / 2f; + var maxAngle = (maxAngleInDegrees / 180f) * Math.PI; + + var points = features.Points; + for (nuint j = 0; j < features.Count; j++) { + var feature = points [j]; + + var featurePosition = new SCNVector3 ((Vector3) feature); + var originToFeature = featurePosition - ray.Value.Origin; + + var crossProduct = SCNVector3.Cross (originToFeature, ray.Value.Direction); + var featureDistanceFromResult = crossProduct.Length; + + var hitTestResult = ray.Value.Origin + (ray.Value.Direction * SCNVector3.Dot (ray.Value.Direction, originToFeature)); + var hitTestResultDistance = (hitTestResult - ray.Value.Origin).Length; + + if (hitTestResultDistance < minDistance || hitTestResultDistance > maxDistance) { + // Skip this feature - it is too close or too far away. + continue; + } + + var originToFeatureNormalized = SCNVector3.Normalize (originToFeature); + var angleBetweenRayAndFeature = Math.Acos (SCNVector3.Dot (ray.Value.Direction, originToFeatureNormalized)); + + if (angleBetweenRayAndFeature > maxAngle) { + // Skip this feature - is outside of the hit test cone. + continue; + } + + // All tests passed: Add the hit against this feature to the results. + results.Add (new FeatureHitTestResult { + Position = hitTestResult, + DistanceToRayOrigin = hitTestResultDistance, + FeatureHit = featurePosition, + FeatureDistanceToHitResult = featureDistanceFromResult + }); + } + + // Sort the results by feature distance to the ray. + results = results.OrderBy (result => result.DistanceToRayOrigin).ToList (); + + // Cap the list to maxResults. + var cappedResults = new List<FeatureHitTestResult> (); + var i = 0; + + while (i < maxResults && i < results.Count) { + cappedResults.Add (results [i]); + i += 1; + } + + results = cappedResults; + } + } + + return results; + } + + public static IList<FeatureHitTestResult> HitTestWithFeatures (this ARSCNView view, CGPoint point) + { + var results = new List<FeatureHitTestResult> (); + + var ray = view.HitTestRayFromScreenPosition (point); + if (ray.HasValue) { + var result = view.HitTestFromOrigin (ray.Value.Origin, ray.Value.Direction); + if (result.HasValue) { + results.Add (result.Value); + } + } + + return results; + } + + public static FeatureHitTestResult? HitTestFromOrigin (this ARSCNView view, SCNVector3 origin, SCNVector3 direction) + { + FeatureHitTestResult? result = null; + + ARPointCloud features = null; + using (var frame = view.Session.CurrentFrame) { + features = frame?.RawFeaturePoints; + } + + if (features != null) { + var points = features.Points; + + // Determine the point from the whole point cloud which is closest to the hit test ray. + var closestFeaturePoint = origin; + var minDistance = float.MaxValue; // Float.greatestFiniteMagnitude + + for (nuint i = 0; i < features.Count; i++) { + var feature = points [i]; + + var featurePosition = new SCNVector3 ((Vector3) feature); + var originVector = origin - featurePosition; + + var crossProduct = SCNVector3.Cross (originVector, direction); + var featureDistanceFromResult = crossProduct.Length; + + if (featureDistanceFromResult < minDistance) { + closestFeaturePoint = featurePosition; + minDistance = featureDistanceFromResult; + } + } + + // Compute the point along the ray that is closest to the selected feature. + var originToFeature = closestFeaturePoint - origin; + var hitTestResult = origin + (direction * SCNVector3.Dot (direction, originToFeature)); + var hitTestResultDistance = (hitTestResult - origin).Length; + + result = new FeatureHitTestResult { + Position = hitTestResult, + DistanceToRayOrigin = hitTestResultDistance, + FeatureHit = closestFeaturePoint, + FeatureDistanceToHitResult = minDistance + }; + } + + return result; + } + } + + public struct HitTestRay { + public SCNVector3 Origin { get; set; } + + public SCNVector3 Direction { get; set; } + } + + public struct FeatureHitTestResult { + public SCNVector3 Position { get; set; } + + public float DistanceToRayOrigin { get; set; } + + public SCNVector3 FeatureHit { get; set; } + + public float FeatureDistanceToHitResult { get; set; } + } +} diff --git a/ios11/ARKitAudio/ARKitAudio/Extensions/Utilities.cs b/ios11/ARKitAudio/ARKitAudio/Extensions/Utilities.cs index 1c8d95663..c3444c31e 100644 --- a/ios11/ARKitAudio/ARKitAudio/Extensions/Utilities.cs +++ b/ios11/ARKitAudio/ARKitAudio/Extensions/Utilities.cs @@ -1,162 +1,146 @@ - -namespace ARKitAudio -{ - using ARKit; - using CoreGraphics; - using SceneKit; - using System.Collections; - using System.Collections.Generic; - using System.Linq; - - /// <summary> - /// Utility functions and type extensions used throughout the projects. - /// </summary> - public static class Utilities - { - public static SCNVector3? GetAverage(this IList<SCNVector3> vectors) - { - SCNVector3? result = null; - - if (vectors != null && vectors.Count > 0) - { - var sum = vectors.Aggregate(SCNVector3.Zero, (vector1, vector2) => vector1 + vector2); - result = sum / vectors.Count; - } - - return result; - } - - public static void KeepLast<T>(this List<T> list, int elementsToKeep) - { - if (list.Count > elementsToKeep) - { - list.RemoveRange(0, list.Count - elementsToKeep); - } - } - - /// <summary> - /// Treats matrix as a (right-hand column-major convention) transform matrix - /// and factors out the translation component of the transform. - /// </summary> - public static OpenTK.Vector3 GetTranslation(this OpenTK.NMatrix4 matrix) - { - var translation = matrix.Column3; - return new OpenTK.Vector3(translation.X, translation.Y, translation.Z); - } - - #region Math - - public static SCNVector3? RayIntersectionWithHorizontalPlane(SCNVector3 rayOrigin, SCNVector3 direction, float planeY) - { - direction = SCNVector3.Normalize(direction); - - // Special case handling: Check if the ray is horizontal as well. - if (direction.Y == 0) - { - if (rayOrigin.Y == planeY) - { - // The ray is horizontal and on the plane, thus all points on the ray intersect with the plane. - // Therefore we simply return the ray origin. - return rayOrigin; - } - else - { - // The ray is parallel to the plane and never intersects. - return null; - } - } - - // The distance from the ray's origin to the intersection point on the plane is: - // (pointOnPlane - rayOrigin) dot planeNormal - // -------------------------------------------- - // direction dot planeNormal - - // Since we know that horizontal planes have normal (0, 1, 0), we can simplify this to: - var dist = (planeY - rayOrigin.Y) / direction.Y; - - // Do not return intersections behind the ray's origin. - if (dist < 0) - { - return null; - } - - // Return the intersection point. - return rayOrigin + (direction * dist); - } - - public static (SCNVector3?, ARPlaneAnchor, bool) WorldPositionFromScreenPosition(CGPoint position, - ARSCNView sceneView, - SCNVector3? objectPos, - bool infinitePlane = false) - { - // ------------------------------------------------------------------------------- - // 1. Always do a hit test against existing plane anchors first. - // (If any such anchors exist & only within their extents.) - - var result = sceneView.HitTest(position, ARHitTestResultType.ExistingPlaneUsingExtent)?.FirstOrDefault(); - if (result != null) - { - var planeHitTestPosition = result.WorldTransform.GetTranslation(); - var planeAnchor = result.Anchor; - - // Return immediately - this is the best possible outcome. - return (planeHitTestPosition, planeAnchor as ARPlaneAnchor, true); - } - - // ------------------------------------------------------------------------------- - // 2. Collect more information about the environment by hit testing against - // the feature point cloud, but do not return the result yet. - - SCNVector3? featureHitTestPosition = null; - var highQualityFeatureHitTestResult = false; - - var highQualityfeatureHitTestResults = sceneView.HitTestWithFeatures(position, 18f, 0.2f, 2f); - if (highQualityfeatureHitTestResults.Any()) - { - featureHitTestPosition = highQualityfeatureHitTestResults[0].Position; - highQualityFeatureHitTestResult = true; - } - - // ------------------------------------------------------------------------------- - // 3. If desired or necessary (no good feature hit test result): Hit test - // against an infinite, horizontal plane (ignoring the real world). - - if (infinitePlane || !highQualityFeatureHitTestResult) - { - if (objectPos.HasValue) - { - var pointOnInfinitePlane = sceneView.HitTestWithInfiniteHorizontalPlane(position, objectPos.Value); - if (pointOnInfinitePlane.HasValue) - { - return (pointOnInfinitePlane, null, true); - } - } - } - - // ------------------------------------------------------------------------------- - // 4. If available, return the result of the hit test against high quality - // features if the hit tests against infinite planes were skipped or no - // infinite plane was hit. - - if (highQualityFeatureHitTestResult) - { - return (featureHitTestPosition, null, false); - } - - // ------------------------------------------------------------------------------- - // 5. As a last resort, perform a second, unfiltered hit test against features. - // If there are no features in the scene, the result returned here will be nil. - - var unfilteredFeatureHitTestResults = sceneView.HitTestWithFeatures(position); - if (unfilteredFeatureHitTestResults.Any()) - { - var first = unfilteredFeatureHitTestResults[0]; - return (first.Position, null, false); - } - - return (null, null, false); - } - - #endregion - } + +namespace ARKitAudio { + using ARKit; + using CoreGraphics; + using SceneKit; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + /// <summary> + /// Utility functions and type extensions used throughout the projects. + /// </summary> + public static class Utilities { + public static SCNVector3? GetAverage (this IList<SCNVector3> vectors) + { + SCNVector3? result = null; + + if (vectors != null && vectors.Count > 0) { + var sum = vectors.Aggregate (SCNVector3.Zero, (vector1, vector2) => vector1 + vector2); + result = sum / vectors.Count; + } + + return result; + } + + public static void KeepLast<T> (this List<T> list, int elementsToKeep) + { + if (list.Count > elementsToKeep) { + list.RemoveRange (0, list.Count - elementsToKeep); + } + } + + /// <summary> + /// Treats matrix as a (right-hand column-major convention) transform matrix + /// and factors out the translation component of the transform. + /// </summary> + public static OpenTK.Vector3 GetTranslation (this OpenTK.NMatrix4 matrix) + { + var translation = matrix.Column3; + return new OpenTK.Vector3 (translation.X, translation.Y, translation.Z); + } + + #region Math + + public static SCNVector3? RayIntersectionWithHorizontalPlane (SCNVector3 rayOrigin, SCNVector3 direction, float planeY) + { + direction = SCNVector3.Normalize (direction); + + // Special case handling: Check if the ray is horizontal as well. + if (direction.Y == 0) { + if (rayOrigin.Y == planeY) { + // The ray is horizontal and on the plane, thus all points on the ray intersect with the plane. + // Therefore we simply return the ray origin. + return rayOrigin; + } else { + // The ray is parallel to the plane and never intersects. + return null; + } + } + + // The distance from the ray's origin to the intersection point on the plane is: + // (pointOnPlane - rayOrigin) dot planeNormal + // -------------------------------------------- + // direction dot planeNormal + + // Since we know that horizontal planes have normal (0, 1, 0), we can simplify this to: + var dist = (planeY - rayOrigin.Y) / direction.Y; + + // Do not return intersections behind the ray's origin. + if (dist < 0) { + return null; + } + + // Return the intersection point. + return rayOrigin + (direction * dist); + } + + public static (SCNVector3?, ARPlaneAnchor, bool) WorldPositionFromScreenPosition (CGPoint position, + ARSCNView sceneView, + SCNVector3? objectPos, + bool infinitePlane = false) + { + // ------------------------------------------------------------------------------- + // 1. Always do a hit test against existing plane anchors first. + // (If any such anchors exist & only within their extents.) + + var result = sceneView.HitTest (position, ARHitTestResultType.ExistingPlaneUsingExtent)?.FirstOrDefault (); + if (result != null) { + var planeHitTestPosition = result.WorldTransform.GetTranslation (); + var planeAnchor = result.Anchor; + + // Return immediately - this is the best possible outcome. + return (planeHitTestPosition, planeAnchor as ARPlaneAnchor, true); + } + + // ------------------------------------------------------------------------------- + // 2. Collect more information about the environment by hit testing against + // the feature point cloud, but do not return the result yet. + + SCNVector3? featureHitTestPosition = null; + var highQualityFeatureHitTestResult = false; + + var highQualityfeatureHitTestResults = sceneView.HitTestWithFeatures (position, 18f, 0.2f, 2f); + if (highQualityfeatureHitTestResults.Any ()) { + featureHitTestPosition = highQualityfeatureHitTestResults [0].Position; + highQualityFeatureHitTestResult = true; + } + + // ------------------------------------------------------------------------------- + // 3. If desired or necessary (no good feature hit test result): Hit test + // against an infinite, horizontal plane (ignoring the real world). + + if (infinitePlane || !highQualityFeatureHitTestResult) { + if (objectPos.HasValue) { + var pointOnInfinitePlane = sceneView.HitTestWithInfiniteHorizontalPlane (position, objectPos.Value); + if (pointOnInfinitePlane.HasValue) { + return (pointOnInfinitePlane, null, true); + } + } + } + + // ------------------------------------------------------------------------------- + // 4. If available, return the result of the hit test against high quality + // features if the hit tests against infinite planes were skipped or no + // infinite plane was hit. + + if (highQualityFeatureHitTestResult) { + return (featureHitTestPosition, null, false); + } + + // ------------------------------------------------------------------------------- + // 5. As a last resort, perform a second, unfiltered hit test against features. + // If there are no features in the scene, the result returned here will be nil. + + var unfilteredFeatureHitTestResults = sceneView.HitTestWithFeatures (position); + if (unfilteredFeatureHitTestResults.Any ()) { + var first = unfilteredFeatureHitTestResults [0]; + return (first.Position, null, false); + } + + return (null, null, false); + } + + #endregion + } } diff --git a/ios11/ARKitAudio/ARKitAudio/Main.cs b/ios11/ARKitAudio/ARKitAudio/Main.cs index f4c31b072..0459dd619 100644 --- a/ios11/ARKitAudio/ARKitAudio/Main.cs +++ b/ios11/ARKitAudio/ARKitAudio/Main.cs @@ -1,16 +1,14 @@ - -namespace ARKitAudio -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace ARKitAudio { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios11/ARKitAudio/ARKitAudio/PreviewNode.cs b/ios11/ARKitAudio/ARKitAudio/PreviewNode.cs index a8a114204..4fab1dd87 100644 --- a/ios11/ARKitAudio/ARKitAudio/PreviewNode.cs +++ b/ios11/ARKitAudio/ARKitAudio/PreviewNode.cs @@ -1,67 +1,63 @@ - -namespace ARKitAudio -{ - using ARKit; - using Foundation; - using SceneKit; - using System; - using System.Collections.Generic; - /// <summary> - /// SceneKit node wrapper that estimates an object's final placement - /// </summary> - public class PreviewNode : SCNNode - { - // Use average of recent positions to avoid jitter. - private readonly List<SCNVector3> recentPreviewNodePositions = new List<SCNVector3>(); - - // Saved positions that help smooth the movement of the preview - private SCNVector3 lastPositionOnPlane; - - // Saved positions that help smooth the movement of the preview - private SCNVector3 lastPosition; - - public PreviewNode(IntPtr handle) : base(handle) { } - - public PreviewNode(NSCoder coder) - { - throw new NotImplementedException("init(coder:) has not been implemented"); - } - - public PreviewNode(SCNNode node) : base() - { - this.Opacity = 0.5f; - this.AddChildNode(node); - } - - // Appearance - - public void Update(SCNVector3 position, ARPlaneAnchor planeAnchor, ARCamera camera) - { - this.lastPosition = position; - - if (planeAnchor != null) - { - this.lastPositionOnPlane = position; - } - - this.UpdateTransform(position, camera); - } - - private void UpdateTransform(SCNVector3 position, ARCamera camera) - { - // Add to the list of recent positions. - this.recentPreviewNodePositions.Add(position); - - // Remove anything older than the last 8 positions. - this.recentPreviewNodePositions.KeepLast(8); - - // Move to average of recent positions to avoid jitter. - var average = this.recentPreviewNodePositions.GetAverage(); - if (average.HasValue) - { - this.Position = average.Value; - } - } - } -} \ No newline at end of file +namespace ARKitAudio { + using ARKit; + using Foundation; + using SceneKit; + using System; + using System.Collections.Generic; + + /// <summary> + /// SceneKit node wrapper that estimates an object's final placement + /// </summary> + public class PreviewNode : SCNNode { + // Use average of recent positions to avoid jitter. + private readonly List<SCNVector3> recentPreviewNodePositions = new List<SCNVector3> (); + + // Saved positions that help smooth the movement of the preview + private SCNVector3 lastPositionOnPlane; + + // Saved positions that help smooth the movement of the preview + private SCNVector3 lastPosition; + + public PreviewNode (IntPtr handle) : base (handle) { } + + public PreviewNode (NSCoder coder) + { + throw new NotImplementedException ("init(coder:) has not been implemented"); + } + + public PreviewNode (SCNNode node) : base () + { + this.Opacity = 0.5f; + this.AddChildNode (node); + } + + // Appearance + + public void Update (SCNVector3 position, ARPlaneAnchor planeAnchor, ARCamera camera) + { + this.lastPosition = position; + + if (planeAnchor != null) { + this.lastPositionOnPlane = position; + } + + this.UpdateTransform (position, camera); + } + + private void UpdateTransform (SCNVector3 position, ARCamera camera) + { + // Add to the list of recent positions. + this.recentPreviewNodePositions.Add (position); + + // Remove anything older than the last 8 positions. + this.recentPreviewNodePositions.KeepLast (8); + + // Move to average of recent positions to avoid jitter. + var average = this.recentPreviewNodePositions.GetAverage (); + if (average.HasValue) { + this.Position = average.Value; + } + } + } +} diff --git a/ios11/ARKitAudio/ARKitAudio/Properties/AssemblyInfo.cs b/ios11/ARKitAudio/ARKitAudio/Properties/AssemblyInfo.cs index e439b3106..fe1b4e26a 100644 --- a/ios11/ARKitAudio/ARKitAudio/Properties/AssemblyInfo.cs +++ b/ios11/ARKitAudio/ARKitAudio/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("ARKitAudio")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ARKitAudio")] -[assembly: AssemblyCopyright("Copyright © 2018")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("ARKitAudio")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("ARKitAudio")] +[assembly: AssemblyCopyright ("Copyright © 2018")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("bc14a9a0-f771-4c15-bcd7-7974a2a71260")] +[assembly: Guid ("bc14a9a0-f771-4c15-bcd7-7974a2a71260")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios11/ARKitAudio/ARKitAudio/ViewController.cs b/ios11/ARKitAudio/ARKitAudio/ViewController.cs index 89076b1c9..bc71121ba 100644 --- a/ios11/ARKitAudio/ARKitAudio/ViewController.cs +++ b/ios11/ARKitAudio/ARKitAudio/ViewController.cs @@ -1,363 +1,340 @@ - -namespace ARKitAudio -{ - using ARKit; - using AVFoundation; - using CoreGraphics; - using Foundation; - using OpenTK; - using SceneKit; - using System; - using System.Linq; - using UIKit; - - /// <summary> - /// Main view controller for the AR experience. - /// </summary> - public partial class ViewController : UIViewController, IARSCNViewDelegate - { - private CGPoint screenCenter = CGPoint.Empty; - - // Shows a preview of the object to be placed and hovers over estimated planes. - private PreviewNode previewNode; - - // Contains the cup model that is shared by the preview and final nodes. - private SCNNode cupNode = new SCNNode(); - - // Audio source for positional audio feedback. - private SCNAudioSource source; - - public ViewController(IntPtr handle) : base(handle) { } - - #region View Life Cycle - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.sceneView.Delegate = this; - - // Show statistics such as FPS and timing information. - this.sceneView.ShowsStatistics = true; - - // Setup environment mapping. - var environmentMap = UIImage.FromBundle("art.scnassets/sharedImages/environment_blur.exr"); - this.sceneView.Scene.LightingEnvironment.Contents = environmentMap; - - // Complete rendering setup of ARSCNView. - this.sceneView.AntialiasingMode = SCNAntialiasingMode.Multisampling4X; - this.sceneView.AutomaticallyUpdatesLighting = false; - this.sceneView.ContentScaleFactor = 1.3f; - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - // Preload the audio file. - this.source = SCNAudioSource.FromFile("art.scnassets/ping.aif"); - this.source.Loops = true; - this.source.Load(); - - if (ARConfiguration.IsSupported) - { - // Start the ARSession. - var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; - this.sceneView.Session.Run(configuration, default(ARSessionRunOptions)); - - this.screenCenter = new CGPoint(this.sceneView.Bounds.GetMidX(), this.sceneView.Bounds.GetMidY()); - - // Prevent the screen from being dimmed after a while as users will likely have - // long periods of interaction without touching the screen or buttons. - UIApplication.SharedApplication.IdleTimerDisabled = true; - } - else - { - this.ShowUnsupportedDeviceError(); - } - } - - public override void ViewWillDisappear(bool animated) - { - base.ViewWillDisappear(animated); - - this.cupNode.RemoveAllAudioPlayers(); - - // Pause the view's session. - this.sceneView.Session.Pause(); - } - - public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) - { - base.ViewWillTransitionToSize(toSize, coordinator); - - // The screen's center point changes on orientation switch, so recalculate `screenCenter`. - this.screenCenter = new CGPoint(toSize.Width / 2f, toSize.Height / 2f); - } - - #endregion - - #region Internal methods - - private void ShowUnsupportedDeviceError() - { - // This device does not support 6DOF world tracking. - var alertController = UIAlertController.Create("ARKit is not available on this device.", - "This app requires world tracking, which is available only on iOS devices with the A9 processor or later.", - UIAlertControllerStyle.Alert); - - alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - this.PresentModalViewController(alertController, true); - } - - /// <summary> - /// Check the light estimate from the current ARFrame and update the scene. - /// </summary> - private void UpdateLightEstimate() - { - using (var frame = this.sceneView.Session.CurrentFrame) - { - var lightEstimate = frame?.LightEstimate; - if (lightEstimate != null) - { - this.sceneView.Scene.LightingEnvironment.Intensity = lightEstimate.AmbientIntensity / 40f; - } - else - { - this.sceneView.Scene.LightingEnvironment.Intensity = 40f; - } - } - } - - private void ResetTracking() - { - var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; - this.sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - - // Reset preview state. - this.cupNode.RemoveFromParentNode(); - this.cupNode.Dispose(); - this.cupNode = new SCNNode(); - - this.previewNode?.RemoveFromParentNode(); - this.previewNode?.Dispose(); - this.previewNode = null; - - this.PlaySound(); - } - - private void SetNewVirtualObjectToAnchor(SCNNode node, ARAnchor anchor, NMatrix4 cameraTransform) - { - var cameraWorldPosition = cameraTransform.GetTranslation(); - var cameraToPosition = anchor.Transform.GetTranslation() - cameraWorldPosition; - - // Limit the distance of the object from the camera to a maximum of 10 meters. - if (cameraToPosition.Length > 10f) - { - cameraToPosition = Vector3.Normalize(cameraToPosition); - cameraToPosition *= 10f; - } - - node.Position = cameraWorldPosition + cameraToPosition; - } - - #endregion - - #region ARSCNViewDelegate - - /// <summary> - /// UpdateAudioPlayback - /// </summary> - [Export("renderer:updateAtTime:")] - public void Update(ISCNSceneRenderer renderer, double timeInSeconds) - { - if (this.cupNode.ParentNode == null && this.previewNode == null) - { - // If our model hasn't been placed and we lack a preview for placement then setup a preview. - this.SetupPreviewNode(); - this.UpdatePreviewNode(); - } - else - { - this.UpdatePreviewNode(); - } - - this.UpdateLightEstimate(); - this.CutVolumeIfPlacedObjectIsInView(); - } - - /// <summary> - /// PlaceARContent - /// </summary> - [Export("renderer:didAddNode:forAnchor:")] - public void DidAddNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) - { - // Place content only for anchors found by plane detection. - if (anchor is ARPlaneAnchor && this.previewNode != null) - { - // Stop showing a preview version of the object to be placed. - this.cupNode.RemoveFromParentNode(); - - this.previewNode?.RemoveFromParentNode(); - this.previewNode?.Dispose(); - this.previewNode = null; - - // Add the cupNode to the scene's root node using the anchor's position. - var cameraTransform = this.sceneView.Session.CurrentFrame?.Camera?.Transform; - if (cameraTransform.HasValue) - { - this.SetNewVirtualObjectToAnchor(this.cupNode, anchor, cameraTransform.Value); - this.sceneView.Scene.RootNode.AddChildNode(this.cupNode); - - // Disable plane detection after the model has been added. - var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; - this.sceneView.Session.Run(configuration, default(ARSessionRunOptions)); - - // Set up positional audio to play in case the object moves offscreen. - this.PlaySound(); - } - } - } - - /// <summary> - /// PlaceARContent - /// </summary> - [Export("session:cameraDidChangeTrackingState:")] - private void CameraDidChangeTrackingState(ARSession session, ARCamera camera) - { - var message = string.Empty; - - // Inform the user of their camera tracking state. - switch (camera.TrackingState) - { - case ARTrackingState.NotAvailable: - message = "Tracking unavailable"; - break; - - case ARTrackingState.Limited: - switch (camera.TrackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: - message = "Tracking limited - Too much camera movement"; - break; - case ARTrackingStateReason.InsufficientFeatures: - message = "Tracking limited - Not enough surface detail"; - break; - case ARTrackingStateReason.Initializing: - message = "Initializing AR Session"; - break; - } - break; - - case ARTrackingState.Normal: - message = "Tracking normal"; - break; - } - - this.sessionInfoLabel.Text = message; - } - - [Export("session:didFailWithError:")] - public void DidFail(ARSession session, NSError error) - { - // Present an error message to the user. - this.sessionInfoLabel.Text = $"Session failed: {error.LocalizedDescription}"; - this.ResetTracking(); - } - - [Export("sessionWasInterrupted:")] - public void WasInterrupted(ARSession session) - { - // Inform the user that the session has been interrupted, for example, by presenting an overlay. - this.sessionInfoLabel.Text = "Session was interrupted"; - this.ResetTracking(); - } - - [Export("sessionInterruptionEnded:")] - public void InterruptionEnded(ARSession session) - { - // Reset tracking and/or remove existing anchors if consistent tracking is required. - this.sessionInfoLabel.Text = "Session interruption ended"; - this.ResetTracking(); - } - - #endregion - - #region Preview Node - - /// <summary> - /// Loads the cup model (`cupNode`) that is used for the duration of the app. - /// Initializes a `PreviewNode` that contains the `cupNode` and adds it to the node hierarchy. - /// </summary> - private void SetupPreviewNode() - { - if (this.cupNode.FindChildNode("candle", false) == null) - { - // Load the cup scene from the bundle only once. - var modelScene = SCNScene.FromFile("art.scnassets/candle/candle.scn"); - // Get a handle to the cup model. - var cup = modelScene.RootNode.FindChildNode("candle", true); - // Set the cup model onto `cupNode`. - this.cupNode.AddChildNode(cup); - } - - // Initialize `previewNode` to display the cup model. - this.previewNode = new PreviewNode(this.cupNode); - // Add `previewNode` to the node hierarchy. - this.sceneView.Scene.RootNode.AddChildNode(this.previewNode); - } - - /// <summary> - /// `previewNode` exists when ARKit is finding a plane. During this time, get a world position for the areas closest to the scene's point of view that ARKit believes might be a plane, and use it to update the `previewNode` position. - /// </summary> - private void UpdatePreviewNode() - { - if (this.previewNode != null) - { - var (worldPosition, planeAnchor, _) = Utilities.WorldPositionFromScreenPosition(this.screenCenter, this.sceneView, this.previewNode.Position); - if (worldPosition.HasValue) - { - this.previewNode.Update(worldPosition.Value, planeAnchor, this.sceneView.Session.CurrentFrame?.Camera); - } - } - } - - #endregion - - #region Sound - - /// <summary> - /// Determines whether the `cupNode` is visible. If the `cupNode` isn't visible, a sound is played using - /// SceneKit's positional audio functionality to locate the `cupNode`. - /// </summary> - private void CutVolumeIfPlacedObjectIsInView() - { - if (this.previewNode == null && this.sceneView.PointOfView != null) - { - var player = this.cupNode.AudioPlayers?.FirstOrDefault(); - var avNode = player?.AudioNode as AVAudioPlayerNode; - if (player != null && avNode != null) - { - var placedObjectIsInView = this.sceneView.IsNodeInsideFrustum(this.cupNode, this.sceneView.PointOfView); - avNode.Volume = placedObjectIsInView ? 0f : 1f; - } - } - } - - /// <summary> - /// Plays a sound on the cupNode using SceneKit's positional audio. - /// </summary> - private void PlaySound() - { - // ensure there is only one audio player - this.cupNode.RemoveAllAudioPlayers(); - - if (this.cupNode.AudioPlayers == null || !this.cupNode.AudioPlayers.Any()) - { - this.cupNode.AddAudioPlayer(new SCNAudioPlayer(this.source)); - } - } - - #endregion - } -} \ No newline at end of file + +namespace ARKitAudio { + using ARKit; + using AVFoundation; + using CoreGraphics; + using Foundation; + using OpenTK; + using SceneKit; + using System; + using System.Linq; + using UIKit; + + /// <summary> + /// Main view controller for the AR experience. + /// </summary> + public partial class ViewController : UIViewController, IARSCNViewDelegate { + private CGPoint screenCenter = CGPoint.Empty; + + // Shows a preview of the object to be placed and hovers over estimated planes. + private PreviewNode previewNode; + + // Contains the cup model that is shared by the preview and final nodes. + private SCNNode cupNode = new SCNNode (); + + // Audio source for positional audio feedback. + private SCNAudioSource source; + + public ViewController (IntPtr handle) : base (handle) { } + + #region View Life Cycle + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.sceneView.Delegate = this; + + // Show statistics such as FPS and timing information. + this.sceneView.ShowsStatistics = true; + + // Setup environment mapping. + var environmentMap = UIImage.FromBundle ("art.scnassets/sharedImages/environment_blur.exr"); + this.sceneView.Scene.LightingEnvironment.Contents = environmentMap; + + // Complete rendering setup of ARSCNView. + this.sceneView.AntialiasingMode = SCNAntialiasingMode.Multisampling4X; + this.sceneView.AutomaticallyUpdatesLighting = false; + this.sceneView.ContentScaleFactor = 1.3f; + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + // Preload the audio file. + this.source = SCNAudioSource.FromFile ("art.scnassets/ping.aif"); + this.source.Loops = true; + this.source.Load (); + + if (ARConfiguration.IsSupported) { + // Start the ARSession. + var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; + this.sceneView.Session.Run (configuration, default (ARSessionRunOptions)); + + this.screenCenter = new CGPoint (this.sceneView.Bounds.GetMidX (), this.sceneView.Bounds.GetMidY ()); + + // Prevent the screen from being dimmed after a while as users will likely have + // long periods of interaction without touching the screen or buttons. + UIApplication.SharedApplication.IdleTimerDisabled = true; + } else { + this.ShowUnsupportedDeviceError (); + } + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + + this.cupNode.RemoveAllAudioPlayers (); + + // Pause the view's session. + this.sceneView.Session.Pause (); + } + + public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) + { + base.ViewWillTransitionToSize (toSize, coordinator); + + // The screen's center point changes on orientation switch, so recalculate `screenCenter`. + this.screenCenter = new CGPoint (toSize.Width / 2f, toSize.Height / 2f); + } + + #endregion + + #region Internal methods + + private void ShowUnsupportedDeviceError () + { + // This device does not support 6DOF world tracking. + var alertController = UIAlertController.Create ("ARKit is not available on this device.", + "This app requires world tracking, which is available only on iOS devices with the A9 processor or later.", + UIAlertControllerStyle.Alert); + + alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + this.PresentModalViewController (alertController, true); + } + + /// <summary> + /// Check the light estimate from the current ARFrame and update the scene. + /// </summary> + private void UpdateLightEstimate () + { + using (var frame = this.sceneView.Session.CurrentFrame) { + var lightEstimate = frame?.LightEstimate; + if (lightEstimate != null) { + this.sceneView.Scene.LightingEnvironment.Intensity = lightEstimate.AmbientIntensity / 40f; + } else { + this.sceneView.Scene.LightingEnvironment.Intensity = 40f; + } + } + } + + private void ResetTracking () + { + var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; + this.sceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + + // Reset preview state. + this.cupNode.RemoveFromParentNode (); + this.cupNode.Dispose (); + this.cupNode = new SCNNode (); + + this.previewNode?.RemoveFromParentNode (); + this.previewNode?.Dispose (); + this.previewNode = null; + + this.PlaySound (); + } + + private void SetNewVirtualObjectToAnchor (SCNNode node, ARAnchor anchor, NMatrix4 cameraTransform) + { + var cameraWorldPosition = cameraTransform.GetTranslation (); + var cameraToPosition = anchor.Transform.GetTranslation () - cameraWorldPosition; + + // Limit the distance of the object from the camera to a maximum of 10 meters. + if (cameraToPosition.Length > 10f) { + cameraToPosition = Vector3.Normalize (cameraToPosition); + cameraToPosition *= 10f; + } + + node.Position = cameraWorldPosition + cameraToPosition; + } + + #endregion + + #region ARSCNViewDelegate + + /// <summary> + /// UpdateAudioPlayback + /// </summary> + [Export ("renderer:updateAtTime:")] + public void Update (ISCNSceneRenderer renderer, double timeInSeconds) + { + if (this.cupNode.ParentNode == null && this.previewNode == null) { + // If our model hasn't been placed and we lack a preview for placement then setup a preview. + this.SetupPreviewNode (); + this.UpdatePreviewNode (); + } else { + this.UpdatePreviewNode (); + } + + this.UpdateLightEstimate (); + this.CutVolumeIfPlacedObjectIsInView (); + } + + /// <summary> + /// PlaceARContent + /// </summary> + [Export ("renderer:didAddNode:forAnchor:")] + public void DidAddNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + { + // Place content only for anchors found by plane detection. + if (anchor is ARPlaneAnchor && this.previewNode != null) { + // Stop showing a preview version of the object to be placed. + this.cupNode.RemoveFromParentNode (); + + this.previewNode?.RemoveFromParentNode (); + this.previewNode?.Dispose (); + this.previewNode = null; + + // Add the cupNode to the scene's root node using the anchor's position. + var cameraTransform = this.sceneView.Session.CurrentFrame?.Camera?.Transform; + if (cameraTransform.HasValue) { + this.SetNewVirtualObjectToAnchor (this.cupNode, anchor, cameraTransform.Value); + this.sceneView.Scene.RootNode.AddChildNode (this.cupNode); + + // Disable plane detection after the model has been added. + var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; + this.sceneView.Session.Run (configuration, default (ARSessionRunOptions)); + + // Set up positional audio to play in case the object moves offscreen. + this.PlaySound (); + } + } + } + + /// <summary> + /// PlaceARContent + /// </summary> + [Export ("session:cameraDidChangeTrackingState:")] + private void CameraDidChangeTrackingState (ARSession session, ARCamera camera) + { + var message = string.Empty; + + // Inform the user of their camera tracking state. + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + message = "Tracking unavailable"; + break; + + case ARTrackingState.Limited: + switch (camera.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: + message = "Tracking limited - Too much camera movement"; + break; + case ARTrackingStateReason.InsufficientFeatures: + message = "Tracking limited - Not enough surface detail"; + break; + case ARTrackingStateReason.Initializing: + message = "Initializing AR Session"; + break; + } + break; + + case ARTrackingState.Normal: + message = "Tracking normal"; + break; + } + + this.sessionInfoLabel.Text = message; + } + + [Export ("session:didFailWithError:")] + public void DidFail (ARSession session, NSError error) + { + // Present an error message to the user. + this.sessionInfoLabel.Text = $"Session failed: {error.LocalizedDescription}"; + this.ResetTracking (); + } + + [Export ("sessionWasInterrupted:")] + public void WasInterrupted (ARSession session) + { + // Inform the user that the session has been interrupted, for example, by presenting an overlay. + this.sessionInfoLabel.Text = "Session was interrupted"; + this.ResetTracking (); + } + + [Export ("sessionInterruptionEnded:")] + public void InterruptionEnded (ARSession session) + { + // Reset tracking and/or remove existing anchors if consistent tracking is required. + this.sessionInfoLabel.Text = "Session interruption ended"; + this.ResetTracking (); + } + + #endregion + + #region Preview Node + + /// <summary> + /// Loads the cup model (`cupNode`) that is used for the duration of the app. + /// Initializes a `PreviewNode` that contains the `cupNode` and adds it to the node hierarchy. + /// </summary> + private void SetupPreviewNode () + { + if (this.cupNode.FindChildNode ("candle", false) == null) { + // Load the cup scene from the bundle only once. + var modelScene = SCNScene.FromFile ("art.scnassets/candle/candle.scn"); + // Get a handle to the cup model. + var cup = modelScene.RootNode.FindChildNode ("candle", true); + // Set the cup model onto `cupNode`. + this.cupNode.AddChildNode (cup); + } + + // Initialize `previewNode` to display the cup model. + this.previewNode = new PreviewNode (this.cupNode); + // Add `previewNode` to the node hierarchy. + this.sceneView.Scene.RootNode.AddChildNode (this.previewNode); + } + + /// <summary> + /// `previewNode` exists when ARKit is finding a plane. During this time, get a world position for the areas closest to the scene's point of view that ARKit believes might be a plane, and use it to update the `previewNode` position. + /// </summary> + private void UpdatePreviewNode () + { + if (this.previewNode != null) { + var (worldPosition, planeAnchor, _) = Utilities.WorldPositionFromScreenPosition (this.screenCenter, this.sceneView, this.previewNode.Position); + if (worldPosition.HasValue) { + this.previewNode.Update (worldPosition.Value, planeAnchor, this.sceneView.Session.CurrentFrame?.Camera); + } + } + } + + #endregion + + #region Sound + + /// <summary> + /// Determines whether the `cupNode` is visible. If the `cupNode` isn't visible, a sound is played using + /// SceneKit's positional audio functionality to locate the `cupNode`. + /// </summary> + private void CutVolumeIfPlacedObjectIsInView () + { + if (this.previewNode == null && this.sceneView.PointOfView != null) { + var player = this.cupNode.AudioPlayers?.FirstOrDefault (); + var avNode = player?.AudioNode as AVAudioPlayerNode; + if (player != null && avNode != null) { + var placedObjectIsInView = this.sceneView.IsNodeInsideFrustum (this.cupNode, this.sceneView.PointOfView); + avNode.Volume = placedObjectIsInView ? 0f : 1f; + } + } + } + + /// <summary> + /// Plays a sound on the cupNode using SceneKit's positional audio. + /// </summary> + private void PlaySound () + { + // ensure there is only one audio player + this.cupNode.RemoveAllAudioPlayers (); + + if (this.cupNode.AudioPlayers == null || !this.cupNode.AudioPlayers.Any ()) { + this.cupNode.AddAudioPlayer (new SCNAudioPlayer (this.source)); + } + } + + #endregion + } +} diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/AppDelegate.cs b/ios11/ARKitPlacingObjects/PlacingObjects/AppDelegate.cs index 8f9bf12b4..a69f5adc6 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/AppDelegate.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/AppDelegate.cs @@ -1,20 +1,17 @@ -using Foundation; +using Foundation; using UIKit; -namespace PlacingObjects -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace PlacingObjects { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -22,7 +19,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -30,25 +27,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/MessageType.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/MessageType.cs index a4e569d7a..7e84dddc8 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/MessageType.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/MessageType.cs @@ -1,8 +1,6 @@ -using System; -namespace PlacingObjects -{ - public enum MessageType - { +using System; +namespace PlacingObjects { + public enum MessageType { ContentPlacement, FocusSquare, PlaneEstimation, diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/TouchEventType.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/TouchEventType.cs index dcdce568f..f65f7dc69 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/TouchEventType.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Enumerations/TouchEventType.cs @@ -1,8 +1,6 @@ -using System; -namespace PlacingObjects -{ - public enum TouchEventType - { +using System; +namespace PlacingObjects { + public enum TouchEventType { TouchBegan, TouchCanceled, TouchMoved, diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Interfaces/IVirtualObjectSelectionViewControllerDelegate.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Interfaces/IVirtualObjectSelectionViewControllerDelegate.cs index fcfe9bc1a..993d553b5 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Interfaces/IVirtualObjectSelectionViewControllerDelegate.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Interfaces/IVirtualObjectSelectionViewControllerDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public interface IVirtualObjectSelectionViewControllerDelegate - { - void DidSelectObjectAt(int index); - void DidDeselectObjectAt(int index); +namespace PlacingObjects { + public interface IVirtualObjectSelectionViewControllerDelegate { + void DidSelectObjectAt (int index); + void DidDeselectObjectAt (int index); } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Main.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Main.cs index 1cbb125b2..dbff5e556 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Main.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PlacingObjects -{ - public class Application - { +namespace PlacingObjects { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectCell.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectCell.cs index ac143d5db..5c83d6209 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectCell.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectCell.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using UIKit; -namespace PlacingObjects -{ - [Register("ObjectCell")] - public class ObjectCell : UITableViewCell - { +namespace PlacingObjects { + [Register ("ObjectCell")] + public class ObjectCell : UITableViewCell { public readonly static string Identifier = "ObjectCell"; [Outlet] @@ -17,19 +15,17 @@ public class ObjectCell : UITableViewCell VirtualObjectDefinition virtualObject; - public VirtualObjectDefinition VirtualObject - { + public VirtualObjectDefinition VirtualObject { get => virtualObject; - set - { + set { objectTitleLabel.Text = value.DisplayName; objectImageView.Image = value.ThumbImage; virtualObject = value; } } - public ObjectCell(IntPtr ptr) : base(ptr) + public ObjectCell (IntPtr ptr) : base (ptr) { } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ARSCNViewExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ARSCNViewExtensions.cs index 165534d87..28c5dfe52 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ARSCNViewExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ARSCNViewExtensions.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using ARKit; using CoreGraphics; using SceneKit; -namespace PlacingObjects -{ - public static class ARSCNViewExtensions - { - public static void Setup(this ARSCNView self) +namespace PlacingObjects { + public static class ARSCNViewExtensions { + public static void Setup (this ARSCNView self) { self.AntialiasingMode = SCNAntialiasingMode.Multisampling4X; self.AutomaticallyUpdatesLighting = false; @@ -17,8 +15,7 @@ public static void Setup(this ARSCNView self) self.ContentScaleFactor = 1.3f; var camera = self.PointOfView.Camera; - if (camera != null) - { + if (camera != null) { camera.WantsHdr = true; camera.WantsExposureAdaptation = true; camera.ExposureOffset = -1; @@ -27,18 +24,16 @@ public static void Setup(this ARSCNView self) } } - public static FeatureHitTestResult HitTestFromOrigin(this ARSCNView self, SCNVector3 origin, SCNVector3 direction) + public static FeatureHitTestResult HitTestFromOrigin (this ARSCNView self, SCNVector3 origin, SCNVector3 direction) { - if (self.Session == null || ViewController.CurrentFrame == null) - { + if (self.Session == null || ViewController.CurrentFrame == null) { return null; } var currentFrame = ViewController.CurrentFrame; var features = currentFrame.RawFeaturePoints; - if (features == null) - { + if (features == null) { return null; } @@ -48,154 +43,139 @@ public static FeatureHitTestResult HitTestFromOrigin(this ARSCNView self, SCNVec var closestFeaturePoint = origin; var minDistance = float.MaxValue; - for (int n = 0; n < (int)features.Count; ++n) - { - var feature = points[n]; - var featurePos = new SCNVector3(feature.X, feature.Y, feature.Z); + for (int n = 0; n < (int) features.Count; ++n) { + var feature = points [n]; + var featurePos = new SCNVector3 (feature.X, feature.Y, feature.Z); - var originVector = origin.Subtract(featurePos); - var crossProduct = originVector.Cross(direction); + var originVector = origin.Subtract (featurePos); + var crossProduct = originVector.Cross (direction); var featureDistanceFromResult = crossProduct.Length; - if (featureDistanceFromResult < minDistance) - { + if (featureDistanceFromResult < minDistance) { closestFeaturePoint = featurePos; minDistance = featureDistanceFromResult; } } // Compute the point along the ray that is closest to the selected feature. - var originToFeature = closestFeaturePoint.Subtract(origin); - var hitTestResult = origin.Add(direction * direction.Dot(originToFeature)); - var hitTestResultDistance = hitTestResult.Subtract(origin).LengthFast; + var originToFeature = closestFeaturePoint.Subtract (origin); + var hitTestResult = origin.Add (direction * direction.Dot (originToFeature)); + var hitTestResultDistance = hitTestResult.Subtract (origin).LengthFast; // Return result - return new FeatureHitTestResult(hitTestResult, hitTestResultDistance, closestFeaturePoint, minDistance); + return new FeatureHitTestResult (hitTestResult, hitTestResultDistance, closestFeaturePoint, minDistance); } - public static HitTestRay HitTestRayFromScreenPos(this ARSCNView self, CGPoint point) + public static HitTestRay HitTestRayFromScreenPos (this ARSCNView self, CGPoint point) { - if (self.Session == null || ViewController.CurrentFrame == null) - { + if (self.Session == null || ViewController.CurrentFrame == null) { return null; } var frame = ViewController.CurrentFrame; - if (frame == null || frame.Camera == null || frame.Camera.Transform == null) - { + if (frame == null || frame.Camera == null || frame.Camera.Transform == null) { return null; } - var cameraPos = SCNVector3Extensions.PositionFromTransform(frame.Camera.Transform); + var cameraPos = SCNVector3Extensions.PositionFromTransform (frame.Camera.Transform); // Note: z: 1.0 will unproject() the screen position to the far clipping plane. - var positionVec = new SCNVector3((float)point.X, (float)point.Y, 1.0f); - var screenPosOnFarClippingPlane = self.UnprojectPoint(positionVec); + var positionVec = new SCNVector3 ((float) point.X, (float) point.Y, 1.0f); + var screenPosOnFarClippingPlane = self.UnprojectPoint (positionVec); - var rayDirection = screenPosOnFarClippingPlane.Subtract(cameraPos); - rayDirection.Normalize(); + var rayDirection = screenPosOnFarClippingPlane.Subtract (cameraPos); + rayDirection.Normalize (); - return new HitTestRay(cameraPos, rayDirection); + return new HitTestRay (cameraPos, rayDirection); } - public static SCNVector3? HitTestWithInfiniteHorizontalPlane(this ARSCNView self, CGPoint point, SCNVector3 pointOnPlane) + public static SCNVector3? HitTestWithInfiniteHorizontalPlane (this ARSCNView self, CGPoint point, SCNVector3 pointOnPlane) { - if (self.Session == null || ViewController.CurrentFrame == null) - { + if (self.Session == null || ViewController.CurrentFrame == null) { return null; } var currentFrame = ViewController.CurrentFrame; - var ray = self.HitTestRayFromScreenPos(point); - if (ray == null) - { + var ray = self.HitTestRayFromScreenPos (point); + if (ray == null) { return null; }; // Do not intersect with planes above the camera or if the ray is almost parallel to the plane. - if (ray.Direction.Y > -0.03f) - { + if (ray.Direction.Y > -0.03f) { return null; } - return Utilities.RayIntersectionWithHorizontalPlane(ray.Origin, ray.Direction, pointOnPlane.Y); + return Utilities.RayIntersectionWithHorizontalPlane (ray.Origin, ray.Direction, pointOnPlane.Y); } - public static FeatureHitTestResult[] HitTestWithFeatures(this ARSCNView self, CGPoint point, double coneOpeningAngleInDegrees, double minDistance = 0, double maxDistance = Double.MaxValue, int maxResults = 1) + public static FeatureHitTestResult [] HitTestWithFeatures (this ARSCNView self, CGPoint point, double coneOpeningAngleInDegrees, double minDistance = 0, double maxDistance = Double.MaxValue, int maxResults = 1) { - var results = new List<FeatureHitTestResult>(); + var results = new List<FeatureHitTestResult> (); - if (self.Session == null || ViewController.CurrentFrame == null) - { - return results.ToArray(); + if (self.Session == null || ViewController.CurrentFrame == null) { + return results.ToArray (); } var features = ViewController.CurrentFrame.RawFeaturePoints; - if (features == null) - { - return results.ToArray(); + if (features == null) { + return results.ToArray (); } - var ray = self.HitTestRayFromScreenPos(point); - if (ray == null) - { - return results.ToArray(); + var ray = self.HitTestRayFromScreenPos (point); + if (ray == null) { + return results.ToArray (); } - var maxAngleInDeg = Math.Min(coneOpeningAngleInDegrees, 360) / 2.0; + var maxAngleInDeg = Math.Min (coneOpeningAngleInDegrees, 360) / 2.0; var maxAngle = (maxAngleInDeg / 180) * Math.PI; - foreach (var featurePos in features.Points) - { - var scnFeaturePos = new SCNVector3(featurePos.X, featurePos.Y, featurePos.Z); + foreach (var featurePos in features.Points) { + var scnFeaturePos = new SCNVector3 (featurePos.X, featurePos.Y, featurePos.Z); var originToFeature = scnFeaturePos - ray.Origin; - var crossProduct = originToFeature.Cross(ray.Direction); + var crossProduct = originToFeature.Cross (ray.Direction); var featureDistanceFromResult = crossProduct.LengthFast; - var hitTestResult = ray.Origin + (ray.Direction * (ray.Direction.Dot(originToFeature))); + var hitTestResult = ray.Origin + (ray.Direction * (ray.Direction.Dot (originToFeature))); var hitTestResultDistance = (hitTestResult - ray.Origin).LengthFast; - if (hitTestResultDistance < minDistance || hitTestResultDistance > maxDistance) - { + if (hitTestResultDistance < minDistance || hitTestResultDistance > maxDistance) { // Skip this feature -- it's too close or too far continue; } - var originToFeatureNormalized = originToFeature.Normalized(); - var angleBetweenRayAndFeature = Math.Acos(ray.Direction.Dot(originToFeatureNormalized)); + var originToFeatureNormalized = originToFeature.Normalized (); + var angleBetweenRayAndFeature = Math.Acos (ray.Direction.Dot (originToFeatureNormalized)); - if (angleBetweenRayAndFeature > maxAngle) - { + if (angleBetweenRayAndFeature > maxAngle) { // Skip this feature -- it's outside the cone continue; } // All tests passed: Add the hit against this feature to the results. - results.Add(new FeatureHitTestResult(hitTestResult, hitTestResultDistance, scnFeaturePos, featureDistanceFromResult)); + results.Add (new FeatureHitTestResult (hitTestResult, hitTestResultDistance, scnFeaturePos, featureDistanceFromResult)); } // Sort the results by feature distance to the ray. - results.Sort((a, b) => a.DistanceToRayOrigin.CompareTo(b.DistanceToRayOrigin)); + results.Sort ((a, b) => a.DistanceToRayOrigin.CompareTo (b.DistanceToRayOrigin)); // Cap the list to maxResults. - results.GetRange(0, Math.Min(results.Count(), maxResults)); - return results.ToArray(); + results.GetRange (0, Math.Min (results.Count (), maxResults)); + return results.ToArray (); } - public static FeatureHitTestResult[] HitTestWithFeatures(this ARSCNView self, CGPoint pt) + public static FeatureHitTestResult [] HitTestWithFeatures (this ARSCNView self, CGPoint pt) { - var results = new List<FeatureHitTestResult>(); - var ray = self.HitTestRayFromScreenPos(pt); - if (ray == null) - { - return results.ToArray(); + var results = new List<FeatureHitTestResult> (); + var ray = self.HitTestRayFromScreenPos (pt); + if (ray == null) { + return results.ToArray (); } - var result = self.HitTestFromOrigin(ray.Origin, ray.Direction); - if (result != null) - { - results.Add(result); + var result = self.HitTestFromOrigin (ray.Origin, ray.Direction); + if (result != null) { + results.Add (result); } - return results.ToArray(); + return results.ToArray (); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGPointExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGPointExtensions.cs index 99b2b69a6..2dcc63f2d 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGPointExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGPointExtensions.cs @@ -1,73 +1,75 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public static class CGPointExtensions - { - public static CGPoint FromSize(CGSize size) { - return new CGPoint(size.Width, size.Height); +namespace PlacingObjects { + public static class CGPointExtensions { + public static CGPoint FromSize (CGSize size) + { + return new CGPoint (size.Width, size.Height); } - public static CGPoint FromVector(SCNVector3 vector) + public static CGPoint FromVector (SCNVector3 vector) { - return new CGPoint(vector.X, vector.Y); + return new CGPoint (vector.X, vector.Y); } - public static float DistanceTo(this CGPoint self, CGPoint point) + public static float DistanceTo (this CGPoint self, CGPoint point) { - return self.Subtract(point).Length(); + return self.Subtract (point).Length (); } - public static float Length(this CGPoint point) { - return (float)Math.Sqrt(point.X * point.X + point.Y * point.Y); + public static float Length (this CGPoint point) + { + return (float) Math.Sqrt (point.X * point.X + point.Y * point.Y); } - public static CGPoint MidPoint(this CGPoint self, CGPoint point) { - return self.Add(point).Divide(2f); + public static CGPoint MidPoint (this CGPoint self, CGPoint point) + { + return self.Add (point).Divide (2f); } - public static CGPoint Add(this CGPoint self, CGPoint point) { - return new CGPoint(self.X + point.X, self.Y + point.Y); + public static CGPoint Add (this CGPoint self, CGPoint point) + { + return new CGPoint (self.X + point.X, self.Y + point.Y); } - public static CGPoint Add(this CGPoint self, float value) + public static CGPoint Add (this CGPoint self, float value) { - return new CGPoint(self.X + value, self.Y + value); + return new CGPoint (self.X + value, self.Y + value); } - - public static CGPoint Subtract(this CGPoint self, CGPoint point) + + public static CGPoint Subtract (this CGPoint self, CGPoint point) { - return new CGPoint(self.X - point.X, self.Y - point.Y); + return new CGPoint (self.X - point.X, self.Y - point.Y); } - public static CGPoint Subtract(this CGPoint self, float value) + public static CGPoint Subtract (this CGPoint self, float value) { - return new CGPoint(self.X - value, self.Y - value); + return new CGPoint (self.X - value, self.Y - value); } - public static CGPoint Multiply(this CGPoint self, CGPoint point) + public static CGPoint Multiply (this CGPoint self, CGPoint point) { - return new CGPoint(self.X * point.X, self.Y * point.Y); + return new CGPoint (self.X * point.X, self.Y * point.Y); } - public static CGPoint Multiply(this CGPoint self, float value) + public static CGPoint Multiply (this CGPoint self, float value) { - return new CGPoint(self.X * value, self.Y * value); + return new CGPoint (self.X * value, self.Y * value); } - public static CGPoint Divide(this CGPoint self, CGPoint point) + public static CGPoint Divide (this CGPoint self, CGPoint point) { - return new CGPoint(self.X / point.X, self.Y / point.Y); + return new CGPoint (self.X / point.X, self.Y / point.Y); } - public static CGPoint Divide(this CGPoint self, float value) + public static CGPoint Divide (this CGPoint self, float value) { - return new CGPoint(self.X / value, self.Y / value); + return new CGPoint (self.X / value, self.Y / value); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGRectExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGRectExtensions.cs index 64dd97df6..3578c7e60 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGRectExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGRectExtensions.cs @@ -1,16 +1,15 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public static class CGRectExtensions - { - public static CGPoint GetMidpoint(this CGRect rect) { - return new CGPoint(rect.GetMidX(), rect.GetMidY()); +namespace PlacingObjects { + public static class CGRectExtensions { + public static CGPoint GetMidpoint (this CGRect rect) + { + return new CGPoint (rect.GetMidX (), rect.GetMidY ()); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGSizeExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGSizeExtensions.cs index 8b07bb01c..2b9ec5c0d 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGSizeExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/CGSizeExtensions.cs @@ -1,61 +1,62 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public static class CGSizeExtensions - { - public static CGSize FromCGPoint (CGPoint point) { +namespace PlacingObjects { + public static class CGSizeExtensions { + public static CGSize FromCGPoint (CGPoint point) + { // Create new size from point - return new CGSize(point.X, point.Y); + return new CGSize (point.X, point.Y); } - public static string ToString(this CGSize size) { + public static string ToString (this CGSize size) + { return $"({size.Width:#.00}, {size.Height:#.00})"; } - public static CGSize Add (this CGSize size, CGSize right){ - return new CGSize(size.Width + right.Width, size.Height + right.Height); + public static CGSize Add (this CGSize size, CGSize right) + { + return new CGSize (size.Width + right.Width, size.Height + right.Height); } - public static CGSize Add(this CGSize size, float value) + public static CGSize Add (this CGSize size, float value) { - return new CGSize(size.Width + value, size.Height + value); + return new CGSize (size.Width + value, size.Height + value); } - public static CGSize Subtract(this CGSize size, CGSize right) + public static CGSize Subtract (this CGSize size, CGSize right) { - return new CGSize(size.Width - right.Width, size.Height - right.Height); + return new CGSize (size.Width - right.Width, size.Height - right.Height); } - public static CGSize Subtract(this CGSize size, float value) + public static CGSize Subtract (this CGSize size, float value) { - return new CGSize(size.Width - value, size.Height - value); + return new CGSize (size.Width - value, size.Height - value); } - public static CGSize Divide(this CGSize size, CGSize right) + public static CGSize Divide (this CGSize size, CGSize right) { - return new CGSize(size.Width / right.Width, size.Height / right.Height); + return new CGSize (size.Width / right.Width, size.Height / right.Height); } - public static CGSize Divide(this CGSize size, float value) + public static CGSize Divide (this CGSize size, float value) { - return new CGSize(size.Width / value, size.Height / value); + return new CGSize (size.Width / value, size.Height / value); } - public static CGSize Multiply(this CGSize size, CGSize right) + public static CGSize Multiply (this CGSize size, CGSize right) { - return new CGSize(size.Width * right.Width, size.Height * right.Height); + return new CGSize (size.Width * right.Width, size.Height * right.Height); } - public static CGSize Multiply(this CGSize size, float value) + public static CGSize Multiply (this CGSize size, float value) { - return new CGSize(size.Width * value, size.Height * value); + return new CGSize (size.Width * value, size.Height * value); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ListExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ListExtensions.cs index b7f720d8a..fef085dc2 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ListExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/ListExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using Foundation; @@ -8,50 +8,49 @@ using ARKit; using System.Linq; -namespace PlacingObjects -{ - public static class ListExtensions - { - public static void Union<T>(this List<T> self, List<T> list) +namespace PlacingObjects { + public static class ListExtensions { + public static void Union<T> (this List<T> self, List<T> list) { // Add list items to self if not already contained - foreach (T item in list) - { - if (!self.Contains(item)) self.Add(item); + foreach (T item in list) { + if (!self.Contains (item)) self.Add (item); } } - public static void Subtract<T>(this List<T> self, List<T> list) { + public static void Subtract<T> (this List<T> self, List<T> list) + { // Remove the items from the list from self - foreach(T item in list) { - self.Remove(item); + foreach (T item in list) { + self.Remove (item); } } - public static void KeepLast<T>(this List<T> self, int count) { + public static void KeepLast<T> (this List<T> self, int count) + { // Remove first item until the count matches the requested number - while(self.Count > count) { - self.RemoveAt(0); + while (self.Count > count) { + self.RemoveAt (0); } } - public static float Average<T>(this List<T> self) { - if (self.Count() == 0) - { + public static float Average<T> (this List<T> self) + { + if (self.Count () == 0) { return 0.0f; } var sum = 0f; - foreach(T value in self) { - float v = default(float); - float.TryParse(value.ToString(), out v); + foreach (T value in self) { + float v = default (float); + float.TryParse (value.ToString (), out v); sum += v; } - return (sum / (float)self.Count); + return (sum / (float) self.Count); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/Matrix4Extensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/Matrix4Extensions.cs index d791e3074..6d92afbdb 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/Matrix4Extensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/Matrix4Extensions.cs @@ -1,14 +1,12 @@ -using System; +using System; using OpenTK; using SceneKit; -namespace PlacingObjects -{ - public static class NMatrix4Extensions - { - public static SCNVector3 Translation(this NMatrix4 self) +namespace PlacingObjects { + public static class NMatrix4Extensions { + public static SCNVector3 Translation (this NMatrix4 self) { - return new SCNVector3(self.M14, self.M24, self.M34); + return new SCNVector3 (self.M14, self.M24, self.M34); } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/NSSetExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/NSSetExtensions.cs index 7a2cf889d..ab6f6acee 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/NSSetExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/NSSetExtensions.cs @@ -1,16 +1,15 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; -namespace PlacingObjects -{ - public static class NSSetExtensions - { - public static List<UITouch> ToTouchList(this NSSet touches) { +namespace PlacingObjects { + public static class NSSetExtensions { + public static List<UITouch> ToTouchList (this NSSet touches) + { - var touchArray = touches.ToArray<UITouch>(); - var touchList = new List<UITouch>(touchArray); + var touchArray = touches.ToArray<UITouch> (); + var touchList = new List<UITouch> (touchArray); return touchList; } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNMaterialExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNMaterialExtensions.cs index 8ee1527b9..87bd27c4c 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNMaterialExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNMaterialExtensions.cs @@ -1,16 +1,15 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public static class SCNMaterialExtensions - { - public static SCNMaterial CreateMaterial(NSObject diffuse, bool respondsToLighting = true) { - var newMaterial = new SCNMaterial(); +namespace PlacingObjects { + public static class SCNMaterialExtensions { + public static SCNMaterial CreateMaterial (NSObject diffuse, bool respondsToLighting = true) + { + var newMaterial = new SCNMaterial (); // Configure material newMaterial.Diffuse.Contents = diffuse; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNNodeExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNNodeExtensions.cs index 1746ddb9a..e4b52ae15 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNNodeExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNNodeExtensions.cs @@ -1,31 +1,31 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public static class SCNNodeExtensions - { - public static void SetUniformScale(this SCNNode node, float scale) { - node.Scale = new SCNVector3(scale, scale, scale); +namespace PlacingObjects { + public static class SCNNodeExtensions { + public static void SetUniformScale (this SCNNode node, float scale) + { + node.Scale = new SCNVector3 (scale, scale, scale); } - public static void RenderOnTop(this SCNNode node) { + public static void RenderOnTop (this SCNNode node) + { node.RenderingOrder = 2; var geom = node.Geometry; if (geom != null) { // process all materials - foreach(SCNMaterial material in geom.Materials) { + foreach (SCNMaterial material in geom.Materials) { material.ReadsFromDepthBuffer = false; } } - foreach(SCNNode child in node.ChildNodes) { - child.RenderOnTop(); + foreach (SCNNode child in node.ChildNodes) { + child.RenderOnTop (); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNScene_Extensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNScene_Extensions.cs index 2506100e9..155afb06a 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNScene_Extensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNScene_Extensions.cs @@ -1,16 +1,13 @@ -using CoreFoundation; +using CoreFoundation; using SceneKit; using UIKit; -namespace PlacingObjects -{ - public static class SCNScene_Extensions - { - public static void EnableEnvironmentMapWithIntensity(this SCNScene self, float intensity, DispatchQueue queue) +namespace PlacingObjects { + public static class SCNScene_Extensions { + public static void EnableEnvironmentMapWithIntensity (this SCNScene self, float intensity, DispatchQueue queue) { - if (self.LightingEnvironment.Contents == null) - { - var environmentMap = UIImage.FromFile("Models.scnassets/sharedImages/environment_blur.exr"); + if (self.LightingEnvironment.Contents == null) { + var environmentMap = UIImage.FromFile ("Models.scnassets/sharedImages/environment_blur.exr"); self.LightingEnvironment.ContentImage = environmentMap; } self.LightingEnvironment.Intensity = intensity; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNVector3Extensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNVector3Extensions.cs index f18eecfa6..ddee88850 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNVector3Extensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/SCNVector3Extensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; @@ -6,44 +6,46 @@ using ARKit; using OpenTK; -namespace PlacingObjects -{ - public static class SCNVector3Extensions - { - public static SCNVector3 One() { - return new SCNVector3(1.0f, 1.0f, 1.0f); +namespace PlacingObjects { + public static class SCNVector3Extensions { + public static SCNVector3 One () + { + return new SCNVector3 (1.0f, 1.0f, 1.0f); } - public static SCNVector3 Uniform(float value) + public static SCNVector3 Uniform (float value) { - return new SCNVector3(value, value, value); + return new SCNVector3 (value, value, value); } - public static CGPoint ToCGPoint(this SCNVector3 self) - { - return new CGPoint(self.X, self.Y); - } + public static CGPoint ToCGPoint (this SCNVector3 self) + { + return new CGPoint (self.X, self.Y); + } - public static void SetLength(this SCNVector3 vector3, float length){ - vector3.Normalize(); + public static void SetLength (this SCNVector3 vector3, float length) + { + vector3.Normalize (); vector3 *= length; } - public static void SetMaximumLength(this SCNVector3 vector3, float maxLength) + public static void SetMaximumLength (this SCNVector3 vector3, float maxLength) { if (vector3.LengthFast > maxLength) { - vector3.SetLength(maxLength); + vector3.SetLength (maxLength); } } - public static void Normalize(this SCNVector3 vector3){ - var normalizedVector = vector3.Normalized(); + public static void Normalize (this SCNVector3 vector3) + { + var normalizedVector = vector3.Normalized (); vector3.X = normalizedVector.X; vector3.Y = normalizedVector.Y; vector3.Z = normalizedVector.Z; } - public static SCNVector3 Normalized(this SCNVector3 vector3) { + public static SCNVector3 Normalized (this SCNVector3 vector3) + { if (vector3.Length < Double.Epsilon) { return vector3; @@ -52,37 +54,40 @@ public static SCNVector3 Normalized(this SCNVector3 vector3) { } } - public static float Dot(this SCNVector3 vector3, SCNVector3 vec) { + public static float Dot (this SCNVector3 vector3, SCNVector3 vec) + { return (vector3.X * vec.X) + (vector3.Y * vec.Y) + (vector3.Z * vec.Z); } - public static SCNVector3 Cross(this SCNVector3 vector3, SCNVector3 vec) + public static SCNVector3 Cross (this SCNVector3 vector3, SCNVector3 vec) { - return new SCNVector3(vector3.Y * vec.Z - vector3.Z * vec.Y, vector3.Z * vec.X - vector3.X * vec.Z, vector3.X * vec.Y - vector3.Y * vec.X); + return new SCNVector3 (vector3.Y * vec.Z - vector3.Z * vec.Y, vector3.Z * vec.X - vector3.X * vec.Z, vector3.X * vec.Y - vector3.Y * vec.X); } - public static SCNVector3 PositionFromTransform(NMatrix4 transform){ - var pFromComponents = new SCNVector3(transform.M14, transform.M24, transform.M34); + public static SCNVector3 PositionFromTransform (NMatrix4 transform) + { + var pFromComponents = new SCNVector3 (transform.M14, transform.M24, transform.M34); return pFromComponents; } - public static SCNVector3 Add(this SCNVector3 vector3, SCNVector3 right) { - return new SCNVector3(vector3.X + right.X, vector3.Y + right.Y, vector3.Z + right.Z); + public static SCNVector3 Add (this SCNVector3 vector3, SCNVector3 right) + { + return new SCNVector3 (vector3.X + right.X, vector3.Y + right.Y, vector3.Z + right.Z); } - public static SCNVector3 Subtract(this SCNVector3 vector3, SCNVector3 right) + public static SCNVector3 Subtract (this SCNVector3 vector3, SCNVector3 right) { - return new SCNVector3(vector3.X - right.X, vector3.Y - right.Y, vector3.Z - right.Z); + return new SCNVector3 (vector3.X - right.X, vector3.Y - right.Y, vector3.Z - right.Z); } - public static SCNVector3 Multiply(this SCNVector3 vector3, SCNVector3 right) + public static SCNVector3 Multiply (this SCNVector3 vector3, SCNVector3 right) { - return new SCNVector3(vector3.X * right.X, vector3.Y * right.Y, vector3.Z * right.Z); + return new SCNVector3 (vector3.X * right.X, vector3.Y * right.Y, vector3.Z * right.Z); } - public static SCNVector3 Divide(this SCNVector3 vector3, SCNVector3 right) + public static SCNVector3 Divide (this SCNVector3 vector3, SCNVector3 right) { - return new SCNVector3(vector3.X / right.X, vector3.Y / right.Y, vector3.Z / right.Z); + return new SCNVector3 (vector3.X / right.X, vector3.Y / right.Y, vector3.Z / right.Z); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/UIImageExtensions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/UIImageExtensions.cs index 5a6352b41..0bce9959e 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/UIImageExtensions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ObjectExtensions/UIImageExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; @@ -6,49 +6,49 @@ using SceneKit; using ARKit; -namespace PlacingObjects -{ - public static class UIImageExtensions - { - public static UIImage Inverted(this UIImage image) { +namespace PlacingObjects { + public static class UIImageExtensions { + public static UIImage Inverted (this UIImage image) + { // Convert to Core Image - var ciImage = new CIImage(image); - if (ciImage == null) - { + var ciImage = new CIImage (image); + if (ciImage == null) { return null; } // Apply filter - ciImage = ciImage.CreateByFiltering("CIColorInvert", new NSDictionary()); + ciImage = ciImage.CreateByFiltering ("CIColorInvert", new NSDictionary ()); // Return results - return new UIImage(ciImage); + return new UIImage (ciImage); } - public static UIImage ComposeButtonImage(string imageName, float alpha = 1.0f) { - return ComposeButtonImage(UIImage.FromBundle(imageName), alpha); + public static UIImage ComposeButtonImage (string imageName, float alpha = 1.0f) + { + return ComposeButtonImage (UIImage.FromBundle (imageName), alpha); } - public static UIImage ComposeButtonImage(UIImage thumbImage, float alpha = 1.0f) { + public static UIImage ComposeButtonImage (UIImage thumbImage, float alpha = 1.0f) + { // Get images and masks var maskImage = thumbImage; - var invertedImage = thumbImage.Inverted(); + var invertedImage = thumbImage.Inverted (); var thumbnailImage = thumbImage; if (invertedImage != null) thumbnailImage = invertedImage; // Compose a button image based on a white background and the inverted thumbnail image. - UIGraphics.BeginImageContextWithOptions(maskImage.Size, false, 0.0f); + UIGraphics.BeginImageContextWithOptions (maskImage.Size, false, 0.0f); - var maskDrawRect = new CGRect(CGPoint.Empty, maskImage.Size); - var thumbDrawRect = new CGRect(CGPointExtensions.FromSize(maskImage.Size.Subtract(thumbImage.Size).Divide(2f)), thumbImage.Size); - - maskImage.Draw(maskDrawRect, CGBlendMode.Normal, alpha); - thumbnailImage.Draw(thumbDrawRect, CGBlendMode.Normal, alpha); + var maskDrawRect = new CGRect (CGPoint.Empty, maskImage.Size); + var thumbDrawRect = new CGRect (CGPointExtensions.FromSize (maskImage.Size.Subtract (thumbImage.Size).Divide (2f)), thumbImage.Size); - var composedImage = UIGraphics.GetImageFromCurrentImageContext(); - UIGraphics.EndImageContext(); + maskImage.Draw (maskDrawRect, CGBlendMode.Normal, alpha); + thumbnailImage.Draw (thumbDrawRect, CGBlendMode.Normal, alpha); + + var composedImage = UIGraphics.GetImageFromCurrentImageContext (); + UIGraphics.EndImageContext (); // Return results return composedImage; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/SettingsViewController.cs b/ios11/ARKitPlacingObjects/PlacingObjects/SettingsViewController.cs index 9cf7874a3..549983136 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/SettingsViewController.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/SettingsViewController.cs @@ -8,34 +8,31 @@ using ARKit; using CoreFoundation; -namespace PlacingObjects -{ - public partial class SettingsViewController : UITableViewController - { - public SettingsViewController(IntPtr handle) : base(handle) +namespace PlacingObjects { + public partial class SettingsViewController : UITableViewController { + public SettingsViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - PopulateSettings(); + PopulateSettings (); } - private void PopulateSettings() { + private void PopulateSettings () + { DragOnInfinitePlanesSwitch.On = AppSettings.DragOnInfinitePlanes; ScaleWithPinchGestureSwitch.On = AppSettings.ScaleWithPinchGesture; } - [Action("didChangeSetting:")] - public void SettingChanged(UISwitch sender) + [Action ("didChangeSetting:")] + public void SettingChanged (UISwitch sender) { - if (sender == DragOnInfinitePlanesSwitch) - { + if (sender == DragOnInfinitePlanesSwitch) { AppSettings.DragOnInfinitePlanes = DragOnInfinitePlanesSwitch.On; } - if (sender == ScaleWithPinchGestureSwitch) - { + if (sender == ScaleWithPinchGestureSwitch) { AppSettings.ScaleWithPinchGesture = ScaleWithPinchGestureSwitch.On; } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquare.cs b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquare.cs index d82b58dbd..176993511 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquare.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquare.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -8,10 +8,8 @@ using ARKit; using System.Linq; -namespace PlacingObjects -{ - public class FocusSquare : SCNNode - { +namespace PlacingObjects { + public class FocusSquare : SCNNode { ///////////////////////////////////////////////// // Variables to configure the focus square @@ -28,29 +26,26 @@ public class FocusSquare : SCNNode private float AnimationDuration = 0.7f; // Color of the focus square - public static readonly UIColor PrimaryColor = UIColor.FromRGB(255, 211, 0); - private UIColor FocusSquareColorLight = UIColor.FromRGB(255, 273, 124); + public static readonly UIColor PrimaryColor = UIColor.FromRGB (255, 211, 0); + private UIColor FocusSquareColorLight = UIColor.FromRGB (255, 273, 124); // For scale adapdation based on the camera distance, see the `ScaleBasedOnDistance(camera:)` method. private bool IsOpen = false; private bool IsAnimating = false; - private SCNVector3[] RecentFocusSquarePositions = new SCNVector3[8]; + private SCNVector3 [] RecentFocusSquarePositions = new SCNVector3 [8]; private int recentFocusSquarePositionIndex = 0; - private ISet<ARAnchor> AnchorsOfVisitedPlanes = new HashSet<ARAnchor>(); + private ISet<ARAnchor> AnchorsOfVisitedPlanes = new HashSet<ARAnchor> (); private SCNNode fillPlane = null; - private SCNNode FillPlane - { + private SCNNode FillPlane { get { - if (fillPlane == null) - { + if (fillPlane == null) { var c = FocusSquareThickness / 2; //Correction to align lines perfectly - var plane = new SCNPlane - { - Width = (nfloat)(1.0 - FocusSquareThickness * 2 + c), - Height = (nfloat)(1.0 - FocusSquareThickness * 2 + c) + var plane = new SCNPlane { + Width = (nfloat) (1.0 - FocusSquareThickness * 2 + c), + Height = (nfloat) (1.0 - FocusSquareThickness * 2 + c) }; fillPlane = new SCNNode { Geometry = plane }; fillPlane.Name = "fillPlane"; @@ -67,11 +62,9 @@ private SCNNode FillPlane } } - private FocusSquareSegment[] segments = new FocusSquareSegment[8]; - private FocusSquareSegment[] Segments - { - get - { + private FocusSquareSegment [] segments = new FocusSquareSegment [8]; + private FocusSquareSegment [] Segments { + get { return segments; } } @@ -80,69 +73,65 @@ private FocusSquareSegment[] Segments public SCNVector3 LastPositionOnPlane { get; set; } public SCNVector3 LastPosition { get; set; } - public FocusSquare() : base() + public FocusSquare () : base () { Name = "Focus Square"; // Initialize Opacity = 0.0f; - AddChildNode(FocusSquareNode()); - Open(); + AddChildNode (FocusSquareNode ()); + Open (); } - public FocusSquare(NSCoder coder) : base(coder) + public FocusSquare (NSCoder coder) : base (coder) { // Initialize Name = "Focus Square"; } - private void UpdateTransform(SCNVector3 position, ARCamera camera) + private void UpdateTransform (SCNVector3 position, ARCamera camera) { // Add to list of recently visited positions - RecentFocusSquarePositions[recentFocusSquarePositionIndex] = position; + RecentFocusSquarePositions [recentFocusSquarePositionIndex] = position; // Increment current position, rolling over to beginning recentFocusSquarePositionIndex = ++recentFocusSquarePositionIndex % RecentFocusSquarePositions.Length; // Note that we don't really care about "current position" as we just average all the positions // Move to average of recent positions to avoid jitter - var average = Utilities.AverageVector3List(RecentFocusSquarePositions); + var average = Utilities.AverageVector3List (RecentFocusSquarePositions); Position = average; - this.SetUniformScale(ScaleBasedOnDistance(camera)); + this.SetUniformScale (ScaleBasedOnDistance (camera)); // Correct y rotation of camera square - if (camera !=null) { - var tilt = (float)Math.Abs(camera.EulerAngles.X); - var threshold1 = (float)(Math.PI / 2f * 0.65f); - var threshold2 = (float)(Math.PI / 2f * 0.75f); - var yaw = (float)Math.Atan2(camera.Transform.M11, camera.Transform.M12); + if (camera != null) { + var tilt = (float) Math.Abs (camera.EulerAngles.X); + var threshold1 = (float) (Math.PI / 2f * 0.65f); + var threshold2 = (float) (Math.PI / 2f * 0.75f); + var yaw = (float) Math.Atan2 (camera.Transform.M11, camera.Transform.M12); var angle = 0f; - if (tilt >=0 && tilt<threshold1) { + if (tilt >= 0 && tilt < threshold1) { angle = camera.EulerAngles.Y; } else if (threshold1 < threshold2) { - var relativeInRange = Math.Abs((tilt - threshold1) / (threshold2 / threshold1)); - var normalizedY = Normalize(camera.EulerAngles.Y, yaw); + var relativeInRange = Math.Abs ((tilt - threshold1) / (threshold2 / threshold1)); + var normalizedY = Normalize (camera.EulerAngles.Y, yaw); angle = normalizedY * (1 - relativeInRange) + yaw * relativeInRange; } else { angle = yaw; } - Rotation = new SCNVector4(0, 1, 0, angle); + Rotation = new SCNVector4 (0, 1, 0, angle); } } - private float Normalize(float angle, float forMinimalRotationTo) + private float Normalize (float angle, float forMinimalRotationTo) { // Normalize angle in steps of 90 degrees such that the rotation to the other angle is minimal var normalized = angle; - while (Math.Abs(normalized - forMinimalRotationTo) > (float)Math.PI / 4) - { - if (angle > forMinimalRotationTo) - { - normalized -= (float)Math.PI / 2; - } - else - { - normalized += (float)Math.PI / 2; + while (Math.Abs (normalized - forMinimalRotationTo) > (float) Math.PI / 4) { + if (angle > forMinimalRotationTo) { + normalized -= (float) Math.PI / 2; + } else { + normalized += (float) Math.PI / 2; } } @@ -154,15 +143,14 @@ private float Normalize(float angle, float forMinimalRotationTo) /// These adjustments result in a scale of 1.0x for a distance of 0.7 m or less /// (estimated distance when looking at a table), and a scale of 1.2x /// for a distance 1.5 m distance (estimated distance when looking at the floor). - private float ScaleBasedOnDistance(ARCamera camera) + private float ScaleBasedOnDistance (ARCamera camera) { - if (camera == null) - { + if (camera == null) { return 1.0f; } - var distanceFromCamera = Position.Subtract(SCNVector3Extensions.PositionFromTransform(camera.Transform)).LengthFast; + var distanceFromCamera = Position.Subtract (SCNVector3Extensions.PositionFromTransform (camera.Transform)).LengthFast; // This function reduces size changes of the focus square based on the distance by scaling it up if it far away, // and down if it is very close. @@ -172,56 +160,57 @@ private float ScaleBasedOnDistance(ARCamera camera) return newScale; } - private SCNAction PulseAction() + private SCNAction PulseAction () { - var pulseOutAction = SCNAction.FadeOpacityTo(0.4f, 0.5f); - var pulseInAction = SCNAction.FadeOpacityTo(1.0f, 0.5f); + var pulseOutAction = SCNAction.FadeOpacityTo (0.4f, 0.5f); + var pulseInAction = SCNAction.FadeOpacityTo (1.0f, 0.5f); pulseOutAction.TimingMode = SCNActionTimingMode.EaseInEaseOut; pulseInAction.TimingMode = SCNActionTimingMode.EaseInEaseOut; - return SCNAction.RepeatActionForever(SCNAction.Sequence(new SCNAction[] { pulseOutAction, pulseInAction })); + return SCNAction.RepeatActionForever (SCNAction.Sequence (new SCNAction [] { pulseOutAction, pulseInAction })); } - private void StopPulsing(SCNNode node) + private void StopPulsing (SCNNode node) { - if (node == null) - { + if (node == null) { return; } - node.RemoveAction("pulse"); + node.RemoveAction ("pulse"); node.Opacity = 1.0f; } - private SCNAction FlashAnimation(double duration) { + private SCNAction FlashAnimation (double duration) + { - var action = SCNAction.CustomAction(duration, (node, elapsedTime) => { + var action = SCNAction.CustomAction (duration, (node, elapsedTime) => { // animate color from HSB 48/100/100 to 48/30/100 and back - var elapsedTimePercentage = elapsedTime / (float)duration; + var elapsedTimePercentage = elapsedTime / (float) duration; var saturation = 2.8f * (elapsedTimePercentage - 0.5f) * (elapsedTimePercentage - 0.5f) + 0.3f; var material = node.Geometry.FirstMaterial; - if (material !=null) { - material.Diffuse.Contents = UIColor.FromHSBA(0.1333f, saturation, 1.0f, 1.0f); + if (material != null) { + material.Diffuse.Contents = UIColor.FromHSBA (0.1333f, saturation, 1.0f, 1.0f); } }); return action; } - private CAKeyFrameAnimation ScaleAnimation(string keyPath){ + private CAKeyFrameAnimation ScaleAnimation (string keyPath) + { - var scaleAnimation = CAKeyFrameAnimation.FromKeyPath(keyPath); + var scaleAnimation = CAKeyFrameAnimation.FromKeyPath (keyPath); - var easeOut = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); - var easeInOut = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); - var liner = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear); + var easeOut = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); + var easeInOut = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut); + var liner = CAMediaTimingFunction.FromName (CAMediaTimingFunction.Linear); var fs = FocusSquareSize; var ts = FocusSquareSize * ScaleForClosedSquare; - var values = new NSNumber[] { fs, fs * 1.15f, fs * 1.15f, ts * 0.97f, ts }; - var keyTimes = new NSNumber[] { 0.00f, 0.25f, 0.50f, 0.75f, 1.00f }; - var timingFunctions = new CAMediaTimingFunction[] { easeOut, liner, easeOut, easeInOut }; + var values = new NSNumber [] { fs, fs * 1.15f, fs * 1.15f, ts * 0.97f, ts }; + var keyTimes = new NSNumber [] { 0.00f, 0.25f, 0.50f, 0.75f, 1.00f }; + var timingFunctions = new CAMediaTimingFunction [] { easeOut, liner, easeOut, easeInOut }; scaleAnimation.Values = values; scaleAnimation.KeyTimes = keyTimes; @@ -231,87 +220,84 @@ private CAKeyFrameAnimation ScaleAnimation(string keyPath){ return scaleAnimation; } - private void Open() { + private void Open () + { - if (IsOpen || IsAnimating) - { + if (IsOpen || IsAnimating) { return; } // Open animation - SCNTransaction.Begin(); - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); + SCNTransaction.Begin (); + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); SCNTransaction.AnimationDuration = AnimationDuration / 4f; - FocusSquareNode().Opacity = 1.0f; + FocusSquareNode ().Opacity = 1.0f; - foreach(var segment in Segments) - { - segment.Open(); + foreach (var segment in Segments) { + segment.Open (); } - SCNTransaction.SetCompletionBlock( () => { - FocusSquareNode().RunAction(PulseAction(), "pulse"); + SCNTransaction.SetCompletionBlock (() => { + FocusSquareNode ().RunAction (PulseAction (), "pulse"); }); - SCNTransaction.Commit(); + SCNTransaction.Commit (); // Scale/bounce animation - SCNTransaction.Begin(); - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); + SCNTransaction.Begin (); + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); SCNTransaction.AnimationDuration = AnimationDuration / 4f; - FocusSquareNode().SetUniformScale(FocusSquareSize); - SCNTransaction.Commit(); + FocusSquareNode ().SetUniformScale (FocusSquareSize); + SCNTransaction.Commit (); IsOpen = true; } - private void Close(bool flash = false) { + private void Close (bool flash = false) + { - if (! IsOpen || IsAnimating) - { + if (!IsOpen || IsAnimating) { return; } IsAnimating = true; - StopPulsing(FocusSquareNode()); + StopPulsing (FocusSquareNode ()); // Close animation - SCNTransaction.Begin(); - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); + SCNTransaction.Begin (); + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); SCNTransaction.AnimationDuration = AnimationDuration / 2f; - FocusSquareNode().Opacity = 0.99f; - SCNTransaction.SetCompletionBlock(() => { - SCNTransaction.Begin(); - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); + FocusSquareNode ().Opacity = 0.99f; + SCNTransaction.SetCompletionBlock (() => { + SCNTransaction.Begin (); + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); SCNTransaction.AnimationDuration = AnimationDuration / 4f; - foreach(var segment in segments) - { - segment.Close(); + foreach (var segment in segments) { + segment.Close (); } - SCNTransaction.SetCompletionBlock(() => { + SCNTransaction.SetCompletionBlock (() => { IsAnimating = false; }); - SCNTransaction.Commit(); + SCNTransaction.Commit (); }); - SCNTransaction.Commit(); + SCNTransaction.Commit (); // Scale/bounce animation - FocusSquareNode().AddAnimation(ScaleAnimation("transform.scale.x"), "transform.scale.y"); - FocusSquareNode().AddAnimation(ScaleAnimation("transform.scale.y"), "transform.scale.y"); - FocusSquareNode().AddAnimation(ScaleAnimation("transform.scale.z"), "transform.scale.z"); + FocusSquareNode ().AddAnimation (ScaleAnimation ("transform.scale.x"), "transform.scale.y"); + FocusSquareNode ().AddAnimation (ScaleAnimation ("transform.scale.y"), "transform.scale.y"); + FocusSquareNode ().AddAnimation (ScaleAnimation ("transform.scale.z"), "transform.scale.z"); // Flash? if (flash) { - var waitAction = SCNAction.Wait(AnimationDuration * 0.75f); - var fadeInAction = SCNAction.FadeOpacityTo(0.25f, AnimationDuration * 0.125f); - var fadeOutAction = SCNAction.FadeOpacityTo(0.0f, AnimationDuration * 0.125f); - FillPlane.RunAction(SCNAction.Sequence(new SCNAction[] {waitAction, fadeInAction, fadeOutAction})); - - var flashSquareAction = FlashAnimation(AnimationDuration * 0.25f); - foreach(var segment in Segments) - { - segment.RunAction(SCNAction.Sequence(new[] { waitAction, flashSquareAction })); + var waitAction = SCNAction.Wait (AnimationDuration * 0.75f); + var fadeInAction = SCNAction.FadeOpacityTo (0.25f, AnimationDuration * 0.125f); + var fadeOutAction = SCNAction.FadeOpacityTo (0.0f, AnimationDuration * 0.125f); + FillPlane.RunAction (SCNAction.Sequence (new SCNAction [] { waitAction, fadeInAction, fadeOutAction })); + + var flashSquareAction = FlashAnimation (AnimationDuration * 0.25f); + foreach (var segment in Segments) { + segment.RunAction (SCNAction.Sequence (new [] { waitAction, flashSquareAction })); } } @@ -319,9 +305,9 @@ private void Close(bool flash = false) { } private SCNNode focusSquareNode = null; - private SCNNode FocusSquareNode() { - if (focusSquareNode == null) - { + private SCNNode FocusSquareNode () + { + if (focusSquareNode == null) { /* The focus square consists of eight Segments as follows, which can be individually animated. @@ -337,74 +323,74 @@ s7 s8 var sl = 0.5f; // segment length var c = FocusSquareThickness / 2f; // correction to align lines perfectly - var s1 = new FocusSquareSegment("s1", Corner.TopLeft, Alignment.Horizontal); - var s2 = new FocusSquareSegment("s2", Corner.TopRight, Alignment.Horizontal); - var s3 = new FocusSquareSegment("s3", Corner.TopLeft, Alignment.Vertical); - var s4 = new FocusSquareSegment("s4", Corner.TopRight, Alignment.Vertical); - var s5 = new FocusSquareSegment("s5", Corner.BottomLeft, Alignment.Vertical); - var s6 = new FocusSquareSegment("s6", Corner.BottomRight, Alignment.Vertical); - var s7 = new FocusSquareSegment("s7", Corner.BottomLeft, Alignment.Horizontal); - var s8 = new FocusSquareSegment("s8", Corner.BottomRight, Alignment.Horizontal); - - s1.Position = s1.Position.Add(new SCNVector3(-(sl / 2 - c), -(sl - c), 0)); - s2.Position = s2.Position.Add(new SCNVector3(sl / 2 - c, -(sl - c), 0)); - s3.Position = s3.Position.Add(new SCNVector3(-sl, -sl / 2, 0)); - s4.Position = s4.Position.Add(new SCNVector3(sl, -sl / 2, 0)); - s5.Position = s5.Position.Add(new SCNVector3(-sl, sl / 2, 0)); - s6.Position = s6.Position.Add(new SCNVector3(sl, sl / 2, 0)); - s7.Position = s7.Position.Add(new SCNVector3(-(sl / 2 - c), sl - c, 0)); - s8.Position = s8.Position.Add(new SCNVector3(sl / 2 - c, sl - c, 0)); - - var planeNode = new SCNNode(); - planeNode.EulerAngles = new SCNVector3((float) (Math.PI / 2), planeNode.EulerAngles.Y, planeNode.EulerAngles.Z); - planeNode.SetUniformScale(FocusSquareSize * ScaleForClosedSquare); - - planeNode.AddChildNode(s1); - planeNode.AddChildNode(s2); - planeNode.AddChildNode(s3); - planeNode.AddChildNode(s4); - planeNode.AddChildNode(s5); - planeNode.AddChildNode(s6); - planeNode.AddChildNode(s7); - planeNode.AddChildNode(s8); - planeNode.AddChildNode(FillPlane); - segments = new FocusSquareSegment[] { s1, s2, s3, s4, s5, s6, s7, s8 }; + var s1 = new FocusSquareSegment ("s1", Corner.TopLeft, Alignment.Horizontal); + var s2 = new FocusSquareSegment ("s2", Corner.TopRight, Alignment.Horizontal); + var s3 = new FocusSquareSegment ("s3", Corner.TopLeft, Alignment.Vertical); + var s4 = new FocusSquareSegment ("s4", Corner.TopRight, Alignment.Vertical); + var s5 = new FocusSquareSegment ("s5", Corner.BottomLeft, Alignment.Vertical); + var s6 = new FocusSquareSegment ("s6", Corner.BottomRight, Alignment.Vertical); + var s7 = new FocusSquareSegment ("s7", Corner.BottomLeft, Alignment.Horizontal); + var s8 = new FocusSquareSegment ("s8", Corner.BottomRight, Alignment.Horizontal); + + s1.Position = s1.Position.Add (new SCNVector3 (-(sl / 2 - c), -(sl - c), 0)); + s2.Position = s2.Position.Add (new SCNVector3 (sl / 2 - c, -(sl - c), 0)); + s3.Position = s3.Position.Add (new SCNVector3 (-sl, -sl / 2, 0)); + s4.Position = s4.Position.Add (new SCNVector3 (sl, -sl / 2, 0)); + s5.Position = s5.Position.Add (new SCNVector3 (-sl, sl / 2, 0)); + s6.Position = s6.Position.Add (new SCNVector3 (sl, sl / 2, 0)); + s7.Position = s7.Position.Add (new SCNVector3 (-(sl / 2 - c), sl - c, 0)); + s8.Position = s8.Position.Add (new SCNVector3 (sl / 2 - c, sl - c, 0)); + + var planeNode = new SCNNode (); + planeNode.EulerAngles = new SCNVector3 ((float) (Math.PI / 2), planeNode.EulerAngles.Y, planeNode.EulerAngles.Z); + planeNode.SetUniformScale (FocusSquareSize * ScaleForClosedSquare); + + planeNode.AddChildNode (s1); + planeNode.AddChildNode (s2); + planeNode.AddChildNode (s3); + planeNode.AddChildNode (s4); + planeNode.AddChildNode (s5); + planeNode.AddChildNode (s6); + planeNode.AddChildNode (s7); + planeNode.AddChildNode (s8); + planeNode.AddChildNode (FillPlane); + segments = new FocusSquareSegment [] { s1, s2, s3, s4, s5, s6, s7, s8 }; IsOpen = false; // Always render focus square on top - planeNode.RenderOnTop(); + planeNode.RenderOnTop (); focusSquareNode = planeNode; } return focusSquareNode; } - public void Update(SCNVector3 position, ARPlaneAnchor planeAnchor, ARCamera camera) + public void Update (SCNVector3 position, ARPlaneAnchor planeAnchor, ARCamera camera) { LastPosition = position; var anchor = planeAnchor; - if (anchor != null) - { - Close(!AnchorsOfVisitedPlanes.Contains(anchor)); + if (anchor != null) { + Close (!AnchorsOfVisitedPlanes.Contains (anchor)); LastPositionOnPlane = position; - AnchorsOfVisitedPlanes.Add(anchor); + AnchorsOfVisitedPlanes.Add (anchor); } else { - Open(); + Open (); } - UpdateTransform(position, camera); + UpdateTransform (position, camera); } - public void Hide() { - if (Math.Abs(Opacity - 1.0) < Double.Epsilon) { - RunAction(SCNAction.FadeOut(0.5f)); + public void Hide () + { + if (Math.Abs (Opacity - 1.0) < Double.Epsilon) { + RunAction (SCNAction.FadeOut (0.5f)); } } - public void Show() { - if (Opacity == 0) - { - RunAction(SCNAction.FadeIn(0.5f)); + public void Show () + { + if (Opacity == 0) { + RunAction (SCNAction.FadeIn (0.5f)); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquareSegment.cs b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquareSegment.cs index 2fb66947f..9714ef982 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquareSegment.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/FocusSquareSegment.cs @@ -1,12 +1,11 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ +namespace PlacingObjects { /* The focus square consists of eight segments as follows, which can be individually animated. @@ -18,42 +17,36 @@ _ _ - - s7 s8 */ - public enum Corner - { - TopLeft, // s1, s3 - TopRight, // s2, s4 - BottomRight, // s6, s8 - BottomLeft // s5, s7 + public enum Corner { + TopLeft, // s1, s3 + TopRight, // s2, s4 + BottomRight, // s6, s8 + BottomLeft // s5, s7 } - public enum Alignment - { - Horizontal, // s1, s2, s7, s8 - Vertical // s3, s4, s5, s6 + public enum Alignment { + Horizontal, // s1, s2, s7, s8 + Vertical // s3, s4, s5, s6 } - enum Direction - { + enum Direction { Up, Down, Left, Right } - static class Direction_Extensions - { - public static Direction Reversed(this Direction self) + static class Direction_Extensions { + public static Direction Reversed (this Direction self) { - switch (self) - { - case Direction.Up : return Direction.Down; - case Direction.Down : return Direction.Up; - case Direction.Left : return Direction.Right; - case Direction.Right : return Direction.Left; - default : - throw new ArgumentOutOfRangeException(); + switch (self) { + case Direction.Up: return Direction.Down; + case Direction.Down: return Direction.Up; + case Direction.Left: return Direction.Right; + case Direction.Right: return Direction.Left; + default: + throw new ArgumentOutOfRangeException (); } } } - public class FocusSquareSegment : SCNNode - { + public class FocusSquareSegment : SCNNode { // Thickness and length in meters static float thickness = 0.018f; static float length = 0.5f; @@ -61,25 +54,24 @@ public class FocusSquareSegment : SCNNode // Side length of the focus square segments when open (w.r.t. to a 1x1 square) static float openLength = 0.2f; - private Corner Corner { get; set; } + private Corner Corner { get; set; } private Alignment Alignment { get; set; } - public FocusSquareSegment(string name, Corner corner, Alignment alignment) : base() + public FocusSquareSegment (string name, Corner corner, Alignment alignment) : base () { this.Name = name; this.Corner = corner; this.Alignment = alignment; - switch (Alignment) - { - case Alignment.Vertical: - this.Geometry = new SCNPlane { Width = FocusSquareSegment.thickness, Height = FocusSquareSegment.length }; - break; - case Alignment.Horizontal : - this.Geometry = new SCNPlane { Width = FocusSquareSegment.length, Height = FocusSquareSegment.thickness }; - break; - default: - throw new ArgumentOutOfRangeException(); + switch (Alignment) { + case Alignment.Vertical: + this.Geometry = new SCNPlane { Width = FocusSquareSegment.thickness, Height = FocusSquareSegment.length }; + break; + case Alignment.Horizontal: + this.Geometry = new SCNPlane { Width = FocusSquareSegment.length, Height = FocusSquareSegment.thickness }; + break; + default: + throw new ArgumentOutOfRangeException (); } var material = Geometry.FirstMaterial; @@ -90,7 +82,7 @@ public FocusSquareSegment(string name, Corner corner, Alignment alignment) : bas material.Emission.ContentColor = FocusSquare.PrimaryColor; } - public FocusSquareSegment(NSCoder coder) : base(coder) + public FocusSquareSegment (NSCoder coder) : base (coder) { // Initialize Name = "Focus Square Segment"; @@ -98,66 +90,58 @@ public FocusSquareSegment(NSCoder coder) : base(coder) private Direction OpenDirection () { - switch (this.Corner) - { - case Corner.TopLeft : - return this.Alignment == Alignment.Horizontal ? Direction.Left : Direction.Up; - case Corner.TopRight : - return this.Alignment == Alignment.Horizontal ? Direction.Right : Direction.Up; - case Corner.BottomLeft : - return this.Alignment == Alignment.Horizontal ? Direction.Left : Direction.Down; - case Corner.BottomRight : - return this.Alignment == Alignment.Horizontal ? Direction.Right : Direction.Down; - default: - throw new ArgumentOutOfRangeException(); + switch (this.Corner) { + case Corner.TopLeft: + return this.Alignment == Alignment.Horizontal ? Direction.Left : Direction.Up; + case Corner.TopRight: + return this.Alignment == Alignment.Horizontal ? Direction.Right : Direction.Up; + case Corner.BottomLeft: + return this.Alignment == Alignment.Horizontal ? Direction.Left : Direction.Down; + case Corner.BottomRight: + return this.Alignment == Alignment.Horizontal ? Direction.Right : Direction.Down; + default: + throw new ArgumentOutOfRangeException (); } } - public void Open() { + public void Open () + { var plane = Geometry as SCNPlane; - if (plane == null) - { + if (plane == null) { return; } - var direction = OpenDirection(); + var direction = OpenDirection (); - if (Alignment == Alignment.Horizontal) - { + if (Alignment == Alignment.Horizontal) { plane.Width = FocusSquareSegment.openLength; - } - else - { + } else { plane.Height = FocusSquareSegment.openLength; } var offset = FocusSquareSegment.length / 2 - FocusSquareSegment.openLength / 2; - switch(direction) - { - case Direction.Left : this.Position = new SCNVector3(Position.X - offset, Position.Y, Position.Z); break; - case Direction.Right : this.Position = new SCNVector3(Position.X + offset, Position.Y, Position.Z); break; - case Direction.Up : this.Position = new SCNVector3(Position.X, Position.Y - offset, Position.Z); break; - case Direction.Down : this.Position = new SCNVector3(Position.X, Position.Y + offset, Position.Z); break; + switch (direction) { + case Direction.Left: this.Position = new SCNVector3 (Position.X - offset, Position.Y, Position.Z); break; + case Direction.Right: this.Position = new SCNVector3 (Position.X + offset, Position.Y, Position.Z); break; + case Direction.Up: this.Position = new SCNVector3 (Position.X, Position.Y - offset, Position.Z); break; + case Direction.Down: this.Position = new SCNVector3 (Position.X, Position.Y + offset, Position.Z); break; } } - public void Close() { + public void Close () + { var plane = Geometry as SCNPlane; - if (plane == null) - { + if (plane == null) { return; } - var direction = this.OpenDirection().Reversed(); + var direction = this.OpenDirection ().Reversed (); var oldLength = 0.0f; - if (Alignment == Alignment.Horizontal) - { - oldLength = (float)plane.Width; + if (Alignment == Alignment.Horizontal) { + oldLength = (float) plane.Width; plane.Width = 0.5f; - } - else - { - oldLength = (float)plane.Height; + } else { + oldLength = (float) plane.Height; plane.Height = 0.5f; } @@ -165,14 +149,13 @@ public void Close() { var y = Position.Y; var z = Position.Z; var offset = FocusSquareSegment.length / 2 - FocusSquareSegment.openLength / 2; - switch (direction) - { - case Direction.Left: x -= offset; break; - case Direction.Right: x += offset; break; - case Direction.Up : y -= offset; break; - case Direction.Down : y += offset; break; + switch (direction) { + case Direction.Left: x -= offset; break; + case Direction.Right: x += offset; break; + case Direction.Up: y -= offset; break; + case Direction.Down: y += offset; break; } - Position = new SCNVector3(x, y, z); + Position = new SCNVector3 (x, y, z); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Gesture.cs b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Gesture.cs index ac3489c52..06c242041 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Gesture.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Gesture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -7,10 +7,8 @@ using ARKit; using System.Linq; -namespace PlacingObjects -{ - public abstract class Gesture : NSObject - { +namespace PlacingObjects { + public abstract class Gesture : NSObject { public VirtualObject LastUsedObject { get; protected set; } protected System.Threading.Timer refreshTimer; @@ -18,7 +16,7 @@ public abstract class Gesture : NSObject protected ARSCNView SceneView { get; set; } protected NSSet currentTouches; - public Gesture(NSSet currentTouches, ARSCNView sceneView, VirtualObject lastUsedObject, VirtualObjectManager manager) + public Gesture (NSSet currentTouches, ARSCNView sceneView, VirtualObject lastUsedObject, VirtualObjectManager manager) { this.currentTouches = currentTouches; this.SceneView = sceneView; @@ -27,96 +25,87 @@ public Gesture(NSSet currentTouches, ARSCNView sceneView, VirtualObject lastUsed // Refresh the current gesture at 60 Hz - This ensures smooth updates even when no // new touch events are incoming (but the camera might have moved). - this.refreshTimer = new System.Threading.Timer(CheckedUpdateGesture, null, 0, 17); + this.refreshTimer = new System.Threading.Timer (CheckedUpdateGesture, null, 0, 17); } // Hit tests against the `sceneView` to find an object at the provided point. - protected VirtualObject VirtualObjectAt(CGPoint loc) + protected VirtualObject VirtualObjectAt (CGPoint loc) { var hitTestOptions = new SCNHitTestOptions { BoundingBoxOnly = true }; - var hitTestResults = SceneView.HitTest(loc, hitTestOptions); - if (hitTestResults.Count() == 0) - { + var hitTestResults = SceneView.HitTest (loc, hitTestOptions); + if (hitTestResults.Count () == 0) { return null; } - var firstNodeHit = hitTestResults.First((result) => VirtualObject.IsNodePartOfVirtualObject(result.Node)); - var voNode = VirtualObject.ForChildNode(firstNodeHit.Node); + var firstNodeHit = hitTestResults.First ((result) => VirtualObject.IsNodePartOfVirtualObject (result.Node)); + var voNode = VirtualObject.ForChildNode (firstNodeHit.Node); return voNode; } - virtual public Gesture UpdateGestureFromTouches(NSSet touches, TouchEventType touchType) + virtual public Gesture UpdateGestureFromTouches (NSSet touches, TouchEventType touchType) { - if (touches.Count() == 0) - { + if (touches.Count () == 0) { // No touches, do nothing return null; } // Update the set of current touches - switch (touchType) - { - case TouchEventType.TouchBegan: - case TouchEventType.TouchMoved: - var touchesUnion = currentTouches.Union(touches); - var touchesArray = new UITouch[touchesUnion.Count()]; - int i = 0; - foreach(UITouch touch in touchesUnion) - { - touchesArray[i] = touch; - i++; - } - currentTouches = new NSSet(touchesArray); - break; - case TouchEventType.TouchCanceled: - case TouchEventType.TouchEnded: - var notInTouches = NSPredicate.FromExpression(new NSPredicateEvaluator((evaluatedObject, bindings) => !touches.Contains(evaluatedObject))); - currentTouches = currentTouches.FilterUsingPredicate(notInTouches); - break; + switch (touchType) { + case TouchEventType.TouchBegan: + case TouchEventType.TouchMoved: + var touchesUnion = currentTouches.Union (touches); + var touchesArray = new UITouch [touchesUnion.Count ()]; + int i = 0; + foreach (UITouch touch in touchesUnion) { + touchesArray [i] = touch; + i++; + } + currentTouches = new NSSet (touchesArray); + break; + case TouchEventType.TouchCanceled: + case TouchEventType.TouchEnded: + var notInTouches = NSPredicate.FromExpression (new NSPredicateEvaluator ((evaluatedObject, bindings) => !touches.Contains (evaluatedObject))); + currentTouches = currentTouches.FilterUsingPredicate (notInTouches); + break; } var expectedTouchCount = (this is SingleFingerGesture) ? 1 : 2; - if (currentTouches.Count() == expectedTouchCount) - { - this.UpdateGesture(null); + if (currentTouches.Count () == expectedTouchCount) { + this.UpdateGesture (null); return this; - } - else - { - this.FinishGesture(); - this.refreshTimer?.Dispose(); + } else { + this.FinishGesture (); + this.refreshTimer?.Dispose (); // Erase reference to timer in case callback fires one last time this.refreshTimer = null; // Switch to two-finger gesture if was single-finger. If was two-finger, return null return (this is SingleFingerGesture) - ? Gesture.StartGestureFromTouches(currentTouches, this.SceneView, LastUsedObject, manager) + ? Gesture.StartGestureFromTouches (currentTouches, this.SceneView, LastUsedObject, manager) : null; } } - protected void CheckedUpdateGesture(object state) + protected void CheckedUpdateGesture (object state) { // Confirm refreshTimer has not been disposed and null'ed out - if (this.refreshTimer != null) - { - UpdateGesture(state); + if (this.refreshTimer != null) { + UpdateGesture (state); } } - abstract protected void UpdateGesture(object state); - abstract protected void FinishGesture(); + abstract protected void UpdateGesture (object state); + abstract protected void FinishGesture (); // Static factory method - public static Gesture StartGestureFromTouches(NSSet currentTouches, ARSCNView sceneView, VirtualObject lastUsedObject, VirtualObjectManager manager) + public static Gesture StartGestureFromTouches (NSSet currentTouches, ARSCNView sceneView, VirtualObject lastUsedObject, VirtualObjectManager manager) { - switch (currentTouches.Count) - { - case 1: return new SingleFingerGesture(currentTouches, sceneView, lastUsedObject, manager); - case 2: return new TwoFingerGesture(currentTouches, sceneView, lastUsedObject, manager); - default: - return null; + switch (currentTouches.Count) { + case 1: return new SingleFingerGesture (currentTouches, sceneView, lastUsedObject, manager); + case 2: return new TwoFingerGesture (currentTouches, sceneView, lastUsedObject, manager); + default: + return null; } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Plane.cs b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Plane.cs index 345b70177..e1d095d20 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Plane.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/Plane.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -7,26 +7,24 @@ using SceneKit; using ARKit; -namespace PlacingObjects -{ - public class Plane : SCNNode - { +namespace PlacingObjects { + public class Plane : SCNNode { public ARPlaneAnchor Anchor { get; set; } - public Plane(ARPlaneAnchor anchor) + public Plane (ARPlaneAnchor anchor) { // Initialize Anchor = anchor; - base.Init(); + base.Init (); } - public Plane(NSCoder coder) : base(coder) + public Plane (NSCoder coder) : base (coder) { } - public void Update(ARPlaneAnchor anchor) + public void Update (ARPlaneAnchor anchor) { Anchor = anchor; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/SingleFingerGesture.cs b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/SingleFingerGesture.cs index abf1b6f8c..5e682fde1 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/SingleFingerGesture.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/SingleFingerGesture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -7,12 +7,10 @@ using ARKit; using System.Linq; -namespace PlacingObjects -{ - public class SingleFingerGesture : Gesture - { - CGPoint initialTouchPosition = new CGPoint(); - CGPoint latestTouchPosition = new CGPoint(); +namespace PlacingObjects { + public class SingleFingerGesture : Gesture { + CGPoint initialTouchPosition = new CGPoint (); + CGPoint latestTouchPosition = new CGPoint (); VirtualObject firstTouchedObject; @@ -20,90 +18,79 @@ public class SingleFingerGesture : Gesture bool translationThresholdPassed = false; bool hasMovedObject = false; - CGPoint dragOffset = new CGPoint(); + CGPoint dragOffset = new CGPoint (); - public SingleFingerGesture(NSSet touches, ARSCNView scnView, VirtualObject lastUsedObject, VirtualObjectManager vom) - : base(touches, scnView, lastUsedObject, vom) + public SingleFingerGesture (NSSet touches, ARSCNView scnView, VirtualObject lastUsedObject, VirtualObjectManager vom) + : base (touches, scnView, lastUsedObject, vom) { - var firstTouch = (UITouch)touches.First(); - initialTouchPosition = firstTouch.LocationInView(scnView); + var firstTouch = (UITouch) touches.First (); + initialTouchPosition = firstTouch.LocationInView (scnView); latestTouchPosition = initialTouchPosition; - firstTouchedObject = this.VirtualObjectAt(initialTouchPosition); + firstTouchedObject = this.VirtualObjectAt (initialTouchPosition); } - override protected void UpdateGesture(object state) + override protected void UpdateGesture (object state) { var virtualObject = firstTouchedObject; - if (virtualObject == null) - { + if (virtualObject == null) { return; } // We know there's a first since the gesture begins with at least one - InvokeOnMainThread(() => - { - if (this.currentTouches.Count() == 0) - { + InvokeOnMainThread (() => { + if (this.currentTouches.Count () == 0) { return; } - latestTouchPosition = ((UITouch)this.currentTouches.First()).LocationInView(this.SceneView); + latestTouchPosition = ((UITouch) this.currentTouches.First ()).LocationInView (this.SceneView); - if (!translationThresholdPassed) - { - var initialLocationToCurrentPosition = latestTouchPosition.Subtract(initialTouchPosition); - var distanceFromStartLocation = initialLocationToCurrentPosition.Length(); - if (distanceFromStartLocation >= translationThreshold) - { + if (!translationThresholdPassed) { + var initialLocationToCurrentPosition = latestTouchPosition.Subtract (initialTouchPosition); + var distanceFromStartLocation = initialLocationToCurrentPosition.Length (); + if (distanceFromStartLocation >= translationThreshold) { translationThresholdPassed = true; - var currentObjectLocation = SceneView.ProjectPoint(virtualObject.Position).ToCGPoint(); - dragOffset = latestTouchPosition.Subtract(currentObjectLocation); + var currentObjectLocation = SceneView.ProjectPoint (virtualObject.Position).ToCGPoint (); + dragOffset = latestTouchPosition.Subtract (currentObjectLocation); } } // A single finger drag will occur if the drag started on the object and the threshold has been passed. - if (translationThresholdPassed) - { - var offsetPos = latestTouchPosition.Subtract(dragOffset); - this.manager.Translate(virtualObject, SceneView, offsetPos, false, true); + if (translationThresholdPassed) { + var offsetPos = latestTouchPosition.Subtract (dragOffset); + this.manager.Translate (virtualObject, SceneView, offsetPos, false, true); hasMovedObject = true; LastUsedObject = virtualObject; } }); } - override protected void FinishGesture() + override protected void FinishGesture () { // Single finger touch allows teleporting the object or interacting with it. // Do not do anything if this gesture is being finished because // another finger has started touching the screen. - if (currentTouches.Count > 1) - { + if (currentTouches.Count > 1) { return; } // Do not do anything either if the touch has dragged the object around. - if (hasMovedObject) - { + if (hasMovedObject) { return; } - if (LastUsedObject != null) - { + if (LastUsedObject != null) { // If this gesture hasn't moved the object then perform a hit test against // the geometry to check if the user has tapped the object itself. // - Note: If the object covers a significant // percentage of the screen then we should interpret the tap as repositioning // the object. - var isObjectHit = VirtualObjectAt(latestTouchPosition) != null; + var isObjectHit = VirtualObjectAt (latestTouchPosition) != null; - if (!isObjectHit) - { + if (!isObjectHit) { // Teleport the object to where-ever the user touched the screen - as long as the // drag threshold has not been reached. - if (!translationThresholdPassed) - { - manager.Translate(LastUsedObject, SceneView, latestTouchPosition, true, false); + if (!translationThresholdPassed) { + manager.Translate (LastUsedObject, SceneView, latestTouchPosition, true, false); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/TwoFingerGesture.cs b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/TwoFingerGesture.cs index 7a081ae3c..661aa8c07 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/TwoFingerGesture.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/UIElements/TwoFingerGesture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -7,10 +7,8 @@ using ARKit; using System.Linq; -namespace PlacingObjects -{ - public class TwoFingerGesture : Gesture - { +namespace PlacingObjects { + public class TwoFingerGesture : Gesture { protected UITouch FirstTouch { get; set; } protected UITouch SecondTouch { get; set; } @@ -19,11 +17,11 @@ public class TwoFingerGesture : Gesture protected float TranslationThresholdHarder { get; set; } = 70f; protected bool TranslationThresholdPassed { get; set; } = false; protected bool AllowTranslation { get; set; } = false; - protected CGPoint DragOffset { get; set; } = new CGPoint(); - protected CGPoint InitialMidpoint { get; set; } = new CGPoint(0, 0); + protected CGPoint DragOffset { get; set; } = new CGPoint (); + protected CGPoint InitialMidpoint { get; set; } = new CGPoint (0, 0); - protected float RotationThreshold { get; set; } = (float)(Math.PI / 15); // (12°) - protected float RotationThresholdHarder { get; set; } = (float)(Math.PI / 10); // (18°) + protected float RotationThreshold { get; set; } = (float) (Math.PI / 15); // (12°) + protected float RotationThresholdHarder { get; set; } = (float) (Math.PI / 10); // (18°) protected bool RotationThresholdPassed { get; set; } = false; protected bool AllowRotation { get; set; } = false; protected double InitialFingerAngle { get; set; } = 0; @@ -38,24 +36,24 @@ public class TwoFingerGesture : Gesture protected float BaseDistanceBetweenFingers { get; set; } = 0; protected double ObjectBaseScale { get; set; } = 1.0; - public TwoFingerGesture(NSSet touches, ARSCNView view, VirtualObject parentObject, VirtualObjectManager manager) : base(touches, view, parentObject, manager) + public TwoFingerGesture (NSSet touches, ARSCNView view, VirtualObject parentObject, VirtualObjectManager manager) : base (touches, view, parentObject, manager) { - var tArray = touches.ToArray<UITouch>(); - FirstTouch = tArray[0]; - SecondTouch = tArray[1]; + var tArray = touches.ToArray<UITouch> (); + FirstTouch = tArray [0]; + SecondTouch = tArray [1]; - var firstTouchPoint = FirstTouch.LocationInView(SceneView); - var secondTouchPoint = SecondTouch.LocationInView(SceneView); + var firstTouchPoint = FirstTouch.LocationInView (SceneView); + var secondTouchPoint = SecondTouch.LocationInView (SceneView); - InitialMidpoint = firstTouchPoint.Add(secondTouchPoint).Divide(2f); + InitialMidpoint = firstTouchPoint.Add (secondTouchPoint).Divide (2f); // Compute the two other corners of the rectangle defined by the two fingers // and compute the points in between. - var thirdCorner = new CGPoint(firstTouchPoint.X, secondTouchPoint.Y); - var fourthCorner = new CGPoint(secondTouchPoint.X, firstTouchPoint.Y); + var thirdCorner = new CGPoint (firstTouchPoint.X, secondTouchPoint.Y); + var fourthCorner = new CGPoint (secondTouchPoint.X, firstTouchPoint.Y); // Compute points in between. - var midpoints = new[] + var midpoints = new [] { thirdCorner.Add(firstTouchPoint).Divide(2f), thirdCorner.Add(secondTouchPoint).Divide(2f), @@ -69,177 +67,154 @@ public TwoFingerGesture(NSSet touches, ARSCNView view, VirtualObject parentObjec // Check if any of the two fingers or their midpoint is touching the object. // Based on that, translation, rotation and scale will be enabled or disabled. - var allPoints = new List<CGPoint>(new[] { firstTouchPoint, secondTouchPoint, thirdCorner, fourthCorner, InitialMidpoint }); - allPoints.AddRange(midpoints); - FirstTouchedObject = allPoints.Select(pt => this.VirtualObjectAt(pt)).Where(vo => vo != null).FirstOrDefault(); + var allPoints = new List<CGPoint> (new [] { firstTouchPoint, secondTouchPoint, thirdCorner, fourthCorner, InitialMidpoint }); + allPoints.AddRange (midpoints); + FirstTouchedObject = allPoints.Select (pt => this.VirtualObjectAt (pt)).Where (vo => vo != null).FirstOrDefault (); - if (FirstTouchedObject != null) - { + if (FirstTouchedObject != null) { ObjectBaseScale = FirstTouchedObject.Scale.X; AllowTranslation = true; AllowRotation = true; - InitialDistanceBetweenFingers = (firstTouchPoint.Subtract(secondTouchPoint)).Length(); - InitialFingerAngle = Math.Atan2(InitialMidpoint.X, InitialMidpoint.Y); + InitialDistanceBetweenFingers = (firstTouchPoint.Subtract (secondTouchPoint)).Length (); + InitialFingerAngle = Math.Atan2 (InitialMidpoint.X, InitialMidpoint.Y); InitialObjectAngle = FirstTouchedObject.EulerAngles.Y; - } - else - { + } else { AllowTranslation = false; AllowRotation = false; } } - override protected void UpdateGesture(object state) + override protected void UpdateGesture (object state) { // Two finger touch enables combined translation, rotation and scale. - if (FirstTouchedObject == null) - { + if (FirstTouchedObject == null) { return; } var virtualObject = FirstTouchedObject; // First: Update the touches. - if (currentTouches.Count < 2) - { + if (currentTouches.Count < 2) { return; } - var tAry = currentTouches.ToArray<UITouch>(); - var newTouch1 = tAry[0]; - var newTouch2 = tAry[1]; + var tAry = currentTouches.ToArray<UITouch> (); + var newTouch1 = tAry [0]; + var newTouch2 = tAry [1]; - if (newTouch1.GetHashCode() == FirstTouch.GetHashCode()) - { + if (newTouch1.GetHashCode () == FirstTouch.GetHashCode ()) { FirstTouch = newTouch1; SecondTouch = newTouch2; - } - else - { + } else { FirstTouch = newTouch2; SecondTouch = newTouch1; } - InvokeOnMainThread(() => - { - var loc1 = FirstTouch.LocationInView(SceneView); - var loc2 = SecondTouch.LocationInView(SceneView); + InvokeOnMainThread (() => { + var loc1 = FirstTouch.LocationInView (SceneView); + var loc2 = SecondTouch.LocationInView (SceneView); - if (AllowTranslation) - { + if (AllowTranslation) { // 1. Translation using the midpoint between the two fingers. - UpdateTranslation(virtualObject, loc1.MidPoint(loc2)); + UpdateTranslation (virtualObject, loc1.MidPoint (loc2)); } - var spanBetweenTouches = loc1.Subtract(loc2); + var spanBetweenTouches = loc1.Subtract (loc2); - if (AllowRotation) - { + if (AllowRotation) { // 2. Rotation based on the relative rotation of the fingers on a unit circle. - UpdateRotation(virtualObject, spanBetweenTouches); + UpdateRotation (virtualObject, spanBetweenTouches); } }); } - override public Gesture UpdateGestureFromTouches(NSSet touches, TouchEventType touchType) + override public Gesture UpdateGestureFromTouches (NSSet touches, TouchEventType touchType) { - base.UpdateGestureFromTouches(touches, touchType); + base.UpdateGestureFromTouches (touches, touchType); // Take action based on the number of touches - switch (currentTouches.Count) - { - case 0: - // Nothing to process - return this; - case 2: - // Update this gesture - UpdateGesture(null); - return this; - default: - // Finish this two finger gesture and switch to no gesture -> The user - // will have to release all other fingers and touch the screen again - // to start a new gesture. - FinishGesture(); - this.refreshTimer?.Dispose(); - // Erase reference to timer in case callback fires one last time - this.refreshTimer = null; - return null; + switch (currentTouches.Count) { + case 0: + // Nothing to process + return this; + case 2: + // Update this gesture + UpdateGesture (null); + return this; + default: + // Finish this two finger gesture and switch to no gesture -> The user + // will have to release all other fingers and touch the screen again + // to start a new gesture. + FinishGesture (); + this.refreshTimer?.Dispose (); + // Erase reference to timer in case callback fires one last time + this.refreshTimer = null; + return null; } } - protected override void FinishGesture() + protected override void FinishGesture () { // Nothing to do when finishing two-finger gesture } - public void UpdateTranslation(VirtualObject virtualObject, CGPoint midpoint) + public void UpdateTranslation (VirtualObject virtualObject, CGPoint midpoint) { - if (!TranslationThresholdPassed) - { - var initialLocationToCurrentLocation = midpoint.Subtract(InitialMidpoint); - var distanceFromStartLocation = initialLocationToCurrentLocation.Length(); + if (!TranslationThresholdPassed) { + var initialLocationToCurrentLocation = midpoint.Subtract (InitialMidpoint); + var distanceFromStartLocation = initialLocationToCurrentLocation.Length (); // Check if the translate gesture has crossed the threshold. // If the user is already rotating and or scaling we use a bigger threshold. var threshold = TranslationThreshold; - if (RotationThresholdPassed || TranslationThresholdPassed) - { + if (RotationThresholdPassed || TranslationThresholdPassed) { threshold = TranslationThresholdHarder; } - if (distanceFromStartLocation >= threshold) - { + if (distanceFromStartLocation >= threshold) { TranslationThresholdPassed = true; - var currentObjectLocation = CGPointExtensions.FromVector(SceneView.ProjectPoint(virtualObject.Position)); - DragOffset = midpoint.Subtract(currentObjectLocation); + var currentObjectLocation = CGPointExtensions.FromVector (SceneView.ProjectPoint (virtualObject.Position)); + DragOffset = midpoint.Subtract (currentObjectLocation); } } - if (TranslationThresholdPassed) - { - var offsetPos = midpoint.Subtract(DragOffset); - manager.Translate(virtualObject, SceneView, offsetPos, false, true); + if (TranslationThresholdPassed) { + var offsetPos = midpoint.Subtract (DragOffset); + manager.Translate (virtualObject, SceneView, offsetPos, false, true); LastUsedObject = virtualObject; } } - public void UpdateRotation(VirtualObject virtualObject, CGPoint span) + public void UpdateRotation (VirtualObject virtualObject, CGPoint span) { - var midPointToFirstTouch = span.Divide(2f); - var currentAngle = Math.Atan2(midPointToFirstTouch.X, midPointToFirstTouch.Y); + var midPointToFirstTouch = span.Divide (2f); + var currentAngle = Math.Atan2 (midPointToFirstTouch.X, midPointToFirstTouch.Y); var currentAngleToInitialFingerAngle = InitialFingerAngle - currentAngle; - if (!RotationThresholdPassed) - { + if (!RotationThresholdPassed) { var threshold = RotationThreshold; - if (TranslationThresholdPassed || ScaleThresholdPassed) - { + if (TranslationThresholdPassed || ScaleThresholdPassed) { threshold = RotationThresholdHarder; } - if ((float)Math.Abs(currentAngleToInitialFingerAngle) > threshold) - { + if ((float) Math.Abs (currentAngleToInitialFingerAngle) > threshold) { RotationThresholdPassed = true; // Change the initial object angle to prevent a sudden jump after crossing the threshold. - if (currentAngleToInitialFingerAngle > 0f) - { + if (currentAngleToInitialFingerAngle > 0f) { InitialObjectAngle += threshold; - } - else - { + } else { InitialObjectAngle -= threshold; } } } - if (RotationThresholdPassed) - { + if (RotationThresholdPassed) { // Note: // For looking down on the object (99% of all use cases), we need to subtract the angle. // To make rotation also work correctly when looking from below the object one would have to @@ -247,7 +222,7 @@ public void UpdateRotation(VirtualObject virtualObject, CGPoint span) var x = virtualObject.EulerAngles.X; var y = InitialObjectAngle - currentAngleToInitialFingerAngle; var z = virtualObject.EulerAngles.Z; - virtualObject.EulerAngles = new SCNVector3(x, (float) y, z); + virtualObject.EulerAngles = new SCNVector3 (x, (float) y, z); LastUsedObject = virtualObject; } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/AppSettings.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/AppSettings.cs index 58f58a52d..81e3cd1d9 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/AppSettings.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/AppSettings.cs @@ -1,24 +1,21 @@ -using System; +using System; using Foundation; using UIKit; -namespace PlacingObjects -{ - public static class AppSettings - { - public static bool ScaleWithPinchGesture - { - get { return NSUserDefaults.StandardUserDefaults.BoolForKey("ScaleWithPinchGesture"); } - set { NSUserDefaults.StandardUserDefaults.SetBool(value, "ScaleWithPinchGesture"); } +namespace PlacingObjects { + public static class AppSettings { + public static bool ScaleWithPinchGesture { + get { return NSUserDefaults.StandardUserDefaults.BoolForKey ("ScaleWithPinchGesture"); } + set { NSUserDefaults.StandardUserDefaults.SetBool (value, "ScaleWithPinchGesture"); } } - public static bool DragOnInfinitePlanes - { - get { return NSUserDefaults.StandardUserDefaults.BoolForKey("DragOnInfinitePlanes"); } - set { NSUserDefaults.StandardUserDefaults.SetBool(value, "DragOnInfinitePlanes"); } + public static bool DragOnInfinitePlanes { + get { return NSUserDefaults.StandardUserDefaults.BoolForKey ("DragOnInfinitePlanes"); } + set { NSUserDefaults.StandardUserDefaults.SetBool (value, "DragOnInfinitePlanes"); } } - public static void RegisterDefaults() { + public static void RegisterDefaults () + { DragOnInfinitePlanes = true; ScaleWithPinchGesture = true; } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/FeatureHitTestResult.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/FeatureHitTestResult.cs index 897f590a7..460b55000 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/FeatureHitTestResult.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/FeatureHitTestResult.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; @@ -6,10 +6,8 @@ using ARKit; using OpenTK; -namespace PlacingObjects -{ - public class FeatureHitTestResult : NSObject - { +namespace PlacingObjects { + public class FeatureHitTestResult : NSObject { public SCNVector3 Position { get; set; } public float DistanceToRayOrigin { get; set; } @@ -18,11 +16,11 @@ public class FeatureHitTestResult : NSObject public float FeatureDistanceToHitResult { get; set; } - public FeatureHitTestResult() + public FeatureHitTestResult () { } - public FeatureHitTestResult(SCNVector3 position, float distanceToRayOrigin, SCNVector3 featureHit, float featureDistanceToHitResult) + public FeatureHitTestResult (SCNVector3 position, float distanceToRayOrigin, SCNVector3 featureHit, float featureDistanceToHitResult) { // Initialize Position = position; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/HitTestRay.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/HitTestRay.cs index 1bac0b6cf..c37466570 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/HitTestRay.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/HitTestRay.cs @@ -1,22 +1,20 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public class HitTestRay : NSObject - { +namespace PlacingObjects { + public class HitTestRay : NSObject { public SCNVector3 Origin { get; set; } public SCNVector3 Direction { get; set; } - public HitTestRay() + public HitTestRay () { } - public HitTestRay(SCNVector3 origin, SCNVector3 direction) + public HitTestRay (SCNVector3 origin, SCNVector3 direction) { // Initialize Origin = origin; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/TextManager.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/TextManager.cs index 8bca4a1e8..3368a3869 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/TextManager.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/TextManager.cs @@ -1,14 +1,12 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - public class TextManager : NSObject - { +namespace PlacingObjects { + public class TextManager : NSObject { private NSTimer MessageHideTimer; private NSTimer FocusSquareMessageTimer; private NSTimer PlaneEstimationMessageTimer; @@ -21,302 +19,272 @@ public class TextManager : NSObject public ViewController Controller { get; set; } - public TextManager(ViewController controller) + public TextManager (ViewController controller) { // Initialize Controller = controller; } - public void ShowMessage(string text, bool autoHide = true) + public void ShowMessage (string text, bool autoHide = true) { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { // Cancel previous hide timer - MessageHideTimer?.Invalidate(); + MessageHideTimer?.Invalidate (); // Set text and display status - InvokeOnMainThread(() => + InvokeOnMainThread (() => Controller.MessageLabel.Text = text); - ShowHideMessage(false, true); + ShowHideMessage (false, true); // Autohide? - if (autoHide) - { + if (autoHide) { // Compute an appropriate amount of time to display the on screen message. // According to https://en.wikipedia.org/wiki/Words_per_minute, adults read // about 200 words per minute and the average English word is 5 characters // long. So 1000 characters per minute / 60 = 15 characters per second. // We limit the duration to a range of 1-10 seconds. var charCount = text.Length; - var displayDuration = Math.Min(10, (double)charCount / 15.0 + 1.0); - MessageHideTimer = NSTimer.CreateScheduledTimer(displayDuration, false, (obj) => - { - ShowHideMessage(true, true); + var displayDuration = Math.Min (10, (double) charCount / 15.0 + 1.0); + MessageHideTimer = NSTimer.CreateScheduledTimer (displayDuration, false, (obj) => { + ShowHideMessage (true, true); }); } }); } - public void ScheduleMessage(string text, double displayDuration, MessageType messageType) + public void ScheduleMessage (string text, double displayDuration, MessageType messageType) { // Can messages be scheduled? - if (SchedulingMessageBlocked) - { + if (SchedulingMessageBlocked) { return; } // Get timer based on the message type - switch (messageType) - { - case MessageType.ContentPlacement: - ScheduleMessageTimer = ContentPlacementMessageTimer; - break; - case MessageType.FocusSquare: - ScheduleMessageTimer = FocusSquareMessageTimer; - break; - case MessageType.PlaneEstimation: - ScheduleMessageTimer = PlaneEstimationMessageTimer; - break; - case MessageType.TrackingStateEscalation: - ScheduleMessageTimer = TrackingStateFeedbackMessageTimer; - break; + switch (messageType) { + case MessageType.ContentPlacement: + ScheduleMessageTimer = ContentPlacementMessageTimer; + break; + case MessageType.FocusSquare: + ScheduleMessageTimer = FocusSquareMessageTimer; + break; + case MessageType.PlaneEstimation: + ScheduleMessageTimer = PlaneEstimationMessageTimer; + break; + case MessageType.TrackingStateEscalation: + ScheduleMessageTimer = TrackingStateFeedbackMessageTimer; + break; } // Stop any running timers - ScheduleMessageTimer?.Invalidate(); + ScheduleMessageTimer?.Invalidate (); // Create a new timer - ScheduleMessageTimer = NSTimer.CreateScheduledTimer(displayDuration, false, (obj) => - { - ShowMessage(text, true); - ScheduleMessageTimer?.Invalidate(); + ScheduleMessageTimer = NSTimer.CreateScheduledTimer (displayDuration, false, (obj) => { + ShowMessage (text, true); + ScheduleMessageTimer?.Invalidate (); }); // Save timer based on the message type - switch (messageType) - { - case MessageType.ContentPlacement: - ContentPlacementMessageTimer = ScheduleMessageTimer; - break; - case MessageType.FocusSquare: - FocusSquareMessageTimer = ScheduleMessageTimer; - break; - case MessageType.PlaneEstimation: - PlaneEstimationMessageTimer = ScheduleMessageTimer; - break; - case MessageType.TrackingStateEscalation: - TrackingStateFeedbackMessageTimer = ScheduleMessageTimer; - break; + switch (messageType) { + case MessageType.ContentPlacement: + ContentPlacementMessageTimer = ScheduleMessageTimer; + break; + case MessageType.FocusSquare: + FocusSquareMessageTimer = ScheduleMessageTimer; + break; + case MessageType.PlaneEstimation: + PlaneEstimationMessageTimer = ScheduleMessageTimer; + break; + case MessageType.TrackingStateEscalation: + TrackingStateFeedbackMessageTimer = ScheduleMessageTimer; + break; } } - public void ShowTrackingQualityInfo(ARTrackingState trackingState, ARTrackingStateReason reason, bool autoHide) + public void ShowTrackingQualityInfo (ARTrackingState trackingState, ARTrackingStateReason reason, bool autoHide) { var title = ""; var message = ""; - switch (trackingState) - { - case ARTrackingState.NotAvailable: - title = "Tracking Not Available"; + switch (trackingState) { + case ARTrackingState.NotAvailable: + title = "Tracking Not Available"; + break; + case ARTrackingState.Normal: + title = "Tracking Normal"; + break; + case ARTrackingState.Limited: + title = "Tracking Limited"; + switch (reason) { + case ARTrackingStateReason.ExcessiveMotion: + message = "because of excessive motion"; break; - case ARTrackingState.Normal: - title = "Tracking Normal"; + case ARTrackingStateReason.Initializing: + message = "because tracking is initializing"; break; - case ARTrackingState.Limited: - title = "Tracking Limited"; - switch (reason) - { - case ARTrackingStateReason.ExcessiveMotion: - message = "because of excessive motion"; - break; - case ARTrackingStateReason.Initializing: - message = "because tracking is initializing"; - break; - case ARTrackingStateReason.InsufficientFeatures: - message = "because of insufficient features in the environment"; - break; - case ARTrackingStateReason.None: - message = "because of an unknown reason"; - break; - } + case ARTrackingStateReason.InsufficientFeatures: + message = "because of insufficient features in the environment"; break; + case ARTrackingStateReason.None: + message = "because of an unknown reason"; + break; + } + break; } - ShowMessage($"{title} {message}", autoHide); + ShowMessage ($"{title} {message}", autoHide); } - public void EscalateFeedback(ARTrackingState trackingState, ARTrackingStateReason reason, double displayDuration) + public void EscalateFeedback (ARTrackingState trackingState, ARTrackingStateReason reason, double displayDuration) { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { var title = "Tracking status: Limited."; var message = "Tracking status has been limited for an extended time. "; // Stop any running timer - TrackingStateFeedbackMessageTimer?.Invalidate(); + TrackingStateFeedbackMessageTimer?.Invalidate (); // Create new timer - TrackingStateFeedbackMessageTimer = NSTimer.CreateScheduledTimer(displayDuration, false, (timer) => - { - TrackingStateFeedbackMessageTimer?.Invalidate(); + TrackingStateFeedbackMessageTimer = NSTimer.CreateScheduledTimer (displayDuration, false, (timer) => { + TrackingStateFeedbackMessageTimer?.Invalidate (); SchedulingMessageBlocked = true; // Take action based on th tracking state - switch (trackingState) - { - case ARTrackingState.NotAvailable: - title = "Tracking Not Available"; + switch (trackingState) { + case ARTrackingState.NotAvailable: + title = "Tracking Not Available"; + break; + case ARTrackingState.Normal: + title = "Tracking Normal"; + break; + case ARTrackingState.Limited: + title = "Tracking Limited"; + switch (reason) { + case ARTrackingStateReason.ExcessiveMotion: + message = "because of excessive motion"; + break; + case ARTrackingStateReason.Initializing: + message = "because tracking is initializing"; break; - case ARTrackingState.Normal: - title = "Tracking Normal"; + case ARTrackingStateReason.InsufficientFeatures: + message = "because of insufficient features in the environment"; break; - case ARTrackingState.Limited: - title = "Tracking Limited"; - switch (reason) - { - case ARTrackingStateReason.ExcessiveMotion: - message = "because of excessive motion"; - break; - case ARTrackingStateReason.Initializing: - message = "because tracking is initializing"; - break; - case ARTrackingStateReason.InsufficientFeatures: - message = "because of insufficient features in the environment"; - break; - case ARTrackingStateReason.None: - message = "because of an unknown reason"; - break; - } + case ARTrackingStateReason.None: + message = "because of an unknown reason"; break; + } + break; } // Create and display an Alert Message - var restartAction = UIAlertAction.Create("Reset", UIAlertActionStyle.Destructive, (obj) => - { - Controller.RestartExperience(this); + var restartAction = UIAlertAction.Create ("Reset", UIAlertActionStyle.Destructive, (obj) => { + Controller.RestartExperience (this); SchedulingMessageBlocked = false; }); - var okAction = UIAlertAction.Create("OK", UIAlertActionStyle.Default, (obj) => - { + var okAction = UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (obj) => { SchedulingMessageBlocked = false; }); - ShowAlert(title, message, new UIAlertAction[] { restartAction, okAction }); + ShowAlert (title, message, new UIAlertAction [] { restartAction, okAction }); }); }); } - public void CancelScheduledMessage(MessageType messageType) + public void CancelScheduledMessage (MessageType messageType) { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { // Get timer based on the message type - switch (messageType) - { - case MessageType.ContentPlacement: - ScheduleMessageTimer = ContentPlacementMessageTimer; - break; - case MessageType.FocusSquare: - ScheduleMessageTimer = FocusSquareMessageTimer; - break; - case MessageType.PlaneEstimation: - ScheduleMessageTimer = PlaneEstimationMessageTimer; - break; - case MessageType.TrackingStateEscalation: - ScheduleMessageTimer = TrackingStateFeedbackMessageTimer; - break; + switch (messageType) { + case MessageType.ContentPlacement: + ScheduleMessageTimer = ContentPlacementMessageTimer; + break; + case MessageType.FocusSquare: + ScheduleMessageTimer = FocusSquareMessageTimer; + break; + case MessageType.PlaneEstimation: + ScheduleMessageTimer = PlaneEstimationMessageTimer; + break; + case MessageType.TrackingStateEscalation: + ScheduleMessageTimer = TrackingStateFeedbackMessageTimer; + break; } // Stop any running timers - ScheduleMessageTimer?.Invalidate(); + ScheduleMessageTimer?.Invalidate (); ScheduleMessageTimer = null; }); } - public void CancelAllScheduledMessages() + public void CancelAllScheduledMessages () { - InvokeOnMainThread(() => - { - CancelScheduledMessage(MessageType.ContentPlacement); - CancelScheduledMessage(MessageType.FocusSquare); - CancelScheduledMessage(MessageType.PlaneEstimation); - CancelScheduledMessage(MessageType.TrackingStateEscalation); + InvokeOnMainThread (() => { + CancelScheduledMessage (MessageType.ContentPlacement); + CancelScheduledMessage (MessageType.FocusSquare); + CancelScheduledMessage (MessageType.PlaneEstimation); + CancelScheduledMessage (MessageType.TrackingStateEscalation); }); } - public void ShowAlert(string title, string message, UIAlertAction[] actions = null) + public void ShowAlert (string title, string message, UIAlertAction [] actions = null) { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { // Create an alert controller - AlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); + AlertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); // Any actions to add? - if (actions != null && actions.Length > 0) - { + if (actions != null && actions.Length > 0) { // Add actions to controller - foreach (UIAlertAction action in actions) - { - AlertController.AddAction(action); + foreach (UIAlertAction action in actions) { + AlertController.AddAction (action); } - } - else - { + } else { // Add default button - AlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, (obj) => { })); + AlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (obj) => { })); } // Display the alert - Controller.PresentViewController(AlertController, true, null); + Controller.PresentViewController (AlertController, true, null); }); } - public void DismissPresentedAlert() + public void DismissPresentedAlert () { - InvokeOnMainThread(() => - { - AlertController?.DismissViewController(true, null); + InvokeOnMainThread (() => { + AlertController?.DismissViewController (true, null); }); } - public void BlurBackground() + public void BlurBackground () { - InvokeOnMainThread(() => - { - var blurEffect = UIBlurEffect.FromStyle(UIBlurEffectStyle.Light); - var blurEffectView = new UIVisualEffectView(blurEffect) - { + InvokeOnMainThread (() => { + var blurEffect = UIBlurEffect.FromStyle (UIBlurEffectStyle.Light); + var blurEffectView = new UIVisualEffectView (blurEffect) { Frame = Controller.View.Bounds, AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight, Tag = BlurEffectViewTag }; - Controller.View.AddSubview(blurEffectView); + Controller.View.AddSubview (blurEffectView); }); } - public void UnblurBackground() + public void UnblurBackground () { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { // Scan all views - foreach (UIView view in Controller.View.Subviews) - { + foreach (UIView view in Controller.View.Subviews) { // Is this the view a blur effect view? - if (view is UIVisualEffectView && view.Tag == BlurEffectViewTag) - { + if (view is UIVisualEffectView && view.Tag == BlurEffectViewTag) { // Yes, remove it - view.RemoveFromSuperview(); + view.RemoveFromSuperview (); } } }); } - private void UpdateMessagePanelVisibility() + private void UpdateMessagePanelVisibility () { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { // Is any message visible? var anyMessageShown = !Controller.MessageLabel.Hidden; @@ -325,22 +293,17 @@ private void UpdateMessagePanelVisibility() }); } - private void ShowHideMessage(bool hide, bool animated) + private void ShowHideMessage (bool hide, bool animated) { - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { // Animated? - if (animated) - { + if (animated) { // Fade out message - UIView.Animate(0.2f, 0, UIViewAnimationOptions.AllowUserInteraction, () => - { + UIView.Animate (0.2f, 0, UIViewAnimationOptions.AllowUserInteraction, () => { Controller.MessageLabel.Hidden = hide; - UpdateMessagePanelVisibility(); + UpdateMessagePanelVisibility (); }, null); - } - else - { + } else { // Instantly hide message Controller.MessageLabel.Hidden = hide; } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/Utilities.cs b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/Utilities.cs index e65f43c9c..10f575e04 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/Utilities.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/Utilities/Utilities.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -8,13 +8,12 @@ using System.Collections; using System.Linq; -namespace PlacingObjects -{ - public static class Utilities - { - public static SCNVector3? RayIntersectionWithHorizontalPlane(SCNVector3 rayOrigin, SCNVector3 direction, float planeY) { +namespace PlacingObjects { + public static class Utilities { + public static SCNVector3? RayIntersectionWithHorizontalPlane (SCNVector3 rayOrigin, SCNVector3 direction, float planeY) + { // Normalize direction - direction = direction.Normalized(); + direction = direction.Normalized (); // Special case handling: Check if the ray is horizontal as well. if (direction.Y == 0) { @@ -37,91 +36,95 @@ public static class Utilities var dist = (planeY - rayOrigin.Y) / direction.Y; // Do not return intersections behind the ray's origin. - if (dist <0) { + if (dist < 0) { return null; } // Return the intersection point. - return rayOrigin.Add(direction * dist); + return rayOrigin.Add (direction * dist); } - public static SCNNode CreateAxesNode(float quiverLength, float quiverThickness) { + public static SCNNode CreateAxesNode (float quiverLength, float quiverThickness) + { quiverThickness = (quiverLength / 50f) * quiverThickness; var chamferRadius = quiverThickness / 2f; - var xQuiverBox = SCNBox.Create(quiverLength, quiverThickness, quiverThickness, chamferRadius); - xQuiverBox.InsertMaterial(SCNMaterialExtensions.CreateMaterial(UIColor.Red, false), 0); - var xQuiverNode = SCNNode.FromGeometry(xQuiverBox); - xQuiverNode.Position = new SCNVector3((quiverLength / 2f), 0, 0); + var xQuiverBox = SCNBox.Create (quiverLength, quiverThickness, quiverThickness, chamferRadius); + xQuiverBox.InsertMaterial (SCNMaterialExtensions.CreateMaterial (UIColor.Red, false), 0); + var xQuiverNode = SCNNode.FromGeometry (xQuiverBox); + xQuiverNode.Position = new SCNVector3 ((quiverLength / 2f), 0, 0); - var yQuiverBox = SCNBox.Create(quiverThickness, quiverLength, quiverThickness, chamferRadius); - yQuiverBox.InsertMaterial(SCNMaterialExtensions.CreateMaterial(UIColor.Green, false), 0); - var yQuiverNode = SCNNode.FromGeometry(yQuiverBox); - yQuiverNode.Position = new SCNVector3(0, (quiverLength / 2f), 0); + var yQuiverBox = SCNBox.Create (quiverThickness, quiverLength, quiverThickness, chamferRadius); + yQuiverBox.InsertMaterial (SCNMaterialExtensions.CreateMaterial (UIColor.Green, false), 0); + var yQuiverNode = SCNNode.FromGeometry (yQuiverBox); + yQuiverNode.Position = new SCNVector3 (0, (quiverLength / 2f), 0); - var zQuiverBox = SCNBox.Create(quiverThickness, quiverThickness, quiverLength, chamferRadius); - zQuiverBox.InsertMaterial(SCNMaterialExtensions.CreateMaterial(UIColor.Blue, false), 0); - var zQuiverNode = SCNNode.FromGeometry(zQuiverBox); - zQuiverNode.Position = new SCNVector3(0, 0, (quiverLength / 2f)); + var zQuiverBox = SCNBox.Create (quiverThickness, quiverThickness, quiverLength, chamferRadius); + zQuiverBox.InsertMaterial (SCNMaterialExtensions.CreateMaterial (UIColor.Blue, false), 0); + var zQuiverNode = SCNNode.FromGeometry (zQuiverBox); + zQuiverNode.Position = new SCNVector3 (0, 0, (quiverLength / 2f)); // Assemble node - var quiverNode = new SCNNode(){ + var quiverNode = new SCNNode () { Name = "Axes" }; - quiverNode.AddChildNode(xQuiverNode); - quiverNode.AddChildNode(yQuiverNode); - quiverNode.AddChildNode(zQuiverNode); + quiverNode.AddChildNode (xQuiverNode); + quiverNode.AddChildNode (yQuiverNode); + quiverNode.AddChildNode (zQuiverNode); // Return results return quiverNode; } - public static SCNNode CreateCrossNode(float size, string style, bool horizontal = true, float opacity = 1f){ + public static SCNNode CreateCrossNode (float size, string style, bool horizontal = true, float opacity = 1f) + { // Create a size x size m plane and put a grid texture onto it. var planeDimention = size; - var image = UIImage.FromBundle(style); + var image = UIImage.FromBundle (style); - var planeNode = SCNNode.FromGeometry(CreateSquarePlane(planeDimention, image)); - var material = planeNode.Geometry.Materials[0]; + var planeNode = SCNNode.FromGeometry (CreateSquarePlane (planeDimention, image)); + var material = planeNode.Geometry.Materials [0]; material.Ambient.Contents = UIColor.Black; material.LightingModelName = SCNLightingModel.Constant; if (horizontal) { - planeNode.EulerAngles = new SCNVector3((float)Math.PI / 2f, 0, (float)Math.PI); + planeNode.EulerAngles = new SCNVector3 ((float) Math.PI / 2f, 0, (float) Math.PI); } else { - planeNode.Constraints = new SCNConstraint[] { new SCNBillboardConstraint()}; + planeNode.Constraints = new SCNConstraint [] { new SCNBillboardConstraint () }; } // Assemble cross - var cross = new SCNNode() { + var cross = new SCNNode () { Name = "Cross" }; - cross.AddChildNode(planeNode); + cross.AddChildNode (planeNode); cross.Opacity = opacity; // Return results return cross; } - public static SCNPlane CreateSquarePlane(float size, NSObject contents) { - var plane = SCNPlane.Create(size, size); - plane.InsertMaterial(SCNMaterialExtensions.CreateMaterial(contents), 0); + public static SCNPlane CreateSquarePlane (float size, NSObject contents) + { + var plane = SCNPlane.Create (size, size); + plane.InsertMaterial (SCNMaterialExtensions.CreateMaterial (contents), 0); return plane; } - public static SCNPlane CreatePlane(CGSize size, NSObject contents) + public static SCNPlane CreatePlane (CGSize size, NSObject contents) { - var plane = SCNPlane.Create(size.Width, size.Height); - plane.InsertMaterial(SCNMaterialExtensions.CreateMaterial(contents), 0); + var plane = SCNPlane.Create (size.Width, size.Height); + plane.InsertMaterial (SCNMaterialExtensions.CreateMaterial (contents), 0); return plane; } - public static SCNVector3 AverageVector3List(SCNVector3[] vectors) { - var average = new SCNVector3(0, 0, 0); + public static SCNVector3 AverageVector3List (SCNVector3 [] vectors) + { + var average = new SCNVector3 (0, 0, 0); // Process all vectors - foreach(SCNVector3 vector in vectors) { + foreach (SCNVector3 vector in vectors) { average.X += vector.X; average.Y += vector.Y; average.Z += vector.Z; diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ARSceneViewDelegate.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ARSceneViewDelegate.cs index bb87132ef..790a59a25 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ARSceneViewDelegate.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ARSceneViewDelegate.cs @@ -1,112 +1,100 @@ -using System; +using System; using ARKit; using CoreFoundation; using Foundation; using SceneKit; -namespace PlacingObjects -{ - public partial class ViewController : IARSCNViewDelegate - { - [Export("renderer:updateAtTime:")] - public void RendererUpdateAtTime(ISCNSceneRenderer renderer, double updateAtTime) +namespace PlacingObjects { + public partial class ViewController : IARSCNViewDelegate { + [Export ("renderer:updateAtTime:")] + public void RendererUpdateAtTime (ISCNSceneRenderer renderer, double updateAtTime) { - if (Session?.CurrentFrame == null) - { + if (Session?.CurrentFrame == null) { return; } // Vital for memory: Single location to set current frame! (Note: Assignment disposes existing frame -- see `set` ViewController.CurrentFrame = Session.CurrentFrame; - UpdateFocusSquare(); + UpdateFocusSquare (); // If light estimation is enabled, update the intensity of the model's lights and the environment map var lightEstimate = ViewController.CurrentFrame.LightEstimate; - if (lightEstimate != null) - { - SceneView.Scene.EnableEnvironmentMapWithIntensity((float)(lightEstimate.AmbientIntensity / 40f), serialQueue); - } - else - { - SceneView.Scene.EnableEnvironmentMapWithIntensity(40f, serialQueue); + if (lightEstimate != null) { + SceneView.Scene.EnableEnvironmentMapWithIntensity ((float) (lightEstimate.AmbientIntensity / 40f), serialQueue); + } else { + SceneView.Scene.EnableEnvironmentMapWithIntensity (40f, serialQueue); } } - [Export("renderer:didAddNode:forAnchor:")] - public void DidAddNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + [Export ("renderer:didAddNode:forAnchor:")] + public void DidAddNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { var planeAnchor = anchor as ARPlaneAnchor; - if (planeAnchor != null) - { - AddPlane(node, planeAnchor); - virtualObjectManager.CheckIfObjectShouldMoveOntoPlane(planeAnchor, node); + if (planeAnchor != null) { + AddPlane (node, planeAnchor); + virtualObjectManager.CheckIfObjectShouldMoveOntoPlane (planeAnchor, node); } } - [Export("renderer:didUpdateNode:forAnchor:")] - public void DidUpdateNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + [Export ("renderer:didUpdateNode:forAnchor:")] + public void DidUpdateNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { var planeAnchor = anchor as ARPlaneAnchor; - if (planeAnchor != null) - { - UpdatePlane(planeAnchor); - virtualObjectManager.CheckIfObjectShouldMoveOntoPlane(planeAnchor, node); + if (planeAnchor != null) { + UpdatePlane (planeAnchor); + virtualObjectManager.CheckIfObjectShouldMoveOntoPlane (planeAnchor, node); } } - [Export("renderer:didRemoveNode:forAnchor:")] - public void DidRemoveNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + [Export ("renderer:didRemoveNode:forAnchor:")] + public void DidRemoveNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { var planeAnchor = anchor as ARPlaneAnchor; - if (planeAnchor != null) - { - serialQueue.DispatchAsync(() => RemovePlane(planeAnchor)); + if (planeAnchor != null) { + serialQueue.DispatchAsync (() => RemovePlane (planeAnchor)); } } - public void SessionDelegate_CameraDidChangeTrackingState(ARSession session, ARCamera camera) + public void SessionDelegate_CameraDidChangeTrackingState (ARSession session, ARCamera camera) { - UserFeedback.ShowTrackingQualityInfo(camera.TrackingState, camera.TrackingStateReason, true); + UserFeedback.ShowTrackingQualityInfo (camera.TrackingState, camera.TrackingStateReason, true); - switch (camera.TrackingState) - { - case ARTrackingState.NotAvailable: - case ARTrackingState.Limited: - UserFeedback.EscalateFeedback(camera.TrackingState, camera.TrackingStateReason, 3); - break; - case ARTrackingState.Normal: - UserFeedback.CancelScheduledMessage(MessageType.TrackingStateEscalation); - break; + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + case ARTrackingState.Limited: + UserFeedback.EscalateFeedback (camera.TrackingState, camera.TrackingStateReason, 3); + break; + case ARTrackingState.Normal: + UserFeedback.CancelScheduledMessage (MessageType.TrackingStateEscalation); + break; } } - public void SessionDelegate_DidFail(ARSession session, NSError error) + public void SessionDelegate_DidFail (ARSession session, NSError error) { var sessionErrorMsg = $"{error.LocalizedDescription} {error.LocalizedFailureReason} "; var recoveryOptions = error.LocalizedRecoveryOptions; - if (recoveryOptions != null) - { - foreach (string option in recoveryOptions) - { + if (recoveryOptions != null) { + foreach (string option in recoveryOptions) { sessionErrorMsg += $"{option}."; } } - DisplayErrorMessage("We're sorry!", sessionErrorMsg, false); + DisplayErrorMessage ("We're sorry!", sessionErrorMsg, false); } - internal void SessionDelegate_WasInterrupted(ARSession session) + internal void SessionDelegate_WasInterrupted (ARSession session) { - UserFeedback.BlurBackground(); - UserFeedback.ShowAlert("Session Interrupted", "The session will be reset after the interruption ends."); + UserFeedback.BlurBackground (); + UserFeedback.ShowAlert ("Session Interrupted", "The session will be reset after the interruption ends."); } - internal void SessionDelegate_InterruptionEnded(ARSession session) + internal void SessionDelegate_InterruptionEnded (ARSession session) { - UserFeedback.UnblurBackground(); - Session.Run(StandardConfiguration(), ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - RestartExperience(this); - UserFeedback.ShowMessage("RESETTING SESSION"); + UserFeedback.UnblurBackground (); + Session.Run (StandardConfiguration (), ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + RestartExperience (this); + UserFeedback.ShowMessage ("RESETTING SESSION"); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+Actions.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+Actions.cs index cbfc0c80e..adb7ce3e5 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+Actions.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+Actions.cs @@ -1,87 +1,79 @@ -using System; +using System; using CoreFoundation; using Foundation; using UIKit; -namespace PlacingObjects -{ - public partial class ViewController : IUIPopoverPresentationControllerDelegate - { - static class SegueIdentifier - { - public static readonly NSString ShowSettings = new NSString("showSettings"); - public static readonly NSString ShowObjects = new NSString("showObjects"); +namespace PlacingObjects { + public partial class ViewController : IUIPopoverPresentationControllerDelegate { + static class SegueIdentifier { + public static readonly NSString ShowSettings = new NSString ("showSettings"); + public static readonly NSString ShowObjects = new NSString ("showObjects"); } - [Export("adaptivePresentationStyleForPresentationController:")] - public UIModalPresentationStyle GetAdaptivePresentationStyle(UIPresentationController forPresentationController) + [Export ("adaptivePresentationStyleForPresentationController:")] + public UIModalPresentationStyle GetAdaptivePresentationStyle (UIPresentationController forPresentationController) { return UIModalPresentationStyle.None; } - [Export("adaptivePresentationStyleForPresentationController:traitCollection:")] - public UIModalPresentationStyle GetAdaptivePresentationStyle(UIPresentationController controller, UITraitCollection traitCollection) + [Export ("adaptivePresentationStyleForPresentationController:traitCollection:")] + public UIModalPresentationStyle GetAdaptivePresentationStyle (UIPresentationController controller, UITraitCollection traitCollection) { return UIModalPresentationStyle.None; } - [Action("RestartExperience:")] - public void RestartExperience(NSObject sender) + [Action ("RestartExperience:")] + public void RestartExperience (NSObject sender) { - if (!RestartExperienceButton.Enabled || IsLoadingObject) - { + if (!RestartExperienceButton.Enabled || IsLoadingObject) { return; } RestartExperienceButton.Enabled = false; - UserFeedback.CancelAllScheduledMessages(); - UserFeedback.DismissPresentedAlert(); - UserFeedback.ShowMessage("STARTING A NEW SESSION"); + UserFeedback.CancelAllScheduledMessages (); + UserFeedback.DismissPresentedAlert (); + UserFeedback.ShowMessage ("STARTING A NEW SESSION"); - virtualObjectManager.RemoveAllVirtualObjects(); - AddObjectButton.SetImage(UIImage.FromBundle("add"), UIControlState.Normal); - AddObjectButton.SetImage(UIImage.FromBundle("addPressed"), UIControlState.Highlighted); - if (FocusSquare != null) - { + virtualObjectManager.RemoveAllVirtualObjects (); + AddObjectButton.SetImage (UIImage.FromBundle ("add"), UIControlState.Normal); + AddObjectButton.SetImage (UIImage.FromBundle ("addPressed"), UIControlState.Highlighted); + if (FocusSquare != null) { FocusSquare.Hidden = true; } - ResetTracking(); + ResetTracking (); - RestartExperienceButton.SetImage(UIImage.FromBundle("restart"), UIControlState.Normal); + RestartExperienceButton.SetImage (UIImage.FromBundle ("restart"), UIControlState.Normal); // Disable Restart button for a second in order to give the session enough time to restart. - var when = new DispatchTime(DispatchTime.Now, new TimeSpan(0, 0, 1)); - DispatchQueue.MainQueue.DispatchAfter(when, () => SetupFocusSquare()); + var when = new DispatchTime (DispatchTime.Now, new TimeSpan (0, 0, 1)); + DispatchQueue.MainQueue.DispatchAfter (when, () => SetupFocusSquare ()); } - [Action("chooseObject:")] - public void ChooseObject(UIButton button) + [Action ("chooseObject:")] + public void ChooseObject (UIButton button) { // Abort if we are about to load another object to avoid concurrent modifications of the scene. - if (IsLoadingObject) - { + if (IsLoadingObject) { return; } - UserFeedback.CancelScheduledMessage(MessageType.ContentPlacement); - PerformSegue(SegueIdentifier.ShowObjects, button); + UserFeedback.CancelScheduledMessage (MessageType.ContentPlacement); + PerformSegue (SegueIdentifier.ShowObjects, button); } - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { // All popover segues should be popovers even on iPhone. var popoverController = segue.DestinationViewController?.PopoverPresentationController; - if (popoverController == null) - { + if (popoverController == null) { return; } - var button = (UIButton)sender; + var button = (UIButton) sender; popoverController.Delegate = this; popoverController.SourceRect = button.Bounds; var identifier = segue.Identifier; - if (identifier == SegueIdentifier.ShowObjects) - { + if (identifier == SegueIdentifier.ShowObjects) { var objectsViewController = segue.DestinationViewController as VirtualObjectSelectionViewController; objectsViewController.Delegate = this; } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ObjectSelection.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ObjectSelection.cs index c402b2091..e06c69fde 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ObjectSelection.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController+ObjectSelection.cs @@ -1,62 +1,58 @@ -using System; +using System; using CoreFoundation; using CoreGraphics; using Foundation; using SceneKit; using UIKit; -namespace PlacingObjects -{ - public partial class ViewController : IVirtualObjectManagerDelegate, IVirtualObjectSelectionViewControllerDelegate - { - public void CouldNotPlace(VirtualObjectManager manager, VirtualObject virtualObject) +namespace PlacingObjects { + public partial class ViewController : IVirtualObjectManagerDelegate, IVirtualObjectSelectionViewControllerDelegate { + public void CouldNotPlace (VirtualObjectManager manager, VirtualObject virtualObject) { - UserFeedback.ShowMessage("Cannot place object\nTry moving left or right."); + UserFeedback.ShowMessage ("Cannot place object\nTry moving left or right."); } - public void DidLoad(VirtualObjectManager manager, VirtualObject virtualObject) + public void DidLoad (VirtualObjectManager manager, VirtualObject virtualObject) { IsLoadingObject = false; //Remove progress indicator - Spinner.RemoveFromSuperview(); - AddObjectButton.SetImage(UIImage.FromBundle("add"), UIControlState.Normal); - AddObjectButton.SetImage(UIImage.FromBundle("addPressed"), UIControlState.Highlighted); + Spinner.RemoveFromSuperview (); + AddObjectButton.SetImage (UIImage.FromBundle ("add"), UIControlState.Normal); + AddObjectButton.SetImage (UIImage.FromBundle ("addPressed"), UIControlState.Highlighted); } - public void WillLoad(VirtualObjectManager manager, VirtualObject virtualObject) + public void WillLoad (VirtualObjectManager manager, VirtualObject virtualObject) { // Show progress indicator - Spinner = new UIActivityIndicatorView(); + Spinner = new UIActivityIndicatorView (); Spinner.Center = AddObjectButton.Center; - Spinner.Bounds = new CGRect(0, 0, AddObjectButton.Bounds.Width - 5, AddObjectButton.Bounds.Height - 5); - AddObjectButton.SetImage(UIImage.FromBundle("buttonring"), UIControlState.Normal); - SceneView.AddSubview(Spinner); - Spinner.StartAnimating(); + Spinner.Bounds = new CGRect (0, 0, AddObjectButton.Bounds.Width - 5, AddObjectButton.Bounds.Height - 5); + AddObjectButton.SetImage (UIImage.FromBundle ("buttonring"), UIControlState.Normal); + SceneView.AddSubview (Spinner); + Spinner.StartAnimating (); IsLoadingObject = true; } - public void DidSelectObjectAt(int index) + public void DidSelectObjectAt (int index) { - if (Session == null || ViewController.CurrentFrame == null) - { + if (Session == null || ViewController.CurrentFrame == null) { return; } var cameraTransform = ViewController.CurrentFrame.Camera.Transform; - var definition = VirtualObjectManager.AvailableObjects[index]; - var vo = new VirtualObject(definition); - var position = FocusSquare != null ? FocusSquare.LastPosition : new SCNVector3(0, 0, -1.0f); - virtualObjectManager.LoadVirtualObject(vo, position, cameraTransform); - if (vo.ParentNode == null) - { - SceneView.Scene.RootNode.AddChildNode(vo); + var definition = VirtualObjectManager.AvailableObjects [index]; + var vo = new VirtualObject (definition); + var position = FocusSquare != null ? FocusSquare.LastPosition : new SCNVector3 (0, 0, -1.0f); + virtualObjectManager.LoadVirtualObject (vo, position, cameraTransform); + if (vo.ParentNode == null) { + SceneView.Scene.RootNode.AddChildNode (vo); } } - public void DidDeselectObjectAt(int index) + public void DidDeselectObjectAt (int index) { - virtualObjectManager.RemoveVirtualObject(index); + virtualObjectManager.RemoveVirtualObject (index); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController.cs b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController.cs index 062a3962f..3380190c8 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/ViewController.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -9,51 +9,48 @@ using CoreFoundation; using Photos; -namespace PlacingObjects -{ +namespace PlacingObjects { - public class SessionDelegateCallbackProxy : ARSessionDelegate - { + public class SessionDelegateCallbackProxy : ARSessionDelegate { ViewController owner; - public SessionDelegateCallbackProxy(ViewController owner) + public SessionDelegateCallbackProxy (ViewController owner) { this.owner = owner; } - public override void CameraDidChangeTrackingState(ARSession session, ARCamera camera) + public override void CameraDidChangeTrackingState (ARSession session, ARCamera camera) { - owner.SessionDelegate_CameraDidChangeTrackingState(session, camera); + owner.SessionDelegate_CameraDidChangeTrackingState (session, camera); } - public override void DidFail(ARSession session, NSError error) + public override void DidFail (ARSession session, NSError error) { - owner.SessionDelegate_DidFail(session, error); + owner.SessionDelegate_DidFail (session, error); } - public override void WasInterrupted(ARSession session) + public override void WasInterrupted (ARSession session) { - owner.SessionDelegate_WasInterrupted(session); + owner.SessionDelegate_WasInterrupted (session); } - public override void InterruptionEnded(ARSession session) + public override void InterruptionEnded (ARSession session) { - owner.SessionDelegate_InterruptionEnded(session); + owner.SessionDelegate_InterruptionEnded (session); } } - public partial class ViewController : UIViewController, ISCNSceneRendererDelegate, IARSessionObserver, IVirtualObjectSelectionViewControllerDelegate - { + public partial class ViewController : UIViewController, ISCNSceneRendererDelegate, IARSessionObserver, IVirtualObjectSelectionViewControllerDelegate { private bool isLoadingObject = false; public CGPoint? ScreenCenter { get; protected set; } public TextManager UserFeedback { get; set; } public bool DragOnInfinitePlanesEnabled { get; set; } = false; - public Dictionary<ARPlaneAnchor, Plane> Planes { get; set; } = new Dictionary<ARPlaneAnchor, Plane>(); + public Dictionary<ARPlaneAnchor, Plane> Planes { get; set; } = new Dictionary<ARPlaneAnchor, Plane> (); - public ARSession Session { get; set; } = new ARSession(); - public ARWorldTrackingConfiguration worldTrackingConfig { get; set; } = new ARWorldTrackingConfiguration(); + public ARSession Session { get; set; } = new ARSession (); + public ARWorldTrackingConfiguration worldTrackingConfig { get; set; } = new ARWorldTrackingConfiguration (); public VirtualObject DisplayedObject { get; set; } public FocusSquare FocusSquare { get; set; } protected UIActivityIndicatorView Spinner { get; set; } @@ -62,26 +59,21 @@ public partial class ViewController : UIViewController, ISCNSceneRendererDelegat protected DispatchQueue serialQueue { get; set; } static private ARFrame currentFrame; - static public ARFrame CurrentFrame - { + static public ARFrame CurrentFrame { get => currentFrame; - private set - { - if (currentFrame != null) - { - currentFrame.Dispose(); + private set { + if (currentFrame != null) { + currentFrame.Dispose (); } currentFrame = value; } } - public bool IsLoadingObject - { + public bool IsLoadingObject { get { return isLoadingObject; } - set - { + set { isLoadingObject = value; SettingsButton.Enabled = !isLoadingObject; @@ -90,193 +82,176 @@ public bool IsLoadingObject } } - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - AppSettings.RegisterDefaults(); - SetupUIControls(); - SetupScene(); + AppSettings.RegisterDefaults (); + SetupUIControls (); + SetupScene (); } - public override void ViewDidAppear(bool animated) + public override void ViewDidAppear (bool animated) { - base.ViewDidAppear(animated); + base.ViewDidAppear (animated); // Prevent the screen from being dimmed after awhile UIApplication.SharedApplication.IdleTimerDisabled = true; - if (ARWorldTrackingConfiguration.IsSupported) - { + if (ARWorldTrackingConfiguration.IsSupported) { // Start the ARSession - ResetTracking(); - } - else - { + ResetTracking (); + } else { // This device does not support 6DOF world tracking. var sessionErrorMsg = "This app requires world tracking. World tracking is only available on iOS devices with A9 processor or newer. " + "Please quit the application."; - DisplayErrorMessage("Unsupported platform", sessionErrorMsg, false); + DisplayErrorMessage ("Unsupported platform", sessionErrorMsg, false); } } - public override void ViewWillDisappear(bool animated) + public override void ViewWillDisappear (bool animated) { - base.ViewWillDisappear(animated); - Session.Pause(); + base.ViewWillDisappear (animated); + Session.Pause (); } - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - virtualObjectManager.ReactToTouchesBegan(touches, evt, SceneView); + virtualObjectManager.ReactToTouchesBegan (touches, evt, SceneView); } - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - virtualObjectManager.ReactToTouchesMoved(touches, evt); + virtualObjectManager.ReactToTouchesMoved (touches, evt); } - public override void TouchesEnded(NSSet touches, UIEvent evt) + public override void TouchesEnded (NSSet touches, UIEvent evt) { - if (virtualObjectManager.VirtualObjects.Count == 0) - { - ChooseObject(AddObjectButton); + if (virtualObjectManager.VirtualObjects.Count == 0) { + ChooseObject (AddObjectButton); } - virtualObjectManager.ReactToTouchesEnded(touches, evt); + virtualObjectManager.ReactToTouchesEnded (touches, evt); } - public override void TouchesCancelled(NSSet touches, UIEvent evt) + public override void TouchesCancelled (NSSet touches, UIEvent evt) { - virtualObjectManager.ReactToTouchesCancelled(touches, evt); + virtualObjectManager.ReactToTouchesCancelled (touches, evt); } - public void AddPlane(SCNNode node, ARPlaneAnchor anchor) + public void AddPlane (SCNNode node, ARPlaneAnchor anchor) { - var plane = new Plane(anchor); + var plane = new Plane (anchor); - Planes.Add(anchor, plane); - node.AddChildNode(plane); + Planes.Add (anchor, plane); + node.AddChildNode (plane); - UserFeedback.CancelScheduledMessage(MessageType.PlaneEstimation); - UserFeedback.ShowMessage("SURFACE DETECTED"); - if (virtualObjectManager.VirtualObjects.Count == 0) - { - UserFeedback.ScheduleMessage("TAP + TO PLACE AN OBJECT", 7.5, MessageType.ContentPlacement); + UserFeedback.CancelScheduledMessage (MessageType.PlaneEstimation); + UserFeedback.ShowMessage ("SURFACE DETECTED"); + if (virtualObjectManager.VirtualObjects.Count == 0) { + UserFeedback.ScheduleMessage ("TAP + TO PLACE AN OBJECT", 7.5, MessageType.ContentPlacement); } } - public void UpdatePlane(ARPlaneAnchor anchor) + public void UpdatePlane (ARPlaneAnchor anchor) { - if (Planes.ContainsKey(anchor)) - { - Planes[anchor].Update(anchor); + if (Planes.ContainsKey (anchor)) { + Planes [anchor].Update (anchor); } } - public void RemovePlane(ARPlaneAnchor anchor) + public void RemovePlane (ARPlaneAnchor anchor) { - if (Planes.ContainsKey(anchor)) - { - Planes[anchor].RemoveFromParentNode(); - Planes.Remove(anchor); + if (Planes.ContainsKey (anchor)) { + Planes [anchor].RemoveFromParentNode (); + Planes.Remove (anchor); } } - public void ResetTracking() + public void ResetTracking () { - Session.Run(StandardConfiguration(), ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + Session.Run (StandardConfiguration (), ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - UserFeedback.ScheduleMessage("FIND A SURFACE TO PLACE AN OBJECT", 7.5, MessageType.PlaneEstimation); + UserFeedback.ScheduleMessage ("FIND A SURFACE TO PLACE AN OBJECT", 7.5, MessageType.PlaneEstimation); } - private ARConfiguration StandardConfiguration() + private ARConfiguration StandardConfiguration () { - var config = new ARWorldTrackingConfiguration(); + var config = new ARWorldTrackingConfiguration (); config.PlaneDetection = ARPlaneDetection.Horizontal; return config; } - public void SetupFocusSquare() + public void SetupFocusSquare () { - if (FocusSquare != null) - { + if (FocusSquare != null) { FocusSquare.Hidden = true; - FocusSquare.RemoveFromParentNode(); + FocusSquare.RemoveFromParentNode (); } - FocusSquare = new FocusSquare(); - SceneView.Scene.RootNode.AddChildNode(FocusSquare); + FocusSquare = new FocusSquare (); + SceneView.Scene.RootNode.AddChildNode (FocusSquare); - UserFeedback.ScheduleMessage("TRY MOVING LEFT OR RIGHT", 5.0, MessageType.FocusSquare); + UserFeedback.ScheduleMessage ("TRY MOVING LEFT OR RIGHT", 5.0, MessageType.FocusSquare); } - private void UpdateFocusSquare() + private void UpdateFocusSquare () { - if (ScreenCenter == null) - { + if (ScreenCenter == null) { return; } - DispatchQueue.MainQueue.DispatchAsync(() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { var objectVisible = false; - foreach (var vo in virtualObjectManager.VirtualObjects) - { - if (SceneView.IsNodeInsideFrustum(vo, SceneView.PointOfView)) - { + foreach (var vo in virtualObjectManager.VirtualObjects) { + if (SceneView.IsNodeInsideFrustum (vo, SceneView.PointOfView)) { objectVisible = true; break; } } - if (objectVisible) - { - FocusSquare?.Hide(); - } - else - { - FocusSquare?.Show(); + if (objectVisible) { + FocusSquare?.Hide (); + } else { + FocusSquare?.Show (); } - var (worldPos, planeAnchor, _) = virtualObjectManager.WorldPositionFromScreenPosition(ScreenCenter.Value, SceneView, FocusSquare?.Position); - if (worldPos != null) - { - if (Session != null && ViewController.CurrentFrame != null) - { - FocusSquare.Update((SCNVector3)worldPos, planeAnchor, ViewController.CurrentFrame.Camera); + var (worldPos, planeAnchor, _) = virtualObjectManager.WorldPositionFromScreenPosition (ScreenCenter.Value, SceneView, FocusSquare?.Position); + if (worldPos != null) { + if (Session != null && ViewController.CurrentFrame != null) { + FocusSquare.Update ((SCNVector3) worldPos, planeAnchor, ViewController.CurrentFrame.Camera); } - UserFeedback.CancelScheduledMessage(MessageType.FocusSquare); + UserFeedback.CancelScheduledMessage (MessageType.FocusSquare); } }); } - public void SetupScene() + public void SetupScene () { // Synchronize updates via the 'serialQueue' - serialQueue = new DispatchQueue(label: "com.xamarin.PlacingObjects.serialSceneKitQueue"); - virtualObjectManager = new VirtualObjectManager(serialQueue); + serialQueue = new DispatchQueue (label: "com.xamarin.PlacingObjects.serialSceneKitQueue"); + virtualObjectManager = new VirtualObjectManager (serialQueue); virtualObjectManager.Delegate = this; // Setup the scene view - SceneView.Setup(); + SceneView.Setup (); SceneView.Delegate = this; SceneView.Session = Session; - SceneView.Scene.EnableEnvironmentMapWithIntensity(25.0f, serialQueue); - SetupFocusSquare(); + SceneView.Scene.EnableEnvironmentMapWithIntensity (25.0f, serialQueue); + SetupFocusSquare (); - DispatchQueue.MainQueue.DispatchAsync(() => ScreenCenter = SceneView.Bounds.GetMidpoint()); + DispatchQueue.MainQueue.DispatchAsync (() => ScreenCenter = SceneView.Bounds.GetMidpoint ()); } - public void SetupUIControls() + public void SetupUIControls () { - UserFeedback = new TextManager(this); + UserFeedback = new TextManager (this); // Set appareance of message output panel MessagePanel.Layer.CornerRadius = 3.0f; @@ -285,24 +260,20 @@ public void SetupUIControls() MessageLabel.Text = ""; } - private void DisplayErrorMessage(string title, string message, bool allowRestart = false) + private void DisplayErrorMessage (string title, string message, bool allowRestart = false) { // Blur the background - UserFeedback.BlurBackground(); + UserFeedback.BlurBackground (); - if (allowRestart) - { + if (allowRestart) { // Present an alert informing about the error that has occurred. - var restartAction = UIAlertAction.Create("Reset", UIAlertActionStyle.Default, (obj) => - { - UserFeedback.UnblurBackground(); - RestartExperience(this); + var restartAction = UIAlertAction.Create ("Reset", UIAlertActionStyle.Default, (obj) => { + UserFeedback.UnblurBackground (); + RestartExperience (this); }); - UserFeedback.ShowAlert(title, message, new UIAlertAction[] { restartAction }); - } - else - { - UserFeedback.ShowAlert(title, message, new UIAlertAction[] { }); + UserFeedback.ShowAlert (title, message, new UIAlertAction [] { restartAction }); + } else { + UserFeedback.ShowAlert (title, message, new UIAlertAction [] { }); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjectSelectionViewController.cs b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjectSelectionViewController.cs index 4f64a8370..a591b2d78 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjectSelectionViewController.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjectSelectionViewController.cs @@ -1,91 +1,81 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; using SceneKit; using ARKit; -namespace PlacingObjects -{ - [Register("VirtualObjectSelectionViewController")] - public class VirtualObjectSelectionViewController : UITableViewController - { +namespace PlacingObjects { + [Register ("VirtualObjectSelectionViewController")] + public class VirtualObjectSelectionViewController : UITableViewController { public IVirtualObjectSelectionViewControllerDelegate Delegate { get; set; } - private NSIndexSet selectedVirtualObjectRows = new NSIndexSet(); + private NSIndexSet selectedVirtualObjectRows = new NSIndexSet (); - public VirtualObjectSelectionViewController(NSCoder coder) : base(coder) + public VirtualObjectSelectionViewController (NSCoder coder) : base (coder) { } - public VirtualObjectSelectionViewController(IntPtr ptr) : base(ptr) + public VirtualObjectSelectionViewController (IntPtr ptr) : base (ptr) { } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - TableView.SeparatorEffect = UIVibrancyEffect.FromBlurEffect(UIBlurEffect.FromStyle(UIBlurEffectStyle.Light)); + TableView.SeparatorEffect = UIVibrancyEffect.FromBlurEffect (UIBlurEffect.FromStyle (UIBlurEffectStyle.Light)); } - public override void ViewWillLayoutSubviews() + public override void ViewWillLayoutSubviews () { - PreferredContentSize = new CGSize(250, TableView.ContentSize.Height); + PreferredContentSize = new CGSize (250, TableView.ContentSize.Height); } - override public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) + override public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = tableView.DequeueReusableCell(ObjectCell.Identifier, indexPath) as ObjectCell; - cell.VirtualObject = VirtualObjectManager.AvailableObjects[indexPath.Row]; + var cell = tableView.DequeueReusableCell (ObjectCell.Identifier, indexPath) as ObjectCell; + cell.VirtualObject = VirtualObjectManager.AvailableObjects [indexPath.Row]; - if (selectedVirtualObjectRows.Contains((nuint)indexPath.Row)) - { + if (selectedVirtualObjectRows.Contains ((nuint) indexPath.Row)) { cell.Accessory = UITableViewCellAccessory.Checkmark; - } - else - { + } else { cell.Accessory = UITableViewCellAccessory.None; } return cell; } - override public nint RowsInSection(UITableView tableView, nint section) + override public nint RowsInSection (UITableView tableView, nint section) { return VirtualObjectManager.AvailableObjects.Count; } - override public void RowSelected(UITableView tableView, NSIndexPath indexPath) + override public void RowSelected (UITableView tableView, NSIndexPath indexPath) { // Check if the current row is already selected, then deselect it. - if (selectedVirtualObjectRows.Contains((nuint)indexPath.Row)) - { - Delegate?.DidDeselectObjectAt(indexPath.Row); - } - else - { - Delegate?.DidSelectObjectAt(indexPath.Row); + if (selectedVirtualObjectRows.Contains ((nuint) indexPath.Row)) { + Delegate?.DidDeselectObjectAt (indexPath.Row); + } else { + Delegate?.DidSelectObjectAt (indexPath.Row); } - DismissViewController(true, null); + DismissViewController (true, null); } - override public void RowHighlighted(UITableView tableView, NSIndexPath rowIndexPath) + override public void RowHighlighted (UITableView tableView, NSIndexPath rowIndexPath) { - var cell = TableView.CellAt(rowIndexPath); - if (cell != null) - { - cell.BackgroundColor = UIColor.LightGray.ColorWithAlpha(0.5f); + var cell = TableView.CellAt (rowIndexPath); + if (cell != null) { + cell.BackgroundColor = UIColor.LightGray.ColorWithAlpha (0.5f); } } - override public void RowUnhighlighted(UITableView tableView, NSIndexPath rowIndexPath) + override public void RowUnhighlighted (UITableView tableView, NSIndexPath rowIndexPath) { - var cell = TableView.CellAt(rowIndexPath); - if (cell != null) - { + var cell = TableView.CellAt (rowIndexPath); + if (cell != null) { cell.BackgroundColor = UIColor.Clear; } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/IVirtualObjectManagerDelegate.cs b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/IVirtualObjectManagerDelegate.cs index 77fe6df45..0047496ae 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/IVirtualObjectManagerDelegate.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/IVirtualObjectManagerDelegate.cs @@ -1,15 +1,12 @@ -namespace PlacingObjects -{ - public interface IVirtualObjectManagerDelegate - { - void WillLoad(VirtualObjectManager manager, VirtualObject virtualObject); - void DidLoad(VirtualObjectManager manager, VirtualObject virtualObject); - void CouldNotPlace(VirtualObjectManager manager, VirtualObject virtualObject); +namespace PlacingObjects { + public interface IVirtualObjectManagerDelegate { + void WillLoad (VirtualObjectManager manager, VirtualObject virtualObject); + void DidLoad (VirtualObjectManager manager, VirtualObject virtualObject); + void CouldNotPlace (VirtualObjectManager manager, VirtualObject virtualObject); } - static class VirtualObjectManagerDelegate_Extensions - { - public static void TransformDidChangeFor(this IVirtualObjectManagerDelegate self, VirtualObjectManager manager, VirtualObject virtualObject) { } - public static void DidMoveObjectOntoNearbyPlane(this IVirtualObjectManagerDelegate self, VirtualObjectManager manager, VirtualObject virtualObject) { } + static class VirtualObjectManagerDelegate_Extensions { + public static void TransformDidChangeFor (this IVirtualObjectManagerDelegate self, VirtualObjectManager manager, VirtualObject virtualObject) { } + public static void DidMoveObjectOntoNearbyPlane (this IVirtualObjectManagerDelegate self, VirtualObjectManager manager, VirtualObject virtualObject) { } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObject.cs b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObject.cs index d0273d5be..6515a5bdd 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObject.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObject.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using CoreGraphics; using SceneKit; using ARKit; @@ -7,13 +7,11 @@ using System.IO; using System; -namespace PlacingObjects -{ - public class VirtualObject : SCNReferenceNode - { +namespace PlacingObjects { + public class VirtualObject : SCNReferenceNode { public VirtualObjectDefinition Definition { get; protected set; } - public VirtualObject(VirtualObjectDefinition definition) : base(NSUrl.FromString( + public VirtualObject (VirtualObjectDefinition definition) : base (NSUrl.FromString ( NSBundle.MainBundle.BundleUrl.AbsoluteString + $"Models.scnassets/{definition.ModelName}/{definition.ModelName}.scn")) { this.Definition = definition; @@ -21,59 +19,52 @@ public VirtualObject(VirtualObjectDefinition definition) : base(NSUrl.FromString } // Use average of recent virtual object distances to avoid rapid changes in object scale. - List<float> recentVirtualObjectDistances = new List<float>(); + List<float> recentVirtualObjectDistances = new List<float> (); public List<float> RecentVirtualObjectDistances { get => recentVirtualObjectDistances; } - public void ReactToScale() + public void ReactToScale () { // Scale the particles in any descendant particle systems (Candle, - foreach (var kv in Definition.ParticleScaleInfo) - { + foreach (var kv in Definition.ParticleScaleInfo) { var nodeName = kv.Key; var particleSize = kv.Value; - var node = this.FindChildNode(nodeName, true); - if (node != null) - { + var node = this.FindChildNode (nodeName, true); + if (node != null) { var particleSystems = node.ParticleSystems; - if (particleSystems != null && particleSystems.Length > 0) - { - var particleSystem = particleSystems.First(); - particleSystem.Reset(); + if (particleSystems != null && particleSystems.Length > 0) { + var particleSystem = particleSystems.First (); + particleSystem.Reset (); particleSystem.ParticleSize = Scale.X * particleSize; } } } } - public static bool IsNodePartOfVirtualObject(SCNNode node) + public static bool IsNodePartOfVirtualObject (SCNNode node) { // End recursion on success - if (node is VirtualObject) - { + if (node is VirtualObject) { return true; } // End recursion because we've gotten to the root object with no parent - if (node.ParentNode == null) - { + if (node.ParentNode == null) { return false; } // Recurse up the scene graph - return IsNodePartOfVirtualObject(node.ParentNode); + return IsNodePartOfVirtualObject (node.ParentNode); } - internal static VirtualObject ForChildNode(SCNNode node) + internal static VirtualObject ForChildNode (SCNNode node) { - if (node is VirtualObject) - { + if (node is VirtualObject) { return node as VirtualObject; } // End recursion if gotten to root object with no parent - if (node.ParentNode == null) - { + if (node.ParentNode == null) { return null; } // Recurse up the scene graph - return ForChildNode(node.ParentNode); + return ForChildNode (node.ParentNode); } } } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectDefinition.cs b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectDefinition.cs index 3bae16e62..4c4e47e5f 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectDefinition.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectDefinition.cs @@ -1,38 +1,33 @@ -using System; +using System; using UIKit; using System.Collections.Generic; using System.Linq; -namespace PlacingObjects -{ - public class VirtualObjectDefinition : IEquatable<VirtualObjectDefinition> - { +namespace PlacingObjects { + public class VirtualObjectDefinition : IEquatable<VirtualObjectDefinition> { public String ModelName { get; } public String DisplayName { get; } public Dictionary<string, float> ParticleScaleInfo { get; } public UIImage ThumbImage { get; protected set; } - public VirtualObjectDefinition(string modelName, string displayName, Dictionary<string, float> particleScaleInfo = null) + public VirtualObjectDefinition (string modelName, string displayName, Dictionary<string, float> particleScaleInfo = null) { this.ModelName = modelName; this.DisplayName = displayName; - this.ParticleScaleInfo = particleScaleInfo == null ? new Dictionary<string, float>() : particleScaleInfo; + this.ParticleScaleInfo = particleScaleInfo == null ? new Dictionary<string, float> () : particleScaleInfo; - this.ThumbImage = UIImage.FromBundle(this.ModelName); + this.ThumbImage = UIImage.FromBundle (this.ModelName); } - public bool Equals(VirtualObjectDefinition other) + public bool Equals (VirtualObjectDefinition other) { - if (this.ModelName.Equals(other.ModelName) - && this.DisplayName.Equals(other.DisplayName)) - { - var thisByKey = this.ParticleScaleInfo.OrderBy(kv => kv.Key); - var otherByKey = other.ParticleScaleInfo.OrderBy(kv => kv.Key); - return thisByKey.SequenceEqual(otherByKey); - } - else - { + if (this.ModelName.Equals (other.ModelName) + && this.DisplayName.Equals (other.DisplayName)) { + var thisByKey = this.ParticleScaleInfo.OrderBy (kv => kv.Key); + var otherByKey = other.ParticleScaleInfo.OrderBy (kv => kv.Key); + return thisByKey.SequenceEqual (otherByKey); + } else { return false; } diff --git a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectManager.cs b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectManager.cs index 128fa318d..dc11c3324 100644 --- a/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectManager.cs +++ b/ios11/ARKitPlacingObjects/PlacingObjects/VirtualObjects/VirtualObjectManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using ARKit; @@ -11,85 +11,74 @@ using SceneKit; using UIKit; -namespace PlacingObjects -{ - public class VirtualObjectManager : NSObject - { - static VirtualObjectManager() +namespace PlacingObjects { + public class VirtualObjectManager : NSObject { + static VirtualObjectManager () { - var jsonPath = NSBundle.MainBundle.PathForResource("VirtualObjects", "json"); - var jsonData = System.IO.File.ReadAllText(jsonPath); - AvailableObjects = JsonConvert.DeserializeObject<List<VirtualObjectDefinition>>(jsonData); + var jsonPath = NSBundle.MainBundle.PathForResource ("VirtualObjects", "json"); + var jsonData = System.IO.File.ReadAllText (jsonPath); + AvailableObjects = JsonConvert.DeserializeObject<List<VirtualObjectDefinition>> (jsonData); } public static List<VirtualObjectDefinition> AvailableObjects { get; protected set; } DispatchQueue queue; public IVirtualObjectManagerDelegate Delegate { get; set; } - public List<VirtualObject> VirtualObjects { get; protected set; } = new List<VirtualObject>(); + public List<VirtualObject> VirtualObjects { get; protected set; } = new List<VirtualObject> (); VirtualObject lastUsedObject = null; Gesture currentGesture = null; - public VirtualObjectManager(DispatchQueue queue) + public VirtualObjectManager (DispatchQueue queue) { this.queue = queue; } - public void Translate(VirtualObject vObject, ARSCNView sceneView, CGPoint screenPos, bool instantly, bool infinitePlane) + public void Translate (VirtualObject vObject, ARSCNView sceneView, CGPoint screenPos, bool instantly, bool infinitePlane) { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var result = WorldPositionFromScreenPosition(screenPos, sceneView, vObject.Position, infinitePlane); + DispatchQueue.MainQueue.DispatchAsync (() => { + var result = WorldPositionFromScreenPosition (screenPos, sceneView, vObject.Position, infinitePlane); var newPosition = result.Item1; - if (newPosition == null) - { - if (this.Delegate != null) - { - this.Delegate.CouldNotPlace(this, vObject); + if (newPosition == null) { + if (this.Delegate != null) { + this.Delegate.CouldNotPlace (this, vObject); return; } } var currentFrame = ViewController.CurrentFrame; - if (currentFrame == null || currentFrame.Camera == null) - { + if (currentFrame == null || currentFrame.Camera == null) { return; } var cameraTransform = currentFrame.Camera.Transform; - queue.DispatchAsync(() => SetPosition(vObject, newPosition.Value, instantly, result.Item3, cameraTransform)); + queue.DispatchAsync (() => SetPosition (vObject, newPosition.Value, instantly, result.Item3, cameraTransform)); }); } - internal void RemoveAllVirtualObjects() + internal void RemoveAllVirtualObjects () { - foreach (var vo in VirtualObjects) - { - vo.Unload(); + foreach (var vo in VirtualObjects) { + vo.Unload (); } - VirtualObjects.Clear(); + VirtualObjects.Clear (); } - private void SetPosition(VirtualObject virtualObject, SCNVector3 position, bool instantly, bool filterPosition, NMatrix4 cameraTransform) + private void SetPosition (VirtualObject virtualObject, SCNVector3 position, bool instantly, bool filterPosition, NMatrix4 cameraTransform) { - if (instantly) - { - SetNewVirtualObjectPosition(virtualObject, position, cameraTransform); - } - else - { - UpdateVirtualObjectPosition(virtualObject, position, filterPosition, cameraTransform); + if (instantly) { + SetNewVirtualObjectPosition (virtualObject, position, cameraTransform); + } else { + UpdateVirtualObjectPosition (virtualObject, position, filterPosition, cameraTransform); } } - public void UpdateVirtualObjectPosition(VirtualObject virtualObject, SCNVector3 position, bool filterPosition, NMatrix4 cameraTransform) + public void UpdateVirtualObjectPosition (VirtualObject virtualObject, SCNVector3 position, bool filterPosition, NMatrix4 cameraTransform) { - var cameraWorldPos = cameraTransform.Translation(); - var cameraToPosition = position.Subtract(cameraWorldPos); + var cameraWorldPos = cameraTransform.Translation (); + var cameraToPosition = position.Subtract (cameraWorldPos); // Limit the distance of the object from the camera to a maximum of 10m - if (cameraToPosition.LengthFast > 10) - { - cameraToPosition = cameraToPosition.Normalized() * 10; + if (cameraToPosition.LengthFast > 10) { + cameraToPosition = cameraToPosition.Normalized () * 10; } // Compute the average distance of the object from the camera over the last ten @@ -99,46 +88,40 @@ public void UpdateVirtualObjectPosition(VirtualObject virtualObject, SCNVector3 // object - the averaging does _not_ make the content "lag". var hitTestResultDistance = cameraToPosition.LengthFast; - virtualObject.RecentVirtualObjectDistances.Add(hitTestResultDistance); - virtualObject.RecentVirtualObjectDistances.KeepLast(10); + virtualObject.RecentVirtualObjectDistances.Add (hitTestResultDistance); + virtualObject.RecentVirtualObjectDistances.KeepLast (10); - if (filterPosition) - { - var averageDistance = virtualObject.RecentVirtualObjectDistances.Average(); - var averagedDistancePos = cameraWorldPos + cameraToPosition.Normalized() * averageDistance; + if (filterPosition) { + var averageDistance = virtualObject.RecentVirtualObjectDistances.Average (); + var averagedDistancePos = cameraWorldPos + cameraToPosition.Normalized () * averageDistance; virtualObject.Position = averagedDistancePos; - } - else - { + } else { virtualObject.Position = cameraWorldPos + cameraToPosition; } } - private void SetNewVirtualObjectPosition(VirtualObject virtualObject, SCNVector3 position, NMatrix4 cameraTransform) + private void SetNewVirtualObjectPosition (VirtualObject virtualObject, SCNVector3 position, NMatrix4 cameraTransform) { - var cameraWorldPos = cameraTransform.Translation(); - var cameraToPosition = position.Subtract(cameraWorldPos); + var cameraWorldPos = cameraTransform.Translation (); + var cameraToPosition = position.Subtract (cameraWorldPos); // Limit the distance of the object from the camera to a maximum of 10m - if (cameraToPosition.LengthFast > 10) - { - cameraToPosition = cameraToPosition.Normalized() * 10; + if (cameraToPosition.LengthFast > 10) { + cameraToPosition = cameraToPosition.Normalized () * 10; } virtualObject.Position = cameraWorldPos + cameraToPosition; - virtualObject.RecentVirtualObjectDistances.Clear(); + virtualObject.RecentVirtualObjectDistances.Clear (); } - public void CheckIfObjectShouldMoveOntoPlane(ARPlaneAnchor anchor, SCNNode planeAnchorNode) + public void CheckIfObjectShouldMoveOntoPlane (ARPlaneAnchor anchor, SCNNode planeAnchorNode) { - foreach (var vo in VirtualObjects) - { + foreach (var vo in VirtualObjects) { // Get the object's position in the plane's coordinate system. - var objectPos = planeAnchorNode.ConvertPositionToNode(vo.Position, vo.ParentNode); + var objectPos = planeAnchorNode.ConvertPositionToNode (vo.Position, vo.ParentNode); - if (Math.Abs(objectPos.Y) < float.Epsilon) - { + if (Math.Abs (objectPos.Y) < float.Epsilon) { return; // The object is already on the plane - nothing to do here. } @@ -150,83 +133,76 @@ public void CheckIfObjectShouldMoveOntoPlane(ARPlaneAnchor anchor, SCNNode plane var minZ = anchor.Center.Z - anchor.Extent.Z / 2f - anchor.Extent.Z * tolerance; var maxZ = anchor.Center.Z + anchor.Extent.Z / 2f + anchor.Extent.Z * tolerance; - if (objectPos.X < minX || objectPos.X > maxX || objectPos.Z < minZ || objectPos.Z > maxZ) - { + if (objectPos.X < minX || objectPos.X > maxX || objectPos.Z < minZ || objectPos.Z > maxZ) { return; } // Drop the object onto the plane if it is near it. var verticalAllowance = 0.05f; var epsilon = 0.001; // Do not bother updating if the difference is less than a mm. - var distanceToPlane = Math.Abs(objectPos.Y); - if (distanceToPlane > epsilon && distanceToPlane < verticalAllowance) - { - Delegate.DidMoveObjectOntoNearbyPlane(this, vo); + var distanceToPlane = Math.Abs (objectPos.Y); + if (distanceToPlane > epsilon && distanceToPlane < verticalAllowance) { + Delegate.DidMoveObjectOntoNearbyPlane (this, vo); - SCNTransaction.Begin(); + SCNTransaction.Begin (); SCNTransaction.AnimationDuration = distanceToPlane * 500; // Move 2mm per second - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); - vo.Position = new SCNVector3(vo.Position.X, anchor.Transform.M32, vo.Position.Z); - SCNTransaction.Commit(); + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut); + vo.Position = new SCNVector3 (vo.Position.X, anchor.Transform.M32, vo.Position.Z); + SCNTransaction.Commit (); } } } - internal void ReactToTouchesCancelled(NSSet touches, UIEvent evt) + internal void ReactToTouchesCancelled (NSSet touches, UIEvent evt) { - if (VirtualObjects.Count() == 0) - { + if (VirtualObjects.Count () == 0) { return; } - currentGesture = currentGesture?.UpdateGestureFromTouches(touches, TouchEventType.TouchCanceled); + currentGesture = currentGesture?.UpdateGestureFromTouches (touches, TouchEventType.TouchCanceled); } - private void MoveIfNecessary(NSSet touches, UIEvent evt, TouchEventType evtType) + private void MoveIfNecessary (NSSet touches, UIEvent evt, TouchEventType evtType) { - if (VirtualObjects.Count() == 0) - { + if (VirtualObjects.Count () == 0) { return; } - currentGesture = currentGesture?.UpdateGestureFromTouches(touches, evtType); + currentGesture = currentGesture?.UpdateGestureFromTouches (touches, evtType); var newObj = currentGesture?.LastUsedObject; - if (newObj != null) - { + if (newObj != null) { lastUsedObject = newObj; } var gesture = currentGesture; var touchedObj = gesture?.LastUsedObject; - if (gesture != null && touchedObj != null) - { - Delegate?.TransformDidChangeFor(this, touchedObj); + if (gesture != null && touchedObj != null) { + Delegate?.TransformDidChangeFor (this, touchedObj); } } - internal void ReactToTouchesEnded(NSSet touches, UIEvent evt) + internal void ReactToTouchesEnded (NSSet touches, UIEvent evt) { - MoveIfNecessary(touches, evt, TouchEventType.TouchEnded); + MoveIfNecessary (touches, evt, TouchEventType.TouchEnded); } - internal void ReactToTouchesMoved(NSSet touches, UIEvent evt) + internal void ReactToTouchesMoved (NSSet touches, UIEvent evt) { - MoveIfNecessary(touches, evt, TouchEventType.TouchMoved); + MoveIfNecessary (touches, evt, TouchEventType.TouchMoved); } - internal (SCNVector3?, ARPlaneAnchor, Boolean) WorldPositionFromScreenPosition(CGPoint position, ARSCNView sceneView, SCNVector3? objectPos, bool infinitePlane = false) + internal (SCNVector3?, ARPlaneAnchor, Boolean) WorldPositionFromScreenPosition (CGPoint position, ARSCNView sceneView, SCNVector3? objectPos, bool infinitePlane = false) { var dragOnInfinitePlanesEnabled = AppSettings.DragOnInfinitePlanes; // ------------------------------------------------------------------------------- // 1. Always do a hit test against exisiting plane anchors first. // (If any such anchors exist & only within their extents.) - var planeHitTestResults = sceneView.HitTest(position, ARHitTestResultType.ExistingPlaneUsingExtent); - var result = planeHitTestResults.FirstOrDefault(); - if (result != null) - { - var planeHitTestPosition = result.WorldTransform.Translation(); + var planeHitTestResults = sceneView.HitTest (position, ARHitTestResultType.ExistingPlaneUsingExtent); + var result = planeHitTestResults.FirstOrDefault (); + if (result != null) { + var planeHitTestPosition = result.WorldTransform.Translation (); var planeAnchor = result.Anchor; - return (planeHitTestPosition, (ARPlaneAnchor)planeAnchor, true); + return (planeHitTestPosition, (ARPlaneAnchor) planeAnchor, true); } // ------------------------------------------------------------------------------- @@ -235,10 +211,9 @@ internal void ReactToTouchesMoved(NSSet touches, UIEvent evt) SCNVector3? featureHitTestPosition = null; var highQualityFeatureHitTestResult = false; - var highQualityfeatureHitTestResults = sceneView.HitTestWithFeatures(position, 18, 0.2, 2.0); - if (highQualityfeatureHitTestResults.Count() > 0) - { - var highQualityFeatureHit = highQualityfeatureHitTestResults.First(); + var highQualityfeatureHitTestResults = sceneView.HitTestWithFeatures (position, 18, 0.2, 2.0); + if (highQualityfeatureHitTestResults.Count () > 0) { + var highQualityFeatureHit = highQualityfeatureHitTestResults.First (); featureHitTestPosition = highQualityFeatureHit.Position; highQualityFeatureHitTestResult = true; } @@ -247,13 +222,10 @@ internal void ReactToTouchesMoved(NSSet touches, UIEvent evt) // ------------------------------------------------------------------------------- // 3. If desired or necessary (no good feature hit test result): Hit test // against an infinite, horizontal plane (ignoring the real world). - if ((infinitePlane && dragOnInfinitePlanesEnabled) || !highQualityFeatureHitTestResult) - { - if (objectPos.HasValue) - { - var pointOnInfinitePlane = sceneView.HitTestWithInfiniteHorizontalPlane(position, objectPos.Value); - if (pointOnInfinitePlane != null) - { + if ((infinitePlane && dragOnInfinitePlanesEnabled) || !highQualityFeatureHitTestResult) { + if (objectPos.HasValue) { + var pointOnInfinitePlane = sceneView.HitTestWithInfiniteHorizontalPlane (position, objectPos.Value); + if (pointOnInfinitePlane != null) { return (pointOnInfinitePlane, null, true); } } @@ -263,95 +235,81 @@ internal void ReactToTouchesMoved(NSSet touches, UIEvent evt) // 4. If available, return the result of the hit test against high quality // features if the hit tests against infinite planes were skipped or no // infinite plane was hit. - if (highQualityFeatureHitTestResult) - { + if (highQualityFeatureHitTestResult) { return (featureHitTestPosition, null, false); } // ------------------------------------------------------------------------------- // 5. As a last resort, perform a second, unfiltered hit test against features. // If there are no features in the scene, the result returned here will be nil. - var unfilteredFeatureHitTestResults = sceneView.HitTestWithFeatures(position); - if (unfilteredFeatureHitTestResults.Count() > 0) - { - var unfilteredFeaturesResult = unfilteredFeatureHitTestResults.First(); + var unfilteredFeatureHitTestResults = sceneView.HitTestWithFeatures (position); + if (unfilteredFeatureHitTestResults.Count () > 0) { + var unfilteredFeaturesResult = unfilteredFeatureHitTestResults.First (); return (unfilteredFeaturesResult.Position, null, false); } return (null, null, false); } - public void ReactToTouchesBegan(NSSet touches, UIEvent evt, ARSCNView scnView) + public void ReactToTouchesBegan (NSSet touches, UIEvent evt, ARSCNView scnView) { - if (!VirtualObjects.Any()) - { + if (!VirtualObjects.Any ()) { return; } - if (currentGesture == null) - { - currentGesture = Gesture.StartGestureFromTouches(touches, scnView, lastUsedObject, this); - } - else - { - currentGesture = currentGesture.UpdateGestureFromTouches(touches, TouchEventType.TouchBegan); + if (currentGesture == null) { + currentGesture = Gesture.StartGestureFromTouches (touches, scnView, lastUsedObject, this); + } else { + currentGesture = currentGesture.UpdateGestureFromTouches (touches, TouchEventType.TouchBegan); } - if (currentGesture != null && currentGesture.LastUsedObject != null) - { + if (currentGesture != null && currentGesture.LastUsedObject != null) { lastUsedObject = currentGesture.LastUsedObject; } } - public void LoadVirtualObject(VirtualObject vo, SCNVector3 position, NMatrix4 cameraTransform) + public void LoadVirtualObject (VirtualObject vo, SCNVector3 position, NMatrix4 cameraTransform) { - VirtualObjects.Add(vo); - if (Delegate != null) - { - Delegate.WillLoad(this, vo); + VirtualObjects.Add (vo); + if (Delegate != null) { + Delegate.WillLoad (this, vo); } - vo.Load(); + vo.Load (); // Immediately place the object in 3D space - SetNewVirtualObjectPosition(vo, position, cameraTransform); + SetNewVirtualObjectPosition (vo, position, cameraTransform); lastUsedObject = vo; - if (Delegate != null) - { - Delegate.DidLoad(this, vo); + if (Delegate != null) { + Delegate.DidLoad (this, vo); } } - public void RemoveVirtualObject(int index) + public void RemoveVirtualObject (int index) { - if (index < 0 || index >= AvailableObjects.Count()) - { + if (index < 0 || index >= AvailableObjects.Count ()) { return; } - var def = AvailableObjects[index]; - var vo = VirtualObjects.Where(vo2 => vo2.Definition.Equals(def)).FirstOrDefault(); - if (vo == null) - { + var def = AvailableObjects [index]; + var vo = VirtualObjects.Where (vo2 => vo2.Definition.Equals (def)).FirstOrDefault (); + if (vo == null) { return; } - UnloadVirtualObject(vo); - if (index >= VirtualObjects.Count()) - { + UnloadVirtualObject (vo); + if (index >= VirtualObjects.Count ()) { return; } - var pos = VirtualObjects[index]; - VirtualObjects.RemoveAt(index); + var pos = VirtualObjects [index]; + VirtualObjects.RemoveAt (index); } - private void UnloadVirtualObject(VirtualObject vo) + private void UnloadVirtualObject (VirtualObject vo) { - vo.Unload(); - vo.RemoveFromParentNode(); - if (lastUsedObject == vo) - { + vo.Unload (); + vo.RemoveFromParentNode (); + if (lastUsedObject == vo) { lastUsedObject = null; - if (VirtualObjects.Count() > 1) - { - lastUsedObject = VirtualObjects[0]; + if (VirtualObjects.Count () > 1) { + lastUsedObject = VirtualObjects [0]; } } } diff --git a/ios11/ARKitSample/ARKitSample/AppDelegate.cs b/ios11/ARKitSample/ARKitSample/AppDelegate.cs index c6c7d8585..a631ce42b 100644 --- a/ios11/ARKitSample/ARKitSample/AppDelegate.cs +++ b/ios11/ARKitSample/ARKitSample/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace ARKitSample -{ +namespace ARKitSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/ARKitSample/ARKitSample/ClassExtensions/Matrix4Extensions.cs b/ios11/ARKitSample/ARKitSample/ClassExtensions/Matrix4Extensions.cs index b2d6abf1f..32b7005ab 100644 --- a/ios11/ARKitSample/ARKitSample/ClassExtensions/Matrix4Extensions.cs +++ b/ios11/ARKitSample/ARKitSample/ClassExtensions/Matrix4Extensions.cs @@ -1,20 +1,18 @@ -using System; +using System; using Foundation; using SceneKit; using ARKit; using OpenTK; -namespace ARKitSample -{ - public static class Matrix4Extensions - { - public static SCNMatrix4 ToSCNMatrix4(this NMatrix4 self) +namespace ARKitSample { + public static class Matrix4Extensions { + public static SCNMatrix4 ToSCNMatrix4 (this NMatrix4 self) { - var row0 = new SCNVector4(self.M11, self.M12, self.M13, self.M14); - var row1 = new SCNVector4(self.M21, self.M22, self.M23, self.M24); - var row2 = new SCNVector4(self.M31, self.M32, self.M33, self.M34); - var row3 = new SCNVector4(self.M41, self.M42, self.M43, self.M44); - return new SCNMatrix4(row0, row1, row2, row3); + var row0 = new SCNVector4 (self.M11, self.M12, self.M13, self.M14); + var row1 = new SCNVector4 (self.M21, self.M22, self.M23, self.M24); + var row2 = new SCNVector4 (self.M31, self.M32, self.M33, self.M34); + var row3 = new SCNVector4 (self.M41, self.M42, self.M43, self.M44); + return new SCNMatrix4 (row0, row1, row2, row3); } } } diff --git a/ios11/ARKitSample/ARKitSample/Classes/SessionDelegate.cs b/ios11/ARKitSample/ARKitSample/Classes/SessionDelegate.cs index 0c07288a2..beaeae449 100644 --- a/ios11/ARKitSample/ARKitSample/Classes/SessionDelegate.cs +++ b/ios11/ARKitSample/ARKitSample/Classes/SessionDelegate.cs @@ -1,51 +1,49 @@ -using System; +using System; using SceneKit; using UIKit; using ARKit; -namespace ARKitSample -{ - public class SessionDelegate : ARSessionDelegate - { +namespace ARKitSample { + public class SessionDelegate : ARSessionDelegate { #region Constructors - public SessionDelegate() + public SessionDelegate () { } #endregion #region Override Methods - public override void CameraDidChangeTrackingState(ARSession session, ARCamera camera) + public override void CameraDidChangeTrackingState (ARSession session, ARCamera camera) { var state = ""; var reason = ""; - switch(camera.TrackingState) { - case ARTrackingState.NotAvailable: - state = "Tracking Not Available"; + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + state = "Tracking Not Available"; + break; + case ARTrackingState.Normal: + state = "Tracking Normal"; + break; + case ARTrackingState.Limited: + state = "Tracking Limited"; + switch (camera.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: + reason = "because of excessive motion"; break; - case ARTrackingState.Normal: - state = "Tracking Normal"; + case ARTrackingStateReason.Initializing: + reason = "because tracking is initializing"; break; - case ARTrackingState.Limited: - state = "Tracking Limited"; - switch(camera.TrackingStateReason) { - case ARTrackingStateReason.ExcessiveMotion: - reason = "because of excessive motion"; - break; - case ARTrackingStateReason.Initializing: - reason = "because tracking is initializing"; - break; - case ARTrackingStateReason.InsufficientFeatures: - reason = "because of insufficient features in the environment"; - break; - case ARTrackingStateReason.None: - reason = "because of an unknown reason"; - break; - } + case ARTrackingStateReason.InsufficientFeatures: + reason = "because of insufficient features in the environment"; break; + case ARTrackingStateReason.None: + reason = "because of an unknown reason"; + break; + } + break; } // Inform user - Console.WriteLine("{0} {1}", state, reason); + Console.WriteLine ("{0} {1}", state, reason); } #endregion diff --git a/ios11/ARKitSample/ARKitSample/GameViewController.cs b/ios11/ARKitSample/ARKitSample/GameViewController.cs index eb6ebc1d6..461cf54dc 100644 --- a/ios11/ARKitSample/ARKitSample/GameViewController.cs +++ b/ios11/ARKitSample/ARKitSample/GameViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using SceneKit; using UIKit; using ARKit; using CoreGraphics; -namespace ARKitSample -{ - public partial class GameViewController : UIViewController, IARSCNViewDelegate - { +namespace ARKitSample { + public partial class GameViewController : UIViewController, IARSCNViewDelegate { #region Computed Properties public ARSCNView SceneView { get { return View as ARSCNView; } @@ -23,46 +21,46 @@ public float AmbientIntensity { if (frame.LightEstimate == null) { return 1000; } else { - return (float)frame.LightEstimate.AmbientIntensity; + return (float) frame.LightEstimate.AmbientIntensity; } } } #endregion #region Constructors - protected GameViewController(IntPtr handle) : base(handle) + protected GameViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Set self as the Scene View's delegate SceneView.Delegate = this; // Track changes to the session - SceneView.Session.Delegate = new SessionDelegate(); + SceneView.Session.Delegate = new SessionDelegate (); // Create a new scene - var scene = SCNScene.FromFile("art.scnassets/ship"); + var scene = SCNScene.FromFile ("art.scnassets/ship"); // Set the scene to the view SceneView.Scene = scene; // Add a tap gesture recognizer - var tapGesture = new UITapGestureRecognizer(HandleTap); - View.AddGestureRecognizer(tapGesture); + var tapGesture = new UITapGestureRecognizer (HandleTap); + View.AddGestureRecognizer (tapGesture); } - public override void ViewWillAppear(bool animated) + public override void ViewWillAppear (bool animated) { - base.ViewWillAppear(animated); + base.ViewWillAppear (animated); // Create a session configuration var configuration = new ARWorldTrackingConfiguration { @@ -71,16 +69,16 @@ public override void ViewWillAppear(bool animated) }; // Run the view's session - SceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking); + SceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking); // Find the ship and position it just in front of the camera - var ship = SceneView.Scene.RootNode.FindChildNode("ship", true); - + var ship = SceneView.Scene.RootNode.FindChildNode ("ship", true); - ship.Position = new SCNVector3(2f, -2f, -9f); - //HACK: to see the jet move (circle around the viewer in a roll), comment out the ship.Position line above - // and uncomment the code below (courtesy @lobrien) + + ship.Position = new SCNVector3 (2f, -2f, -9f); + //HACK: to see the jet move (circle around the viewer in a roll), comment out the ship.Position line above + // and uncomment the code below (courtesy @lobrien) //var animation = SCNAction.RepeatActionForever(SCNAction.RotateBy(0, (float)Math.PI, (float)Math.PI, (float)1)); //var pivotNode = new SCNNode { Position = new SCNVector3(0.0f, 2.0f, 0.0f) }; @@ -92,71 +90,72 @@ public override void ViewWillAppear(bool animated) //ship.Position = new SCNVector3(2f, -2f, -3f); //ship.RunAction(SCNAction.RepeatActionForever(SCNAction.RotateBy(0, 0, 2, 1))); - //ENDHACK + //ENDHACK } - public override void ViewWillDisappear(bool animated) + public override void ViewWillDisappear (bool animated) { - base.ViewWillDisappear(animated); + base.ViewWillDisappear (animated); // Pause the view's session - SceneView.Session.Pause(); + SceneView.Session.Pause (); } - public override bool ShouldAutorotate() + public override bool ShouldAutorotate () { return true; } - public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations() + public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () { return UIInterfaceOrientationMask.All; } #endregion #region Private Methods - private void HandleTap(UIGestureRecognizer gestureRecognize) + private void HandleTap (UIGestureRecognizer gestureRecognize) { // Get current frame var currentFrame = SceneView.Session.CurrentFrame; if (currentFrame == null) return; // Create an image plane using a snapshot of the view - var imagePlane = SCNPlane.Create(SceneView.Bounds.Width / 6000, SceneView.Bounds.Height / 6000); - imagePlane.FirstMaterial.Diffuse.Contents = SceneView.Snapshot(); + var imagePlane = SCNPlane.Create (SceneView.Bounds.Width / 6000, SceneView.Bounds.Height / 6000); + imagePlane.FirstMaterial.Diffuse.Contents = SceneView.Snapshot (); imagePlane.FirstMaterial.LightingModelName = SCNLightingModel.Constant; // Create a plane node and add it to the scene - var planeNode = SCNNode.FromGeometry(imagePlane); - SceneView.Scene.RootNode.AddChildNode(planeNode); + var planeNode = SCNNode.FromGeometry (imagePlane); + SceneView.Scene.RootNode.AddChildNode (planeNode); // Set transform of node to be 10cm in front of the camera - var translation = SCNMatrix4.CreateTranslation(0, 0, 0.1f); - var cameraTranslation = currentFrame.Camera.Transform.ToSCNMatrix4(); - planeNode.Transform = SCNMatrix4.Mult(cameraTranslation, translation); + var translation = SCNMatrix4.CreateTranslation (0, 0, 0.1f); + var cameraTranslation = currentFrame.Camera.Transform.ToSCNMatrix4 (); + planeNode.Transform = SCNMatrix4.Mult (cameraTranslation, translation); } - private void AddAnchorToScene() { + private void AddAnchorToScene () + { // Get the current frame var frame = SceneView.Session.CurrentFrame; if (frame == null) return; // Create a ray to test from - var point = new CGPoint(0.5, 0.5); + var point = new CGPoint (0.5, 0.5); // Preform hit testing on frame - var results = frame.HitTest(point, ARHitTestResultType.ExistingPlane | ARHitTestResultType.EstimatedHorizontalPlane); + var results = frame.HitTest (point, ARHitTestResultType.ExistingPlane | ARHitTestResultType.EstimatedHorizontalPlane); // Use the first result - if (results.Length >0) { - var result = results[0]; + if (results.Length > 0) { + var result = results [0]; // Create an anchor for it - var anchor = new ARAnchor(result.WorldTransform); + var anchor = new ARAnchor (result.WorldTransform); // Add anchor to session - SceneView.Session.AddAnchor(anchor); + SceneView.Session.AddAnchor (anchor); } } diff --git a/ios11/ARKitSample/ARKitSample/Main.cs b/ios11/ARKitSample/ARKitSample/Main.cs index bef7b8d2d..4a7b6affd 100644 --- a/ios11/ARKitSample/ARKitSample/Main.cs +++ b/ios11/ARKitSample/ARKitSample/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace ARKitSample -{ - public class Application - { +namespace ARKitSample { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/AVCam/src/AVCamCameraViewController.cs b/ios11/AVCam/src/AVCamCameraViewController.cs index d4fa4cd2f..23bbab77d 100644 --- a/ios11/AVCam/src/AVCamCameraViewController.cs +++ b/ios11/AVCam/src/AVCamCameraViewController.cs @@ -11,10 +11,8 @@ using Photos; using UIKit; -namespace AVCam -{ - public partial class AVCamCameraViewController : UIViewController, IAVCaptureFileOutputRecordingDelegate - { +namespace AVCam { + public partial class AVCamCameraViewController : UIViewController, IAVCaptureFileOutputRecordingDelegate { AVCamSetupResult setupResult; DispatchQueue sessionQueue; AVCaptureSession session; @@ -43,18 +41,18 @@ public override void ViewDidLoad () PhotoButton.Enabled = false; LivePhotoModeButton.Enabled = false; CaptureModeControl.Enabled = false; - DepthDataDeliveryButton.Enabled = false; + DepthDataDeliveryButton.Enabled = false; // Create the AVCaptureSession. session = new AVCaptureSession (); // Create a device discovery session. videoDeviceDiscoverySession = AVCaptureDeviceDiscoverySession.Create ( - new AVCaptureDeviceType[] { AVCaptureDeviceType.BuiltInWideAngleCamera, AVCaptureDeviceType.BuiltInDualCamera }, - AVMediaType.Video, + new AVCaptureDeviceType [] { AVCaptureDeviceType.BuiltInWideAngleCamera, AVCaptureDeviceType.BuiltInDualCamera }, + AVMediaType.Video, AVCaptureDevicePosition.Unspecified ); - + // Set up the preview view. PreviewView.Session = session; @@ -62,42 +60,40 @@ public override void ViewDidLoad () sessionQueue = new DispatchQueue ("session queue", false); setupResult = AVCamSetupResult.Success; - + /* Check video authorization status. Video access is required and audio access is optional. If audio access is denied, audio is not recorded during movie recording. */ - switch (AVCaptureDevice.GetAuthorizationStatus (AVMediaType.Video )) - { - case AVAuthorizationStatus.Authorized: - // The user has previously granted access to the camera. - break; + switch (AVCaptureDevice.GetAuthorizationStatus (AVMediaType.Video)) { + case AVAuthorizationStatus.Authorized: + // The user has previously granted access to the camera. + break; - case AVAuthorizationStatus.NotDetermined: + case AVAuthorizationStatus.NotDetermined: - /* - The user has not yet been presented with the option to grant - video access. We suspend the session queue to delay session - setup until the access request has completed. - - Note that audio access will be implicitly requested when we - create an AVCaptureDeviceInput for audio during session setup. - */ - sessionQueue.Suspend (); - AVCaptureDevice.RequestAccessForMediaType (AVMediaType.Video, (bool granted) => { - if( !granted ) { - setupResult = AVCamSetupResult.CameraNotAuthorized; - } - sessionQueue.Resume (); - }); - break; - default: - { - // The user has previously denied access. - setupResult = AVCamSetupResult.CameraNotAuthorized; - break; - } + /* + The user has not yet been presented with the option to grant + video access. We suspend the session queue to delay session + setup until the access request has completed. + + Note that audio access will be implicitly requested when we + create an AVCaptureDeviceInput for audio during session setup. + */ + sessionQueue.Suspend (); + AVCaptureDevice.RequestAccessForMediaType (AVMediaType.Video, (bool granted) => { + if (!granted) { + setupResult = AVCamSetupResult.CameraNotAuthorized; + } + sessionQueue.Resume (); + }); + break; + default: { + // The user has previously denied access. + setupResult = AVCamSetupResult.CameraNotAuthorized; + break; + } } /* Setup the capture session. @@ -109,8 +105,7 @@ In general it is not safe to mutate an AVCaptureSession or any of its take a long time. We dispatch session setup to the sessionQueue so that the main queue isn't blocked, which keeps the UI responsive. */ - sessionQueue.DispatchAsync (() => - { + sessionQueue.DispatchAsync (() => { ConfigureSession (); }); } @@ -119,41 +114,38 @@ public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); - sessionQueue.DispatchAsync (() => - { - switch (setupResult) - { - case AVCamSetupResult.Success: - // Only setup observers and start the session running if setup succeeded. - AddObservers (); - session.StartRunning (); - sessionRunning = session.Running; - break; + sessionQueue.DispatchAsync (() => { + switch (setupResult) { + case AVCamSetupResult.Success: + // Only setup observers and start the session running if setup succeeded. + AddObservers (); + session.StartRunning (); + sessionRunning = session.Running; + break; - case AVCamSetupResult.CameraNotAuthorized: - sessionQueue.DispatchAsync (() => { - var message = NSBundle.MainBundle.LocalizedString (@"AVCam doesn't have permission to use the camera, please change privacy settings", @"Alert message when the user has denied access to the camera"); - var alertController = UIAlertController.Create ( @"AVCam", message, UIAlertControllerStyle.Alert); - var cancelAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"OK", @"Alert OK button"), UIAlertActionStyle.Cancel, null); - alertController.AddAction (cancelAction); - // Provide quick access to Settings. - var settingsAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"Settings", @"Alert button to open Settings"), UIAlertActionStyle.Default,(action) => { - UIApplication.SharedApplication.OpenUrl (new NSUrl (UIApplication.OpenSettingsUrlString)); - }); - alertController.AddAction (settingsAction); - PresentViewController (alertController, true, null); + case AVCamSetupResult.CameraNotAuthorized: + sessionQueue.DispatchAsync (() => { + var message = NSBundle.MainBundle.LocalizedString (@"AVCam doesn't have permission to use the camera, please change privacy settings", @"Alert message when the user has denied access to the camera"); + var alertController = UIAlertController.Create (@"AVCam", message, UIAlertControllerStyle.Alert); + var cancelAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"OK", @"Alert OK button"), UIAlertActionStyle.Cancel, null); + alertController.AddAction (cancelAction); + // Provide quick access to Settings. + var settingsAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"Settings", @"Alert button to open Settings"), UIAlertActionStyle.Default, (action) => { + UIApplication.SharedApplication.OpenUrl (new NSUrl (UIApplication.OpenSettingsUrlString)); }); - break; - case AVCamSetupResult.SessionConfigurationFailed: - sessionQueue.DispatchAsync (() => - { - var message = NSBundle.MainBundle.LocalizedString (@"Unable to capture media", @"Alert message when something goes wrong during capture session configuration"); - var alertController = UIAlertController.Create (@"AVCam", message, UIAlertControllerStyle.Alert); - var cancelAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"OK", @"Alert OK button"), UIAlertActionStyle.Cancel, null); - alertController.AddAction (cancelAction); - PresentViewController (alertController, true, null); - } ); - break; + alertController.AddAction (settingsAction); + PresentViewController (alertController, true, null); + }); + break; + case AVCamSetupResult.SessionConfigurationFailed: + sessionQueue.DispatchAsync (() => { + var message = NSBundle.MainBundle.LocalizedString (@"Unable to capture media", @"Alert message when something goes wrong during capture session configuration"); + var alertController = UIAlertController.Create (@"AVCam", message, UIAlertControllerStyle.Alert); + var cancelAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"OK", @"Alert OK button"), UIAlertActionStyle.Cancel, null); + alertController.AddAction (cancelAction); + PresentViewController (alertController, true, null); + }); + break; } }); } @@ -162,10 +154,8 @@ public override void ViewDidDisappear (bool animated) { base.ViewDidDisappear (animated); - sessionQueue.DispatchAsync (() => - { - if (setupResult == AVCamSetupResult.Success) - { + sessionQueue.DispatchAsync (() => { + if (setupResult == AVCamSetupResult.Success) { session.StopRunning (); RemoveObservers (); } @@ -189,47 +179,44 @@ public override void ViewWillTransitionToSize (CoreGraphics.CGSize toSize, IUIVi var deviceOrientation = UIDevice.CurrentDevice.Orientation; - if (deviceOrientation.IsPortrait () || deviceOrientation.IsLandscape ()) - { - PreviewView.VideoPreviewLayer.Connection.VideoOrientation = (AVCaptureVideoOrientation)deviceOrientation; + if (deviceOrientation.IsPortrait () || deviceOrientation.IsLandscape ()) { + PreviewView.VideoPreviewLayer.Connection.VideoOrientation = (AVCaptureVideoOrientation) deviceOrientation; } } // Call this on the session queue. void ConfigureSession () { - if (setupResult != AVCamSetupResult.Success) - { + if (setupResult != AVCamSetupResult.Success) { return; } NSError error = null; session.BeginConfiguration (); - + /* We do not create an AVCaptureMovieFileOutput when setting up the session because the AVCaptureMovieFileOutput does not support movie recording with AVCaptureSessionPresetPhoto. */ session.SessionPreset = AVCaptureSession.PresetPhoto; - + // Add video input. - + // Choose the back dual camera if available, otherwise default to a wide angle camera. - var videoDevice = AVCaptureDevice.GetDefaultDevice (AVCaptureDeviceType.BuiltInDualCamera, AVMediaType.Video,AVCaptureDevicePosition.Back); - if ( videoDevice == null) { + var videoDevice = AVCaptureDevice.GetDefaultDevice (AVCaptureDeviceType.BuiltInDualCamera, AVMediaType.Video, AVCaptureDevicePosition.Back); + if (videoDevice == null) { // If the back dual camera is not available, default to the back wide angle camera. videoDevice = AVCaptureDevice.GetDefaultDevice (AVCaptureDeviceType.BuiltInWideAngleCamera, AVMediaType.Video, AVCaptureDevicePosition.Back); - + // In some cases where users break their phones, the back wide angle camera is not available. In this case, we should default to the front wide angle camera. - if (videoDevice == null) - { + if (videoDevice == null) { videoDevice = AVCaptureDevice.GetDefaultDevice (AVCaptureDeviceType.BuiltInWideAngleCamera, AVMediaType.Video, AVCaptureDevicePosition.Front); } } var lVideoDeviceInput = AVCaptureDeviceInput.FromDevice (videoDevice, out error); - if ( lVideoDeviceInput == null ) { - Console.WriteLine ( $"Could not create video device input: {error}" ); + if (lVideoDeviceInput == null) { + Console.WriteLine ($"Could not create video device input: {error}"); setupResult = AVCamSetupResult.SessionConfigurationFailed; session.CommitConfiguration (); return; @@ -251,40 +238,37 @@ Use the status bar orientation as the initial video orientation. Subsequent orie */ var statusBarOrientation = UIApplication.SharedApplication.StatusBarOrientation; var initialVideoOrientation = AVCaptureVideoOrientation.Portrait; - if (statusBarOrientation != UIInterfaceOrientation.Unknown) - { - initialVideoOrientation = (AVCaptureVideoOrientation)statusBarOrientation; + if (statusBarOrientation != UIInterfaceOrientation.Unknown) { + initialVideoOrientation = (AVCaptureVideoOrientation) statusBarOrientation; } PreviewView.VideoPreviewLayer.Connection.VideoOrientation = initialVideoOrientation; - } ); - } - else { - Console.WriteLine ( @"Could not add video device input to the session" ); + }); + } else { + Console.WriteLine (@"Could not add video device input to the session"); setupResult = AVCamSetupResult.SessionConfigurationFailed; session.CommitConfiguration (); return; } - + // Add audio input. var audioDevice = AVCaptureDevice.GetDefaultDevice (AVMediaType.Audio); var audioDeviceInput = AVCaptureDeviceInput.FromDevice (audioDevice, out error); if (audioDeviceInput == null) { - Console.WriteLine ( $"Could not create audio device input: {error}"); + Console.WriteLine ($"Could not create audio device input: {error}"); } if (session.CanAddInput (audioDeviceInput)) { session.AddInput (audioDeviceInput); - } - else { - Console.WriteLine ( @"Could not add audio device input to the session" ); + } else { + Console.WriteLine (@"Could not add audio device input to the session"); } // Add photo output. var lPhotoOutput = new AVCapturePhotoOutput (); - if (session.CanAddOutput (lPhotoOutput) ) { + if (session.CanAddOutput (lPhotoOutput)) { session.AddOutput (lPhotoOutput); photoOutput = lPhotoOutput; - + photoOutput.IsHighResolutionCaptureEnabled = true; photoOutput.IsLivePhotoCaptureEnabled = photoOutput.IsLivePhotoCaptureSupported; photoOutput.IsDepthDataDeliveryEnabled (photoOutput.IsDepthDataDeliverySupported ()); @@ -295,14 +279,13 @@ Use the status bar orientation as the initial video orientation. Subsequent orie inProgressPhotoCaptureDelegates = new Dictionary<long, AVCamPhotoCaptureDelegate> (); inProgressLivePhotoCapturesCount = 0; - } - else { - Console.WriteLine ( @"Could not add photo output to the session" ); + } else { + Console.WriteLine (@"Could not add photo output to the session"); setupResult = AVCamSetupResult.SessionConfigurationFailed; session.CommitConfiguration (); return; } - + backgroundRecordingId = UIApplication.BackgroundTaskInvalid; session.CommitConfiguration (); @@ -310,8 +293,7 @@ Use the status bar orientation as the initial video orientation. Subsequent orie partial void ResumeInterruptedSession (NSObject sender) { - sessionQueue.DispatchAsync (() => - { + sessionQueue.DispatchAsync (() => { /* The session might fail to start running, e.g., if a phone or FaceTime call is still using audio or video. A failure to start the session running will be communicated via @@ -321,28 +303,25 @@ a session runtime error notification. To avoid repeatedly failing to start the s */ session.StartRunning (); sessionRunning = session.Running; - if (!session.Running) - { + if (!session.Running) { DispatchQueue.MainQueue.DispatchAsync (() => { var message = NSBundle.MainBundle.LocalizedString (@"Unable to resume", @"Alert message when unable to resume the session running"); var alertController = UIAlertController.Create (@"AVCam", message, UIAlertControllerStyle.Alert); var cancelAction = UIAlertAction.Create (NSBundle.MainBundle.LocalizedString (@"OK", @"Alert OK button"), UIAlertActionStyle.Cancel, null); alertController.AddAction (cancelAction); PresentViewController (alertController, true, null); - } ); - } - else { + }); + } else { DispatchQueue.MainQueue.DispatchAsync (() => { ResumeButton.Hidden = true; - } ); + }); } }); } partial void ToggleCaptureMode (UISegmentedControl captureModeControl) { - if (captureModeControl.SelectedSegment == (int)AVCamCaptureMode.Photo) - { + if (captureModeControl.SelectedSegment == (int) AVCamCaptureMode.Photo) { RecordButton.Enabled = false; sessionQueue.DispatchAsync (() => { @@ -357,15 +336,15 @@ capture is not supported when an AVCaptureMovieFileOutput is connected to the se session.CommitConfiguration (); movieFileOutput = null; - - if (photoOutput.IsLivePhotoCaptureSupported ) { + + if (photoOutput.IsLivePhotoCaptureSupported) { photoOutput.IsLivePhotoCaptureEnabled = true; DispatchQueue.MainQueue.DispatchAsync (() => { LivePhotoModeButton.Enabled = true; LivePhotoModeButton.Hidden = false; - } ); + }); } if (photoOutput.IsDepthDataDeliverySupported ()) { @@ -375,11 +354,10 @@ capture is not supported when an AVCaptureMovieFileOutput is connected to the se DispatchQueue.MainQueue.DispatchAsync (() => { DepthDataDeliveryButton.Hidden = false; DepthDataDeliveryButton.Enabled = true; - } ); + }); } - } ); - } - else if (captureModeControl.SelectedSegment == (int)AVCamCaptureMode.Movie ) { + }); + } else if (captureModeControl.SelectedSegment == (int) AVCamCaptureMode.Movie) { LivePhotoModeButton.Hidden = true; DepthDataDeliveryButton.Hidden = true; @@ -387,13 +365,12 @@ capture is not supported when an AVCaptureMovieFileOutput is connected to the se sessionQueue.DispatchAsync (() => { var lMovieFileOutput = new AVCaptureMovieFileOutput (); - if ( session.CanAddOutput (lMovieFileOutput)) - { + if (session.CanAddOutput (lMovieFileOutput)) { session.BeginConfiguration (); session.AddOutput (lMovieFileOutput); session.SessionPreset = AVCaptureSession.PresetHigh; var connection = lMovieFileOutput.ConnectionFromMediaType (AVMediaType.Video); - if (connection.SupportsVideoStabilization ) { + if (connection.SupportsVideoStabilization) { connection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } session.CommitConfiguration (); @@ -403,9 +380,9 @@ capture is not supported when an AVCaptureMovieFileOutput is connected to the se DispatchQueue.MainQueue.DispatchAsync (() => { RecordButton.Enabled = true; - } ); + }); } - } ); + }); } } @@ -424,59 +401,52 @@ partial void ChangeCamera (NSObject sender) AVCaptureDevicePosition preferredPosition = AVCaptureDevicePosition.Unspecified; AVCaptureDeviceType preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; - switch (currentPosition) - { - //case AVCaptureDevicePosition.Unspecified: - //preferredPosition = AVCaptureDevicePosition.Back; - //preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; - //break; - case AVCaptureDevicePosition.Unspecified: - case AVCaptureDevicePosition.Front: - preferredPosition = AVCaptureDevicePosition.Back; - preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; - break; - case AVCaptureDevicePosition.Back: - preferredPosition = AVCaptureDevicePosition.Front; - preferredDeviceType = AVCaptureDeviceType.BuiltInWideAngleCamera; - break; + switch (currentPosition) { + //case AVCaptureDevicePosition.Unspecified: + //preferredPosition = AVCaptureDevicePosition.Back; + //preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; + //break; + case AVCaptureDevicePosition.Unspecified: + case AVCaptureDevicePosition.Front: + preferredPosition = AVCaptureDevicePosition.Back; + preferredDeviceType = AVCaptureDeviceType.BuiltInDualCamera; + break; + case AVCaptureDevicePosition.Back: + preferredPosition = AVCaptureDevicePosition.Front; + preferredDeviceType = AVCaptureDeviceType.BuiltInWideAngleCamera; + break; } var devices = videoDeviceDiscoverySession.Devices; AVCaptureDevice newVideoDevice = null; - + // First, look for a device with both the preferred position and device type. - foreach (var device in devices) - { - if (device.Position == preferredPosition && device.DeviceType.GetConstant () == preferredDeviceType.GetConstant ()) - { + foreach (var device in devices) { + if (device.Position == preferredPosition && device.DeviceType.GetConstant () == preferredDeviceType.GetConstant ()) { newVideoDevice = device; break; } } // Otherwise, look for a device with only the preferred position. - if (newVideoDevice == null) - { - foreach (var device in devices) - { - if (device.Position == preferredPosition) - { + if (newVideoDevice == null) { + foreach (var device in devices) { + if (device.Position == preferredPosition) { newVideoDevice = device; break; } } } - if (newVideoDevice != null) - { + if (newVideoDevice != null) { var lVideoDeviceInput = AVCaptureDeviceInput.FromDevice (newVideoDevice); session.BeginConfiguration (); // Remove the existing device input first, since using the front and back camera simultaneously is not supported. session.RemoveInput (videoDeviceInput); - - if ( session.CanAddInput (lVideoDeviceInput) ) { + + if (session.CanAddInput (lVideoDeviceInput)) { if (subjectAreaDidChangeObserver != null) subjectAreaDidChangeObserver.Dispose (); @@ -484,20 +454,17 @@ partial void ChangeCamera (NSObject sender) session.AddInput (lVideoDeviceInput); videoDeviceInput = lVideoDeviceInput; - } - else { + } else { session.AddInput (videoDeviceInput); } - if (movieFileOutput != null) - { + if (movieFileOutput != null) { var movieFileOutputConnection = movieFileOutput.ConnectionFromMediaType (AVMediaType.Video); - if (movieFileOutputConnection.SupportsVideoStabilization) - { + if (movieFileOutputConnection.SupportsVideoStabilization) { movieFileOutputConnection.PreferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.Auto; } } - + /* Set Live Photo capture and depth data delivery if it is supported. When changing cameras, the `livePhotoCaptureEnabled` and `depthDataDeliveryEnabled` properties of the AVCapturePhotoOutput gets set to NO when @@ -505,7 +472,7 @@ partial void ChangeCamera (NSObject sender) added to the session, re-enable Live Photo capture and depth data delivery if they are supported. */ photoOutput.IsLivePhotoCaptureEnabled = photoOutput.IsLivePhotoCaptureSupported; - photoOutput.IsDepthDataDeliveryEnabled(photoOutput.IsDepthDataDeliverySupported ()); + photoOutput.IsDepthDataDeliveryEnabled (photoOutput.IsDepthDataDeliverySupported ()); session.CommitConfiguration (); } @@ -513,14 +480,14 @@ partial void ChangeCamera (NSObject sender) DispatchQueue.MainQueue.DispatchAsync (() => { CameraButton.Enabled = true; - RecordButton.Enabled = CaptureModeControl.SelectedSegment == (int)AVCamCaptureMode.Movie; + RecordButton.Enabled = CaptureModeControl.SelectedSegment == (int) AVCamCaptureMode.Movie; PhotoButton.Enabled = true; LivePhotoModeButton.Enabled = true; CaptureModeControl.Enabled = true; DepthDataDeliveryButton.Enabled = photoOutput.IsDepthDataDeliveryEnabled (); DepthDataDeliveryButton.Hidden = !photoOutput.IsDepthDataDeliverySupported (); - } ); - } ); + }); + }); } partial void FocusAndExposeTap (UIGestureRecognizer gestureRecognizer) @@ -534,16 +501,16 @@ void FocusWithMode (AVCaptureFocusMode focusMode, AVCaptureExposureMode exposure sessionQueue.DispatchAsync (() => { var device = videoDeviceInput.Device; NSError error = null; - if ( device.LockForConfiguration (out error )) { + if (device.LockForConfiguration (out error)) { /* Setting (focus/exposure)PointOfInterest alone does not initiate a (focus/exposure) operation. Call set(Focus/Exposure)Mode() to apply the new point of interest. */ - if (device.FocusPointOfInterestSupported && device.IsFocusModeSupported (focusMode) ) { + if (device.FocusPointOfInterestSupported && device.IsFocusModeSupported (focusMode)) { device.FocusPointOfInterest = point; device.FocusMode = focusMode; } - + if (device.ExposurePointOfInterestSupported && device.IsExposureModeSupported (exposureMode)) { device.ExposurePointOfInterest = point; device.ExposureMode = exposureMode; @@ -551,11 +518,10 @@ void FocusWithMode (AVCaptureFocusMode focusMode, AVCaptureExposureMode exposure device.SubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange; device.UnlockForConfiguration (); + } else { + Console.WriteLine ($"Could not lock device for configuration: {error}"); } - else { - Console.WriteLine ( $"Could not lock device for configuration: {error}"); - } - } ); + }); } partial void CapturePhoto (NSObject sender) @@ -576,38 +542,29 @@ the main thread and session configuration is done on the session queue. AVCapturePhotoSettings photoSettings; // Capture HEIF photo when supported, with flash set to auto and high resolution photo enabled. - if ( photoOutput.AvailablePhotoCodecTypes.Where (codec => codec == AVVideo2.CodecHEVC).Any ()) - { + if (photoOutput.AvailablePhotoCodecTypes.Where (codec => codec == AVVideo2.CodecHEVC).Any ()) { photoSettings = AVCapturePhotoSettings.FromFormat (new NSDictionary<NSString, NSObject> (AVVideo.CodecKey, AVVideo2.CodecHEVC)); - } - else - { + } else { photoSettings = AVCapturePhotoSettings.Create (); } - if (videoDeviceInput.Device.FlashAvailable) - { + if (videoDeviceInput.Device.FlashAvailable) { photoSettings.FlashMode = AVCaptureFlashMode.Auto; } photoSettings.IsHighResolutionPhotoEnabled = true; - if (photoSettings.AvailablePreviewPhotoPixelFormatTypes.Count () > 0) - { + if (photoSettings.AvailablePreviewPhotoPixelFormatTypes.Count () > 0) { photoSettings.PreviewPhotoFormat = new NSDictionary<NSString, NSObject> (CoreVideo.CVPixelBuffer.PixelFormatTypeKey, photoSettings.AvailablePreviewPhotoPixelFormatTypes.First ()); } - if (livePhotoMode == AVCamLivePhotoMode.On && photoOutput.IsLivePhotoCaptureSupported) - { + if (livePhotoMode == AVCamLivePhotoMode.On && photoOutput.IsLivePhotoCaptureSupported) { // Live Photo capture is not supported in movie mode. var livePhotoMovieFileName = Guid.NewGuid ().ToString (); var livePhotoMovieFilePath = NSFileManager.DefaultManager.GetTemporaryDirectory ().Append ($"{livePhotoMovieFileName}.mov", false); photoSettings.LivePhotoMovieFileUrl = livePhotoMovieFilePath; } - if (depthDataDeliveryMode == AVCamDepthDataDeliveryMode.On && photoOutput.IsDepthDataDeliverySupported ()) - { + if (depthDataDeliveryMode == AVCamDepthDataDeliveryMode.On && photoOutput.IsDepthDataDeliverySupported ()) { photoSettings.IsDepthDataDeliveryEnabled (true); - } - else - { + } else { photoSettings.IsDepthDataDeliveryEnabled (false); } @@ -618,54 +575,46 @@ the main thread and session configuration is done on the session queue. UIView.Animate (0.25, () => { PreviewView.VideoPreviewLayer.Opacity = 1.0f; }); - } ); - }, (bool capturing ) => { + }); + }, (bool capturing) => { /* Because Live Photo captures can overlap, we need to keep track of the number of in progress Live Photo captures to ensure that the Live Photo label stays visible during these captures. */ sessionQueue.DispatchAsync (() => { - if (capturing) - { + if (capturing) { inProgressLivePhotoCapturesCount++; - } - else - { + } else { inProgressLivePhotoCapturesCount--; } var lInProgressLivePhotoCapturesCount = inProgressLivePhotoCapturesCount; DispatchQueue.MainQueue.DispatchAsync (() => { - if (lInProgressLivePhotoCapturesCount > 0) - { + if (lInProgressLivePhotoCapturesCount > 0) { CapturingLivePhotoLabel.Hidden = false; - } - else if (lInProgressLivePhotoCapturesCount == 0) - { + } else if (lInProgressLivePhotoCapturesCount == 0) { CapturingLivePhotoLabel.Hidden = true; - } - else - { + } else { Console.WriteLine (@"Error: In progress live photo capture count is less than 0"); } - } ); - } ); - }, (AVCamPhotoCaptureDelegate lPhotoCaptureDelegate ) => { + }); + }); + }, (AVCamPhotoCaptureDelegate lPhotoCaptureDelegate) => { // When the capture is complete, remove a reference to the photo capture delegate so it can be deallocated. sessionQueue.DispatchAsync (() => { - inProgressPhotoCaptureDelegates[lPhotoCaptureDelegate.RequestedPhotoSettings.UniqueID] = null; - } ); + inProgressPhotoCaptureDelegates [lPhotoCaptureDelegate.RequestedPhotoSettings.UniqueID] = null; + }); }); - + /* The Photo Output keeps a weak reference to the photo capture delegate so we store it in an array to maintain a strong reference to this object until the capture is completed. */ - inProgressPhotoCaptureDelegates[photoCaptureDelegate.RequestedPhotoSettings.UniqueID] = photoCaptureDelegate; + inProgressPhotoCaptureDelegates [photoCaptureDelegate.RequestedPhotoSettings.UniqueID] = photoCaptureDelegate; photoOutput.CapturePhoto (photoSettings, photoCaptureDelegate); - } ); + }); } partial void ToggleLivePhotoMode (UIButton livePhotoModeButton) @@ -674,16 +623,14 @@ partial void ToggleLivePhotoMode (UIButton livePhotoModeButton) livePhotoMode = (livePhotoMode == AVCamLivePhotoMode.On) ? AVCamLivePhotoMode.Off : AVCamLivePhotoMode.On; var lLivePhotoMode = livePhotoMode; - DispatchQueue.MainQueue.DispatchAsync ( () => { - if (lLivePhotoMode == AVCamLivePhotoMode.On) - { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (lLivePhotoMode == AVCamLivePhotoMode.On) { LivePhotoModeButton.SetTitle (NSBundle.MainBundle.LocalizedString (@"Live Photo Mode: On", @"Live photo mode button on title"), UIControlState.Normal); - } - else { + } else { LivePhotoModeButton.SetTitle (NSBundle.MainBundle.LocalizedString (@"Live Photo Mode: Off", @"Live photo mode button off title"), UIControlState.Normal); } - } ); - } ); + }); + }); } partial void ToggleDepthDataDeliveryMode (UIButton depthDataDeliveryButton) @@ -693,17 +640,15 @@ partial void ToggleDepthDataDeliveryMode (UIButton depthDataDeliveryButton) var lDepthDataDeliveryMode = depthDataDeliveryMode; DispatchQueue.MainQueue.DispatchAsync (() => { - if (lDepthDataDeliveryMode == AVCamDepthDataDeliveryMode.On) - { + if (lDepthDataDeliveryMode == AVCamDepthDataDeliveryMode.On) { DepthDataDeliveryButton.SetTitle (NSBundle.MainBundle.LocalizedString (@"Depth Data Delivery: On", @"Depth Data mode button on title"), UIControlState.Normal); - } - else { + } else { DepthDataDeliveryButton.SetTitle (NSBundle.MainBundle.LocalizedString (@"Depth Data Delivery: Off", @"Depth Data mode button off title"), UIControlState.Normal); } - } ); - } ); + }); + }); } partial void ToggleMovieRecording (NSObject sender) @@ -726,10 +671,8 @@ accessed on the main thread and session configuration is done on the session que var videoPreviewLayerVideoOrientation = PreviewView.VideoPreviewLayer.Connection.VideoOrientation; sessionQueue.DispatchAsync (() => { - if (!movieFileOutput.Recording) - { - if ( UIDevice.CurrentDevice.IsMultitaskingSupported) - { + if (!movieFileOutput.Recording) { + if (UIDevice.CurrentDevice.IsMultitaskingSupported) { /* Setup background task. This is needed because the -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:] @@ -746,8 +689,7 @@ This also ensures that there will be time to write the file to the photo library movieFileOutputConnection.VideoOrientation = videoPreviewLayerVideoOrientation; // Use HEVC codec if supported - if ( movieFileOutput.AvailableVideoCodecTypes.Where (codec => codec == AVVideo2.CodecHEVC).Any ()) - { + if (movieFileOutput.AvailableVideoCodecTypes.Where (codec => codec == AVVideo2.CodecHEVC).Any ()) { movieFileOutput.SetOutputSettings (new NSDictionary (AVVideo.CodecKey, AVVideo2.CodecHEVC), movieFileOutputConnection); } @@ -755,24 +697,23 @@ This also ensures that there will be time to write the file to the photo library var outputFileName = Guid.NewGuid ().ToString (); var livePhotoMovieFilePath = NSFileManager.DefaultManager.GetTemporaryDirectory ().Append ($"{outputFileName}.mov", false); movieFileOutput.StartRecordingToOutputFile (livePhotoMovieFilePath, this); - } - else { + } else { movieFileOutput.StopRecording (); } - } ); + }); } [Export ("captureOutput:didStartRecordingToOutputFileAtURL:fromConnections:")] - public void DidStartRecording (AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject[] connections) + public void DidStartRecording (AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject [] connections) { // Enable the Record button to let the user stop the recording. DispatchQueue.MainQueue.DispatchAsync (() => { RecordButton.Enabled = true; - RecordButton.SetTitle (NSBundle.MainBundle.LocalizedString(@"Stop", @"Recording button stop title"), UIControlState.Normal); + RecordButton.SetTitle (NSBundle.MainBundle.LocalizedString (@"Stop", @"Recording button stop title"), UIControlState.Normal); }); } - public void FinishedRecording (AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject[] connections, NSError error) + public void FinishedRecording (AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject [] connections, NSError error) { /* Note that currentBackgroundRecordingID is used to end the background task @@ -788,54 +729,52 @@ not overwrite a recording currently being saved. backgroundRecordingId = UIApplication.BackgroundTaskInvalid; Action cleanup = () => { - if ( NSFileManager.DefaultManager.FileExists (outputFileUrl.Path) ) { + if (NSFileManager.DefaultManager.FileExists (outputFileUrl.Path)) { NSError tError; NSFileManager.DefaultManager.Remove (outputFileUrl.Path, out tError); } - - if (currentBackgroundRecordingId != UIApplication.BackgroundTaskInvalid ) { + + if (currentBackgroundRecordingId != UIApplication.BackgroundTaskInvalid) { UIApplication.SharedApplication.EndBackgroundTask (currentBackgroundRecordingId); } }; - + var success = true; - - if (error != null ) { - Console.WriteLine ( $"Movie file finishing error: {error}"); - var tmpObj = error.UserInfo[AVErrorKeys.RecordingSuccessfullyFinished]; - if (tmpObj is NSNumber) success = ((NSNumber)tmpObj).BoolValue; - else if (tmpObj is NSString) success = ((NSString)tmpObj).BoolValue (); + + if (error != null) { + Console.WriteLine ($"Movie file finishing error: {error}"); + var tmpObj = error.UserInfo [AVErrorKeys.RecordingSuccessfullyFinished]; + if (tmpObj is NSNumber) success = ((NSNumber) tmpObj).BoolValue; + else if (tmpObj is NSString) success = ((NSString) tmpObj).BoolValue (); } - if (success ) { + if (success) { // Check authorization status. - PHPhotoLibrary.RequestAuthorization (( PHAuthorizationStatus status ) => { - if ( status == PHAuthorizationStatus.Authorized ) { + PHPhotoLibrary.RequestAuthorization ((PHAuthorizationStatus status) => { + if (status == PHAuthorizationStatus.Authorized) { // Save the movie file to the photo library and cleanup. PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { var options = new PHAssetResourceCreationOptions (); options.ShouldMoveFile = true; var creationRequest = PHAssetCreationRequest.CreationRequestForAsset (); creationRequest.AddResource (PHAssetResourceType.Video, outputFileUrl, options); - },(cbSuccess, cbError) => { - if ( ! cbSuccess ) { - Console.WriteLine ( $"Could not save movie to photo library: {cbError}"); + }, (cbSuccess, cbError) => { + if (!cbSuccess) { + Console.WriteLine ($"Could not save movie to photo library: {cbError}"); } cleanup (); }); - } - else { + } else { cleanup (); } }); - } - else { + } else { cleanup (); } // Enable the Camera and Record buttons to let the user switch camera and start another recording. - DispatchQueue.MainQueue.DispatchAsync ( () => { + DispatchQueue.MainQueue.DispatchAsync (() => { // Only enable the ability to change camera if the device has more than one camera. - CameraButton.Enabled = (videoDeviceDiscoverySession.UniqueDevicePositionsCount() > 1); + CameraButton.Enabled = (videoDeviceDiscoverySession.UniqueDevicePositionsCount () > 1); RecordButton.Enabled = true; CaptureModeControl.Enabled = true; RecordButton.SetTitle (NSBundle.MainBundle.LocalizedString (@"Record", @"Recording button record title"), UIControlState.Normal); @@ -871,16 +810,16 @@ private void RemoveObservers () subjectAreaDidChangeObserver.Dispose (); subjectAreaDidChangeObserver = null; - observerList.ForEach ( i => i.Dispose ()); + observerList.ForEach (i => i.Dispose ()); observerList.Clear (); } void ObserveNewSession (NSObservedChange change) { - bool isSessionRunning = false ; + bool isSessionRunning = false; NSObject tmpObj = change.NewValue; - if (tmpObj is NSNumber) isSessionRunning = ((NSNumber)tmpObj).BoolValue; - else if (tmpObj is NSString) isSessionRunning = ((NSString)tmpObj).BoolValue (); + if (tmpObj is NSNumber) isSessionRunning = ((NSNumber) tmpObj).BoolValue; + else if (tmpObj is NSString) isSessionRunning = ((NSString) tmpObj).BoolValue (); var livePhotoCaptureSupported = photoOutput.IsLivePhotoCaptureSupported; var livePhotoCaptureEnabled = photoOutput.IsLivePhotoCaptureEnabled; @@ -889,14 +828,14 @@ void ObserveNewSession (NSObservedChange change) DispatchQueue.MainQueue.DispatchAsync (() => { // Only enable the ability to change camera if the device has more than one camera. - CameraButton.Enabled = isSessionRunning && (videoDeviceDiscoverySession.UniqueDevicePositionsCount() > 1); - RecordButton.Enabled = isSessionRunning && (CaptureModeControl.SelectedSegment == (int)AVCamCaptureMode.Movie); + CameraButton.Enabled = isSessionRunning && (videoDeviceDiscoverySession.UniqueDevicePositionsCount () > 1); + RecordButton.Enabled = isSessionRunning && (CaptureModeControl.SelectedSegment == (int) AVCamCaptureMode.Movie); PhotoButton.Enabled = isSessionRunning; CaptureModeControl.Enabled = isSessionRunning; LivePhotoModeButton.Enabled = isSessionRunning && livePhotoCaptureEnabled; - LivePhotoModeButton.Hidden = !(isSessionRunning && livePhotoCaptureSupported);DepthDataDeliveryButton.Enabled = isSessionRunning && depthDataDeliveryEnabled; + LivePhotoModeButton.Hidden = !(isSessionRunning && livePhotoCaptureSupported); DepthDataDeliveryButton.Enabled = isSessionRunning && depthDataDeliveryEnabled; DepthDataDeliveryButton.Hidden = !(isSessionRunning && depthDataDeliverySupported); - } ); + }); } void SubjectAreaDidChange (NSNotification notification) @@ -907,7 +846,7 @@ void SubjectAreaDidChange (NSNotification notification) void SessionRuntimeError (NSNotification notification) { - NSError error = notification.UserInfo[AVCaptureSession.ErrorKey] as NSError; + NSError error = notification.UserInfo [AVCaptureSession.ErrorKey] as NSError; if (error == null) { ResumeButton.Hidden = false; return; @@ -919,22 +858,18 @@ void SessionRuntimeError (NSNotification notification) reset and the last start running succeeded. Otherwise, enable the user to try to resume the session running. */ - if (error.Code == (int)AVError.MediaServicesWereReset) - { + if (error.Code == (int) AVError.MediaServicesWereReset) { sessionQueue.DispatchAsync (() => { - if (sessionRunning) - { + if (sessionRunning) { session.StartRunning (); sessionRunning = session.Running; - } - else { + } else { DispatchQueue.MainQueue.DispatchAsync (() => { ResumeButton.Hidden = false; - } ); + }); } - } ); - } - else { + }); + } else { ResumeButton.Hidden = false; } } @@ -951,16 +886,13 @@ music playback in control center will not automatically resume the session */ var showResumeButton = false; - var reason = (AVCaptureSessionInterruptionReason)(notification.UserInfo[AVCaptureSession.InterruptionReasonKey] as NSNumber).Int32Value; - Console.WriteLine ($"Capture session was interrupted with reason {(int)reason}"); + var reason = (AVCaptureSessionInterruptionReason) (notification.UserInfo [AVCaptureSession.InterruptionReasonKey] as NSNumber).Int32Value; + Console.WriteLine ($"Capture session was interrupted with reason {(int) reason}"); if (reason == AVCaptureSessionInterruptionReason.AudioDeviceInUseByAnotherClient || - reason == AVCaptureSessionInterruptionReason.VideoDeviceInUseByAnotherClient) - { + reason == AVCaptureSessionInterruptionReason.VideoDeviceInUseByAnotherClient) { showResumeButton = true; - } - else if (reason == AVCaptureSessionInterruptionReason.VideoDeviceNotAvailableWithMultipleForegroundApps) - { + } else if (reason == AVCaptureSessionInterruptionReason.VideoDeviceNotAvailableWithMultipleForegroundApps) { // Simply fade-in a label to inform the user that the camera is unavailable. CameraUnavailableLabel.Alpha = 0.0f; CameraUnavailableLabel.Hidden = false; @@ -968,8 +900,8 @@ music playback in control center will not automatically resume the session CameraUnavailableLabel.Alpha = 1.0f; }); } - - if (showResumeButton ) { + + if (showResumeButton) { // Simply fade-in a button to enable the user to try to resume the session running. ResumeButton.Alpha = 0.0f; ResumeButton.Hidden = false; @@ -983,8 +915,7 @@ void SessionInterruptionEnded (NSNotification notification) { Console.WriteLine (@"Capture session interruption ended"); - if (!ResumeButton.Hidden) - { + if (!ResumeButton.Hidden) { UIView.Animate (0.25, () => { ResumeButton.Alpha = 0.0f; }, @@ -992,7 +923,7 @@ void SessionInterruptionEnded (NSNotification notification) ResumeButton.Hidden = true; }); } - if ( ! CameraUnavailableLabel.Hidden ) { + if (!CameraUnavailableLabel.Hidden) { UIView.Animate (0.25, () => { CameraUnavailableLabel.Alpha = 0.0f; }, @@ -1007,45 +938,38 @@ void SessionInterruptionEnded (NSNotification notification) - enum AVCamSetupResult - { + enum AVCamSetupResult { Success, CameraNotAuthorized, SessionConfigurationFailed }; - enum AVCamCaptureMode - { + enum AVCamCaptureMode { Photo = 0, Movie = 1 }; - enum AVCamLivePhotoMode - { + enum AVCamLivePhotoMode { On, Off }; - enum AVCamDepthDataDeliveryMode - { + enum AVCamDepthDataDeliveryMode { On, Off }; - static class AVCaptureDeviceDiscoverySessionUtilities - { + static class AVCaptureDeviceDiscoverySessionUtilities { public static int UniqueDevicePositionsCount (this AVCaptureDeviceDiscoverySession session) { var uniqueDevicePositions = new List<AVCaptureDevicePosition> (); - - foreach (AVCaptureDevice device in session.Devices) - { - if (!uniqueDevicePositions.Contains (device.Position)) - { + + foreach (AVCaptureDevice device in session.Devices) { + if (!uniqueDevicePositions.Contains (device.Position)) { uniqueDevicePositions.Add (device.Position); } } - + return uniqueDevicePositions.Count; } } diff --git a/ios11/AVCam/src/AVCamPhotoCaptureDelegate.cs b/ios11/AVCam/src/AVCamPhotoCaptureDelegate.cs index 754a4d296..8065adbca 100644 --- a/ios11/AVCam/src/AVCamPhotoCaptureDelegate.cs +++ b/ios11/AVCam/src/AVCamPhotoCaptureDelegate.cs @@ -1,134 +1,119 @@ -using System; +using System; using AVFoundation; using CoreMedia; using Foundation; -namespace AVCam -{ - public class AVCamPhotoCaptureDelegate : NSObject, IAVCapturePhotoCaptureDelegate - { - public AVCapturePhotoSettings RequestedPhotoSettings { get; set; } - Action WillCapturePhotoAnimation { get; set; } - Action<bool> LivePhotoCaptureHandler { get; set; } - Action<AVCamPhotoCaptureDelegate> CompletionHandler { get; set; } - NSData PhotoData { get; set; } - NSUrl LivePhotoCompanionMovieUrl { get; set; } - - public AVCamPhotoCaptureDelegate (AVCapturePhotoSettings requestedPhotoSettings, Action willCapturePhotoAnimation, Action<bool> livePhotoCaptureHandler, Action<AVCamPhotoCaptureDelegate> completionHandler) - { - RequestedPhotoSettings = requestedPhotoSettings; - WillCapturePhotoAnimation = willCapturePhotoAnimation; - LivePhotoCaptureHandler = livePhotoCaptureHandler; - CompletionHandler = completionHandler; - } - - void DidFinish () - { - if (LivePhotoCompanionMovieUrl != null && NSFileManager.DefaultManager.FileExists (LivePhotoCompanionMovieUrl.Path)) - { - NSError error; - NSFileManager.DefaultManager.Remove (LivePhotoCompanionMovieUrl.Path, out error); - - if (error != null) - Console.WriteLine ($"Could not remove file at url: {LivePhotoCompanionMovieUrl.Path}"); - } - - CompletionHandler (this); - } - - [Export ("captureOutput:willBeginCaptureForResolvedSettings:")] - public virtual void WillBeginCapture (AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings) - { - if ((resolvedSettings.LivePhotoMovieDimensions.Width > 0) && (resolvedSettings.LivePhotoMovieDimensions.Height > 0)) - { - LivePhotoCaptureHandler (true); - } - } - - [Export ("captureOutput:willCapturePhotoForResolvedSettings:")] - public virtual void WillCapturePhoto (AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings) - { - WillCapturePhotoAnimation (); - } - - [Export ("captureOutput:didFinishProcessingPhoto:error:")] - public virtual void DidFinishProcessingPhoto (AVCapturePhotoOutput captureOutput, AVCapturePhoto photo, NSError error) - { - if (error != null) - { - Console.WriteLine ($"Error capturing photo: {error}", error); - return; - } - PhotoData = photo.FileDataRepresentation (); - } - - [Export ("captureOutput:didFinishRecordingLivePhotoMovieForEventualFileAtURL:resolvedSettings:")] - public virtual void DidFinishRecordingLivePhotoMovie (AVCapturePhotoOutput captureOutput, NSUrl outputFileUrl, AVCaptureResolvedPhotoSettings resolvedSettings) - { - LivePhotoCaptureHandler (false); - } - - [Export ("captureOutput:didFinishProcessingLivePhotoToMovieFileAtURL:duration:photoDisplayTime:resolvedSettings:error:")] - public virtual void DidFinishProcessingLivePhotoMovie (AVCapturePhotoOutput captureOutput, NSUrl outputFileUrl, CMTime duration, CMTime photoDisplayTime, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error) - { - if (error != null) - { - Console.WriteLine ($"Error processing live photo companion movie: {error}", error); - return; - } - - LivePhotoCompanionMovieUrl = outputFileUrl; - } - - [Export ("captureOutput:didFinishCaptureForResolvedSettings:error:")] - public virtual async void DidFinishCapture (AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error) - { - if (error != null) - { - Console.WriteLine ($"Error capturing photo: {error}", error); - DidFinish (); - return; - } - - if (PhotoData == null) - { - Console.WriteLine ("No photo data resource"); - DidFinish (); - return; - } - - var status = await Photos.PHPhotoLibrary.RequestAuthorizationAsync (); - - if (status == Photos.PHAuthorizationStatus.Authorized) - { - Photos.PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { - var options = new Photos.PHAssetResourceCreationOptions (); - options.UniformTypeIdentifier = RequestedPhotoSettings.ProcessedFileType (); - var creationRequest = Photos.PHAssetCreationRequest.CreationRequestForAsset (); - creationRequest.AddResource (Photos.PHAssetResourceType.Photo, PhotoData, options); - - if (LivePhotoCompanionMovieUrl != null) - { - var livePhotoCompanionMovieResourceOptions = new Photos.PHAssetResourceCreationOptions (); - livePhotoCompanionMovieResourceOptions.ShouldMoveFile = true; - creationRequest.AddResource (Photos.PHAssetResourceType.PairedVideo, LivePhotoCompanionMovieUrl, livePhotoCompanionMovieResourceOptions); - } - }, (success, completeError) => - { - if (!success) - { - Console.WriteLine ($"Error occurred while saving photo to photo library: {error}"); - } - - DidFinish (); - }); - } - else - { - Console.WriteLine (@"Not authorized to save photo"); - DidFinish (); - } - } - } +namespace AVCam { + public class AVCamPhotoCaptureDelegate : NSObject, IAVCapturePhotoCaptureDelegate { + public AVCapturePhotoSettings RequestedPhotoSettings { get; set; } + Action WillCapturePhotoAnimation { get; set; } + Action<bool> LivePhotoCaptureHandler { get; set; } + Action<AVCamPhotoCaptureDelegate> CompletionHandler { get; set; } + NSData PhotoData { get; set; } + NSUrl LivePhotoCompanionMovieUrl { get; set; } + + public AVCamPhotoCaptureDelegate (AVCapturePhotoSettings requestedPhotoSettings, Action willCapturePhotoAnimation, Action<bool> livePhotoCaptureHandler, Action<AVCamPhotoCaptureDelegate> completionHandler) + { + RequestedPhotoSettings = requestedPhotoSettings; + WillCapturePhotoAnimation = willCapturePhotoAnimation; + LivePhotoCaptureHandler = livePhotoCaptureHandler; + CompletionHandler = completionHandler; + } + + void DidFinish () + { + if (LivePhotoCompanionMovieUrl != null && NSFileManager.DefaultManager.FileExists (LivePhotoCompanionMovieUrl.Path)) { + NSError error; + NSFileManager.DefaultManager.Remove (LivePhotoCompanionMovieUrl.Path, out error); + + if (error != null) + Console.WriteLine ($"Could not remove file at url: {LivePhotoCompanionMovieUrl.Path}"); + } + + CompletionHandler (this); + } + + [Export ("captureOutput:willBeginCaptureForResolvedSettings:")] + public virtual void WillBeginCapture (AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings) + { + if ((resolvedSettings.LivePhotoMovieDimensions.Width > 0) && (resolvedSettings.LivePhotoMovieDimensions.Height > 0)) { + LivePhotoCaptureHandler (true); + } + } + + [Export ("captureOutput:willCapturePhotoForResolvedSettings:")] + public virtual void WillCapturePhoto (AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings) + { + WillCapturePhotoAnimation (); + } + + [Export ("captureOutput:didFinishProcessingPhoto:error:")] + public virtual void DidFinishProcessingPhoto (AVCapturePhotoOutput captureOutput, AVCapturePhoto photo, NSError error) + { + if (error != null) { + Console.WriteLine ($"Error capturing photo: {error}", error); + return; + } + PhotoData = photo.FileDataRepresentation (); + } + + [Export ("captureOutput:didFinishRecordingLivePhotoMovieForEventualFileAtURL:resolvedSettings:")] + public virtual void DidFinishRecordingLivePhotoMovie (AVCapturePhotoOutput captureOutput, NSUrl outputFileUrl, AVCaptureResolvedPhotoSettings resolvedSettings) + { + LivePhotoCaptureHandler (false); + } + + [Export ("captureOutput:didFinishProcessingLivePhotoToMovieFileAtURL:duration:photoDisplayTime:resolvedSettings:error:")] + public virtual void DidFinishProcessingLivePhotoMovie (AVCapturePhotoOutput captureOutput, NSUrl outputFileUrl, CMTime duration, CMTime photoDisplayTime, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error) + { + if (error != null) { + Console.WriteLine ($"Error processing live photo companion movie: {error}", error); + return; + } + + LivePhotoCompanionMovieUrl = outputFileUrl; + } + + [Export ("captureOutput:didFinishCaptureForResolvedSettings:error:")] + public virtual async void DidFinishCapture (AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error) + { + if (error != null) { + Console.WriteLine ($"Error capturing photo: {error}", error); + DidFinish (); + return; + } + + if (PhotoData == null) { + Console.WriteLine ("No photo data resource"); + DidFinish (); + return; + } + + var status = await Photos.PHPhotoLibrary.RequestAuthorizationAsync (); + + if (status == Photos.PHAuthorizationStatus.Authorized) { + Photos.PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { + var options = new Photos.PHAssetResourceCreationOptions (); + options.UniformTypeIdentifier = RequestedPhotoSettings.ProcessedFileType (); + var creationRequest = Photos.PHAssetCreationRequest.CreationRequestForAsset (); + creationRequest.AddResource (Photos.PHAssetResourceType.Photo, PhotoData, options); + + if (LivePhotoCompanionMovieUrl != null) { + var livePhotoCompanionMovieResourceOptions = new Photos.PHAssetResourceCreationOptions (); + livePhotoCompanionMovieResourceOptions.ShouldMoveFile = true; + creationRequest.AddResource (Photos.PHAssetResourceType.PairedVideo, LivePhotoCompanionMovieUrl, livePhotoCompanionMovieResourceOptions); + } + }, (success, completeError) => { + if (!success) { + Console.WriteLine ($"Error occurred while saving photo to photo library: {error}"); + } + + DidFinish (); + }); + } else { + Console.WriteLine (@"Not authorized to save photo"); + DidFinish (); + } + } + } } diff --git a/ios11/AVCam/src/AVCamPreviewView.cs b/ios11/AVCam/src/AVCamPreviewView.cs index 150b6551b..732d94009 100644 --- a/ios11/AVCam/src/AVCamPreviewView.cs +++ b/ios11/AVCam/src/AVCamPreviewView.cs @@ -6,10 +6,8 @@ using ObjCRuntime; using UIKit; -namespace AVCam -{ - public partial class AVCamPreviewView : UIView - { +namespace AVCam { + public partial class AVCamPreviewView : UIView { public AVCamPreviewView (IntPtr handle) : base (handle) { } @@ -31,7 +29,7 @@ public AVCaptureSession Session { var videoPreviewLayer = VideoPreviewLayer; return videoPreviewLayer == null ? null : videoPreviewLayer.Session; } - set{ + set { var videoPreviewLayer = VideoPreviewLayer; if (videoPreviewLayer != null) videoPreviewLayer.Session = value; diff --git a/ios11/AVCam/src/AppDelegate.cs b/ios11/AVCam/src/AppDelegate.cs index 240686c1a..2ba1c5b36 100644 --- a/ios11/AVCam/src/AppDelegate.cs +++ b/ios11/AVCam/src/AppDelegate.cs @@ -1,17 +1,14 @@ -using Foundation; +using Foundation; using UIKit; -namespace AVCam -{ +namespace AVCam { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } diff --git a/ios11/AVCam/src/Main.cs b/ios11/AVCam/src/Main.cs index 7c3981fa2..cb8a5e8d7 100644 --- a/ios11/AVCam/src/Main.cs +++ b/ios11/AVCam/src/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace AVCam -{ - public class Application - { +namespace AVCam { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios11/AVCam/src/MissingBindings.cs b/ios11/AVCam/src/MissingBindings.cs index dd0c7edc2..e26450d00 100644 --- a/ios11/AVCam/src/MissingBindings.cs +++ b/ios11/AVCam/src/MissingBindings.cs @@ -1,156 +1,142 @@ -using System; +using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using AVFoundation; using Foundation; using ObjCRuntime; -namespace AVCam -{ - public unsafe static partial class AVCapturePhoto_Ext - { - [CompilerGenerated] - static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhoto"); - - [Export ("fileDataRepresentation")] - [CompilerGenerated] - public static NSData FileDataRepresentation (this AVCapturePhoto This) - { - return Runtime.GetNSObject<NSData> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (This.Handle, Selector.GetHandle ("fileDataRepresentation"))); - } - - } /* class AVCapturePhoto_Ext */ - - public unsafe static partial class AVCapturePhotoOutput_AVCapturePhotoOutputDepthDataDeliverySupport - { - [CompilerGenerated] - static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhotoOutput"); - - [Export ("isDepthDataDeliveryEnabled")] - [CompilerGenerated] - public static bool IsDepthDataDeliveryEnabled (this AVCapturePhotoOutput This) - { - return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("isDepthDataDeliveryEnabled")); - } - - [Export ("setDepthDataDeliveryEnabled:")] - [CompilerGenerated] - public static void IsDepthDataDeliveryEnabled (this AVCapturePhotoOutput This, bool enabled) - { - global::ApiDefinition.Messaging.void_objc_msgSend_bool (This.Handle, Selector.GetHandle ("setDepthDataDeliveryEnabled:"), enabled); - } - - [Export ("isDepthDataDeliverySupported")] - [CompilerGenerated] - public static bool IsDepthDataDeliverySupported (this AVCapturePhotoOutput This) - { - return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("isDepthDataDeliverySupported")); - } - - } /* class AVCapturePhotoOutput_AVCapturePhotoOutputDepthDataDeliverySupport */ - - public unsafe static partial class AVCapturePhotoSettings_AVCapturePhotoSettings - { - [CompilerGenerated] - static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhotoSettings"); - - [Export ("isDepthDataDeliveryEnabled")] - [CompilerGenerated] - public static bool IsDepthDataDeliveryEnabled (this AVCapturePhotoSettings This) - { - return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("isDepthDataDeliveryEnabled")); - } - - [Export ("setDepthDataDeliveryEnabled:")] - [CompilerGenerated] - public static void IsDepthDataDeliveryEnabled (this AVCapturePhotoSettings This, bool enabled) - { - global::ApiDefinition.Messaging.void_objc_msgSend_bool (This.Handle, Selector.GetHandle ("setDepthDataDeliveryEnabled:"), enabled); - } - - } /* class AVCapturePhotoSettings_AVCapturePhotoSettings */ - - public unsafe static partial class AVCapturePhotoSettings_AVCapturePhotoSettingsConversions - { - [CompilerGenerated] - static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhotoSettings"); - - [Export ("processedFileType")] - [CompilerGenerated] - public static string ProcessedFileType (this AVCapturePhotoSettings This) - { - return NSString.FromHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (This.Handle, Selector.GetHandle ("processedFileType"))); - } - - } /* class AVCapturePhotoSettings_AVCapturePhotoSettingsConversions */ - - public unsafe static partial class AVVideo2 - { - [CompilerGenerated] - static NSString _CodecHEVC; - [Field ("AVVideoCodecTypeHEVC", "__Internal")] - public static NSString CodecHEVC - { - get - { - if (_CodecHEVC == null) - _CodecHEVC = Dlfcn.GetStringConstant (Libraries.__Internal.Handle, "AVVideoCodecTypeHEVC"); - return _CodecHEVC; - } - } - } /* class AVVideo2 */ - - public unsafe static partial class NSString_NSStringExt - { - - [CompilerGenerated] - static readonly IntPtr class_ptr = Class.GetHandle ("NSString"); - - [Export ("boolValue")] - [CompilerGenerated] - public static bool BoolValue (this NSString This) - { - return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("boolValue")); - } - - } /* class NSString_NSStringExt */ +namespace AVCam { + public unsafe static partial class AVCapturePhoto_Ext { + [CompilerGenerated] + static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhoto"); + + [Export ("fileDataRepresentation")] + [CompilerGenerated] + public static NSData FileDataRepresentation (this AVCapturePhoto This) + { + return Runtime.GetNSObject<NSData> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (This.Handle, Selector.GetHandle ("fileDataRepresentation"))); + } + + } /* class AVCapturePhoto_Ext */ + + public unsafe static partial class AVCapturePhotoOutput_AVCapturePhotoOutputDepthDataDeliverySupport { + [CompilerGenerated] + static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhotoOutput"); + + [Export ("isDepthDataDeliveryEnabled")] + [CompilerGenerated] + public static bool IsDepthDataDeliveryEnabled (this AVCapturePhotoOutput This) + { + return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("isDepthDataDeliveryEnabled")); + } + + [Export ("setDepthDataDeliveryEnabled:")] + [CompilerGenerated] + public static void IsDepthDataDeliveryEnabled (this AVCapturePhotoOutput This, bool enabled) + { + global::ApiDefinition.Messaging.void_objc_msgSend_bool (This.Handle, Selector.GetHandle ("setDepthDataDeliveryEnabled:"), enabled); + } + + [Export ("isDepthDataDeliverySupported")] + [CompilerGenerated] + public static bool IsDepthDataDeliverySupported (this AVCapturePhotoOutput This) + { + return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("isDepthDataDeliverySupported")); + } + + } /* class AVCapturePhotoOutput_AVCapturePhotoOutputDepthDataDeliverySupport */ + + public unsafe static partial class AVCapturePhotoSettings_AVCapturePhotoSettings { + [CompilerGenerated] + static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhotoSettings"); + + [Export ("isDepthDataDeliveryEnabled")] + [CompilerGenerated] + public static bool IsDepthDataDeliveryEnabled (this AVCapturePhotoSettings This) + { + return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("isDepthDataDeliveryEnabled")); + } + + [Export ("setDepthDataDeliveryEnabled:")] + [CompilerGenerated] + public static void IsDepthDataDeliveryEnabled (this AVCapturePhotoSettings This, bool enabled) + { + global::ApiDefinition.Messaging.void_objc_msgSend_bool (This.Handle, Selector.GetHandle ("setDepthDataDeliveryEnabled:"), enabled); + } + + } /* class AVCapturePhotoSettings_AVCapturePhotoSettings */ + + public unsafe static partial class AVCapturePhotoSettings_AVCapturePhotoSettingsConversions { + [CompilerGenerated] + static readonly IntPtr class_ptr = Class.GetHandle ("AVCapturePhotoSettings"); + + [Export ("processedFileType")] + [CompilerGenerated] + public static string ProcessedFileType (this AVCapturePhotoSettings This) + { + return NSString.FromHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (This.Handle, Selector.GetHandle ("processedFileType"))); + } + + } /* class AVCapturePhotoSettings_AVCapturePhotoSettingsConversions */ + + public unsafe static partial class AVVideo2 { + [CompilerGenerated] + static NSString _CodecHEVC; + [Field ("AVVideoCodecTypeHEVC", "__Internal")] + public static NSString CodecHEVC { + get { + if (_CodecHEVC == null) + _CodecHEVC = Dlfcn.GetStringConstant (Libraries.__Internal.Handle, "AVVideoCodecTypeHEVC"); + return _CodecHEVC; + } + } + } /* class AVVideo2 */ + + public unsafe static partial class NSString_NSStringExt { + + [CompilerGenerated] + static readonly IntPtr class_ptr = Class.GetHandle ("NSString"); + + [Export ("boolValue")] + [CompilerGenerated] + public static bool BoolValue (this NSString This) + { + return global::ApiDefinition.Messaging.bool_objc_msgSend (This.Handle, Selector.GetHandle ("boolValue")); + } + + } /* class NSString_NSStringExt */ } -namespace ApiDefinition -{ - partial class Messaging - { - static internal System.Reflection.Assembly this_assembly = typeof (Messaging).Assembly; - - const string LIBOBJC_DYLIB = "/usr/lib/libobjc.dylib"; - - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] - public extern static IntPtr IntPtr_objc_msgSend (IntPtr receiever, IntPtr selector); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] - public extern static IntPtr IntPtr_objc_msgSendSuper (IntPtr receiever, IntPtr selector); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] - public extern static IntPtr IntPtr_objc_msgSend_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] - public extern static IntPtr IntPtr_objc_msgSendSuper_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] - public extern static bool bool_objc_msgSend (IntPtr receiver, IntPtr selector); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] - public extern static bool bool_objc_msgSendSuper (IntPtr receiver, IntPtr selector); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] - public extern static void void_objc_msgSend_bool (IntPtr receiver, IntPtr selector, bool arg1); - [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] - public extern static void void_objc_msgSendSuper_bool (IntPtr receiver, IntPtr selector, bool arg1); - } +namespace ApiDefinition { + partial class Messaging { + static internal System.Reflection.Assembly this_assembly = typeof (Messaging).Assembly; + + const string LIBOBJC_DYLIB = "/usr/lib/libobjc.dylib"; + + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] + public extern static IntPtr IntPtr_objc_msgSend (IntPtr receiever, IntPtr selector); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] + public extern static IntPtr IntPtr_objc_msgSendSuper (IntPtr receiever, IntPtr selector); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] + public extern static IntPtr IntPtr_objc_msgSend_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] + public extern static IntPtr IntPtr_objc_msgSendSuper_IntPtr (IntPtr receiever, IntPtr selector, IntPtr arg1); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] + public extern static bool bool_objc_msgSend (IntPtr receiver, IntPtr selector); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] + public extern static bool bool_objc_msgSendSuper (IntPtr receiver, IntPtr selector); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSend")] + public extern static void void_objc_msgSend_bool (IntPtr receiver, IntPtr selector, bool arg1); + [DllImport (LIBOBJC_DYLIB, EntryPoint = "objc_msgSendSuper")] + public extern static void void_objc_msgSendSuper_bool (IntPtr receiver, IntPtr selector, bool arg1); + } } -namespace ObjCRuntime -{ - [CompilerGenerated] - static partial class Libraries - { - static public class __Internal - { - static public readonly IntPtr Handle = Dlfcn.dlopen (null, 0); - } - } +namespace ObjCRuntime { + [CompilerGenerated] + static partial class Libraries { + static public class __Internal { + static public readonly IntPtr Handle = Dlfcn.dlopen (null, 0); + } + } } diff --git a/ios11/AVCamBarcode/AVCamBarcode/AppDelegate.cs b/ios11/AVCamBarcode/AVCamBarcode/AppDelegate.cs index a561a2f1c..d41c73e64 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/AppDelegate.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/AppDelegate.cs @@ -1,56 +1,54 @@ - -namespace AVCamBarcode -{ - using Foundation; - using UIKit; - - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window { get; set; } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } -} \ No newline at end of file + +namespace AVCamBarcode { + using Foundation; + using UIKit; + + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { get; set; } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/CameraViewController.cs b/ios11/AVCamBarcode/AVCamBarcode/CameraViewController.cs index d76d02abb..ce443abaa 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/CameraViewController.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/CameraViewController.cs @@ -1,857 +1,776 @@ - -namespace AVCamBarcode -{ - using AVCamBarcode.Extensions; - using AVFoundation; - using CoreAnimation; - using CoreFoundation; - using CoreGraphics; - using CoreText; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading; - using UIKit; - - public partial class CameraViewController : UIViewController, IAVCaptureMetadataOutputObjectsDelegate, IItemSelectionViewControllerDelegate - { - private readonly AVCaptureMetadataOutput metadataOutput = new AVCaptureMetadataOutput(); - - /// <summary> - /// Communicate with the session and other session objects on this queue. - /// </summary> - private readonly DispatchQueue sessionQueue = new DispatchQueue("session queue"); - - private readonly AVCaptureSession session = new AVCaptureSession(); - - private SessionSetupResult setupResult = SessionSetupResult.Success; - - private AVCaptureDeviceInput videoDeviceInput; - - private bool isSessionRunning; - - // KVO and Notifications - - private readonly List<MetadataObjectLayer> metadataObjectOverlayLayers = new List<MetadataObjectLayer>(); - - private UITapGestureRecognizer openBarcodeURLGestureRecognizer; - - public CameraViewController(IntPtr handle) : base(handle) { } - - protected UITapGestureRecognizer OpenBarcodeURLGestureRecognizer - { - get - { - if (this.openBarcodeURLGestureRecognizer == null) - { - this.openBarcodeURLGestureRecognizer = new UITapGestureRecognizer(this.OpenBarcodeUrl); - } - - return this.openBarcodeURLGestureRecognizer; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Disable UI. The UI is enabled if and only if the session starts running. - this.MetadataObjectTypesButton.Enabled = false; - this.SessionPresetsButton.Enabled = false; - this.CameraButton.Enabled = false; - this.ZoomSlider.Enabled = false; - - // Add the open barcode gesture recognizer to the region of interest view. - this.PreviewView.AddGestureRecognizer(this.OpenBarcodeURLGestureRecognizer); - - // Set up the video preview view. - this.PreviewView.Session = session; - - // Check video authorization status. Video access is required and audio - // access is optional. If audio access is denied, audio is not recorded - // during movie recording. - switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video)) - { - case AVAuthorizationStatus.Authorized: - // The user has previously granted access to the camera. - break; - - case AVAuthorizationStatus.NotDetermined: - // The user has not yet been presented with the option to grant - // video access. We suspend the session queue to delay session - // setup until the access request has completed. - this.sessionQueue.Suspend(); - AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) => - { - if (!granted) - { - this.setupResult = SessionSetupResult.NotAuthorized; - } - - this.sessionQueue.Resume(); - }); - break; - - default: - // The user has previously denied access. - this.setupResult = SessionSetupResult.NotAuthorized; - break; - } - - // Setup the capture session. - // In general it is not safe to mutate an AVCaptureSession or any of its - // inputs, outputs, or connections from multiple threads at the same time. - // - // Why not do all of this on the main queue? - // Because AVCaptureSession.StartRunning() is a blocking call which can - // take a long time. We dispatch session setup to the sessionQueue so - // that the main queue isn't blocked, which keeps the UI responsive. - this.sessionQueue.DispatchAsync(this.ConfigureSession); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - this.sessionQueue.DispatchAsync(() => - { - switch (this.setupResult) - { - case SessionSetupResult.Success: - // Only setup observers and start the session running if setup succeeded. - this.AddObservers(); - this.session.StartRunning(); - this.isSessionRunning = session.Running; - - break; - - case SessionSetupResult.NotAuthorized: - DispatchQueue.MainQueue.DispatchAsync(() => - { - var message = "AVCamBarcode doesn't have permission to use the camera, please change privacy settings"; - var alertController = UIAlertController.Create("AVCamBarcode", message, UIAlertControllerStyle.Alert); - alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null)); - alertController.AddAction(UIAlertAction.Create("Settings", UIAlertActionStyle.Default, action => - { - UIApplication.SharedApplication.OpenUrl(new NSUrl(UIApplication.OpenSettingsUrlString)); - })); - - this.PresentViewController(alertController, true, null); - }); - break; - - case SessionSetupResult.ConfigurationFailed: - DispatchQueue.MainQueue.DispatchAsync(() => - { - var message = "Unable to capture media"; - var alertController = UIAlertController.Create("AVCamBarcode", message, UIAlertControllerStyle.Alert); - alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null)); - - this.PresentViewController(alertController, true, null); - }); - break; - } - }); - } - - public override void ViewWillDisappear(bool animated) - { - this.sessionQueue.DispatchAsync(() => - { - if (this.setupResult == SessionSetupResult.Success) - { - this.session.StopRunning(); - this.isSessionRunning = this.session.Running; - this.RemoveObservers(); - } - }); - - base.ViewWillDisappear(animated); - } - - public override bool ShouldAutorotate() - { - // Do now allow rotation if the region of interest is being resized - return !this.PreviewView.IsResizingRegionOfInterest; - } - - public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) - { - base.ViewWillTransitionToSize(toSize, coordinator); - - var videoPreviewLayerConnection = this.PreviewView.VideoPreviewLayer.Connection; - if (videoPreviewLayerConnection != null) - { - var deviceOrientation = UIDevice.CurrentDevice.Orientation; - if (deviceOrientation.IsPortrait() || deviceOrientation.IsLandscape()) - { - var newVideoOrientation = this.ConvertOrientation(deviceOrientation); - videoPreviewLayerConnection.VideoOrientation = newVideoOrientation; - - // When we transition to the new size, we need to adjust the region - // of interest's origin and size so that it stays anchored relative - // to the camera. - coordinator.AnimateAlongsideTransition((context) => // animate - { - var newRegionOfInterest = this.PreviewView.VideoPreviewLayer.MapToLayerCoordinates(this.metadataOutput.RectOfInterest); - this.PreviewView.SetRegionOfInterestWithProposedRegionOfInterest(newRegionOfInterest); - }, (context) => // completion - { - // Remove the old metadata object overlays - this.RemoveMetadataObjectOverlayLayers(); - }); - } - } - } - - private AVCaptureVideoOrientation ConvertOrientation(UIDeviceOrientation deviceOrientation) - { - var result = default(AVCaptureVideoOrientation); - switch (deviceOrientation) - { - case UIDeviceOrientation.Portrait: - result = AVCaptureVideoOrientation.Portrait; - break; - case UIDeviceOrientation.PortraitUpsideDown: - result = AVCaptureVideoOrientation.PortraitUpsideDown; - break; - // TODO: change to logical naming after it will be fixed (map `LandscapeLeft` to `LandscapeLeft`) - case UIDeviceOrientation.LandscapeLeft: - result = AVCaptureVideoOrientation.LandscapeRight; - break; - case UIDeviceOrientation.LandscapeRight: - result = AVCaptureVideoOrientation.LandscapeLeft; - break; - default: - throw new InvalidProgramException(); - } - - return result; - } - - private void PresentItemSelectionViewController<T>(ItemSelectionViewController<T> itemSelectionViewController) - { - var navigationController = new UINavigationController(itemSelectionViewController); - navigationController.NavigationBar.BarTintColor = UIColor.Black; - navigationController.NavigationBar.TintColor = this.View.TintColor; - - this.PresentViewController(navigationController, true, null); - } - - #region Session Management - - private readonly DispatchQueue metadataObjectsQueue = new DispatchQueue("metadata objects queue"); - - private void ConfigureSession() - { - if (setupResult == SessionSetupResult.Success) - { - this.session.BeginConfiguration(); - - // Add video input - // Choose the back wide angle camera if available, otherwise default to the front wide angle camera - AVCaptureDevice defaultVideoDevice = AVCaptureDevice.GetDefaultDevice(AVCaptureDeviceType.BuiltInWideAngleCamera, AVMediaType.Video, AVCaptureDevicePosition.Back) ?? - AVCaptureDevice.GetDefaultDevice(AVCaptureDeviceType.BuiltInWideAngleCamera, AVMediaType.Video, AVCaptureDevicePosition.Front) ?? - null; - - if (defaultVideoDevice == null) - { - Console.WriteLine("Could not get video device"); - this.setupResult = SessionSetupResult.ConfigurationFailed; - this.session.CommitConfiguration(); - return; - } - - NSError error; - var videoDeviceInput = AVCaptureDeviceInput.FromDevice(defaultVideoDevice, out error); - if (this.session.CanAddInput(videoDeviceInput)) - { - this.session.AddInput(videoDeviceInput); - this.videoDeviceInput = videoDeviceInput; - - DispatchQueue.MainQueue.DispatchAsync(() => - { - // Why are we dispatching this to the main queue? - // Because AVCaptureVideoPreviewLayer is the backing layer for PreviewView and UIView - // can only be manipulated on the main thread - // Note: As an exception to the above rule, it's not necessary to serialize video orientation changed - // on the AVCaptureVideoPreviewLayer's connection with other session manipulation - // - // Use the status bar orientation as the internal video orientation. Subsequent orientation changes are - // handled by CameraViewController.ViewWillTransition(to:with:). - - var initialVideoOrientation = AVCaptureVideoOrientation.Portrait; - var statusBarOrientation = UIApplication.SharedApplication.StatusBarOrientation; - if (statusBarOrientation != UIInterfaceOrientation.Unknown) - { - AVCaptureVideoOrientation videoOrintation; - if (Enum.TryParse(statusBarOrientation.ToString(), out videoOrintation)) - { - initialVideoOrientation = videoOrintation; - } - } - - this.PreviewView.VideoPreviewLayer.Connection.VideoOrientation = initialVideoOrientation; - }); - } - else if (error != null) - { - Console.WriteLine($"Could not create video device input: {error}"); - this.setupResult = SessionSetupResult.ConfigurationFailed; - this.session.CommitConfiguration(); - return; - } - else - { - Console.WriteLine("Could not add video device input to the session"); - this.setupResult = SessionSetupResult.ConfigurationFailed; - this.session.CommitConfiguration(); - - return; - } - - - // Add metadata output - if (this.session.CanAddOutput(metadataOutput)) - { - this.session.AddOutput(metadataOutput); - - // Set this view controller as the delegate for metadata objects - this.metadataOutput.SetDelegate(this, this.metadataObjectsQueue); - this.metadataOutput.MetadataObjectTypes = this.metadataOutput.AvailableMetadataObjectTypes; // Use all metadata object types by default - - // Set an initial rect of interest that is 80% of the views's shortest side - // and 25% of the longest side. This means that the region on interest will - // appear in the same spot regardless of whether the app starts in portrait - // or landscape - - var width = 0.25; - var height = 0.8; - var x = (1 - width) / 2; - var y = (1 - height) / 2; - var initialRectOfInterest = new CGRect(x, y, width, height); - this.metadataOutput.RectOfInterest = initialRectOfInterest; - - DispatchQueue.MainQueue.DispatchAsync(() => - { - var initialRegionOfInterest = this.PreviewView.VideoPreviewLayer.MapToLayerCoordinates(initialRectOfInterest); - this.PreviewView.SetRegionOfInterestWithProposedRegionOfInterest(initialRegionOfInterest); - }); - } - else - { - Console.WriteLine("Could not add metadata output to the session"); - this.setupResult = SessionSetupResult.ConfigurationFailed; - this.session.CommitConfiguration(); - - return; - } - - this.session.CommitConfiguration(); - } - } - - #endregion - - #region Presets - - partial void SelectSessionPreset(UIButton sender) - { - var controller = new ItemSelectionViewController<NSString>(this, - SessionPresetItemSelectionIdentifier, - new List<NSString>(AvailableSessionPresets()), - new List<NSString> { this.session.SessionPreset }, - false); - - this.PresentItemSelectionViewController(controller); - } - - private NSString[] AvailableSessionPresets() - { - return GetAllSessionPresets().Where(preset => session.CanSetSessionPreset(preset)).ToArray(); - } - - private static IEnumerable<NSString> GetAllSessionPresets() - { - yield return AVCaptureSession.PresetPhoto; - yield return AVCaptureSession.PresetLow; - yield return AVCaptureSession.PresetMedium; - yield return AVCaptureSession.PresetHigh; - yield return AVCaptureSession.Preset352x288; - yield return AVCaptureSession.Preset640x480; - yield return AVCaptureSession.Preset1280x720; - yield return AVCaptureSession.PresetiFrame960x540; - yield return AVCaptureSession.PresetiFrame1280x720; - yield return AVCaptureSession.Preset1920x1080; - yield return AVCaptureSession.Preset3840x2160; - } - - #endregion - - #region Device Configuration - - partial void ChangeCamera(UIButton sender) - { - this.MetadataObjectTypesButton.Enabled = false; - this.SessionPresetsButton.Enabled = false; - this.CameraButton.Enabled = false; - this.ZoomSlider.Enabled = false; - - // Remove the metadata overlay layers, if any. - this.RemoveMetadataObjectOverlayLayers(); - - DispatchQueue.MainQueue.DispatchAsync(() => - { - var preferredPosition = AVCaptureDevicePosition.Unspecified; - switch (this.videoDeviceInput.Device.Position) - { - case AVCaptureDevicePosition.Unspecified: - case AVCaptureDevicePosition.Front: - preferredPosition = AVCaptureDevicePosition.Back; - break; - - case AVCaptureDevicePosition.Back: - preferredPosition = AVCaptureDevicePosition.Front; - break; - } - - var devices = AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video); - var videoDevice = devices.FirstOrDefault(device => device.Position == preferredPosition); - if (videoDevice != null) - { - NSError error; - var captureDeviceInput = AVCaptureDeviceInput.FromDevice(videoDevice, out error); - if (error != null) - { - Console.WriteLine($"Error occurred while creating video device input: {error}"); - return; - } - - this.session.BeginConfiguration(); - - // Remove the existing device input first, since using the front and back camera simultaneously is not supported. - this.session.RemoveInput(this.videoDeviceInput); - - // When changing devices, a session preset that may be supported - // on one device may not be supported by another. To allow the - // user to successfully switch devices, we must save the previous - // session preset, set the default session preset (High), and - // attempt to restore it after the new video device has been - // added. For example, the 4K session preset is only supported - // by the back device on the iPhone 6s and iPhone 6s Plus. As a - // result, the session will not let us add a video device that - // does not support the current session preset. - var previousSessionPreset = this.session.SessionPreset; - this.session.SessionPreset = AVCaptureSession.PresetHigh; - - if (this.session.CanAddInput(captureDeviceInput)) - { - this.session.AddInput(captureDeviceInput); - this.videoDeviceInput = captureDeviceInput; - } - else - { - this.session.AddInput(this.videoDeviceInput); - } - - // Restore the previous session preset if we can. - if (this.session.CanSetSessionPreset(previousSessionPreset)) - { - this.session.SessionPreset = previousSessionPreset; - } - - this.session.CommitConfiguration(); - } - - this.MetadataObjectTypesButton.Enabled = true; - this.SessionPresetsButton.Enabled = true; - this.CameraButton.Enabled = true; - this.ZoomSlider.Enabled = true; - - this.ZoomSlider.MaxValue = (float)NMath.Min(this.videoDeviceInput.Device.ActiveFormat.VideoMaxZoomFactor, 8); - this.ZoomSlider.Value = (float)this.videoDeviceInput.Device.VideoZoomFactor; - }); - } - - partial void ZoomCamera(UISlider sender) - { - var device = this.videoDeviceInput.Device; - - NSError error; - this.videoDeviceInput.Device.LockForConfiguration(out error); - if (error == null) - { - device.VideoZoomFactor = this.ZoomSlider.Value; - device.UnlockForConfiguration(); - } - else - { - Console.WriteLine($"Could not lock for configuration: {error}"); - } - } - - #endregion - - #region KVO and Notifications - - private NSObject interruptionEndedNotificationToken; - - private NSObject wasInterruptedNotificationToken; - - private NSObject runtimeErrorNotificationToken; - - private IDisposable runningChangeToken; - - private void AddObservers() - { - this.runningChangeToken = this.session.AddObserver("running", NSKeyValueObservingOptions.New, this.OnRunningChanged); - - // Observe the previewView's regionOfInterest to update the AVCaptureMetadataOutput's - // RectOfInterest when the user finishes resizing the region of interest. - this.PreviewView.RegionOfInterestChanged += this.OnRegionOfInterestChanged; - - var notificationCenter = NSNotificationCenter.DefaultCenter; - - this.runtimeErrorNotificationToken = notificationCenter.AddObserver(AVCaptureSession.RuntimeErrorNotification, this.OnRuntimeErrorNotification, this.session); - - // A session can only run when the app is full screen. It will be interrupted - // in a multi-app layout, introduced in iOS 9, see also the documentation of - // AVCaptureSessionInterruptionReason.Add observers to handle these session - // interruptions and show a preview is paused message.See the documentation - // of AVCaptureSessionWasInterruptedNotification for other interruption reasons. - this.wasInterruptedNotificationToken = notificationCenter.AddObserver(AVCaptureSession.WasInterruptedNotification, this.OnSessionWasInterrupted, this.session); - this.interruptionEndedNotificationToken = notificationCenter.AddObserver(AVCaptureSession.InterruptionEndedNotification, this.OnSessionInterruptionEnded, this.session); - } - - private void RemoveObservers() - { - this.runningChangeToken?.Dispose(); - this.runtimeErrorNotificationToken?.Dispose(); - this.wasInterruptedNotificationToken?.Dispose(); - this.interruptionEndedNotificationToken?.Dispose(); - this.PreviewView.RegionOfInterestChanged -= this.OnRegionOfInterestChanged; - } - - private void OnRegionOfInterestChanged(object sender, EventArgs e) - { - var newRegion = (sender as PreviewView).RegionOfInterest; - DispatchQueue.MainQueue.DispatchAsync(() => - { - // Ensure we are not drawing old metadata object overlays. - this.RemoveMetadataObjectOverlayLayers(); - - // Translate the preview view's region of interest to the metadata output's coordinate system. - var metadataOutputRectOfInterest = this.PreviewView.VideoPreviewLayer.MapToMetadataOutputCoordinates(newRegion); - - this.sessionQueue.DispatchAsync(() => - { - // Update the AVCaptureMetadataOutput with the new region of interest - metadataOutput.RectOfInterest = metadataOutputRectOfInterest; - }); - }); - } - - private void OnRunningChanged(NSObservedChange change) - { - var isSessionRunning = ((NSNumber)change.NewValue).BoolValue; - - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.CameraButton.Enabled = isSessionRunning && AVCaptureDevice.DevicesWithMediaType(AVMediaType.Video).Length > 1; - this.MetadataObjectTypesButton.Enabled = isSessionRunning; - this.SessionPresetsButton.Enabled = isSessionRunning; - - this.ZoomSlider.Enabled = isSessionRunning; - this.ZoomSlider.MaxValue = (float)NMath.Min(this.videoDeviceInput.Device.ActiveFormat.VideoMaxZoomFactor, 8); - this.ZoomSlider.Value = (float)(this.videoDeviceInput.Device.VideoZoomFactor); - - // After the session stop running, remove the metadata object overlays, - // if any, so that if the view appears again, the previously displayed - // metadata object overlays are removed. - if (!isSessionRunning) - { - this.RemoveMetadataObjectOverlayLayers(); - } - - // When the session starts running, the aspect ration of the video preview may also change if a new session present was applied . - // To keep the preview view's region of interest within the visible portion of the video preview, the preview view's region of - // interest will need to be updates. - if (isSessionRunning) - { - this.PreviewView.SetRegionOfInterestWithProposedRegionOfInterest(this.PreviewView.RegionOfInterest); - } - }); - } - - private void OnRuntimeErrorNotification(NSNotification notification) - { - var args = new AVCaptureSessionRuntimeErrorEventArgs(notification); - if (args.Error != null) - { - var error = (AVError)(long)args.Error.Code; - Console.WriteLine($"Capture session runtime error: {error}"); - - // Automatically try to restart the session running if media services were - // reset and the last start running succeeded. Otherwise, enable the user - // to try to resume the session running. - - if (error == AVError.MediaServicesWereReset) - { - this.sessionQueue.DispatchAsync(() => - { - if (this.isSessionRunning) - { - this.session.StartRunning(); - this.isSessionRunning = session.Running; - } - }); - } - } - } - - private void OnSessionWasInterrupted(NSNotification notification) - { - // In some scenarios we want to enable the user to resume the session running. - // For example, if music playback is initiated via control center while - // using AVMetadataRecordPlay, then the user can let AVMetadataRecordPlay resume - // the session running, which will stop music playback. Note that stopping - // music playback in control center will not automatically resume the session - // running. Also note that it is not always possible to resume - - var reasonIntegerValue = ((NSNumber)notification.UserInfo[AVCaptureSession.InterruptionReasonKey]).Int32Value; - var reason = (AVCaptureSessionInterruptionReason)reasonIntegerValue; - Console.WriteLine($"Capture session was interrupted with reason {reason}"); - - if (reason == AVCaptureSessionInterruptionReason.VideoDeviceNotAvailableWithMultipleForegroundApps) - { - // Simply fade-in a label to inform the user that the camera is unavailable. - this.CameraUnavailableLabel.Hidden = false; - this.CameraUnavailableLabel.Alpha = 0; - UIView.Animate(0.25d, () => this.CameraUnavailableLabel.Alpha = 1); - } - } - - private void OnSessionInterruptionEnded(NSNotification notification) - { - Console.WriteLine("Capture session interruption ended"); - - if (this.CameraUnavailableLabel.Hidden) - { - UIView.Animate(0.25, () => - { - this.CameraUnavailableLabel.Alpha = 0; - }, () => - { - this.CameraUnavailableLabel.Hidden = true; - }); - } - } - - #endregion - - #region Drawing Metadata Object Overlay Layers - - private NSTimer removeMetadataObjectOverlayLayersTimer; - - partial void SelectMetadataObjectTypes(UIButton sender) - { - var controller = new ItemSelectionViewController<AVMetadataObjectType>(this, - MetadataObjectTypeItemSelectionIdentifier, - this.metadataOutput.AvailableMetadataObjectTypes.GetFlags().ToList(), - this.metadataOutput.MetadataObjectTypes.GetFlags().ToList(), - true); - - this.PresentItemSelectionViewController(controller); - } - - private MetadataObjectLayer CreateMetadataOverlay(AVMetadataObject metadataObject) - { - // Transform the metadata object so the bounds are updated to reflect those of the video preview layer. - var transformedMetadataObject = this.PreviewView.VideoPreviewLayer.GetTransformedMetadataObject(metadataObject); - - // Create the initial metadata object overlay layer that can be used for either machine readable codes or faces. - var metadataObjectOverlayLayer = new MetadataObjectLayer - { - LineWidth = 7, - LineJoin = CAShapeLayer.JoinRound, - MetadataObject = transformedMetadataObject, - FillColor = this.View.TintColor.ColorWithAlpha(0.3f).CGColor, - StrokeColor = this.View.TintColor.ColorWithAlpha(0.7f).CGColor, - }; - - var barcodeMetadataObject = transformedMetadataObject as AVMetadataMachineReadableCodeObject; - if (barcodeMetadataObject != null) - { - var barcodeOverlayPath = this.BarcodeOverlayPathWithCorners(barcodeMetadataObject.Corners); - metadataObjectOverlayLayer.Path = barcodeOverlayPath; - - // If the metadata object has a string value, display it. - string textLayerString = null; - if (!string.IsNullOrEmpty(barcodeMetadataObject.StringValue)) - { - textLayerString = barcodeMetadataObject.StringValue; - } - else - { - // TODO: add Descriptor (line 618 in original iOS sample) - } - - if (!string.IsNullOrEmpty(textLayerString)) - { - var barcodeOverlayBoundingBox = barcodeOverlayPath.BoundingBox; - - var font = UIFont.BoldSystemFontOfSize(19).ToCTFont(); - var textLayer = new CATextLayer - { - AlignmentMode = CATextLayer.AlignmentCenter, - Bounds = new CGRect(0, 0, barcodeOverlayBoundingBox.Size.Width, barcodeOverlayBoundingBox.Size.Height), - ContentsScale = UIScreen.MainScreen.Scale, - Position = new CGPoint(barcodeOverlayBoundingBox.GetMidX(), barcodeOverlayBoundingBox.GetMidY()), - Wrapped = true, - - // Invert the effect of transform of the video preview so the text is oriented with the interface orientation - Transform = CATransform3D.MakeFromAffine(this.PreviewView.Transform).Invert(), - String = textLayerString, - AttributedString = new NSAttributedString(textLayerString, new CTStringAttributes - { - Font = font, - StrokeWidth = -5, - StrokeColor = UIColor.Black.CGColor, - ForegroundColor = UIColor.White.CGColor, - }), - }; - - textLayer.SetFont(font); - metadataObjectOverlayLayer.AddSublayer(textLayer); - } - } - else if (transformedMetadataObject is AVMetadataFaceObject) - { - metadataObjectOverlayLayer.Path = CGPath.FromRect(transformedMetadataObject.Bounds); - } - - return metadataObjectOverlayLayer; - } - - private CGPath BarcodeOverlayPathWithCorners(CGPoint[] corners) - { - var path = new CGPath(); - - if (corners.Any()) - { - path.MoveToPoint(CGAffineTransform.MakeIdentity(), corners[0]); - - for (int i = 1; i < corners.Length; i++) - { - path.AddLineToPoint(corners[i]); - } - - path.CloseSubpath(); - } - - return path; - } - - private void RemoveMetadataObjectOverlayLayers() - { - this.metadataObjectOverlayLayers.ForEach(layer => layer.RemoveFromSuperLayer()); - this.metadataObjectOverlayLayers.Clear(); - - this.removeMetadataObjectOverlayLayersTimer?.Invalidate(); - this.removeMetadataObjectOverlayLayersTimer = null; - } - - private void AddMetadataOverlayLayers(IEnumerable<MetadataObjectLayer> layers) - { - // Add the metadata object overlays as sublayers of the video preview layer. We disable actions to allow for fast drawing. - CATransaction.Begin(); - CATransaction.DisableActions = true; - - foreach (var layer in layers) - { - this.PreviewView.VideoPreviewLayer.AddSublayer(layer); - this.metadataObjectOverlayLayers.Add(layer); // Save the new metadata object overlays. - } - - CATransaction.Commit(); - - // Create a timer to destroy the metadata object overlays. - this.removeMetadataObjectOverlayLayersTimer = NSTimer.CreateScheduledTimer(TimeSpan.FromSeconds(1), (param) => this.RemoveMetadataObjectOverlayLayers()); - } - - private void OpenBarcodeUrl(UITapGestureRecognizer openBarcodeURLGestureRecognizer) - { - foreach (var metadataObjectOverlayLayer in this.metadataObjectOverlayLayers) - { - var location = openBarcodeURLGestureRecognizer.LocationInView(this.PreviewView); - if (metadataObjectOverlayLayer.Path.ContainsPoint(location, false)) - { - var barcodeMetadataObject = metadataObjectOverlayLayer.MetadataObject as AVMetadataMachineReadableCodeObject; - if (barcodeMetadataObject != null) - { - if (!string.IsNullOrEmpty(barcodeMetadataObject.StringValue)) - { - var url = NSUrl.FromString(barcodeMetadataObject.StringValue); - if (UIApplication.SharedApplication.CanOpenUrl(url)) - { - UIApplication.SharedApplication.OpenUrl(url); - } - } - } - } - } - } - - #endregion - - #region AVCaptureMetadataOutputObjectsDelegate - - private readonly AutoResetEvent resetEvent = new AutoResetEvent(true); - - [Export("captureOutput:didOutputMetadataObjects:fromConnection:")] - public void DidOutputMetadataObjects(AVCaptureMetadataOutput captureOutput, AVMetadataObject[] metadataObjects, AVCaptureConnection connection) - { - // resetEvent is used to drop new notifications if old ones are still processing, to avoid queuing up a bunch of stale data. - if (this.resetEvent.WaitOne(0)) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.RemoveMetadataObjectOverlayLayers(); - this.AddMetadataOverlayLayers(metadataObjects.Select(this.CreateMetadataOverlay)); - - this.resetEvent.Set(); - }); - } - } - - #endregion - - #region ItemSelectionViewControllerDelegate - - private const string MetadataObjectTypeItemSelectionIdentifier = "MetadataObjectTypes"; - - private const string SessionPresetItemSelectionIdentifier = "SessionPreset"; - - public void ItemSelectionViewController<T>(ItemSelectionViewController<T> itemSelectionViewController, IList<T> selectedItems) - { - var identifier = itemSelectionViewController.Identifier; - if (identifier == MetadataObjectTypeItemSelectionIdentifier) - { - this.sessionQueue.DispatchAsync(() => - { - this.metadataOutput.MetadataObjectTypes = selectedItems.OfType<AVMetadataObjectType>().Aggregate((t1, t2) => t1 | t2); - }); - } - else if (identifier == SessionPresetItemSelectionIdentifier) - { - this.sessionQueue.DispatchAsync(() => - { - this.session.SessionPreset = selectedItems.OfType<NSString>().FirstOrDefault(); - }); - } - } - - #endregion - } -} \ No newline at end of file + +namespace AVCamBarcode { + using AVCamBarcode.Extensions; + using AVFoundation; + using CoreAnimation; + using CoreFoundation; + using CoreGraphics; + using CoreText; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using UIKit; + + public partial class CameraViewController : UIViewController, IAVCaptureMetadataOutputObjectsDelegate, IItemSelectionViewControllerDelegate { + private readonly AVCaptureMetadataOutput metadataOutput = new AVCaptureMetadataOutput (); + + /// <summary> + /// Communicate with the session and other session objects on this queue. + /// </summary> + private readonly DispatchQueue sessionQueue = new DispatchQueue ("session queue"); + + private readonly AVCaptureSession session = new AVCaptureSession (); + + private SessionSetupResult setupResult = SessionSetupResult.Success; + + private AVCaptureDeviceInput videoDeviceInput; + + private bool isSessionRunning; + + // KVO and Notifications + + private readonly List<MetadataObjectLayer> metadataObjectOverlayLayers = new List<MetadataObjectLayer> (); + + private UITapGestureRecognizer openBarcodeURLGestureRecognizer; + + public CameraViewController (IntPtr handle) : base (handle) { } + + protected UITapGestureRecognizer OpenBarcodeURLGestureRecognizer { + get { + if (this.openBarcodeURLGestureRecognizer == null) { + this.openBarcodeURLGestureRecognizer = new UITapGestureRecognizer (this.OpenBarcodeUrl); + } + + return this.openBarcodeURLGestureRecognizer; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Disable UI. The UI is enabled if and only if the session starts running. + this.MetadataObjectTypesButton.Enabled = false; + this.SessionPresetsButton.Enabled = false; + this.CameraButton.Enabled = false; + this.ZoomSlider.Enabled = false; + + // Add the open barcode gesture recognizer to the region of interest view. + this.PreviewView.AddGestureRecognizer (this.OpenBarcodeURLGestureRecognizer); + + // Set up the video preview view. + this.PreviewView.Session = session; + + // Check video authorization status. Video access is required and audio + // access is optional. If audio access is denied, audio is not recorded + // during movie recording. + switch (AVCaptureDevice.GetAuthorizationStatus (AVMediaType.Video)) { + case AVAuthorizationStatus.Authorized: + // The user has previously granted access to the camera. + break; + + case AVAuthorizationStatus.NotDetermined: + // The user has not yet been presented with the option to grant + // video access. We suspend the session queue to delay session + // setup until the access request has completed. + this.sessionQueue.Suspend (); + AVCaptureDevice.RequestAccessForMediaType (AVMediaType.Video, (granted) => { + if (!granted) { + this.setupResult = SessionSetupResult.NotAuthorized; + } + + this.sessionQueue.Resume (); + }); + break; + + default: + // The user has previously denied access. + this.setupResult = SessionSetupResult.NotAuthorized; + break; + } + + // Setup the capture session. + // In general it is not safe to mutate an AVCaptureSession or any of its + // inputs, outputs, or connections from multiple threads at the same time. + // + // Why not do all of this on the main queue? + // Because AVCaptureSession.StartRunning() is a blocking call which can + // take a long time. We dispatch session setup to the sessionQueue so + // that the main queue isn't blocked, which keeps the UI responsive. + this.sessionQueue.DispatchAsync (this.ConfigureSession); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + this.sessionQueue.DispatchAsync (() => { + switch (this.setupResult) { + case SessionSetupResult.Success: + // Only setup observers and start the session running if setup succeeded. + this.AddObservers (); + this.session.StartRunning (); + this.isSessionRunning = session.Running; + + break; + + case SessionSetupResult.NotAuthorized: + DispatchQueue.MainQueue.DispatchAsync (() => { + var message = "AVCamBarcode doesn't have permission to use the camera, please change privacy settings"; + var alertController = UIAlertController.Create ("AVCamBarcode", message, UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Cancel, null)); + alertController.AddAction (UIAlertAction.Create ("Settings", UIAlertActionStyle.Default, action => { + UIApplication.SharedApplication.OpenUrl (new NSUrl (UIApplication.OpenSettingsUrlString)); + })); + + this.PresentViewController (alertController, true, null); + }); + break; + + case SessionSetupResult.ConfigurationFailed: + DispatchQueue.MainQueue.DispatchAsync (() => { + var message = "Unable to capture media"; + var alertController = UIAlertController.Create ("AVCamBarcode", message, UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Cancel, null)); + + this.PresentViewController (alertController, true, null); + }); + break; + } + }); + } + + public override void ViewWillDisappear (bool animated) + { + this.sessionQueue.DispatchAsync (() => { + if (this.setupResult == SessionSetupResult.Success) { + this.session.StopRunning (); + this.isSessionRunning = this.session.Running; + this.RemoveObservers (); + } + }); + + base.ViewWillDisappear (animated); + } + + public override bool ShouldAutorotate () + { + // Do now allow rotation if the region of interest is being resized + return !this.PreviewView.IsResizingRegionOfInterest; + } + + public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) + { + base.ViewWillTransitionToSize (toSize, coordinator); + + var videoPreviewLayerConnection = this.PreviewView.VideoPreviewLayer.Connection; + if (videoPreviewLayerConnection != null) { + var deviceOrientation = UIDevice.CurrentDevice.Orientation; + if (deviceOrientation.IsPortrait () || deviceOrientation.IsLandscape ()) { + var newVideoOrientation = this.ConvertOrientation (deviceOrientation); + videoPreviewLayerConnection.VideoOrientation = newVideoOrientation; + + // When we transition to the new size, we need to adjust the region + // of interest's origin and size so that it stays anchored relative + // to the camera. + coordinator.AnimateAlongsideTransition ((context) => // animate + { + var newRegionOfInterest = this.PreviewView.VideoPreviewLayer.MapToLayerCoordinates (this.metadataOutput.RectOfInterest); + this.PreviewView.SetRegionOfInterestWithProposedRegionOfInterest (newRegionOfInterest); + }, (context) => // completion + { + // Remove the old metadata object overlays + this.RemoveMetadataObjectOverlayLayers (); + }); + } + } + } + + private AVCaptureVideoOrientation ConvertOrientation (UIDeviceOrientation deviceOrientation) + { + var result = default (AVCaptureVideoOrientation); + switch (deviceOrientation) { + case UIDeviceOrientation.Portrait: + result = AVCaptureVideoOrientation.Portrait; + break; + case UIDeviceOrientation.PortraitUpsideDown: + result = AVCaptureVideoOrientation.PortraitUpsideDown; + break; + // TODO: change to logical naming after it will be fixed (map `LandscapeLeft` to `LandscapeLeft`) + case UIDeviceOrientation.LandscapeLeft: + result = AVCaptureVideoOrientation.LandscapeRight; + break; + case UIDeviceOrientation.LandscapeRight: + result = AVCaptureVideoOrientation.LandscapeLeft; + break; + default: + throw new InvalidProgramException (); + } + + return result; + } + + private void PresentItemSelectionViewController<T> (ItemSelectionViewController<T> itemSelectionViewController) + { + var navigationController = new UINavigationController (itemSelectionViewController); + navigationController.NavigationBar.BarTintColor = UIColor.Black; + navigationController.NavigationBar.TintColor = this.View.TintColor; + + this.PresentViewController (navigationController, true, null); + } + + #region Session Management + + private readonly DispatchQueue metadataObjectsQueue = new DispatchQueue ("metadata objects queue"); + + private void ConfigureSession () + { + if (setupResult == SessionSetupResult.Success) { + this.session.BeginConfiguration (); + + // Add video input + // Choose the back wide angle camera if available, otherwise default to the front wide angle camera + AVCaptureDevice defaultVideoDevice = AVCaptureDevice.GetDefaultDevice (AVCaptureDeviceType.BuiltInWideAngleCamera, AVMediaType.Video, AVCaptureDevicePosition.Back) ?? + AVCaptureDevice.GetDefaultDevice (AVCaptureDeviceType.BuiltInWideAngleCamera, AVMediaType.Video, AVCaptureDevicePosition.Front) ?? + null; + + if (defaultVideoDevice == null) { + Console.WriteLine ("Could not get video device"); + this.setupResult = SessionSetupResult.ConfigurationFailed; + this.session.CommitConfiguration (); + return; + } + + NSError error; + var videoDeviceInput = AVCaptureDeviceInput.FromDevice (defaultVideoDevice, out error); + if (this.session.CanAddInput (videoDeviceInput)) { + this.session.AddInput (videoDeviceInput); + this.videoDeviceInput = videoDeviceInput; + + DispatchQueue.MainQueue.DispatchAsync (() => { + // Why are we dispatching this to the main queue? + // Because AVCaptureVideoPreviewLayer is the backing layer for PreviewView and UIView + // can only be manipulated on the main thread + // Note: As an exception to the above rule, it's not necessary to serialize video orientation changed + // on the AVCaptureVideoPreviewLayer's connection with other session manipulation + // + // Use the status bar orientation as the internal video orientation. Subsequent orientation changes are + // handled by CameraViewController.ViewWillTransition(to:with:). + + var initialVideoOrientation = AVCaptureVideoOrientation.Portrait; + var statusBarOrientation = UIApplication.SharedApplication.StatusBarOrientation; + if (statusBarOrientation != UIInterfaceOrientation.Unknown) { + AVCaptureVideoOrientation videoOrintation; + if (Enum.TryParse (statusBarOrientation.ToString (), out videoOrintation)) { + initialVideoOrientation = videoOrintation; + } + } + + this.PreviewView.VideoPreviewLayer.Connection.VideoOrientation = initialVideoOrientation; + }); + } else if (error != null) { + Console.WriteLine ($"Could not create video device input: {error}"); + this.setupResult = SessionSetupResult.ConfigurationFailed; + this.session.CommitConfiguration (); + return; + } else { + Console.WriteLine ("Could not add video device input to the session"); + this.setupResult = SessionSetupResult.ConfigurationFailed; + this.session.CommitConfiguration (); + + return; + } + + + // Add metadata output + if (this.session.CanAddOutput (metadataOutput)) { + this.session.AddOutput (metadataOutput); + + // Set this view controller as the delegate for metadata objects + this.metadataOutput.SetDelegate (this, this.metadataObjectsQueue); + this.metadataOutput.MetadataObjectTypes = this.metadataOutput.AvailableMetadataObjectTypes; // Use all metadata object types by default + + // Set an initial rect of interest that is 80% of the views's shortest side + // and 25% of the longest side. This means that the region on interest will + // appear in the same spot regardless of whether the app starts in portrait + // or landscape + + var width = 0.25; + var height = 0.8; + var x = (1 - width) / 2; + var y = (1 - height) / 2; + var initialRectOfInterest = new CGRect (x, y, width, height); + this.metadataOutput.RectOfInterest = initialRectOfInterest; + + DispatchQueue.MainQueue.DispatchAsync (() => { + var initialRegionOfInterest = this.PreviewView.VideoPreviewLayer.MapToLayerCoordinates (initialRectOfInterest); + this.PreviewView.SetRegionOfInterestWithProposedRegionOfInterest (initialRegionOfInterest); + }); + } else { + Console.WriteLine ("Could not add metadata output to the session"); + this.setupResult = SessionSetupResult.ConfigurationFailed; + this.session.CommitConfiguration (); + + return; + } + + this.session.CommitConfiguration (); + } + } + + #endregion + + #region Presets + + partial void SelectSessionPreset (UIButton sender) + { + var controller = new ItemSelectionViewController<NSString> (this, + SessionPresetItemSelectionIdentifier, + new List<NSString> (AvailableSessionPresets ()), + new List<NSString> { this.session.SessionPreset }, + false); + + this.PresentItemSelectionViewController (controller); + } + + private NSString [] AvailableSessionPresets () + { + return GetAllSessionPresets ().Where (preset => session.CanSetSessionPreset (preset)).ToArray (); + } + + private static IEnumerable<NSString> GetAllSessionPresets () + { + yield return AVCaptureSession.PresetPhoto; + yield return AVCaptureSession.PresetLow; + yield return AVCaptureSession.PresetMedium; + yield return AVCaptureSession.PresetHigh; + yield return AVCaptureSession.Preset352x288; + yield return AVCaptureSession.Preset640x480; + yield return AVCaptureSession.Preset1280x720; + yield return AVCaptureSession.PresetiFrame960x540; + yield return AVCaptureSession.PresetiFrame1280x720; + yield return AVCaptureSession.Preset1920x1080; + yield return AVCaptureSession.Preset3840x2160; + } + + #endregion + + #region Device Configuration + + partial void ChangeCamera (UIButton sender) + { + this.MetadataObjectTypesButton.Enabled = false; + this.SessionPresetsButton.Enabled = false; + this.CameraButton.Enabled = false; + this.ZoomSlider.Enabled = false; + + // Remove the metadata overlay layers, if any. + this.RemoveMetadataObjectOverlayLayers (); + + DispatchQueue.MainQueue.DispatchAsync (() => { + var preferredPosition = AVCaptureDevicePosition.Unspecified; + switch (this.videoDeviceInput.Device.Position) { + case AVCaptureDevicePosition.Unspecified: + case AVCaptureDevicePosition.Front: + preferredPosition = AVCaptureDevicePosition.Back; + break; + + case AVCaptureDevicePosition.Back: + preferredPosition = AVCaptureDevicePosition.Front; + break; + } + + var devices = AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video); + var videoDevice = devices.FirstOrDefault (device => device.Position == preferredPosition); + if (videoDevice != null) { + NSError error; + var captureDeviceInput = AVCaptureDeviceInput.FromDevice (videoDevice, out error); + if (error != null) { + Console.WriteLine ($"Error occurred while creating video device input: {error}"); + return; + } + + this.session.BeginConfiguration (); + + // Remove the existing device input first, since using the front and back camera simultaneously is not supported. + this.session.RemoveInput (this.videoDeviceInput); + + // When changing devices, a session preset that may be supported + // on one device may not be supported by another. To allow the + // user to successfully switch devices, we must save the previous + // session preset, set the default session preset (High), and + // attempt to restore it after the new video device has been + // added. For example, the 4K session preset is only supported + // by the back device on the iPhone 6s and iPhone 6s Plus. As a + // result, the session will not let us add a video device that + // does not support the current session preset. + var previousSessionPreset = this.session.SessionPreset; + this.session.SessionPreset = AVCaptureSession.PresetHigh; + + if (this.session.CanAddInput (captureDeviceInput)) { + this.session.AddInput (captureDeviceInput); + this.videoDeviceInput = captureDeviceInput; + } else { + this.session.AddInput (this.videoDeviceInput); + } + + // Restore the previous session preset if we can. + if (this.session.CanSetSessionPreset (previousSessionPreset)) { + this.session.SessionPreset = previousSessionPreset; + } + + this.session.CommitConfiguration (); + } + + this.MetadataObjectTypesButton.Enabled = true; + this.SessionPresetsButton.Enabled = true; + this.CameraButton.Enabled = true; + this.ZoomSlider.Enabled = true; + + this.ZoomSlider.MaxValue = (float) NMath.Min (this.videoDeviceInput.Device.ActiveFormat.VideoMaxZoomFactor, 8); + this.ZoomSlider.Value = (float) this.videoDeviceInput.Device.VideoZoomFactor; + }); + } + + partial void ZoomCamera (UISlider sender) + { + var device = this.videoDeviceInput.Device; + + NSError error; + this.videoDeviceInput.Device.LockForConfiguration (out error); + if (error == null) { + device.VideoZoomFactor = this.ZoomSlider.Value; + device.UnlockForConfiguration (); + } else { + Console.WriteLine ($"Could not lock for configuration: {error}"); + } + } + + #endregion + + #region KVO and Notifications + + private NSObject interruptionEndedNotificationToken; + + private NSObject wasInterruptedNotificationToken; + + private NSObject runtimeErrorNotificationToken; + + private IDisposable runningChangeToken; + + private void AddObservers () + { + this.runningChangeToken = this.session.AddObserver ("running", NSKeyValueObservingOptions.New, this.OnRunningChanged); + + // Observe the previewView's regionOfInterest to update the AVCaptureMetadataOutput's + // RectOfInterest when the user finishes resizing the region of interest. + this.PreviewView.RegionOfInterestChanged += this.OnRegionOfInterestChanged; + + var notificationCenter = NSNotificationCenter.DefaultCenter; + + this.runtimeErrorNotificationToken = notificationCenter.AddObserver (AVCaptureSession.RuntimeErrorNotification, this.OnRuntimeErrorNotification, this.session); + + // A session can only run when the app is full screen. It will be interrupted + // in a multi-app layout, introduced in iOS 9, see also the documentation of + // AVCaptureSessionInterruptionReason.Add observers to handle these session + // interruptions and show a preview is paused message.See the documentation + // of AVCaptureSessionWasInterruptedNotification for other interruption reasons. + this.wasInterruptedNotificationToken = notificationCenter.AddObserver (AVCaptureSession.WasInterruptedNotification, this.OnSessionWasInterrupted, this.session); + this.interruptionEndedNotificationToken = notificationCenter.AddObserver (AVCaptureSession.InterruptionEndedNotification, this.OnSessionInterruptionEnded, this.session); + } + + private void RemoveObservers () + { + this.runningChangeToken?.Dispose (); + this.runtimeErrorNotificationToken?.Dispose (); + this.wasInterruptedNotificationToken?.Dispose (); + this.interruptionEndedNotificationToken?.Dispose (); + this.PreviewView.RegionOfInterestChanged -= this.OnRegionOfInterestChanged; + } + + private void OnRegionOfInterestChanged (object sender, EventArgs e) + { + var newRegion = (sender as PreviewView).RegionOfInterest; + DispatchQueue.MainQueue.DispatchAsync (() => { + // Ensure we are not drawing old metadata object overlays. + this.RemoveMetadataObjectOverlayLayers (); + + // Translate the preview view's region of interest to the metadata output's coordinate system. + var metadataOutputRectOfInterest = this.PreviewView.VideoPreviewLayer.MapToMetadataOutputCoordinates (newRegion); + + this.sessionQueue.DispatchAsync (() => { + // Update the AVCaptureMetadataOutput with the new region of interest + metadataOutput.RectOfInterest = metadataOutputRectOfInterest; + }); + }); + } + + private void OnRunningChanged (NSObservedChange change) + { + var isSessionRunning = ((NSNumber) change.NewValue).BoolValue; + + DispatchQueue.MainQueue.DispatchAsync (() => { + this.CameraButton.Enabled = isSessionRunning && AVCaptureDevice.DevicesWithMediaType (AVMediaType.Video).Length > 1; + this.MetadataObjectTypesButton.Enabled = isSessionRunning; + this.SessionPresetsButton.Enabled = isSessionRunning; + + this.ZoomSlider.Enabled = isSessionRunning; + this.ZoomSlider.MaxValue = (float) NMath.Min (this.videoDeviceInput.Device.ActiveFormat.VideoMaxZoomFactor, 8); + this.ZoomSlider.Value = (float) (this.videoDeviceInput.Device.VideoZoomFactor); + + // After the session stop running, remove the metadata object overlays, + // if any, so that if the view appears again, the previously displayed + // metadata object overlays are removed. + if (!isSessionRunning) { + this.RemoveMetadataObjectOverlayLayers (); + } + + // When the session starts running, the aspect ration of the video preview may also change if a new session present was applied . + // To keep the preview view's region of interest within the visible portion of the video preview, the preview view's region of + // interest will need to be updates. + if (isSessionRunning) { + this.PreviewView.SetRegionOfInterestWithProposedRegionOfInterest (this.PreviewView.RegionOfInterest); + } + }); + } + + private void OnRuntimeErrorNotification (NSNotification notification) + { + var args = new AVCaptureSessionRuntimeErrorEventArgs (notification); + if (args.Error != null) { + var error = (AVError) (long) args.Error.Code; + Console.WriteLine ($"Capture session runtime error: {error}"); + + // Automatically try to restart the session running if media services were + // reset and the last start running succeeded. Otherwise, enable the user + // to try to resume the session running. + + if (error == AVError.MediaServicesWereReset) { + this.sessionQueue.DispatchAsync (() => { + if (this.isSessionRunning) { + this.session.StartRunning (); + this.isSessionRunning = session.Running; + } + }); + } + } + } + + private void OnSessionWasInterrupted (NSNotification notification) + { + // In some scenarios we want to enable the user to resume the session running. + // For example, if music playback is initiated via control center while + // using AVMetadataRecordPlay, then the user can let AVMetadataRecordPlay resume + // the session running, which will stop music playback. Note that stopping + // music playback in control center will not automatically resume the session + // running. Also note that it is not always possible to resume + + var reasonIntegerValue = ((NSNumber) notification.UserInfo [AVCaptureSession.InterruptionReasonKey]).Int32Value; + var reason = (AVCaptureSessionInterruptionReason) reasonIntegerValue; + Console.WriteLine ($"Capture session was interrupted with reason {reason}"); + + if (reason == AVCaptureSessionInterruptionReason.VideoDeviceNotAvailableWithMultipleForegroundApps) { + // Simply fade-in a label to inform the user that the camera is unavailable. + this.CameraUnavailableLabel.Hidden = false; + this.CameraUnavailableLabel.Alpha = 0; + UIView.Animate (0.25d, () => this.CameraUnavailableLabel.Alpha = 1); + } + } + + private void OnSessionInterruptionEnded (NSNotification notification) + { + Console.WriteLine ("Capture session interruption ended"); + + if (this.CameraUnavailableLabel.Hidden) { + UIView.Animate (0.25, () => { + this.CameraUnavailableLabel.Alpha = 0; + }, () => { + this.CameraUnavailableLabel.Hidden = true; + }); + } + } + + #endregion + + #region Drawing Metadata Object Overlay Layers + + private NSTimer removeMetadataObjectOverlayLayersTimer; + + partial void SelectMetadataObjectTypes (UIButton sender) + { + var controller = new ItemSelectionViewController<AVMetadataObjectType> (this, + MetadataObjectTypeItemSelectionIdentifier, + this.metadataOutput.AvailableMetadataObjectTypes.GetFlags ().ToList (), + this.metadataOutput.MetadataObjectTypes.GetFlags ().ToList (), + true); + + this.PresentItemSelectionViewController (controller); + } + + private MetadataObjectLayer CreateMetadataOverlay (AVMetadataObject metadataObject) + { + // Transform the metadata object so the bounds are updated to reflect those of the video preview layer. + var transformedMetadataObject = this.PreviewView.VideoPreviewLayer.GetTransformedMetadataObject (metadataObject); + + // Create the initial metadata object overlay layer that can be used for either machine readable codes or faces. + var metadataObjectOverlayLayer = new MetadataObjectLayer { + LineWidth = 7, + LineJoin = CAShapeLayer.JoinRound, + MetadataObject = transformedMetadataObject, + FillColor = this.View.TintColor.ColorWithAlpha (0.3f).CGColor, + StrokeColor = this.View.TintColor.ColorWithAlpha (0.7f).CGColor, + }; + + var barcodeMetadataObject = transformedMetadataObject as AVMetadataMachineReadableCodeObject; + if (barcodeMetadataObject != null) { + var barcodeOverlayPath = this.BarcodeOverlayPathWithCorners (barcodeMetadataObject.Corners); + metadataObjectOverlayLayer.Path = barcodeOverlayPath; + + // If the metadata object has a string value, display it. + string textLayerString = null; + if (!string.IsNullOrEmpty (barcodeMetadataObject.StringValue)) { + textLayerString = barcodeMetadataObject.StringValue; + } else { + // TODO: add Descriptor (line 618 in original iOS sample) + } + + if (!string.IsNullOrEmpty (textLayerString)) { + var barcodeOverlayBoundingBox = barcodeOverlayPath.BoundingBox; + + var font = UIFont.BoldSystemFontOfSize (19).ToCTFont (); + var textLayer = new CATextLayer { + AlignmentMode = CATextLayer.AlignmentCenter, + Bounds = new CGRect (0, 0, barcodeOverlayBoundingBox.Size.Width, barcodeOverlayBoundingBox.Size.Height), + ContentsScale = UIScreen.MainScreen.Scale, + Position = new CGPoint (barcodeOverlayBoundingBox.GetMidX (), barcodeOverlayBoundingBox.GetMidY ()), + Wrapped = true, + + // Invert the effect of transform of the video preview so the text is oriented with the interface orientation + Transform = CATransform3D.MakeFromAffine (this.PreviewView.Transform).Invert (), + String = textLayerString, + AttributedString = new NSAttributedString (textLayerString, new CTStringAttributes { + Font = font, + StrokeWidth = -5, + StrokeColor = UIColor.Black.CGColor, + ForegroundColor = UIColor.White.CGColor, + }), + }; + + textLayer.SetFont (font); + metadataObjectOverlayLayer.AddSublayer (textLayer); + } + } else if (transformedMetadataObject is AVMetadataFaceObject) { + metadataObjectOverlayLayer.Path = CGPath.FromRect (transformedMetadataObject.Bounds); + } + + return metadataObjectOverlayLayer; + } + + private CGPath BarcodeOverlayPathWithCorners (CGPoint [] corners) + { + var path = new CGPath (); + + if (corners.Any ()) { + path.MoveToPoint (CGAffineTransform.MakeIdentity (), corners [0]); + + for (int i = 1; i < corners.Length; i++) { + path.AddLineToPoint (corners [i]); + } + + path.CloseSubpath (); + } + + return path; + } + + private void RemoveMetadataObjectOverlayLayers () + { + this.metadataObjectOverlayLayers.ForEach (layer => layer.RemoveFromSuperLayer ()); + this.metadataObjectOverlayLayers.Clear (); + + this.removeMetadataObjectOverlayLayersTimer?.Invalidate (); + this.removeMetadataObjectOverlayLayersTimer = null; + } + + private void AddMetadataOverlayLayers (IEnumerable<MetadataObjectLayer> layers) + { + // Add the metadata object overlays as sublayers of the video preview layer. We disable actions to allow for fast drawing. + CATransaction.Begin (); + CATransaction.DisableActions = true; + + foreach (var layer in layers) { + this.PreviewView.VideoPreviewLayer.AddSublayer (layer); + this.metadataObjectOverlayLayers.Add (layer); // Save the new metadata object overlays. + } + + CATransaction.Commit (); + + // Create a timer to destroy the metadata object overlays. + this.removeMetadataObjectOverlayLayersTimer = NSTimer.CreateScheduledTimer (TimeSpan.FromSeconds (1), (param) => this.RemoveMetadataObjectOverlayLayers ()); + } + + private void OpenBarcodeUrl (UITapGestureRecognizer openBarcodeURLGestureRecognizer) + { + foreach (var metadataObjectOverlayLayer in this.metadataObjectOverlayLayers) { + var location = openBarcodeURLGestureRecognizer.LocationInView (this.PreviewView); + if (metadataObjectOverlayLayer.Path.ContainsPoint (location, false)) { + var barcodeMetadataObject = metadataObjectOverlayLayer.MetadataObject as AVMetadataMachineReadableCodeObject; + if (barcodeMetadataObject != null) { + if (!string.IsNullOrEmpty (barcodeMetadataObject.StringValue)) { + var url = NSUrl.FromString (barcodeMetadataObject.StringValue); + if (UIApplication.SharedApplication.CanOpenUrl (url)) { + UIApplication.SharedApplication.OpenUrl (url); + } + } + } + } + } + } + + #endregion + + #region AVCaptureMetadataOutputObjectsDelegate + + private readonly AutoResetEvent resetEvent = new AutoResetEvent (true); + + [Export ("captureOutput:didOutputMetadataObjects:fromConnection:")] + public void DidOutputMetadataObjects (AVCaptureMetadataOutput captureOutput, AVMetadataObject [] metadataObjects, AVCaptureConnection connection) + { + // resetEvent is used to drop new notifications if old ones are still processing, to avoid queuing up a bunch of stale data. + if (this.resetEvent.WaitOne (0)) { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.RemoveMetadataObjectOverlayLayers (); + this.AddMetadataOverlayLayers (metadataObjects.Select (this.CreateMetadataOverlay)); + + this.resetEvent.Set (); + }); + } + } + + #endregion + + #region ItemSelectionViewControllerDelegate + + private const string MetadataObjectTypeItemSelectionIdentifier = "MetadataObjectTypes"; + + private const string SessionPresetItemSelectionIdentifier = "SessionPreset"; + + public void ItemSelectionViewController<T> (ItemSelectionViewController<T> itemSelectionViewController, IList<T> selectedItems) + { + var identifier = itemSelectionViewController.Identifier; + if (identifier == MetadataObjectTypeItemSelectionIdentifier) { + this.sessionQueue.DispatchAsync (() => { + this.metadataOutput.MetadataObjectTypes = selectedItems.OfType<AVMetadataObjectType> ().Aggregate ((t1, t2) => t1 | t2); + }); + } else if (identifier == SessionPresetItemSelectionIdentifier) { + this.sessionQueue.DispatchAsync (() => { + this.session.SessionPreset = selectedItems.OfType<NSString> ().FirstOrDefault (); + }); + } + } + + #endregion + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Enums/ControlCorner.cs b/ios11/AVCamBarcode/AVCamBarcode/Enums/ControlCorner.cs index 8a1669a28..5030da87f 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Enums/ControlCorner.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Enums/ControlCorner.cs @@ -1,16 +1,14 @@ - -namespace AVCamBarcode -{ - public enum ControlCorner - { - None, - TopLeft, +namespace AVCamBarcode { + public enum ControlCorner { + None, - TopRight, + TopLeft, - BottomLeft, + TopRight, - BottomRight - } -} \ No newline at end of file + BottomLeft, + + BottomRight + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Enums/SessionSetupResult.cs b/ios11/AVCamBarcode/AVCamBarcode/Enums/SessionSetupResult.cs index 7f1a94bb0..3aee98fef 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Enums/SessionSetupResult.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Enums/SessionSetupResult.cs @@ -1,12 +1,10 @@ - -namespace AVCamBarcode -{ - public enum SessionSetupResult - { - Success, - NotAuthorized, +namespace AVCamBarcode { + public enum SessionSetupResult { + Success, - ConfigurationFailed - } -} \ No newline at end of file + NotAuthorized, + + ConfigurationFailed + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Extensions/CGRectExtensions.cs b/ios11/AVCamBarcode/AVCamBarcode/Extensions/CGRectExtensions.cs index a674a11f2..d15d1d8f7 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Extensions/CGRectExtensions.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Extensions/CGRectExtensions.cs @@ -1,29 +1,27 @@ - -namespace AVCamBarcode.Extensions -{ - using CoreGraphics; - public static class CGRectExtensions - { - public static CGPoint CornerTopLeft(this CGRect rect) - { - return rect.Location; - } +namespace AVCamBarcode.Extensions { + using CoreGraphics; - public static CGPoint CornerTopRight(this CGRect rect) - { - rect.X += rect.Width; - return rect.Location; - } + public static class CGRectExtensions { + public static CGPoint CornerTopLeft (this CGRect rect) + { + return rect.Location; + } - public static CGPoint CornerBottomRight(this CGRect rect) - { - return new CGPoint(rect.GetMaxX(), rect.GetMaxY()); - } + public static CGPoint CornerTopRight (this CGRect rect) + { + rect.X += rect.Width; + return rect.Location; + } - public static CGPoint CornerBottomLeft(this CGRect rect) - { - return new CGPoint(rect.GetMinX(), rect.GetMaxY()); - } - } -} \ No newline at end of file + public static CGPoint CornerBottomRight (this CGRect rect) + { + return new CGPoint (rect.GetMaxX (), rect.GetMaxY ()); + } + + public static CGPoint CornerBottomLeft (this CGRect rect) + { + return new CGPoint (rect.GetMinX (), rect.GetMaxY ()); + } + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Extensions/EnumExtensions.cs b/ios11/AVCamBarcode/AVCamBarcode/Extensions/EnumExtensions.cs index acb5e36bd..2f9df398c 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Extensions/EnumExtensions.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Extensions/EnumExtensions.cs @@ -1,26 +1,22 @@ - -namespace AVCamBarcode.Extensions -{ - using AVFoundation; - using System.Collections.Generic; - public static class EnumExtensions - { - public static IEnumerable<AVMetadataObjectType> GetFlags(this AVMetadataObjectType metadataObjectType) - { - var shifts = 0; +namespace AVCamBarcode.Extensions { + using AVFoundation; + using System.Collections.Generic; - var value = (ulong)metadataObjectType; - while (value != 0) - { - if ((value & 1) == 1) - { - yield return (AVMetadataObjectType)(1 << shifts); - } + public static class EnumExtensions { + public static IEnumerable<AVMetadataObjectType> GetFlags (this AVMetadataObjectType metadataObjectType) + { + var shifts = 0; - shifts++; - value >>= 1; - } - } - } -} \ No newline at end of file + var value = (ulong) metadataObjectType; + while (value != 0) { + if ((value & 1) == 1) { + yield return (AVMetadataObjectType) (1 << shifts); + } + + shifts++; + value >>= 1; + } + } + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Extensions/FontExtensions.cs b/ios11/AVCamBarcode/AVCamBarcode/Extensions/FontExtensions.cs index a9cdbcb54..02a3cb5ec 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Extensions/FontExtensions.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Extensions/FontExtensions.cs @@ -1,14 +1,12 @@ - -namespace AVCamBarcode.Extensions -{ - using CoreText; - using UIKit; - public static class FontExtensions - { - public static CTFont ToCTFont(this UIFont font) - { - return new CTFont(font.Name, font.PointSize); - } - } -} \ No newline at end of file +namespace AVCamBarcode.Extensions { + using CoreText; + using UIKit; + + public static class FontExtensions { + public static CTFont ToCTFont (this UIFont font) + { + return new CTFont (font.Name, font.PointSize); + } + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/ItemSelectionViewController.cs b/ios11/AVCamBarcode/AVCamBarcode/ItemSelectionViewController.cs index 53fc159b2..2b46a9775 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/ItemSelectionViewController.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/ItemSelectionViewController.cs @@ -1,106 +1,99 @@ - -namespace AVCamBarcode -{ - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - public interface IItemSelectionViewControllerDelegate - { - void ItemSelectionViewController<T>(ItemSelectionViewController<T> itemSelectionViewController, IList<T> selectedItems); - } - - public class ItemSelectionViewController<T> : UITableViewController - { - private const string itemCellIdentifier = "Item"; - - private readonly IItemSelectionViewControllerDelegate @delegate; - - private bool isMultipleSelectionAllowed; - - private readonly IList<T> selectedItems; - - private readonly IList<T> items; - - public ItemSelectionViewController(IItemSelectionViewControllerDelegate @delegate, - string identifier, - IList<T> items, - IList<T> selectedItems, - bool isMultipleSelectionAllowed) : base(UITableViewStyle.Grouped) - { - this.@delegate = @delegate; - this.Identifier = identifier; - this.items = items; - this.selectedItems = selectedItems; - this.isMultipleSelectionAllowed = isMultipleSelectionAllowed; - - base.NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Done, (sender, args) => this.Done()); - this.TableView.RegisterClassForCellReuse(typeof(UITableViewCell), itemCellIdentifier); - } - - public string Identifier { get; private set; } - - private void Done() - { - // Notify the delegate that selecting items is finished. - this.@delegate?.ItemSelectionViewController(this, this.selectedItems); - - // Dismiss the view controller. - this.DismissViewController(true, null); - } - - #region UITableView - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var item = this.items[indexPath.Row]; - - var cell = tableView.DequeueReusableCell(itemCellIdentifier, indexPath); - cell.TintColor = UIColor.Black; - cell.TextLabel.Text = item.ToString(); - cell.Accessory = this.selectedItems.Contains(item) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; - - return cell; - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.items.Count; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - NSIndexPath[] indexPathsToReload = null; - if (this.isMultipleSelectionAllowed) - { - var item = this.items[indexPath.Row]; - if (!this.selectedItems.Remove(item)) - { - this.selectedItems.Add(item); - } - - indexPathsToReload = new NSIndexPath[] { indexPath }; - } - else - { - indexPathsToReload = !this.selectedItems.Any() - ? new NSIndexPath[] { indexPath } - : this.selectedItems.Select(item => this.items.IndexOf(item)) - .Select(index => NSIndexPath.FromRowSection(index, 0)) - .Concat(new NSIndexPath[] { indexPath }) - .ToArray(); - - this.selectedItems.Clear(); - this.selectedItems.Add(this.items[indexPath.Row]); - } - - // Deselect the selected row & reload the table view cells for the old and new items to swap checkmarks. - tableView.DeselectRow(indexPath, true); - tableView.ReloadRows(indexPathsToReload, UITableViewRowAnimation.Automatic); - } - - #endregion - } -} \ No newline at end of file + +namespace AVCamBarcode { + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + public interface IItemSelectionViewControllerDelegate { + void ItemSelectionViewController<T> (ItemSelectionViewController<T> itemSelectionViewController, IList<T> selectedItems); + } + + public class ItemSelectionViewController<T> : UITableViewController { + private const string itemCellIdentifier = "Item"; + + private readonly IItemSelectionViewControllerDelegate @delegate; + + private bool isMultipleSelectionAllowed; + + private readonly IList<T> selectedItems; + + private readonly IList<T> items; + + public ItemSelectionViewController (IItemSelectionViewControllerDelegate @delegate, + string identifier, + IList<T> items, + IList<T> selectedItems, + bool isMultipleSelectionAllowed) : base (UITableViewStyle.Grouped) + { + this.@delegate = @delegate; + this.Identifier = identifier; + this.items = items; + this.selectedItems = selectedItems; + this.isMultipleSelectionAllowed = isMultipleSelectionAllowed; + + base.NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, (sender, args) => this.Done ()); + this.TableView.RegisterClassForCellReuse (typeof (UITableViewCell), itemCellIdentifier); + } + + public string Identifier { get; private set; } + + private void Done () + { + // Notify the delegate that selecting items is finished. + this.@delegate?.ItemSelectionViewController (this, this.selectedItems); + + // Dismiss the view controller. + this.DismissViewController (true, null); + } + + #region UITableView + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var item = this.items [indexPath.Row]; + + var cell = tableView.DequeueReusableCell (itemCellIdentifier, indexPath); + cell.TintColor = UIColor.Black; + cell.TextLabel.Text = item.ToString (); + cell.Accessory = this.selectedItems.Contains (item) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + + return cell; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.items.Count; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + NSIndexPath [] indexPathsToReload = null; + if (this.isMultipleSelectionAllowed) { + var item = this.items [indexPath.Row]; + if (!this.selectedItems.Remove (item)) { + this.selectedItems.Add (item); + } + + indexPathsToReload = new NSIndexPath [] { indexPath }; + } else { + indexPathsToReload = !this.selectedItems.Any () + ? new NSIndexPath [] { indexPath } + : this.selectedItems.Select (item => this.items.IndexOf (item)) + .Select (index => NSIndexPath.FromRowSection (index, 0)) + .Concat (new NSIndexPath [] { indexPath }) + .ToArray (); + + this.selectedItems.Clear (); + this.selectedItems.Add (this.items [indexPath.Row]); + } + + // Deselect the selected row & reload the table view cells for the old and new items to swap checkmarks. + tableView.DeselectRow (indexPath, true); + tableView.ReloadRows (indexPathsToReload, UITableViewRowAnimation.Automatic); + } + + #endregion + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Main.cs b/ios11/AVCamBarcode/AVCamBarcode/Main.cs index a2220c74a..ae60d2221 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Main.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Main.cs @@ -1,16 +1,14 @@ - -namespace AVCamBarcode -{ -using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace AVCamBarcode { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/MetadataObjectLayer.cs b/ios11/AVCamBarcode/AVCamBarcode/MetadataObjectLayer.cs index 3222e4c60..3b1bfcbe9 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/MetadataObjectLayer.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/MetadataObjectLayer.cs @@ -1,11 +1,9 @@ - -namespace AVCamBarcode -{ - using AVFoundation; - using CoreAnimation; - public class MetadataObjectLayer : CAShapeLayer - { - public AVMetadataObject MetadataObject { get; set; } - } -} \ No newline at end of file +namespace AVCamBarcode { + using AVFoundation; + using CoreAnimation; + + public class MetadataObjectLayer : CAShapeLayer { + public AVMetadataObject MetadataObject { get; set; } + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/PreviewView.cs b/ios11/AVCamBarcode/AVCamBarcode/PreviewView.cs index 66ca5f4b8..6f7640d72 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/PreviewView.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/PreviewView.cs @@ -1,482 +1,449 @@ - -namespace AVCamBarcode -{ - using AVCamBarcode.Extensions; - using AVFoundation; - using CoreAnimation; - using CoreGraphics; - using Foundation; - using ObjCRuntime; - using System; - using UIKit; - - [Register("PreviewView")] - public class PreviewView : UIView, IUIGestureRecognizerDelegate - { - private static readonly object layerClassLock = new object(); - - private static Class layerClass; - - private const float RegionOfInterestCornerTouchThreshold = 50; - - private const float RegionOfInterestControlDiameter = 12; - - private readonly CAShapeLayer maskLayer = new CAShapeLayer(); - - private readonly CAShapeLayer regionOfInterestOutline = new CAShapeLayer(); - - /// <summary> - /// White dot on the top left of the region of interest. - /// </summary> - private readonly CAShapeLayer topLeftControl = new CAShapeLayer(); - - /// <summary> - /// White dot on the top right of the region of interest. - /// </summary> - private readonly CAShapeLayer topRightControl = new CAShapeLayer(); - - /// <summary> - /// White dot on the bottom left of the region of interest. - /// </summary> - private readonly CAShapeLayer bottomLeftControl = new CAShapeLayer(); - - /// <summary> - /// White dot on the bottom right of the region of interest. - /// </summary> - private readonly CAShapeLayer bottomRightControl = new CAShapeLayer(); - - /// <summary> - /// Saves a reference to the control corner that the user is using to resize - /// the region of interest in `resizeRegionOfInterestWithGestureRecognizer()`. - /// </summary> - private ControlCorner currentControlCorner = ControlCorner.None; - - private UIPanGestureRecognizer resizeRegionOfInterestGestureRecognizer; - - public event EventHandler RegionOfInterestChanged; - - public PreviewView(CGRect frame) : base(frame) - { - this.Initialize(); - } - - [Export("initWithCoder:")] - public PreviewView(NSCoder coder) : base(coder) - { - this.Initialize(); - } - - public static Class LayerClass - { - [Export("layerClass")] - get - { - if (layerClass == null) - { - lock (layerClassLock) - { - if (layerClass == null) - { - layerClass = new Class(typeof(AVCaptureVideoPreviewLayer)); - } - } - } - - return layerClass; - } - } - - // Region of Interest - - /// <summary> - /// The minimum region of interest's size cannot be smaller than the corner - /// touch threshold as to avoid control selection conflicts when a user tries - /// to resize the region of interest. - /// </summary> - protected float MinimumRegionOfInterestSize => RegionOfInterestCornerTouchThreshold; - - protected float RegionOfInterestControlRadius => RegionOfInterestControlDiameter / 2; - - public bool IsResizingRegionOfInterest => this.resizeRegionOfInterestGestureRecognizer.State == UIGestureRecognizerState.Changed; - - // This property is set only in `setRegionOfInterestWithProposedRegionOfInterest()`. - // When a user is resizing the region of interest in `resizeRegionOfInterestWithGestureRecognizer()`, - // the KVO notification will be triggered when the resizing is finished. - public CGRect RegionOfInterest { get; private set; } - - // AV capture properties - - public AVCaptureVideoPreviewLayer VideoPreviewLayer => this.Layer as AVCaptureVideoPreviewLayer; - - public AVCaptureSession Session - { - get - { - return this.VideoPreviewLayer.Session; - } - - set - { - this.VideoPreviewLayer.Session = value; - } - } - - protected UIPanGestureRecognizer ResizeRegionOfInterestGestureRecognizer - { - get - { - if (this.resizeRegionOfInterestGestureRecognizer == null) - { - this.resizeRegionOfInterestGestureRecognizer = new UIPanGestureRecognizer(this.ResizeRegionOfInterestWithGestureRecognizer); - } - - return this.resizeRegionOfInterestGestureRecognizer; - } - } - - private void Initialize() - { - this.maskLayer.FillRule = CAShapeLayer.FillRuleEvenOdd; - this.maskLayer.FillColor = UIColor.Black.CGColor; - this.maskLayer.Opacity = 0.6f; - this.Layer.AddSublayer(this.maskLayer); - - this.regionOfInterestOutline.Path = UIBezierPath.FromRect(this.RegionOfInterest).CGPath; - this.regionOfInterestOutline.FillColor = UIColor.Clear.CGColor; - this.regionOfInterestOutline.StrokeColor = UIColor.Yellow.CGColor; - this.Layer.AddSublayer(this.regionOfInterestOutline); - - var controlRect = new CGRect(0, 0, RegionOfInterestControlDiameter, RegionOfInterestControlDiameter); - - this.topLeftControl.Path = UIBezierPath.FromOval(controlRect).CGPath; - this.topLeftControl.FillColor = UIColor.White.CGColor; - this.Layer.AddSublayer(this.topLeftControl); - - this.topRightControl.Path = UIBezierPath.FromOval(controlRect).CGPath; - this.topRightControl.FillColor = UIColor.White.CGColor; - this.Layer.AddSublayer(this.topRightControl); - - this.bottomLeftControl.Path = UIBezierPath.FromOval(controlRect).CGPath; - this.bottomLeftControl.FillColor = UIColor.White.CGColor; - this.Layer.AddSublayer(this.bottomLeftControl); - - this.bottomRightControl.Path = UIBezierPath.FromOval(controlRect).CGPath; - this.bottomRightControl.FillColor = UIColor.White.CGColor; - this.Layer.AddSublayer(this.bottomRightControl); - - // Add the region of interest gesture recognizer to the region of interest - // view so that the region of interest can be resized and moved. If you - // would like to have a fixed region of interest that cannot be resized - // or moved, do not add the following gesture recognizer. You will simply - // need to set the region of interest once. - this.ResizeRegionOfInterestGestureRecognizer.Delegate = this; - this.AddGestureRecognizer(this.ResizeRegionOfInterestGestureRecognizer); - } - - /// <summary> - /// Updates the region of interest with a proposed region of interest ensuring - /// the new region of interest is within the bounds of the video preview. When - /// a new region of interest is set, the region of interest is redrawn. - /// </summary> - /// <param name="proposedRegionOfInterest"></param> - public void SetRegionOfInterestWithProposedRegionOfInterest(CGRect proposedRegionOfInterest) - { - // We standardize to ensure we have positive widths and heights with an origin at the top left. - var videoPreviewRect = this.VideoPreviewLayer.MapToLayerCoordinates(new CGRect(0, 0, 1, 1)).Standardize(); - - // Intersect the video preview view with the view's frame to only get - // the visible portions of the video preview view. - - var visibleVideoPreviewRect = CGRect.Intersect(videoPreviewRect, this.Frame); - var oldRegionOfInterest = this.RegionOfInterest; - var newRegionOfInterest = proposedRegionOfInterest.Standardize(); - - // Move the region of interest in bounds. - if (this.currentControlCorner == ControlCorner.None) - { - nfloat xOffset = 0; - nfloat yOffset = 0; - - if (!visibleVideoPreviewRect.Contains(newRegionOfInterest.CornerTopLeft())) - { - xOffset = NMath.Max(visibleVideoPreviewRect.GetMinX() - newRegionOfInterest.GetMinX(), 0); - yOffset = NMath.Max(visibleVideoPreviewRect.GetMinY() - newRegionOfInterest.GetMinY(), 0); - } - - if (!visibleVideoPreviewRect.Contains(visibleVideoPreviewRect.CornerBottomRight())) - { - xOffset = NMath.Min(visibleVideoPreviewRect.GetMaxX() - newRegionOfInterest.GetMaxX(), xOffset); - yOffset = NMath.Min(visibleVideoPreviewRect.GetMaxY() - newRegionOfInterest.GetMaxY(), yOffset); - } - - newRegionOfInterest.Offset(xOffset, yOffset); - } - - // Clamp the size when the region of interest is being resized. - visibleVideoPreviewRect.Intersect(newRegionOfInterest); - newRegionOfInterest = visibleVideoPreviewRect; - - // Fix a minimum width of the region of interest. - if (proposedRegionOfInterest.Size.Width < this.MinimumRegionOfInterestSize) - { - switch (this.currentControlCorner) - { - case ControlCorner.TopLeft: - case ControlCorner.BottomLeft: - var x = oldRegionOfInterest.Location.X + oldRegionOfInterest.Size.Width - this.MinimumRegionOfInterestSize; - - newRegionOfInterest.X = x; - newRegionOfInterest.Width = this.MinimumRegionOfInterestSize; - break; - - case ControlCorner.TopRight: - newRegionOfInterest.X = oldRegionOfInterest.Location.X; - newRegionOfInterest.Width = this.MinimumRegionOfInterestSize; - break; - - default: - newRegionOfInterest.Location = oldRegionOfInterest.Location; - newRegionOfInterest.Width = this.MinimumRegionOfInterestSize; - break; - } - } - - // Fix a minimum height of the region of interest. - if (proposedRegionOfInterest.Height < this.MinimumRegionOfInterestSize) - { - switch (currentControlCorner) - { - case ControlCorner.TopLeft: - case ControlCorner.TopRight: - newRegionOfInterest.Y = oldRegionOfInterest.Y + oldRegionOfInterest.Height - this.MinimumRegionOfInterestSize; - newRegionOfInterest.Height = this.MinimumRegionOfInterestSize; - break; - - case ControlCorner.BottomLeft: - newRegionOfInterest.Y = oldRegionOfInterest.Y; - newRegionOfInterest.Height = this.MinimumRegionOfInterestSize; - break; - - default: - newRegionOfInterest.Location = oldRegionOfInterest.Location; - newRegionOfInterest.Height = this.MinimumRegionOfInterestSize; - break; - } - } - - this.RegionOfInterest = newRegionOfInterest; - this.SetNeedsLayout(); - } - - private void ResizeRegionOfInterestWithGestureRecognizer(UIPanGestureRecognizer gestureRecognizer) - { - var touchLocation = gestureRecognizer.LocationInView(gestureRecognizer.View); - var oldRegionOfInterest = this.RegionOfInterest; - - switch (gestureRecognizer.State) - { - case UIGestureRecognizerState.Began: - // When the gesture begins, save the corner that is closes to - // the resize region of interest gesture recognizer's touch location. - this.currentControlCorner = CornerOfRect(oldRegionOfInterest, touchLocation); - break; - - - case UIGestureRecognizerState.Changed: - var newRegionOfInterest = oldRegionOfInterest; - - switch (this.currentControlCorner) - { - case ControlCorner.None: - // Update the new region of interest with the gesture recognizer's translation. - var translation = gestureRecognizer.TranslationInView(gestureRecognizer.View); - - // Move the region of interest with the gesture recognizer's translation. - if (this.RegionOfInterest.Contains(touchLocation)) - { - newRegionOfInterest.X += translation.X; - newRegionOfInterest.Y += translation.Y; - } - - // If the touch location goes outside the preview layer, - // we will only translate the region of interest in the - // plane that is not out of bounds. - var normalizedRect = new CGRect(0, 0, 1, 1); - if (!normalizedRect.Contains(this.VideoPreviewLayer.PointForCaptureDevicePointOfInterest(touchLocation))) - { - if (touchLocation.X < RegionOfInterest.GetMinX() || touchLocation.X > RegionOfInterest.GetMaxX()) - { - newRegionOfInterest.Y += translation.Y; - } - else if (touchLocation.Y < RegionOfInterest.GetMinY() || touchLocation.Y > RegionOfInterest.GetMaxY()) - { - newRegionOfInterest.X += translation.X; - } - } - - // Set the translation to be zero so that the new gesture - // recognizer's translation is in respect to the region of - // interest's new position. - gestureRecognizer.SetTranslation(CGPoint.Empty, gestureRecognizer.View); - break; - - case ControlCorner.TopLeft: - newRegionOfInterest = new CGRect(touchLocation.X, touchLocation.Y, - oldRegionOfInterest.Width + oldRegionOfInterest.X - touchLocation.X, - oldRegionOfInterest.Height + oldRegionOfInterest.Y - touchLocation.Y); - break; - - case ControlCorner.TopRight: - newRegionOfInterest = new CGRect(newRegionOfInterest.X, - touchLocation.Y, - touchLocation.X - newRegionOfInterest.X, - oldRegionOfInterest.Height + newRegionOfInterest.Y - touchLocation.Y); - break; - - - case ControlCorner.BottomLeft: - newRegionOfInterest = new CGRect(touchLocation.X, - oldRegionOfInterest.Y, - oldRegionOfInterest.Width + oldRegionOfInterest.X - touchLocation.X, - touchLocation.Y - oldRegionOfInterest.Y); - break; - - case ControlCorner.BottomRight: - newRegionOfInterest = new CGRect(oldRegionOfInterest.X, - oldRegionOfInterest.Y, - touchLocation.X - oldRegionOfInterest.X, - touchLocation.Y - oldRegionOfInterest.Y); - break; - } - - // Update the region of interest with a valid CGRect. - this.SetRegionOfInterestWithProposedRegionOfInterest(newRegionOfInterest); - break; - - case UIGestureRecognizerState.Ended: - this.RegionOfInterestChanged?.Invoke(this, EventArgs.Empty); - - // Reset the current corner reference to none now that the resize. - // gesture recognizer has ended. - this.currentControlCorner = ControlCorner.None; - break; - - default: - return; - } - } - - private ControlCorner CornerOfRect(CGRect rect, CGPoint point) - { - var closestDistance = nfloat.MaxValue; - var closestCorner = ControlCorner.None; - - Tuple<ControlCorner, CGPoint>[] corners = { - Tuple (ControlCorner.TopLeft, rect.CornerTopLeft()), - Tuple (ControlCorner.TopRight, rect.CornerTopRight ()), - Tuple (ControlCorner.BottomLeft, rect.CornerBottomLeft ()), - Tuple (ControlCorner.BottomRight, rect.CornerBottomRight()) - }; - - foreach (var tuple in corners) - { - var corner = tuple.Item1; - var cornerPoint = tuple.Item2; - - var dX = point.X - cornerPoint.X; - var dY = point.Y - cornerPoint.Y; - var distance = NMath.Sqrt((dX * dX) + (dY * dY)); - - if (distance < closestDistance) - { - closestDistance = distance; - closestCorner = corner; - } - } - - if (closestDistance > RegionOfInterestCornerTouchThreshold) - { - closestCorner = ControlCorner.None; - } - - return closestCorner; - } - - private static Tuple<ControlCorner, CGPoint> Tuple(ControlCorner corner, CGPoint point) - { - return new Tuple<ControlCorner, CGPoint>(corner, point); - } - - #region UIView - - public override void LayoutSubviews() - { - base.LayoutSubviews(); - - // Disable CoreAnimation actions so that the positions of the sublayers immediately move to their new position. - CATransaction.Begin(); - CATransaction.DisableActions = true; - - // Create the path for the mask layer. We use the even odd fill rule so that the region of interest does not have a fill color. - var path = UIBezierPath.FromRect(new CGRect(0, 0, this.Frame.Width, this.Frame.Height)); - path.AppendPath(UIBezierPath.FromRect(this.RegionOfInterest)); - path.UsesEvenOddFillRule = true; - this.maskLayer.Path = path.CGPath; - - this.regionOfInterestOutline.Path = CGPath.FromRect(this.RegionOfInterest); - - var left = this.RegionOfInterest.X - this.RegionOfInterestControlRadius; - var right = this.RegionOfInterest.X + this.RegionOfInterest.Width - this.RegionOfInterestControlRadius; - var top = this.RegionOfInterest.Y - this.RegionOfInterestControlRadius; - var bottom = this.RegionOfInterest.Y + this.RegionOfInterest.Height - this.RegionOfInterestControlRadius; - - this.topLeftControl.Position = new CGPoint(left, top); - this.topRightControl.Position = new CGPoint(right, top); - this.bottomLeftControl.Position = new CGPoint(left, bottom); - this.bottomRightControl.Position = new CGPoint(right, bottom); - - CATransaction.Commit(); - } - - #endregion - - #region IUIGestureRecognizerDelegate - - [Export("gestureRecognizer:shouldReceiveTouch:")] - public bool ShouldReceiveTouch(UIGestureRecognizer gestureRecognizer, UITouch touch) - { - var result = true; - - // Ignore drags outside of the region of interest (plus some padding). - if (gestureRecognizer == this.resizeRegionOfInterestGestureRecognizer) - { - var touchLocation = touch.LocationInView(gestureRecognizer.View); - - var paddedRegionOfInterest = this.RegionOfInterest.Inset(-RegionOfInterestCornerTouchThreshold, -RegionOfInterestCornerTouchThreshold); - if (!paddedRegionOfInterest.Contains(touchLocation)) - { - result = false; - } - } - - return result; - } - - [Export("gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:")] - public bool ShouldRecognizeSimultaneously(UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer) - { - var result = false; - - // Allow multiple gesture recognizers to be recognized simultaneously if and only if the touch location is not within the touch threshold. - if (gestureRecognizer == this.resizeRegionOfInterestGestureRecognizer) - { - var touchLocation = gestureRecognizer.LocationInView(gestureRecognizer.View); - result = this.CornerOfRect(this.RegionOfInterest, touchLocation) == ControlCorner.None; - } - - return result; - } - - #endregion - } -} \ No newline at end of file + +namespace AVCamBarcode { + using AVCamBarcode.Extensions; + using AVFoundation; + using CoreAnimation; + using CoreGraphics; + using Foundation; + using ObjCRuntime; + using System; + using UIKit; + + [Register ("PreviewView")] + public class PreviewView : UIView, IUIGestureRecognizerDelegate { + private static readonly object layerClassLock = new object (); + + private static Class layerClass; + + private const float RegionOfInterestCornerTouchThreshold = 50; + + private const float RegionOfInterestControlDiameter = 12; + + private readonly CAShapeLayer maskLayer = new CAShapeLayer (); + + private readonly CAShapeLayer regionOfInterestOutline = new CAShapeLayer (); + + /// <summary> + /// White dot on the top left of the region of interest. + /// </summary> + private readonly CAShapeLayer topLeftControl = new CAShapeLayer (); + + /// <summary> + /// White dot on the top right of the region of interest. + /// </summary> + private readonly CAShapeLayer topRightControl = new CAShapeLayer (); + + /// <summary> + /// White dot on the bottom left of the region of interest. + /// </summary> + private readonly CAShapeLayer bottomLeftControl = new CAShapeLayer (); + + /// <summary> + /// White dot on the bottom right of the region of interest. + /// </summary> + private readonly CAShapeLayer bottomRightControl = new CAShapeLayer (); + + /// <summary> + /// Saves a reference to the control corner that the user is using to resize + /// the region of interest in `resizeRegionOfInterestWithGestureRecognizer()`. + /// </summary> + private ControlCorner currentControlCorner = ControlCorner.None; + + private UIPanGestureRecognizer resizeRegionOfInterestGestureRecognizer; + + public event EventHandler RegionOfInterestChanged; + + public PreviewView (CGRect frame) : base (frame) + { + this.Initialize (); + } + + [Export ("initWithCoder:")] + public PreviewView (NSCoder coder) : base (coder) + { + this.Initialize (); + } + + public static Class LayerClass { + [Export ("layerClass")] + get { + if (layerClass == null) { + lock (layerClassLock) { + if (layerClass == null) { + layerClass = new Class (typeof (AVCaptureVideoPreviewLayer)); + } + } + } + + return layerClass; + } + } + + // Region of Interest + + /// <summary> + /// The minimum region of interest's size cannot be smaller than the corner + /// touch threshold as to avoid control selection conflicts when a user tries + /// to resize the region of interest. + /// </summary> + protected float MinimumRegionOfInterestSize => RegionOfInterestCornerTouchThreshold; + + protected float RegionOfInterestControlRadius => RegionOfInterestControlDiameter / 2; + + public bool IsResizingRegionOfInterest => this.resizeRegionOfInterestGestureRecognizer.State == UIGestureRecognizerState.Changed; + + // This property is set only in `setRegionOfInterestWithProposedRegionOfInterest()`. + // When a user is resizing the region of interest in `resizeRegionOfInterestWithGestureRecognizer()`, + // the KVO notification will be triggered when the resizing is finished. + public CGRect RegionOfInterest { get; private set; } + + // AV capture properties + + public AVCaptureVideoPreviewLayer VideoPreviewLayer => this.Layer as AVCaptureVideoPreviewLayer; + + public AVCaptureSession Session { + get { + return this.VideoPreviewLayer.Session; + } + + set { + this.VideoPreviewLayer.Session = value; + } + } + + protected UIPanGestureRecognizer ResizeRegionOfInterestGestureRecognizer { + get { + if (this.resizeRegionOfInterestGestureRecognizer == null) { + this.resizeRegionOfInterestGestureRecognizer = new UIPanGestureRecognizer (this.ResizeRegionOfInterestWithGestureRecognizer); + } + + return this.resizeRegionOfInterestGestureRecognizer; + } + } + + private void Initialize () + { + this.maskLayer.FillRule = CAShapeLayer.FillRuleEvenOdd; + this.maskLayer.FillColor = UIColor.Black.CGColor; + this.maskLayer.Opacity = 0.6f; + this.Layer.AddSublayer (this.maskLayer); + + this.regionOfInterestOutline.Path = UIBezierPath.FromRect (this.RegionOfInterest).CGPath; + this.regionOfInterestOutline.FillColor = UIColor.Clear.CGColor; + this.regionOfInterestOutline.StrokeColor = UIColor.Yellow.CGColor; + this.Layer.AddSublayer (this.regionOfInterestOutline); + + var controlRect = new CGRect (0, 0, RegionOfInterestControlDiameter, RegionOfInterestControlDiameter); + + this.topLeftControl.Path = UIBezierPath.FromOval (controlRect).CGPath; + this.topLeftControl.FillColor = UIColor.White.CGColor; + this.Layer.AddSublayer (this.topLeftControl); + + this.topRightControl.Path = UIBezierPath.FromOval (controlRect).CGPath; + this.topRightControl.FillColor = UIColor.White.CGColor; + this.Layer.AddSublayer (this.topRightControl); + + this.bottomLeftControl.Path = UIBezierPath.FromOval (controlRect).CGPath; + this.bottomLeftControl.FillColor = UIColor.White.CGColor; + this.Layer.AddSublayer (this.bottomLeftControl); + + this.bottomRightControl.Path = UIBezierPath.FromOval (controlRect).CGPath; + this.bottomRightControl.FillColor = UIColor.White.CGColor; + this.Layer.AddSublayer (this.bottomRightControl); + + // Add the region of interest gesture recognizer to the region of interest + // view so that the region of interest can be resized and moved. If you + // would like to have a fixed region of interest that cannot be resized + // or moved, do not add the following gesture recognizer. You will simply + // need to set the region of interest once. + this.ResizeRegionOfInterestGestureRecognizer.Delegate = this; + this.AddGestureRecognizer (this.ResizeRegionOfInterestGestureRecognizer); + } + + /// <summary> + /// Updates the region of interest with a proposed region of interest ensuring + /// the new region of interest is within the bounds of the video preview. When + /// a new region of interest is set, the region of interest is redrawn. + /// </summary> + /// <param name="proposedRegionOfInterest"></param> + public void SetRegionOfInterestWithProposedRegionOfInterest (CGRect proposedRegionOfInterest) + { + // We standardize to ensure we have positive widths and heights with an origin at the top left. + var videoPreviewRect = this.VideoPreviewLayer.MapToLayerCoordinates (new CGRect (0, 0, 1, 1)).Standardize (); + + // Intersect the video preview view with the view's frame to only get + // the visible portions of the video preview view. + + var visibleVideoPreviewRect = CGRect.Intersect (videoPreviewRect, this.Frame); + var oldRegionOfInterest = this.RegionOfInterest; + var newRegionOfInterest = proposedRegionOfInterest.Standardize (); + + // Move the region of interest in bounds. + if (this.currentControlCorner == ControlCorner.None) { + nfloat xOffset = 0; + nfloat yOffset = 0; + + if (!visibleVideoPreviewRect.Contains (newRegionOfInterest.CornerTopLeft ())) { + xOffset = NMath.Max (visibleVideoPreviewRect.GetMinX () - newRegionOfInterest.GetMinX (), 0); + yOffset = NMath.Max (visibleVideoPreviewRect.GetMinY () - newRegionOfInterest.GetMinY (), 0); + } + + if (!visibleVideoPreviewRect.Contains (visibleVideoPreviewRect.CornerBottomRight ())) { + xOffset = NMath.Min (visibleVideoPreviewRect.GetMaxX () - newRegionOfInterest.GetMaxX (), xOffset); + yOffset = NMath.Min (visibleVideoPreviewRect.GetMaxY () - newRegionOfInterest.GetMaxY (), yOffset); + } + + newRegionOfInterest.Offset (xOffset, yOffset); + } + + // Clamp the size when the region of interest is being resized. + visibleVideoPreviewRect.Intersect (newRegionOfInterest); + newRegionOfInterest = visibleVideoPreviewRect; + + // Fix a minimum width of the region of interest. + if (proposedRegionOfInterest.Size.Width < this.MinimumRegionOfInterestSize) { + switch (this.currentControlCorner) { + case ControlCorner.TopLeft: + case ControlCorner.BottomLeft: + var x = oldRegionOfInterest.Location.X + oldRegionOfInterest.Size.Width - this.MinimumRegionOfInterestSize; + + newRegionOfInterest.X = x; + newRegionOfInterest.Width = this.MinimumRegionOfInterestSize; + break; + + case ControlCorner.TopRight: + newRegionOfInterest.X = oldRegionOfInterest.Location.X; + newRegionOfInterest.Width = this.MinimumRegionOfInterestSize; + break; + + default: + newRegionOfInterest.Location = oldRegionOfInterest.Location; + newRegionOfInterest.Width = this.MinimumRegionOfInterestSize; + break; + } + } + + // Fix a minimum height of the region of interest. + if (proposedRegionOfInterest.Height < this.MinimumRegionOfInterestSize) { + switch (currentControlCorner) { + case ControlCorner.TopLeft: + case ControlCorner.TopRight: + newRegionOfInterest.Y = oldRegionOfInterest.Y + oldRegionOfInterest.Height - this.MinimumRegionOfInterestSize; + newRegionOfInterest.Height = this.MinimumRegionOfInterestSize; + break; + + case ControlCorner.BottomLeft: + newRegionOfInterest.Y = oldRegionOfInterest.Y; + newRegionOfInterest.Height = this.MinimumRegionOfInterestSize; + break; + + default: + newRegionOfInterest.Location = oldRegionOfInterest.Location; + newRegionOfInterest.Height = this.MinimumRegionOfInterestSize; + break; + } + } + + this.RegionOfInterest = newRegionOfInterest; + this.SetNeedsLayout (); + } + + private void ResizeRegionOfInterestWithGestureRecognizer (UIPanGestureRecognizer gestureRecognizer) + { + var touchLocation = gestureRecognizer.LocationInView (gestureRecognizer.View); + var oldRegionOfInterest = this.RegionOfInterest; + + switch (gestureRecognizer.State) { + case UIGestureRecognizerState.Began: + // When the gesture begins, save the corner that is closes to + // the resize region of interest gesture recognizer's touch location. + this.currentControlCorner = CornerOfRect (oldRegionOfInterest, touchLocation); + break; + + + case UIGestureRecognizerState.Changed: + var newRegionOfInterest = oldRegionOfInterest; + + switch (this.currentControlCorner) { + case ControlCorner.None: + // Update the new region of interest with the gesture recognizer's translation. + var translation = gestureRecognizer.TranslationInView (gestureRecognizer.View); + + // Move the region of interest with the gesture recognizer's translation. + if (this.RegionOfInterest.Contains (touchLocation)) { + newRegionOfInterest.X += translation.X; + newRegionOfInterest.Y += translation.Y; + } + + // If the touch location goes outside the preview layer, + // we will only translate the region of interest in the + // plane that is not out of bounds. + var normalizedRect = new CGRect (0, 0, 1, 1); + if (!normalizedRect.Contains (this.VideoPreviewLayer.PointForCaptureDevicePointOfInterest (touchLocation))) { + if (touchLocation.X < RegionOfInterest.GetMinX () || touchLocation.X > RegionOfInterest.GetMaxX ()) { + newRegionOfInterest.Y += translation.Y; + } else if (touchLocation.Y < RegionOfInterest.GetMinY () || touchLocation.Y > RegionOfInterest.GetMaxY ()) { + newRegionOfInterest.X += translation.X; + } + } + + // Set the translation to be zero so that the new gesture + // recognizer's translation is in respect to the region of + // interest's new position. + gestureRecognizer.SetTranslation (CGPoint.Empty, gestureRecognizer.View); + break; + + case ControlCorner.TopLeft: + newRegionOfInterest = new CGRect (touchLocation.X, touchLocation.Y, + oldRegionOfInterest.Width + oldRegionOfInterest.X - touchLocation.X, + oldRegionOfInterest.Height + oldRegionOfInterest.Y - touchLocation.Y); + break; + + case ControlCorner.TopRight: + newRegionOfInterest = new CGRect (newRegionOfInterest.X, + touchLocation.Y, + touchLocation.X - newRegionOfInterest.X, + oldRegionOfInterest.Height + newRegionOfInterest.Y - touchLocation.Y); + break; + + + case ControlCorner.BottomLeft: + newRegionOfInterest = new CGRect (touchLocation.X, + oldRegionOfInterest.Y, + oldRegionOfInterest.Width + oldRegionOfInterest.X - touchLocation.X, + touchLocation.Y - oldRegionOfInterest.Y); + break; + + case ControlCorner.BottomRight: + newRegionOfInterest = new CGRect (oldRegionOfInterest.X, + oldRegionOfInterest.Y, + touchLocation.X - oldRegionOfInterest.X, + touchLocation.Y - oldRegionOfInterest.Y); + break; + } + + // Update the region of interest with a valid CGRect. + this.SetRegionOfInterestWithProposedRegionOfInterest (newRegionOfInterest); + break; + + case UIGestureRecognizerState.Ended: + this.RegionOfInterestChanged?.Invoke (this, EventArgs.Empty); + + // Reset the current corner reference to none now that the resize. + // gesture recognizer has ended. + this.currentControlCorner = ControlCorner.None; + break; + + default: + return; + } + } + + private ControlCorner CornerOfRect (CGRect rect, CGPoint point) + { + var closestDistance = nfloat.MaxValue; + var closestCorner = ControlCorner.None; + + Tuple<ControlCorner, CGPoint> [] corners = { + Tuple (ControlCorner.TopLeft, rect.CornerTopLeft()), + Tuple (ControlCorner.TopRight, rect.CornerTopRight ()), + Tuple (ControlCorner.BottomLeft, rect.CornerBottomLeft ()), + Tuple (ControlCorner.BottomRight, rect.CornerBottomRight()) + }; + + foreach (var tuple in corners) { + var corner = tuple.Item1; + var cornerPoint = tuple.Item2; + + var dX = point.X - cornerPoint.X; + var dY = point.Y - cornerPoint.Y; + var distance = NMath.Sqrt ((dX * dX) + (dY * dY)); + + if (distance < closestDistance) { + closestDistance = distance; + closestCorner = corner; + } + } + + if (closestDistance > RegionOfInterestCornerTouchThreshold) { + closestCorner = ControlCorner.None; + } + + return closestCorner; + } + + private static Tuple<ControlCorner, CGPoint> Tuple (ControlCorner corner, CGPoint point) + { + return new Tuple<ControlCorner, CGPoint> (corner, point); + } + + #region UIView + + public override void LayoutSubviews () + { + base.LayoutSubviews (); + + // Disable CoreAnimation actions so that the positions of the sublayers immediately move to their new position. + CATransaction.Begin (); + CATransaction.DisableActions = true; + + // Create the path for the mask layer. We use the even odd fill rule so that the region of interest does not have a fill color. + var path = UIBezierPath.FromRect (new CGRect (0, 0, this.Frame.Width, this.Frame.Height)); + path.AppendPath (UIBezierPath.FromRect (this.RegionOfInterest)); + path.UsesEvenOddFillRule = true; + this.maskLayer.Path = path.CGPath; + + this.regionOfInterestOutline.Path = CGPath.FromRect (this.RegionOfInterest); + + var left = this.RegionOfInterest.X - this.RegionOfInterestControlRadius; + var right = this.RegionOfInterest.X + this.RegionOfInterest.Width - this.RegionOfInterestControlRadius; + var top = this.RegionOfInterest.Y - this.RegionOfInterestControlRadius; + var bottom = this.RegionOfInterest.Y + this.RegionOfInterest.Height - this.RegionOfInterestControlRadius; + + this.topLeftControl.Position = new CGPoint (left, top); + this.topRightControl.Position = new CGPoint (right, top); + this.bottomLeftControl.Position = new CGPoint (left, bottom); + this.bottomRightControl.Position = new CGPoint (right, bottom); + + CATransaction.Commit (); + } + + #endregion + + #region IUIGestureRecognizerDelegate + + [Export ("gestureRecognizer:shouldReceiveTouch:")] + public bool ShouldReceiveTouch (UIGestureRecognizer gestureRecognizer, UITouch touch) + { + var result = true; + + // Ignore drags outside of the region of interest (plus some padding). + if (gestureRecognizer == this.resizeRegionOfInterestGestureRecognizer) { + var touchLocation = touch.LocationInView (gestureRecognizer.View); + + var paddedRegionOfInterest = this.RegionOfInterest.Inset (-RegionOfInterestCornerTouchThreshold, -RegionOfInterestCornerTouchThreshold); + if (!paddedRegionOfInterest.Contains (touchLocation)) { + result = false; + } + } + + return result; + } + + [Export ("gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:")] + public bool ShouldRecognizeSimultaneously (UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer) + { + var result = false; + + // Allow multiple gesture recognizers to be recognized simultaneously if and only if the touch location is not within the touch threshold. + if (gestureRecognizer == this.resizeRegionOfInterestGestureRecognizer) { + var touchLocation = gestureRecognizer.LocationInView (gestureRecognizer.View); + result = this.CornerOfRect (this.RegionOfInterest, touchLocation) == ControlCorner.None; + } + + return result; + } + + #endregion + } +} diff --git a/ios11/AVCamBarcode/AVCamBarcode/Properties/AssemblyInfo.cs b/ios11/AVCamBarcode/AVCamBarcode/Properties/AssemblyInfo.cs index 7bd29e9f3..cf5eab691 100644 --- a/ios11/AVCamBarcode/AVCamBarcode/Properties/AssemblyInfo.cs +++ b/ios11/AVCamBarcode/AVCamBarcode/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("AVCamBarcode")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("AVCamBarcode")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("AVCamBarcode")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("AVCamBarcode")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("944aef71-c52c-4c82-91d5-208131adfebf")] +[assembly: Guid ("944aef71-c52c-4c82-91d5-208131adfebf")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios11/CoreMLAzureModel/CustomVision/AppDelegate.cs b/ios11/CoreMLAzureModel/CustomVision/AppDelegate.cs index 926b30ea5..ca475ee4e 100644 --- a/ios11/CoreMLAzureModel/CustomVision/AppDelegate.cs +++ b/ios11/CoreMLAzureModel/CustomVision/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace CustomVision -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace CustomVision { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios11/CoreMLAzureModel/CustomVision/BubbleLayer.cs b/ios11/CoreMLAzureModel/CustomVision/BubbleLayer.cs index 617cfb7b5..7c7ce907d 100644 --- a/ios11/CoreMLAzureModel/CustomVision/BubbleLayer.cs +++ b/ios11/CoreMLAzureModel/CustomVision/BubbleLayer.cs @@ -1,127 +1,117 @@ -using System; +using System; using CoreAnimation; using UIKit; using CoreGraphics; -namespace CustomVision -{ - public class BubbleLayer : CALayer - { - // MARK: Public Properties - - string _string; - public string @String - { - get { return _string; } - set - { - _string = value; - if (String.IsNullOrEmpty(_string)) - { - Opacity = 0.0f; - } - else - { - Opacity = 1.0f; - Console.WriteLine("BubbleLayer set: " + _string); - layerLabel.String = _string; - } - SetNeedsLayout(); - } - } - - public UIFont font = UIFont.FromName("Helvetica-Bold", 24.0f); - public UIFont Font - { - set { - font = value; - layerLabel.SetFont(font.Name); - layerLabel.FontSize = font.PointSize; - } - } - - UIColor textColor = UIColor.White; - public UIColor TextColor { - set { - textColor = value; - layerLabel.ForegroundColor = textColor.CGColor; - } - } - - float paddingHorizontal = 25; - public float PaddingHorizontal { - set { - paddingHorizontal = value; - SetNeedsLayout(); - } - } +namespace CustomVision { + public class BubbleLayer : CALayer { + // MARK: Public Properties + + string _string; + public string @String { + get { return _string; } + set { + _string = value; + if (String.IsNullOrEmpty (_string)) { + Opacity = 0.0f; + } else { + Opacity = 1.0f; + Console.WriteLine ("BubbleLayer set: " + _string); + layerLabel.String = _string; + } + SetNeedsLayout (); + } + } + + public UIFont font = UIFont.FromName ("Helvetica-Bold", 24.0f); + public UIFont Font { + set { + font = value; + layerLabel.SetFont (font.Name); + layerLabel.FontSize = font.PointSize; + } + } + + UIColor textColor = UIColor.White; + public UIColor TextColor { + set { + textColor = value; + layerLabel.ForegroundColor = textColor.CGColor; + } + } + + float paddingHorizontal = 25; + public float PaddingHorizontal { + set { + paddingHorizontal = value; + SetNeedsLayout (); + } + } float paddingVertical = 25; - public float PaddingVertical - { - set - { + public float PaddingVertical { + set { paddingVertical = value; - SetNeedsLayout(); + SetNeedsLayout (); } } - float maxWidth = 300; - public float MaxWidth { - set { - maxWidth = value; - SetNeedsLayout(); - } - } - - BubbleLayerLabel layerLabel = new BubbleLayerLabel(); - - - public BubbleLayer(string @string) : base() - { - _string = @string; - - BackgroundColor = new UIColor(1, 0, 217 / 255, 1).CGColor; - BorderColor = UIColor.White.CGColor; - BorderWidth = 3.5f; - - ContentsScale = UIScreen.MainScreen.Scale; - AllowsEdgeAntialiasing = true; - - layerLabel.String = this.String; - layerLabel.SetFont(font.Name); - layerLabel.FontSize = font.PointSize; - layerLabel.ForegroundColor = textColor.CGColor; - layerLabel.AlignmentMode = CATextLayer.AlignmentCenter; - layerLabel.ContentsScale = UIScreen.MainScreen.Scale; - layerLabel.AllowsFontSubpixelQuantization = true; - layerLabel.Wrapped = true; - layerLabel.UpdatePreferredSize(maxWidth - paddingHorizontal * 2); - layerLabel.Frame = new CGRect( - new CGPoint(paddingHorizontal, paddingVertical), - layerLabel.PreferredFrameSize()); - AddSublayer(layerLabel); - - SetNeedsLayout(); - } - - public override void LayoutSublayers() - { - layerLabel.UpdatePreferredSize(maxWidth - paddingHorizontal / 2); - - var preferredSize = PreferredFrameSize(); - var diffSize = new CGSize(Frame.Size.Width - preferredSize.Width, Frame.Size.Height - preferredSize.Height); - Frame = new CGRect(new CGPoint(Frame.X + diffSize.Width / 2, Frame.Y + diffSize.Height / 2), preferredSize); - CornerRadius = Frame.Height / 2; - - layerLabel.Frame = new CGRect(0, paddingVertical, Frame.Width, Frame.Height); - } - - public override CGSize PreferredFrameSize() - { - var layerLabelSize = layerLabel.PreferredFrameSize(); - return new CGSize(layerLabelSize.Width + paddingHorizontal * 2, - layerLabelSize.Height + paddingVertical * 2); - } - } + float maxWidth = 300; + public float MaxWidth { + set { + maxWidth = value; + SetNeedsLayout (); + } + } + + BubbleLayerLabel layerLabel = new BubbleLayerLabel (); + + + public BubbleLayer (string @string) : base () + { + _string = @string; + + BackgroundColor = new UIColor (1, 0, 217 / 255, 1).CGColor; + BorderColor = UIColor.White.CGColor; + BorderWidth = 3.5f; + + ContentsScale = UIScreen.MainScreen.Scale; + AllowsEdgeAntialiasing = true; + + layerLabel.String = this.String; + layerLabel.SetFont (font.Name); + layerLabel.FontSize = font.PointSize; + layerLabel.ForegroundColor = textColor.CGColor; + layerLabel.AlignmentMode = CATextLayer.AlignmentCenter; + layerLabel.ContentsScale = UIScreen.MainScreen.Scale; + layerLabel.AllowsFontSubpixelQuantization = true; + layerLabel.Wrapped = true; + layerLabel.UpdatePreferredSize (maxWidth - paddingHorizontal * 2); + layerLabel.Frame = new CGRect ( + new CGPoint (paddingHorizontal, paddingVertical), + layerLabel.PreferredFrameSize ()); + AddSublayer (layerLabel); + + SetNeedsLayout (); + } + + public override void LayoutSublayers () + { + layerLabel.UpdatePreferredSize (maxWidth - paddingHorizontal / 2); + + var preferredSize = PreferredFrameSize (); + var diffSize = new CGSize (Frame.Size.Width - preferredSize.Width, Frame.Size.Height - preferredSize.Height); + Frame = new CGRect (new CGPoint (Frame.X + diffSize.Width / 2, Frame.Y + diffSize.Height / 2), preferredSize); + CornerRadius = Frame.Height / 2; + + layerLabel.Frame = new CGRect (0, paddingVertical, Frame.Width, Frame.Height); + } + + public override CGSize PreferredFrameSize () + { + var layerLabelSize = layerLabel.PreferredFrameSize (); + return new CGSize (layerLabelSize.Width + paddingHorizontal * 2, + layerLabelSize.Height + paddingVertical * 2); + } + } } diff --git a/ios11/CoreMLAzureModel/CustomVision/BubbleLayerLabel.cs b/ios11/CoreMLAzureModel/CustomVision/BubbleLayerLabel.cs index 5ac8cba18..c37625158 100644 --- a/ios11/CoreMLAzureModel/CustomVision/BubbleLayerLabel.cs +++ b/ios11/CoreMLAzureModel/CustomVision/BubbleLayerLabel.cs @@ -1,61 +1,54 @@ -using System; +using System; using CoreAnimation; using CoreGraphics; using CoreText; using Foundation; using UIKit; -namespace CustomVision -{ - public class BubbleLayerLabel : CATextLayer - { - CGSize preferredSize = CGSize.Empty; - CGSize PreferredSize - { - set { +namespace CustomVision { + public class BubbleLayerLabel : CATextLayer { + CGSize preferredSize = CGSize.Empty; + CGSize PreferredSize { + set { preferredSize = value; - base.NeedsLayout(); - } - } + base.NeedsLayout (); + } + } UIFont font; - public void UpdatePreferredSize(float maxWidth) - { - var text = this.String; - if (string.IsNullOrEmpty(text)) - { - preferredSize = CGSize.Empty; - return; - } + public void UpdatePreferredSize (float maxWidth) + { + var text = this.String; + if (string.IsNullOrEmpty (text)) { + preferredSize = CGSize.Empty; + return; + } - // TODO: test .Font property - var fontName = this.WeakFont as string; - if (fontName == null) - { - Console.WriteLine("Trying to update label size without font"); - preferredSize = CGSize.Empty; - return; - } - if (font == null) - { - font = UIFont.FromName(fontName, UIFont.ButtonFontSize); + // TODO: test .Font property + var fontName = this.WeakFont as string; + if (fontName == null) { + Console.WriteLine ("Trying to update label size without font"); + preferredSize = CGSize.Empty; + return; + } + if (font == null) { + font = UIFont.FromName (fontName, UIFont.ButtonFontSize); } - var attributes = new UIStringAttributes - { - Font = font - }; - var nsString = new NSAttributedString(text, attributes); - var fontBounds = nsString.GetBoundingRect(new CGSize(maxWidth, float.MaxValue), - NSStringDrawingOptions.UsesLineFragmentOrigin, null); - fontBounds.Size = new CGSize(fontBounds.Size.Width, fontBounds.Size.Height + Math.Abs(font.Descender)); - preferredSize = fontBounds.Size; - } + var attributes = new UIStringAttributes { + Font = font + }; + var nsString = new NSAttributedString (text, attributes); + var fontBounds = nsString.GetBoundingRect (new CGSize (maxWidth, float.MaxValue), + NSStringDrawingOptions.UsesLineFragmentOrigin, null); + fontBounds.Size = new CGSize (fontBounds.Size.Width, fontBounds.Size.Height + Math.Abs (font.Descender)); + preferredSize = fontBounds.Size; + } - public override CGSize PreferredFrameSize() - { - return preferredSize; - } - } + public override CGSize PreferredFrameSize () + { + return preferredSize; + } + } } diff --git a/ios11/CoreMLAzureModel/CustomVision/Main.cs b/ios11/CoreMLAzureModel/CustomVision/Main.cs index 05cabc5c2..6c40559a0 100644 --- a/ios11/CoreMLAzureModel/CustomVision/Main.cs +++ b/ios11/CoreMLAzureModel/CustomVision/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace CustomVision -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace CustomVision { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/CoreMLAzureModel/CustomVision/ViewController.cs b/ios11/CoreMLAzureModel/CustomVision/ViewController.cs index edcddb268..b7f5ee655 100644 --- a/ios11/CoreMLAzureModel/CustomVision/ViewController.cs +++ b/ios11/CoreMLAzureModel/CustomVision/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using AVFoundation; using CoreFoundation; @@ -11,14 +11,12 @@ using CoreML; using CoreImage; -namespace CustomVision -{ - public partial class ViewController : UIViewController, IAVCaptureVideoDataOutputSampleBufferDelegate - { +namespace CustomVision { + public partial class ViewController : UIViewController, IAVCaptureVideoDataOutputSampleBufferDelegate { // controlling the pace of the machine vision analysis DateTime lastAnalysis = DateTime.Now; - TimeSpan pace = new TimeSpan(0, 0, 0, 0, 800); // in milliseconds, classification will not repeat faster than this value + TimeSpan pace = new TimeSpan (0, 0, 0, 0, 800); // in milliseconds, classification will not repeat faster than this value // performance tracking bool trackPerformance = false; // use "true" for performance logging @@ -26,230 +24,201 @@ public partial class ViewController : UIViewController, IAVCaptureVideoDataOutpu int framesPerSample = 10; DateTime startDate = DateTime.Now; - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } AVCaptureVideoPreviewLayer previewLayer; - BubbleLayer bubbleLayer = new BubbleLayer("INITIALIZING"); + BubbleLayer bubbleLayer = new BubbleLayer ("INITIALIZING"); UIView topBlurView; UIView bottomBlurView; - DispatchQueue queue = new DispatchQueue("videoQueue"); - AVCaptureSession captureSession = new AVCaptureSession(); + DispatchQueue queue = new DispatchQueue ("videoQueue"); + AVCaptureSession captureSession = new AVCaptureSession (); AVCaptureDevice captureDevice; - AVCaptureVideoDataOutput videoOutput = new AVCaptureVideoDataOutput(); + AVCaptureVideoDataOutput videoOutput = new AVCaptureVideoDataOutput (); int unknownCounter = 0; // used to track how many unclassified images in a row float confidence = 0.01f; // MARK: Load the Model - CGSize targetImageSize = new CGSize(227, 227); // must match model data input + CGSize targetImageSize = new CGSize (227, 227); // must match model data input VNCoreMLModel model; - VNRequest[] classificationRequestAry; - public VNRequest[] ClassificationRequest - { - get - { - if (model == null) - { - var modelPath = NSBundle.MainBundle.GetUrlForResource("Fruit", "mlmodelc"); - NSError createErr, mlErr; - var mlModel = MLModel.Create(modelPath, out createErr); - model = VNCoreMLModel.FromMLModel(mlModel, out mlErr); + VNRequest [] classificationRequestAry; + public VNRequest [] ClassificationRequest { + get { + if (model == null) { + var modelPath = NSBundle.MainBundle.GetUrlForResource ("Fruit", "mlmodelc"); + NSError createErr, mlErr; + var mlModel = MLModel.Create (modelPath, out createErr); + model = VNCoreMLModel.FromMLModel (mlModel, out mlErr); } - if (classificationRequestAry == null) - { - var classificationRequest = new VNCoreMLRequest(model, handleClassification); - classificationRequestAry = new VNRequest[] { classificationRequest }; + if (classificationRequestAry == null) { + var classificationRequest = new VNCoreMLRequest (model, handleClassification); + classificationRequestAry = new VNRequest [] { classificationRequest }; } return classificationRequestAry; } } // MARK: Handle image classification results - public void handleClassification(VNRequest request, NSError error) + public void handleClassification (VNRequest request, NSError error) { - var observations = request.GetResults<VNClassificationObservation>(); - if (observations == null) - { - Console.WriteLine("Error: no results"); + var observations = request.GetResults<VNClassificationObservation> (); + if (observations == null) { + Console.WriteLine ("Error: no results"); } - var best = observations[0]; - if (best == null) - { - Console.WriteLine("Error: no observations"); + var best = observations [0]; + if (best == null) { + Console.WriteLine ("Error: no observations"); } // Use results to update user interface (includes basic filtering) - Console.WriteLine($"{best.Identifier}: {best.Confidence:P0}"); - if (best.Identifier.IndexOf("Unknown", StringComparison.InvariantCulture) > -1 - || best.Confidence < confidence) - { - if (unknownCounter < 3) - { // a bit of a low-pass filter to avoid flickering + Console.WriteLine ($"{best.Identifier}: {best.Confidence:P0}"); + if (best.Identifier.IndexOf ("Unknown", StringComparison.InvariantCulture) > -1 + || best.Confidence < confidence) { + if (unknownCounter < 3) { // a bit of a low-pass filter to avoid flickering unknownCounter++; - } - else - { + } else { unknownCounter = 0; - DispatchQueue.MainQueue.DispatchAsync(() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { bubbleLayer.String = ""; }); } - } - else - { + } else { unknownCounter = 0; - Console.WriteLine("Identified: " + best.Identifier.Trim()); - DispatchQueue.MainQueue.DispatchAsync(() => - { - bubbleLayer.String = $"{best.Identifier.Trim()} : {best.Confidence:P0}"; + Console.WriteLine ("Identified: " + best.Identifier.Trim ()); + DispatchQueue.MainQueue.DispatchAsync (() => { + bubbleLayer.String = $"{best.Identifier.Trim ()} : {best.Confidence:P0}"; }); } } // MARK: Lifecycle - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); - previewLayer = new AVCaptureVideoPreviewLayer(captureSession); + base.ViewDidLoad (); + previewLayer = new AVCaptureVideoPreviewLayer (captureSession); //previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; - previewView.Layer.AddSublayer(previewLayer); - ConfigureBlurViews(); + previewView.Layer.AddSublayer (previewLayer); + ConfigureBlurViews (); } - public override void ViewDidAppear(bool animated) + public override void ViewDidAppear (bool animated) { bubbleLayer.String = "Custom View: Fruit"; bubbleLayer.Opacity = 0.0f; - bubbleLayer.Position = new CGPoint(bottomBlurView.Frame.Width / 2.0, bottomBlurView.Frame.Height / 2); + bubbleLayer.Position = new CGPoint (bottomBlurView.Frame.Width / 2.0, bottomBlurView.Frame.Height / 2); //lowerView.Layer.AddSublayer(bubbleLayer); - bottomBlurView.Layer.AddSublayer(bubbleLayer); + bottomBlurView.Layer.AddSublayer (bubbleLayer); - SetupCamera(); - } + SetupCamera (); + } - private void ConfigureBlurViews() + private void ConfigureBlurViews () { - var blur = UIBlurEffect.FromStyle(UIBlurEffectStyle.Regular); - topBlurView = new UIVisualEffectView(blur); - this.View.AddSubview(topBlurView); - bottomBlurView = new UIVisualEffectView(blur); - View.AddSubview(bottomBlurView); + var blur = UIBlurEffect.FromStyle (UIBlurEffectStyle.Regular); + topBlurView = new UIVisualEffectView (blur); + this.View.AddSubview (topBlurView); + bottomBlurView = new UIVisualEffectView (blur); + View.AddSubview (bottomBlurView); } - public override void ViewDidLayoutSubviews() + public override void ViewDidLayoutSubviews () { - base.ViewDidLayoutSubviews(); + base.ViewDidLayoutSubviews (); previewLayer.Frame = previewView.Bounds; - topBlurView.Frame = new CGRect(previewLayer.Frame.Left, previewLayer.Frame.Top, previewLayer.Frame.Right, 150); - bottomBlurView.Frame = new CGRect(previewLayer.Frame.Left, previewLayer.Frame.Bottom - 150, previewLayer.Frame.Right, 150); + topBlurView.Frame = new CGRect (previewLayer.Frame.Left, previewLayer.Frame.Top, previewLayer.Frame.Right, 150); + bottomBlurView.Frame = new CGRect (previewLayer.Frame.Left, previewLayer.Frame.Bottom - 150, previewLayer.Frame.Right, 150); } - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); + base.TouchesBegan (touches, evt); var subviews = View.Subviews; - foreach(var vw in subviews) - { - Console.WriteLine(vw.Frame); + foreach (var vw in subviews) { + Console.WriteLine (vw.Frame); } } - public void SetupCamera() + public void SetupCamera () { - var deviceDiscovery = AVCaptureDeviceDiscoverySession.Create( - new AVCaptureDeviceType[] { AVCaptureDeviceType.BuiltInWideAngleCamera }, AVMediaType.Video, AVCaptureDevicePosition.Back); - var device = deviceDiscovery.Devices.LastOrDefault(); - if (device != null) - { + var deviceDiscovery = AVCaptureDeviceDiscoverySession.Create ( + new AVCaptureDeviceType [] { AVCaptureDeviceType.BuiltInWideAngleCamera }, AVMediaType.Video, AVCaptureDevicePosition.Back); + var device = deviceDiscovery.Devices.LastOrDefault (); + if (device != null) { captureDevice = device; - BeginSession(); + BeginSession (); } } - public void BeginSession() + public void BeginSession () { - try - { - captureSession.BeginConfiguration(); + try { + captureSession.BeginConfiguration (); - var settings = new CVPixelBufferAttributes - { + var settings = new CVPixelBufferAttributes { PixelFormatType = CVPixelFormatType.CV32BGRA }; videoOutput.WeakVideoSettings = settings.Dictionary; videoOutput.AlwaysDiscardsLateVideoFrames = true; - videoOutput.SetSampleBufferDelegateQueue(this, queue); + videoOutput.SetSampleBufferDelegateQueue (this, queue); captureSession.SessionPreset = AVCaptureSession.Preset1920x1080; - captureSession.AddOutput(videoOutput); + captureSession.AddOutput (videoOutput); - NSError err; - var input = new AVCaptureDeviceInput(captureDevice, out err); - if (err != null) - { - Console.WriteLine("AVCapture error: " + err); + NSError err; + var input = new AVCaptureDeviceInput (captureDevice, out err); + if (err != null) { + Console.WriteLine ("AVCapture error: " + err); } - captureSession.AddInput(input); + captureSession.AddInput (input); - videoConnection = videoOutput.ConnectionFromMediaType(AVMediaType.Video); + videoConnection = videoOutput.ConnectionFromMediaType (AVMediaType.Video); - captureSession.CommitConfiguration(); - captureSession.StartRunning(); - Console.WriteLine("started AV capture session"); - } - catch - { - Console.WriteLine("error connecting to the capture device"); + captureSession.CommitConfiguration (); + captureSession.StartRunning (); + Console.WriteLine ("started AV capture session"); + } catch { + Console.WriteLine ("error connecting to the capture device"); } } // MARK: Video Data Delegate - [Export("captureOutput:didOutputSampleBuffer:fromConnection:")] - public void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + [Export ("captureOutput:didOutputSampleBuffer:fromConnection:")] + public void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { - try - { + try { var currentDate = DateTime.Now; //Console.WriteLine("DidOutputSampleBuffer: " + currentDate + " " + lastAnalysis + " " + currentDate.Subtract(lastAnalysis).Milliseconds); // control the pace of the machine vision to protect battery life - if (currentDate - lastAnalysis >= pace) - { + if (currentDate - lastAnalysis >= pace) { lastAnalysis = currentDate; - } - else - { + } else { //Console.WriteLine("-- skip --"); return; // don't run the classifier more often than we need } // keep track of performance and log the frame rate - if (trackPerformance) - { + if (trackPerformance) { frameCount = frameCount + 1; - if (frameCount % framesPerSample == 0) - { - var diff = currentDate.Subtract(startDate); - if (diff.Seconds > 0) - { - if (pace > TimeSpan.Zero) - { - Console.WriteLine("WARNING: Frame rate of image classification is being limited by \"pace\" setting. Set to 0.0 for fastest possible rate."); + if (frameCount % framesPerSample == 0) { + var diff = currentDate.Subtract (startDate); + if (diff.Seconds > 0) { + if (pace > TimeSpan.Zero) { + Console.WriteLine ("WARNING: Frame rate of image classification is being limited by \"pace\" setting. Set to 0.0 for fastest possible rate."); } } - Console.WriteLine($"{diff.Seconds / framesPerSample}s per frame (average"); + Console.WriteLine ($"{diff.Seconds / framesPerSample}s per frame (average"); } startDate = currentDate; } @@ -258,38 +227,30 @@ public void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer // Note, this uses a Core Image pipeline that could be appended with other pre-processing. // If we don't want to do anything custom, we can remove this step and let the Vision framework handle // crop and resize as long as we are careful to pass the orientation properly. - using (var croppedBuffer = CroppedSampleBuffer(sampleBuffer, targetImageSize)) - { - if (croppedBuffer == null) - { + using (var croppedBuffer = CroppedSampleBuffer (sampleBuffer, targetImageSize)) { + if (croppedBuffer == null) { return; } - try - { - VNImageOptions options = new VNImageOptions(); - classifierRequestHandler = new VNImageRequestHandler(croppedBuffer, options); - NSError err; - classifierRequestHandler.Perform(ClassificationRequest, out err); - if (err != null) - { - Console.WriteLine(err); + try { + VNImageOptions options = new VNImageOptions (); + classifierRequestHandler = new VNImageRequestHandler (croppedBuffer, options); + NSError err; + classifierRequestHandler.Perform (ClassificationRequest, out err); + if (err != null) { + Console.WriteLine (err); } - } - catch (Exception error) - { - Console.WriteLine(error); + } catch (Exception error) { + Console.WriteLine (error); } } - } - finally - { - sampleBuffer.Dispose(); + } finally { + sampleBuffer.Dispose (); } } - CIContext context = CIContext.Create(); - bool alreadySet = false; + CIContext context = CIContext.Create (); + bool alreadySet = false; CIAffineTransform rotateTransform; CIAffineTransform scaleTransform; CIAffineTransform cropTransform; @@ -298,91 +259,84 @@ public void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer private VNImageRequestHandler classifierRequestHandler; private AVCaptureConnection videoConnection; - public CVPixelBuffer CroppedSampleBuffer(CMSampleBuffer sampleBuffer, CGSize targetSize) + public CVPixelBuffer CroppedSampleBuffer (CMSampleBuffer sampleBuffer, CGSize targetSize) { - var imageBuffer = sampleBuffer.GetImageBuffer(); - if (imageBuffer == null) - { - throw new ArgumentException("Cannot convert to CVImageBuffer"); + var imageBuffer = sampleBuffer.GetImageBuffer (); + if (imageBuffer == null) { + throw new ArgumentException ("Cannot convert to CVImageBuffer"); } // Only doing these calculations once for efficiency. // If the incoming images could change orientation or size during a session, this would need to be reset when that happens. - if (!alreadySet) - { + if (!alreadySet) { alreadySet = true; var imageSize = imageBuffer.EncodedSize; - var rotatedSize = new CGSize(imageSize.Height, imageSize.Width); + var rotatedSize = new CGSize (imageSize.Height, imageSize.Width); - if (targetSize.Width > rotatedSize.Width || targetSize.Height > rotatedSize.Height) - { - throw new NotSupportedException("Captured image is smaller than image size for model."); + if (targetSize.Width > rotatedSize.Width || targetSize.Height > rotatedSize.Height) { + throw new NotSupportedException ("Captured image is smaller than image size for model."); } var shorterSide = rotatedSize.Width < rotatedSize.Height ? rotatedSize.Width : rotatedSize.Height; - rotateTransform = new CIAffineTransform - { - Transform = new CGAffineTransform(0, -1, 1, 0, 0, shorterSide) + rotateTransform = new CIAffineTransform { + Transform = new CGAffineTransform (0, -1, 1, 0, 0, shorterSide) //Transform = CGAffineTransform.MakeIdentity() }; - + var scale = targetSize.Width / shorterSide; - scaleTransform = new CIAffineTransform - { - Transform = CGAffineTransform.MakeScale(scale, scale), + scaleTransform = new CIAffineTransform { + Transform = CGAffineTransform.MakeScale (scale, scale), }; var xDiff = rotatedSize.Width * scale - targetSize.Width; var yDiff = rotatedSize.Height * scale - targetSize.Height; - cropTransform = new CIAffineTransform - { + cropTransform = new CIAffineTransform { //Transform = CGAffineTransform.MakeTranslation(xDiff / 2.0f, yDiff / 2.0f), - Transform = CGAffineTransform.MakeIdentity() + Transform = CGAffineTransform.MakeIdentity () }; } // Convert to CIImage because it is easier to manipulate - var ciImage = CIImage.FromImageBuffer(imageBuffer); + var ciImage = CIImage.FromImageBuffer (imageBuffer); rotateTransform.Image = ciImage; scaleTransform.Image = rotateTransform.OutputImage; cropTransform.Image = scaleTransform.OutputImage; var cropped = cropTransform.OutputImage; - - // Note that the above pipeline could be easily appended with other image manipulations. + + // Note that the above pipeline could be easily appended with other image manipulations. // For example, to change the image contrast. It would be most efficient to handle all of // the image manipulation in a single Core Image pipeline because it can be hardware optimized. // Only need to create this buffer one time and then we can reuse it for every frame - if (resultBuffer == null || resultBuffer.Handle == IntPtr.Zero) - { - byte[] data = new byte[(int)targetSize.Height * 4 * (int)targetSize.Width]; + if (resultBuffer == null || resultBuffer.Handle == IntPtr.Zero) { + byte [] data = new byte [(int) targetSize.Height * 4 * (int) targetSize.Width]; - resultBuffer = CVPixelBuffer.Create((nint)targetSize.Width, (nint)targetSize.Height, CVPixelFormatType.CV32BGRA, data, 4 * (nint)targetSize.Width, null); // HACK + resultBuffer = CVPixelBuffer.Create ((nint) targetSize.Width, (nint) targetSize.Height, CVPixelFormatType.CV32BGRA, data, 4 * (nint) targetSize.Width, null); // HACK - if (resultBuffer == null) throw new Exception("Can't allocate pixel buffer."); + if (resultBuffer == null) throw new Exception ("Can't allocate pixel buffer."); } - context.Render(cropped, resultBuffer); + context.Render (cropped, resultBuffer); - // For debugging - //var image = ImageBufferToUIImage(resultBuffer); - //Console.WriteLine("Image size: " + image.Size); // set breakpoint to see image being provided to CoreML + // For debugging + //var image = ImageBufferToUIImage(resultBuffer); + //Console.WriteLine("Image size: " + image.Size); // set breakpoint to see image being provided to CoreML return resultBuffer; } - /// <summary> - /// for debugging... - /// </summary> - public UIImage ImageBufferToUIImage(CVPixelBuffer imageBuffer) + /// <summary> + /// for debugging... + /// </summary> + public UIImage ImageBufferToUIImage (CVPixelBuffer imageBuffer) { //imageBuffer - imageBuffer.Lock(CVPixelBufferLock.None); + imageBuffer.Lock (CVPixelBufferLock.None); var baseAddress = imageBuffer.BaseAddress; var bytesPerRow = imageBuffer.BytesPerRow; @@ -390,17 +344,17 @@ public UIImage ImageBufferToUIImage(CVPixelBuffer imageBuffer) var width = imageBuffer.Width; var height = imageBuffer.Height; - var colorSpace = CGColorSpace.CreateDeviceRGB(); - var bitmapInfo = (uint)CGImageAlphaInfo.NoneSkipFirst | (uint)CGBitmapFlags.ByteOrder32Little; + var colorSpace = CGColorSpace.CreateDeviceRGB (); + var bitmapInfo = (uint) CGImageAlphaInfo.NoneSkipFirst | (uint) CGBitmapFlags.ByteOrder32Little; - var context = new CGBitmapContext(baseAddress, width, height, 8, bytesPerRow, colorSpace, (CGImageAlphaInfo)bitmapInfo); + var context = new CGBitmapContext (baseAddress, width, height, 8, bytesPerRow, colorSpace, (CGImageAlphaInfo) bitmapInfo); - var quartzImage = context?.ToImage(); - imageBuffer.Unlock(CVPixelBufferLock.None); + var quartzImage = context?.ToImage (); + imageBuffer.Unlock (CVPixelBufferLock.None); - var image = new UIImage(quartzImage, 1.0f, UIImageOrientation.Right); + var image = new UIImage (quartzImage, 1.0f, UIImageOrientation.Right); - // HACK: save as file + // HACK: save as file //var documentsDirectory = Environment.GetFolderPath // (Environment.SpecialFolder.Personal); //string jpgFilename = System.IO.Path.Combine(documentsDirectory, "Photo.jpg"); // hardcoded filename, overwritten each time diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/AppDelegate.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/AppDelegate.cs index 2710f7d09..6540a7248 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/AppDelegate.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/AppDelegate.cs @@ -1,17 +1,14 @@ -using Foundation; +using Foundation; using UIKit; -namespace CoreMLImageRecognition -{ +namespace CoreMLImageRecognition { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageExtensions.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageExtensions.cs index 6369cc99c..774d255ba 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageExtensions.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageExtensions.cs @@ -1,31 +1,29 @@ -using System; +using System; using CoreGraphics; using CoreVideo; using UIKit; -namespace CoreMLImageRecognition -{ - public static class UIImageExtensions - { - public static CVPixelBuffer ToCVPixelBuffer(this UIImage self) +namespace CoreMLImageRecognition { + public static class UIImageExtensions { + public static CVPixelBuffer ToCVPixelBuffer (this UIImage self) { - var attrs = new CVPixelBufferAttributes(); + var attrs = new CVPixelBufferAttributes (); attrs.CGImageCompatibility = true; attrs.CGBitmapContextCompatibility = true; var cgImg = self.CGImage; - var pb = new CVPixelBuffer(cgImg.Width, cgImg.Height, CVPixelFormatType.CV32ARGB, attrs); - pb.Lock(CVPixelBufferLock.None); + var pb = new CVPixelBuffer (cgImg.Width, cgImg.Height, CVPixelFormatType.CV32ARGB, attrs); + pb.Lock (CVPixelBufferLock.None); var pData = pb.BaseAddress; - var colorSpace = CGColorSpace.CreateDeviceRGB(); - var ctxt = new CGBitmapContext(pData, cgImg.Width, cgImg.Height, 8, pb.BytesPerRow, colorSpace, CGImageAlphaInfo.NoneSkipFirst); - ctxt.TranslateCTM(0, cgImg.Height); - ctxt.ScaleCTM(1.0f, -1.0f); - UIGraphics.PushContext(ctxt); - self.Draw(new CGRect(0, 0, cgImg.Width, cgImg.Height)); - UIGraphics.PopContext(); - pb.Unlock(CVPixelBufferLock.None); + var colorSpace = CGColorSpace.CreateDeviceRGB (); + var ctxt = new CGBitmapContext (pData, cgImg.Width, cgImg.Height, 8, pb.BytesPerRow, colorSpace, CGImageAlphaInfo.NoneSkipFirst); + ctxt.TranslateCTM (0, cgImg.Height); + ctxt.ScaleCTM (1.0f, -1.0f); + UIGraphics.PushContext (ctxt); + self.Draw (new CGRect (0, 0, cgImg.Width, cgImg.Height)); + UIGraphics.PopContext (); + pb.Unlock (CVPixelBufferLock.None); return pb; diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageOrientationExtensions.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageOrientationExtensions.cs index 56145dfd7..ddf096527 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageOrientationExtensions.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ClassExtensions/UIImageOrientationExtensions.cs @@ -1,34 +1,32 @@ -using System; +using System; using UIKit; using CoreGraphics; using CoreImage; using ImageIO; -namespace CoreMLImageRecognition -{ - public static class UIImageOrientationExtensions - { - public static CIImageOrientation ToCIImageOrientation(this UIImageOrientation self) { +namespace CoreMLImageRecognition { + public static class UIImageOrientationExtensions { + public static CIImageOrientation ToCIImageOrientation (this UIImageOrientation self) + { // Take action based on value - switch (self) - { - case UIImageOrientation.Up: - return CIImageOrientation.TopLeft; - case UIImageOrientation.UpMirrored: - return CIImageOrientation.TopRight; - case UIImageOrientation.Down: - return CIImageOrientation.BottomLeft; - case UIImageOrientation.DownMirrored: - return CIImageOrientation.BottomRight; - case UIImageOrientation.Left: - return CIImageOrientation.LeftTop; - case UIImageOrientation.LeftMirrored: - return CIImageOrientation.LeftBottom; - case UIImageOrientation.Right: - return CIImageOrientation.RightTop; - case UIImageOrientation.RightMirrored: - return CIImageOrientation.RightBottom; + switch (self) { + case UIImageOrientation.Up: + return CIImageOrientation.TopLeft; + case UIImageOrientation.UpMirrored: + return CIImageOrientation.TopRight; + case UIImageOrientation.Down: + return CIImageOrientation.BottomLeft; + case UIImageOrientation.DownMirrored: + return CIImageOrientation.BottomRight; + case UIImageOrientation.Left: + return CIImageOrientation.LeftTop; + case UIImageOrientation.LeftMirrored: + return CIImageOrientation.LeftBottom; + case UIImageOrientation.Right: + return CIImageOrientation.RightTop; + case UIImageOrientation.RightMirrored: + return CIImageOrientation.RightBottom; } // Default to up diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/EventArgsT.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/EventArgsT.cs index 18d517504..851caf054 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/EventArgsT.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/EventArgsT.cs @@ -1,11 +1,9 @@ -using System; -namespace CoreMLImageRecognition -{ - public class EventArgsT<T> : EventArgs - { +using System; +namespace CoreMLImageRecognition { + public class EventArgsT<T> : EventArgs { public T Value { get; } - public EventArgsT(T val) + public EventArgsT (T val) { this.Value = val; } diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/MachineLearningModel.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/MachineLearningModel.cs index da0253b7f..2ae3f9796 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/MachineLearningModel.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/MachineLearningModel.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using CoreGraphics; @@ -7,126 +7,112 @@ using Foundation; using UIKit; -namespace CoreMLImageRecognition -{ - struct ImageDescriptionPrediction - { +namespace CoreMLImageRecognition { + struct ImageDescriptionPrediction { public string ModelName; public List<Tuple<double, string>> predictions; } - class MachineLearningModel - { + class MachineLearningModel { public event EventHandler<EventArgsT<ImageDescriptionPrediction>> PredictionsUpdated = delegate { }; public event EventHandler<EventArgsT<String>> ErrorOccurred = delegate { }; public event EventHandler<EventArgsT<String>> MessageUpdated = delegate { }; - Dictionary<string, MLModel> models = new Dictionary<string, MLModel>(); - Dictionary<MLModel, CGSize> sizeFor = new Dictionary<MLModel, CGSize>(); + Dictionary<string, MLModel> models = new Dictionary<string, MLModel> (); + Dictionary<MLModel, CGSize> sizeFor = new Dictionary<MLModel, CGSize> (); string currentModel; string currentAuthors; - internal MachineLearningModel() + internal MachineLearningModel () { - - var modelData = new[] { - new Tuple<string,CGSize>("VGG16", new CGSize(224,224)), - new Tuple<string,CGSize>("SqueezeNet", new CGSize(227,227)) + + var modelData = new [] { + new Tuple<string,CGSize>("VGG16", new CGSize(224,224)), + new Tuple<string,CGSize>("SqueezeNet", new CGSize(227,227)) }; - foreach(var m in modelData) - { + foreach (var m in modelData) { var modelName = m.Item1; var modelInputImageSize = m.Item2; - models[modelName] = LoadModel(modelName); - if (models[modelName] != null) - sizeFor[models[modelName]] = modelInputImageSize; + models [modelName] = LoadModel (modelName); + if (models [modelName] != null) + sizeFor [models [modelName]] = modelInputImageSize; } - SwitchToModel("SqueezeNet"); + SwitchToModel ("SqueezeNet"); } public IEnumerable<string> ModelNames => models.Keys; - public MLModel Model(string name) => models[name]; + public MLModel Model (string name) => models [name]; - public MLModel SwitchToModel(string modelName) + public MLModel SwitchToModel (string modelName) { - if (models[modelName] == null) - { - var errorSuffix = modelName == "VGG16"?"(it probably hasn't been download, built, and added to the project's Resources. See the README for instructions). Touch again to switch back to the SqueezeNet model.not sur":""; - ErrorOccurred(this, new EventArgsT<string>($"ML model '{modelName}' is null " + errorSuffix)); - } - else - { - MessageUpdated(this, new EventArgsT<string>($"Switched to {modelName}")); + if (models [modelName] == null) { + var errorSuffix = modelName == "VGG16" ? "(it probably hasn't been download, built, and added to the project's Resources. See the README for instructions). Touch again to switch back to the SqueezeNet model.not sur" : ""; + ErrorOccurred (this, new EventArgsT<string> ($"ML model '{modelName}' is null " + errorSuffix)); + } else { + MessageUpdated (this, new EventArgsT<string> ($"Switched to {modelName}")); currentModel = modelName; - currentAuthors = models[modelName].ModelDescription.Metadata.Author; + currentAuthors = models [modelName].ModelDescription.Metadata.Author; } - return models[modelName]; + return models [modelName]; } - MLModel LoadModel(string modelName) + MLModel LoadModel (string modelName) { NSBundle bundle = NSBundle.MainBundle; - var assetPath = bundle.GetUrlForResource(modelName, "mlmodelc"); - MLModel mdl = null; - try - { - NSError err; - mdl = MLModel.Create(assetPath, out err); - if (err != null) - { - ErrorOccurred(this, new EventArgsT<string>(err.ToString())); - } - } - catch (ArgumentNullException ane) - { - Console.WriteLine("*** VGG16 model probably hasn't been downloaded, built, and added to the project's Resources. Refer to the README for instructions. Error: " + ane.Message); - } - return mdl; + var assetPath = bundle.GetUrlForResource (modelName, "mlmodelc"); + MLModel mdl = null; + try { + NSError err; + mdl = MLModel.Create (assetPath, out err); + if (err != null) { + ErrorOccurred (this, new EventArgsT<string> (err.ToString ())); + } + } catch (ArgumentNullException ane) { + Console.WriteLine ("*** VGG16 model probably hasn't been downloaded, built, and added to the project's Resources. Refer to the README for instructions. Error: " + ane.Message); + } + return mdl; } - internal void Classify(UIImage source) + internal void Classify (UIImage source) { - var model = models[currentModel]; + var model = models [currentModel]; - var pixelBuffer = source.Scale(sizeFor[model]).ToCVPixelBuffer(); - var imageValue = MLFeatureValue.Create(pixelBuffer); + var pixelBuffer = source.Scale (sizeFor [model]).ToCVPixelBuffer (); + var imageValue = MLFeatureValue.Create (pixelBuffer); - var inputs = new NSDictionary<NSString, NSObject>(new NSString("image"), imageValue); + var inputs = new NSDictionary<NSString, NSObject> (new NSString ("image"), imageValue); - NSError error, error2; - var inputFp = new MLDictionaryFeatureProvider(inputs, out error); - if(error != null) - { - ErrorOccurred(this, new EventArgsT<string>(error.ToString())); + NSError error, error2; + var inputFp = new MLDictionaryFeatureProvider (inputs, out error); + if (error != null) { + ErrorOccurred (this, new EventArgsT<string> (error.ToString ())); return; } - var outFeatures = model.GetPrediction(inputFp, out error2); - if(error2 != null) - { - ErrorOccurred(this, new EventArgsT<string>(error2.ToString())); + var outFeatures = model.GetPrediction (inputFp, out error2); + if (error2 != null) { + ErrorOccurred (this, new EventArgsT<string> (error2.ToString ())); return; } - var predictionsDictionary = outFeatures.GetFeatureValue("classLabelProbs").DictionaryValue; - var byProbability = new List<Tuple<double, string>>(); - foreach(var key in predictionsDictionary.Keys) - { + var predictionsDictionary = outFeatures.GetFeatureValue ("classLabelProbs").DictionaryValue; + var byProbability = new List<Tuple<double, string>> (); + foreach (var key in predictionsDictionary.Keys) { var description = (string) (NSString) key; - var prob = (double)predictionsDictionary[key]; - byProbability.Add(new Tuple<double, string>(prob, description)); + var prob = (double) predictionsDictionary [key]; + byProbability.Add (new Tuple<double, string> (prob, description)); } //Sort descending - byProbability.Sort((t1, t2) => t1.Item1.CompareTo(t2.Item1) * -1); + byProbability.Sort ((t1, t2) => t1.Item1.CompareTo (t2.Item1) * -1); - var prediction = new ImageDescriptionPrediction(); + var prediction = new ImageDescriptionPrediction (); prediction.ModelName = currentModel; prediction.predictions = byProbability; - PredictionsUpdated(this, new EventArgsT<ImageDescriptionPrediction>(prediction)); + PredictionsUpdated (this, new EventArgsT<ImageDescriptionPrediction> (prediction)); } } diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/Main.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/Main.cs index bcdba795d..0d63d5e36 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/Main.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace CoreMLImageRecognition -{ - public class Application - { +namespace CoreMLImageRecognition { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ViewController.cs b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ViewController.cs index 0ab20a42e..92b4ae4dd 100644 --- a/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ViewController.cs +++ b/ios11/CoreMLImageRecognition/CoreMLImageRecognition/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -7,35 +7,32 @@ using System.Threading.Tasks; using CoreFoundation; -namespace CoreMLImageRecognition -{ - public partial class ViewController : UIViewController - { +namespace CoreMLImageRecognition { + public partial class ViewController : UIViewController { ImagePickerControllerDelegate imagePickerControllerDelegate; MachineLearningModel model; - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Configure UI - CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera); - GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum); + CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera); + GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum); // Configure Behavior - imagePickerControllerDelegate = new ImagePickerControllerDelegate(); - imagePickerControllerDelegate.ErrorOccurred += (s, e) => ShowAlert("Processing Error", e.Value); - imagePickerControllerDelegate.MessageUpdated += (s, e) => ShowMessage(e.Value); - imagePickerControllerDelegate.ImagePicked += (s, e) => - { - var img = UIImage.FromImage(e.Value); - ShowImage(img); - ClassifyImageAsync(img); + imagePickerControllerDelegate = new ImagePickerControllerDelegate (); + imagePickerControllerDelegate.ErrorOccurred += (s, e) => ShowAlert ("Processing Error", e.Value); + imagePickerControllerDelegate.MessageUpdated += (s, e) => ShowMessage (e.Value); + imagePickerControllerDelegate.ImagePicked += (s, e) => { + var img = UIImage.FromImage (e.Value); + ShowImage (img); + ClassifyImageAsync (img); }; CameraButton.Clicked += ShowCamera; @@ -43,140 +40,130 @@ public override void ViewDidLoad() ModelSwapButton.Clicked += SwapModels; // Configure Model - model = new MachineLearningModel(); - model.PredictionsUpdated += (s, e) => ShowPrediction(e.Value); - model.ErrorOccurred += (s, e) => ShowAlert("Processing Error", e.Value); - model.MessageUpdated += (s, e) => ShowMessage(e.Value); + model = new MachineLearningModel (); + model.PredictionsUpdated += (s, e) => ShowPrediction (e.Value); + model.ErrorOccurred += (s, e) => ShowAlert ("Processing Error", e.Value); + model.MessageUpdated += (s, e) => ShowMessage (e.Value); } - private void SwapModels(object sender, EventArgs e) + private void SwapModels (object sender, EventArgs e) { var currentModelName = ModelSwapButton.Title; var newModelName = currentModelName == "VGG16" ? "SqueezeNet" : "VGG16"; - model.SwitchToModel(newModelName); + model.SwitchToModel (newModelName); ModelSwapButton.Title = newModelName; //If there's an image, see what the new model thinks... - if (ImageView.Image != null) - { - ClassifyImageAsync(ImageView.Image); + if (ImageView.Image != null) { + ClassifyImageAsync (ImageView.Image); } } - private void ShowAlert(string title, string message) + private void ShowAlert (string title, string message) { - var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, (_) => { })); - InvokeOnMainThread(() => PresentViewController(okAlertController, true, () => { })); + var okAlertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (_) => { })); + InvokeOnMainThread (() => PresentViewController (okAlertController, true, () => { })); } - void ShowMessage(string msg) + void ShowMessage (string msg) { - InvokeOnMainThread(() => ClassificationLabel.Text = msg); + InvokeOnMainThread (() => ClassificationLabel.Text = msg); } - private void ShowImage(UIImage img) + private void ShowImage (UIImage img) { - InvokeOnMainThread(() => ImageView.Image = img); + InvokeOnMainThread (() => ImageView.Image = img); } - void ClassifyImageAsync(UIImage img) + void ClassifyImageAsync (UIImage img) { - Task.Run(() => model.Classify(img)); + Task.Run (() => model.Classify (img)); } - void ShowPrediction(ImageDescriptionPrediction imageDescriptionPrediction) + void ShowPrediction (ImageDescriptionPrediction imageDescriptionPrediction) { //Grab the first 5 predictions, format them for display, and show 'em - InvokeOnMainThread(() => - { + InvokeOnMainThread (() => { var message = $"{imageDescriptionPrediction.ModelName} thinks:\n"; - var topFive = imageDescriptionPrediction.predictions.Take(5); - foreach (var prediction in topFive) - { + var topFive = imageDescriptionPrediction.predictions.Take (5); + foreach (var prediction in topFive) { var prob = prediction.Item1; var desc = prediction.Item2; - message += $"{desc} : {prob.ToString("P") }\n"; + message += $"{desc} : {prob.ToString ("P")}\n"; } - ShowMessage(message); + ShowMessage (message); }); } - void ShowCamera(object sender, EventArgs e) + void ShowCamera (object sender, EventArgs e) { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = imagePickerControllerDelegate, SourceType = UIImagePickerControllerSourceType.Camera, CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } - void ShowGallery(object sender, EventArgs e) + void ShowGallery (object sender, EventArgs e) { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the camera is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the camera is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = imagePickerControllerDelegate, SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } } - class ImagePickerControllerDelegate : UIImagePickerControllerDelegate - { + class ImagePickerControllerDelegate : UIImagePickerControllerDelegate { public event EventHandler<EventArgsT<String>> MessageUpdated = delegate { }; public event EventHandler<EventArgsT<String>> ErrorOccurred = delegate { }; public event EventHandler<EventArgsT<CIImage>> ImagePicked = delegate { }; - public override void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) + public override void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) { // Close the picker - picker.DismissViewController(true, null); + picker.DismissViewController (true, null); - MessageUpdated(this, new EventArgsT<string>("Analyzing image...")); + MessageUpdated (this, new EventArgsT<string> ("Analyzing image...")); // Read Image from returned data - var uiImage = info[UIImagePickerController.OriginalImage] as UIImage; - if (uiImage == null) - { - ErrorOccurred(this, new EventArgsT<string>("Unable to read image from picker.")); + var uiImage = info [UIImagePickerController.OriginalImage] as UIImage; + if (uiImage == null) { + ErrorOccurred (this, new EventArgsT<string> ("Unable to read image from picker.")); return; } // Convert to CIImage - var ciImage = new CIImage(uiImage); - if (ciImage == null) - { - ErrorOccurred(this, new EventArgsT<string>("Unable to create required CIImage from UIImage.")); + var ciImage = new CIImage (uiImage); + if (ciImage == null) { + ErrorOccurred (this, new EventArgsT<string> ("Unable to create required CIImage from UIImage.")); return; } - var inputImage = ciImage.CreateWithOrientation(uiImage.Orientation.ToCIImageOrientation()); + var inputImage = ciImage.CreateWithOrientation (uiImage.Orientation.ToCIImageOrientation ()); - ImagePicked(this, new EventArgsT<CIImage>(inputImage)); + ImagePicked (this, new EventArgsT<CIImage> (inputImage)); } } diff --git a/ios11/CoreMLVision/CoreMLVision/AppDelegate.cs b/ios11/CoreMLVision/CoreMLVision/AppDelegate.cs index 53532569d..9a9a8722e 100644 --- a/ios11/CoreMLVision/CoreMLVision/AppDelegate.cs +++ b/ios11/CoreMLVision/CoreMLVision/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace CoreMLVision -{ +namespace CoreMLVision { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGPointExtensions.cs b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGPointExtensions.cs index 91bf8fa2b..716ce4aad 100644 --- a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGPointExtensions.cs +++ b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGPointExtensions.cs @@ -1,13 +1,12 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace CoreMLVision -{ - public static class CGPointExtensions - { - public static CGPoint Scaled(this CGPoint self, CGSize size) { - return new CGPoint(self.X * size.Width, self.Y * size.Height); +namespace CoreMLVision { + public static class CGPointExtensions { + public static CGPoint Scaled (this CGPoint self, CGSize size) + { + return new CGPoint (self.X * size.Width, self.Y * size.Height); } } } diff --git a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGRectExtensions.cs b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGRectExtensions.cs index 9771f6acf..2c7a47d1d 100644 --- a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGRectExtensions.cs +++ b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/CGRectExtensions.cs @@ -1,16 +1,15 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace CoreMLVision -{ - public static class CGRectExtensions - { - public static CGRect Scaled(this CGRect self, CGSize size) { - return new CGRect(self.X * size.Width, - self.Y * size.Height, - self.Size.Width * size.Width, - self.Size.Height * size.Height); +namespace CoreMLVision { + public static class CGRectExtensions { + public static CGRect Scaled (this CGRect self, CGSize size) + { + return new CGRect (self.X * size.Width, + self.Y * size.Height, + self.Size.Width * size.Width, + self.Size.Height * size.Height); } } } diff --git a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/DictionaryExtensions.cs b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/DictionaryExtensions.cs index e5a40c5cc..3324ade00 100644 --- a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/DictionaryExtensions.cs +++ b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/DictionaryExtensions.cs @@ -1,44 +1,42 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using CoreGraphics; using CoreImage; -namespace CoreMLVision -{ - public static class DictionaryExtensions - { - public static NSDictionary<NSString, CIVector> ToNSDictionary(this Dictionary<string, CGPoint> self){ +namespace CoreMLVision { + public static class DictionaryExtensions { + public static NSDictionary<NSString, CIVector> ToNSDictionary (this Dictionary<string, CGPoint> self) + { - var keys = new List<NSString>(); - var values = new List<CIVector>(); + var keys = new List<NSString> (); + var values = new List<CIVector> (); // Process all keys in the dictionary - foreach(string key in self.Keys) { - keys.Add(new NSString(key)); - values.Add(new CIVector(self[key])); + foreach (string key in self.Keys) { + keys.Add (new NSString (key)); + values.Add (new CIVector (self [key])); } // Return results - return new NSDictionary<NSString, CIVector>(keys.ToArray(), values.ToArray()); + return new NSDictionary<NSString, CIVector> (keys.ToArray (), values.ToArray ()); } - public static NSDictionary<NSString, NSNumber> ToNSDictionary(this Dictionary<NSString, NSNumber> self) + public static NSDictionary<NSString, NSNumber> ToNSDictionary (this Dictionary<NSString, NSNumber> self) { - var keys = new List<NSString>(); - var values = new List<NSNumber>(); + var keys = new List<NSString> (); + var values = new List<NSNumber> (); // Process all keys in the dictionary - foreach (NSString key in self.Keys) - { - keys.Add(key); - values.Add(self[key]); + foreach (NSString key in self.Keys) { + keys.Add (key); + values.Add (self [key]); } // Return results - return new NSDictionary<NSString, NSNumber>(keys.ToArray(), values.ToArray()); + return new NSDictionary<NSString, NSNumber> (keys.ToArray (), values.ToArray ()); } } } diff --git a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/UIImageOrientationExtensions.cs b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/UIImageOrientationExtensions.cs index 97f77ddf9..d2974b3b4 100644 --- a/ios11/CoreMLVision/CoreMLVision/ClassExtensions/UIImageOrientationExtensions.cs +++ b/ios11/CoreMLVision/CoreMLVision/ClassExtensions/UIImageOrientationExtensions.cs @@ -1,60 +1,59 @@ -using System; +using System; using UIKit; using CoreGraphics; using CoreImage; using ImageIO; -namespace CoreMLVision -{ - public static class UIImageOrientationExtensions - { - public static CGImagePropertyOrientation ToCGImagePropertyOrientation(this UIImageOrientation self) { +namespace CoreMLVision { + public static class UIImageOrientationExtensions { + public static CGImagePropertyOrientation ToCGImagePropertyOrientation (this UIImageOrientation self) + { // Take action based on value - switch(self) { - case UIImageOrientation.Up: - return CGImagePropertyOrientation.Up; - case UIImageOrientation.UpMirrored: - return CGImagePropertyOrientation.UpMirrored; - case UIImageOrientation.Down: - return CGImagePropertyOrientation.Down; - case UIImageOrientation.DownMirrored: - return CGImagePropertyOrientation.DownMirrored; - case UIImageOrientation.Left: - return CGImagePropertyOrientation.Left; - case UIImageOrientation.LeftMirrored: - return CGImagePropertyOrientation.LeftMirrored; - case UIImageOrientation.Right: - return CGImagePropertyOrientation.Right; - case UIImageOrientation.RightMirrored: - return CGImagePropertyOrientation.RightMirrored; + switch (self) { + case UIImageOrientation.Up: + return CGImagePropertyOrientation.Up; + case UIImageOrientation.UpMirrored: + return CGImagePropertyOrientation.UpMirrored; + case UIImageOrientation.Down: + return CGImagePropertyOrientation.Down; + case UIImageOrientation.DownMirrored: + return CGImagePropertyOrientation.DownMirrored; + case UIImageOrientation.Left: + return CGImagePropertyOrientation.Left; + case UIImageOrientation.LeftMirrored: + return CGImagePropertyOrientation.LeftMirrored; + case UIImageOrientation.Right: + return CGImagePropertyOrientation.Right; + case UIImageOrientation.RightMirrored: + return CGImagePropertyOrientation.RightMirrored; } // Default to up return CGImagePropertyOrientation.Up; } - public static CIImageOrientation ToCIImageOrientation(this UIImageOrientation self) { + public static CIImageOrientation ToCIImageOrientation (this UIImageOrientation self) + { // Take action based on value - switch (self) - { - case UIImageOrientation.Up: - return CIImageOrientation.TopLeft; - case UIImageOrientation.UpMirrored: - return CIImageOrientation.TopRight; - case UIImageOrientation.Down: - return CIImageOrientation.BottomLeft; - case UIImageOrientation.DownMirrored: - return CIImageOrientation.BottomRight; - case UIImageOrientation.Left: - return CIImageOrientation.LeftTop; - case UIImageOrientation.LeftMirrored: - return CIImageOrientation.LeftBottom; - case UIImageOrientation.Right: - return CIImageOrientation.RightTop; - case UIImageOrientation.RightMirrored: - return CIImageOrientation.RightBottom; + switch (self) { + case UIImageOrientation.Up: + return CIImageOrientation.TopLeft; + case UIImageOrientation.UpMirrored: + return CIImageOrientation.TopRight; + case UIImageOrientation.Down: + return CIImageOrientation.BottomLeft; + case UIImageOrientation.DownMirrored: + return CIImageOrientation.BottomRight; + case UIImageOrientation.Left: + return CIImageOrientation.LeftTop; + case UIImageOrientation.LeftMirrored: + return CIImageOrientation.LeftBottom; + case UIImageOrientation.Right: + return CIImageOrientation.RightTop; + case UIImageOrientation.RightMirrored: + return CIImageOrientation.RightBottom; } // Default to up diff --git a/ios11/CoreMLVision/CoreMLVision/Main.cs b/ios11/CoreMLVision/CoreMLVision/Main.cs index 38c262eb7..0e2ef6ca4 100644 --- a/ios11/CoreMLVision/CoreMLVision/Main.cs +++ b/ios11/CoreMLVision/CoreMLVision/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace CoreMLVision -{ - public class Application - { +namespace CoreMLVision { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/CoreMLVision/CoreMLVision/ViewController.cs b/ios11/CoreMLVision/CoreMLVision/ViewController.cs index 64832a30f..c340ce2aa 100644 --- a/ios11/CoreMLVision/CoreMLVision/ViewController.cs +++ b/ios11/CoreMLVision/CoreMLVision/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using Foundation; @@ -10,10 +10,8 @@ using CoreFoundation; using CoreGraphics; -namespace CoreMLVision -{ - public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUINavigationControllerDelegate - { +namespace CoreMLVision { + public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUINavigationControllerDelegate { #region Private Variables private CIImage InputImage; private VNDetectRectanglesRequest RectangleRequest; @@ -21,216 +19,214 @@ public partial class ViewController : UIViewController, IUIImagePickerController #endregion #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Configure UI - CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera); - GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum); + CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera); + GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum); // Load the ML model var bundle = NSBundle.MainBundle; - var assetPath = bundle.GetUrlForResource("MNISTClassifier", "mlmodelc"); - NSError mlErr, vnErr; - var mlModel = MLModel.Create(assetPath, out mlErr); - var model = VNCoreMLModel.FromMLModel(mlModel, out vnErr); + var assetPath = bundle.GetUrlForResource ("MNISTClassifier", "mlmodelc"); + NSError mlErr, vnErr; + var mlModel = MLModel.Create (assetPath, out mlErr); + var model = VNCoreMLModel.FromMLModel (mlModel, out vnErr); // Initialize - RectangleRequest = new VNDetectRectanglesRequest(HandleRectangles); - ClassificationRequest = new VNCoreMLRequest(model, HandleClassification); + RectangleRequest = new VNDetectRectanglesRequest (HandleRectangles); + ClassificationRequest = new VNCoreMLRequest (model, HandleClassification); } #endregion #region Private Methods - private void ShowAlert(string title, string message) { + private void ShowAlert (string title, string message) + { //Create Alert - var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); + var okAlertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); //Add Action - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); // Present Alert - PresentViewController(okAlertController, true, null); + PresentViewController (okAlertController, true, null); } - private void HandleClassification(VNRequest request, NSError error){ + private void HandleClassification (VNRequest request, NSError error) + { - var observations = request.GetResults<VNClassificationObservation>(); - if (observations == null) - { - ShowAlert("Processing Error", "Unexpected result type from VNCoreMLRequest."); + var observations = request.GetResults<VNClassificationObservation> (); + if (observations == null) { + ShowAlert ("Processing Error", "Unexpected result type from VNCoreMLRequest."); return; } - if (observations.Length < 1) - { - DispatchQueue.MainQueue.DispatchAsync(() => { + if (observations.Length < 1) { + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "Can't Get Best Result"; }); return; } - var best = observations[0]; + var best = observations [0]; - DispatchQueue.MainQueue.DispatchAsync(()=>{ + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = $"Classification: {best.Identifier} Confidence: {best.Confidence * 100f:#.00}%"; }); } - private void HandleRectangles(VNRequest request, NSError error){ + private void HandleRectangles (VNRequest request, NSError error) + { - var observations = request.GetResults<VNRectangleObservation>(); + var observations = request.GetResults<VNRectangleObservation> (); if (observations == null) { - ShowAlert("Processing Error","Unexpected result type from VNDetectRectanglesRequest."); + ShowAlert ("Processing Error", "Unexpected result type from VNDetectRectanglesRequest."); return; } if (observations.Length < 1) { - DispatchQueue.MainQueue.DispatchAsync(()=>{ + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "No rectangles detected."; }); return; } - var detectedRectangle = observations[0]; + var detectedRectangle = observations [0]; var imageSize = InputImage.Extent.Size; // Verify detected rectangle is valid. - var boundingBox = detectedRectangle.BoundingBox.Scaled(imageSize); - if (!InputImage.Extent.Contains(boundingBox)) { - DispatchQueue.MainQueue.DispatchAsync(() => { + var boundingBox = detectedRectangle.BoundingBox.Scaled (imageSize); + if (!InputImage.Extent.Contains (boundingBox)) { + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "Invalid rectangle detected."; }); return; } // Rectify the detected image and reduce it to inverted grayscale for applying model. - var topLeft = detectedRectangle.TopLeft.Scaled(imageSize); - var topRight = detectedRectangle.TopRight.Scaled(imageSize); - var bottomLeft = detectedRectangle.BottomLeft.Scaled(imageSize); - var bottomRight = detectedRectangle.BottomRight.Scaled(imageSize); + var topLeft = detectedRectangle.TopLeft.Scaled (imageSize); + var topRight = detectedRectangle.TopRight.Scaled (imageSize); + var bottomLeft = detectedRectangle.BottomLeft.Scaled (imageSize); + var bottomRight = detectedRectangle.BottomRight.Scaled (imageSize); - var correctedImage = InputImage.ImageByCroppingToRect(boundingBox); + var correctedImage = InputImage.ImageByCroppingToRect (boundingBox); - var fp1 = new Dictionary<string, CGPoint>() { + var fp1 = new Dictionary<string, CGPoint> () { {"inputTopLeft", topLeft}, {"inputTopRight", topRight}, {"inputBottomLeft", bottomLeft}, {"inputBottomRight", bottomRight} }; - correctedImage = correctedImage.CreateByFiltering("CIPerspectiveCorrection", fp1.ToNSDictionary()); + correctedImage = correctedImage.CreateByFiltering ("CIPerspectiveCorrection", fp1.ToNSDictionary ()); - var fp2 = new Dictionary<NSString, NSNumber>() { + var fp2 = new Dictionary<NSString, NSNumber> () { {CIFilterInputKey.Saturation, new NSNumber(0)}, {CIFilterInputKey.Contrast, new NSNumber(32)} }; - correctedImage = correctedImage.CreateByFiltering("CIColorControls", fp2.ToNSDictionary()); + correctedImage = correctedImage.CreateByFiltering ("CIColorControls", fp2.ToNSDictionary ()); - var fp3 = new Dictionary<NSString, NSNumber>(); - correctedImage = correctedImage.CreateByFiltering("CIColorInvert", fp3.ToNSDictionary()); + var fp3 = new Dictionary<NSString, NSNumber> (); + correctedImage = correctedImage.CreateByFiltering ("CIColorInvert", fp3.ToNSDictionary ()); // Show the pre-processed image - DispatchQueue.MainQueue.DispatchAsync(() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "Selected First Rectangle"; - CorrectedImageView.Image = new UIImage(correctedImage); + CorrectedImageView.Image = new UIImage (correctedImage); }); // Run the Core ML MNIST classifier -- results in handleClassification method - var handler = new VNImageRequestHandler(correctedImage, new VNImageOptions()); - DispatchQueue.DefaultGlobalQueue.DispatchAsync(() => { - NSError err; - handler.Perform(new VNRequest[] { ClassificationRequest }, out err); + var handler = new VNImageRequestHandler (correctedImage, new VNImageOptions ()); + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + NSError err; + handler.Perform (new VNRequest [] { ClassificationRequest }, out err); }); } #endregion #region UIImagePickerControllerDelegate - [Export("imagePickerController:didFinishPickingMediaWithInfo:")] - public void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) + [Export ("imagePickerController:didFinishPickingMediaWithInfo:")] + public void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) { // Close the picker - picker.DismissViewController(true, null); + picker.DismissViewController (true, null); // Update UI ClassificationLabel.Text = "Analyizing Image..."; CorrectedImageView.Image = null; // Read Image from returned data - var uiImage = info[UIImagePickerController.OriginalImage] as UIImage; + var uiImage = info [UIImagePickerController.OriginalImage] as UIImage; if (uiImage == null) { - ShowAlert("Processing Error","Unable to read image from picker."); + ShowAlert ("Processing Error", "Unable to read image from picker."); return; } // Convert to CIImage - var ciImage = new CIImage(uiImage); + var ciImage = new CIImage (uiImage); if (ciImage == null) { - ShowAlert("Processing Error", "Unable to create required CIImage from UIImage."); + ShowAlert ("Processing Error", "Unable to create required CIImage from UIImage."); return; } - InputImage = ciImage.CreateWithOrientation(uiImage.Orientation.ToCIImageOrientation()); + InputImage = ciImage.CreateWithOrientation (uiImage.Orientation.ToCIImageOrientation ()); // Show source image ImageView.Image = uiImage; // Run the rectangle detector, which upon completion runs the ML classifier. - var handler = new VNImageRequestHandler(ciImage, uiImage.Orientation.ToCGImagePropertyOrientation(), new VNImageOptions()); - DispatchQueue.DefaultGlobalQueue.DispatchAsync(()=>{ - NSError error; - handler.Perform(new VNRequest[] {RectangleRequest}, out error); + var handler = new VNImageRequestHandler (ciImage, uiImage.Orientation.ToCGImagePropertyOrientation (), new VNImageOptions ()); + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + NSError error; + handler.Perform (new VNRequest [] { RectangleRequest }, out error); }); } #endregion #region Custom Actions - [Action("TakePicture:")] - public void TakePicture(NSObject sender) { + [Action ("TakePicture:")] + public void TakePicture (NSObject sender) + { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable( UIImagePickerControllerSourceType.Camera)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = this, SourceType = UIImagePickerControllerSourceType.Camera, CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } - [Action("ChooseImage:")] - public void ChooseImage(NSObject senter) { + [Action ("ChooseImage:")] + public void ChooseImage (NSObject senter) + { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the camera is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the camera is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = this, SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } #endregion } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewCell.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewCell.cs index b17607ac6..21073b1a0 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewCell.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewCell.cs @@ -1,44 +1,41 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using CoreGraphics; -namespace PhotoAlbum -{ - /// <summary> - /// A table view cell used to display a photo album in the photo library. - /// </summary> - public partial class AlbumTableViewCell : UITableViewCell - { - public static string Identifier = "AlbumTableViewCell"; - - public AlbumTableViewCell (IntPtr handle) : base (handle) - { - } +namespace PhotoAlbum { + /// <summary> + /// A table view cell used to display a photo album in the photo library. + /// </summary> + public partial class AlbumTableViewCell : UITableViewCell { + public static string Identifier = "AlbumTableViewCell"; - /// <summary> - /// Returns a rect for the image view that displays the album thumbnail in the coordinate space of the cell, if it is visible. - /// </summary> - public CGRect? RectForAlbumThumbnail { - get { - var imageView = this.ImageView; - - if (imageView != null && imageView.Bounds.Size.Width > 0 && imageView.Bounds.Size.Height > 0 && imageView.Superview != null) - { - return this.ConvertRectToView(imageView.Bounds, imageView); - } - return null; - } - } + public AlbumTableViewCell (IntPtr handle) : base (handle) + { + } - /// <summary> - /// Configures the cell to display the album. - /// </summary> - public void Configure (PhotoAlbum album) - { - Accessory = UITableViewCellAccessory.DisclosureIndicator; - TextLabel.Text = album.Title; - ImageView.Image = album?.Thumbnail; - } - } -} \ No newline at end of file + /// <summary> + /// Returns a rect for the image view that displays the album thumbnail in the coordinate space of the cell, if it is visible. + /// </summary> + public CGRect? RectForAlbumThumbnail { + get { + var imageView = this.ImageView; + + if (imageView != null && imageView.Bounds.Size.Width > 0 && imageView.Bounds.Size.Height > 0 && imageView.Superview != null) { + return this.ConvertRectToView (imageView.Bounds, imageView); + } + return null; + } + } + + /// <summary> + /// Configures the cell to display the album. + /// </summary> + public void Configure (PhotoAlbum album) + { + Accessory = UITableViewCellAccessory.DisclosureIndicator; + TextLabel.Text = album.Title; + ImageView.Image = album?.Thumbnail; + } + } +} diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drag.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drag.cs index ce7d67d36..eb4dce1bb 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drag.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drag.cs @@ -1,45 +1,42 @@ -using System; +using System; using Foundation; using UIKit; using System.Linq; -namespace PhotoAlbum -{ - public partial class AlbumTableViewController - { - public UIDragItem[] GetItemsForBeginningDragSession(UITableView tableView, IUIDragSession session, NSIndexPath indexPath) +namespace PhotoAlbum { + public partial class AlbumTableViewController { + public UIDragItem [] GetItemsForBeginningDragSession (UITableView tableView, IUIDragSession session, NSIndexPath indexPath) { - if (tableView.Editing) - { - return new UIDragItem[0]; - } - var dragItems = DragItems(indexPath); - return dragItems; + if (tableView.Editing) { + return new UIDragItem [0]; + } + var dragItems = DragItems (indexPath); + return dragItems; } - UIDragItem[] DragItems (NSIndexPath forAlbumAt) - { - var album = this.Album(forAlbumAt); - var dragItems = album.Photos.Select((photo) => { - var itemProvider = photo.ItemProvider; - var dragItem = new UIDragItem(itemProvider); - dragItem.LocalObject = photo; - dragItem.PreviewProvider = photo.PreviewProvider; - return dragItem; - }); - return dragItems.ToArray(); - } + UIDragItem [] DragItems (NSIndexPath forAlbumAt) + { + var album = this.Album (forAlbumAt); + var dragItems = album.Photos.Select ((photo) => { + var itemProvider = photo.ItemProvider; + var dragItem = new UIDragItem (itemProvider); + dragItem.LocalObject = photo; + dragItem.PreviewProvider = photo.PreviewProvider; + return dragItem; + }); + return dragItems.ToArray (); + } - [Export("tableView:dragSessionWillBegin:")] - public void DragSessionWillBegin(UIKit.UITableView tableView, UIKit.IUIDragSession session) - { - NavigationItem.RightBarButtonItem.Enabled = false; - } + [Export ("tableView:dragSessionWillBegin:")] + public void DragSessionWillBegin (UIKit.UITableView tableView, UIKit.IUIDragSession session) + { + NavigationItem.RightBarButtonItem.Enabled = false; + } - [Export("tableView:dragSessionDidEnd:")] - public void DragSessionDidEnd(UIKit.UITableView tableView, UIKit.IUIDragSession session) - { - NavigationItem.RightBarButtonItem.Enabled = true; - } + [Export ("tableView:dragSessionDidEnd:")] + public void DragSessionDidEnd (UIKit.UITableView tableView, UIKit.IUIDragSession session) + { + NavigationItem.RightBarButtonItem.Enabled = true; + } } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drop.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drop.cs index 9c2ffbd84..fc3a0ebe6 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drop.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController+Drop.cs @@ -1,119 +1,101 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; -namespace PhotoAlbum -{ - public partial class AlbumTableViewController - { +namespace PhotoAlbum { + public partial class AlbumTableViewController { - public bool CanHandle (UITableView tableView, IUIDropSession session) - { - return session.HasConformingItems(UIImage.ReadableTypeIdentifiers); - } + public bool CanHandle (UITableView tableView, IUIDropSession session) + { + return session.HasConformingItems (UIImage.ReadableTypeIdentifiers); + } - [Export("tableView:dropSessionDidUpdate:withDestinationIndexPath:")] - public UITableViewDropProposal DropSessionDidUpdate(UITableView tableView, IUIDropSession session, Foundation.NSIndexPath destinationIndexPath) - { - if (tableView.Editing && tableView.HasActiveDrag) - { - return new UITableViewDropProposal(UIDropOperation.Move, UITableViewDropIntent.InsertAtDestinationIndexPath); - } - else if (tableView.Editing || tableView.HasActiveDrag) - { - return new UITableViewDropProposal(UIDropOperation.Forbidden); - } - else if (destinationIndexPath != null && destinationIndexPath.Row < albums.Count) - { - if (session.LocalDragSession != null) - { - return new UITableViewDropProposal(UIDropOperation.Move, UITableViewDropIntent.InsertIntoDestinationIndexPath); - } - else - { - return new UITableViewDropProposal(UIDropOperation.Copy, UITableViewDropIntent.InsertIntoDestinationIndexPath); + [Export ("tableView:dropSessionDidUpdate:withDestinationIndexPath:")] + public UITableViewDropProposal DropSessionDidUpdate (UITableView tableView, IUIDropSession session, Foundation.NSIndexPath destinationIndexPath) + { + if (tableView.Editing && tableView.HasActiveDrag) { + return new UITableViewDropProposal (UIDropOperation.Move, UITableViewDropIntent.InsertAtDestinationIndexPath); + } else if (tableView.Editing || tableView.HasActiveDrag) { + return new UITableViewDropProposal (UIDropOperation.Forbidden); + } else if (destinationIndexPath != null && destinationIndexPath.Row < albums.Count) { + if (session.LocalDragSession != null) { + return new UITableViewDropProposal (UIDropOperation.Move, UITableViewDropIntent.InsertIntoDestinationIndexPath); + } else { + return new UITableViewDropProposal (UIDropOperation.Copy, UITableViewDropIntent.InsertIntoDestinationIndexPath); } - } - return new UITableViewDropProposal(UIDropOperation.Cancel); - } + } + return new UITableViewDropProposal (UIDropOperation.Cancel); + } - public void PerformDrop(UITableView tableView, IUITableViewDropCoordinator coordinator) + public void PerformDrop (UITableView tableView, IUITableViewDropCoordinator coordinator) { var destinationIndexPath = coordinator.DestinationIndexPath; if (destinationIndexPath.Row >= albums.Count) return; - switch (coordinator.Proposal.Operation) - { - case UIDropOperation.Copy: - LoadAndInsertItems(destinationIndexPath, coordinator); + switch (coordinator.Proposal.Operation) { + case UIDropOperation.Copy: + LoadAndInsertItems (destinationIndexPath, coordinator); - break; - case UIDropOperation.Move: - break; - default: - return; + break; + case UIDropOperation.Move: + break; + default: + return; } } - void LoadAndInsertItems (NSIndexPath destinationIndexPath, IUITableViewDropCoordinator coordinator) - { - var destinationAlbum = Album(destinationIndexPath); + void LoadAndInsertItems (NSIndexPath destinationIndexPath, IUITableViewDropCoordinator coordinator) + { + var destinationAlbum = Album (destinationIndexPath); - foreach (var item in coordinator.Items) - { - var dragItem = item.DragItem; - if (dragItem.ItemProvider.CanLoadObject(typeof(UIImage))) - { - dragItem.ItemProvider.LoadObject<UIImage>((droppedImage, err) => { - var image = droppedImage as UIImage; - if (image != null) - { - var photo = new Photo(image); - UpdatePhotoLibrary( (photoLibrary) => { - photoLibrary.Add(photo, destinationAlbum); - }); + foreach (var item in coordinator.Items) { + var dragItem = item.DragItem; + if (dragItem.ItemProvider.CanLoadObject (typeof (UIImage))) { + dragItem.ItemProvider.LoadObject<UIImage> ((droppedImage, err) => { + var image = droppedImage as UIImage; + if (image != null) { + var photo = new Photo (image); + UpdatePhotoLibrary ((photoLibrary) => { + photoLibrary.Add (photo, destinationAlbum); + }); - UpdateVisibleAlbumsAndPhotos(); - } - }); + UpdateVisibleAlbumsAndPhotos (); + } + }); - var cell = TableView.CellAt(destinationIndexPath) as AlbumTableViewCell; - if (cell != null) - { - var rect = cell.RectForAlbumThumbnail; - if (!rect.HasValue) rect = new CGRect(cell.ContentView.Center, CGSize.Empty); //?? - coordinator.DropItemIntoRow(dragItem, destinationIndexPath, rect.Value); - } - } - } - } + var cell = TableView.CellAt (destinationIndexPath) as AlbumTableViewCell; + if (cell != null) { + var rect = cell.RectForAlbumThumbnail; + if (!rect.HasValue) rect = new CGRect (cell.ContentView.Center, CGSize.Empty); //?? + coordinator.DropItemIntoRow (dragItem, destinationIndexPath, rect.Value); + } + } + } + } - void MoveItems (NSIndexPath destinationIndexPath, IUITableViewDropCoordinator coordinator) - { - var destinationAlbum = Album(destinationIndexPath); + void MoveItems (NSIndexPath destinationIndexPath, IUITableViewDropCoordinator coordinator) + { + var destinationAlbum = Album (destinationIndexPath); - foreach (var item in coordinator.Items) - { - var dragItem = item.DragItem; + foreach (var item in coordinator.Items) { + var dragItem = item.DragItem; - var photo = dragItem.LocalObject as Photo; - if (photo is null) return; + var photo = dragItem.LocalObject as Photo; + if (photo is null) return; - UpdatePhotoLibrary((photoLibrary) => - { - photoLibrary.MovePhoto(photo, destinationAlbum); - }); + UpdatePhotoLibrary ((photoLibrary) => { + photoLibrary.MovePhoto (photo, destinationAlbum); + }); - var cell = TableView.CellAt(destinationIndexPath) as AlbumTableViewCell; - if (cell != null) - { - var rect = cell.RectForAlbumThumbnail; - if (!rect.HasValue) rect = new CGRect(cell.ContentView.Center, CGSize.Empty); - coordinator.DropItemIntoRow(dragItem, destinationIndexPath, rect.Value); - } - UpdateVisibleAlbumsAndPhotos(); - } - } + var cell = TableView.CellAt (destinationIndexPath) as AlbumTableViewCell; + if (cell != null) { + var rect = cell.RectForAlbumThumbnail; + if (!rect.HasValue) rect = new CGRect (cell.ContentView.Center, CGSize.Empty); + coordinator.DropItemIntoRow (dragItem, destinationIndexPath, rect.Value); + } + UpdateVisibleAlbumsAndPhotos (); + } + } } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController.cs index 575b24f54..ded55575e 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/AlbumTableViewController.cs @@ -1,145 +1,137 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using System.Collections.Generic; -namespace PhotoAlbum -{ - public partial class AlbumTableViewController : UITableViewController, IUITableViewDragDelegate, IUITableViewDropDelegate - { - public AlbumTableViewController() { } - public AlbumTableViewController(IntPtr handle) : base(handle) - { - } - - List<PhotoAlbum> albums = PhotoLibrary.SharedInstance.Albums; - - PhotoAlbum Album(NSIndexPath atPath) - { - return albums[atPath.Row]; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - TableView.DataSource = this; - TableView.Delegate = this; - - TableView.DragDelegate = this; - TableView.DropDelegate = this; - - NavigationItem.RightBarButtonItem = EditButtonItem; - //TODO: TableView.IsSpringLoaded = true; - } - - - - - - public override bool Editing - { - get - { - return base.Editing; - } - set - { - //TODO: TableView.SpringLoaded = !value; - base.Editing = value; - } - } - - /// <summary> - /// Performs updates to the photo library backing store, then loads the latest album values from it. - /// </summary> - void UpdatePhotoLibrary(Action<PhotoLibrary> updates) - { - updates(PhotoLibrary.SharedInstance); - ReloadAlbumsFromPhotoLibrary(); - } - - /// <summary> - /// Loads the latest album values from the photo library backing store. - /// </summary> - public void ReloadAlbumsFromPhotoLibrary() - { - albums = PhotoLibrary.SharedInstance.Albums; - } - - /// <summary> - /// Updates the visible cells to display the latest values for albums. - /// </summary> - public void UpdateVisibleAlbumCells() - { - var visibleIndexPaths = TableView.IndexPathsForVisibleRows; - if (visibleIndexPaths is null) return; - - foreach (var indexPath in visibleIndexPaths) - { - var cell = TableView.CellAt(indexPath) as AlbumTableViewCell; - if (cell != null) - { - cell.Configure(Album(indexPath)); - cell.SetNeedsLayout(); - } - } - } - - void UpdateVisibleAlbumsAndPhotos() - { - UpdateVisibleAlbumCells(); - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - var selectedIndexPath = TableView.IndexPathForSelectedRow; - var navigationController = segue.DestinationViewController as UINavigationController; - var photosViewController = navigationController.TopViewController as PhotoCollectionViewController; - - if (selectedIndexPath is null || navigationController is null || photosViewController is null) return; +namespace PhotoAlbum { + public partial class AlbumTableViewController : UITableViewController, IUITableViewDragDelegate, IUITableViewDropDelegate { + public AlbumTableViewController () { } + public AlbumTableViewController (IntPtr handle) : base (handle) + { + } + + List<PhotoAlbum> albums = PhotoLibrary.SharedInstance.Albums; + + PhotoAlbum Album (NSIndexPath atPath) + { + return albums [atPath.Row]; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + TableView.DataSource = this; + TableView.Delegate = this; + + TableView.DragDelegate = this; + TableView.DropDelegate = this; + + NavigationItem.RightBarButtonItem = EditButtonItem; + //TODO: TableView.IsSpringLoaded = true; + } + + + + + + public override bool Editing { + get { + return base.Editing; + } + set { + //TODO: TableView.SpringLoaded = !value; + base.Editing = value; + } + } + + /// <summary> + /// Performs updates to the photo library backing store, then loads the latest album values from it. + /// </summary> + void UpdatePhotoLibrary (Action<PhotoLibrary> updates) + { + updates (PhotoLibrary.SharedInstance); + ReloadAlbumsFromPhotoLibrary (); + } + + /// <summary> + /// Loads the latest album values from the photo library backing store. + /// </summary> + public void ReloadAlbumsFromPhotoLibrary () + { + albums = PhotoLibrary.SharedInstance.Albums; + } + + /// <summary> + /// Updates the visible cells to display the latest values for albums. + /// </summary> + public void UpdateVisibleAlbumCells () + { + var visibleIndexPaths = TableView.IndexPathsForVisibleRows; + if (visibleIndexPaths is null) return; + + foreach (var indexPath in visibleIndexPaths) { + var cell = TableView.CellAt (indexPath) as AlbumTableViewCell; + if (cell != null) { + cell.Configure (Album (indexPath)); + cell.SetNeedsLayout (); + } + } + } + + void UpdateVisibleAlbumsAndPhotos () + { + UpdateVisibleAlbumCells (); + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + var selectedIndexPath = TableView.IndexPathForSelectedRow; + var navigationController = segue.DestinationViewController as UINavigationController; + var photosViewController = navigationController.TopViewController as PhotoCollectionViewController; + + if (selectedIndexPath is null || navigationController is null || photosViewController is null) return; // Load the selected album in the collection view to display its photos. - var album = Album(selectedIndexPath); - photosViewController.LoadAlbum(album, this); - } - - - # region MARK UITableViewDataSource & UITableViewDelegate - - public override nint RowsInSection(UITableView tableView, nint section) - { - return albums.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(AlbumTableViewCell.Identifier, indexPath) as AlbumTableViewCell; - cell.Configure(albums[indexPath.Row]); - return cell; - } - - public override UITableViewCellEditingStyle EditingStyleForRow(UITableView tableView, NSIndexPath indexPath) - { - return UITableViewCellEditingStyle.None; - } - - public override bool ShouldIndentWhileEditing(UITableView tableView, NSIndexPath indexPath) - { - return false; - } - - /// <summary> - /// Implement reordering by simply updating the photo library backing store. - /// </summary> - public override void MoveRow(UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) - { - UpdatePhotoLibrary((photoLibrary) => - { - photoLibrary.MoveAlbum(sourceIndexPath.Row, destinationIndexPath.Row); - }); - } - #endregion - - } -} \ No newline at end of file + var album = Album (selectedIndexPath); + photosViewController.LoadAlbum (album, this); + } + + + #region MARK UITableViewDataSource & UITableViewDelegate + + public override nint RowsInSection (UITableView tableView, nint section) + { + return albums.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (AlbumTableViewCell.Identifier, indexPath) as AlbumTableViewCell; + cell.Configure (albums [indexPath.Row]); + return cell; + } + + public override UITableViewCellEditingStyle EditingStyleForRow (UITableView tableView, NSIndexPath indexPath) + { + return UITableViewCellEditingStyle.None; + } + + public override bool ShouldIndentWhileEditing (UITableView tableView, NSIndexPath indexPath) + { + return false; + } + + /// <summary> + /// Implement reordering by simply updating the photo library backing store. + /// </summary> + public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) + { + UpdatePhotoLibrary ((photoLibrary) => { + photoLibrary.MoveAlbum (sourceIndexPath.Row, destinationIndexPath.Row); + }); + } + #endregion + + } +} diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/AppDelegate.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/AppDelegate.cs index a8fc7ab2e..9b93c3358 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/AppDelegate.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/AppDelegate.cs @@ -1,46 +1,43 @@ -using Foundation; +using Foundation; using UIKit; -namespace PhotoAlbum -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - - // Override point for customization after application launch. - var splitViewController = (UISplitViewController)Window.RootViewController; - var navigationController = (UINavigationController)splitViewController.ViewControllers[1]; - navigationController.TopViewController.NavigationItem.LeftBarButtonItem = splitViewController.DisplayModeButtonItem; - splitViewController.WeakDelegate = this; - - return true; - } - - - [Export("splitViewController:collapseSecondaryViewController:ontoPrimaryViewController:")] - public bool CollapseSecondViewController(UISplitViewController splitViewController, UIViewController secondaryViewController, UIViewController primaryViewController) - { - //if (secondaryViewController.GetType() == typeof(UINavigationController) && - // ((UINavigationController)secondaryViewController).TopViewController.GetType() == typeof(PhotoCollectionViewController) && - // ((PhotoCollectionViewController)((UINavigationController)secondaryViewController).TopViewController).GetItemsCount(null, 0) > 0) - //{ - // // Return YES to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. - // return true; - //} - return false; - } - } +namespace PhotoAlbum { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + + // Override point for customization after application launch. + var splitViewController = (UISplitViewController) Window.RootViewController; + var navigationController = (UINavigationController) splitViewController.ViewControllers [1]; + navigationController.TopViewController.NavigationItem.LeftBarButtonItem = splitViewController.DisplayModeButtonItem; + splitViewController.WeakDelegate = this; + + return true; + } + + + [Export ("splitViewController:collapseSecondaryViewController:ontoPrimaryViewController:")] + public bool CollapseSecondViewController (UISplitViewController splitViewController, UIViewController secondaryViewController, UIViewController primaryViewController) + { + //if (secondaryViewController.GetType() == typeof(UINavigationController) && + // ((UINavigationController)secondaryViewController).TopViewController.GetType() == typeof(PhotoCollectionViewController) && + // ((PhotoCollectionViewController)((UINavigationController)secondaryViewController).TopViewController).GetItemsCount(null, 0) > 0) + //{ + // // Return YES to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. + // return true; + //} + return false; + } + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo+DragDrop.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo+DragDrop.cs index 7282912c1..5c0c85a33 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo+DragDrop.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo+DragDrop.cs @@ -1,32 +1,28 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; -namespace PhotoAlbum -{ - public partial class Photo - { +namespace PhotoAlbum { + public partial class Photo { /// <summary> /// Returns an item provider that can load the image for this photo. /// </summary> - public NSItemProvider ItemProvider - { - get - { - return new NSItemProvider(image); + public NSItemProvider ItemProvider { + get { + return new NSItemProvider (image); } } /// <summary> /// Returns a closure that will generate a drag preview for this photo. /// </summary> - public UIDragPreview PreviewProvider() + public UIDragPreview PreviewProvider () { - var imageView = new UIImageView(image); - imageView.Bounds = new CGRect(imageView.Bounds.Location, new CGSize(200, 200)); - imageView.Frame = imageView.ContentClippingRect(); - return new UIDragPreview(imageView); + var imageView = new UIImageView (image); + imageView.Bounds = new CGRect (imageView.Bounds.Location, new CGSize (200, 200)); + imageView.Frame = imageView.ContentClippingRect (); + return new UIDragPreview (imageView); } - } + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo.cs index b2ac6bff5..26124c5ac 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/Photo.cs @@ -1,59 +1,57 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; -namespace PhotoAlbum -{ +namespace PhotoAlbum { /// <summary> /// A model object that represents a photo. /// </summary> - public partial class Photo : NSObject - { - public Photo(UIImage image) - { - this.image = image; - thumbnail = GenerateThumbnail(image, new CGSize(50, 50)); - } + public partial class Photo : NSObject { + public Photo (UIImage image) + { + this.image = image; + thumbnail = GenerateThumbnail (image, new CGSize (50, 50)); + } - public readonly Guid Identifier = Guid.NewGuid(); - public UIImage image; - public UIImage thumbnail; + public readonly Guid Identifier = Guid.NewGuid (); + public UIImage image; + public UIImage thumbnail; - #region Equatable - public override bool Equals(System.Object obj) + #region Equatable + public override bool Equals (System.Object obj) { - return ((Photo)obj).Identifier == Identifier; + return ((Photo) obj).Identifier == Identifier; } - public bool Equals(Photo p) + public bool Equals (Photo p) { return p.Identifier == Identifier; } - public override int GetHashCode() + public override int GetHashCode () { - return Identifier.GetHashCode(); + return Identifier.GetHashCode (); } - #endregion + #endregion - /// <summary> - /// Generates and returns a thumbnail for the image using scale aspect fill. - /// </summary> - UIImage GenerateThumbnail (UIImage forImage, CGSize thumbnailSize){ - var imageSize = forImage.Size; + /// <summary> + /// Generates and returns a thumbnail for the image using scale aspect fill. + /// </summary> + UIImage GenerateThumbnail (UIImage forImage, CGSize thumbnailSize) + { + var imageSize = forImage.Size; - var widthRatio = thumbnailSize.Width / imageSize.Width; - var heightRatio = thumbnailSize.Height / imageSize.Height; - var scaleFactor = widthRatio > heightRatio ? widthRatio : heightRatio; + var widthRatio = thumbnailSize.Width / imageSize.Width; + var heightRatio = thumbnailSize.Height / imageSize.Height; + var scaleFactor = widthRatio > heightRatio ? widthRatio : heightRatio; - var renderer = new UIGraphicsImageRenderer(thumbnailSize); - var newThumbnail = renderer.CreateImage((err) => - { - var size = new CGSize(imageSize.Width * scaleFactor, imageSize.Height * scaleFactor); - var x = (thumbnailSize.Width - size.Width) / 2.0; - var y = (thumbnailSize.Height - size.Height) / 2.0; - forImage.Draw(new CGRect(new CGPoint(x,y), size)); - }); - return newThumbnail; - } - } + var renderer = new UIGraphicsImageRenderer (thumbnailSize); + var newThumbnail = renderer.CreateImage ((err) => { + var size = new CGSize (imageSize.Width * scaleFactor, imageSize.Height * scaleFactor); + var x = (thumbnailSize.Width - size.Width) / 2.0; + var y = (thumbnailSize.Height - size.Height) / 2.0; + forImage.Draw (new CGRect (new CGPoint (x, y), size)); + }); + return newThumbnail; + } + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoAlbum.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoAlbum.cs index eb5720cfa..441cd419f 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoAlbum.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoAlbum.cs @@ -1,47 +1,45 @@ -using System; +using System; using System.Collections.Generic; using UIKit; -namespace PhotoAlbum -{ +namespace PhotoAlbum { /// <summary> /// A model object that represents an album of photos. /// </summary> - public class PhotoAlbum - { - public PhotoAlbum() - { - } + public class PhotoAlbum { + public PhotoAlbum () + { + } - public readonly Guid Identifier = Guid.NewGuid(); - public string Title = ""; - public List<Photo> Photos = new List<Photo>(); + public readonly Guid Identifier = Guid.NewGuid (); + public string Title = ""; + public List<Photo> Photos = new List<Photo> (); - public UIImage Thumbnail { - get { - if (Photos.Count > 0) - return Photos[0]?.thumbnail; - else - return null; - } - } + public UIImage Thumbnail { + get { + if (Photos.Count > 0) + return Photos [0]?.thumbnail; + else + return null; + } + } - public bool Contains (Photo photo) - { - return Photos.Contains(photo); - } + public bool Contains (Photo photo) + { + return Photos.Contains (photo); + } - public override bool Equals(System.Object obj) + public override bool Equals (System.Object obj) { - return ((PhotoAlbum)obj).Identifier == Identifier; + return ((PhotoAlbum) obj).Identifier == Identifier; } - public bool Equals(PhotoAlbum p) + public bool Equals (PhotoAlbum p) { - return p.Identifier == Identifier; + return p.Identifier == Identifier; } - public override int GetHashCode() + public override int GetHashCode () { - return Identifier.GetHashCode(); + return Identifier.GetHashCode (); } - } + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoLibrary.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoLibrary.cs index 1e7cb651a..71736dc43 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoLibrary.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/DataModel/PhotoLibrary.cs @@ -1,191 +1,181 @@ -using System; +using System; using System.Collections.Generic; using System.Timers; using CoreFoundation; using UIKit; -namespace PhotoAlbum -{ - /// <summary> - /// The backing data store for the application that contains an array of photo albums, and methods to retrieve data from and mutate the contents of these albums. - /// </summary> - public class PhotoLibrary - { - static PhotoLibrary sharedInstance = new PhotoLibrary(); - public static PhotoLibrary SharedInstance - { - get - { - return sharedInstance; - } - } - - public List<PhotoAlbum> Albums = new List<PhotoAlbum>(); - - #region Identifier Lookups - public PhotoAlbum Album(Guid identifier) - { - return Albums.Find(photo => photo.Identifier == identifier); - } - - public Photo Photo(Guid identifier) - { - var album = Albums.Find(a => - { - return a.Photos.Contains(a.Photos.Find(p => p.Identifier == identifier)); - }); - return album?.Photos.Find(photo => photo.Identifier == identifier); - } - #endregion - - #region Photo Library Mutations - /// <summary> - /// Adds a photo to the album. - /// </summary> - public void Add(Photo photo, PhotoAlbum toAlbum) - { - var albumIndex = Albums.IndexOf(toAlbum); - - Albums[albumIndex].Photos.Insert(0, photo); - } - - /// <summary> - /// Inserts the photo at a specific index in the album. - /// </summary> - public void Insert(Photo photo, PhotoAlbum inAlbum, int index) - { - var albumIndex = Albums.IndexOf(inAlbum); - - Albums[albumIndex].Photos.Insert(index, photo); - } - - /// <summary> - /// Moves an album from one index to another. - /// </summary> - public void MoveAlbum(int sourceIndex, int destinationIndex) - { - var album = Albums[sourceIndex]; - Albums.Remove(album); - Albums.Insert(destinationIndex, album); - } - - /// <summary> - /// Moves a photo from one index to another in the album. - /// </summary> - public void MovePhoto(PhotoAlbum album, int sourceIndex, int destinationIndex) - { - var albumIndex = Albums.IndexOf(album); - if (albumIndex < 0) return; - - var photo = Albums[albumIndex].Photos[sourceIndex]; - Albums[albumIndex].Photos.Remove(photo); - Albums[albumIndex].Photos.Insert(destinationIndex, photo); - } - - /// <summary> - /// Moves a photo to a different album at a specific index in that album. Defaults to inserting at the beginning of the album if no index is specified. - /// </summary> - public void MovePhoto(Photo photo, PhotoAlbum toAlbum, int index = 0) - { - var sourceAlbumIndex = Albums.IndexOf(Albums.Find(a => a.Photos.Contains(photo))); - var indexOfPhotoInSourceAlbum = Albums[sourceAlbumIndex].Photos.IndexOf(photo); - var destinationAlbumIndex = Albums.IndexOf(toAlbum); - - if (sourceAlbumIndex < 0 || indexOfPhotoInSourceAlbum < 0 || destinationAlbumIndex < 0) return; - - var movePhoto = Albums[sourceAlbumIndex].Photos[indexOfPhotoInSourceAlbum]; - Albums[sourceAlbumIndex].Photos.Remove(movePhoto); - Albums[destinationAlbumIndex].Photos.Insert(index, movePhoto); - } - #endregion - - #region Timed Automatic Insertions - PhotoAlbum albumForAutomaticInsertions; - Timer automaticInsertionTimer; - - /// <summary> - /// Starts a timer that performs an automatic insertion of a photo into the album when it fires. - /// </summary> - public void StartAutomaticInsertions(PhotoAlbum album, PhotoCollectionViewController photoCollectionViewController) - { - StopAutomaticInsertions(); - - albumForAutomaticInsertions = album; - automaticInsertionTimer = new Timer(1000); - automaticInsertionTimer.Elapsed += (sender, e) => { - var intoAlbum = albumForAutomaticInsertions; - var albumIndex = Albums.IndexOf(intoAlbum); - if (intoAlbum == null || albumIndex < 0) return; - - DispatchQueue.MainQueue.DispatchAsync(() => - { - var image = UIImage.FromBundle("AutomaticInsertion.png"); - - var photo = new Photo(image); - var insertionIndex = new Random().Next(Albums[albumIndex].Photos.Count); - Console.WriteLine("insert" + insertionIndex); - Albums[albumIndex].Photos.Insert(insertionIndex, photo); - photoCollectionViewController.InsertedItem(insertionIndex); - }); +namespace PhotoAlbum { + /// <summary> + /// The backing data store for the application that contains an array of photo albums, and methods to retrieve data from and mutate the contents of these albums. + /// </summary> + public class PhotoLibrary { + static PhotoLibrary sharedInstance = new PhotoLibrary (); + public static PhotoLibrary SharedInstance { + get { + return sharedInstance; + } + } + + public List<PhotoAlbum> Albums = new List<PhotoAlbum> (); + + #region Identifier Lookups + public PhotoAlbum Album (Guid identifier) + { + return Albums.Find (photo => photo.Identifier == identifier); + } + + public Photo Photo (Guid identifier) + { + var album = Albums.Find (a => { + return a.Photos.Contains (a.Photos.Find (p => p.Identifier == identifier)); + }); + return album?.Photos.Find (photo => photo.Identifier == identifier); + } + #endregion + + #region Photo Library Mutations + /// <summary> + /// Adds a photo to the album. + /// </summary> + public void Add (Photo photo, PhotoAlbum toAlbum) + { + var albumIndex = Albums.IndexOf (toAlbum); + + Albums [albumIndex].Photos.Insert (0, photo); + } + + /// <summary> + /// Inserts the photo at a specific index in the album. + /// </summary> + public void Insert (Photo photo, PhotoAlbum inAlbum, int index) + { + var albumIndex = Albums.IndexOf (inAlbum); + + Albums [albumIndex].Photos.Insert (index, photo); + } + + /// <summary> + /// Moves an album from one index to another. + /// </summary> + public void MoveAlbum (int sourceIndex, int destinationIndex) + { + var album = Albums [sourceIndex]; + Albums.Remove (album); + Albums.Insert (destinationIndex, album); + } + + /// <summary> + /// Moves a photo from one index to another in the album. + /// </summary> + public void MovePhoto (PhotoAlbum album, int sourceIndex, int destinationIndex) + { + var albumIndex = Albums.IndexOf (album); + if (albumIndex < 0) return; + + var photo = Albums [albumIndex].Photos [sourceIndex]; + Albums [albumIndex].Photos.Remove (photo); + Albums [albumIndex].Photos.Insert (destinationIndex, photo); + } + + /// <summary> + /// Moves a photo to a different album at a specific index in that album. Defaults to inserting at the beginning of the album if no index is specified. + /// </summary> + public void MovePhoto (Photo photo, PhotoAlbum toAlbum, int index = 0) + { + var sourceAlbumIndex = Albums.IndexOf (Albums.Find (a => a.Photos.Contains (photo))); + var indexOfPhotoInSourceAlbum = Albums [sourceAlbumIndex].Photos.IndexOf (photo); + var destinationAlbumIndex = Albums.IndexOf (toAlbum); + + if (sourceAlbumIndex < 0 || indexOfPhotoInSourceAlbum < 0 || destinationAlbumIndex < 0) return; + + var movePhoto = Albums [sourceAlbumIndex].Photos [indexOfPhotoInSourceAlbum]; + Albums [sourceAlbumIndex].Photos.Remove (movePhoto); + Albums [destinationAlbumIndex].Photos.Insert (index, movePhoto); + } + #endregion + + #region Timed Automatic Insertions + PhotoAlbum albumForAutomaticInsertions; + Timer automaticInsertionTimer; + + /// <summary> + /// Starts a timer that performs an automatic insertion of a photo into the album when it fires. + /// </summary> + public void StartAutomaticInsertions (PhotoAlbum album, PhotoCollectionViewController photoCollectionViewController) + { + StopAutomaticInsertions (); + + albumForAutomaticInsertions = album; + automaticInsertionTimer = new Timer (1000); + automaticInsertionTimer.Elapsed += (sender, e) => { + var intoAlbum = albumForAutomaticInsertions; + var albumIndex = Albums.IndexOf (intoAlbum); + if (intoAlbum == null || albumIndex < 0) return; + + DispatchQueue.MainQueue.DispatchAsync (() => { + var image = UIImage.FromBundle ("AutomaticInsertion.png"); + + var photo = new Photo (image); + var insertionIndex = new Random ().Next (Albums [albumIndex].Photos.Count); + Console.WriteLine ("insert" + insertionIndex); + Albums [albumIndex].Photos.Insert (insertionIndex, photo); + photoCollectionViewController.InsertedItem (insertionIndex); + }); }; - automaticInsertionTimer.Start(); - } - - /// <summary> - /// Stops the timer that performs automatic insertions. - /// </summary> - public void StopAutomaticInsertions() - { - albumForAutomaticInsertions = null; - automaticInsertionTimer?.Stop(); - automaticInsertionTimer = null; - } - #endregion - - #region Initialization and Loading Sample Data - public PhotoLibrary() + automaticInsertionTimer.Start (); + } + + /// <summary> + /// Stops the timer that performs automatic insertions. + /// </summary> + public void StopAutomaticInsertions () { - LoadSampleData(); + albumForAutomaticInsertions = null; + automaticInsertionTimer?.Stop (); + automaticInsertionTimer = null; } + #endregion - void LoadSampleData() - { - var albumIndex = 0; - bool foundAlbum; - - do - { - foundAlbum = false; - var photos = new List<Photo>(); - - var photoIndex = 0; - bool foundPhoto; - - do - { - foundPhoto = false; - var imageName = $"Sample Data/Album{albumIndex}Photo{photoIndex}.jpg"; - var image = UIImage.FromBundle(imageName); - if (image != null) - { - foundPhoto = true; - var photo = new Photo(image); - photos.Add(photo); - } - photoIndex++; - } while (foundPhoto); - - if (photos.Count != 0) - { - foundAlbum = true; - var title = $"Album {albumIndex + 1}"; - var album = new PhotoAlbum { Title = title, Photos = photos }; - Albums.Add(album); - } - albumIndex++; - } while (foundAlbum); - Console.WriteLine("" + albumIndex); - } - #endregion - } + #region Initialization and Loading Sample Data + public PhotoLibrary () + { + LoadSampleData (); + } + + void LoadSampleData () + { + var albumIndex = 0; + bool foundAlbum; + + do { + foundAlbum = false; + var photos = new List<Photo> (); + + var photoIndex = 0; + bool foundPhoto; + + do { + foundPhoto = false; + var imageName = $"Sample Data/Album{albumIndex}Photo{photoIndex}.jpg"; + var image = UIImage.FromBundle (imageName); + if (image != null) { + foundPhoto = true; + var photo = new Photo (image); + photos.Add (photo); + } + photoIndex++; + } while (foundPhoto); + + if (photos.Count != 0) { + foundAlbum = true; + var title = $"Album {albumIndex + 1}"; + var album = new PhotoAlbum { Title = title, Photos = photos }; + Albums.Add (album); + } + albumIndex++; + } while (foundAlbum); + Console.WriteLine ("" + albumIndex); + } + #endregion + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/Main.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/Main.cs index 62d3a918a..b7d2c6b6d 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/Main.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PhotoAlbum -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace PhotoAlbum { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewCell.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewCell.cs index 9d18f946a..8903cd1c9 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewCell.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewCell.cs @@ -1,37 +1,35 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using CoreGraphics; -namespace PhotoAlbum -{ - /// <summary> - /// A collection view cell used to display a photo in a photo album. - /// </summary> - public partial class PhotoCollectionViewCell : UICollectionViewCell - { - public static string Identifier = "PhotoCollectionViewCell"; - - public PhotoCollectionViewCell (IntPtr handle) : base (handle) - { - photoImageView = new UIImageView(); - photoImageView.Frame = new CGRect(0, 0, 200, 200); - photoImageView.AlignmentRectForFrame(new CGRect(0, 0, 200, 200)); - AddSubview(photoImageView); - } - - public CGRect ClippingRectForPhoto { - get { - return photoImageView.ContentClippingRect(); - } - } +namespace PhotoAlbum { + /// <summary> + /// A collection view cell used to display a photo in a photo album. + /// </summary> + public partial class PhotoCollectionViewCell : UICollectionViewCell { + public static string Identifier = "PhotoCollectionViewCell"; - /// <summary> - /// Configures the cell to display the photo. - /// </summary> - public void Configure (Photo photo) - { - photoImageView.Image = photo.image; - } - } -} \ No newline at end of file + public PhotoCollectionViewCell (IntPtr handle) : base (handle) + { + photoImageView = new UIImageView (); + photoImageView.Frame = new CGRect (0, 0, 200, 200); + photoImageView.AlignmentRectForFrame (new CGRect (0, 0, 200, 200)); + AddSubview (photoImageView); + } + + public CGRect ClippingRectForPhoto { + get { + return photoImageView.ContentClippingRect (); + } + } + + /// <summary> + /// Configures the cell to display the photo. + /// </summary> + public void Configure (Photo photo) + { + photoImageView.Image = photo.image; + } + } +} diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drag.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drag.cs index 4f97acbf7..13c7d1907 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drag.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drag.cs @@ -1,86 +1,81 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; -namespace PhotoAlbum -{ - public partial class PhotoCollectionViewController - { - public UIDragItem[] GetItemsForBeginningDragSession(UICollectionView collectionView, IUIDragSession session, NSIndexPath indexPath) +namespace PhotoAlbum { + public partial class PhotoCollectionViewController { + public UIDragItem [] GetItemsForBeginningDragSession (UICollectionView collectionView, IUIDragSession session, NSIndexPath indexPath) { - var dragItem = DragItem(indexPath); - return new UIDragItem[] { dragItem }; + var dragItem = DragItem (indexPath); + return new UIDragItem [] { dragItem }; } - [Export("collectionView:itemsForAddingToDragSession:atIndexPath:point:")] - public UIDragItem[] GetItemsForAddingToDragSession(UICollectionView collectionView, IUIDragSession session, Foundation.NSIndexPath indexPath, CoreGraphics.CGPoint point) + [Export ("collectionView:itemsForAddingToDragSession:atIndexPath:point:")] + public UIDragItem [] GetItemsForAddingToDragSession (UICollectionView collectionView, IUIDragSession session, Foundation.NSIndexPath indexPath, CoreGraphics.CGPoint point) { - var dragItem = DragItem(indexPath); - return new UIDragItem[] { dragItem }; + var dragItem = DragItem (indexPath); + return new UIDragItem [] { dragItem }; } // Helper method to obtain a drag item for the photo at the index path. - UIDragItem DragItem(NSIndexPath indexPath) + UIDragItem DragItem (NSIndexPath indexPath) { - var photo = Photo(indexPath); + var photo = Photo (indexPath); var itemProvider = photo.ItemProvider; - var dragItem = new UIDragItem(itemProvider); + var dragItem = new UIDragItem (itemProvider); dragItem.LocalObject = photo; return dragItem; } - [Export("collectionView:dragPreviewParametersForItemAtIndexPath:")] - public UIDragPreviewParameters GetDragPreviewParameters(UICollectionView collectionView, NSIndexPath indexPath) + [Export ("collectionView:dragPreviewParametersForItemAtIndexPath:")] + public UIDragPreviewParameters GetDragPreviewParameters (UICollectionView collectionView, NSIndexPath indexPath) { - return PreviewParameters(indexPath); + return PreviewParameters (indexPath); } /// <summary>Stores the album state when the drag begins.</summary> PhotoAlbum albumBeforeDrag; - [Export("collectionView:dragSessionWillBegin:")] - public void DragSessionWillBegin(UICollectionView collectionView, IUIDragSession session) - { - albumBeforeDrag = album; - } + [Export ("collectionView:dragSessionWillBegin:")] + public void DragSessionWillBegin (UICollectionView collectionView, IUIDragSession session) + { + albumBeforeDrag = album; + } - [Export("collectionView:dragSessionDidEnd:")] - public void DragSessionDidEnd(UICollectionView collectionView, IUIDragSession session) - { - ReloadAlbumFromPhotoLibrary(); - DeleteItems(collectionView); - albumBeforeDrag = null; - } + [Export ("collectionView:dragSessionDidEnd:")] + public void DragSessionDidEnd (UICollectionView collectionView, IUIDragSession session) + { + ReloadAlbumFromPhotoLibrary (); + DeleteItems (collectionView); + albumBeforeDrag = null; + } /// <summary> /// Compares the album state before and after the drag to delete items in the collection view that represent photos moved elsewhere. /// </summary> void DeleteItems (UICollectionView collectionView) - { - var albumAfterDrag = album; - if (albumBeforeDrag is null || albumAfterDrag is null) return; + { + var albumAfterDrag = album; + if (albumBeforeDrag is null || albumAfterDrag is null) return; + + var indexPathsToDelete = new List<NSIndexPath> (); - var indexPathsToDelete = new List<NSIndexPath> (); + for (var i = 0; i < albumBeforeDrag.Photos.Count; i++) { + var photo = albumBeforeDrag.Photos [i]; + if (!albumAfterDrag.Contains (photo)) { + indexPathsToDelete.Add (NSIndexPath.FromItemSection (i, 0)); + } + } + if (indexPathsToDelete.Count > 0) { + collectionView.PerformBatchUpdates (() => { + collectionView.DeleteItems (indexPathsToDelete.ToArray ()); + }, (finished) => { }); + } + } - for (var i = 0; i < albumBeforeDrag.Photos.Count; i++) - { - var photo = albumBeforeDrag.Photos[i]; - if (!albumAfterDrag.Contains(photo)) - { - indexPathsToDelete.Add(NSIndexPath.FromItemSection(i, 0)); - } - } - if (indexPathsToDelete.Count > 0) - { - collectionView.PerformBatchUpdates(() =>{ - collectionView.DeleteItems(indexPathsToDelete.ToArray()); - }, (finished) => {}); - } - } - } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drop.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drop.cs index be6de9408..e0dafa7cf 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drop.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController+Drop.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using System; using System.Collections; using System.Collections.Generic; @@ -6,190 +6,167 @@ using System.Linq; using CoreFoundation; -namespace PhotoAlbum -{ - public partial class PhotoCollectionViewController - { - [Export("collectionView:canHandleDropSession:")] - public bool CanHandleDropSession(UICollectionView collectionView, IUIDropSession session) - { - if (album == null) return false; - return session.HasConformingItems(UIImage.ReadableTypeIdentifiers); +namespace PhotoAlbum { + public partial class PhotoCollectionViewController { + [Export ("collectionView:canHandleDropSession:")] + public bool CanHandleDropSession (UICollectionView collectionView, IUIDropSession session) + { + if (album == null) return false; + return session.HasConformingItems (UIImage.ReadableTypeIdentifiers); } - [Export("collectionView:dropSessionDidUpdate:withDestinationIndexPath:")] - public UICollectionViewDropProposal DropSessionDidUpdate(UICollectionView collectionView, IUIDropSession session, NSIndexPath destinationIndexPath) - { - if (session.LocalDragSession != null) - { - return new UICollectionViewDropProposal(UIDropOperation.Move, UICollectionViewDropIntent.InsertAtDestinationIndexPath); - } - else - { - return new UICollectionViewDropProposal(UIDropOperation.Copy, UICollectionViewDropIntent.InsertAtDestinationIndexPath); - } - } + [Export ("collectionView:dropSessionDidUpdate:withDestinationIndexPath:")] + public UICollectionViewDropProposal DropSessionDidUpdate (UICollectionView collectionView, IUIDropSession session, NSIndexPath destinationIndexPath) + { + if (session.LocalDragSession != null) { + return new UICollectionViewDropProposal (UIDropOperation.Move, UICollectionViewDropIntent.InsertAtDestinationIndexPath); + } else { + return new UICollectionViewDropProposal (UIDropOperation.Copy, UICollectionViewDropIntent.InsertAtDestinationIndexPath); + } + } public void PerformDrop (UICollectionView collectionView, IUICollectionViewDropCoordinator coordinator) { - if (album == null) return; - - var destinationIndexPath = coordinator.DestinationIndexPath ?? NSIndexPath.FromRowSection(0, 0); - - switch (coordinator.Proposal.Operation) - { - case UIDropOperation.Copy: - // Receiving items from another app. - LoadAndInsertItems(destinationIndexPath, coordinator); - break; - case UIDropOperation.Move: - var items = coordinator.Items; - var hasSourceIndex = items.FirstOrDefault(i => i.SourceIndexPath != null); - var containsSourceIndex = items.ToList().Contains(hasSourceIndex); // HACK: not sure about this port of `if items.contains(where: { $0.sourceIndexPath != nil }) ` - if (hasSourceIndex != null) - { - if (items.Length == 1) { - // Reordering a single item from this collection view. - var item = items[0]; - Reorder(item, destinationIndexPath, coordinator); - } - } - else - { - // Moving items from somewhere else in this app. - MoveItems(destinationIndexPath, coordinator); - } - - break; - default: - return; - } + if (album == null) return; + + var destinationIndexPath = coordinator.DestinationIndexPath ?? NSIndexPath.FromRowSection (0, 0); + + switch (coordinator.Proposal.Operation) { + case UIDropOperation.Copy: + // Receiving items from another app. + LoadAndInsertItems (destinationIndexPath, coordinator); + break; + case UIDropOperation.Move: + var items = coordinator.Items; + var hasSourceIndex = items.FirstOrDefault (i => i.SourceIndexPath != null); + var containsSourceIndex = items.ToList ().Contains (hasSourceIndex); // HACK: not sure about this port of `if items.contains(where: { $0.sourceIndexPath != nil }) ` + if (hasSourceIndex != null) { + if (items.Length == 1) { + // Reordering a single item from this collection view. + var item = items [0]; + Reorder (item, destinationIndexPath, coordinator); + } + } else { + // Moving items from somewhere else in this app. + MoveItems (destinationIndexPath, coordinator); + } + + break; + default: + return; + } } /// <summary> /// Loads data using the item provider and inserts a new item in the collection view for each item in the drop session, using placeholders while the data loads asynchronously. /// </summary> void LoadAndInsertItems (NSIndexPath destinationPath, IUICollectionViewDropCoordinator coordinator) - { - if (album == null) return; - - foreach (var item in coordinator.Items) - { - var dragItem = item.DragItem; - if (dragItem.ItemProvider.CanLoadObject(typeof(UIImage))) - { - IUICollectionViewDropPlaceholderContext placeholderContext = null; - - // Start loading the image for this drag item. - var progress = dragItem.ItemProvider.LoadObject<UIImage>( - (droppedImage, err) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var image = droppedImage as UIImage; - if (image != null) - { //The image loaded successfully, commit the insertion to exchange the placeholder for the final cell. - placeholderContext?.CommitInsertion((insertionIndexPath) => - { // Update the photo library backing store to insert the new photo, using the insertionIndexPath passed into the closure. - var photo = new Photo(image); - var insertionIndex = insertionIndexPath.Item; - UpdatePhotoLibrary((photoLibrary) => - { - photoLibrary.Insert(photo, album, (int)insertionIndex); - }); - }); - } - else - { // The data transfer for this item was canceled or failed, delete the placeholder. - placeholderContext?.DeletePlaceholder(); - } - }); - }); + { + if (album == null) return; + + foreach (var item in coordinator.Items) { + var dragItem = item.DragItem; + if (dragItem.ItemProvider.CanLoadObject (typeof (UIImage))) { + IUICollectionViewDropPlaceholderContext placeholderContext = null; + + // Start loading the image for this drag item. + var progress = dragItem.ItemProvider.LoadObject<UIImage> ( + (droppedImage, err) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + var image = droppedImage as UIImage; + if (image != null) { //The image loaded successfully, commit the insertion to exchange the placeholder for the final cell. + placeholderContext?.CommitInsertion ((insertionIndexPath) => { // Update the photo library backing store to insert the new photo, using the insertionIndexPath passed into the closure. + var photo = new Photo (image); + var insertionIndex = insertionIndexPath.Item; + UpdatePhotoLibrary ((photoLibrary) => { + photoLibrary.Insert (photo, album, (int) insertionIndex); + }); + }); + } else { // The data transfer for this item was canceled or failed, delete the placeholder. + placeholderContext?.DeletePlaceholder (); + } + }); + }); // Insert and animate to a placeholder for this item, configuring the placeholder cell to display the progress of the data transfer for this item. - var placeholder = new UICollectionViewDropPlaceholder(destinationPath, PhotoPlaceholderCollectionViewCell.Identifier); - placeholder.CellUpdateHandler = (cell) => { - var placeholderCell = cell as PhotoPlaceholderCollectionViewCell; - if (cell is null) return; - placeholderCell.Configure(progress); - }; - placeholderContext = coordinator.DropItemToPlaceholder(dragItem, placeholder); - } - } - } - - public UIDragPreviewParameters GetDropPreviewParameters (UICollectionView collectionView, NSIndexPath indexPath) - { - return PreviewParameters(indexPath); - } - - UIDragPreviewParameters PreviewParameters (NSIndexPath indexPath) - { - var cell = CollectionView.CellForItem(indexPath) as PhotoCollectionViewCell; - var previewParameters = new UIDragPreviewParameters(); - previewParameters.VisiblePath = UIBezierPath.FromRect(cell.ClippingRectForPhoto); - return previewParameters; - } + var placeholder = new UICollectionViewDropPlaceholder (destinationPath, PhotoPlaceholderCollectionViewCell.Identifier); + placeholder.CellUpdateHandler = (cell) => { + var placeholderCell = cell as PhotoPlaceholderCollectionViewCell; + if (cell is null) return; + placeholderCell.Configure (progress); + }; + placeholderContext = coordinator.DropItemToPlaceholder (dragItem, placeholder); + } + } + } + + public UIDragPreviewParameters GetDropPreviewParameters (UICollectionView collectionView, NSIndexPath indexPath) + { + return PreviewParameters (indexPath); + } + + UIDragPreviewParameters PreviewParameters (NSIndexPath indexPath) + { + var cell = CollectionView.CellForItem (indexPath) as PhotoCollectionViewCell; + var previewParameters = new UIDragPreviewParameters (); + previewParameters.VisiblePath = UIBezierPath.FromRect (cell.ClippingRectForPhoto); + return previewParameters; + } /// <summary> /// Moves an item (photo) in this collection view from one index path to another index path. /// </summary> void Reorder (IUICollectionViewDropItem item, NSIndexPath destinationIndexPath, IUICollectionViewDropCoordinator coordinator) - { - var sourceIndexPath = item?.SourceIndexPath; - if (CollectionView is null || album is null || sourceIndexPath is null) return; + { + var sourceIndexPath = item?.SourceIndexPath; + if (CollectionView is null || album is null || sourceIndexPath is null) return; // Perform batch updates to update the photo library backing store and perform the delete & insert on the collection view. - CollectionView.PerformBatchUpdates(() => - { - UpdatePhotoLibrary( (photoLibrary) => { - photoLibrary.MovePhoto(album, (int)sourceIndexPath.Item, (int)destinationIndexPath.Item); - }); - - CollectionView.DeleteItems(new NSIndexPath[] { sourceIndexPath}); - CollectionView.InsertItems(new NSIndexPath[] { destinationIndexPath }); - }, (finished) => { - - }); - - coordinator.DropItemToItem(item.DragItem, destinationIndexPath); - } + CollectionView.PerformBatchUpdates (() => { + UpdatePhotoLibrary ((photoLibrary) => { + photoLibrary.MovePhoto (album, (int) sourceIndexPath.Item, (int) destinationIndexPath.Item); + }); + + CollectionView.DeleteItems (new NSIndexPath [] { sourceIndexPath }); + CollectionView.InsertItems (new NSIndexPath [] { destinationIndexPath }); + }, (finished) => { + + }); + + coordinator.DropItemToItem (item.DragItem, destinationIndexPath); + } /// <summary> /// Moves one or more photos from a different album into this album by inserting items into this collection view. /// </summary> void MoveItems (NSIndexPath destinationIndexPath, IUICollectionViewDropCoordinator coordinator) - { - if (CollectionView is null || album is null) return; - - var destinationIndex = destinationIndexPath.Item; - - foreach (var item in coordinator.Items) - { - var photo = item.DragItem.LocalObject as Photo; - if (!album.Contains(photo)) - { - var insertionIndexPath = NSIndexPath.FromRowSection(destinationIndex, 0); - - CollectionView.PerformBatchUpdates(() => { - UpdatePhotoLibrary((photoLibrary) => - { - photoLibrary.MovePhoto (photo, album, (int)destinationIndex); - }); - try - { - CollectionView.InsertItems(new NSIndexPath[] { insertionIndexPath }); - } catch (Exception e){ - Console.WriteLine(e); - } - }, (finished) => {}); - - - coordinator.DropItemToItem(item.DragItem, insertionIndexPath); - destinationIndex += 1; - } - } - } - } + { + if (CollectionView is null || album is null) return; + + var destinationIndex = destinationIndexPath.Item; + + foreach (var item in coordinator.Items) { + var photo = item.DragItem.LocalObject as Photo; + if (!album.Contains (photo)) { + var insertionIndexPath = NSIndexPath.FromRowSection (destinationIndex, 0); + + CollectionView.PerformBatchUpdates (() => { + UpdatePhotoLibrary ((photoLibrary) => { + photoLibrary.MovePhoto (photo, album, (int) destinationIndex); + }); + try { + CollectionView.InsertItems (new NSIndexPath [] { insertionIndexPath }); + } catch (Exception e) { + Console.WriteLine (e); + } + }, (finished) => { }); + + + coordinator.DropItemToItem (item.DragItem, insertionIndexPath); + destinationIndex += 1; + } + } + } + } } diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController.cs index a4097936c..5e68e7932 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoCollectionViewController.cs @@ -1,147 +1,141 @@ -using Foundation; -using System; -using UIKit; -using ObjCRuntime; - -namespace PhotoAlbum -{ - /// <summary> - /// A collection view controller that displays the photos in a photo album. Supports drag and drop and reordering of photos in the album. - /// </summary> - public partial class PhotoCollectionViewController : UICollectionViewController, IUICollectionViewDelegateFlowLayout, IUICollectionViewDragDelegate, IUICollectionViewDropDelegate - { - public PhotoCollectionViewController(IntPtr handle) : base(handle) - { - } - - WeakReference<AlbumTableViewController> albumTableViewController; - - PhotoAlbum album; - PhotoAlbum Album - { - get { return album; } - set - { - album = value; - Title = album?.Title; - } - } - - Photo Photo(NSIndexPath atPath) - { - return Album?.Photos[(int)atPath.Item]; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - CollectionView.DragDelegate = this; - CollectionView.DropDelegate = this; - - UpdateRightBarButtonItem(); - } - - public override void ViewWillDisappear(bool animated) - { - base.ViewWillDisappear(animated); - - StopInsertions(); - } - - bool isPerformingAutomaticInsertions = false; - - void UpdateRightBarButtonItem() - { - var startInsertionsBarButtonItem = new UIBarButtonItem("Start Insertions", UIBarButtonItemStyle.Plain, this, new Selector("startInsertions")); - var stopInsertionsBarButtonItem = new UIBarButtonItem("Stop Insertions", UIBarButtonItemStyle.Done, this, new Selector("stopInsertions")); - NavigationItem.RightBarButtonItem = isPerformingAutomaticInsertions ? stopInsertionsBarButtonItem : startInsertionsBarButtonItem; - } - - [Export("startInsertions")] - public void StartInsertions() - { - if (album == null) return; - PhotoLibrary.SharedInstance.StartAutomaticInsertions(album, this); - isPerformingAutomaticInsertions = true; - UpdateRightBarButtonItem(); - } - - [Export("stopInsertions")] - void StopInsertions() - { - PhotoLibrary.SharedInstance.StopAutomaticInsertions(); - isPerformingAutomaticInsertions = false; - UpdateRightBarButtonItem(); - } - - public void LoadAlbum(PhotoAlbum album, AlbumTableViewController albumTableViewController) - { - this.Album = album; - this.albumTableViewController = new WeakReference<AlbumTableViewController>(albumTableViewController); - - if (albumBeforeDrag == null) - { - CollectionView?.ReloadData(); - } - - } - - /// <summary> - /// Performs updates to the photo library backing store, then loads the latest album and photo values from it. - /// </summary> - void UpdatePhotoLibrary(Action<PhotoLibrary> updates) - { - updates(PhotoLibrary.SharedInstance); - ReloadAlbumFromPhotoLibrary(); - } - - /// <summary> - /// Loads the latest album & photo values from the photo library backing store. - /// </summary> - void ReloadAlbumFromPhotoLibrary() - { - var albumIdentifier = album?.Identifier; - if (albumIdentifier != null) - Album = PhotoLibrary.SharedInstance.Album(albumIdentifier.Value); - - if (albumTableViewController.TryGetTarget(out var ctrl)) - { - ctrl.ReloadAlbumsFromPhotoLibrary(); - ctrl.UpdateVisibleAlbumCells(); - } - } - - /// <summary> - /// Called when an photo has been automatically inserted into the album this collection view is displaying. - /// </summary> - public void InsertedItem(int atIndex) - { - CollectionView?.PerformBatchUpdates( () =>{ - ReloadAlbumFromPhotoLibrary(); - CollectionView.InsertItems(new NSIndexPath[] { NSIndexPath.FromItemSection(atIndex, 0)}); - },(finished) => { - - }); - } - - #region UICollectionViewDataSource & UICollectionViewDelegate - - public override nint GetItemsCount(UICollectionView collectionView, nint section) - { - if (album == null) return 0; - return album.Photos.Count; - } - - public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) - { - var cell = collectionView.DequeueReusableCell(PhotoCollectionViewCell.Identifier, indexPath) as PhotoCollectionViewCell; - cell.Configure(Photo(indexPath)); - return cell; - } - - #endregion - - - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; +using ObjCRuntime; + +namespace PhotoAlbum { + /// <summary> + /// A collection view controller that displays the photos in a photo album. Supports drag and drop and reordering of photos in the album. + /// </summary> + public partial class PhotoCollectionViewController : UICollectionViewController, IUICollectionViewDelegateFlowLayout, IUICollectionViewDragDelegate, IUICollectionViewDropDelegate { + public PhotoCollectionViewController (IntPtr handle) : base (handle) + { + } + + WeakReference<AlbumTableViewController> albumTableViewController; + + PhotoAlbum album; + PhotoAlbum Album { + get { return album; } + set { + album = value; + Title = album?.Title; + } + } + + Photo Photo (NSIndexPath atPath) + { + return Album?.Photos [(int) atPath.Item]; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + CollectionView.DragDelegate = this; + CollectionView.DropDelegate = this; + + UpdateRightBarButtonItem (); + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + + StopInsertions (); + } + + bool isPerformingAutomaticInsertions = false; + + void UpdateRightBarButtonItem () + { + var startInsertionsBarButtonItem = new UIBarButtonItem ("Start Insertions", UIBarButtonItemStyle.Plain, this, new Selector ("startInsertions")); + var stopInsertionsBarButtonItem = new UIBarButtonItem ("Stop Insertions", UIBarButtonItemStyle.Done, this, new Selector ("stopInsertions")); + NavigationItem.RightBarButtonItem = isPerformingAutomaticInsertions ? stopInsertionsBarButtonItem : startInsertionsBarButtonItem; + } + + [Export ("startInsertions")] + public void StartInsertions () + { + if (album == null) return; + PhotoLibrary.SharedInstance.StartAutomaticInsertions (album, this); + isPerformingAutomaticInsertions = true; + UpdateRightBarButtonItem (); + } + + [Export ("stopInsertions")] + void StopInsertions () + { + PhotoLibrary.SharedInstance.StopAutomaticInsertions (); + isPerformingAutomaticInsertions = false; + UpdateRightBarButtonItem (); + } + + public void LoadAlbum (PhotoAlbum album, AlbumTableViewController albumTableViewController) + { + this.Album = album; + this.albumTableViewController = new WeakReference<AlbumTableViewController> (albumTableViewController); + + if (albumBeforeDrag == null) { + CollectionView?.ReloadData (); + } + + } + + /// <summary> + /// Performs updates to the photo library backing store, then loads the latest album and photo values from it. + /// </summary> + void UpdatePhotoLibrary (Action<PhotoLibrary> updates) + { + updates (PhotoLibrary.SharedInstance); + ReloadAlbumFromPhotoLibrary (); + } + + /// <summary> + /// Loads the latest album & photo values from the photo library backing store. + /// </summary> + void ReloadAlbumFromPhotoLibrary () + { + var albumIdentifier = album?.Identifier; + if (albumIdentifier != null) + Album = PhotoLibrary.SharedInstance.Album (albumIdentifier.Value); + + if (albumTableViewController.TryGetTarget (out var ctrl)) { + ctrl.ReloadAlbumsFromPhotoLibrary (); + ctrl.UpdateVisibleAlbumCells (); + } + } + + /// <summary> + /// Called when an photo has been automatically inserted into the album this collection view is displaying. + /// </summary> + public void InsertedItem (int atIndex) + { + CollectionView?.PerformBatchUpdates (() => { + ReloadAlbumFromPhotoLibrary (); + CollectionView.InsertItems (new NSIndexPath [] { NSIndexPath.FromItemSection (atIndex, 0) }); + }, (finished) => { + + }); + } + + #region UICollectionViewDataSource & UICollectionViewDelegate + + public override nint GetItemsCount (UICollectionView collectionView, nint section) + { + if (album == null) return 0; + return album.Photos.Count; + } + + public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) + { + var cell = collectionView.DequeueReusableCell (PhotoCollectionViewCell.Identifier, indexPath) as PhotoCollectionViewCell; + cell.Configure (Photo (indexPath)); + return cell; + } + + #endregion + + + } +} diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoPlaceholderCollectionViewCell.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoPlaceholderCollectionViewCell.cs index 4ef5955de..a1aef66f3 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoPlaceholderCollectionViewCell.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/PhotoPlaceholderCollectionViewCell.cs @@ -1,68 +1,62 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using CoreFoundation; using CoreGraphics; -namespace PhotoAlbum -{ - public partial class PhotoPlaceholderCollectionViewCell : UICollectionViewCell - { - public static string Identifier = "PhotoPlaceholderCollectionViewCell"; - public static NSString localKeyPath = new NSString("progress.fractionCompleted"); - - - public PhotoPlaceholderCollectionViewCell (IntPtr handle) : base (handle) - { - progressView = new UIProgressView(); - progressView.Frame = new CGRect(0, 95, 200, 10); - progressView.SetProgress(0.1f, false); - AddSubview(progressView); - } - - NSProgress progress; - - [Export("progress")] - public NSProgress Progress { - - get - { - return progress; - } - - set - { - progress = value; - - if (progress == null) return; - progressView.SetProgress((float)progress.FractionCompleted, false); - - Console.WriteLine("Dropping images from external applications doesn't work due to a bug with NSItemProviderReading and UIImage"); - // HACK: fix KVO once the LoadObject bug is resolved - //Progress.AddObserver(this, - //localKeyPath, - //NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, - //IntPtr.Zero); - } - } +namespace PhotoAlbum { + public partial class PhotoPlaceholderCollectionViewCell : UICollectionViewCell { + public static string Identifier = "PhotoPlaceholderCollectionViewCell"; + public static NSString localKeyPath = new NSString ("progress.fractionCompleted"); - public void Configure(NSProgress progress) + + public PhotoPlaceholderCollectionViewCell (IntPtr handle) : base (handle) + { + progressView = new UIProgressView (); + progressView.Frame = new CGRect (0, 95, 200, 10); + progressView.SetProgress (0.1f, false); + AddSubview (progressView); + } + + NSProgress progress; + + [Export ("progress")] + public NSProgress Progress { + + get { + return progress; + } + + set { + progress = value; + + if (progress == null) return; + progressView.SetProgress ((float) progress.FractionCompleted, false); + + Console.WriteLine ("Dropping images from external applications doesn't work due to a bug with NSItemProviderReading and UIImage"); + // HACK: fix KVO once the LoadObject bug is resolved + //Progress.AddObserver(this, + //localKeyPath, + //NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, + //IntPtr.Zero); + } + } + + public void Configure (NSProgress progress) + { + Progress = progress; + } + + public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { - Progress = progress; - } - - public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) - { - var @object = ofObject as NSProgress; + var @object = ofObject as NSProgress; - if (@object == progress && keyPath == localKeyPath) - { - var fractionCompleted = Convert.ToDouble(change?[ChangeNewKey]); - DispatchQueue.MainQueue.DispatchAsync(() => - { - progressView.SetProgress((float)fractionCompleted, true); - }); - } - } - } -} \ No newline at end of file + if (@object == progress && keyPath == localKeyPath) { + var fractionCompleted = Convert.ToDouble (change? [ChangeNewKey]); + DispatchQueue.MainQueue.DispatchAsync (() => { + progressView.SetProgress ((float) fractionCompleted, true); + }); + } + } + } +} diff --git a/ios11/DragAndDropCollectionView/PhotoAlbum/Utility/UIImageViewExtensions.cs b/ios11/DragAndDropCollectionView/PhotoAlbum/Utility/UIImageViewExtensions.cs index 79bd68048..8d78e3b5e 100644 --- a/ios11/DragAndDropCollectionView/PhotoAlbum/Utility/UIImageViewExtensions.cs +++ b/ios11/DragAndDropCollectionView/PhotoAlbum/Utility/UIImageViewExtensions.cs @@ -1,39 +1,37 @@ -using System; +using System; using CoreGraphics; using UIKit; -namespace PhotoAlbum -{ - public static class UIImageViewExtensions - { +namespace PhotoAlbum { + public static class UIImageViewExtensions { /// <summary> /// Returns a rect that can be applied to the image view to clip to the image, assuming a scale aspect fit content mode /// </summary> - public static CGRect ContentClippingRect(this UIImageView imageView) - { - if (imageView.ContentMode != UIViewContentMode.ScaleAspectFit) { - return imageView.Bounds; - } - var image = imageView.Image; + public static CGRect ContentClippingRect (this UIImageView imageView) + { + if (imageView.ContentMode != UIViewContentMode.ScaleAspectFit) { + return imageView.Bounds; + } + var image = imageView.Image; - var imageWidth = image.Size.Width; - var imageHeight = image.Size.Height; - if (!(imageWidth > 0 && imageHeight > 0)) { - return imageView.Bounds; - } + var imageWidth = image.Size.Width; + var imageHeight = image.Size.Height; + if (!(imageWidth > 0 && imageHeight > 0)) { + return imageView.Bounds; + } - nfloat scale; - if (imageWidth > imageHeight) { - scale = imageView.Bounds.Size.Width / imageWidth; - } else { - scale = imageView.Bounds.Size.Height / imageHeight; - } + nfloat scale; + if (imageWidth > imageHeight) { + scale = imageView.Bounds.Size.Width / imageWidth; + } else { + scale = imageView.Bounds.Size.Height / imageHeight; + } - var clippingSize = new CGSize(imageWidth * scale, imageHeight * scale); - var x = (imageView.Bounds.Size.Width - clippingSize.Width) / 2.0; - var y = (imageView.Bounds.Size.Height - clippingSize.Height) / 2.0; + var clippingSize = new CGSize (imageWidth * scale, imageHeight * scale); + var x = (imageView.Bounds.Size.Width - clippingSize.Width) / 2.0; + var y = (imageView.Bounds.Size.Height - clippingSize.Height) / 2.0; - return new CGRect(new CGPoint(x, y), clippingSize); - } - } + return new CGRect (new CGPoint (x, y), clippingSize); + } + } } diff --git a/ios11/DragAndDropCustomView/CustomViewDragAndDrop/AppDelegate.cs b/ios11/DragAndDropCustomView/CustomViewDragAndDrop/AppDelegate.cs index 0ea6d9bf2..a64d714e6 100644 --- a/ios11/DragAndDropCustomView/CustomViewDragAndDrop/AppDelegate.cs +++ b/ios11/DragAndDropCustomView/CustomViewDragAndDrop/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace CustomViewDragAndDrop { diff --git a/ios11/DragAndDropCustomView/CustomViewDragAndDrop/Main.cs b/ios11/DragAndDropCustomView/CustomViewDragAndDrop/Main.cs index ca73e3c75..1a7cf5847 100644 --- a/ios11/DragAndDropCustomView/CustomViewDragAndDrop/Main.cs +++ b/ios11/DragAndDropCustomView/CustomViewDragAndDrop/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace CustomViewDragAndDrop { public class Application { diff --git a/ios11/DragAndDropCustomView/CustomViewDragAndDrop/ViewController.cs b/ios11/DragAndDropCustomView/CustomViewDragAndDrop/ViewController.cs index 651120086..df9c64459 100644 --- a/ios11/DragAndDropCustomView/CustomViewDragAndDrop/ViewController.cs +++ b/ios11/DragAndDropCustomView/CustomViewDragAndDrop/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using CoreGraphics; using Foundation; diff --git a/ios11/DragAndDropDragBoard/DragBoard/AppDelegate.cs b/ios11/DragAndDropDragBoard/DragBoard/AppDelegate.cs index 232edbeb5..61da79d1e 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/AppDelegate.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace DragBoard -{ +namespace DragBoard { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method diff --git a/ios11/DragAndDropDragBoard/DragBoard/DragBoardView.cs b/ios11/DragAndDropDragBoard/DragBoard/DragBoardView.cs index 423e3a0d9..c881a71fc 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/DragBoardView.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/DragBoardView.cs @@ -2,25 +2,22 @@ using Foundation; using UIKit; -namespace DragBoard -{ +namespace DragBoard { /// <summary> /// A custom view that can handle paste events. /// </summary> - public partial class DragBoardView : UIView - { - public DragBoardView(IntPtr handle) : base(handle) + public partial class DragBoardView : UIView { + public DragBoardView (IntPtr handle) : base (handle) { } - - public override void AwakeFromNib() + + public override void AwakeFromNib () { - base.AwakeFromNib(); - BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle("Cork")); + base.AwakeFromNib (); + BackgroundColor = UIColor.FromPatternImage (UIImage.FromBundle ("Cork")); } - public override bool CanBecomeFirstResponder - { + public override bool CanBecomeFirstResponder { get { return true; } } } diff --git a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drag.cs b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drag.cs index 615cff98a..25e84bd1b 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drag.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drag.cs @@ -1,84 +1,77 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using CoreGraphics; using CoreFoundation; -namespace DragBoard -{ - public partial class DragBoardViewController : IUIDragInteractionDelegate - { - public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) - { - var point = session.LocationInView(interaction.View); +namespace DragBoard { + public partial class DragBoardViewController : IUIDragInteractionDelegate { + public UIDragItem [] GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) + { + var point = session.LocationInView (interaction.View); - var index = ImageIndex(point); - if (index >= 0) - { - var image = Images[index]; - var itemProvider = new NSItemProvider(image); - var dragItem = new UIDragItem(itemProvider); + var index = ImageIndex (point); + if (index >= 0) { + var image = Images [index]; + var itemProvider = new NSItemProvider (image); + var dragItem = new UIDragItem (itemProvider); - dragItem.LocalObject = new NSNumber(index); + dragItem.LocalObject = new NSNumber (index); - return new UIDragItem[] { dragItem }; + return new UIDragItem [] { dragItem }; } - return new UIDragItem[0]; - } + return new UIDragItem [0]; + } - [Export("dragInteraction:previewForLiftingItem:session:")] - public UITargetedDragPreview GetPreviewForLiftingItem(UIDragInteraction interaction, UIDragItem item, IUIDragSession session) - { - var index = item.LocalObject as NSNumber; - var i = index.Int32Value; - return new UITargetedDragPreview(Views[i]); - } + [Export ("dragInteraction:previewForLiftingItem:session:")] + public UITargetedDragPreview GetPreviewForLiftingItem (UIDragInteraction interaction, UIDragItem item, IUIDragSession session) + { + var index = item.LocalObject as NSNumber; + var i = index.Int32Value; + return new UITargetedDragPreview (Views [i]); + } - [Export("dragInteraction:willAnimateLiftWithAnimator:session:")] - public void WillAnimateLift(UIDragInteraction interaction, IUIDragAnimating animator, IUIDragSession session) - { - animator.AddCompletion((position) => { - if (position == UIViewAnimatingPosition.End) - { - FadeItems(session.Items, 0.5f); - } - }); - } + [Export ("dragInteraction:willAnimateLiftWithAnimator:session:")] + public void WillAnimateLift (UIDragInteraction interaction, IUIDragAnimating animator, IUIDragSession session) + { + animator.AddCompletion ((position) => { + if (position == UIViewAnimatingPosition.End) { + FadeItems (session.Items, 0.5f); + } + }); + } - [Export("dragInteraction:item:willAnimateCancelWithAnimator:")] - public void WillAnimateCancel(UIDragInteraction interaction, UIDragItem item, IUIDragAnimating animator) - { - animator.AddAnimations(() => - { - FadeItems(new UIDragItem[] {item}, 1f); - }); - } + [Export ("dragInteraction:item:willAnimateCancelWithAnimator:")] + public void WillAnimateCancel (UIDragInteraction interaction, UIDragItem item, IUIDragAnimating animator) + { + animator.AddAnimations (() => { + FadeItems (new UIDragItem [] { item }, 1f); + }); + } - [Export("dragInteraction:session:willEndWithOperation:")] - public void SessionWillEnd(UIDragInteraction interaction, IUIDragSession session, UIDropOperation operation) - { - if (operation == UIDropOperation.Copy) - { - FadeItems(session.Items, 1f); - } - } + [Export ("dragInteraction:session:willEndWithOperation:")] + public void SessionWillEnd (UIDragInteraction interaction, IUIDragSession session, UIDropOperation operation) + { + if (operation == UIDropOperation.Copy) { + FadeItems (session.Items, 1f); + } + } - // Returns the index of an image in the pin board - // at the given point, if any. - // - // - Parameter point: the point in the pin board coordinate space. - // - Returns: The index of an image if the point is over an image in pin board, nothing otherwise. - public int ImageIndex(CGPoint point) + // Returns the index of an image in the pin board + // at the given point, if any. + // + // - Parameter point: the point in the pin board coordinate space. + // - Returns: The index of an image if the point is over an image in pin board, nothing otherwise. + public int ImageIndex (CGPoint point) { - var hitTestView = View.HitTest(point, null); + var hitTestView = View.HitTest (point, null); if (hitTestView == null) return -1; // Search for view var n = 0; - foreach (UIView view in Views) - { + foreach (UIView view in Views) { if (view == hitTestView) return n; ++n; } @@ -86,5 +79,5 @@ public int ImageIndex(CGPoint point) // Not found return -1; } - } + } } diff --git a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drop.cs b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drop.cs index 9dffd79da..65731a4e9 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drop.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Drop.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -6,84 +6,70 @@ using CoreFoundation; -namespace DragBoard -{ - public partial class DragBoardViewController : IUIDropInteractionDelegate - { - [Export("dropInteraction:canHandleSession:")] - public bool CanHandleSession(UIDropInteraction interaction, IUIDropSession session) - { - return session.CanLoadObjects(typeof(UIImage)); - } +namespace DragBoard { + public partial class DragBoardViewController : IUIDropInteractionDelegate { + [Export ("dropInteraction:canHandleSession:")] + public bool CanHandleSession (UIDropInteraction interaction, IUIDropSession session) + { + return session.CanLoadObjects (typeof (UIImage)); + } - [Export("dropInteraction:sessionDidUpdate:")] - public UIDropProposal SessionDidUpdate(UIDropInteraction interaction, IUIDropSession session) - { - UIDropOperation operation; - if (session.LocalDragSession == null) - { - operation = UIDropOperation.Copy; - } - else - { - operation = UIDropOperation.Move; - } - return new UIDropProposal(operation); - } + [Export ("dropInteraction:sessionDidUpdate:")] + public UIDropProposal SessionDidUpdate (UIDropInteraction interaction, IUIDropSession session) + { + UIDropOperation operation; + if (session.LocalDragSession == null) { + operation = UIDropOperation.Copy; + } else { + operation = UIDropOperation.Move; + } + return new UIDropProposal (operation); + } - [Export("dropInteraction:performDrop:")] - public void PerformDrop(UIDropInteraction interaction, IUIDropSession session) - { - if (session.LocalDragSession == null) - { - DropPoint = session.LocationInView(interaction.View); - foreach (var dragItem in session.Items) - { - LoadImage (dragItem.ItemProvider, DropPoint); - } - } - else - { - MovePoint = session.LocationInView(interaction.View); - } - } + [Export ("dropInteraction:performDrop:")] + public void PerformDrop (UIDropInteraction interaction, IUIDropSession session) + { + if (session.LocalDragSession == null) { + DropPoint = session.LocationInView (interaction.View); + foreach (var dragItem in session.Items) { + LoadImage (dragItem.ItemProvider, DropPoint); + } + } else { + MovePoint = session.LocationInView (interaction.View); + } + } - [Export("dropInteraction:previewForDroppingItem:withDefault:")] - public UITargetedDragPreview GetPreviewForDroppingItem(UIDropInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) - { - if (item.LocalObject == null) - { - return null; - } - else - { - DropPoint = defaultPreview.View.Center; - var target = new UIDragPreviewTarget(View, DropPoint); // HACK: why is this null? - //return defaultPreview.GetRetargetedPreview(target); - return defaultPreview; - } - } + [Export ("dropInteraction:previewForDroppingItem:withDefault:")] + public UITargetedDragPreview GetPreviewForDroppingItem (UIDropInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) + { + if (item.LocalObject == null) { + return null; + } else { + DropPoint = defaultPreview.View.Center; + var target = new UIDragPreviewTarget (View, DropPoint); // HACK: why is this null? + //return defaultPreview.GetRetargetedPreview(target); + return defaultPreview; + } + } - [Export("dropInteraction:item:willAnimateDropWithAnimator:")] - public void WillAnimateDrop(UIDropInteraction interaction, UIDragItem item, IUIDragAnimating animator) - { - animator.AddAnimations(() =>{ - FadeItems(new UIDragItem[] { item }, 0f); - }); + [Export ("dropInteraction:item:willAnimateDropWithAnimator:")] + public void WillAnimateDrop (UIDropInteraction interaction, UIDragItem item, IUIDragAnimating animator) + { + animator.AddAnimations (() => { + FadeItems (new UIDragItem [] { item }, 0f); + }); - var movePoint = MovePoint; //DropPoint - animator.AddCompletion( (err) => { - var index = item.LocalObject as NSNumber; - if (index != null) - { - var i = index.Int32Value; - if (i >= 0) - { - Views[i].Center = movePoint; - Views[i].Alpha = 1f; - } - } - }); - } - } + var movePoint = MovePoint; //DropPoint + animator.AddCompletion ((err) => { + var index = item.LocalObject as NSNumber; + if (index != null) { + var i = index.Int32Value; + if (i >= 0) { + Views [i].Center = movePoint; + Views [i].Alpha = 1f; + } + } + }); + } + } } diff --git a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Paste.cs b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Paste.cs index 2ef139da2..f72a7815b 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Paste.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController+Paste.cs @@ -1,49 +1,41 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using CoreGraphics; using CoreFoundation; -namespace DragBoard -{ - public partial class DragBoardViewController - { +namespace DragBoard { + public partial class DragBoardViewController { /// <summary> /// Sets up the gestures to display and dismiss the menu performing the paste operation on the pin board. /// </summary> - void SetupPasteMenu() + void SetupPasteMenu () { - var longPressGesture = new UILongPressGestureRecognizer((longPress) => - { - if (longPress.State == UIGestureRecognizerState.Began) - { - DropPoint = longPress.LocationInView(View); + var longPressGesture = new UILongPressGestureRecognizer ((longPress) => { + if (longPress.State == UIGestureRecognizerState.Began) { + DropPoint = longPress.LocationInView (View); // Only show the paste menu if we are // not over an image in the pin board. - if (ImageIndex(DropPoint) < 0) - { - View.BecomeFirstResponder(); + if (ImageIndex (DropPoint) < 0) { + View.BecomeFirstResponder (); var menu = UIMenuController.SharedMenuController; - var rect = new CGRect(DropPoint, new CGSize(10, 10)); - menu.SetTargetRect(rect, View); - menu.SetMenuVisible(true, true); + var rect = new CGRect (DropPoint, new CGSize (10, 10)); + menu.SetTargetRect (rect, View); + menu.SetMenuVisible (true, true); } - } - else if (longPress.State == UIGestureRecognizerState.Cancelled) - { - UIMenuController.SharedMenuController.SetMenuVisible(false, true); + } else if (longPress.State == UIGestureRecognizerState.Cancelled) { + UIMenuController.SharedMenuController.SetMenuVisible (false, true); } }); - View.AddGestureRecognizer(longPressGesture); + View.AddGestureRecognizer (longPressGesture); - var tapGesture = new UITapGestureRecognizer((obj) => - { - UIMenuController.SharedMenuController.SetMenuVisible(false, true); + var tapGesture = new UITapGestureRecognizer ((obj) => { + UIMenuController.SharedMenuController.SetMenuVisible (false, true); }); - View.AddGestureRecognizer(tapGesture); + View.AddGestureRecognizer (tapGesture); } - } + } } diff --git a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController.cs b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController.cs index 04a9022cd..dea6f7cd2 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/DragBoardViewController.cs @@ -5,54 +5,50 @@ using CoreGraphics; using CoreFoundation; -namespace DragBoard -{ +namespace DragBoard { /// <summary> /// A view controller that supports pasting and installs drag and drop interactions on its view. /// It also provides helper functions used by paste and drop operations to load and display images in the pin board. - /// </summary> - public partial class DragBoardViewController : UIViewController - { - List<UIImage> Images { get; set; } = new List<UIImage>(); - List<UIView> Views { get; set; } = new List<UIView>(); + /// </summary> + public partial class DragBoardViewController : UIViewController { + List<UIImage> Images { get; set; } = new List<UIImage> (); + List<UIView> Views { get; set; } = new List<UIView> (); // A property that keeps track of the location where the drop operation was performed. - public CGPoint DropPoint { get; set; } = new CGPoint(0, 0); - public CGPoint MovePoint { get; set; } = new CGPoint(0, 0); + public CGPoint DropPoint { get; set; } = new CGPoint (0, 0); + public CGPoint MovePoint { get; set; } = new CGPoint (0, 0); - public DragBoardViewController(IntPtr handle) : base(handle) + public DragBoardViewController (IntPtr handle) : base (handle) { } - - public override void ViewDidLoad() + + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - SetupPasteMenu(); + SetupPasteMenu (); // Set a paste configuration - PasteConfiguration = new UIPasteConfiguration(typeof(UIImage)); + PasteConfiguration = new UIPasteConfiguration (typeof (UIImage)); // Add drag interaction - View.AddInteraction(new UIDragInteraction(this)); + View.AddInteraction (new UIDragInteraction (this)); // Add drag interaction - View.AddInteraction(new UIDropInteraction(this)); + View.AddInteraction (new UIDropInteraction (this)); } - - - //public bool CanPastCanPasteItemProviders (NSItemProvider[] itemProviders) - //{ - // return true; - //} - public void PasteItemProviders(NSItemProvider[] itemProviders) - { - Console.WriteLine(itemProviders); - if (itemProviders != null) - { - foreach (var item in itemProviders) - { - LoadImage(item, DropPoint); - } + + + //public bool CanPastCanPasteItemProviders (NSItemProvider[] itemProviders) + //{ + // return true; + //} + public void PasteItemProviders (NSItemProvider [] itemProviders) + { + Console.WriteLine (itemProviders); + if (itemProviders != null) { + foreach (var item in itemProviders) { + LoadImage (item, DropPoint); + } } } @@ -62,24 +58,20 @@ public void PasteItemProviders(NSItemProvider[] itemProviders) // - Parameters: // - itemProvider: an item provider that can load an image. // - imageView: the image view that will display the loaded image. - public void LoadImage(NSItemProvider itemProvider, CGPoint center) - { - Console.WriteLine("can load : " + itemProvider.CanLoadObject(typeof(UIImage))); - - var progress = itemProvider.LoadObject<UIImage>((droppedImage, err) => - { - var image = droppedImage as UIImage; - DispatchQueue.MainQueue.DispatchAsync(()=>{ - if (image != null) - { - var imageView = NewImageView(image); - imageView.Center = center; - Images.Add(image); - } - else - { - Console.WriteLine("Image is null"); - } + public void LoadImage (NSItemProvider itemProvider, CGPoint center) + { + Console.WriteLine ("can load : " + itemProvider.CanLoadObject (typeof (UIImage))); + + var progress = itemProvider.LoadObject<UIImage> ((droppedImage, err) => { + var image = droppedImage as UIImage; + DispatchQueue.MainQueue.DispatchAsync (() => { + if (image != null) { + var imageView = NewImageView (image); + imageView.Center = center; + Images.Add (image); + } else { + Console.WriteLine ("Image is null"); + } }); }); @@ -92,29 +84,30 @@ public void LoadImage(NSItemProvider itemProvider, CGPoint center) // // - Parameter image: the image to be displayed in the image view. // - Returns: A newly created image view with the given image, resized if necessary. - public UIImageView NewImageView(UIImage image) { + public UIImageView NewImageView (UIImage image) + { - var imageView = new UIImageView() { + var imageView = new UIImageView () { Image = image, ContentMode = UIViewContentMode.ScaleAspectFit, UserInteractionEnabled = true }; var size = image.Size; - var longestSide = (float)Math.Max(size.Width, size.Height); + var longestSide = (float) Math.Max (size.Width, size.Height); var maximumLength = 200f; var scaleFactor = 1f; // If the given image exceeds `maximumLength`, // we resize the image view to match that length // while preserving the original aspect ratio. - if (longestSide > maximumLength ) { + if (longestSide > maximumLength) { scaleFactor = maximumLength / longestSide; } - size = new CGSize((float)Math.Round(size.Width * scaleFactor), (float)Math.Round(size.Height * scaleFactor)); - imageView.Frame = new CGRect(imageView.Frame.Location, size); + size = new CGSize ((float) Math.Round (size.Width * scaleFactor), (float) Math.Round (size.Height * scaleFactor)); + imageView.Frame = new CGRect (imageView.Frame.Location, size); - Views.Add(imageView); - View.AddSubview(imageView); + Views.Add (imageView); + View.AddSubview (imageView); return imageView; } @@ -125,11 +118,12 @@ public UIImageView NewImageView(UIImage image) { // - Parameters: // - items: the list of drag items. // - alpha: the alpha value applied to each drag item. - public void FadeItems(UIDragItem[] items, float alpha) { - foreach(UIDragItem item in items) { + public void FadeItems (UIDragItem [] items, float alpha) + { + foreach (UIDragItem item in items) { var index = item.LocalObject as NSNumber; - if (index !=null) { - Views[index.Int32Value].Alpha = alpha; + if (index != null) { + Views [index.Int32Value].Alpha = alpha; } } } diff --git a/ios11/DragAndDropDragBoard/DragBoard/Main.cs b/ios11/DragAndDropDragBoard/DragBoard/Main.cs index c5aeb14a3..4ea77e57d 100644 --- a/ios11/DragAndDropDragBoard/DragBoard/Main.cs +++ b/ios11/DragAndDropDragBoard/DragBoard/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace DragBoard -{ - public class Application - { +namespace DragBoard { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CGRectExtensions.cs b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CGRectExtensions.cs index cc171a815..59c0be615 100644 --- a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CGRectExtensions.cs +++ b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CGRectExtensions.cs @@ -1,12 +1,11 @@ -using System; +using System; using CoreGraphics; -namespace CoreGraphics -{ - public static class CGRectExtensions - { - public static float Area(this CGRect self) { - return (float)(self.Width * self.Height); +namespace CoreGraphics { + public static class CGRectExtensions { + public static float Area (this CGRect self) + { + return (float) (self.Width * self.Height); } } } diff --git a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CLLocationExtensions.cs b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CLLocationExtensions.cs index 853a06842..bee83bb33 100644 --- a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CLLocationExtensions.cs +++ b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/CLLocationExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -7,29 +7,26 @@ using MapKit; using CoreLocation; -namespace CoreLocation -{ - public static class CLLocationExtensions - { - public static void LoadMapItem(this CLLocation self, MapItemLoadCompletionHandler completionHandler) { - var geocoder = new CLGeocoder(); +namespace CoreLocation { + public static class CLLocationExtensions { + public static void LoadMapItem (this CLLocation self, MapItemLoadCompletionHandler completionHandler) + { + var geocoder = new CLGeocoder (); - geocoder.ReverseGeocodeLocation(self, (placemarks, error) => { - if (placemarks == null) - { - completionHandler(null, error); - return; - } - if (placemarks.Length == 0) - { - completionHandler(null, error); - return; - } - var mkPlacement = new MKPlacemark(placemarks[0].Location.Coordinate); - completionHandler(new MKMapItem(mkPlacement), null); + geocoder.ReverseGeocodeLocation (self, (placemarks, error) => { + if (placemarks == null) { + completionHandler (null, error); + return; + } + if (placemarks.Length == 0) { + completionHandler (null, error); + return; + } + var mkPlacement = new MKPlacemark (placemarks [0].Location.Coordinate); + completionHandler (new MKMapItem (mkPlacement), null); }); } } - public delegate void MapItemLoadCompletionHandler(MKMapItem mapItem, NSError error); + public delegate void MapItemLoadCompletionHandler (MKMapItem mapItem, NSError error); } diff --git a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageExtensions.cs b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageExtensions.cs index ee9e3af14..7f612a1bd 100644 --- a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageExtensions.cs +++ b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -8,50 +8,51 @@ using CoreLocation; using CoreImage; -namespace UIKit -{ - public static class UIImageExtensions - { - public static UIImage[] ImagesForNames(string[] imageNames) { - var images = new List<UIImage>(); +namespace UIKit { + public static class UIImageExtensions { + public static UIImage [] ImagesForNames (string [] imageNames) + { + var images = new List<UIImage> (); - foreach (string name in imageNames) - { - images.Add(UIImage.FromBundle(name)); + foreach (string name in imageNames) { + images.Add (UIImage.FromBundle (name)); } - return images.ToArray(); + return images.ToArray (); } - public static UIImage CroppedImageInRect(this UIImage self, CGRect rect) { + public static UIImage CroppedImageInRect (this UIImage self, CGRect rect) + { var cgImage = self.CGImage; if (cgImage == null) return null; - var croppedImage = cgImage.WithImageInRect(rect); - return UIImage.FromImage(croppedImage, self.CurrentScale, self.Orientation); + var croppedImage = cgImage.WithImageInRect (rect); + return UIImage.FromImage (croppedImage, self.CurrentScale, self.Orientation); } - public static (CGRect rect, string message)[] ComputeQRCodeRectsAndMessages(this UIImage self) { + public static (CGRect rect, string message) [] ComputeQRCodeRectsAndMessages (this UIImage self) + { - var image = new CIImage(self); - var context = new CIContext(new CIContextOptions()); - var detector = CIDetector.CreateQRDetector(context, new CIDetectorOptions()); - var features = detector.FeaturesInImage(image); - var results = new List<(CGRect, string)>(); + var image = new CIImage (self); + var context = new CIContext (new CIContextOptions ()); + var detector = CIDetector.CreateQRDetector (context, new CIDetectorOptions ()); + var features = detector.FeaturesInImage (image); + var results = new List<(CGRect, string)> (); - foreach (CIQRCodeFeature feature in features){ + foreach (CIQRCodeFeature feature in features) { var message = feature.MessageString; if (message != null) { // Flip about the x axis to convert from the coordinate space used by CoreGraphics. var bounds = feature.Bounds; - bounds.Y = self.Size.Height - bounds.GetMaxY(); - results.Add((bounds, message)); + bounds.Y = self.Size.Height - bounds.GetMaxY (); + results.Add ((bounds, message)); } } - return results.ToArray(); - } + return results.ToArray (); + } - public static nfloat AspectRatio(this UIImage self) { + public static nfloat AspectRatio (this UIImage self) + { return self.Size.Width / self.Size.Height; } } diff --git a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageViewExtensions.cs b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageViewExtensions.cs index b9ffe7880..2ad485e68 100644 --- a/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageViewExtensions.cs +++ b/ios11/DragAndDropMastering/DragAndDropCommon/ClassExtensions/UIImageViewExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -8,22 +8,21 @@ using CoreLocation; using CoreImage; -namespace UIKit -{ - public static class UIImageViewExtensions - { +namespace UIKit { + public static class UIImageViewExtensions { /** Converts a rect in image coordinates to a rect in the image view's coordinate space. Does not take clipping into account. */ - public static CGRect ConvertFromImageRect(this UIImageView self, CGRect rect) { + public static CGRect ConvertFromImageRect (this UIImageView self, CGRect rect) + { if (self.Image == null) return CGRect.Empty; var widthScale = self.Bounds.Width / self.Image.Size.Width; var heightScale = self.Bounds.Height / self.Image.Size.Height; - return new CGRect(rect.GetMinX() * widthScale, - rect.GetMinY() * heightScale, + return new CGRect (rect.GetMinX () * widthScale, + rect.GetMinY () * heightScale, rect.Width * widthScale, rect.Height * heightScale ); diff --git a/ios11/DragAndDropMastering/DragSource/AppDelegate.cs b/ios11/DragAndDropMastering/DragSource/AppDelegate.cs index f03d010f9..278b36573 100644 --- a/ios11/DragAndDropMastering/DragSource/AppDelegate.cs +++ b/ios11/DragAndDropMastering/DragSource/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace DragSource -{ +namespace DragSource { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/DragAndDropMastering/DragSource/Classes/QRDetectionResult.cs b/ios11/DragAndDropMastering/DragSource/Classes/QRDetectionResult.cs index d75cf9532..80162f107 100644 --- a/ios11/DragAndDropMastering/DragSource/Classes/QRDetectionResult.cs +++ b/ios11/DragAndDropMastering/DragSource/Classes/QRDetectionResult.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; using Foundation; -namespace DragSource -{ - public class QRDetectionResult : NSObject - { +namespace DragSource { + public class QRDetectionResult : NSObject { #region Computed Properties public UIImage CroppedImage { get; set; } public CGRect RectInOriginalImage { get; set; } = CGRect.Empty; @@ -14,11 +12,11 @@ public class QRDetectionResult : NSObject #endregion #region Constructors - public QRDetectionResult() + public QRDetectionResult () { } - public QRDetectionResult(UIImage croppedImage, CGRect rectInOriginalImage, string message) + public QRDetectionResult (UIImage croppedImage, CGRect rectInOriginalImage, string message) { // Initialize CroppedImage = croppedImage; diff --git a/ios11/DragAndDropMastering/DragSource/CustomViews/ImageContainerView.cs b/ios11/DragAndDropMastering/DragSource/CustomViews/ImageContainerView.cs index a0a8548e5..ca714807d 100644 --- a/ios11/DragAndDropMastering/DragSource/CustomViews/ImageContainerView.cs +++ b/ios11/DragAndDropMastering/DragSource/CustomViews/ImageContainerView.cs @@ -1,44 +1,41 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; -namespace DragSource -{ +namespace DragSource { /** An ImageContainerView wraps an image view, sizing it appropriately within its bounds, with margins applied on all sides. The child image view is centered within this container. */ - public class ImageContainerView : UIView - { + public class ImageContainerView : UIView { #region Computed Properties public float Margin { get; set; } = 10f; public UIImageView ContentView { get; set; } #endregion #region Constructors - public ImageContainerView() + public ImageContainerView () { } - public ImageContainerView(NSCoder coder) : base(coder) + public ImageContainerView (NSCoder coder) : base (coder) { } - public ImageContainerView(UIImageView imageView, float margin) : base(CGRect.Empty) + public ImageContainerView (UIImageView imageView, float margin) : base (CGRect.Empty) { - AddSubview(imageView); + AddSubview (imageView); - if (imageView.Image != null) - { + if (imageView.Image != null) { imageView.TranslatesAutoresizingMaskIntoConstraints = false; - imageView.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Horizontal); - imageView.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Vertical); + imageView.SetContentCompressionResistancePriority ((float) UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Horizontal); + imageView.SetContentCompressionResistancePriority ((float) UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Vertical); - var ivContraints = new NSLayoutConstraint[]{ + var ivContraints = new NSLayoutConstraint []{ imageView.WidthAnchor.ConstraintEqualTo(imageView.HeightAnchor, imageView.Image.AspectRatio()), imageView.WidthAnchor.ConstraintLessThanOrEqualTo(this.WidthAnchor, 1, -margin), imageView.HeightAnchor.ConstraintLessThanOrEqualTo(HeightAnchor, 1, -margin), @@ -46,7 +43,7 @@ public ImageContainerView(UIImageView imageView, float margin) : base(CGRect.Emp imageView.CenterYAnchor.ConstraintEqualTo(CenterYAnchor) }; - NSLayoutConstraint.ActivateConstraints(ivContraints); + NSLayoutConstraint.ActivateConstraints (ivContraints); } } #endregion diff --git a/ios11/DragAndDropMastering/DragSource/CustomViews/LocationImageView.cs b/ios11/DragAndDropMastering/DragSource/CustomViews/LocationImageView.cs index 7ec6e9a0a..bd5e42ede 100644 --- a/ios11/DragAndDropMastering/DragSource/CustomViews/LocationImageView.cs +++ b/ios11/DragAndDropMastering/DragSource/CustomViews/LocationImageView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -6,31 +6,29 @@ using Foundation; using MapKit; -namespace DragSource -{ +namespace DragSource { /** A LocationImageView is a UIImageView that also contains an MKMapItem. Upon initialization with a CLLocation, it requests a map item via reverse geocoding. */ - public class LocationImageView : UIImageView - { + public class LocationImageView : UIImageView { #region Computed Properties public MKMapItem MapItem { get; set; } #endregion #region Constructors - public LocationImageView() + public LocationImageView () { } - public LocationImageView(NSCoder coder) : base(coder) + public LocationImageView (NSCoder coder) : base (coder) { } - public LocationImageView(UIImage image, CLLocation location) : base(image) + public LocationImageView (UIImage image, CLLocation location) : base (image) { - location.LoadMapItem( (mapItem, error) => { + location.LoadMapItem ((mapItem, error) => { if (error == null) { MapItem = mapItem; } diff --git a/ios11/DragAndDropMastering/DragSource/CustomViews/LocationPlatterView.cs b/ios11/DragAndDropMastering/DragSource/CustomViews/LocationPlatterView.cs index e1737f26e..1f75d5d13 100644 --- a/ios11/DragAndDropMastering/DragSource/CustomViews/LocationPlatterView.cs +++ b/ios11/DragAndDropMastering/DragSource/CustomViews/LocationPlatterView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -6,56 +6,53 @@ using Foundation; using MapKit; -namespace DragSource -{ +namespace DragSource { /** A LocationPlatterView is a view of fixed size that is capable of representing a given image and location. */ - public class LocationPlatterView : UIView - { + public class LocationPlatterView : UIView { #region Constructors - public LocationPlatterView() + public LocationPlatterView () { } - public LocationPlatterView(NSCoder coder) : base(coder) + public LocationPlatterView (NSCoder coder) : base (coder) { } - public LocationPlatterView(UIImage image, MKMapItem item) : base(new CGRect(0,0,200,180)) + public LocationPlatterView (UIImage image, MKMapItem item) : base (new CGRect (0, 0, 200, 180)) { - var imageView = new UIImageView(image); + var imageView = new UIImageView (image); - NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[] { + NSLayoutConstraint.ActivateConstraints (new NSLayoutConstraint [] { imageView.WidthAnchor.ConstraintEqualTo(120), imageView.HeightAnchor.ConstraintEqualTo(120) }); imageView.Layer.CornerRadius = 60; imageView.Layer.MasksToBounds = true; - var cityNameLabel = new UILabel() { + var cityNameLabel = new UILabel () { Text = (item.Placemark.Locality == null) ? $"Longitude {item.Placemark.Coordinate.Longitude}" : item.Placemark.Locality, - Font = UIFont.BoldSystemFontOfSize(16), + Font = UIFont.BoldSystemFontOfSize (16), Lines = 1 }; - var countryNameLabel = new UILabel() - { + var countryNameLabel = new UILabel () { Text = (item.Placemark.Country == null) ? $"Latitude {item.Placemark.Coordinate.Latitude}" : item.Placemark.Country, - Font = UIFont.BoldSystemFontOfSize(14), + Font = UIFont.BoldSystemFontOfSize (14), Lines = 1 }; - var container = new UIStackView(new UIView[] {imageView, cityNameLabel, countryNameLabel}){ + var container = new UIStackView (new UIView [] { imageView, cityNameLabel, countryNameLabel }) { Alignment = UIStackViewAlignment.Center, Axis = UILayoutConstraintAxis.Vertical, ClipsToBounds = true, Frame = Bounds }; - AddSubview(container); + AddSubview (container); } #endregion diff --git a/ios11/DragAndDropMastering/DragSource/CustomViews/PhotoStackColumnView.cs b/ios11/DragAndDropMastering/DragSource/CustomViews/PhotoStackColumnView.cs index c3bca2a21..f42e20c73 100644 --- a/ios11/DragAndDropMastering/DragSource/CustomViews/PhotoStackColumnView.cs +++ b/ios11/DragAndDropMastering/DragSource/CustomViews/PhotoStackColumnView.cs @@ -1,12 +1,11 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using CoreLocation; using Foundation; -namespace DragSource -{ +namespace DragSource { /** A PhotoStackColumnView is a view that is able to arrange a given list of views in a vertical stack, applying spacing @@ -14,46 +13,44 @@ and constraints to each view. This wraps and positions a UIStackView. This view's purpose is to help lay out other views in the app. */ - public class PhotoStackColumnView : UIView - { + public class PhotoStackColumnView : UIView { #region Static Variables public static float MinimumMargin = 25f; public static float VerticalSpacing = 10f; - public UIStackView StackView = new UIStackView(); + public UIStackView StackView = new UIStackView (); #endregion #region Constructors - public PhotoStackColumnView() + public PhotoStackColumnView () { } - public PhotoStackColumnView(NSCoder coder) : base(coder) + public PhotoStackColumnView (NSCoder coder) : base (coder) { } - public PhotoStackColumnView(UIView[] views) : base(CGRect.Empty) + public PhotoStackColumnView (UIView [] views) : base (CGRect.Empty) { StackView.Spacing = VerticalSpacing; - AddSubview(StackView); + AddSubview (StackView); var totalMarginAmount = 2f * MinimumMargin; - foreach (UIView view in views) - { - StackView.AddArrangedSubview(view); + foreach (UIView view in views) { + StackView.AddArrangedSubview (view); - view.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Horizontal); - view.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Vertical); + view.SetContentCompressionResistancePriority ((float) UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Horizontal); + view.SetContentCompressionResistancePriority ((float) UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Vertical); - var heightMultiplier = 1.0f / (float)views.Length; + var heightMultiplier = 1.0f / (float) views.Length; var heightConstant = -totalMarginAmount - VerticalSpacing; - var vContraints = new[]{ + var vContraints = new []{ view.WidthAnchor.ConstraintLessThanOrEqualTo(this.WidthAnchor, 1.0f, -totalMarginAmount), view.HeightAnchor.ConstraintLessThanOrEqualTo(this.HeightAnchor, heightMultiplier, heightConstant) }; - NSLayoutConstraint.ActivateConstraints(vContraints); + NSLayoutConstraint.ActivateConstraints (vContraints); } @@ -61,12 +58,12 @@ public PhotoStackColumnView(UIView[] views) : base(CGRect.Empty) StackView.Axis = UILayoutConstraintAxis.Vertical; StackView.TranslatesAutoresizingMaskIntoConstraints = false; - var svContraints = new[]{ + var svContraints = new []{ StackView.CenterXAnchor.ConstraintEqualTo(CenterXAnchor), StackView.CenterYAnchor.ConstraintEqualTo(CenterYAnchor) }; - NSLayoutConstraint.ActivateConstraints(svContraints); + NSLayoutConstraint.ActivateConstraints (svContraints); } #endregion diff --git a/ios11/DragAndDropMastering/DragSource/CustomViews/QRCodeDetectedImageView.cs b/ios11/DragAndDropMastering/DragSource/CustomViews/QRCodeDetectedImageView.cs index 9cf4a5262..af86b8e8e 100644 --- a/ios11/DragAndDropMastering/DragSource/CustomViews/QRCodeDetectedImageView.cs +++ b/ios11/DragAndDropMastering/DragSource/CustomViews/QRCodeDetectedImageView.cs @@ -1,41 +1,39 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; -namespace DragSource -{ +namespace DragSource { /** A QRCodeDetectedImageView represents an image view that contains QR codes. Each QR code is determined by a cropped image of the source image, and the rect indicating where in the source image the QR code appears. */ - public class QRCodeDetectedImageView : UIImageView - { + public class QRCodeDetectedImageView : UIImageView { #region Computed Properties - public List<QRDetectionResult> QRCodes { get; set; } = new List<QRDetectionResult>(); - #endregion + public List<QRDetectionResult> QRCodes { get; set; } = new List<QRDetectionResult> (); + #endregion #region Constructors - public QRCodeDetectedImageView() + public QRCodeDetectedImageView () { } - public QRCodeDetectedImageView(NSCoder coder) : base(coder) + public QRCodeDetectedImageView (NSCoder coder) : base (coder) { } - public QRCodeDetectedImageView(UIImage image) : base(image) + public QRCodeDetectedImageView (UIImage image) : base (image) { if (image != null) { - var codes = image.ComputeQRCodeRectsAndMessages(); - foreach((CGRect rect, string message) in codes){ - var croppedImage = image.CroppedImageInRect(rect); - if (croppedImage !=null) { - var result = new QRDetectionResult(croppedImage, rect, message); - QRCodes.Add(result); + var codes = image.ComputeQRCodeRectsAndMessages (); + foreach ((CGRect rect, string message) in codes) { + var croppedImage = image.CroppedImageInRect (rect); + if (croppedImage != null) { + var result = new QRDetectionResult (croppedImage, rect, message); + QRCodes.Add (result); } } } diff --git a/ios11/DragAndDropMastering/DragSource/CustomViews/StackedPhotosView.cs b/ios11/DragAndDropMastering/DragSource/CustomViews/StackedPhotosView.cs index 068887166..c04c73ca6 100644 --- a/ios11/DragAndDropMastering/DragSource/CustomViews/StackedPhotosView.cs +++ b/ios11/DragAndDropMastering/DragSource/CustomViews/StackedPhotosView.cs @@ -1,65 +1,60 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using CoreLocation; using Foundation; -namespace DragSource -{ +namespace DragSource { /** A StackedPhotosView represents a series of images stacked on top of each other. The last image in the array will appear at the top of the stack. */ - public class StackedPhotosView : UIView - { + public class StackedPhotosView : UIView { #region Static Variables public static float Offset = 10f; #endregion #region Computed Views - public List<UIImageView> ImageViews { get; set; } = new List<UIImageView>(); + public List<UIImageView> ImageViews { get; set; } = new List<UIImageView> (); #endregion #region Constructors - public StackedPhotosView() + public StackedPhotosView () { } - public StackedPhotosView(NSCoder coder) : base(coder) + public StackedPhotosView (NSCoder coder) : base (coder) { } - public StackedPhotosView(UIImage[] images) : base(CGRect.Empty) + public StackedPhotosView (UIImage [] images) : base (CGRect.Empty) { TranslatesAutoresizingMaskIntoConstraints = false; - var totalStackOffset = (float)(images.Length - 1) * Offset; + var totalStackOffset = (float) (images.Length - 1) * Offset; var currentStackOffset = totalStackOffset; BackgroundColor = UIColor.Clear; - foreach (UIImage image in images) - { - var imageView = new UIImageView(image) - { + foreach (UIImage image in images) { + var imageView = new UIImageView (image) { ContentMode = UIViewContentMode.ScaleAspectFill, ClipsToBounds = true }; - if (image == null) - { - imageView.Image = UIImage.FromBundle("Corkboard"); + if (image == null) { + imageView.Image = UIImage.FromBundle ("Corkboard"); } - ImageViews.Add(imageView); - AddSubview(imageView); + ImageViews.Add (imageView); + AddSubview (imageView); imageView.TranslatesAutoresizingMaskIntoConstraints = false; - imageView.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Horizontal); - imageView.SetContentCompressionResistancePriority((float)UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Vertical); + imageView.SetContentCompressionResistancePriority ((float) UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Horizontal); + imageView.SetContentCompressionResistancePriority ((float) UILayoutPriority.DefaultHigh, UILayoutConstraintAxis.Vertical); - var svContraints = new[]{ + var svContraints = new []{ imageView.WidthAnchor.ConstraintEqualTo(imageView.HeightAnchor, image.AspectRatio()), imageView.TopAnchor.ConstraintEqualTo(this.TopAnchor, currentStackOffset), imageView.LeftAnchor.ConstraintEqualTo(this.LeftAnchor, currentStackOffset), @@ -67,7 +62,7 @@ public StackedPhotosView(UIImage[] images) : base(CGRect.Empty) imageView.HeightAnchor.ConstraintLessThanOrEqualTo(this.HeightAnchor, constant:-totalStackOffset) }; - NSLayoutConstraint.ActivateConstraints(svContraints); + NSLayoutConstraint.ActivateConstraints (svContraints); currentStackOffset -= Offset; } diff --git a/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableLocationImageView.cs b/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableLocationImageView.cs index 38d52afce..b253128a4 100644 --- a/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableLocationImageView.cs +++ b/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableLocationImageView.cs @@ -1,69 +1,67 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using CoreLocation; using Foundation; -namespace DragSource -{ +namespace DragSource { /** A DraggableLocationImageView is a LocationImageView that supports dragging. This view vends its map item as well as its image when dragging, and customizes its preview when beginning a drag session. */ - public class DraggableLocationImageView : LocationImageView, IUIDragInteractionDelegate - { + public class DraggableLocationImageView : LocationImageView, IUIDragInteractionDelegate { #region Constructors - public DraggableLocationImageView() + public DraggableLocationImageView () { } - public DraggableLocationImageView(NSCoder coder) : base(coder) + public DraggableLocationImageView (NSCoder coder) : base (coder) { } - public DraggableLocationImageView(UIImage image, CLLocation location) : base(image, location) + public DraggableLocationImageView (UIImage image, CLLocation location) : base (image, location) { // Initialize UserInteractionEnabled = true; - AddInteraction(new UIDragInteraction(this)); + AddInteraction (new UIDragInteraction (this)); } #endregion #region Private Methods - private UIDragPreview DragPreviewForItem() { + private UIDragPreview DragPreviewForItem () + { - if (Image == null || MapItem == null) return new UIDragPreview(this); - var previewView = new LocationPlatterView(Image, MapItem); - var inflatedBounds = previewView.Bounds.Inset(-20, -20); - var parameters = new UIDragPreviewParameters() - { - VisiblePath = UIBezierPath.FromRoundedRect(inflatedBounds, 20f) + if (Image == null || MapItem == null) return new UIDragPreview (this); + var previewView = new LocationPlatterView (Image, MapItem); + var inflatedBounds = previewView.Bounds.Inset (-20, -20); + var parameters = new UIDragPreviewParameters () { + VisiblePath = UIBezierPath.FromRoundedRect (inflatedBounds, 20f) }; - return new UIDragPreview(previewView, parameters); + return new UIDragPreview (previewView, parameters); } #endregion #region UIDragInteractionDelegate - public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) + public UIDragItem [] GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) { - var results = new List<UIDragItem>(); - if (MapItem == null) return results.ToArray(); + var results = new List<UIDragItem> (); + if (MapItem == null) return results.ToArray (); - var itemProvider = new NSItemProvider(MapItem); - itemProvider.RegisterObject(Image, NSItemProviderRepresentationVisibility.All); - results.Add(new UIDragItem(itemProvider)); + var itemProvider = new NSItemProvider (MapItem); + itemProvider.RegisterObject (Image, NSItemProviderRepresentationVisibility.All); + results.Add (new UIDragItem (itemProvider)); - return results.ToArray(); + return results.ToArray (); } - [Export("dragInteraction:sessionWillBegin:")] - public void SessionWillBegin(UIDragInteraction interaction, IUIDragSession session) + [Export ("dragInteraction:sessionWillBegin:")] + public void SessionWillBegin (UIDragInteraction interaction, IUIDragSession session) { - session.Items[0].PreviewProvider = DragPreviewForItem; + session.Items [0].PreviewProvider = DragPreviewForItem; } #endregion diff --git a/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableQRCodeImageView.cs b/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableQRCodeImageView.cs index 2cb76a2a9..d78f347b2 100644 --- a/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableQRCodeImageView.cs +++ b/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableQRCodeImageView.cs @@ -1,100 +1,98 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using CoreLocation; using Foundation; -namespace DragSource -{ +namespace DragSource { /** The DraggableQRCodeImageView is a subclass of QRCodeDetectedImageView supports for dragging cropped images representing the QR codes that appear in the image view. */ - public class DraggableQRCodeImageView : QRCodeDetectedImageView, IUIDragInteractionDelegate - { + public class DraggableQRCodeImageView : QRCodeDetectedImageView, IUIDragInteractionDelegate { #region Constructors - public DraggableQRCodeImageView() + public DraggableQRCodeImageView () { } - public DraggableQRCodeImageView(NSCoder coder) : base(coder) + public DraggableQRCodeImageView (NSCoder coder) : base (coder) { } - public DraggableQRCodeImageView(UIImage image) : base(image) + public DraggableQRCodeImageView (UIImage image) : base (image) { // Initialize UserInteractionEnabled = true; - AddInteraction(new UIDragInteraction(this)); + AddInteraction (new UIDragInteraction (this)); } #endregion #region Private Methods - private UITargetedDragPreview DragPreviewForItem(UIDragItem item) { + private UITargetedDragPreview DragPreviewForItem (UIDragItem item) + { var qrCode = item.LocalObject as QRDetectionResult; - if (qrCode == null) return new UITargetedDragPreview(this); - var previewView = new UIImageView(qrCode.CroppedImage); - previewView.Frame = ConvertRectToView(this.ConvertFromImageRect(qrCode.RectInOriginalImage), Window); + if (qrCode == null) return new UITargetedDragPreview (this); + var previewView = new UIImageView (qrCode.CroppedImage); + previewView.Frame = ConvertRectToView (this.ConvertFromImageRect (qrCode.RectInOriginalImage), Window); - var target = new UIDragPreviewTarget(Window, previewView.Center); - var parameters = new UIDragPreviewParameters() - { - VisiblePath = UIBezierPath.FromRoundedRect(previewView.Bounds, 20f) + var target = new UIDragPreviewTarget (Window, previewView.Center); + var parameters = new UIDragPreviewParameters () { + VisiblePath = UIBezierPath.FromRoundedRect (previewView.Bounds, 20f) }; - return new UITargetedDragPreview(previewView, parameters, target); + return new UITargetedDragPreview (previewView, parameters, target); } #endregion #region UIDragInteractionDelegate - UIDragItem[] IUIDragInteractionDelegate.GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) + UIDragItem [] IUIDragInteractionDelegate.GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) { - var results = new List<UIDragItem>(); + var results = new List<UIDragItem> (); - foreach(QRDetectionResult qrCode in QRCodes) { - var itemProvider = new NSItemProvider((NSString)qrCode.Message); - itemProvider.RegisterObject(qrCode.CroppedImage, NSItemProviderRepresentationVisibility.All); - var item = new UIDragItem(itemProvider) { + foreach (QRDetectionResult qrCode in QRCodes) { + var itemProvider = new NSItemProvider ((NSString) qrCode.Message); + itemProvider.RegisterObject (qrCode.CroppedImage, NSItemProviderRepresentationVisibility.All); + var item = new UIDragItem (itemProvider) { LocalObject = qrCode }; - results.Add(item); + results.Add (item); } - return results.ToArray(); + return results.ToArray (); } - [Export("dragInteraction:previewForLiftingItem:session:")] - public UITargetedDragPreview GetPreviewForLiftingItem(UIDragInteraction interaction, UIDragItem item, IUIDragSession session) + [Export ("dragInteraction:previewForLiftingItem:session:")] + public UITargetedDragPreview GetPreviewForLiftingItem (UIDragInteraction interaction, UIDragItem item, IUIDragSession session) { - return DragPreviewForItem(item); + return DragPreviewForItem (item); } - [Export("dragInteraction:previewForCancellingItem:withDefault:")] - public UITargetedDragPreview GetPreviewForCancellingItem(UIDragInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) + [Export ("dragInteraction:previewForCancellingItem:withDefault:")] + public UITargetedDragPreview GetPreviewForCancellingItem (UIDragInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) { - return DragPreviewForItem(item); + return DragPreviewForItem (item); } - [Export("dragInteraction:willAnimateLiftWithAnimator:session:")] - public void WillAnimateLift(UIDragInteraction interaction, IUIDragAnimating animator, IUIDragSession session) + [Export ("dragInteraction:willAnimateLiftWithAnimator:session:")] + public void WillAnimateLift (UIDragInteraction interaction, IUIDragAnimating animator, IUIDragSession session) { - animator.AddAnimations(()=>{ + animator.AddAnimations (() => { Alpha = 0.5f; }); } - [Export("dragInteraction:item:willAnimateCancelWithAnimator:")] - public void WillAnimateCancel(UIDragInteraction interaction, UIDragItem item, IUIDragAnimating animator) + [Export ("dragInteraction:item:willAnimateCancelWithAnimator:")] + public void WillAnimateCancel (UIDragInteraction interaction, UIDragItem item, IUIDragAnimating animator) { - animator.AddAnimations(() => { + animator.AddAnimations (() => { Alpha = 1f; }); } - [Export("dragInteraction:session:didEndWithOperation:")] - public void SessionDidEnd(UIDragInteraction interaction, IUIDragSession session, UIDropOperation operation) + [Export ("dragInteraction:session:didEndWithOperation:")] + public void SessionDidEnd (UIDragInteraction interaction, IUIDragSession session, UIDropOperation operation) { Alpha = 1f; } diff --git a/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableStackedPhotosView.cs b/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableStackedPhotosView.cs index 3765ecc66..f243d8321 100644 --- a/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableStackedPhotosView.cs +++ b/ios11/DragAndDropMastering/DragSource/DragAndDrop/DraggableStackedPhotosView.cs @@ -1,70 +1,68 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using CoreLocation; using Foundation; -namespace DragSource -{ +namespace DragSource { /** A DraggableStackedPhotosView is a StackedPhotosView that supports dragging. When dragging, this view vends a list of drag items constructed from each image. */ - public class DraggableStackedPhotosView : StackedPhotosView, IUIDragInteractionDelegate - { + public class DraggableStackedPhotosView : StackedPhotosView, IUIDragInteractionDelegate { #region Computed Properties - public UIDragItem[] DragItems { + public UIDragItem [] DragItems { get { - var results = new List<UIDragItem>(); - foreach(UIImageView imageView in ImageViews) { - var itemProvider = new NSItemProvider(imageView.Image); - var item = new UIDragItem(itemProvider) { + var results = new List<UIDragItem> (); + foreach (UIImageView imageView in ImageViews) { + var itemProvider = new NSItemProvider (imageView.Image); + var item = new UIDragItem (itemProvider) { LocalObject = imageView }; - results.Add(item); + results.Add (item); } - return results.ToArray(); + return results.ToArray (); } } #endregion #region Constructors - public DraggableStackedPhotosView() + public DraggableStackedPhotosView () { } - public DraggableStackedPhotosView(NSCoder coder) : base(coder) + public DraggableStackedPhotosView (NSCoder coder) : base (coder) { } - public DraggableStackedPhotosView(UIImage[] images) : base(images) + public DraggableStackedPhotosView (UIImage [] images) : base (images) { // Initialize UserInteractionEnabled = true; - AddInteraction(new UIDragInteraction(this)); + AddInteraction (new UIDragInteraction (this)); } #endregion #region UIDragInteractionDelegate - public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) + public UIDragItem [] GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) { return DragItems; } - [Export("dragInteraction:itemsForAddingToSession:withTouchAtPoint:")] - public UIDragItem[] GetItemsForAddingToSession(UIDragInteraction interaction, IUIDragSession session, CGPoint point) + [Export ("dragInteraction:itemsForAddingToSession:withTouchAtPoint:")] + public UIDragItem [] GetItemsForAddingToSession (UIDragInteraction interaction, IUIDragSession session, CGPoint point) { return DragItems; } - [Export("dragInteraction:previewForLiftingItem:session:")] - public UITargetedDragPreview GetPreviewForLiftingItem(UIDragInteraction interaction, UIDragItem item, IUIDragSession session) + [Export ("dragInteraction:previewForLiftingItem:session:")] + public UITargetedDragPreview GetPreviewForLiftingItem (UIDragInteraction interaction, UIDragItem item, IUIDragSession session) { var imageView = item.LocalObject as UIImageView; if (imageView == null) return null; - return new UITargetedDragPreview(imageView); + return new UITargetedDragPreview (imageView); } #endregion } diff --git a/ios11/DragAndDropMastering/DragSource/DragAndDrop/SlowDraggableImageView.cs b/ios11/DragAndDropMastering/DragSource/DragAndDrop/SlowDraggableImageView.cs index 4d7eb23e6..4a62f9831 100644 --- a/ios11/DragAndDropMastering/DragSource/DragAndDrop/SlowDraggableImageView.cs +++ b/ios11/DragAndDropMastering/DragSource/DragAndDrop/SlowDraggableImageView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -7,8 +7,7 @@ using MobileCoreServices; using CoreFoundation; -namespace DragSource -{ +namespace DragSource { /** A SlowDraggableImageView is an image view that supports dragging and vends its image when dragged. The item @@ -18,57 +17,55 @@ time to complete. Drag items coming from this view can be dropped into the drop destination app to demonstrate custom progress UI. */ - public class SlowDraggableImageView : UIImageView, IUIDragInteractionDelegate - { + public class SlowDraggableImageView : UIImageView, IUIDragInteractionDelegate { #region Computed Properties public float Delay { get; set; } = 0f; - public UIDragItem[] DragItems - { - get - { - var results = new List<UIDragItem>(); + public UIDragItem [] DragItems { + get { + var results = new List<UIDragItem> (); - var itemProvider = new NSItemProvider(); - itemProvider.RegisterDataRepresentation(UTType.PNG, NSItemProviderRepresentationVisibility.All, SlowImageTransfer); - results.Add(new UIDragItem(itemProvider)); + var itemProvider = new NSItemProvider (); + itemProvider.RegisterDataRepresentation (UTType.PNG, NSItemProviderRepresentationVisibility.All, SlowImageTransfer); + results.Add (new UIDragItem (itemProvider)); - return results.ToArray(); + return results.ToArray (); } } #endregion #region Constructors - public SlowDraggableImageView() + public SlowDraggableImageView () { } - public SlowDraggableImageView(NSCoder coder) : base(coder) + public SlowDraggableImageView (NSCoder coder) : base (coder) { } - public SlowDraggableImageView(UIImage image, float delay) : base(image) + public SlowDraggableImageView (UIImage image, float delay) : base (image) { // Initialize Delay = delay; UserInteractionEnabled = true; - AddInteraction(new UIDragInteraction(this)); + AddInteraction (new UIDragInteraction (this)); } #endregion #region Private Methods - private NSProgress SlowImageTransfer(ItemProviderDataCompletionHandler completionHandler){ + private NSProgress SlowImageTransfer (ItemProviderDataCompletionHandler completionHandler) + { - var progress = NSProgress.FromTotalUnitCount(100); - var loadStartDate = new NSDate(); + var progress = NSProgress.FromTotalUnitCount (100); + var loadStartDate = new NSDate (); - DispatchQueue.MainQueue.DispatchAsync(()=>{ - progress.BecomeCurrent(100); - NSTimer.CreateScheduledTimer(0.033f, true, (timer) => { - progress.CompletedUnitCount = CompletedUnitCount(loadStartDate); + DispatchQueue.MainQueue.DispatchAsync (() => { + progress.BecomeCurrent (100); + NSTimer.CreateScheduledTimer (0.033f, true, (timer) => { + progress.CompletedUnitCount = CompletedUnitCount (loadStartDate); if (progress.CompletedUnitCount >= 100) { - completionHandler(Image.AsPNG(), null); - timer.Invalidate(); + completionHandler (Image.AsPNG (), null); + timer.Invalidate (); } }); }); @@ -76,19 +73,20 @@ private NSProgress SlowImageTransfer(ItemProviderDataCompletionHandler completio return progress; } - private Int64 CompletedUnitCount(NSDate loadStartDate) { - return (long)Math.Round(Math.Max(0, Math.Min(1, NSDate.FromTimeIntervalSinceReferenceDate(loadStartDate.SecondsSinceReferenceDate).SecondsSinceReferenceDate / Delay)) * 100); + private Int64 CompletedUnitCount (NSDate loadStartDate) + { + return (long) Math.Round (Math.Max (0, Math.Min (1, NSDate.FromTimeIntervalSinceReferenceDate (loadStartDate.SecondsSinceReferenceDate).SecondsSinceReferenceDate / Delay)) * 100); } #endregion #region UIDragInteractionDelegate - public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) + public UIDragItem [] GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) { return DragItems; } - [Export("dragInteraction:itemsForAddingToSession:withTouchAtPoint:")] - public UIDragItem[] GetItemsForAddingToSession(UIDragInteraction interaction, IUIDragSession session, CGPoint point) + [Export ("dragInteraction:itemsForAddingToSession:withTouchAtPoint:")] + public UIDragItem [] GetItemsForAddingToSession (UIDragInteraction interaction, IUIDragSession session, CGPoint point) { return DragItems; } diff --git a/ios11/DragAndDropMastering/DragSource/Main.cs b/ios11/DragAndDropMastering/DragSource/Main.cs index fb9991087..e226c93db 100644 --- a/ios11/DragAndDropMastering/DragSource/Main.cs +++ b/ios11/DragAndDropMastering/DragSource/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace DragSource -{ - public class Application - { +namespace DragSource { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/DragAndDropMastering/DragSource/ViewController.cs b/ios11/DragAndDropMastering/DragSource/ViewController.cs index 1e4922823..515fb3a39 100644 --- a/ios11/DragAndDropMastering/DragSource/ViewController.cs +++ b/ios11/DragAndDropMastering/DragSource/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using MapKit; @@ -8,132 +8,126 @@ using MobileCoreServices; using CoreFoundation; -namespace DragSource -{ - public partial class ViewController : UIViewController - { +namespace DragSource { + public partial class ViewController : UIViewController { #region Computed Properties - public UIView ContentView { get; set; } = new UIView(); - public UIScrollView ScrollView { get; set; } = new UIScrollView(); - public List<UIView> ExampleViews { get; set; } = new List<UIView>(); + public UIView ContentView { get; set; } = new UIView (); + public UIScrollView ScrollView { get; set; } = new UIScrollView (); + public List<UIView> ExampleViews { get; set; } = new List<UIView> (); - public UIImage[] ImageStack1 { - get { return UIImageExtensions.ImagesForNames(new string[] {"Corkboard", "Food1"}); } + public UIImage [] ImageStack1 { + get { return UIImageExtensions.ImagesForNames (new string [] { "Corkboard", "Food1" }); } } - public UIImage[] ImageStack2 - { - get { return UIImageExtensions.ImagesForNames(new string[] {"Fish", "Flowers1", "Flowers2"}); } + public UIImage [] ImageStack2 { + get { return UIImageExtensions.ImagesForNames (new string [] { "Fish", "Flowers1", "Flowers2" }); } } - public UIImage[] ImageStack3 - { - get { return UIImageExtensions.ImagesForNames(new string[] {"Flowers4", "Flowers5"}); } + public UIImage [] ImageStack3 { + get { return UIImageExtensions.ImagesForNames (new string [] { "Flowers4", "Flowers5" }); } } - public UIImage[] ImageStack4 - { - get { return UIImageExtensions.ImagesForNames(new string[] {"Cooking", "Food4", "Food5"}); } + public UIImage [] ImageStack4 { + get { return UIImageExtensions.ImagesForNames (new string [] { "Cooking", "Food4", "Food5" }); } } - public UIImage[] ImageStack5 - { - get { return UIImageExtensions.ImagesForNames(new string[] {"Pond", "Rainbow", "Sand", "Sunset"}); } + public UIImage [] ImageStack5 { + get { return UIImageExtensions.ImagesForNames (new string [] { "Pond", "Rainbow", "Sand", "Sunset" }); } } - public ImageContainerView[] SlowImageViews { + public ImageContainerView [] SlowImageViews { get { - var results = new List<ImageContainerView>(); + var results = new List<ImageContainerView> (); - foreach(UIImage image in ImageStack5){ - results.Add(new ImageContainerView(new SlowDraggableImageView(image, 10f), 25)); + foreach (UIImage image in ImageStack5) { + results.Add (new ImageContainerView (new SlowDraggableImageView (image, 10f), 25)); } - return results.ToArray(); + return results.ToArray (); } } - public DraggableStackedPhotosView[] StackedPhotoViews { + public DraggableStackedPhotosView [] StackedPhotoViews { get { - var results = new List<DraggableStackedPhotosView>(); + var results = new List<DraggableStackedPhotosView> (); - results.Add(new DraggableStackedPhotosView(ImageStack1)); - results.Add(new DraggableStackedPhotosView(ImageStack2)); - results.Add(new DraggableStackedPhotosView(ImageStack3)); - results.Add(new DraggableStackedPhotosView(ImageStack4)); + results.Add (new DraggableStackedPhotosView (ImageStack1)); + results.Add (new DraggableStackedPhotosView (ImageStack2)); + results.Add (new DraggableStackedPhotosView (ImageStack3)); + results.Add (new DraggableStackedPhotosView (ImageStack4)); - return results.ToArray(); + return results.ToArray (); } } public List<(UIView view, string description)> ExamplesAndDescriptions { get { - var results = new List<(UIView, string)>(); + var results = new List<(UIView, string)> (); + + results.Add ((new PhotoStackColumnView (StackedPhotoViews), "DraggableStackedPhotosView")); + results.Add ((new ImageContainerView (new DraggableQRCodeImageView (UIImage.FromBundle ("QRCode")), 100), "DraggableQRCodeImageView")); + results.Add ((new ImageContainerView (new DraggableLocationImageView (UIImage.FromBundle ("GGBridge"), new CLLocation (37.8199, -122.4783)), 100), "DraggableLocationImageView")); + results.Add ((new PhotoStackColumnView (SlowImageViews), "SlowDraggableImageView")); - results.Add((new PhotoStackColumnView(StackedPhotoViews), "DraggableStackedPhotosView")); - results.Add((new ImageContainerView(new DraggableQRCodeImageView(UIImage.FromBundle("QRCode")), 100), "DraggableQRCodeImageView")); - results.Add((new ImageContainerView(new DraggableLocationImageView(UIImage.FromBundle("GGBridge"), new CLLocation(37.8199, -122.4783)), 100), "DraggableLocationImageView")); - results.Add((new PhotoStackColumnView(SlowImageViews), "SlowDraggableImageView")); - return results; } } #endregion #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - ScrollView.AddSubview(ContentView); - View.AddSubview(ScrollView); - Console.WriteLine("View Loaded"); + ScrollView.AddSubview (ContentView); + View.AddSubview (ScrollView); + Console.WriteLine ("View Loaded"); - foreach((UIView view, string description) in ExamplesAndDescriptions) { + foreach ((UIView view, string description) in ExamplesAndDescriptions) { view.Layer.BorderColor = UIColor.LightGray.CGColor; view.Layer.BorderWidth = 1; - Console.WriteLine("Processing: {0}", description); + Console.WriteLine ("Processing: {0}", description); - var label = new UILabel() { + var label = new UILabel () { Text = description, - Font = UIFont.BoldSystemFontOfSize(28), + Font = UIFont.BoldSystemFontOfSize (28), //TextColor = UIColor.White, TranslatesAutoresizingMaskIntoConstraints = false, //ShadowColor = UIColor.Black, //ShadowOffset = new CGSize(0.5f, 0.5f) }; - view.AddSubview(label); - NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{ + view.AddSubview (label); + NSLayoutConstraint.ActivateConstraints (new NSLayoutConstraint []{ label.CenterXAnchor.ConstraintEqualTo(view.CenterXAnchor), label.CenterYAnchor.ConstraintEqualTo(view.BottomAnchor, constant:-20) }); - ContentView.AddSubview(view); - ExampleViews.Add(view); + ContentView.AddSubview (view); + ExampleViews.Add (view); } ScrollView.PagingEnabled = true; } - public override void ViewWillLayoutSubviews() + public override void ViewWillLayoutSubviews () { - base.ViewWillLayoutSubviews(); + base.ViewWillLayoutSubviews (); //Background.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height); var size = View.Bounds.Size; - for (int n = 0; n < ExampleViews.Count; ++n){ - ExampleViews[n].Frame = new CGRect(new CGPoint(0, n * size.Height), size); + for (int n = 0; n < ExampleViews.Count; ++n) { + ExampleViews [n].Frame = new CGRect (new CGPoint (0, n * size.Height), size); } - ContentView.Frame = new CGRect(0, 0, size.Width, ExampleViews.Count * size.Height); - ScrollView.Frame = new CGRect(0, 0, size.Width, size.Height); + ContentView.Frame = new CGRect (0, 0, size.Width, ExampleViews.Count * size.Height); + ScrollView.Frame = new CGRect (0, 0, size.Width, size.Height); ScrollView.ContentSize = ContentView.Bounds.Size; } #endregion diff --git a/ios11/DragAndDropMastering/DropDestination/AppDelegate.cs b/ios11/DragAndDropMastering/DropDestination/AppDelegate.cs index a5c677a87..b480745c9 100644 --- a/ios11/DragAndDropMastering/DropDestination/AppDelegate.cs +++ b/ios11/DragAndDropMastering/DropDestination/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace DropDestination -{ +namespace DropDestination { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/DragAndDropMastering/DropDestination/CustomViewControllers/ImageGridViewController.cs b/ios11/DragAndDropMastering/DropDestination/CustomViewControllers/ImageGridViewController.cs index 1229f45eb..cb2932631 100644 --- a/ios11/DragAndDropMastering/DropDestination/CustomViewControllers/ImageGridViewController.cs +++ b/ios11/DragAndDropMastering/DropDestination/CustomViewControllers/ImageGridViewController.cs @@ -1,36 +1,34 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; using CoreAnimation; -namespace DropDestination -{ +namespace DropDestination { /** Wraps a GridView of a given fixed cell size with a scroll view. May be subclassed for additional drop interaction functionality -- see DroppableImageGridViewController. */ - public class ImageGridViewController : UIViewController - { + public class ImageGridViewController : UIViewController { #region Computed Properties public CGSize FixedCellSize { get; set; } = CGSize.Empty; - public UIScrollView ScrollView { get; set; } = new UIScrollView(); + public UIScrollView ScrollView { get; set; } = new UIScrollView (); public GridView ContainerView { get; set; } #endregion #region Constructors - public ImageGridViewController() + public ImageGridViewController () { } - public ImageGridViewController(NSCoder coder) : base(coder) + public ImageGridViewController (NSCoder coder) : base (coder) { } - public ImageGridViewController(CGSize cellSize) + public ImageGridViewController (CGSize cellSize) { // Initialize FixedCellSize = cellSize; @@ -39,59 +37,62 @@ public ImageGridViewController(CGSize cellSize) #endregion #region Public Methods - public void AddImageNamed(string name) { - var image = UIImage.FromBundle(name); + public void AddImageNamed (string name) + { + var image = UIImage.FromBundle (name); if (image == null) return; - var view = NextView(); + var view = NextView (); view.Image = image; } - public DraggableImageView NextView() { - var newView = new DraggableImageView(){ + public DraggableImageView NextView () + { + var newView = new DraggableImageView () { ClipsToBounds = true, ContentMode = UIViewContentMode.ScaleAspectFill }; - ContainerView.AddArrangedView(newView); - ScrollView.SetNeedsLayout(); + ContainerView.AddArrangedView (newView); + ScrollView.SetNeedsLayout (); return newView; } - public void RemoveViewsInSet(List<UIView> viewsToRemove) { - var indicesToRemove = new NSMutableIndexSet(); + public void RemoveViewsInSet (List<UIView> viewsToRemove) + { + var indicesToRemove = new NSMutableIndexSet (); - foreach(UIView view in viewsToRemove) { - var index = ContainerView.IndexForView(view); - if (index > -1) indicesToRemove.Add((nuint)index); + foreach (UIView view in viewsToRemove) { + var index = ContainerView.IndexForView (view); + if (index > -1) indicesToRemove.Add ((nuint) index); } if (indicesToRemove.Count == 0) return; - ContainerView.RemoveArrangedViewsAtIndexes(indicesToRemove); - ScrollView.SetNeedsLayout(); + ContainerView.RemoveArrangedViewsAtIndexes (indicesToRemove); + ScrollView.SetNeedsLayout (); } #endregion #region Override Methods - public override void LoadView() + public override void LoadView () { - base.LoadView(); + base.LoadView (); - ScrollView.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height); - View.AddSubview(ScrollView); + ScrollView.Frame = new CGRect (0, 0, View.Frame.Width, View.Frame.Height); + View.AddSubview (ScrollView); - ContainerView = new GridView(FixedCellSize, new CGRect(0, 0, ScrollView.Frame.Width, ScrollView.Frame.Height)); - ScrollView.AddSubview(ContainerView); + ContainerView = new GridView (FixedCellSize, new CGRect (0, 0, ScrollView.Frame.Width, ScrollView.Frame.Height)); + ScrollView.AddSubview (ContainerView); ContainerView.GridSizeChanged += (size) => { ScrollView.ContentSize = size; }; } - public override void ViewDidLayoutSubviews() + public override void ViewDidLayoutSubviews () { - base.ViewDidLayoutSubviews(); + base.ViewDidLayoutSubviews (); - ScrollView.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height); + ScrollView.Frame = new CGRect (0, 0, View.Frame.Width, View.Frame.Height); ContainerView.Width = View.Frame.Width; } #endregion diff --git a/ios11/DragAndDropMastering/DropDestination/CustomViews/DeleteView.cs b/ios11/DragAndDropMastering/DropDestination/CustomViews/DeleteView.cs index 7ac943ad9..669cd98ab 100644 --- a/ios11/DragAndDropMastering/DropDestination/CustomViews/DeleteView.cs +++ b/ios11/DragAndDropMastering/DropDestination/CustomViews/DeleteView.cs @@ -1,12 +1,11 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; using CoreAnimation; -namespace DropDestination -{ +namespace DropDestination { /** The DeleteView handles UI for showing a deletion area. Subclasses are responsible for notifying the delegate @@ -14,41 +13,40 @@ of deletion. Refer to DroppableDeleteView for an example. */ - public class DeleteView : UIView - { + public class DeleteView : UIView { #region Computed Properties public UIImageView IconView { get; set; } #endregion #region Constructors - public DeleteView() + public DeleteView () { } - public DeleteView(NSCoder coder) : base(coder) + public DeleteView (NSCoder coder) : base (coder) { } - public DeleteView(string labelText) + public DeleteView (string labelText) { // Initialize - var topDivider = new UIView(){ + var topDivider = new UIView () { TranslatesAutoresizingMaskIntoConstraints = false, BackgroundColor = UIColor.DarkGray }; - AddSubview(topDivider); - NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{ + AddSubview (topDivider); + NSLayoutConstraint.ActivateConstraints (new NSLayoutConstraint []{ topDivider.TopAnchor.ConstraintEqualTo(TopAnchor, 1), topDivider.WidthAnchor.ConstraintEqualTo(WidthAnchor), topDivider.HeightAnchor.ConstraintEqualTo(1) }); - var trashIcon = new UIImageView(UIImage.FromBundle("Trash")){ + var trashIcon = new UIImageView (UIImage.FromBundle ("Trash")) { TranslatesAutoresizingMaskIntoConstraints = false, ClipsToBounds = true }; - AddSubview(trashIcon); - NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{ + AddSubview (trashIcon); + NSLayoutConstraint.ActivateConstraints (new NSLayoutConstraint []{ trashIcon.WidthAnchor.ConstraintEqualTo(64), trashIcon.HeightAnchor.ConstraintEqualTo(64), trashIcon.CenterYAnchor.ConstraintEqualTo(CenterYAnchor), @@ -58,16 +56,16 @@ public DeleteView(string labelText) trashIcon.Layer.CornerRadius = 32; IconView = trashIcon; - var labelView = new UILabel() { + var labelView = new UILabel () { Text = labelText, - Font = UIFont.SystemFontOfSize(24), + Font = UIFont.SystemFontOfSize (24), TextColor = UIColor.DarkGray, AllowsDefaultTighteningForTruncation = true, Lines = 1, TranslatesAutoresizingMaskIntoConstraints = false }; - AddSubview(labelView); - NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{ + AddSubview (labelView); + NSLayoutConstraint.ActivateConstraints (new NSLayoutConstraint []{ labelView.CenterYAnchor.ConstraintEqualTo(CenterYAnchor), labelView.LeftAnchor.ConstraintEqualTo(trashIcon.RightAnchor, 12) }); @@ -78,12 +76,13 @@ public DeleteView(string labelText) #endregion #region Events - public delegate void DidDeleteViewsDelegate(List<UIView> views); + public delegate void DidDeleteViewsDelegate (List<UIView> views); public event DidDeleteViewsDelegate DidDeleteViews; - internal void RaiseDidDeleteViews(List<UIView> views) { + internal void RaiseDidDeleteViews (List<UIView> views) + { // Inform caller - if (DidDeleteViews != null) DidDeleteViews(views); + if (DidDeleteViews != null) DidDeleteViews (views); } #endregion } diff --git a/ios11/DragAndDropMastering/DropDestination/CustomViews/GridView.cs b/ios11/DragAndDropMastering/DropDestination/CustomViews/GridView.cs index bebb23412..b944f2380 100644 --- a/ios11/DragAndDropMastering/DropDestination/CustomViews/GridView.cs +++ b/ios11/DragAndDropMastering/DropDestination/CustomViews/GridView.cs @@ -1,12 +1,11 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; using CoreAnimation; -namespace DropDestination -{ +namespace DropDestination { /** A GridView is responsible for laying out UIViews of a given fixed size in an evenly spaced grid. @@ -16,60 +15,52 @@ to demonstrate that UICollectionView-like drag and drop support can also be supported in any arbitrary type of UIView using drag and drop interactions. */ - public class GridView : UIView - { + public class GridView : UIView { #region Computed Properties public float GridViewMargin { get; set; } = 18f; public CGSize FixedCellSize { get; set; } = CGSize.Empty; - public List<UIView> ArrangedViews { get; set; } = new List<UIView>(); + public List<UIView> ArrangedViews { get; set; } = new List<UIView> (); - public nfloat Width - { + public nfloat Width { get { return Frame.Width; } - set { - Frame = new CGRect(Frame.X, Frame.Y, value, Height); - RaiseGridSizeChanged(); + set { + Frame = new CGRect (Frame.X, Frame.Y, value, Height); + RaiseGridSizeChanged (); } } - public nfloat Height - { + public nfloat Height { get { return (FixedCellSize.Height + (GridViewMargin * 2f)) * NumberOfRows; } } - public int NumberOfColumns - { - get { return (int)(Width / (FixedCellSize.Width + (GridViewMargin * 2f))); } + public int NumberOfColumns { + get { return (int) (Width / (FixedCellSize.Width + (GridViewMargin * 2f))); } } - public int NumberOfRows - { - get - { + public int NumberOfRows { + get { if (NumberOfColumns < 1 || ArrangedViews.Count < 1) return 0; return (ArrangedViews.Count / NumberOfColumns) + 1; } } - public override CGSize IntrinsicContentSize - { - get - { - return new CGSize(Width, Height); + public override CGSize IntrinsicContentSize { + get { + return new CGSize (Width, Height); } } #endregion #region Constructors - public GridView() + public GridView () { } - public GridView(NSCoder coder) : base(coder) + public GridView (NSCoder coder) : base (coder) { } - public GridView(CGSize cellSize, CGRect rect) : base(rect) + public GridView (CGSize cellSize, CGRect rect) : base (rect) { // Initialize FixedCellSize = cellSize; @@ -77,57 +68,54 @@ public GridView(CGSize cellSize, CGRect rect) : base(rect) #endregion #region Public Methods - public int RowForViewAtIndex(int index) + public int RowForViewAtIndex (int index) { if (index < 0 || index >= ArrangedViews.Count || NumberOfColumns < 1) return 0; return (index / NumberOfColumns); } - public int ColumnForViewAtIndex(int index) + public int ColumnForViewAtIndex (int index) { if (index < 0 || index >= ArrangedViews.Count || NumberOfColumns < 1) return 0; - return index - (NumberOfColumns * RowForViewAtIndex(index)); + return index - (NumberOfColumns * RowForViewAtIndex (index)); } - public CGRect FrameForViewAtIndex(int index) + public CGRect FrameForViewAtIndex (int index) { if (index < 0 || index >= ArrangedViews.Count) return CGRect.Empty; - return new CGRect(GridViewMargin + ColumnForViewAtIndex(index) * (GridViewMargin + FixedCellSize.Width), - GridViewMargin + RowForViewAtIndex(index) * (GridViewMargin + FixedCellSize.Height), + return new CGRect (GridViewMargin + ColumnForViewAtIndex (index) * (GridViewMargin + FixedCellSize.Width), + GridViewMargin + RowForViewAtIndex (index) * (GridViewMargin + FixedCellSize.Height), FixedCellSize.Width, FixedCellSize.Height ); } - public void AddArrangedView(UIView view) + public void AddArrangedView (UIView view) { - ArrangedViews.Add(view); - view.Frame = FrameForViewAtIndex(ArrangedViews.Count - 1); - AddSubview(view); - RaiseGridSizeChanged(); + ArrangedViews.Add (view); + view.Frame = FrameForViewAtIndex (ArrangedViews.Count - 1); + AddSubview (view); + RaiseGridSizeChanged (); } - public void RemoveArrangedViewsAtIndexes(NSIndexSet indices) + public void RemoveArrangedViewsAtIndexes (NSIndexSet indices) { - for (int n = ArrangedViews.Count - 1; n >= 0; --n) - { - if (indices.Contains((nuint)n)) - { - ArrangedViews[n].RemoveFromSuperview(); - ArrangedViews.RemoveAt(n); + for (int n = ArrangedViews.Count - 1; n >= 0; --n) { + if (indices.Contains ((nuint) n)) { + ArrangedViews [n].RemoveFromSuperview (); + ArrangedViews.RemoveAt (n); } } - RaiseGridSizeChanged(); + RaiseGridSizeChanged (); } - public int IndexForView(UIView view) + public int IndexForView (UIView view) { // Scan all views - for (int n = 0; n < ArrangedViews.Count; ++n) - { - if (ArrangedViews[n] == view) return n; + for (int n = 0; n < ArrangedViews.Count; ++n) { + if (ArrangedViews [n] == view) return n; } // Not found @@ -136,24 +124,24 @@ public int IndexForView(UIView view) #endregion #region Override Methods - public override void LayoutSubviews() + public override void LayoutSubviews () { - for (int n = 0; n < ArrangedViews.Count; ++n) - { - ArrangedViews[n].Frame = FrameForViewAtIndex(n); + for (int n = 0; n < ArrangedViews.Count; ++n) { + ArrangedViews [n].Frame = FrameForViewAtIndex (n); } - base.LayoutSubviews(); + base.LayoutSubviews (); } #endregion #region Events - public delegate void GridSizeChangedDelegate(CGSize size); + public delegate void GridSizeChangedDelegate (CGSize size); public event GridSizeChangedDelegate GridSizeChanged; - internal void RaiseGridSizeChanged() { - Frame = new CGRect(0, 0, Width, Height); - GridSizeChanged?.Invoke(IntrinsicContentSize); + internal void RaiseGridSizeChanged () + { + Frame = new CGRect (0, 0, Width, Height); + GridSizeChanged?.Invoke (IntrinsicContentSize); } #endregion } diff --git a/ios11/DragAndDropMastering/DropDestination/CustomViews/ProgressSpinnerView.cs b/ios11/DragAndDropMastering/DropDestination/CustomViews/ProgressSpinnerView.cs index 444bc6fba..d7eb9749a 100644 --- a/ios11/DragAndDropMastering/DropDestination/CustomViews/ProgressSpinnerView.cs +++ b/ios11/DragAndDropMastering/DropDestination/CustomViews/ProgressSpinnerView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -6,33 +6,31 @@ using CoreAnimation; using CoreFoundation; -namespace DropDestination -{ +namespace DropDestination { /** A ProgressSpinnerView observes changes in the `fractionCompleted` property of its given progress, and updates its spinner UI accordingly. */ - public class ProgressSpinnerView : UIView - { + public class ProgressSpinnerView : UIView { #region Computed Properties - public CAShapeLayer ArcLayer { get; set; } = new CAShapeLayer(); + public CAShapeLayer ArcLayer { get; set; } = new CAShapeLayer (); public NSProgress Progress { get; set; } - public UILabel ProgressLabel { get; set; } = new UILabel(); + public UILabel ProgressLabel { get; set; } = new UILabel (); #endregion #region Constructors - public ProgressSpinnerView(CGRect frame, NSProgress progress) : base(frame) + public ProgressSpinnerView (CGRect frame, NSProgress progress) : base (frame) { // Initialize Progress = progress; - Progress.AddObserver(this, "fractionCompleted", NSKeyValueObservingOptions.New, IntPtr.Zero); + Progress.AddObserver (this, "fractionCompleted", NSKeyValueObservingOptions.New, IntPtr.Zero); - ArcLayer.Path = UIBezierPath.FromArc(new CGPoint(Bounds.GetMidX(), Bounds.GetMidY()), - (float)(0.2f * Math.Min(Bounds.Width, Bounds.Height)), - (float)(-(Math.PI / 2f)), - (float)(2f * Math.PI - (Math.PI / 2f)), - true).CGPath; + ArcLayer.Path = UIBezierPath.FromArc (new CGPoint (Bounds.GetMidX (), Bounds.GetMidY ()), + (float) (0.2f * Math.Min (Bounds.Width, Bounds.Height)), + (float) (-(Math.PI / 2f)), + (float) (2f * Math.PI - (Math.PI / 2f)), + true).CGPath; ArcLayer.StrokeColor = TintColor.CGColor; ArcLayer.FillColor = UIColor.Clear.CGColor; @@ -40,7 +38,7 @@ public ProgressSpinnerView(CGRect frame, NSProgress progress) : base(frame) ArcLayer.StrokeStart = 0; ArcLayer.StrokeEnd = 0; ArcLayer.Position = CGPoint.Empty; - Layer.AddSublayer(ArcLayer); + Layer.AddSublayer (ArcLayer); BackgroundColor = UIColor.Clear; Layer.BorderColor = UIColor.LightGray.CGColor; @@ -50,35 +48,35 @@ public ProgressSpinnerView(CGRect frame, NSProgress progress) : base(frame) ProgressLabel.Text = "0%"; ProgressLabel.TextAlignment = UITextAlignment.Center; ProgressLabel.Frame = Bounds; - AddSubview(ProgressLabel); + AddSubview (ProgressLabel); } #endregion - public override void ObserveValue(NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) + public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context) { BeginInvokeOnMainThread (() => { - ArcLayer.StrokeEnd = (float)Progress.FractionCompleted; - ArcLayer.Opacity = (float)(1 - Progress.FractionCompleted); + ArcLayer.StrokeEnd = (float) Progress.FractionCompleted; + ArcLayer.Opacity = (float) (1 - Progress.FractionCompleted); ProgressLabel.Text = $"{100 * Progress.FractionCompleted:##0}%"; if (Progress.Finished || Progress.Cancelled) - StopObservingValue(); + StopObservingValue (); }); } - void StopObservingValue() + void StopObservingValue () { if (Progress != null) { - Progress.RemoveObserver(this, "fractionCompleted"); + Progress.RemoveObserver (this, "fractionCompleted"); Progress = null; } } #region Destructors - protected override void Dispose(bool disposing) + protected override void Dispose (bool disposing) { if (disposing) - StopObservingValue(); - base.Dispose(disposing); + StopObservingValue (); + base.Dispose (disposing); } #endregion } diff --git a/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DraggableImageView.cs b/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DraggableImageView.cs index b60fa96b1..4e0b967d6 100644 --- a/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DraggableImageView.cs +++ b/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DraggableImageView.cs @@ -1,101 +1,100 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; using CoreAnimation; -namespace DropDestination -{ +namespace DropDestination { /** A DraggableImageView is a UIImageView that can be dragged, and also fades out when dragged. It is also capable of presenting and hiding a progress spinner within its view hierarchy, given a Progress. */ - public class DraggableImageView : UIImageView, IUIDragInteractionDelegate - { + public class DraggableImageView : UIImageView, IUIDragInteractionDelegate { #region Computed Properties - public ProgressSpinnerView ProgressView {get; set;} + public ProgressSpinnerView ProgressView { get; set; } - public UIDragItem[] DragItems { + public UIDragItem [] DragItems { get { - if (Image == null) return new UIDragItem[] { }; - var itemProvider = new NSItemProvider(Image); - var item = new UIDragItem(itemProvider); + if (Image == null) return new UIDragItem [] { }; + var itemProvider = new NSItemProvider (Image); + var item = new UIDragItem (itemProvider); item.LocalObject = this; - return new UIDragItem[] { item }; + return new UIDragItem [] { item }; } } #endregion #region Constructors - public DraggableImageView() : base(CGRect.Empty) + public DraggableImageView () : base (CGRect.Empty) { // Initialize UserInteractionEnabled = true; - AddInteraction(new UIDragInteraction(this)); + AddInteraction (new UIDragInteraction (this)); } - public DraggableImageView(NSCoder coder) : base(coder) + public DraggableImageView (NSCoder coder) : base (coder) { } #endregion #region Public Methods - public void StartShowingProgress(NSProgress progress) { - StopShowingProgress(); - ProgressView = new ProgressSpinnerView(Bounds, progress); - AddSubview(ProgressView); + public void StartShowingProgress (NSProgress progress) + { + StopShowingProgress (); + ProgressView = new ProgressSpinnerView (Bounds, progress); + AddSubview (ProgressView); } - public void StopShowingProgress() { - if (ProgressView != null) - { - ProgressView.RemoveFromSuperview(); - ProgressView.Dispose(); + public void StopShowingProgress () + { + if (ProgressView != null) { + ProgressView.RemoveFromSuperview (); + ProgressView.Dispose (); ProgressView = null; } } #endregion #region UIDragInteractionDelegate - [Export("dragInteraction:willAnimateLiftWithAnimator:session:")] - public void WillAnimateLift(UIDragInteraction interaction, IUIDragAnimating animator, IUIDragSession session) + [Export ("dragInteraction:willAnimateLiftWithAnimator:session:")] + public void WillAnimateLift (UIDragInteraction interaction, IUIDragAnimating animator, IUIDragSession session) { - animator.AddAnimations( () => { + animator.AddAnimations (() => { Alpha = 0.25f; }); } - [Export("dragInteraction:item:willAnimateCancelWithAnimator:")] - public void WillAnimateCancel(UIDragInteraction interaction, UIDragItem item, IUIDragAnimating animator) + [Export ("dragInteraction:item:willAnimateCancelWithAnimator:")] + public void WillAnimateCancel (UIDragInteraction interaction, UIDragItem item, IUIDragAnimating animator) { - animator.AddAnimations(() => { + animator.AddAnimations (() => { Alpha = 1; }); } - [Export("dragInteraction:previewForLiftingItem:session:")] - public UITargetedDragPreview GetPreviewForLiftingItem(UIDragInteraction interaction, UIDragItem item, IUIDragSession session) + [Export ("dragInteraction:previewForLiftingItem:session:")] + public UITargetedDragPreview GetPreviewForLiftingItem (UIDragInteraction interaction, UIDragItem item, IUIDragSession session) { - var imageView = new UIImageView(Image){ + var imageView = new UIImageView (Image) { Frame = this.Frame, ClipsToBounds = true, ContentMode = UIViewContentMode.ScaleAspectFill }; - var target = new UIDragPreviewTarget(Superview, imageView.Center); - return new UITargetedDragPreview(imageView, new UIDragPreviewParameters(), target); + var target = new UIDragPreviewTarget (Superview, imageView.Center); + return new UITargetedDragPreview (imageView, new UIDragPreviewParameters (), target); } - public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) + public UIDragItem [] GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) { return DragItems; } - [Export("dragInteraction:itemsForAddingToSession:withTouchAtPoint:")] - public UIDragItem[] GetItemsForAddingToSession(UIDragInteraction interaction, IUIDragSession session, CGPoint point) + [Export ("dragInteraction:itemsForAddingToSession:withTouchAtPoint:")] + public UIDragItem [] GetItemsForAddingToSession (UIDragInteraction interaction, IUIDragSession session, CGPoint point) { return DragItems; } diff --git a/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableDeleteView.cs b/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableDeleteView.cs index 528da5d82..7ab3ace6f 100644 --- a/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableDeleteView.cs +++ b/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableDeleteView.cs @@ -1,46 +1,45 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; using Foundation; using CoreAnimation; -namespace DropDestination -{ +namespace DropDestination { /** A DroppableDeleteView is a DeleteView that invokes its delegate when a drop occurs on it. All local objects that represent views in the list of dropped items are to be removed. */ - public class DroppableDeleteView : DeleteView, IUIDropInteractionDelegate - { + public class DroppableDeleteView : DeleteView, IUIDropInteractionDelegate { #region Constructors - public DroppableDeleteView() + public DroppableDeleteView () { } - public DroppableDeleteView(NSCoder coder) : base(coder) + public DroppableDeleteView (NSCoder coder) : base (coder) { } - public DroppableDeleteView(string labelText, DidDeleteViewsDelegate deleteDelegate) : base(labelText) + public DroppableDeleteView (string labelText, DidDeleteViewsDelegate deleteDelegate) : base (labelText) { // Initialize this.DidDeleteViews += deleteDelegate; UserInteractionEnabled = true; - AddInteraction(new UIDropInteraction(this)); + AddInteraction (new UIDropInteraction (this)); } #endregion #region Public Methods - public List<UIView> LocalViewsForSession(IUIDropSession session) { - var views = new List<UIView>(); + public List<UIView> LocalViewsForSession (IUIDropSession session) + { + var views = new List<UIView> (); - if (session.LocalDragSession !=null) { - foreach(UIDragItem item in session.Items) { + if (session.LocalDragSession != null) { + foreach (UIDragItem item in session.Items) { var view = item.LocalObject as UIView; - if (view != null) views.Add(view); + if (view != null) views.Add (view); } } @@ -49,40 +48,40 @@ public List<UIView> LocalViewsForSession(IUIDropSession session) { #endregion #region UIDropInteractionDelegate - [Export("dropInteraction:previewForDroppingItem:withDefault:")] - public UITargetedDragPreview GetPreviewForDroppingItem(UIDropInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) + [Export ("dropInteraction:previewForDroppingItem:withDefault:")] + public UITargetedDragPreview GetPreviewForDroppingItem (UIDropInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) { - var target = new UIDragPreviewTarget(this, IconView.Center, CGAffineTransform.Scale(new CGAffineTransform(), 0.1f, 0.1f)); - return defaultPreview.GetRetargetedPreview(target); + var target = new UIDragPreviewTarget (this, IconView.Center, CGAffineTransform.Scale (new CGAffineTransform (), 0.1f, 0.1f)); + return defaultPreview.GetRetargetedPreview (target); } - [Export("dropInteraction:sessionDidUpdate:")] - public UIDropProposal SessionDidUpdate(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:sessionDidUpdate:")] + public UIDropProposal SessionDidUpdate (UIDropInteraction interaction, IUIDropSession session) { - if (session.LocalDragSession == null) return new UIDropProposal(UIDropOperation.Forbidden); - return new UIDropProposal(UIDropOperation.Move); + if (session.LocalDragSession == null) return new UIDropProposal (UIDropOperation.Forbidden); + return new UIDropProposal (UIDropOperation.Move); } - [Export("dropInteraction:performDrop:")] - public void PerformDrop(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:performDrop:")] + public void PerformDrop (UIDropInteraction interaction, IUIDropSession session) { - RaiseDidDeleteViews(LocalViewsForSession(session)); + RaiseDidDeleteViews (LocalViewsForSession (session)); } - [Export("dropInteraction:sessionDidEnter:")] - public void SessionDidEnter(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:sessionDidEnter:")] + public void SessionDidEnter (UIDropInteraction interaction, IUIDropSession session) { Alpha = 1.0f; } - [Export("dropInteraction:sessionDidExit:")] - public void SessionDidExit(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:sessionDidExit:")] + public void SessionDidExit (UIDropInteraction interaction, IUIDropSession session) { Alpha = 0.5f; } - [Export("dropInteraction:sessionDidEnd:")] - public void SessionDidEnd(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:sessionDidEnd:")] + public void SessionDidEnd (UIDropInteraction interaction, IUIDropSession session) { Alpha = 0.5f; } diff --git a/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableImageGridViewController.cs b/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableImageGridViewController.cs index 330f88727..a358c3553 100644 --- a/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableImageGridViewController.cs +++ b/ios11/DragAndDropMastering/DropDestination/DragAndDrop/DroppableImageGridViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using CoreGraphics; @@ -7,100 +7,97 @@ using CoreFoundation; using ObjCRuntime; -namespace DropDestination -{ +namespace DropDestination { /** A DroppableImageGridViewController is a ImageGridViewController that supports drop interactions. When one or more items containing images are dropped within this view, it will insert them as image views to its view hierarchy. */ - public class DroppableImageGridViewController : ImageGridViewController, IUIDropInteractionDelegate - { + public class DroppableImageGridViewController : ImageGridViewController, IUIDropInteractionDelegate { #region Computed Properties - public Dictionary<UIDragItem, (DraggableImageView view, NSProgress progress)> ItemStates { get; set; } = new Dictionary<UIDragItem, (DraggableImageView, NSProgress)>(); + public Dictionary<UIDragItem, (DraggableImageView view, NSProgress progress)> ItemStates { get; set; } = new Dictionary<UIDragItem, (DraggableImageView, NSProgress)> (); #endregion #region Constructors - public DroppableImageGridViewController() + public DroppableImageGridViewController () { } - public DroppableImageGridViewController(NSCoder coder) : base(coder) + public DroppableImageGridViewController (NSCoder coder) : base (coder) { } - public DroppableImageGridViewController(CGSize cellSize) : base(cellSize) + public DroppableImageGridViewController (CGSize cellSize) : base (cellSize) { } #endregion - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Initialize View.UserInteractionEnabled = true; - View.AddInteraction(new UIDropInteraction(this)); + View.AddInteraction (new UIDropInteraction (this)); } #region UIDropInteractionDelegate - [Export("dropInteraction:sessionDidUpdate:")] - public UIDropProposal SessionDidUpdate(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:sessionDidUpdate:")] + public UIDropProposal SessionDidUpdate (UIDropInteraction interaction, IUIDropSession session) { - if (session.LocalDragSession == null && session.CanLoadObjects(typeof(UIImage))) - { - return new UIDropProposal(UIDropOperation.Copy); + if (session.LocalDragSession == null && session.CanLoadObjects (typeof (UIImage))) { + return new UIDropProposal (UIDropOperation.Copy); } - return new UIDropProposal(UIDropOperation.Cancel); + return new UIDropProposal (UIDropOperation.Cancel); } - [Export("dropInteraction:performDrop:")] - public void PerformDrop(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:performDrop:")] + public void PerformDrop (UIDropInteraction interaction, IUIDropSession session) { session.ProgressIndicatorStyle = UIDropSessionProgressIndicatorStyle.None; - foreach(UIDragItem item in session.Items){ - if (item.ItemProvider.CanLoadObject(typeof(UIImage))) { - var photoView = NextView(); - var progress = item.ItemProvider.LoadObject<UIImage>((img, err) => { - DispatchQueue.MainQueue.DispatchAsync(()=>{ - photoView.StopShowingProgress(); + foreach (UIDragItem item in session.Items) { + if (item.ItemProvider.CanLoadObject (typeof (UIImage))) { + var photoView = NextView (); + var progress = item.ItemProvider.LoadObject<UIImage> ((img, err) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + photoView.StopShowingProgress (); photoView.Image = img; }); }); - ItemStates.Add(item, (photoView, progress)); + ItemStates.Add (item, (photoView, progress)); } } } - [Export("dropInteraction:item:willAnimateDropWithAnimator:")] - public void WillAnimateDrop(UIDropInteraction interaction, UIDragItem item, IUIDragAnimating animator) + [Export ("dropInteraction:item:willAnimateDropWithAnimator:")] + public void WillAnimateDrop (UIDropInteraction interaction, UIDragItem item, IUIDragAnimating animator) { - if (!ItemStates.ContainsKey(item)) return; - var state = ItemStates[item]; + if (!ItemStates.ContainsKey (item)) return; + var state = ItemStates [item]; //if (state.view.Image == null) return; state.view.Alpha = 0f; - state.view.StartShowingProgress(state.progress); - animator.AddCompletion( (obj) => { + state.view.StartShowingProgress (state.progress); + animator.AddCompletion ((obj) => { state.view.Alpha = 1f; }); } - [Export("dropInteraction:concludeDrop:")] - public void ConcludeDrop(UIDropInteraction interaction, IUIDropSession session) + [Export ("dropInteraction:concludeDrop:")] + public void ConcludeDrop (UIDropInteraction interaction, IUIDropSession session) { - ItemStates.Clear(); + ItemStates.Clear (); } - [Export("dropInteraction:previewForDroppingItem:withDefault:")] - public UITargetedDragPreview GetPreviewForDroppingItem(UIDropInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) + [Export ("dropInteraction:previewForDroppingItem:withDefault:")] + public UITargetedDragPreview GetPreviewForDroppingItem (UIDropInteraction interaction, UIDragItem item, UITargetedDragPreview defaultPreview) { - if (!ItemStates.ContainsKey(item)) return null; - var state = ItemStates[item]; - var previewView = new ProgressSpinnerView(state.view.Frame, state.progress); - var target = new UIDragPreviewTarget(ContainerView, state.view.Center); - return new UITargetedDragPreview(previewView, new UIDragPreviewParameters(), target); + if (!ItemStates.ContainsKey (item)) return null; + var state = ItemStates [item]; + var previewView = new ProgressSpinnerView (state.view.Frame, state.progress); + var target = new UIDragPreviewTarget (ContainerView, state.view.Center); + return new UITargetedDragPreview (previewView, new UIDragPreviewParameters (), target); } #endregion } diff --git a/ios11/DragAndDropMastering/DropDestination/Main.cs b/ios11/DragAndDropMastering/DropDestination/Main.cs index eaff61f27..33f76c847 100644 --- a/ios11/DragAndDropMastering/DropDestination/Main.cs +++ b/ios11/DragAndDropMastering/DropDestination/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace DropDestination -{ - public class Application - { +namespace DropDestination { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/DragAndDropMastering/DropDestination/ViewController.cs b/ios11/DragAndDropMastering/DropDestination/ViewController.cs index d014a8258..5da582976 100644 --- a/ios11/DragAndDropMastering/DropDestination/ViewController.cs +++ b/ios11/DragAndDropMastering/DropDestination/ViewController.cs @@ -1,47 +1,45 @@ -using System; +using System; using CoreGraphics; using UIKit; -namespace DropDestination -{ - public partial class ViewController : UIViewController - { +namespace DropDestination { + public partial class ViewController : UIViewController { #region Computed Properties - public DroppableImageGridViewController Grid {get; set;} = new DroppableImageGridViewController(new CGSize(200,200)); + public DroppableImageGridViewController Grid { get; set; } = new DroppableImageGridViewController (new CGSize (200, 200)); public DroppableDeleteView DeleteView { get; set; } #endregion #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); View.UserInteractionEnabled = true; var gridView = Grid.View; - View.AddSubview(gridView); + View.AddSubview (gridView); - DeleteView = new DroppableDeleteView("Drop here to delete photos", (views) => { - Grid.RemoveViewsInSet(views); - View.LayoutIfNeeded(); + DeleteView = new DroppableDeleteView ("Drop here to delete photos", (views) => { + Grid.RemoveViewsInSet (views); + View.LayoutIfNeeded (); }); - View.AddSubview(DeleteView); + View.AddSubview (DeleteView); } - public override void ViewWillLayoutSubviews() + public override void ViewWillLayoutSubviews () { - base.ViewWillLayoutSubviews(); + base.ViewWillLayoutSubviews (); //Background.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height); - Grid.View.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height - 150f); - DeleteView.Frame = new CGRect(0, View.Frame.Height - 150f, View.Frame.Width, 150f); + Grid.View.Frame = new CGRect (0, 0, View.Frame.Width, View.Frame.Height - 150f); + DeleteView.Frame = new CGRect (0, View.Frame.Height - 150f, View.Frame.Width, 150f); } #endregion } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/AppDelegate.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/AppDelegate.cs index cfa300b19..2a2ba8f55 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/AppDelegate.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/AppDelegate.cs @@ -1,27 +1,24 @@ -using Foundation; +using Foundation; using UIKit; -namespace TableViewDragAndDrop -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace TableViewDragAndDrop { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window - { - get; - set; - } + public override UIWindow Window { + get; + set; + } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/Main.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/Main.cs index 2ec76d774..b7b8894bb 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/Main.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TableViewDragAndDrop -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace TableViewDragAndDrop { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model+Dragging.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model+Dragging.cs index 8ef516cec..5005f701c 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model+Dragging.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model+Dragging.cs @@ -1,44 +1,41 @@ -using System; +using System; using UIKit; using Foundation; using MobileCoreServices; -namespace TableViewDragAndDrop -{ +namespace TableViewDragAndDrop { /// <summary> /// Helper methods for providing and consuming drag-and-drop data /// </summary> - public partial class Model - { + public partial class Model { /// <summary> /// A helper function that serves as an interface to the data model, /// called by the implementation of the `tableView(_ canHandle:)` method. - /// </summary> - public bool CanHandle(IUIDropSession session) - { - return session.CanLoadObjects(typeof(NSString)); - } + /// </summary> + public bool CanHandle (IUIDropSession session) + { + return session.CanLoadObjects (typeof (NSString)); + } /// <summary> /// A helper function that serves as an interface to the data mode, called /// by the `tableView(_:itemsForBeginning:at:)` method. - /// </summary> - public UIDragItem[] DragItems(NSIndexPath indexPath) - { - var placeName = PlaceNames[indexPath.Row]; + /// </summary> + public UIDragItem [] DragItems (NSIndexPath indexPath) + { + var placeName = PlaceNames [indexPath.Row]; - var data = NSData.FromString(placeName, NSStringEncoding.UTF8); - var itemProvider = new NSItemProvider(); + var data = NSData.FromString (placeName, NSStringEncoding.UTF8); + var itemProvider = new NSItemProvider (); - itemProvider.RegisterDataRepresentation(UTType.PlainText, - NSItemProviderRepresentationVisibility.All, - (completion) => - { - completion(data, null); - return null; - }); + itemProvider.RegisterDataRepresentation (UTType.PlainText, + NSItemProviderRepresentationVisibility.All, + (completion) => { + completion (data, null); + return null; + }); - return new UIDragItem[] { new UIDragItem(itemProvider) }; - } - } + return new UIDragItem [] { new UIDragItem (itemProvider) }; + } + } } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model.cs index 133fa08b8..5b129e9ca 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/Model/Model.cs @@ -1,45 +1,43 @@ -using System; +using System; using System.Collections.Generic; -namespace TableViewDragAndDrop -{ +namespace TableViewDragAndDrop { /// <summary> /// The data model used to populate the table view on app launch /// </summary> - public partial class Model - { - public List<String> PlaceNames; - public Model() - { - PlaceNames = new List<string> { + public partial class Model { + public List<String> PlaceNames; + public Model () + { + PlaceNames = new List<string> { "Exploratorium", - "SF MOMA", - "California Academy of Sciences", - "San Francisco Zoo", - "Golden Gate Park", - "De Young Museum", - "Pier 39", - "Aquarium of the Bay", - "AT&T Park" - }; - } + "SF MOMA", + "California Academy of Sciences", + "San Francisco Zoo", + "Golden Gate Park", + "De Young Museum", + "Pier 39", + "Aquarium of the Bay", + "AT&T Park" + }; + } /// <summary> /// The traditional method for rearranging rows in a table view /// </summary> public void MoveItem (int sourceIndex, int destinationIndex) - { - var place = PlaceNames[sourceIndex]; - PlaceNames.RemoveAt(sourceIndex); - PlaceNames.Insert(destinationIndex, place); - } + { + var place = PlaceNames [sourceIndex]; + PlaceNames.RemoveAt (sourceIndex); + PlaceNames.Insert (destinationIndex, place); + } /// <summary> /// The method for adding a new item to the table view's data model /// </summary> public void AddItem (string name, int index) - { - PlaceNames.Insert(index, name); - } - } + { + PlaceNames.Insert (index, name); + } + } } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Data.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Data.cs index 5b5075ca1..d93e86785 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Data.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Data.cs @@ -1,35 +1,33 @@ -using System; +using System; using UIKit; -namespace TableViewDragAndDrop -{ +namespace TableViewDragAndDrop { /// <summary> /// The standard delegate methods for a table view, which are required whether or not you add drag and drop /// </summary> - public partial class TableViewController: IUITableViewDataSource, IUITableViewDelegate - { + public partial class TableViewController : IUITableViewDataSource, IUITableViewDelegate { // IUITableViewDataSource - public override nint RowsInSection(UIKit.UITableView tableView, nint section) + public override nint RowsInSection (UIKit.UITableView tableView, nint section) { return model.PlaceNames.Count; } - public override UIKit.UITableViewCell GetCell(UIKit.UITableView tableView, Foundation.NSIndexPath indexPath) + public override UIKit.UITableViewCell GetCell (UIKit.UITableView tableView, Foundation.NSIndexPath indexPath) { - var cell = tableView.DequeueReusableCell("Cell", indexPath); - cell.TextLabel.Text = model.PlaceNames[indexPath.Row]; + var cell = tableView.DequeueReusableCell ("Cell", indexPath); + cell.TextLabel.Text = model.PlaceNames [indexPath.Row]; return cell; } // IUITableViewDelegate - public override bool CanMoveRow(UIKit.UITableView tableView, Foundation.NSIndexPath indexPath) + public override bool CanMoveRow (UIKit.UITableView tableView, Foundation.NSIndexPath indexPath) { return true; } - public override void MoveRow(UIKit.UITableView tableView, Foundation.NSIndexPath sourceIndexPath, Foundation.NSIndexPath destinationIndexPath) + public override void MoveRow (UIKit.UITableView tableView, Foundation.NSIndexPath sourceIndexPath, Foundation.NSIndexPath destinationIndexPath) { - model.MoveItem(sourceIndexPath.Row, destinationIndexPath.Row); + model.MoveItem (sourceIndexPath.Row, destinationIndexPath.Row); } - } + } } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drag.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drag.cs index 4899e680a..5829108ca 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drag.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drag.cs @@ -1,20 +1,18 @@ -using System; +using System; using Foundation; using UIKit; -namespace TableViewDragAndDrop -{ +namespace TableViewDragAndDrop { /// <summary> /// Implements the delegate methods for providing data for a drag interaction /// </summary> - public partial class TableViewController : IUITableViewDragDelegate - { - /// <summary> - /// Required for drag operations from a table - /// </summary> - public UIDragItem[] GetItemsForBeginningDragSession(UITableView tableView, IUIDragSession session, NSIndexPath indexPath) - { - return model.DragItems(indexPath); - } - } + public partial class TableViewController : IUITableViewDragDelegate { + /// <summary> + /// Required for drag operations from a table + /// </summary> + public UIDragItem [] GetItemsForBeginningDragSession (UITableView tableView, IUIDragSession session, NSIndexPath indexPath) + { + return model.DragItems (indexPath); + } + } } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drop.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drop.cs index 7ea192fcf..2a071876c 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drop.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController+Drop.cs @@ -1,23 +1,21 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; -namespace TableViewDragAndDrop -{ +namespace TableViewDragAndDrop { /// <summary> /// Implements the delegate methods for consuming data for a drop interaction /// </summary> - public partial class TableViewController : IUITableViewDropDelegate - { + public partial class TableViewController : IUITableViewDropDelegate { /// <summary> /// Ensure that the drop session contains a drag item with a data representation that the view can consume. - /// </summary> - [Export("tableView:canHandleDropSession:")] - public bool CanHandleDropSession(UITableView tableView, IUIDropSession session) - { - return model.CanHandle(session); - } + /// </summary> + [Export ("tableView:canHandleDropSession:")] + public bool CanHandleDropSession (UITableView tableView, IUIDropSession session) + { + return model.CanHandle (session); + } /// <summary> /// A drop proposal from a table view includes two items: a drop operation, @@ -25,22 +23,20 @@ public bool CanHandleDropSession(UITableView tableView, IUIDropSession session) /// table view will take upon receiving the items. (A drop proposal from a /// custom view does includes only a drop operation, not an intent.) /// </summary> - [Export("tableView:dropSessionDidUpdate:withDestinationIndexPath:")] - public UITableViewDropProposal DropSessionDidUpdate(UITableView tableView, IUIDropSession session, NSIndexPath destinationIndexPath) - { + [Export ("tableView:dropSessionDidUpdate:withDestinationIndexPath:")] + public UITableViewDropProposal DropSessionDidUpdate (UITableView tableView, IUIDropSession session, NSIndexPath destinationIndexPath) + { // The .move operation is available only for dragging within a single app. - if (tableView.HasActiveDrag) - { - if (session.Items.Length > 1) - { - return new UITableViewDropProposal(UIDropOperation.Cancel); - } else { - return new UITableViewDropProposal(UIDropOperation.Move, UITableViewDropIntent.InsertAtDestinationIndexPath); - } + if (tableView.HasActiveDrag) { + if (session.Items.Length > 1) { + return new UITableViewDropProposal (UIDropOperation.Cancel); + } else { + return new UITableViewDropProposal (UIDropOperation.Move, UITableViewDropIntent.InsertAtDestinationIndexPath); + } } else { - return new UITableViewDropProposal(UIDropOperation.Copy, UITableViewDropIntent.InsertAtDestinationIndexPath); + return new UITableViewDropProposal (UIDropOperation.Copy, UITableViewDropIntent.InsertAtDestinationIndexPath); } - } + } /// <summary> /// his delegate method is the only opportunity for accessing and loading @@ -49,42 +45,36 @@ public UITableViewDropProposal DropSessionDidUpdate(UITableView tableView, IUIDr /// optional animations.Local drags with one item go through the existing /// `tableView(_:moveRowAt:to:)` method on the data source. /// </summary> - public void PerformDrop(UITableView tableView, IUITableViewDropCoordinator coordinator) - { - NSIndexPath indexPath, destinationIndexPath; + public void PerformDrop (UITableView tableView, IUITableViewDropCoordinator coordinator) + { + NSIndexPath indexPath, destinationIndexPath; - // TODO: confirm this port is accurate - if (coordinator.DestinationIndexPath != null) - { - indexPath = coordinator.DestinationIndexPath; - destinationIndexPath = indexPath; - } - else - { - // Get last index path of table view - var section = tableView.NumberOfSections() - 1; - var row = tableView.NumberOfRowsInSection(section); - destinationIndexPath = NSIndexPath.FromRowSection(row, section); - } + // TODO: confirm this port is accurate + if (coordinator.DestinationIndexPath != null) { + indexPath = coordinator.DestinationIndexPath; + destinationIndexPath = indexPath; + } else { + // Get last index path of table view + var section = tableView.NumberOfSections () - 1; + var row = tableView.NumberOfRowsInSection (section); + destinationIndexPath = NSIndexPath.FromRowSection (row, section); + } - coordinator.Session.LoadObjects<NSString>((items) => - { - // Consume drag items - List<string> stringItems = new List<string>(); - foreach (var i in items) - { - var q = NSString.FromHandle(i.Handle); - stringItems.Add(q.ToString()); - } - var indexPaths = new List<NSIndexPath>(); - for (var j = 0; j < stringItems.Count; j++) - { - var indexPath1 = NSIndexPath.FromRowSection(destinationIndexPath.Row + j, destinationIndexPath.Section); - model.AddItem(stringItems[j], indexPath1.Row); - indexPaths.Add(indexPath1); - } - tableView.InsertRows(indexPaths.ToArray(), UITableViewRowAnimation.Automatic); - }); - } - } + coordinator.Session.LoadObjects<NSString> ((items) => { + // Consume drag items + List<string> stringItems = new List<string> (); + foreach (var i in items) { + var q = NSString.FromHandle (i.Handle); + stringItems.Add (q.ToString ()); + } + var indexPaths = new List<NSIndexPath> (); + for (var j = 0; j < stringItems.Count; j++) { + var indexPath1 = NSIndexPath.FromRowSection (destinationIndexPath.Row + j, destinationIndexPath.Section); + model.AddItem (stringItems [j], indexPath1.Row); + indexPaths.Add (indexPath1); + } + tableView.InsertRows (indexPaths.ToArray (), UITableViewRowAnimation.Automatic); + }); + } + } } diff --git a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController.cs b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController.cs index 784b41984..4f4ef6ec9 100644 --- a/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController.cs +++ b/ios11/DragAndDropTableView/TableViewDragAndDrop/TableViewController/TableViewController.cs @@ -1,31 +1,29 @@ -using Foundation; -using System; -using UIKit; - -namespace TableViewDragAndDrop -{ - /// <summary> - /// Demonstrates how to enable drag and drop for a UITableView instance - /// </summary> - public partial class TableViewController : UITableViewController - { - public TableViewController (IntPtr handle) : base (handle) - { - } - - Model model = new Model(); - - public override void ViewDidLoad() - { - base.ViewDidLoad(); +using Foundation; +using System; +using UIKit; + +namespace TableViewDragAndDrop { + /// <summary> + /// Demonstrates how to enable drag and drop for a UITableView instance + /// </summary> + public partial class TableViewController : UITableViewController { + public TableViewController (IntPtr handle) : base (handle) + { + } + + Model model = new Model (); + + public override void ViewDidLoad () + { + base.ViewDidLoad (); // Specify the table as its own drag source and drop delegate - this.TableView.DragDelegate = this; - this.TableView.DropDelegate = this; - - // Impelement delegate and datasource for tableview to operate - this.TableView.DataSource = this; - this.TableView.Delegate = this; - } - } -} \ No newline at end of file + this.TableView.DragDelegate = this; + this.TableView.DropDelegate = this; + + // Impelement delegate and datasource for tableview to operate + this.TableView.DataSource = this; + this.TableView.Delegate = this; + } + } +} diff --git a/ios11/EnvironmentTexturing/EnvironmentTexturing/AppDelegate.cs b/ios11/EnvironmentTexturing/EnvironmentTexturing/AppDelegate.cs index bac1ae186..0ea6ba789 100644 --- a/ios11/EnvironmentTexturing/EnvironmentTexturing/AppDelegate.cs +++ b/ios11/EnvironmentTexturing/EnvironmentTexturing/AppDelegate.cs @@ -1,29 +1,26 @@ -using ARKit; +using ARKit; using Foundation; using System; using UIKit; -namespace EnvironmentTexturing -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace EnvironmentTexturing { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - if (!ARConfiguration.IsSupported) - { - throw new NotSupportedException("ARKit is not available on this device.For apps that require ARKit " + - "for core functionality, use the `arkit` key in the key in the " + - "`UIRequiredDeviceCapabilities` section of the Info.plist to prevent " + - "the app from installing. (If the app can't be installed, this error " + - "can't be triggered in a production scenario.) " + - "In apps where AR is an additive feature, use `isSupported` to " + - "determine whether to show UI for launching AR experiences"); // For details, see https://developer.apple.com/documentation/arkit - } + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + if (!ARConfiguration.IsSupported) { + throw new NotSupportedException ("ARKit is not available on this device.For apps that require ARKit " + + "for core functionality, use the `arkit` key in the key in the " + + "`UIRequiredDeviceCapabilities` section of the Info.plist to prevent " + + "the app from installing. (If the app can't be installed, this error " + + "can't be triggered in a production scenario.) " + + "In apps where AR is an additive feature, use `isSupported` to " + + "determine whether to show UI for launching AR experiences"); // For details, see https://developer.apple.com/documentation/arkit + } - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/ios11/EnvironmentTexturing/EnvironmentTexturing/Main.cs b/ios11/EnvironmentTexturing/EnvironmentTexturing/Main.cs index da329dc6a..f2024aa9f 100644 --- a/ios11/EnvironmentTexturing/EnvironmentTexturing/Main.cs +++ b/ios11/EnvironmentTexturing/EnvironmentTexturing/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace EnvironmentTexturing -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace EnvironmentTexturing { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios11/EnvironmentTexturing/EnvironmentTexturing/Utilities.cs b/ios11/EnvironmentTexturing/EnvironmentTexturing/Utilities.cs index ba9713093..e55b638ad 100644 --- a/ios11/EnvironmentTexturing/EnvironmentTexturing/Utilities.cs +++ b/ios11/EnvironmentTexturing/EnvironmentTexturing/Utilities.cs @@ -1,76 +1,69 @@ -using ARKit; +using ARKit; using CoreGraphics; using SceneKit; using System.Linq; -namespace EnvironmentTexturing -{ - public static class CGPointExtensions - { - /// <summary> - /// Extracts the screen space point from a vector returned by SCNView.projectPoint(_:). - /// </summary> - public static CGPoint Create(this SCNVector3 vector) - { - return new CGPoint(vector.X, vector.Y); - } - } +namespace EnvironmentTexturing { + public static class CGPointExtensions { + /// <summary> + /// Extracts the screen space point from a vector returned by SCNView.projectPoint(_:). + /// </summary> + public static CGPoint Create (this SCNVector3 vector) + { + return new CGPoint (vector.X, vector.Y); + } + } - public static class ARSCNViewExtensions - { - public static ARHitTestResult SmartHitTest(this ARSCNView self, CGPoint point) - { - // Perform the hit test. - var results = self.HitTest(point, ARHitTestResultType.ExistingPlaneUsingGeometry); + public static class ARSCNViewExtensions { + public static ARHitTestResult SmartHitTest (this ARSCNView self, CGPoint point) + { + // Perform the hit test. + var results = self.HitTest (point, ARHitTestResultType.ExistingPlaneUsingGeometry); - // 1. Check for a result on an existing plane using geometry. - var existingPlaneUsingGeometryResult = results.FirstOrDefault(result => result.Type == ARHitTestResultType.ExistingPlaneUsingGeometry); - if (existingPlaneUsingGeometryResult != null) - { - return existingPlaneUsingGeometryResult; - } + // 1. Check for a result on an existing plane using geometry. + var existingPlaneUsingGeometryResult = results.FirstOrDefault (result => result.Type == ARHitTestResultType.ExistingPlaneUsingGeometry); + if (existingPlaneUsingGeometryResult != null) { + return existingPlaneUsingGeometryResult; + } - // 2. Check for a result on an existing plane, assuming its dimensions are infinite. - var infinitePlaneResults = self.HitTest(point, ARHitTestResultType.ExistingPlane); + // 2. Check for a result on an existing plane, assuming its dimensions are infinite. + var infinitePlaneResults = self.HitTest (point, ARHitTestResultType.ExistingPlane); - var infinitePlaneResult = infinitePlaneResults.FirstOrDefault(); - if (infinitePlaneResult != null) - { - return infinitePlaneResult; - } + var infinitePlaneResult = infinitePlaneResults.FirstOrDefault (); + if (infinitePlaneResult != null) { + return infinitePlaneResult; + } - // 3. As a final fallback, check for a result on estimated planes. - return results.FirstOrDefault(result => result.Type == ARHitTestResultType.EstimatedHorizontalPlane); - } - } + // 3. As a final fallback, check for a result on estimated planes. + return results.FirstOrDefault (result => result.Type == ARHitTestResultType.EstimatedHorizontalPlane); + } + } - public static class NNodeExtensions - { - public static SCNVector3 GetExtents(this SCNNode self) - { - var min = default(SCNVector3); - var max = default(SCNVector3); - self.GetBoundingBox(ref min, ref max); + public static class NNodeExtensions { + public static SCNVector3 GetExtents (this SCNNode self) + { + var min = default (SCNVector3); + var max = default (SCNVector3); + self.GetBoundingBox (ref min, ref max); - return max - min; - } - } + return max - min; + } + } - public static class NMatrix4Extensions - { - public static OpenTK.NMatrix4 CreateTranslation(SCNVector3 vector) - { - return new OpenTK.NMatrix4(new OpenTK.Vector4(1, 0, 0, vector.X), - new OpenTK.Vector4(0, 1, 0, vector.Y), - new OpenTK.Vector4(0, 0, 1, vector.Z), - new OpenTK.Vector4(0, 0, 0, 1)); - } + public static class NMatrix4Extensions { + public static OpenTK.NMatrix4 CreateTranslation (SCNVector3 vector) + { + return new OpenTK.NMatrix4 (new OpenTK.Vector4 (1, 0, 0, vector.X), + new OpenTK.Vector4 (0, 1, 0, vector.Y), + new OpenTK.Vector4 (0, 0, 1, vector.Z), + new OpenTK.Vector4 (0, 0, 0, 1)); + } - public static SCNVector3 GetTranslation(this OpenTK.NMatrix4 self) - { - var translation = self.Column3; - return new SCNVector3(translation.X, translation.Y, translation.Z); - //return new SCNVector3(self.Column0.Z, self.Column1.Z, self.Column2.Z); - } - } -} \ No newline at end of file + public static SCNVector3 GetTranslation (this OpenTK.NMatrix4 self) + { + var translation = self.Column3; + return new SCNVector3 (translation.X, translation.Y, translation.Z); + //return new SCNVector3(self.Column0.Z, self.Column1.Z, self.Column2.Z); + } + } +} diff --git a/ios11/EnvironmentTexturing/EnvironmentTexturing/ViewController.cs b/ios11/EnvironmentTexturing/EnvironmentTexturing/ViewController.cs index c5015e3da..e363736cd 100644 --- a/ios11/EnvironmentTexturing/EnvironmentTexturing/ViewController.cs +++ b/ios11/EnvironmentTexturing/EnvironmentTexturing/ViewController.cs @@ -1,4 +1,4 @@ -using ARKit; +using ARKit; using CoreFoundation; using CoreGraphics; using Foundation; @@ -6,472 +6,424 @@ using System; using UIKit; -namespace EnvironmentTexturing -{ - /// <summary> - /// Main view controller for the AR experience. - /// </summary> - public partial class ViewController : UIViewController, IARSCNViewDelegate, IARSessionDelegate - { - // Model of shiny sphere that is added to the scene - private SCNNode virtualObjectModel; - - // Environment Texturing Configuration - - // The virtual object that the user interacts with in the scene. - private SCNNode virtualObject; - - // An environment probe for shading that virtual object. - private AREnvironmentProbeAnchor environmentProbeAnchor; - - // A fallback environment probe encompassing the whole scene. - private AREnvironmentProbeAnchor sceneEnvironmentProbeAnchor; - - // Place environment probes manually or allow ARKit to place them automatically. - private AREnvironmentTexturing currentTexturingMode = AREnvironmentTexturing.Automatic; - - // Indicates whether manually placed probes need updating. - private bool requiresProbeRefresh = true; - - // Tracks timing of manual probe updates to prevent updating too frequently. - private double lastProbeAnchorUpdateTime; - - // Indicates whether ARKit has provided an environment texture. - private bool isEnvironmentTextureAvailable; - - // The latest screen touch position when a pan gesture is active - private CGPoint? lastPanTouchPosition; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.InitializeVirtualObjectModel(); - - this.sceneView.Delegate = this; - this.sceneView.Session.Delegate = this; - - switch (this.currentTexturingMode) - { - case AREnvironmentTexturing.Manual: - this.textureModeSelectionControl.SelectedSegment = 1; - break; - case AREnvironmentTexturing.Automatic: - this.textureModeSelectionControl.SelectedSegment = 0; - break; - default: - throw new Exception("This app supports only manual and automatic environment texturing."); - } - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - // Prevent the screen from dimming to avoid interrupting the AR experience. - UIApplication.SharedApplication.IdleTimerDisabled = true; - - // Start the AR session with automatic environment texturing. - this.sceneView.Session.Run(new ARWorldTrackingConfiguration - { - PlaneDetection = ARPlaneDetection.Horizontal, - EnvironmentTexturing = AREnvironmentTexturing.Automatic - }); - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - this.sceneView.Session.Pause(); - } - - #region Session management - - partial void ChangeTextureMode(UISegmentedControl sender) - { - if (sender.SelectedSegment == 0) - { - this.currentTexturingMode = AREnvironmentTexturing.Automatic; - this.environmentProbeAnchor?.Dispose(); - this.environmentProbeAnchor = null; - } - else - { - this.currentTexturingMode = AREnvironmentTexturing.Manual; - this.requiresProbeRefresh = true; - } - - // Remove anchors and change texturing mode - this.ResetTracking(true); - } - - partial void RestartExperience(NSObject sender) - { - if (this.virtualObject != null) - { - this.virtualObject.RemoveFromParentNode(); - this.virtualObject = null; - } - - this.ResetTracking(); - } - - /// <summary> - /// Runs the session with a new AR configuration to change modes or reset the experience. - /// </summary> - private void ResetTracking(bool changeTextureMode = false) - { - var configuration = new ARWorldTrackingConfiguration(); - configuration.PlaneDetection = ARPlaneDetection.Horizontal; - configuration.EnvironmentTexturing = this.currentTexturingMode; - - var session = this.sceneView.Session; - if (changeTextureMode) - { - // Remove existing environment probe anchors. - if (session.CurrentFrame?.Anchors != null) - { - foreach (var anchor in session.CurrentFrame.Anchors) - { - session.RemoveAnchor(anchor); - } - } - - // Don't reset tracking when changing modes in the same session. - session.Run(configuration); - } - else - { - session.Run(configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - } - - this.isEnvironmentTextureAvailable = false; - this.sceneEnvironmentProbeAnchor?.Dispose(); - this.sceneEnvironmentProbeAnchor = null; - configuration.Dispose(); - session.Dispose(); - } - - /// <summary> - /// Updates the UI to provide feedback on the state of the AR experience. - /// </summary> - private void UpdateSessionInfoLabel(ARCamera camera) - { - string message = null; - - switch (camera.TrackingState) - { - case ARTrackingState.NotAvailable: - message = "Tracking Unavailable"; - break; - - case ARTrackingState.Limited: - switch (camera.TrackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: - message = "Tracking Limited\nExcessive motion - Try slowing down your movement, or reset the session."; - break; - - case ARTrackingStateReason.InsufficientFeatures: - message = "Tracking Limited\nLow detail - Try pointing at a flat surface, or reset the session."; - break; - - case ARTrackingStateReason.Initializing: - message = "Initializing"; - break; - - case ARTrackingStateReason.Relocalizing: - message = "Recovering from interruption"; - break; - } - break; - - case ARTrackingState.Normal: - if (this.virtualObject == null) - { - if (this.isEnvironmentTextureAvailable) - { - message = "Tap to place a sphere, then tap or drag to move it or pinch to scale it."; - } - else - { - message = "Generating environment texture."; - } - } - break; - } - - - // Show the message, or hide the label if there's no message. - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (this.sessionInfoLabel.Text != message) - { - UIView.Animate(0.25d, () => - { - this.sessionInfoLabel.Text = message; - if (!string.IsNullOrEmpty(message)) - { - this.sessionInfoView.Alpha = 1; - } - else - { - this.sessionInfoView.Alpha = 0; - } - }); - } - }); - } - - #endregion - - #region Environment Texturing - - private void UpdateEnvironmentProbe(double time) - { - // Update the probe only if the object has been moved or scaled, - // only when manually placed, not too often. - if (this.virtualObject != null && - this.currentTexturingMode == AREnvironmentTexturing.Manual && - time - this.lastProbeAnchorUpdateTime >= 1d && - this.requiresProbeRefresh) - { - // Remove existing probe anchor, if any. - var probeAnchor = this.environmentProbeAnchor; - if (probeAnchor != null) - { - this.sceneView.Session.RemoveAnchor(probeAnchor); - this.environmentProbeAnchor.Dispose(); - this.environmentProbeAnchor = null; - } - - // Make sure the probe encompasses the object and provides some surrounding area to appear in reflections. - var extent = SCNVector3.Multiply(this.virtualObject.GetExtents(), this.virtualObject.Scale); - extent.X *= 3; // Reflect an area 3x the width of the object. - extent.Z *= 3; // Reflect an area 3x the depth of the object. - - // Also include some vertical area around the object, but keep the bottom of the probe at the - // bottom of the object so that it captures the real-world surface underneath. - var verticalOffset = new SCNVector3(0, extent.Y, 0); - var transform = NMatrix4Extensions.CreateTranslation(this.virtualObject.Position + verticalOffset); - extent.Y *= 2; - - // Create the new environment probe anchor and add it to the session. - probeAnchor = new AREnvironmentProbeAnchor(transform, new OpenTK.NVector3(extent.X, extent.Y, extent.Z)); - this.sceneView.Session.AddAnchor(probeAnchor); - - // Remember state to prevent updating the environment probe too often. - this.environmentProbeAnchor = probeAnchor; - this.lastProbeAnchorUpdateTime = CoreAnimation.CAAnimation.CurrentMediaTime(); - this.requiresProbeRefresh = false; - } - } - - private void UpdateSceneEnvironmentProbe(ARFrame frame) - { - if (this.sceneEnvironmentProbeAnchor == null && this.currentTexturingMode == AREnvironmentTexturing.Manual) - { - // Create an environment probe anchor with room-sized extent to act as fallback when the probe anchor of - // an object is removed and added during translation and scaling - this.sceneEnvironmentProbeAnchor = new AREnvironmentProbeAnchor("sceneProbe", OpenTK.NMatrix4.Identity, new OpenTK.NVector3(5f, 5f, 5f)); - this.sceneView.Session.AddAnchor(this.sceneEnvironmentProbeAnchor); - } - } - - #endregion - - #region IARSCNViewDelegate - - [Export("renderer:updateAtTime:")] - public void Update(ISCNSceneRenderer renderer, double timeInSeconds) - { - this.UpdateEnvironmentProbe(timeInSeconds); - } - - [Export("renderer:didUpdateNode:forAnchor:")] - public void DidUpdateNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) - { - // Check for whether any environment textures have been generated. - if (anchor is AREnvironmentProbeAnchor envProbeAnchor && !this.isEnvironmentTextureAvailable) - { - this.isEnvironmentTextureAvailable = envProbeAnchor.EnvironmentTexture != null; - } - } - - #endregion - - #region ARSessionObserver - - [Export("session:cameraDidChangeTrackingState:")] - public void CameraDidChangeTrackingState(ARSession session, ARCamera camera) - { - var frame = session.CurrentFrame; - if (frame == null) - { - throw new Exception("ARSession should have an ARFrame"); - } - - this.UpdateSessionInfoLabel(camera); - frame.Dispose(); - } - - [Export("session:didFailWithError:")] - public void DidFail(ARSession session, NSError error) - { - this.ResetTracking(); - } - - [Export("sessionShouldAttemptRelocalization:")] - public bool ShouldAttemptRelocalization(ARSession session) - { - return true; - } - - #endregion - - #region IARSessionDelegate - - [Export("session:didUpdateFrame:")] - public void DidUpdateFrame(ARSession session, ARFrame frame) - { - this.UpdateSceneEnvironmentProbe(frame); - this.UpdateSessionInfoLabel(frame.Camera); - frame.Dispose(); - } - - #endregion - - #region Virtual Object gesture interaction - - partial void DidPan(UIPanGestureRecognizer gesture) - { - if (this.virtualObject != null) - { - switch (gesture.State) - { - case UIGestureRecognizerState.Changed: - var translation = gesture.TranslationInView(this.sceneView); - - var previousPosition = this.lastPanTouchPosition ?? CGPointExtensions.Create(this.sceneView.ProjectPoint(this.virtualObject.Position)); - // Calculate the new touch position - var currentPosition = new CGPoint(previousPosition.X + translation.X, previousPosition.Y + translation.Y); - using (var hitTestResult = this.sceneView.SmartHitTest(currentPosition)) - { - if (hitTestResult != null) - { - this.virtualObject.Position = hitTestResult.WorldTransform.GetTranslation(); - // Refresh the probe as the object keeps moving - this.requiresProbeRefresh = true; - } - } - - this.lastPanTouchPosition = currentPosition; - // reset the gesture's translation - gesture.SetTranslation(CGPoint.Empty, this.sceneView); - break; - - default: - // Clear the current position tracking. - this.lastPanTouchPosition = null; - break; - - } - } - } - - partial void DidTap(UITapGestureRecognizer gesture) - { - // Allow placing objects only when ARKit tracking is in a good state for hit testing, - // and environment texture is available (to prevent undesirable changes in reflected texture). - var camera = this.sceneView.Session.CurrentFrame?.Camera; - if (camera != null && camera.TrackingState == ARTrackingState.Normal && this.isEnvironmentTextureAvailable) - { - var touchLocation = gesture.LocationInView(this.sceneView); - - if (this.virtualObject != null) - { - using (var hitTestResult = this.sceneView.SmartHitTest(touchLocation)) - { - if (hitTestResult != null) - { - // Teleport the object to wherever the user touched the screen. - this.virtualObject.Position = hitTestResult.WorldTransform.GetTranslation(); - // Update the environment probe anchor when object is teleported. - this.requiresProbeRefresh = true; - } - } - } - else - { - // Add the object to the scene at the tap location. - DispatchQueue.DefaultGlobalQueue.DispatchAsync(() => - { - this.Place(this.virtualObjectModel, touchLocation); - - // Newly added object requires an environment probe anchor. - this.requiresProbeRefresh = true; - }); - } - - camera.Dispose(); - } - } - - partial void DidScale(UIPinchGestureRecognizer gesture) - { - if (this.virtualObject != null && gesture.State == UIGestureRecognizerState.Changed) - { - var newScale = SCNVector3.Multiply(this.virtualObject.Scale, (float)gesture.Scale); - this.virtualObject.Scale = newScale; - gesture.Scale = 1f; - // Realistic reflections require an environment probe extent based on the size of the object, - // so update the environment probe when the object is resized. - this.requiresProbeRefresh = true; - } - } - - private void Place(SCNNode node, CGPoint location) - { - using (var hitTestResult = this.sceneView.SmartHitTest(location)) - { - if (hitTestResult != null) - { - this.sceneView.Scene.RootNode.AddChildNode(node); - this.virtualObject = node;// Remember that the object has been placed. - - node.Position = hitTestResult.WorldTransform.GetTranslation(); - - // Update the status UI to indicate the newly placed object. - var frame = this.sceneView.Session.CurrentFrame; - if (frame != null) - { - this.UpdateSessionInfoLabel(frame.Camera); - } - } - } - } - - #endregion - - private void InitializeVirtualObjectModel() - { - var sceneUrl = NSBundle.MainBundle.GetUrlForResource("sphere", "scn", "art.scnassets/sphere"); - if (sceneUrl != null) - { - var referenceNode = SCNReferenceNode.CreateFromUrl(sceneUrl); - if (referenceNode != null) - { - referenceNode.Load(); - this.virtualObjectModel = referenceNode; - } - } - - if (this.virtualObjectModel == null) - { - throw new Exception("can't load virtual object"); - } - } - } -} \ No newline at end of file +namespace EnvironmentTexturing { + /// <summary> + /// Main view controller for the AR experience. + /// </summary> + public partial class ViewController : UIViewController, IARSCNViewDelegate, IARSessionDelegate { + // Model of shiny sphere that is added to the scene + private SCNNode virtualObjectModel; + + // Environment Texturing Configuration + + // The virtual object that the user interacts with in the scene. + private SCNNode virtualObject; + + // An environment probe for shading that virtual object. + private AREnvironmentProbeAnchor environmentProbeAnchor; + + // A fallback environment probe encompassing the whole scene. + private AREnvironmentProbeAnchor sceneEnvironmentProbeAnchor; + + // Place environment probes manually or allow ARKit to place them automatically. + private AREnvironmentTexturing currentTexturingMode = AREnvironmentTexturing.Automatic; + + // Indicates whether manually placed probes need updating. + private bool requiresProbeRefresh = true; + + // Tracks timing of manual probe updates to prevent updating too frequently. + private double lastProbeAnchorUpdateTime; + + // Indicates whether ARKit has provided an environment texture. + private bool isEnvironmentTextureAvailable; + + // The latest screen touch position when a pan gesture is active + private CGPoint? lastPanTouchPosition; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.InitializeVirtualObjectModel (); + + this.sceneView.Delegate = this; + this.sceneView.Session.Delegate = this; + + switch (this.currentTexturingMode) { + case AREnvironmentTexturing.Manual: + this.textureModeSelectionControl.SelectedSegment = 1; + break; + case AREnvironmentTexturing.Automatic: + this.textureModeSelectionControl.SelectedSegment = 0; + break; + default: + throw new Exception ("This app supports only manual and automatic environment texturing."); + } + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + // Prevent the screen from dimming to avoid interrupting the AR experience. + UIApplication.SharedApplication.IdleTimerDisabled = true; + + // Start the AR session with automatic environment texturing. + this.sceneView.Session.Run (new ARWorldTrackingConfiguration { + PlaneDetection = ARPlaneDetection.Horizontal, + EnvironmentTexturing = AREnvironmentTexturing.Automatic + }); + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + this.sceneView.Session.Pause (); + } + + #region Session management + + partial void ChangeTextureMode (UISegmentedControl sender) + { + if (sender.SelectedSegment == 0) { + this.currentTexturingMode = AREnvironmentTexturing.Automatic; + this.environmentProbeAnchor?.Dispose (); + this.environmentProbeAnchor = null; + } else { + this.currentTexturingMode = AREnvironmentTexturing.Manual; + this.requiresProbeRefresh = true; + } + + // Remove anchors and change texturing mode + this.ResetTracking (true); + } + + partial void RestartExperience (NSObject sender) + { + if (this.virtualObject != null) { + this.virtualObject.RemoveFromParentNode (); + this.virtualObject = null; + } + + this.ResetTracking (); + } + + /// <summary> + /// Runs the session with a new AR configuration to change modes or reset the experience. + /// </summary> + private void ResetTracking (bool changeTextureMode = false) + { + var configuration = new ARWorldTrackingConfiguration (); + configuration.PlaneDetection = ARPlaneDetection.Horizontal; + configuration.EnvironmentTexturing = this.currentTexturingMode; + + var session = this.sceneView.Session; + if (changeTextureMode) { + // Remove existing environment probe anchors. + if (session.CurrentFrame?.Anchors != null) { + foreach (var anchor in session.CurrentFrame.Anchors) { + session.RemoveAnchor (anchor); + } + } + + // Don't reset tracking when changing modes in the same session. + session.Run (configuration); + } else { + session.Run (configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + } + + this.isEnvironmentTextureAvailable = false; + this.sceneEnvironmentProbeAnchor?.Dispose (); + this.sceneEnvironmentProbeAnchor = null; + configuration.Dispose (); + session.Dispose (); + } + + /// <summary> + /// Updates the UI to provide feedback on the state of the AR experience. + /// </summary> + private void UpdateSessionInfoLabel (ARCamera camera) + { + string message = null; + + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + message = "Tracking Unavailable"; + break; + + case ARTrackingState.Limited: + switch (camera.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: + message = "Tracking Limited\nExcessive motion - Try slowing down your movement, or reset the session."; + break; + + case ARTrackingStateReason.InsufficientFeatures: + message = "Tracking Limited\nLow detail - Try pointing at a flat surface, or reset the session."; + break; + + case ARTrackingStateReason.Initializing: + message = "Initializing"; + break; + + case ARTrackingStateReason.Relocalizing: + message = "Recovering from interruption"; + break; + } + break; + + case ARTrackingState.Normal: + if (this.virtualObject == null) { + if (this.isEnvironmentTextureAvailable) { + message = "Tap to place a sphere, then tap or drag to move it or pinch to scale it."; + } else { + message = "Generating environment texture."; + } + } + break; + } + + + // Show the message, or hide the label if there's no message. + DispatchQueue.MainQueue.DispatchAsync (() => { + if (this.sessionInfoLabel.Text != message) { + UIView.Animate (0.25d, () => { + this.sessionInfoLabel.Text = message; + if (!string.IsNullOrEmpty (message)) { + this.sessionInfoView.Alpha = 1; + } else { + this.sessionInfoView.Alpha = 0; + } + }); + } + }); + } + + #endregion + + #region Environment Texturing + + private void UpdateEnvironmentProbe (double time) + { + // Update the probe only if the object has been moved or scaled, + // only when manually placed, not too often. + if (this.virtualObject != null && + this.currentTexturingMode == AREnvironmentTexturing.Manual && + time - this.lastProbeAnchorUpdateTime >= 1d && + this.requiresProbeRefresh) { + // Remove existing probe anchor, if any. + var probeAnchor = this.environmentProbeAnchor; + if (probeAnchor != null) { + this.sceneView.Session.RemoveAnchor (probeAnchor); + this.environmentProbeAnchor.Dispose (); + this.environmentProbeAnchor = null; + } + + // Make sure the probe encompasses the object and provides some surrounding area to appear in reflections. + var extent = SCNVector3.Multiply (this.virtualObject.GetExtents (), this.virtualObject.Scale); + extent.X *= 3; // Reflect an area 3x the width of the object. + extent.Z *= 3; // Reflect an area 3x the depth of the object. + + // Also include some vertical area around the object, but keep the bottom of the probe at the + // bottom of the object so that it captures the real-world surface underneath. + var verticalOffset = new SCNVector3 (0, extent.Y, 0); + var transform = NMatrix4Extensions.CreateTranslation (this.virtualObject.Position + verticalOffset); + extent.Y *= 2; + + // Create the new environment probe anchor and add it to the session. + probeAnchor = new AREnvironmentProbeAnchor (transform, new OpenTK.NVector3 (extent.X, extent.Y, extent.Z)); + this.sceneView.Session.AddAnchor (probeAnchor); + + // Remember state to prevent updating the environment probe too often. + this.environmentProbeAnchor = probeAnchor; + this.lastProbeAnchorUpdateTime = CoreAnimation.CAAnimation.CurrentMediaTime (); + this.requiresProbeRefresh = false; + } + } + + private void UpdateSceneEnvironmentProbe (ARFrame frame) + { + if (this.sceneEnvironmentProbeAnchor == null && this.currentTexturingMode == AREnvironmentTexturing.Manual) { + // Create an environment probe anchor with room-sized extent to act as fallback when the probe anchor of + // an object is removed and added during translation and scaling + this.sceneEnvironmentProbeAnchor = new AREnvironmentProbeAnchor ("sceneProbe", OpenTK.NMatrix4.Identity, new OpenTK.NVector3 (5f, 5f, 5f)); + this.sceneView.Session.AddAnchor (this.sceneEnvironmentProbeAnchor); + } + } + + #endregion + + #region IARSCNViewDelegate + + [Export ("renderer:updateAtTime:")] + public void Update (ISCNSceneRenderer renderer, double timeInSeconds) + { + this.UpdateEnvironmentProbe (timeInSeconds); + } + + [Export ("renderer:didUpdateNode:forAnchor:")] + public void DidUpdateNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + { + // Check for whether any environment textures have been generated. + if (anchor is AREnvironmentProbeAnchor envProbeAnchor && !this.isEnvironmentTextureAvailable) { + this.isEnvironmentTextureAvailable = envProbeAnchor.EnvironmentTexture != null; + } + } + + #endregion + + #region ARSessionObserver + + [Export ("session:cameraDidChangeTrackingState:")] + public void CameraDidChangeTrackingState (ARSession session, ARCamera camera) + { + var frame = session.CurrentFrame; + if (frame == null) { + throw new Exception ("ARSession should have an ARFrame"); + } + + this.UpdateSessionInfoLabel (camera); + frame.Dispose (); + } + + [Export ("session:didFailWithError:")] + public void DidFail (ARSession session, NSError error) + { + this.ResetTracking (); + } + + [Export ("sessionShouldAttemptRelocalization:")] + public bool ShouldAttemptRelocalization (ARSession session) + { + return true; + } + + #endregion + + #region IARSessionDelegate + + [Export ("session:didUpdateFrame:")] + public void DidUpdateFrame (ARSession session, ARFrame frame) + { + this.UpdateSceneEnvironmentProbe (frame); + this.UpdateSessionInfoLabel (frame.Camera); + frame.Dispose (); + } + + #endregion + + #region Virtual Object gesture interaction + + partial void DidPan (UIPanGestureRecognizer gesture) + { + if (this.virtualObject != null) { + switch (gesture.State) { + case UIGestureRecognizerState.Changed: + var translation = gesture.TranslationInView (this.sceneView); + + var previousPosition = this.lastPanTouchPosition ?? CGPointExtensions.Create (this.sceneView.ProjectPoint (this.virtualObject.Position)); + // Calculate the new touch position + var currentPosition = new CGPoint (previousPosition.X + translation.X, previousPosition.Y + translation.Y); + using (var hitTestResult = this.sceneView.SmartHitTest (currentPosition)) { + if (hitTestResult != null) { + this.virtualObject.Position = hitTestResult.WorldTransform.GetTranslation (); + // Refresh the probe as the object keeps moving + this.requiresProbeRefresh = true; + } + } + + this.lastPanTouchPosition = currentPosition; + // reset the gesture's translation + gesture.SetTranslation (CGPoint.Empty, this.sceneView); + break; + + default: + // Clear the current position tracking. + this.lastPanTouchPosition = null; + break; + + } + } + } + + partial void DidTap (UITapGestureRecognizer gesture) + { + // Allow placing objects only when ARKit tracking is in a good state for hit testing, + // and environment texture is available (to prevent undesirable changes in reflected texture). + var camera = this.sceneView.Session.CurrentFrame?.Camera; + if (camera != null && camera.TrackingState == ARTrackingState.Normal && this.isEnvironmentTextureAvailable) { + var touchLocation = gesture.LocationInView (this.sceneView); + + if (this.virtualObject != null) { + using (var hitTestResult = this.sceneView.SmartHitTest (touchLocation)) { + if (hitTestResult != null) { + // Teleport the object to wherever the user touched the screen. + this.virtualObject.Position = hitTestResult.WorldTransform.GetTranslation (); + // Update the environment probe anchor when object is teleported. + this.requiresProbeRefresh = true; + } + } + } else { + // Add the object to the scene at the tap location. + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + this.Place (this.virtualObjectModel, touchLocation); + + // Newly added object requires an environment probe anchor. + this.requiresProbeRefresh = true; + }); + } + + camera.Dispose (); + } + } + + partial void DidScale (UIPinchGestureRecognizer gesture) + { + if (this.virtualObject != null && gesture.State == UIGestureRecognizerState.Changed) { + var newScale = SCNVector3.Multiply (this.virtualObject.Scale, (float) gesture.Scale); + this.virtualObject.Scale = newScale; + gesture.Scale = 1f; + // Realistic reflections require an environment probe extent based on the size of the object, + // so update the environment probe when the object is resized. + this.requiresProbeRefresh = true; + } + } + + private void Place (SCNNode node, CGPoint location) + { + using (var hitTestResult = this.sceneView.SmartHitTest (location)) { + if (hitTestResult != null) { + this.sceneView.Scene.RootNode.AddChildNode (node); + this.virtualObject = node;// Remember that the object has been placed. + + node.Position = hitTestResult.WorldTransform.GetTranslation (); + + // Update the status UI to indicate the newly placed object. + var frame = this.sceneView.Session.CurrentFrame; + if (frame != null) { + this.UpdateSessionInfoLabel (frame.Camera); + } + } + } + } + + #endregion + + private void InitializeVirtualObjectModel () + { + var sceneUrl = NSBundle.MainBundle.GetUrlForResource ("sphere", "scn", "art.scnassets/sphere"); + if (sceneUrl != null) { + var referenceNode = SCNReferenceNode.CreateFromUrl (sceneUrl); + if (referenceNode != null) { + referenceNode.Load (); + this.virtualObjectModel = referenceNode; + } + } + + if (this.virtualObjectModel == null) { + throw new Exception ("can't load virtual object"); + } + } + } +} diff --git a/ios11/EvenOddNumberDrag/EvenOddNumberDrag/AppDelegate.cs b/ios11/EvenOddNumberDrag/EvenOddNumberDrag/AppDelegate.cs index 9e39c70c4..bc08ca7af 100644 --- a/ios11/EvenOddNumberDrag/EvenOddNumberDrag/AppDelegate.cs +++ b/ios11/EvenOddNumberDrag/EvenOddNumberDrag/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace EvenOddNumberDrag -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace EvenOddNumberDrag { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios11/EvenOddNumberDrag/EvenOddNumberDrag/Main.cs b/ios11/EvenOddNumberDrag/EvenOddNumberDrag/Main.cs index 09044e531..996706603 100644 --- a/ios11/EvenOddNumberDrag/EvenOddNumberDrag/Main.cs +++ b/ios11/EvenOddNumberDrag/EvenOddNumberDrag/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace EvenOddNumberDrag -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace EvenOddNumberDrag { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/EvenOddNumberDrag/EvenOddNumberDrag/ViewController.cs b/ios11/EvenOddNumberDrag/EvenOddNumberDrag/ViewController.cs index 34acff86e..9b0c4e69c 100644 --- a/ios11/EvenOddNumberDrag/EvenOddNumberDrag/ViewController.cs +++ b/ios11/EvenOddNumberDrag/EvenOddNumberDrag/ViewController.cs @@ -1,127 +1,115 @@ -using System; +using System; using UIKit; using Foundation; -namespace EvenOddNumberDrag -{ - public partial class ViewController : UIViewController, IUIDragInteractionDelegate, IUIDropInteractionDelegate - { - #region Fields - - Random random; - UIDropInteraction evenDropInteraction; - UIDropInteraction oddDropInteraction; - - #endregion - - #region Constructors - - protected ViewController(IntPtr handle) : base(handle) { } - - #endregion - - #region UIViewController overrides - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - SetupDragAndDrop(); - - random = new Random(); - GenerateNumber(); - } - - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - } - - #endregion - - #region Methods - - protected void SetupDragAndDrop() - { - NumberLabel.UserInteractionEnabled = true; - EvenNumbersLabel.UserInteractionEnabled = true; - OddNumbersLabel.UserInteractionEnabled = true; - - var numberDragInteraction = new UIDragInteraction(this); - NumberLabel.AddInteraction(numberDragInteraction); - - // On iPad, this defaults to true. On iPhone, this defaults to - // false. Since this app should work on the iPhone, enable the the - // drag interaction. - numberDragInteraction.Enabled = true; - - evenDropInteraction = new UIDropInteraction(this); - EvenNumbersLabel.AddInteraction(evenDropInteraction); - oddDropInteraction = new UIDropInteraction(this); - OddNumbersLabel.AddInteraction(oddDropInteraction); - } - - protected void GenerateNumber() - { - NumberLabel.Text = random.Next(500).ToString(); - } - - #endregion - - #region IUIDragInteractionDelegate - - public UIDragItem[] GetItemsForBeginningSession(UIDragInteraction interaction, IUIDragSession session) - { - bool isEven = Convert.ToInt16(NumberLabel.Text) % 2 == 0; - var provider = new NSItemProvider(new NSString(NumberLabel.Text)); - var item = new UIDragItem(provider) - { - LocalObject = new NSNumber(isEven) - }; - return new UIDragItem[] { item }; - } - - #endregion - - #region IUIDropInteractionDelegate - - [Export("dropInteraction:sessionDidUpdate:")] - public UIDropProposal SessionDidUpdate(UIDropInteraction interaction, IUIDropSession session) - { - UIDropProposal proposal; - var isEven = (session.Items[0].LocalObject as NSNumber).BoolValue; - if( interaction == oddDropInteraction && !isEven ) - { - proposal = new UIDropProposal(UIDropOperation.Copy); - } - else if( interaction == evenDropInteraction && isEven ) - { - proposal = new UIDropProposal(UIDropOperation.Copy); - } - else - { - proposal = new UIDropProposal(UIDropOperation.Forbidden); - } - return proposal; - } - - [Export("dropInteraction:performDrop:")] - public void PerformDrop(UIDropInteraction interaction, IUIDropSession session) - { - var label = interaction == oddDropInteraction ? OddNumbersLabel : EvenNumbersLabel; - session.LoadObjects<NSString>(strings => - { - if (String.IsNullOrEmpty(label.Text)) - { - label.Text = strings[0]; - } - else - { - label.Text = $"{strings[0]}, {label.Text}"; - } - }); - GenerateNumber(); - } - #endregion - } +namespace EvenOddNumberDrag { + public partial class ViewController : UIViewController, IUIDragInteractionDelegate, IUIDropInteractionDelegate { + #region Fields + + Random random; + UIDropInteraction evenDropInteraction; + UIDropInteraction oddDropInteraction; + + #endregion + + #region Constructors + + protected ViewController (IntPtr handle) : base (handle) { } + + #endregion + + #region UIViewController overrides + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + SetupDragAndDrop (); + + random = new Random (); + GenerateNumber (); + } + + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + } + + #endregion + + #region Methods + + protected void SetupDragAndDrop () + { + NumberLabel.UserInteractionEnabled = true; + EvenNumbersLabel.UserInteractionEnabled = true; + OddNumbersLabel.UserInteractionEnabled = true; + + var numberDragInteraction = new UIDragInteraction (this); + NumberLabel.AddInteraction (numberDragInteraction); + + // On iPad, this defaults to true. On iPhone, this defaults to + // false. Since this app should work on the iPhone, enable the the + // drag interaction. + numberDragInteraction.Enabled = true; + + evenDropInteraction = new UIDropInteraction (this); + EvenNumbersLabel.AddInteraction (evenDropInteraction); + oddDropInteraction = new UIDropInteraction (this); + OddNumbersLabel.AddInteraction (oddDropInteraction); + } + + protected void GenerateNumber () + { + NumberLabel.Text = random.Next (500).ToString (); + } + + #endregion + + #region IUIDragInteractionDelegate + + public UIDragItem [] GetItemsForBeginningSession (UIDragInteraction interaction, IUIDragSession session) + { + bool isEven = Convert.ToInt16 (NumberLabel.Text) % 2 == 0; + var provider = new NSItemProvider (new NSString (NumberLabel.Text)); + var item = new UIDragItem (provider) { + LocalObject = new NSNumber (isEven) + }; + return new UIDragItem [] { item }; + } + + #endregion + + #region IUIDropInteractionDelegate + + [Export ("dropInteraction:sessionDidUpdate:")] + public UIDropProposal SessionDidUpdate (UIDropInteraction interaction, IUIDropSession session) + { + UIDropProposal proposal; + var isEven = (session.Items [0].LocalObject as NSNumber).BoolValue; + if (interaction == oddDropInteraction && !isEven) { + proposal = new UIDropProposal (UIDropOperation.Copy); + } else if (interaction == evenDropInteraction && isEven) { + proposal = new UIDropProposal (UIDropOperation.Copy); + } else { + proposal = new UIDropProposal (UIDropOperation.Forbidden); + } + return proposal; + } + + [Export ("dropInteraction:performDrop:")] + public void PerformDrop (UIDropInteraction interaction, IUIDropSession session) + { + var label = interaction == oddDropInteraction ? OddNumbersLabel : EvenNumbersLabel; + session.LoadObjects<NSString> (strings => { + if (String.IsNullOrEmpty (label.Text)) { + label.Text = strings [0]; + } else { + label.Text = $"{strings [0]}, {label.Text}"; + } + }); + GenerateNumber (); + } + #endregion + } } diff --git a/ios11/FaceIDSample/LocalAuthentication/AppDelegate.cs b/ios11/FaceIDSample/LocalAuthentication/AppDelegate.cs index 2a9c547fd..1727d95f9 100755 --- a/ios11/FaceIDSample/LocalAuthentication/AppDelegate.cs +++ b/ios11/FaceIDSample/LocalAuthentication/AppDelegate.cs @@ -1,49 +1,47 @@ -using System; - -using Foundation; -using UIKit; - -namespace StoryboardTable -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to - // application events from iOS. - [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window { - get; - set; - } - // - // This method is invoked when the application is about to move from active to inactive state. - // - // OpenGL applications should use this method to pause. - // - - - public override void OnResignActivation (UIApplication application) - { - } - - // This method should be used to release shared resources and it should store the application state. - // If your application supports background exection this method is called instead of WillTerminate - // when the user quits. - public override void DidEnterBackground (UIApplication application) - { - } - - // This method is called as part of the transiton from background to active state. - public override void WillEnterForeground (UIApplication application) - { - } - - // This method is called when the application is about to terminate. Save data, if needed. - public override void WillTerminate (UIApplication application) - { - } - } -} - +using System; + +using Foundation; +using UIKit; + +namespace StoryboardTable { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to + // application events from iOS. + [Register ("AppDelegate")] + public partial class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + // + // This method is invoked when the application is about to move from active to inactive state. + // + // OpenGL applications should use this method to pause. + // + + + public override void OnResignActivation (UIApplication application) + { + } + + // This method should be used to release shared resources and it should store the application state. + // If your application supports background exection this method is called instead of WillTerminate + // when the user quits. + public override void DidEnterBackground (UIApplication application) + { + } + + // This method is called as part of the transiton from background to active state. + public override void WillEnterForeground (UIApplication application) + { + } + + // This method is called when the application is about to terminate. Save data, if needed. + public override void WillTerminate (UIApplication application) + { + } + } +} + diff --git a/ios11/FaceIDSample/LocalAuthentication/AuthenticationViewController.cs b/ios11/FaceIDSample/LocalAuthentication/AuthenticationViewController.cs index db17c5341..142f650c5 100644 --- a/ios11/FaceIDSample/LocalAuthentication/AuthenticationViewController.cs +++ b/ios11/FaceIDSample/LocalAuthentication/AuthenticationViewController.cs @@ -3,8 +3,7 @@ using UIKit; using LocalAuthentication; -namespace StoryboardTable -{ +namespace StoryboardTable { /* * https://developer.apple.com/ios/human-interface-guidelines/user-interaction/authentication/ * @@ -20,140 +19,114 @@ namespace StoryboardTable /// /// *Remember* in iOS 11 to add the Info.plist key NSFaceIDUsageDescription /// </remarks> - partial class AuthenticationViewController : UIViewController - { - LAContextReplyHandler replyHandler; - /// <summary>String to use for display</summary> - string BiometryType = ""; + partial class AuthenticationViewController : UIViewController { + LAContextReplyHandler replyHandler; + /// <summary>String to use for display</summary> + string BiometryType = ""; - public AuthenticationViewController(IntPtr handle) : base(handle) - { - } + public AuthenticationViewController (IntPtr handle) : base (handle) + { + } - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); - // bind every time, to reflect deletion in the Detail view - unAuthenticatedLabel.Text = ""; + // bind every time, to reflect deletion in the Detail view + unAuthenticatedLabel.Text = ""; - var context = new LAContext(); - var buttonText = ""; - if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError1)) - { // has Biometrics (Touch or Face) - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { + var context = new LAContext (); + var buttonText = ""; + if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out var authError1)) { // has Biometrics (Touch or Face) + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { context.LocalizedReason = "Authorize for access to secrets"; // iOS 11 BiometryType = context.BiometryType == LABiometryType.TouchId ? "Touch ID" : "Face ID"; - buttonText = $"Login with {BiometryType}"; - } - else - { // no FaceID before iOS 11 - buttonText = $"Login with Touch ID"; - } - } - else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out var authError2)) - { + buttonText = $"Login with {BiometryType}"; + } else { // no FaceID before iOS 11 + buttonText = $"Login with Touch ID"; + } + } else if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthentication, out var authError2)) { buttonText = $"Login"; // with device PIN - BiometryType = "Device PIN"; - } - else - { - // Application might choose to implement a custom username/password - buttonText = "Use unsecured"; - BiometryType = "none"; - } - AuthenticateButton.SetTitle(buttonText, UIControlState.Normal); - } + BiometryType = "Device PIN"; + } else { + // Application might choose to implement a custom username/password + buttonText = "Use unsecured"; + BiometryType = "none"; + } + AuthenticateButton.SetTitle (buttonText, UIControlState.Normal); + } - partial void AuthenticateMe(UIButton sender) - { - var context = new LAContext(); - NSError AuthError; - var localizedReason = new NSString("To access secrets"); + partial void AuthenticateMe (UIButton sender) + { + var context = new LAContext (); + NSError AuthError; + var localizedReason = new NSString ("To access secrets"); - // because LocalAuthentication APIs have been extended over time, need to check iOS version before setting some properties - context.LocalizedFallbackTitle = "Fallback"; // iOS 8 + // because LocalAuthentication APIs have been extended over time, need to check iOS version before setting some properties + context.LocalizedFallbackTitle = "Fallback"; // iOS 8 - if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) - { - context.LocalizedCancelTitle = "Cancel"; // iOS 10 - } - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { - context.LocalizedReason = "Authorize for access to secrets"; // iOS 11 - BiometryType = context.BiometryType == LABiometryType.TouchId ? "TouchID" : "FaceID"; - } + if (UIDevice.CurrentDevice.CheckSystemVersion (10, 0)) { + context.LocalizedCancelTitle = "Cancel"; // iOS 10 + } + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { + context.LocalizedReason = "Authorize for access to secrets"; // iOS 11 + BiometryType = context.BiometryType == LABiometryType.TouchId ? "TouchID" : "FaceID"; + } - //Use canEvaluatePolicy method to test if device is TouchID or FaceID enabled - //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics - if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)) - { - Console.WriteLine("TouchID/FaceID available/enrolled"); - replyHandler = new LAContextReplyHandler((success, error) => - { - //Make sure it runs on MainThread, not in Background - this.InvokeOnMainThread(() => - { - if (success) - { - Console.WriteLine($"You logged in with {BiometryType}!"); + //Use canEvaluatePolicy method to test if device is TouchID or FaceID enabled + //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics + if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out AuthError)) { + Console.WriteLine ("TouchID/FaceID available/enrolled"); + replyHandler = new LAContextReplyHandler ((success, error) => { + //Make sure it runs on MainThread, not in Background + this.InvokeOnMainThread (() => { + if (success) { + Console.WriteLine ($"You logged in with {BiometryType}!"); - PerformSegue("AuthenticationSegue", this); - } - else - { - Console.WriteLine(error.LocalizedDescription); - //Show fallback mechanism here - unAuthenticatedLabel.Text = $"{BiometryType} Authentication Failed"; - //AuthenticateButton.Hidden = true; - } - }); + PerformSegue ("AuthenticationSegue", this); + } else { + Console.WriteLine (error.LocalizedDescription); + //Show fallback mechanism here + unAuthenticatedLabel.Text = $"{BiometryType} Authentication Failed"; + //AuthenticateButton.Hidden = true; + } + }); - }); - //Use evaluatePolicy to start authentication operation and show the UI as an Alert view - //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics - context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler); - } - else if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, out AuthError)) - { - Console.WriteLine("When TouchID/FaceID aren't available or enrolled, use the device PIN"); - replyHandler = new LAContextReplyHandler((success, error) => - { - //Make sure it runs on MainThread, not in Background - this.InvokeOnMainThread(() => - { - if (success) - { - Console.WriteLine($"You logged in with {BiometryType}!"); + }); + //Use evaluatePolicy to start authentication operation and show the UI as an Alert view + //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics + context.EvaluatePolicy (LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason, replyHandler); + } else if (context.CanEvaluatePolicy (LAPolicy.DeviceOwnerAuthentication, out AuthError)) { + Console.WriteLine ("When TouchID/FaceID aren't available or enrolled, use the device PIN"); + replyHandler = new LAContextReplyHandler ((success, error) => { + //Make sure it runs on MainThread, not in Background + this.InvokeOnMainThread (() => { + if (success) { + Console.WriteLine ($"You logged in with {BiometryType}!"); - PerformSegue("AuthenticationSegue", this); - } - else - { - Console.WriteLine(error.LocalizedDescription); - //Show fallback mechanism here - unAuthenticatedLabel.Text = "Device PIN Authentication Failed"; - AuthenticateButton.Hidden = true; - } - }); + PerformSegue ("AuthenticationSegue", this); + } else { + Console.WriteLine (error.LocalizedDescription); + //Show fallback mechanism here + unAuthenticatedLabel.Text = "Device PIN Authentication Failed"; + AuthenticateButton.Hidden = true; + } + }); - }); - //Use evaluatePolicy to start authentication operation and show the UI as an Alert view - //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics - context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthentication, localizedReason, replyHandler); - } - else - { - // User hasn't configured a PIN or any biometric auth. - // App may implement its own login, or choose to allow open access - unAuthenticatedLabel.Text = "No device auth configured"; + }); + //Use evaluatePolicy to start authentication operation and show the UI as an Alert view + //Use the LocalAuthentication Policy DeviceOwnerAuthenticationWithBiometrics + context.EvaluatePolicy (LAPolicy.DeviceOwnerAuthentication, localizedReason, replyHandler); + } else { + // User hasn't configured a PIN or any biometric auth. + // App may implement its own login, or choose to allow open access + unAuthenticatedLabel.Text = "No device auth configured"; - var okCancelAlertController = UIAlertController.Create("No authentication", "This device does't have authentication configured.", UIAlertControllerStyle.Alert); - okCancelAlertController.AddAction(UIAlertAction.Create("Use unsecured", UIAlertActionStyle.Default, alert => PerformSegue("AuthenticationSegue", this))); - okCancelAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine("Cancel was clicked"))); - PresentViewController(okCancelAlertController, true, null); - } - } + var okCancelAlertController = UIAlertController.Create ("No authentication", "This device does't have authentication configured.", UIAlertControllerStyle.Alert); + okCancelAlertController.AddAction (UIAlertAction.Create ("Use unsecured", UIAlertActionStyle.Default, alert => PerformSegue ("AuthenticationSegue", this))); + okCancelAlertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine ("Cancel was clicked"))); + PresentViewController (okCancelAlertController, true, null); + } + } } -} \ No newline at end of file +} diff --git a/ios11/FaceIDSample/LocalAuthentication/DetailViewController.cs b/ios11/FaceIDSample/LocalAuthentication/DetailViewController.cs index bb611e58a..898f87a29 100755 --- a/ios11/FaceIDSample/LocalAuthentication/DetailViewController.cs +++ b/ios11/FaceIDSample/LocalAuthentication/DetailViewController.cs @@ -1,52 +1,50 @@ -using System; -using System.Drawing; -using System.Collections.Generic; - -using MonoTouch.Foundation; -using MonoTouch.UIKit; - -namespace StoryboardTable -{ - public partial class DetailViewController : UIViewController - { - object detailItem; - - public DetailViewController (IntPtr handle) : base (handle) - { - } - - public void SetDetailItem (object newDetailItem) - { - if (detailItem != newDetailItem) { - detailItem = newDetailItem; - - // Update the view - ConfigureView (); - } - } - - void ConfigureView () - { - // Update the user interface for the detail item - if (IsViewLoaded && detailItem != null) - detailDescriptionLabel.Text = detailItem.ToString (); - } - - public override void DidReceiveMemoryWarning () - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning (); - - // Release any cached data, images, etc that aren't in use. - } - - public override void ViewDidLoad () - { - base.ViewDidLoad (); - - // Perform any additional setup after loading the view, typically from a nib. - ConfigureView (); - } - } -} - +using System; +using System.Drawing; +using System.Collections.Generic; + +using MonoTouch.Foundation; +using MonoTouch.UIKit; + +namespace StoryboardTable { + public partial class DetailViewController : UIViewController { + object detailItem; + + public DetailViewController (IntPtr handle) : base (handle) + { + } + + public void SetDetailItem (object newDetailItem) + { + if (detailItem != newDetailItem) { + detailItem = newDetailItem; + + // Update the view + ConfigureView (); + } + } + + void ConfigureView () + { + // Update the user interface for the detail item + if (IsViewLoaded && detailItem != null) + detailDescriptionLabel.Text = detailItem.ToString (); + } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Perform any additional setup after loading the view, typically from a nib. + ConfigureView (); + } + } +} + diff --git a/ios11/FaceIDSample/LocalAuthentication/Main.cs b/ios11/FaceIDSample/LocalAuthentication/Main.cs index f76366a47..8311c04fd 100755 --- a/ios11/FaceIDSample/LocalAuthentication/Main.cs +++ b/ios11/FaceIDSample/LocalAuthentication/Main.cs @@ -1,20 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -using Foundation; -using UIKit; - -namespace StoryboardTable -{ - public class Application - { - // This is the main entry point of the application. - static void Main (string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main (args, null, "AppDelegate"); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; + +using Foundation; +using UIKit; + +namespace StoryboardTable { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios11/FaceIDSample/LocalAuthentication/MasterViewController.cs b/ios11/FaceIDSample/LocalAuthentication/MasterViewController.cs index 48a36010c..744a0aae7 100755 --- a/ios11/FaceIDSample/LocalAuthentication/MasterViewController.cs +++ b/ios11/FaceIDSample/LocalAuthentication/MasterViewController.cs @@ -1,25 +1,23 @@ -using System; -using CoreGraphics; -using System.Collections.Generic; - -using Foundation; -using UIKit; - -namespace StoryboardTable -{ - public partial class MasterViewController : UITableViewController - { - public MasterViewController (IntPtr handle) : base (handle) - { - Title = "Secret Data"; - } - - public override void ViewWillAppear (bool animated) - { - base.ViewWillAppear (animated); - - // bind every time, to reflect deletion in the Detail view - TableView.Source = new SecretTableSource(); - } - } -} \ No newline at end of file +using System; +using CoreGraphics; +using System.Collections.Generic; + +using Foundation; +using UIKit; + +namespace StoryboardTable { + public partial class MasterViewController : UITableViewController { + public MasterViewController (IntPtr handle) : base (handle) + { + Title = "Secret Data"; + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + // bind every time, to reflect deletion in the Detail view + TableView.Source = new SecretTableSource (); + } + } +} diff --git a/ios11/FaceIDSample/LocalAuthentication/SecretItem.cs b/ios11/FaceIDSample/LocalAuthentication/SecretItem.cs index d2ae58b09..8f730d260 100644 --- a/ios11/FaceIDSample/LocalAuthentication/SecretItem.cs +++ b/ios11/FaceIDSample/LocalAuthentication/SecretItem.cs @@ -1,21 +1,21 @@ -using System; - -namespace StoryboardTable { - - /// <summary> - /// Represents a Chore. - /// </summary> - /// - public class SecretItem { - - public SecretItem () - { - } - - public int Id { get; set; } - public string Name { get; set; } - public string Notes { get; set; } - public bool Done { get; set; } - } -} - +using System; + +namespace StoryboardTable { + + /// <summary> + /// Represents a Chore. + /// </summary> + /// + public class SecretItem { + + public SecretItem () + { + } + + public int Id { get; set; } + public string Name { get; set; } + public string Notes { get; set; } + public bool Done { get; set; } + } +} + diff --git a/ios11/FaceIDSample/LocalAuthentication/SecretTableSource.cs b/ios11/FaceIDSample/LocalAuthentication/SecretTableSource.cs index e862078c8..d8e377d1d 100644 --- a/ios11/FaceIDSample/LocalAuthentication/SecretTableSource.cs +++ b/ios11/FaceIDSample/LocalAuthentication/SecretTableSource.cs @@ -1,40 +1,39 @@ -using System; +using System; using System.Collections.Generic; -using UIKit; - - -namespace StoryboardTable -{ - public class SecretTableSource : UITableViewSource { - - // there is NO database or storage of Tasks in this example, just an in-memory List<> - SecretItem[] tableItems; - string cellIdentifier = "taskcell"; // set in the Storyboard - - public SecretTableSource () - { +using UIKit; + + +namespace StoryboardTable { + public class SecretTableSource : UITableViewSource { + + // there is NO database or storage of Tasks in this example, just an in-memory List<> + SecretItem [] tableItems; + string cellIdentifier = "taskcell"; // set in the Storyboard + + public SecretTableSource () + { tableItems = new List<SecretItem> { new SecretItem() {Name="Gift list", Notes="iPhone X, Apple Watch, HomePod", Done=false}, new SecretItem() {Name="Reminders", Notes="buy flowers", Done=false} - }.ToArray(); - } - public override nint RowsInSection (UITableView tableview, nint section) - { - return tableItems.Length; - } - public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath) - { - // in a Storyboard, Dequeue will ALWAYS return a cell, - UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); - // now set the properties as normal - cell.TextLabel.Text = tableItems[indexPath.Row].Name; - cell.DetailTextLabel.Text = tableItems[indexPath.Row].Notes; - return cell; - } - public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) - { - tableView.DeselectRow(indexPath, true); - } - } -} - + }.ToArray (); + } + public override nint RowsInSection (UITableView tableview, nint section) + { + return tableItems.Length; + } + public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath) + { + // in a Storyboard, Dequeue will ALWAYS return a cell, + UITableViewCell cell = tableView.DequeueReusableCell (cellIdentifier); + // now set the properties as normal + cell.TextLabel.Text = tableItems [indexPath.Row].Name; + cell.DetailTextLabel.Text = tableItems [indexPath.Row].Notes; + return cell; + } + public override void RowSelected (UITableView tableView, Foundation.NSIndexPath indexPath) + { + tableView.DeselectRow (indexPath, true); + } + } +} + diff --git a/ios11/LargeTitlesSample/LargeTitles/AppDelegate.cs b/ios11/LargeTitlesSample/LargeTitles/AppDelegate.cs index 55ee6f1d0..d54e7daa5 100644 --- a/ios11/LargeTitlesSample/LargeTitles/AppDelegate.cs +++ b/ios11/LargeTitlesSample/LargeTitles/AppDelegate.cs @@ -1,42 +1,37 @@ -using Foundation; +using Foundation; using UIKit; -namespace largetitles -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace largetitles { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override UIWindow Window - { - get; - set; - } + public override UIWindow Window { + get; + set; + } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // < Back button color - UINavigationBar.Appearance.TintColor = UIColor.FromRGB(0xE7, 0x63, 0x3B); // e7963b dark - // Title bar background color - UINavigationBar.Appearance.BarTintColor = UIColor.FromRGB(0xF7, 0xE2, 0x8B); // f7e28b light - // 'small' Title bar text - UINavigationBar.Appearance.SetTitleTextAttributes(new UITextAttributes() - { - TextColor = UIColor.FromRGB(0xE7, 0x63, 0x3B), // e7963b dark - TextShadowColor = UIColor.Clear - }); - // 'Large' Title bar text - UINavigationBar.Appearance.LargeTitleTextAttributes = new UIStringAttributes - { - ForegroundColor = UIColor.FromRGB(0xE7, 0x63, 0x3B), // e7963b dark - }; + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // < Back button color + UINavigationBar.Appearance.TintColor = UIColor.FromRGB (0xE7, 0x63, 0x3B); // e7963b dark + // Title bar background color + UINavigationBar.Appearance.BarTintColor = UIColor.FromRGB (0xF7, 0xE2, 0x8B); // f7e28b light + // 'small' Title bar text + UINavigationBar.Appearance.SetTitleTextAttributes (new UITextAttributes () { + TextColor = UIColor.FromRGB (0xE7, 0x63, 0x3B), // e7963b dark + TextShadowColor = UIColor.Clear + }); + // 'Large' Title bar text + UINavigationBar.Appearance.LargeTitleTextAttributes = new UIStringAttributes { + ForegroundColor = UIColor.FromRGB (0xE7, 0x63, 0x3B), // e7963b dark + }; - return true; - } - } + return true; + } + } } diff --git a/ios11/LargeTitlesSample/LargeTitles/DetailViewController.cs b/ios11/LargeTitlesSample/LargeTitles/DetailViewController.cs index 3fd967f9f..9765a6cf0 100644 --- a/ios11/LargeTitlesSample/LargeTitles/DetailViewController.cs +++ b/ios11/LargeTitlesSample/LargeTitles/DetailViewController.cs @@ -1,41 +1,39 @@ -using System; -using UIKit; - -namespace largetitles -{ - public partial class DetailViewController : UIViewController - { - public override void ViewDidLoad() - { - NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Never; - - // to demonstrate layout - LargeLabel.BackgroundColor = UIColor.LightGray; - - var safeGuide = View.SafeAreaLayoutGuide; - LargeLabel.TopAnchor.ConstraintEqualTo(safeGuide.TopAnchor).Active = true; - LargeLabel.BottomAnchor.ConstraintEqualTo(safeGuide.BottomAnchor).Active = true; - //LargeLabel.LeadingAnchor.ConstraintEqualTo(safeGuide.LeadingAnchor).Active = true; - //LargeLabel.TrailingAnchor.ConstraintEqualTo(safeGuide.TrailingAnchor).Active = true; - - - var margins = View.LayoutMarginsGuide; - LargeLabel.TopAnchor.ConstraintEqualTo(margins.TopAnchor).Active = true; - LargeLabel.BottomAnchor.ConstraintEqualTo(margins.BottomAnchor).Active = true; - //LargeLabel.LeadingAnchor.ConstraintEqualTo(margins.LeadingAnchor).Active = true; - //LargeLabel.TrailingAnchor.ConstraintEqualTo(margins.TrailingAnchor).Active = true; - } - - public void SetTitle(string title) - { - Title = title; - LargeLabel.Text = $"The title \"{title}\" is {title.Length} characters long."; - } - - public DetailViewController(IntPtr handle) : base(handle) - { - LargeLabel = new UILabel(); - LargeLabel.Frame = new CoreGraphics.CGRect(10, 100, View.Bounds.Width - 20, View.Bounds.Height / 2); - } - } -} \ No newline at end of file +using System; +using UIKit; + +namespace largetitles { + public partial class DetailViewController : UIViewController { + public override void ViewDidLoad () + { + NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Never; + + // to demonstrate layout + LargeLabel.BackgroundColor = UIColor.LightGray; + + var safeGuide = View.SafeAreaLayoutGuide; + LargeLabel.TopAnchor.ConstraintEqualTo (safeGuide.TopAnchor).Active = true; + LargeLabel.BottomAnchor.ConstraintEqualTo (safeGuide.BottomAnchor).Active = true; + //LargeLabel.LeadingAnchor.ConstraintEqualTo(safeGuide.LeadingAnchor).Active = true; + //LargeLabel.TrailingAnchor.ConstraintEqualTo(safeGuide.TrailingAnchor).Active = true; + + + var margins = View.LayoutMarginsGuide; + LargeLabel.TopAnchor.ConstraintEqualTo (margins.TopAnchor).Active = true; + LargeLabel.BottomAnchor.ConstraintEqualTo (margins.BottomAnchor).Active = true; + //LargeLabel.LeadingAnchor.ConstraintEqualTo(margins.LeadingAnchor).Active = true; + //LargeLabel.TrailingAnchor.ConstraintEqualTo(margins.TrailingAnchor).Active = true; + } + + public void SetTitle (string title) + { + Title = title; + LargeLabel.Text = $"The title \"{title}\" is {title.Length} characters long."; + } + + public DetailViewController (IntPtr handle) : base (handle) + { + LargeLabel = new UILabel (); + LargeLabel.Frame = new CoreGraphics.CGRect (10, 100, View.Bounds.Width - 20, View.Bounds.Height / 2); + } + } +} diff --git a/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController+Search.cs b/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController+Search.cs index 51a7b6537..2e61616d7 100644 --- a/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController+Search.cs +++ b/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController+Search.cs @@ -1,41 +1,35 @@ -using Foundation; +using Foundation; using System; using UIKit; using System.Linq; -namespace largetitles -{ - public partial class LargeTitlesViewController : UITableViewController, IUITableViewDelegate, IUITableViewDataSource, IUISearchResultsUpdating - { - string[] searchResults; +namespace largetitles { + public partial class LargeTitlesViewController : UITableViewController, IUITableViewDelegate, IUITableViewDataSource, IUISearchResultsUpdating { + string [] searchResults; - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - var search = new UISearchController(searchResultsController: null) - { - DimsBackgroundDuringPresentation = false - }; - search.SearchResultsUpdater = this; + var search = new UISearchController (searchResultsController: null) { + DimsBackgroundDuringPresentation = false + }; + search.SearchResultsUpdater = this; // ensures the segue works in the context of the underling ViewController, thanks @artemkalinovsky DefinesPresentationContext = true; - NavigationItem.SearchController = search; - } + NavigationItem.SearchController = search; + } - public void UpdateSearchResultsForSearchController(UISearchController searchController) - { - var find = searchController.SearchBar.Text; - if (!String.IsNullOrEmpty(find)) - { - searchResults = titles.Where(t => t.ToLower().Contains(find.ToLower())).Select(p => p).ToArray(); - } - else - { - searchResults = null; - } - TableView.ReloadData(); - } - } -} \ No newline at end of file + public void UpdateSearchResultsForSearchController (UISearchController searchController) + { + var find = searchController.SearchBar.Text; + if (!String.IsNullOrEmpty (find)) { + searchResults = titles.Where (t => t.ToLower ().Contains (find.ToLower ())).Select (p => p).ToArray (); + } else { + searchResults = null; + } + TableView.ReloadData (); + } + } +} diff --git a/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController.cs b/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController.cs index 9568e413e..38fcc3fcc 100644 --- a/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController.cs +++ b/ios11/LargeTitlesSample/LargeTitles/LargeTitlesViewController.cs @@ -1,60 +1,58 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using System.Linq; -namespace largetitles -{ - public partial class LargeTitlesViewController : UITableViewController, IUITableViewDelegate, IUITableViewDataSource, IUISearchResultsUpdating - { - public LargeTitlesViewController (IntPtr handle) : base (handle) - { - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return searchResults == null ? titles.Length : searchResults.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("titlecell"); - cell.TextLabel.Text = searchResults == null ? titles[indexPath.Row] : searchResults[indexPath.Row]; - cell.DetailTextLabel.Text = ""; - return cell; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - TableView.DeselectRow(indexPath, true); - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - var dvc = segue.DestinationViewController as DetailViewController; - var indexPath = TableView.IndexPathForCell(sender as UITableViewCell); - var item = searchResults == null ? titles[indexPath.Row] : searchResults[indexPath.Row]; - dvc.SetTitle(item); - } +namespace largetitles { + public partial class LargeTitlesViewController : UITableViewController, IUITableViewDelegate, IUITableViewDataSource, IUISearchResultsUpdating { + public LargeTitlesViewController (IntPtr handle) : base (handle) + { + } - string[] titles = new string[] { - "The Ocean at the End of the Lane" - ,"So Long, and Thanks for All the Fish" - ,"Twenty Thousand Leagues Under the Sea" - ,"Rosencrantz and Guildenstern Are Dead" - ,"A Portrait of the Artist as a Young Man" - ,"Midnight in the Garden of Good and Evil" - ,"Miss Peregrine’s Home for Peculiar Children" - ,"Fried Green Tomatoes at the Whistle Stop Cafe" - ,"World War Z: An Oral History of the Zombie War" - ,"The Curious Incident of the Dog in the Night-Time" - ,"His Last Bow: Some Reminiscences of Sherlock Holmes" - ,"Zen and the Art of Motorcycle Maintenance: An Inquiry Into Values" - ,"The Princess Bride: S. Morgenstern's Classic Tale of True Love and High Adventure" - ,"Mr. William Shakespeares Comedies, Histories, and Tragedies: A Facsimile of the First Folio, 1623" - ,"Longitude: The True Story of a Lone Genius Who Solved the Greatest Scientific Problem of His Time" - ,"The Persecution and Assassination of Jean-Paul Marat as Performed by the Inmates of the Asylum of Charenton Under the Direction of the Marquis de Sade " - ,"Don't Get Too Comfortable: The Indignities of Coach Class, The Torments of Low Thread Count, The Never-Ending Quest for Artisanal Olive Oil, and Other First World Problems " - }; - } -} \ No newline at end of file + public override nint RowsInSection (UITableView tableView, nint section) + { + return searchResults == null ? titles.Length : searchResults.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("titlecell"); + cell.TextLabel.Text = searchResults == null ? titles [indexPath.Row] : searchResults [indexPath.Row]; + cell.DetailTextLabel.Text = ""; + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + TableView.DeselectRow (indexPath, true); + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + var dvc = segue.DestinationViewController as DetailViewController; + var indexPath = TableView.IndexPathForCell (sender as UITableViewCell); + var item = searchResults == null ? titles [indexPath.Row] : searchResults [indexPath.Row]; + dvc.SetTitle (item); + } + + string [] titles = new string [] { + "The Ocean at the End of the Lane" + ,"So Long, and Thanks for All the Fish" + ,"Twenty Thousand Leagues Under the Sea" + ,"Rosencrantz and Guildenstern Are Dead" + ,"A Portrait of the Artist as a Young Man" + ,"Midnight in the Garden of Good and Evil" + ,"Miss Peregrine’s Home for Peculiar Children" + ,"Fried Green Tomatoes at the Whistle Stop Cafe" + ,"World War Z: An Oral History of the Zombie War" + ,"The Curious Incident of the Dog in the Night-Time" + ,"His Last Bow: Some Reminiscences of Sherlock Holmes" + ,"Zen and the Art of Motorcycle Maintenance: An Inquiry Into Values" + ,"The Princess Bride: S. Morgenstern's Classic Tale of True Love and High Adventure" + ,"Mr. William Shakespeares Comedies, Histories, and Tragedies: A Facsimile of the First Folio, 1623" + ,"Longitude: The True Story of a Lone Genius Who Solved the Greatest Scientific Problem of His Time" + ,"The Persecution and Assassination of Jean-Paul Marat as Performed by the Inmates of the Asylum of Charenton Under the Direction of the Marquis de Sade " + ,"Don't Get Too Comfortable: The Indignities of Coach Class, The Torments of Low Thread Count, The Never-Ending Quest for Artisanal Olive Oil, and Other First World Problems " + }; + } +} diff --git a/ios11/LargeTitlesSample/LargeTitles/Main.cs b/ios11/LargeTitlesSample/LargeTitles/Main.cs index 1b1e77bd9..fc97463e4 100644 --- a/ios11/LargeTitlesSample/LargeTitles/Main.cs +++ b/ios11/LargeTitlesSample/LargeTitles/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace largetitles -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace largetitles { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/LargeTitlesSample/LargeTitles/NavigationController.cs b/ios11/LargeTitlesSample/LargeTitles/NavigationController.cs index 2d856b036..45aa5e60e 100644 --- a/ios11/LargeTitlesSample/LargeTitles/NavigationController.cs +++ b/ios11/LargeTitlesSample/LargeTitles/NavigationController.cs @@ -1,20 +1,18 @@ -using Foundation; -using System; -using UIKit; - -namespace largetitles -{ - public partial class NavigationController : UINavigationController - { - public NavigationController (IntPtr handle) : base (handle) - { - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - NavigationBar.PrefersLargeTitles = true; - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace largetitles { + public partial class NavigationController : UINavigationController { + public NavigationController (IntPtr handle) : base (handle) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + NavigationBar.PrefersLargeTitles = true; + } + } +} diff --git a/ios11/MapKitSample/Tandm/AppDelegate.cs b/ios11/MapKitSample/Tandm/AppDelegate.cs index f84c5d3ca..0a9b8c375 100644 --- a/ios11/MapKitSample/Tandm/AppDelegate.cs +++ b/ios11/MapKitSample/Tandm/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Tandm -{ +namespace Tandm { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/MapKitSample/Tandm/ClassExtensions/MKAnnotationWrapperExtensions.cs b/ios11/MapKitSample/Tandm/ClassExtensions/MKAnnotationWrapperExtensions.cs index 8a1411080..180a99818 100644 --- a/ios11/MapKitSample/Tandm/ClassExtensions/MKAnnotationWrapperExtensions.cs +++ b/ios11/MapKitSample/Tandm/ClassExtensions/MKAnnotationWrapperExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -6,13 +6,12 @@ using CoreGraphics; using CoreLocation; -namespace Tandm -{ - public static class MKAnnotationWrapperExtensions - { - public static MKClusterAnnotation UnwrapClusterAnnotation(IMKAnnotation annotation) { +namespace Tandm { + public static class MKAnnotationWrapperExtensions { + public static MKClusterAnnotation UnwrapClusterAnnotation (IMKAnnotation annotation) + { if (annotation == null) return null; - return ObjCRuntime.Runtime.GetNSObject(annotation.Handle) as MKClusterAnnotation; + return ObjCRuntime.Runtime.GetNSObject (annotation.Handle) as MKClusterAnnotation; } } } diff --git a/ios11/MapKitSample/Tandm/Classes/Bike.cs b/ios11/MapKitSample/Tandm/Classes/Bike.cs index bdd6ca726..94c86f0f2 100644 --- a/ios11/MapKitSample/Tandm/Classes/Bike.cs +++ b/ios11/MapKitSample/Tandm/Classes/Bike.cs @@ -1,29 +1,28 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using MapKit; using CoreLocation; -namespace Tandm -{ - public class Bike : MKPointAnnotation - { +namespace Tandm { + public class Bike : MKPointAnnotation { #region Static Methods - public static Bike[] FromDictionaryArray(NSArray dictionaryArray) { - var bikes = new List<Bike>(); + public static Bike [] FromDictionaryArray (NSArray dictionaryArray) + { + var bikes = new List<Bike> (); - for (nuint n = 0; n < dictionaryArray.Count; ++n){ - var dictionary = dictionaryArray.GetItem<NSDictionary<NSString, NSNumber>>(n); - if (dictionary !=null) { - var lat = dictionary[new NSString("lat")]; - var lgn = dictionary[new NSString("long")]; - var type = dictionary[new NSString("type")]; - bikes.Add(new Bike(lat, lgn, type)); + for (nuint n = 0; n < dictionaryArray.Count; ++n) { + var dictionary = dictionaryArray.GetItem<NSDictionary<NSString, NSNumber>> (n); + if (dictionary != null) { + var lat = dictionary [new NSString ("lat")]; + var lgn = dictionary [new NSString ("long")]; + var type = dictionary [new NSString ("type")]; + bikes.Add (new Bike (lat, lgn, type)); } } - return bikes.ToArray(); + return bikes.ToArray (); } #endregion @@ -32,22 +31,22 @@ public static Bike[] FromDictionaryArray(NSArray dictionaryArray) { #endregion #region Constructors - public Bike() + public Bike () { } - public Bike(NSNumber lat, NSNumber lgn, NSNumber type) + public Bike (NSNumber lat, NSNumber lgn, NSNumber type) { // Initialize - Coordinate = new CLLocationCoordinate2D(lat.NFloatValue, lgn.NFloatValue); + Coordinate = new CLLocationCoordinate2D (lat.NFloatValue, lgn.NFloatValue); - switch(type.NUIntValue) { - case 0: - Type = BikeType.Unicycle; - break; - case 1: - Type = BikeType.Tricycle; - break; + switch (type.NUIntValue) { + case 0: + Type = BikeType.Unicycle; + break; + case 1: + Type = BikeType.Tricycle; + break; } } #endregion diff --git a/ios11/MapKitSample/Tandm/Classes/BikeView.cs b/ios11/MapKitSample/Tandm/Classes/BikeView.cs index e809c5db8..4948189bc 100644 --- a/ios11/MapKitSample/Tandm/Classes/BikeView.cs +++ b/ios11/MapKitSample/Tandm/Classes/BikeView.cs @@ -1,45 +1,40 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using MapKit; using CoreLocation; -namespace Tandm -{ - [Register("BikeView")] - public class BikeView : MKMarkerAnnotationView - { +namespace Tandm { + [Register ("BikeView")] + public class BikeView : MKMarkerAnnotationView { #region Static Variables - public static UIColor UnicycleColor = UIColor.FromRGB(254, 122, 36); - public static UIColor TricycleColor = UIColor.FromRGB(153, 180, 44); + public static UIColor UnicycleColor = UIColor.FromRGB (254, 122, 36); + public static UIColor TricycleColor = UIColor.FromRGB (153, 180, 44); #endregion #region Override Methods - public override IMKAnnotation Annotation - { - get - { + public override IMKAnnotation Annotation { + get { return base.Annotation; } - set - { + set { base.Annotation = value; var bike = value as Bike; - if (bike != null){ + if (bike != null) { ClusteringIdentifier = "bike"; - switch(bike.Type){ - case BikeType.Unicycle: - MarkerTintColor = UnicycleColor; - GlyphImage = UIImage.FromBundle("Unicycle"); - DisplayPriority = MKFeatureDisplayPriority.DefaultLow; - break; - case BikeType.Tricycle: - MarkerTintColor = TricycleColor; - GlyphImage = UIImage.FromBundle("Tricycle"); - DisplayPriority = MKFeatureDisplayPriority.DefaultHigh; - break; + switch (bike.Type) { + case BikeType.Unicycle: + MarkerTintColor = UnicycleColor; + GlyphImage = UIImage.FromBundle ("Unicycle"); + DisplayPriority = MKFeatureDisplayPriority.DefaultLow; + break; + case BikeType.Tricycle: + MarkerTintColor = TricycleColor; + GlyphImage = UIImage.FromBundle ("Tricycle"); + DisplayPriority = MKFeatureDisplayPriority.DefaultHigh; + break; } } } @@ -47,22 +42,22 @@ public override IMKAnnotation Annotation #endregion #region Constructors - public BikeView() + public BikeView () { } - public BikeView(NSCoder coder) : base(coder) + public BikeView (NSCoder coder) : base (coder) { } - public BikeView(IntPtr handle) : base(handle) + public BikeView (IntPtr handle) : base (handle) { } - public BikeView(IMKAnnotation annotation, string identifier) : base(annotation, identifier) - { + public BikeView (IMKAnnotation annotation, string identifier) : base (annotation, identifier) + { - } + } #endregion diff --git a/ios11/MapKitSample/Tandm/Classes/ClusterView.cs b/ios11/MapKitSample/Tandm/Classes/ClusterView.cs index 1dd626df2..db91fded3 100644 --- a/ios11/MapKitSample/Tandm/Classes/ClusterView.cs +++ b/ios11/MapKitSample/Tandm/Classes/ClusterView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; @@ -6,62 +6,56 @@ using CoreGraphics; using CoreLocation; -namespace Tandm -{ - [Register("ClusterView")] - public class ClusterView : MKAnnotationView - { +namespace Tandm { + [Register ("ClusterView")] + public class ClusterView : MKAnnotationView { #region Static Variables - public static UIColor ClusterColor = UIColor.FromRGB(202, 150, 38); + public static UIColor ClusterColor = UIColor.FromRGB (202, 150, 38); #endregion #region Computed Properties - public override IMKAnnotation Annotation - { - get - { + public override IMKAnnotation Annotation { + get { return base.Annotation; } - set - { + set { base.Annotation = value; // TODO: Workaround, the developer should be able to use // `value as MKClusterAnnotation` instead of the following // extension method call: - var cluster = MKAnnotationWrapperExtensions.UnwrapClusterAnnotation(value); - if (cluster != null) - { - var renderer = new UIGraphicsImageRenderer(new CGSize(40, 40)); + var cluster = MKAnnotationWrapperExtensions.UnwrapClusterAnnotation (value); + if (cluster != null) { + var renderer = new UIGraphicsImageRenderer (new CGSize (40, 40)); var count = cluster.MemberAnnotations.Length; - var unicycleCount = CountBikeType(cluster.MemberAnnotations, BikeType.Unicycle); + var unicycleCount = CountBikeType (cluster.MemberAnnotations, BikeType.Unicycle); - Image = renderer.CreateImage((context) => { + Image = renderer.CreateImage ((context) => { // Fill full circle with tricycle color - BikeView.TricycleColor.SetFill(); - UIBezierPath.FromOval(new CGRect(0, 0, 40, 40)).Fill(); + BikeView.TricycleColor.SetFill (); + UIBezierPath.FromOval (new CGRect (0, 0, 40, 40)).Fill (); // Fill pie with unicycle color - BikeView.UnicycleColor.SetFill(); - var piePath = new UIBezierPath(); - piePath.AddArc(new CGPoint(20,20), 20, 0, (nfloat)(Math.PI * 2.0 * unicycleCount / count), true); - piePath.AddLineTo(new CGPoint(20, 20)); - piePath.ClosePath(); - piePath.Fill(); + BikeView.UnicycleColor.SetFill (); + var piePath = new UIBezierPath (); + piePath.AddArc (new CGPoint (20, 20), 20, 0, (nfloat) (Math.PI * 2.0 * unicycleCount / count), true); + piePath.AddLineTo (new CGPoint (20, 20)); + piePath.ClosePath (); + piePath.Fill (); // Fill inner circle with white color - UIColor.White.SetFill(); - UIBezierPath.FromOval(new CGRect(8, 8, 24, 24)).Fill(); + UIColor.White.SetFill (); + UIBezierPath.FromOval (new CGRect (8, 8, 24, 24)).Fill (); // Finally draw count text vertically and horizontally centered - var attributes = new UIStringAttributes() { + var attributes = new UIStringAttributes () { ForegroundColor = UIColor.Black, - Font = UIFont.BoldSystemFontOfSize(20) + Font = UIFont.BoldSystemFontOfSize (20) }; - var text = new NSString($"{count}"); - var size = text.GetSizeUsingAttributes(attributes); - var rect = new CGRect(20 - size.Width / 2, 20 - size.Height / 2, size.Width, size.Height); - text.DrawString(rect, attributes); + var text = new NSString ($"{count}"); + var size = text.GetSizeUsingAttributes (attributes); + var rect = new CGRect (20 - size.Width / 2, 20 - size.Height / 2, size.Width, size.Height); + text.DrawString (rect, attributes); }); } } @@ -69,34 +63,35 @@ public override IMKAnnotation Annotation #endregion #region Constructors - public ClusterView() + public ClusterView () { } - public ClusterView(NSCoder coder) : base(coder) + public ClusterView (NSCoder coder) : base (coder) { } - public ClusterView(IntPtr handle) : base(handle) + public ClusterView (IntPtr handle) : base (handle) { } - public ClusterView(IMKAnnotation annotation, string reuseIdentifier) : base(annotation, reuseIdentifier) + public ClusterView (IMKAnnotation annotation, string reuseIdentifier) : base (annotation, reuseIdentifier) { // Initialize DisplayPriority = MKFeatureDisplayPriority.DefaultHigh; CollisionMode = MKAnnotationViewCollisionMode.Circle; // Offset center point to animate better with marker annotations - CenterOffset = new CoreGraphics.CGPoint(0, -10); + CenterOffset = new CoreGraphics.CGPoint (0, -10); } #endregion #region Private Methods - private nuint CountBikeType(IMKAnnotation[] members, BikeType type) { + private nuint CountBikeType (IMKAnnotation [] members, BikeType type) + { nuint count = 0; - foreach(Bike member in members){ + foreach (Bike member in members) { if (member.Type == type) ++count; } diff --git a/ios11/MapKitSample/Tandm/Enums/BikeType.cs b/ios11/MapKitSample/Tandm/Enums/BikeType.cs index c2032ca5e..484e6bba5 100644 --- a/ios11/MapKitSample/Tandm/Enums/BikeType.cs +++ b/ios11/MapKitSample/Tandm/Enums/BikeType.cs @@ -1,8 +1,6 @@ -using System; -namespace Tandm -{ - public enum BikeType - { +using System; +namespace Tandm { + public enum BikeType { Unicycle, Tricycle } diff --git a/ios11/MapKitSample/Tandm/Main.cs b/ios11/MapKitSample/Tandm/Main.cs index ec4d43696..867a48d03 100644 --- a/ios11/MapKitSample/Tandm/Main.cs +++ b/ios11/MapKitSample/Tandm/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Tandm -{ - public class Application - { +namespace Tandm { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/MapKitSample/Tandm/ViewController.cs b/ios11/MapKitSample/Tandm/ViewController.cs index 637be96ef..88ea221b8 100644 --- a/ios11/MapKitSample/Tandm/ViewController.cs +++ b/ios11/MapKitSample/Tandm/ViewController.cs @@ -1,49 +1,49 @@ -using System; +using System; using Foundation; using UIKit; using MapKit; using CoreLocation; -namespace Tandm -{ - public partial class ViewController : UIViewController - { +namespace Tandm { + public partial class ViewController : UIViewController { #region Private Variables - private CLLocationManager LocationManager = new CLLocationManager(); + private CLLocationManager LocationManager = new CLLocationManager (); #endregion #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Private Methods - private void SetupCompassButton() { + private void SetupCompassButton () + { - var compass = MKCompassButton.FromMapView(MapView); + var compass = MKCompassButton.FromMapView (MapView); compass.CompassVisibility = MKFeatureVisibility.Visible; - NavigationItem.RightBarButtonItem = new UIBarButtonItem(compass); + NavigationItem.RightBarButtonItem = new UIBarButtonItem (compass); MapView.ShowsCompass = false; } - private void SetupUserTrackingAndScaleView() { + private void SetupUserTrackingAndScaleView () + { - var button = MKUserTrackingButton.FromMapView(MapView); - button.Layer.BackgroundColor = UIColor.FromRGBA(255,255,255,80).CGColor; + var button = MKUserTrackingButton.FromMapView (MapView); + button.Layer.BackgroundColor = UIColor.FromRGBA (255, 255, 255, 80).CGColor; button.Layer.BorderColor = UIColor.White.CGColor; button.Layer.BorderWidth = 1; button.Layer.CornerRadius = 5; button.TranslatesAutoresizingMaskIntoConstraints = false; - View.AddSubview(button); + View.AddSubview (button); - var scale = MKScaleView.FromMapView(MapView); + var scale = MKScaleView.FromMapView (MapView); scale.LegendAlignment = MKScaleViewAlignment.Trailing; scale.TranslatesAutoresizingMaskIntoConstraints = false; - View.AddSubview(scale); + View.AddSubview (scale); - NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[]{ + NSLayoutConstraint.ActivateConstraints (new NSLayoutConstraint []{ button.BottomAnchor.ConstraintEqualTo(View.BottomAnchor, -10), button.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor, -10), scale.TrailingAnchor.ConstraintEqualTo(button.LeadingAnchor, -10), @@ -51,66 +51,66 @@ private void SetupUserTrackingAndScaleView() { }); } - private void RegisterAnnotationViewClasses() { - MapView.Register(typeof(BikeView), MKMapViewDefault.AnnotationViewReuseIdentifier); - MapView.Register(typeof(ClusterView), MKMapViewDefault.ClusterAnnotationViewReuseIdentifier); + private void RegisterAnnotationViewClasses () + { + MapView.Register (typeof (BikeView), MKMapViewDefault.AnnotationViewReuseIdentifier); + MapView.Register (typeof (ClusterView), MKMapViewDefault.ClusterAnnotationViewReuseIdentifier); } - private void LoadDataForMapRegionAndBikes() { + private void LoadDataForMapRegionAndBikes () + { - var plist = NSDictionary.FromFile(NSBundle.MainBundle.PathForResource("Data", "plist")); - var region = plist["region"] as NSArray; - if (region !=null) { - var coordinate = new CLLocationCoordinate2D(region.GetItem<NSNumber>(0).NFloatValue, region.GetItem<NSNumber>(1).NFloatValue); - var span = new MKCoordinateSpan(region.GetItem<NSNumber>(2).NFloatValue, region.GetItem<NSNumber>(3).NFloatValue); - MapView.Region = new MKCoordinateRegion(coordinate, span); + var plist = NSDictionary.FromFile (NSBundle.MainBundle.PathForResource ("Data", "plist")); + var region = plist ["region"] as NSArray; + if (region != null) { + var coordinate = new CLLocationCoordinate2D (region.GetItem<NSNumber> (0).NFloatValue, region.GetItem<NSNumber> (1).NFloatValue); + var span = new MKCoordinateSpan (region.GetItem<NSNumber> (2).NFloatValue, region.GetItem<NSNumber> (3).NFloatValue); + MapView.Region = new MKCoordinateRegion (coordinate, span); } - var bikes = plist["bikes"] as NSArray; - if (bikes !=null) { - MapView.AddAnnotations(Bike.FromDictionaryArray(bikes)); + var bikes = plist ["bikes"] as NSArray; + if (bikes != null) { + MapView.AddAnnotations (Bike.FromDictionaryArray (bikes)); } } - private MKAnnotationView HandleMKMapViewAnnotation(MKMapView mapView, IMKAnnotation annotation) - { - if (annotation is Bike) { - var marker = annotation as Bike; - - var view = mapView.DequeueReusableAnnotation(MKMapViewDefault.AnnotationViewReuseIdentifier) as BikeView; - if (view == null) { - view = new BikeView(marker, MKMapViewDefault.AnnotationViewReuseIdentifier); - } - return view; - } - else if (annotation is MKClusterAnnotation) { - var cluster = annotation as MKClusterAnnotation; - - var view = mapView.DequeueReusableAnnotation(MKMapViewDefault.ClusterAnnotationViewReuseIdentifier) as ClusterView; - if (view == null) { - view = new ClusterView(cluster, MKMapViewDefault.ClusterAnnotationViewReuseIdentifier); - } - return view; - } - else if (annotation != null) { - var unwrappedAnnotation = MKAnnotationWrapperExtensions.UnwrapClusterAnnotation(annotation); - - return HandleMKMapViewAnnotation(mapView, unwrappedAnnotation); - } - return null; - } + private MKAnnotationView HandleMKMapViewAnnotation (MKMapView mapView, IMKAnnotation annotation) + { + if (annotation is Bike) { + var marker = annotation as Bike; + + var view = mapView.DequeueReusableAnnotation (MKMapViewDefault.AnnotationViewReuseIdentifier) as BikeView; + if (view == null) { + view = new BikeView (marker, MKMapViewDefault.AnnotationViewReuseIdentifier); + } + return view; + } else if (annotation is MKClusterAnnotation) { + var cluster = annotation as MKClusterAnnotation; + + var view = mapView.DequeueReusableAnnotation (MKMapViewDefault.ClusterAnnotationViewReuseIdentifier) as ClusterView; + if (view == null) { + view = new ClusterView (cluster, MKMapViewDefault.ClusterAnnotationViewReuseIdentifier); + } + return view; + } else if (annotation != null) { + var unwrappedAnnotation = MKAnnotationWrapperExtensions.UnwrapClusterAnnotation (annotation); + + return HandleMKMapViewAnnotation (mapView, unwrappedAnnotation); + } + return null; + } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - SetupCompassButton(); - SetupUserTrackingAndScaleView(); - RegisterAnnotationViewClasses(); - LoadDataForMapRegionAndBikes(); + SetupCompassButton (); + SetupUserTrackingAndScaleView (); + RegisterAnnotationViewClasses (); + LoadDataForMapRegionAndBikes (); - MapView.GetViewForAnnotation = HandleMKMapViewAnnotation; + MapView.GetViewForAnnotation = HandleMKMapViewAnnotation; } #endregion } diff --git a/ios11/MusicKitSample/MusicKitSample/AppDelegate.cs b/ios11/MusicKitSample/MusicKitSample/AppDelegate.cs index 3048fbc8c..53700fd04 100644 --- a/ios11/MusicKitSample/MusicKitSample/AppDelegate.cs +++ b/ios11/MusicKitSample/MusicKitSample/AppDelegate.cs @@ -1,15 +1,13 @@ -using Foundation; +using Foundation; using UIKit; using MusicKitSample.Controllers; using System; -namespace MusicKitSample -{ +namespace MusicKitSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { @@ -66,7 +64,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary recentlyPlayedTableViewController.MusicPlayerManager = MusicPlayerManager; } else throw new InvalidCastException ($"Unable to find expected {nameof (RecentlyPlayedTableViewController)} in at TabBar Index 3"); - + if (TopViewController (4) is MediaSearchTableViewController mediaSearchTableViewController) { mediaSearchTableViewController.AuthorizationManager = AuthorizationManager; mediaSearchTableViewController.MediaLibraryManager = MediaLibraryManager; @@ -80,7 +78,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary UIViewController TopViewController (int index) { if (Window.RootViewController is UITabBarController tabBarController && - tabBarController.ViewControllers [index] is UINavigationController navigationController) + tabBarController.ViewControllers [index] is UINavigationController navigationController) return navigationController.TopViewController; else throw new InvalidCastException ("Unable to find expected View Controller in Main.storyboard."); diff --git a/ios11/MusicKitSample/MusicKitSample/Controllers/AppleMusicManager.cs b/ios11/MusicKitSample/MusicKitSample/Controllers/AppleMusicManager.cs index 0c533dc80..9ba3e9faa 100644 --- a/ios11/MusicKitSample/MusicKitSample/Controllers/AppleMusicManager.cs +++ b/ios11/MusicKitSample/MusicKitSample/Controllers/AppleMusicManager.cs @@ -1,14 +1,12 @@ -using System; +using System; using Foundation; using MusicKitSample.Models; using MusicKitSample.Utilities; using System.Collections.Generic; using UIKit; using System.Threading.Tasks; -namespace MusicKitSample.Controllers -{ - public class AppleMusicManager - { +namespace MusicKitSample.Controllers { + public class AppleMusicManager { #region Properties // The instance of `URLSession` that is going to be used for making network calls. @@ -125,7 +123,7 @@ MediaItem [] [] ProcessMediaItemSections (NSData json) if (error != null) throw new NSErrorException (error); - + var results = jsonDictionary [ResponseRootJsonKeys.Results] as NSDictionary ?? throw new SerializationException (ResponseRootJsonKeys.Results); diff --git a/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationDataSource.cs b/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationDataSource.cs index 25bb4f20f..c2a857d0c 100644 --- a/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationDataSource.cs +++ b/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationDataSource.cs @@ -1,16 +1,13 @@ -using System; +using System; using StoreKit; using System.Collections.Generic; using Foundation; using MediaPlayer; using ObjCRuntime; -namespace MusicKitSample.Controllers -{ - public class AuthorizationDataSource - { +namespace MusicKitSample.Controllers { + public class AuthorizationDataSource { [Native] - enum SectionTypes : long - { + enum SectionTypes : long { MediaLibraryAuthorizationStatus = 0, CloudServiceAuthorizationStatus, RequestCapabilities @@ -67,7 +64,7 @@ public int NumberOfSections () public int NumberOfItems (long section) { - var sectionType = (SectionTypes)section; + var sectionType = (SectionTypes) section; switch (sectionType) { case SectionTypes.MediaLibraryAuthorizationStatus: @@ -82,7 +79,7 @@ public int NumberOfItems (long section) public string SectionTitle (long section) { - var sectionType = (SectionTypes)section; + var sectionType = (SectionTypes) section; switch (sectionType) { case SectionTypes.MediaLibraryAuthorizationStatus: @@ -98,7 +95,7 @@ public string SectionTitle (long section) public string StringForItem (NSIndexPath indexPath) { - var sectionType = (SectionTypes)indexPath.Section; + var sectionType = (SectionTypes) indexPath.Section; switch (sectionType) { case SectionTypes.MediaLibraryAuthorizationStatus: diff --git a/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationManager.cs b/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationManager.cs index c99fa6fbc..c68bf7ef7 100644 --- a/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationManager.cs +++ b/ios11/MusicKitSample/MusicKitSample/Controllers/AuthorizationManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using StoreKit; @@ -6,10 +6,8 @@ using UIKit; using MediaPlayer; -namespace MusicKitSample.Controllers -{ - public class AuthorizationManager : NSObject - { +namespace MusicKitSample.Controllers { + public class AuthorizationManager : NSObject { #region Fields NSObject CloudServiceCapabilitiesDidChangeNotificationToken; @@ -66,7 +64,7 @@ public AuthorizationManager (AppleMusicManager appleMusicManager) */ var notificationCenter = NSNotificationCenter.DefaultCenter; CloudServiceCapabilitiesDidChangeNotificationToken = notificationCenter.AddObserver (SKCloudServiceController.CloudServiceCapabilitiesDidChangeNotification, - async (obj) => await RequestCloudServiceCapabilitiesAsync ()); + async (obj) => await RequestCloudServiceCapabilitiesAsync ()); if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) StorefrontCountryCodeDidChangeNotificationToken = notificationCenter.AddObserver (SKCloudServiceController.StorefrontCountryCodeDidChangeNotification, diff --git a/ios11/MusicKitSample/MusicKitSample/Controllers/ImageCacheManager.cs b/ios11/MusicKitSample/MusicKitSample/Controllers/ImageCacheManager.cs index 84eb47c5e..5ce599326 100644 --- a/ios11/MusicKitSample/MusicKitSample/Controllers/ImageCacheManager.cs +++ b/ios11/MusicKitSample/MusicKitSample/Controllers/ImageCacheManager.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; using System.Threading.Tasks; -namespace MusicKitSample.Controllers -{ - public class ImageCacheManager - { +namespace MusicKitSample.Controllers { + public class ImageCacheManager { #region Fields NSCache imageCache; diff --git a/ios11/MusicKitSample/MusicKitSample/Controllers/MediaLibraryManager.cs b/ios11/MusicKitSample/MusicKitSample/Controllers/MediaLibraryManager.cs index a0783c3ca..6dc5c0755 100644 --- a/ios11/MusicKitSample/MusicKitSample/Controllers/MediaLibraryManager.cs +++ b/ios11/MusicKitSample/MusicKitSample/Controllers/MediaLibraryManager.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using MediaPlayer; using System.Threading.Tasks; using UIKit; -namespace MusicKitSample.Controllers -{ - public class MediaLibraryManager : NSObject - { +namespace MusicKitSample.Controllers { + public class MediaLibraryManager : NSObject { #region Types // The Key for the `UserDefaults` value representing the UUID of @@ -51,15 +49,15 @@ public MediaLibraryManager (AuthorizationManager authorizationManager) // events from the `AuthorizationManager`, // `MPMediaLibrary` and `UIApplication`. var notificationCenter = NSNotificationCenter.DefaultCenter; - authorizationDidUpdateNotificationToken = notificationCenter.AddObserver (AuthorizationManager.AuthorizationDidUpdateNotification, - HandleAuthorizationManagerAuthorizationDidUpdateNotification, - null); - didChangeNotificationToken = notificationCenter.AddObserver (MPMediaLibrary.DidChangeNotification, - HandleMediaLibraryDidChangeNotification, - null); + authorizationDidUpdateNotificationToken = notificationCenter.AddObserver (AuthorizationManager.AuthorizationDidUpdateNotification, + HandleAuthorizationManagerAuthorizationDidUpdateNotification, + null); + didChangeNotificationToken = notificationCenter.AddObserver (MPMediaLibrary.DidChangeNotification, + HandleMediaLibraryDidChangeNotification, + null); willEnterForegroundNotificationToken = notificationCenter.AddObserver (UIApplication.WillEnterForegroundNotification, - HandleMediaLibraryDidChangeNotification, - null); + HandleMediaLibraryDidChangeNotification, + null); HandleAuthorizationManagerAuthorizationDidUpdateNotification (null); } diff --git a/ios11/MusicKitSample/MusicKitSample/Controllers/MusicPlayerManager.cs b/ios11/MusicKitSample/MusicKitSample/Controllers/MusicPlayerManager.cs index 2eddc22d6..0ea046df9 100644 --- a/ios11/MusicKitSample/MusicKitSample/Controllers/MusicPlayerManager.cs +++ b/ios11/MusicKitSample/MusicKitSample/Controllers/MusicPlayerManager.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; using MediaPlayer; -namespace MusicKitSample.Controllers -{ - public class MusicPlayerManager : NSObject - { +namespace MusicKitSample.Controllers { + public class MusicPlayerManager : NSObject { #region Types // Notification that is fired when there is an update to the @@ -46,11 +44,11 @@ public MusicPlayerManager () var notificationCenter = NSNotificationCenter.DefaultCenter; nowPlayingItemDidChangeNotificationToken = notificationCenter.AddObserver (MPMusicPlayerController.NowPlayingItemDidChangeNotification, - HandleMusicPlayerControllerNowPlayingItemDidChange, - null); + HandleMusicPlayerControllerNowPlayingItemDidChange, + null); playbackStateDidChangeNotificationChangeToken = notificationCenter.AddObserver (MPMusicPlayerController.PlaybackStateDidChangeNotification, - HandleMusicPlayerControllerPlaybackStateDidChange, - null); + HandleMusicPlayerControllerPlaybackStateDidChange, + null); } #endregion diff --git a/ios11/MusicKitSample/MusicKitSample/Main.cs b/ios11/MusicKitSample/MusicKitSample/Main.cs index 94464409d..9840f95ed 100644 --- a/ios11/MusicKitSample/MusicKitSample/Main.cs +++ b/ios11/MusicKitSample/MusicKitSample/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace MusicKitSample -{ - public class Application - { +namespace MusicKitSample { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/ios11/MusicKitSample/MusicKitSample/Models/Artwork.cs b/ios11/MusicKitSample/MusicKitSample/Models/Artwork.cs index efa6cdf54..595470a46 100644 --- a/ios11/MusicKitSample/MusicKitSample/Models/Artwork.cs +++ b/ios11/MusicKitSample/MusicKitSample/Models/Artwork.cs @@ -1,4 +1,4 @@ -/* +/* Abstract: `Artwork` represents a `Artwork` object from the Apple Music Web Services. */ @@ -7,15 +7,12 @@ using Foundation; using System.Collections.Generic; using CoreGraphics; -namespace MusicKitSample.Models -{ - public class Artwork - { +namespace MusicKitSample.Models { + public class Artwork { #region Types // The various keys needed for serializing an instance of `Artwork` using a JSON response from the Apple Music Web Service. - struct JsonKeys - { + struct JsonKeys { public static readonly string Height = "height"; public static readonly string Width = "width"; public static readonly string Url = "url"; diff --git a/ios11/MusicKitSample/MusicKitSample/Models/MediaItem.cs b/ios11/MusicKitSample/MusicKitSample/Models/MediaItem.cs index 7094691d0..df5140fbb 100644 --- a/ios11/MusicKitSample/MusicKitSample/Models/MediaItem.cs +++ b/ios11/MusicKitSample/MusicKitSample/Models/MediaItem.cs @@ -1,20 +1,17 @@ -/* +/* Abstract: `MediaItem` represents a `Resource` object from the Apple Music Web Services. */ using System; using Foundation; -namespace MusicKitSample.Models -{ - public class MediaItem - { +namespace MusicKitSample.Models { + public class MediaItem { #region Types // The various keys needed for serializing an instance of `MediaItem` // using a Json response from the Apple Music Web Service. - struct JsonKeys - { + struct JsonKeys { public static readonly string Id = "id"; public static readonly string Type = "type"; public static readonly string Attributes = "attributes"; @@ -73,9 +70,9 @@ public static MediaItem From (NSDictionary json) var id = json [JsonKeys.Id]?.ToString () ?? throw new SerializationException (JsonKeys.Id); var typeString = json [JsonKeys.Type]?.ToString () ?? throw new SerializationException (JsonKeys.Type); - var type = (MediaType)Enum.Parse (typeof (MediaType), typeString, true); + var type = (MediaType) Enum.Parse (typeof (MediaType), typeString, true); - var attributes = json [JsonKeys.Attributes] as NSDictionary ?? + var attributes = json [JsonKeys.Attributes] as NSDictionary ?? throw new SerializationException (JsonKeys.Attributes); var name = attributes [JsonKeys.Name]?.ToString () ?? throw new SerializationException (JsonKeys.Name); diff --git a/ios11/MusicKitSample/MusicKitSample/Models/MediaType.cs b/ios11/MusicKitSample/MusicKitSample/Models/MediaType.cs index dffc8a59c..fd15c8df0 100644 --- a/ios11/MusicKitSample/MusicKitSample/Models/MediaType.cs +++ b/ios11/MusicKitSample/MusicKitSample/Models/MediaType.cs @@ -1,10 +1,8 @@ -using System; -namespace MusicKitSample.Models -{ +using System; +namespace MusicKitSample.Models { // - Songs: This indicates that the `MediaItem` is a song from the Apple Music Catalog. // - Albums: This indicates that the `MediaItem` is an album from the Apple Music Catalog. - public enum MediaType - { + public enum MediaType { Songs, Albums, Stations, diff --git a/ios11/MusicKitSample/MusicKitSample/Models/SerializationException.cs b/ios11/MusicKitSample/MusicKitSample/Models/SerializationException.cs index 2ca7ef740..b2c37f5ee 100644 --- a/ios11/MusicKitSample/MusicKitSample/Models/SerializationException.cs +++ b/ios11/MusicKitSample/MusicKitSample/Models/SerializationException.cs @@ -1,9 +1,7 @@ -using System; +using System; using System.Runtime.Serialization; -namespace MusicKitSample.Models -{ - public class SerializationException : Exception - { +namespace MusicKitSample.Models { + public class SerializationException : Exception { #region Properties public string JsonKey { get; private set; } @@ -14,7 +12,7 @@ public override string Message { if (!string.IsNullOrEmpty (JsonKey)) return message + Environment.NewLine + $"The key {JsonKey} is missing."; - + return message; } } diff --git a/ios11/MusicKitSample/MusicKitSample/Utilities/AppleMusicRequestFactory.cs b/ios11/MusicKitSample/MusicKitSample/Utilities/AppleMusicRequestFactory.cs index bf09b9377..0e92a2b91 100644 --- a/ios11/MusicKitSample/MusicKitSample/Utilities/AppleMusicRequestFactory.cs +++ b/ios11/MusicKitSample/MusicKitSample/Utilities/AppleMusicRequestFactory.cs @@ -1,4 +1,4 @@ -/* +/* Abstract: The `AppleMusicRequestFactory` type is used to build the various Apple Music API calls used by the sample. */ @@ -6,10 +6,8 @@ using System; using Foundation; using System.Collections.Generic; -namespace MusicKitSample.Utilities -{ - public struct AppleMusicRequestFactory - { +namespace MusicKitSample.Utilities { + public struct AppleMusicRequestFactory { #region Types // The base URL for all Apple Music API network calls. @@ -70,7 +68,7 @@ public static NSUrlRequest CreateRecentlyPlayedRequest (string developerToken, s // Create and configure the `URLRequest`. var urlRequest = new NSMutableUrlRequest (urlComponents.Url) { HttpMethod = "GET" }; urlRequest.Headers = new NSDictionary ("Authorization", $"Bearer {developerToken}", - "Music-User-Token", userToken); + "Music-User-Token", userToken); return urlRequest; } @@ -83,7 +81,7 @@ public static NSUrlRequest CreateGetUserStorefrontRequest (string developerToken // Create and configure the `URLRequest`. var urlRequest = new NSMutableUrlRequest (urlComponents.Url) { HttpMethod = "GET" }; urlRequest.Headers = new NSDictionary ("Authorization", $"Bearer {developerToken}", - "Music-User-Token", userToken); + "Music-User-Token", userToken); return urlRequest; } diff --git a/ios11/MusicKitSample/MusicKitSample/Utilities/JsonKeys.cs b/ios11/MusicKitSample/MusicKitSample/Utilities/JsonKeys.cs index 4a44d3d01..f5c9c90e0 100644 --- a/ios11/MusicKitSample/MusicKitSample/Utilities/JsonKeys.cs +++ b/ios11/MusicKitSample/MusicKitSample/Utilities/JsonKeys.cs @@ -1,29 +1,25 @@ -/* +/* Abstract: Various JSON keys needed when making calls to the Apple Music API. */ using System; -namespace MusicKitSample.Utilities -{ +namespace MusicKitSample.Utilities { // Keys related to the `Response Root` JSON object in the Apple Music API. - public struct ResponseRootJsonKeys - { + public struct ResponseRootJsonKeys { public static readonly string Data = "data"; public static readonly string Results = "results"; } // Keys related to the `Resource` JSON object in the Apple Music API. - public struct ResourceJsonKeys - { + public struct ResourceJsonKeys { public static readonly string Id = "id"; public static readonly string Attributes = "attributes"; public static readonly string Type = "type"; } // The various keys needed for parsing a JSON response from the Apple Music Web Service. - public struct ResourceTypeJsonKeys - { + public struct ResourceTypeJsonKeys { public static readonly string Songs = "songs"; public static readonly string Albums = "albums"; } diff --git a/ios11/MusicKitSample/MusicKitSample/Views/AuthorizationTableViewController.cs b/ios11/MusicKitSample/MusicKitSample/Views/AuthorizationTableViewController.cs index 31849877a..78ef9beea 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/AuthorizationTableViewController.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/AuthorizationTableViewController.cs @@ -10,10 +10,8 @@ using MediaPlayer; using System.Threading.Tasks; -namespace MusicKitSample -{ - public partial class AuthorizationTableViewController : UITableViewController, ISKCloudServiceSetupViewControllerDelegate - { +namespace MusicKitSample { + public partial class AuthorizationTableViewController : UITableViewController, ISKCloudServiceSetupViewControllerDelegate { #region Fields NSObject cloudServiceDidUpdateNotificationToken; @@ -59,14 +57,14 @@ public override void ViewDidLoad () // from the `AuthorizationManager` and `UIApplication`. var notificationCenter = NSNotificationCenter.DefaultCenter; cloudServiceDidUpdateNotificationToken = notificationCenter.AddObserver (AuthorizationManager.CloudServiceDidUpdateNotification, - HandleAuthorizationManagerDidUpdateNotification, - null); + HandleAuthorizationManagerDidUpdateNotification, + null); authorizationDidUpdateNotificationToken = notificationCenter.AddObserver (AuthorizationManager.AuthorizationDidUpdateNotification, - HandleAuthorizationManagerDidUpdateNotification, - null); + HandleAuthorizationManagerDidUpdateNotification, + null); willEnterForegroundNotificationToken = notificationCenter.AddObserver (UIApplication.WillEnterForegroundNotification, - HandleAuthorizationManagerDidUpdateNotification, - null); + HandleAuthorizationManagerDidUpdateNotification, + null); SetAuthorizationRequestButtonState (); } @@ -98,7 +96,7 @@ protected override void Dispose (bool disposing) void SetAuthorizationRequestButtonState () { if (SKCloudServiceController.AuthorizationStatus == SKCloudServiceAuthorizationStatus.NotDetermined || - MPMediaLibrary.AuthorizationStatus == MPMediaLibraryAuthorizationStatus.NotDetermined) + MPMediaLibrary.AuthorizationStatus == MPMediaLibraryAuthorizationStatus.NotDetermined) NavigationItem.RightBarButtonItem.Enabled = true; else NavigationItem.RightBarButtonItem.Enabled = false; @@ -174,13 +172,13 @@ async Task PresentCloudServiceSetupAsync () void HandleAuthorizationManagerDidUpdateNotification (NSNotification notification) { if (SKCloudServiceController.AuthorizationStatus == SKCloudServiceAuthorizationStatus.NotDetermined || - MPMediaLibrary.AuthorizationStatus == MPMediaLibraryAuthorizationStatus.NotDetermined) { + MPMediaLibrary.AuthorizationStatus == MPMediaLibraryAuthorizationStatus.NotDetermined) { NavigationItem.RightBarButtonItem.Enabled = true; } else { NavigationItem.RightBarButtonItem.Enabled = false; if (AuthorizationManager.CloudServiceCapabilities.HasFlag (SKCloudServiceCapability.MusicCatalogSubscriptionEligible) && - AuthorizationManager.CloudServiceCapabilities.HasFlag (SKCloudServiceCapability.MusicCatalogPlayback)) { + AuthorizationManager.CloudServiceCapabilities.HasFlag (SKCloudServiceCapability.MusicCatalogPlayback)) { PresentCloudServiceSetupAsync (); } } diff --git a/ios11/MusicKitSample/MusicKitSample/Views/MediaItemTableViewCell.cs b/ios11/MusicKitSample/MusicKitSample/Views/MediaItemTableViewCell.cs index f2f7c43e6..1e46f9e2a 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/MediaItemTableViewCell.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/MediaItemTableViewCell.cs @@ -1,13 +1,11 @@ -using System; +using System; using Foundation; using UIKit; using MusicKitSample.Models; -namespace MusicKitSample -{ - public partial class MediaItemTableViewCell : UITableViewCell - { +namespace MusicKitSample { + public partial class MediaItemTableViewCell : UITableViewCell { #region Cell Identifier public static readonly NSString Key = new NSString ("MediaItemTableViewCell"); @@ -82,8 +80,7 @@ partial void BtnPlayItem_TouchUpInside (UIButton sender) #endregion } - public interface IMediaSearchTableViewCellDelegate - { + public interface IMediaSearchTableViewCellDelegate { void AddToPlaylist (MediaItemTableViewCell mediaSearchTableViewCell, MediaItem mediaItem); void PlayMediaItem (MediaItemTableViewCell mediaSearchTableViewCell, MediaItem mediaItem); } diff --git a/ios11/MusicKitSample/MusicKitSample/Views/MediaSearchTableViewController.cs b/ios11/MusicKitSample/MusicKitSample/Views/MediaSearchTableViewController.cs index d643363fe..f646cb0f5 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/MediaSearchTableViewController.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/MediaSearchTableViewController.cs @@ -11,10 +11,8 @@ using CoreGraphics; using StoreKit; -namespace MusicKitSample -{ - public partial class MediaSearchTableViewController : UITableViewController, IUISearchResultsUpdating, IUISearchBarDelegate, IMediaSearchTableViewCellDelegate - { +namespace MusicKitSample { + public partial class MediaSearchTableViewController : UITableViewController, IUISearchResultsUpdating, IUISearchBarDelegate, IMediaSearchTableViewCellDelegate { #region Fields static readonly object padlock = new object (); @@ -91,12 +89,12 @@ public override void ViewDidLoad () * Settings app the application will reflect those changes accurately. */ var notificationCenter = NSNotificationCenter.DefaultCenter; - authorizationDidUpdateNotificationToken = notificationCenter.AddObserver (AuthorizationManager.AuthorizationDidUpdateNotification, - HandleAuthorizationManagerAuthorizationDidUpdateNotification, - null); - willEnterForegroundNotificationToken = notificationCenter.AddObserver (UIApplication.WillEnterForegroundNotification, - HandleAuthorizationManagerAuthorizationDidUpdateNotification, - null); + authorizationDidUpdateNotificationToken = notificationCenter.AddObserver (AuthorizationManager.AuthorizationDidUpdateNotification, + HandleAuthorizationManagerAuthorizationDidUpdateNotification, + null); + willEnterForegroundNotificationToken = notificationCenter.AddObserver (UIApplication.WillEnterForegroundNotification, + HandleAuthorizationManagerAuthorizationDidUpdateNotification, + null); } protected override void Dispose (bool disposing) diff --git a/ios11/MusicKitSample/MusicKitSample/Views/PlayerViewController.cs b/ios11/MusicKitSample/MusicKitSample/Views/PlayerViewController.cs index d6b2e6ee1..55927131d 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/PlayerViewController.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/PlayerViewController.cs @@ -7,11 +7,9 @@ using MusicKitSample.Controllers; using MediaPlayer; -namespace MusicKitSample -{ - public partial class PlayerViewController : UIViewController - { - +namespace MusicKitSample { + public partial class PlayerViewController : UIViewController { + #region Fields NSObject didUpdateStateToken; @@ -43,8 +41,8 @@ public override void ViewDidLoad () // Add the notification observer needed to respond to events // from the `MusicPlayerManager`. didUpdateStateToken = NSNotificationCenter.DefaultCenter.AddObserver (MusicPlayerManager.DidUpdateState, - HandleMusicPlayerManagerDidUpdateState, - null); + HandleMusicPlayerManagerDidUpdateState, + null); UpdatePlaybackControls (); UpdateCurrentItemMetadata (); diff --git a/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewCell.cs b/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewCell.cs index 30667b2b7..473375e83 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewCell.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewCell.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace MusicKitSample -{ - public partial class PlaylistTableViewCell : UITableViewCell - { +namespace MusicKitSample { + public partial class PlaylistTableViewCell : UITableViewCell { #region Cell Identifier public static readonly NSString Key = new NSString ("PlaylistTableViewCell"); diff --git a/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewController.cs b/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewController.cs index 36def3776..d9dc06d94 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewController.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/PlaylistTableViewController.cs @@ -8,10 +8,8 @@ using StoreKit; using CoreGraphics; -namespace MusicKitSample -{ - public partial class PlaylistTableViewController : UITableViewController - { +namespace MusicKitSample { + public partial class PlaylistTableViewController : UITableViewController { #region Fields NSObject libraryDidUpdateToken; @@ -54,9 +52,9 @@ public override void ViewDidLoad () // Add the notification observer needed to respond to events // from the `MediaLibraryManager`. - libraryDidUpdateToken = NSNotificationCenter.DefaultCenter.AddObserver (MediaLibraryManager.LibraryDidUpdate, - HandleMediaLibraryManagerLibraryDidUpdate, - null); + libraryDidUpdateToken = NSNotificationCenter.DefaultCenter.AddObserver (MediaLibraryManager.LibraryDidUpdate, + HandleMediaLibraryManagerLibraryDidUpdate, + null); } protected override void Dispose (bool disposing) diff --git a/ios11/MusicKitSample/MusicKitSample/Views/RecentlyPlayedTableViewController.cs b/ios11/MusicKitSample/MusicKitSample/Views/RecentlyPlayedTableViewController.cs index 593b34bdb..8958f5ddb 100644 --- a/ios11/MusicKitSample/MusicKitSample/Views/RecentlyPlayedTableViewController.cs +++ b/ios11/MusicKitSample/MusicKitSample/Views/RecentlyPlayedTableViewController.cs @@ -10,10 +10,8 @@ using System.Threading.Tasks; using StoreKit; -namespace MusicKitSample -{ - public partial class RecentlyPlayedTableViewController : UITableViewController, IMediaSearchTableViewCellDelegate - { +namespace MusicKitSample { + public partial class RecentlyPlayedTableViewController : UITableViewController, IMediaSearchTableViewCellDelegate { #region Fields static readonly object padlock = new object (); @@ -142,7 +140,7 @@ async Task RefreshData () InvokeOnMainThread (() => TableView.ReloadData ()); } } - + #endregion #region MediaItemTableViewCell Delegate diff --git a/ios11/MusicKitSample/MusicKitTokenGenerator/MusicKitTokenGenerator/Program.cs b/ios11/MusicKitSample/MusicKitTokenGenerator/MusicKitTokenGenerator/Program.cs index 0fd83c7ec..80c6ee95f 100644 --- a/ios11/MusicKitSample/MusicKitTokenGenerator/MusicKitTokenGenerator/Program.cs +++ b/ios11/MusicKitSample/MusicKitTokenGenerator/MusicKitTokenGenerator/Program.cs @@ -1,53 +1,51 @@ -using System; -using System.IO; -using System.Linq; -using System.Collections.Generic; -using System.Security.Cryptography; - -using Jose; -using Org.BouncyCastle.Crypto.Parameters; -using Org.BouncyCastle.OpenSsl; - -namespace MusicKitTokenGenerator -{ - class Program - { - static void Main(string[] args) - { - Console.WriteLine ("----- GENERATING TOKEN -----"); - - var token = GenerateToken (); - - Console.WriteLine ("----- GENERATED TOKEN -----"); - Console.WriteLine ($"{token}\n"); - } - - static string GenerateToken() - { - var algorithm = "ES256"; - - /* - * The Key ID of your MusicKit Private key: - * https://developer.apple.com/account/ios/authkey/ - * For more information, go to Apple Music API Reference: - * https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/AppleMusicWebServicesReference/SetUpWebServices.html#//apple_ref/doc/uid/TP40017625-CH2-SW1 - */ - var keyId = "«MusicKit_Private_Key_ID»"; - Console.WriteLine ($"Your MusicKit Private Key ID: {keyId}"); - - // Your Team ID from your Apple Developer Account: - // https://developer.apple.com/account/#/membership/ - var teamId = "«Team_ID»"; - Console.WriteLine ($"Your Apple Team ID: {keyId}"); - - var utcNow = DateTime.UtcNow; - var epoch = new DateTime (1970, 1, 1); - var epochNow = (int)utcNow.Subtract (epoch).TotalSeconds; - var utcExpire = utcNow.AddMonths (6); - var epochExpire = (int)utcExpire.Subtract(epoch).TotalSeconds; - - Console.WriteLine ($"The Token was issued at (UTC Time): {utcNow.ToString ("yyyy/MM/dd")}"); - Console.WriteLine ($"The Token will expire at (UTC Time): {utcExpire.ToString ("yyyy/MM/dd")}\n"); +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using System.Security.Cryptography; + +using Jose; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.OpenSsl; + +namespace MusicKitTokenGenerator { + class Program { + static void Main (string [] args) + { + Console.WriteLine ("----- GENERATING TOKEN -----"); + + var token = GenerateToken (); + + Console.WriteLine ("----- GENERATED TOKEN -----"); + Console.WriteLine ($"{token}\n"); + } + + static string GenerateToken () + { + var algorithm = "ES256"; + + /* + * The Key ID of your MusicKit Private key: + * https://developer.apple.com/account/ios/authkey/ + * For more information, go to Apple Music API Reference: + * https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/AppleMusicWebServicesReference/SetUpWebServices.html#//apple_ref/doc/uid/TP40017625-CH2-SW1 + */ + var keyId = "«MusicKit_Private_Key_ID»"; + Console.WriteLine ($"Your MusicKit Private Key ID: {keyId}"); + + // Your Team ID from your Apple Developer Account: + // https://developer.apple.com/account/#/membership/ + var teamId = "«Team_ID»"; + Console.WriteLine ($"Your Apple Team ID: {keyId}"); + + var utcNow = DateTime.UtcNow; + var epoch = new DateTime (1970, 1, 1); + var epochNow = (int) utcNow.Subtract (epoch).TotalSeconds; + var utcExpire = utcNow.AddMonths (6); + var epochExpire = (int) utcExpire.Subtract (epoch).TotalSeconds; + + Console.WriteLine ($"The Token was issued at (UTC Time): {utcNow.ToString ("yyyy/MM/dd")}"); + Console.WriteLine ($"The Token will expire at (UTC Time): {utcExpire.ToString ("yyyy/MM/dd")}\n"); var headers = new Dictionary<string, object> { @@ -60,32 +58,31 @@ static string GenerateToken() { "iat", epochNow }, { "exp", epochExpire } }; - - var headersString = string.Join ($",\n{" ",4}", headers.Select (kv => $"{kv.Key}: {kv.Value}")); - Console.WriteLine ($"Headers to be encoded:"); - Console.WriteLine ($"{{\n{" ",4}{headersString}\n}}\n"); - - var payloadString = string.Join ($",\n{" ",4}", payload.Select (kv => $"{kv.Key}: {kv.Value}")); - Console.WriteLine ($"Payload to be encoded:"); - Console.WriteLine ($"{{\n{" ", 4}{payloadString}\n}}\n"); - - var parameters = GetPrivateParameters(); - var secretKey = ECDsa.Create (parameters); - var token = JWT.Encode (payload, secretKey, JwsAlgorithm.ES256, headers); - - return token; + + var headersString = string.Join ($",\n{" ",4}", headers.Select (kv => $"{kv.Key}: {kv.Value}")); + Console.WriteLine ($"Headers to be encoded:"); + Console.WriteLine ($"{{\n{" ",4}{headersString}\n}}\n"); + + var payloadString = string.Join ($",\n{" ",4}", payload.Select (kv => $"{kv.Key}: {kv.Value}")); + Console.WriteLine ($"Payload to be encoded:"); + Console.WriteLine ($"{{\n{" ",4}{payloadString}\n}}\n"); + + var parameters = GetPrivateParameters (); + var secretKey = ECDsa.Create (parameters); + var token = JWT.Encode (payload, secretKey, JwsAlgorithm.ES256, headers); + + return token; } - static ECParameters GetPrivateParameters() + static ECParameters GetPrivateParameters () { - using (var reader = File.OpenText("/path/to/your/MusicKit_Secret_Key.p8")) - { - var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader (reader).ReadObject (); + using (var reader = File.OpenText ("/path/to/your/MusicKit_Secret_Key.p8")) { + var ecPrivateKeyParameters = (ECPrivateKeyParameters) new PemReader (reader).ReadObject (); var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded (); var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded (); - var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned (); + var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned (); - var parameters = new ECParameters { + var parameters = new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = d, Q = new ECPoint { @@ -96,6 +93,6 @@ static ECParameters GetPrivateParameters() return parameters; } - } - } -} + } + } +} diff --git a/ios11/NFCTagReader/NFCTagReader/AppDelegate.cs b/ios11/NFCTagReader/NFCTagReader/AppDelegate.cs index 7568c1bad..1132aa2cc 100644 --- a/ios11/NFCTagReader/NFCTagReader/AppDelegate.cs +++ b/ios11/NFCTagReader/NFCTagReader/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace NFCTagReader -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace NFCTagReader { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios11/NFCTagReader/NFCTagReader/Main.cs b/ios11/NFCTagReader/NFCTagReader/Main.cs index 8e07ba03b..89c5f7a4e 100644 --- a/ios11/NFCTagReader/NFCTagReader/Main.cs +++ b/ios11/NFCTagReader/NFCTagReader/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace NFCTagReader -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace NFCTagReader { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/NFCTagReader/NFCTagReader/MessagesTableViewController.cs b/ios11/NFCTagReader/NFCTagReader/MessagesTableViewController.cs index 527878f6d..e76305441 100644 --- a/ios11/NFCTagReader/NFCTagReader/MessagesTableViewController.cs +++ b/ios11/NFCTagReader/NFCTagReader/MessagesTableViewController.cs @@ -1,124 +1,118 @@ -using System; +using System; using CoreNFC; using UIKit; using Foundation; using CoreFoundation; using System.Collections.Generic; -namespace NFCTagReader -{ - public partial class MessagesTableViewController : UITableViewController, INFCNdefReaderSessionDelegate - { +namespace NFCTagReader { + public partial class MessagesTableViewController : UITableViewController, INFCNdefReaderSessionDelegate { - public MessagesTableViewController(IntPtr p) : base(p) - { + public MessagesTableViewController (IntPtr p) : base (p) + { } - public MessagesTableViewController() : base("MessagesTableViewController", null) - { - } + public MessagesTableViewController () : base ("MessagesTableViewController", null) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + // Perform any additional setup after loading the view, typically from a nib. + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - // Perform any additional setup after loading the view, typically from a nib. - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + // Release any cached data, images, etc that aren't in use. + } - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - // Release any cached data, images, etc that aren't in use. - } + #region Properties - #region Properties + List<NFCNdefMessage> DetectedMessages = new List<NFCNdefMessage> { }; + NFCNdefReaderSession Session; + string CellIdentifier = "reuseIdentifier"; - List<NFCNdefMessage> DetectedMessages = new List<NFCNdefMessage> { }; - NFCNdefReaderSession Session; - string CellIdentifier = "reuseIdentifier"; + partial void Scan (UIBarButtonItem sender) + { + Session = new NFCNdefReaderSession (this, null, true); + if (Session != null) { + Session.BeginSession (); + } + } - partial void Scan(UIBarButtonItem sender) - { - Session = new NFCNdefReaderSession(this, null, true); - if (Session != null) - { - Session.BeginSession(); - } - } + #endregion - #endregion + #region NFCNDEFReaderSessionDelegate - #region NFCNDEFReaderSessionDelegate + public void DidDetect (NFCNdefReaderSession session, NFCNdefMessage [] messages) + { + foreach (NFCNdefMessage msg in messages) { + DetectedMessages.Add (msg); + } + DispatchQueue.MainQueue.DispatchAsync (() => { + this.TableView.ReloadData (); + }); + } - public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages) - { - foreach (NFCNdefMessage msg in messages) - { - DetectedMessages.Add(msg); - } - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.TableView.ReloadData(); - }); - } + public void DidInvalidate (NFCNdefReaderSession session, NSError error) + { - public void DidInvalidate(NFCNdefReaderSession session, NSError error) - { + var readerError = (NFCReaderError) (long) error.Code; - var readerError = (NFCReaderError)(long)error.Code; + if (readerError != NFCReaderError.ReaderSessionInvalidationErrorFirstNDEFTagRead && + readerError != NFCReaderError.ReaderSessionInvalidationErrorUserCanceled) { + BeginInvokeOnMainThread (() => { + var alertController = UIAlertController.Create ("Session Invalidated", error.LocalizedDescription, UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); + PresentViewController (alertController, true, null); + }); + } - if (readerError != NFCReaderError.ReaderSessionInvalidationErrorFirstNDEFTagRead && - readerError != NFCReaderError.ReaderSessionInvalidationErrorUserCanceled) - { - BeginInvokeOnMainThread (() => { - var alertController = UIAlertController.Create ("Session Invalidated", error.LocalizedDescription, UIAlertControllerStyle.Alert); - alertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); - PresentViewController (alertController, true, null); - }); - } + } - } + #endregion - #endregion + #region DataSource - #region DataSource + public override nint RowsInSection (UITableView tableView, nint section) + { + return DetectedMessages.Count; + } - public override nint RowsInSection(UITableView tableView, nint section) - { - return DetectedMessages.Count; - } + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier); + string item = $"{DetectedMessages [indexPath.Row].Records.Length.ToString ()} payload(s)"; - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); - string item = $"{DetectedMessages[indexPath.Row].Records.Length.ToString()} payload(s)"; + //---- if there are no cells to reuse, create a new one + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); } - //---- if there are no cells to reuse, create a new one - if (cell == null) - { cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier); } + cell.TextLabel.Text = item; - cell.TextLabel.Text = item; + return cell; + } - return cell; - } + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender){ + var indexPath = TableView.IndexPathForSelectedRow; + if (indexPath != null) { + var payloadsTableViewController = (PayloadsTableViewController) segue.DestinationViewController; + payloadsTableViewController.Payloads = DetectedMessages [indexPath.Row].Records; - var indexPath = TableView.IndexPathForSelectedRow; - if (indexPath != null){ - var payloadsTableViewController = (PayloadsTableViewController)segue.DestinationViewController; - payloadsTableViewController.Payloads = DetectedMessages[indexPath.Row].Records; - - } + } - } + } #endregion diff --git a/ios11/NFCTagReader/NFCTagReader/PayloadsTableViewController.cs b/ios11/NFCTagReader/NFCTagReader/PayloadsTableViewController.cs index 7b9d5d109..65a0d40b2 100644 --- a/ios11/NFCTagReader/NFCTagReader/PayloadsTableViewController.cs +++ b/ios11/NFCTagReader/NFCTagReader/PayloadsTableViewController.cs @@ -1,109 +1,96 @@ -using System; +using System; using CoreNFC; using UIKit; using Foundation; using CoreFoundation; using System.Collections.Generic; -namespace NFCTagReader -{ - public partial class PayloadsTableViewController : UITableViewController - { - public PayloadsTableViewController() : base("PayloadsTableViewController", null) - { - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - // Perform any additional setup after loading the view, typically from a nib. - } - - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - // Release any cached data, images, etc that aren't in use. - } - - #region Properties - - public NFCNdefPayload[] Payloads = new NFCNdefPayload[] { }; - string CellIdentifier = "reuseIdentifier"; - - #endregion - - - #region DataSource - - public override nint RowsInSection(UITableView tableView, nint section) - { - return Payloads.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); - - var payload = Payloads[indexPath.Row]; - - //---- if there are no cells to reuse, create a new one - if (cell == null) - { cell = new UITableViewCell(UITableViewCellStyle.Default, CellIdentifier); } - - switch (payload.TypeNameFormat) - { - case NFCTypeNameFormat.NFCWellKnown: - var type = new NSString(payload.Type, NSStringEncoding.UTF8); - if (type != null) - { - cell.TextLabel.Text = $"NFC Well Known type: {type}"; - } - else - { - cell.TextLabel.Text = "Invalid data"; - } - break; - case NFCTypeNameFormat.AbsoluteUri: - var text = new NSString(payload.Payload, NSStringEncoding.UTF8); - if (text != null) - { - cell.TextLabel.Text = text; - } - else - { - cell.TextLabel.Text = "Invalid data"; - } - break; - case NFCTypeNameFormat.Media: - var mediaType = new NSString(payload.Type, NSStringEncoding.UTF8); - if (mediaType != null) - { - cell.TextLabel.Text = $"Media type: {mediaType}"; - } - else - { - cell.TextLabel.Text = "Invalid data"; - } - break; - case NFCTypeNameFormat.NFCExternal: - cell.TextLabel.Text = "NFC External type"; - break; - case NFCTypeNameFormat.Unknown: - cell.TextLabel.Text = "Unknown type"; - break; - case NFCTypeNameFormat.Unchanged: - cell.TextLabel.Text = "Unchanged type"; - break; - default: - cell.TextLabel.Text = "Invalid data"; - break; - } - - - return cell; - } - - #endregion - } +namespace NFCTagReader { + public partial class PayloadsTableViewController : UITableViewController { + public PayloadsTableViewController () : base ("PayloadsTableViewController", null) + { + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + // Perform any additional setup after loading the view, typically from a nib. + } + + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + // Release any cached data, images, etc that aren't in use. + } + + #region Properties + + public NFCNdefPayload [] Payloads = new NFCNdefPayload [] { }; + string CellIdentifier = "reuseIdentifier"; + + #endregion + + + #region DataSource + + public override nint RowsInSection (UITableView tableView, nint section) + { + return Payloads.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + UITableViewCell cell = tableView.DequeueReusableCell (CellIdentifier); + + var payload = Payloads [indexPath.Row]; + + //---- if there are no cells to reuse, create a new one + if (cell == null) { cell = new UITableViewCell (UITableViewCellStyle.Default, CellIdentifier); } + + switch (payload.TypeNameFormat) { + case NFCTypeNameFormat.NFCWellKnown: + var type = new NSString (payload.Type, NSStringEncoding.UTF8); + if (type != null) { + cell.TextLabel.Text = $"NFC Well Known type: {type}"; + } else { + cell.TextLabel.Text = "Invalid data"; + } + break; + case NFCTypeNameFormat.AbsoluteUri: + var text = new NSString (payload.Payload, NSStringEncoding.UTF8); + if (text != null) { + cell.TextLabel.Text = text; + } else { + cell.TextLabel.Text = "Invalid data"; + } + break; + case NFCTypeNameFormat.Media: + var mediaType = new NSString (payload.Type, NSStringEncoding.UTF8); + if (mediaType != null) { + cell.TextLabel.Text = $"Media type: {mediaType}"; + } else { + cell.TextLabel.Text = "Invalid data"; + } + break; + case NFCTypeNameFormat.NFCExternal: + cell.TextLabel.Text = "NFC External type"; + break; + case NFCTypeNameFormat.Unknown: + cell.TextLabel.Text = "Unknown type"; + break; + case NFCTypeNameFormat.Unchanged: + cell.TextLabel.Text = "Unchanged type"; + break; + default: + cell.TextLabel.Text = "Invalid data"; + break; + } + + + return cell; + } + + #endregion + } } diff --git a/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/AppDelegate.cs b/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/AppDelegate.cs index 8f391c4a6..61d69ff67 100644 --- a/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/AppDelegate.cs +++ b/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace PDFAnnotationWidgetsAdvanced -{ +namespace PDFAnnotationWidgetsAdvanced { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/Main.cs b/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/Main.cs index c7c3b8690..862cecb96 100644 --- a/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/Main.cs +++ b/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace PDFAnnotationWidgetsAdvanced -{ - public class Application - { +namespace PDFAnnotationWidgetsAdvanced { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/ViewController.cs b/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/ViewController.cs index f2975339e..0e1d45f2b 100644 --- a/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/ViewController.cs +++ b/ios11/PDFAnnotationWidgetsAdvanced/PDFAnnotationWidgetsAdvanced/ViewController.cs @@ -1,11 +1,10 @@ -using System; +using System; using UIKit; using PdfKit; using CoreGraphics; using Foundation; -namespace PDFAnnotationWidgetsAdvanced -{ +namespace PDFAnnotationWidgetsAdvanced { /** ViewController first loads a path to our MyForm.pdf file through the application's main bundle. This URL is then used to instantiate a PDFDocument. On success, the document is assigned to our PDFView, which @@ -23,25 +22,24 @@ explicitly set the widgetControlType. See the README for more detail on both widget annotation creation, and in-depth explanations regarding the widget-specific properties. */ - public partial class ViewController : UIViewController - { + public partial class ViewController : UIViewController { #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Load our simple PDF document, retrieve the first page - var documentURL = NSBundle.MainBundle.GetUrlForResource("MyForm", "pdf"); - if (documentURL !=null) { - var document = new PdfDocument(documentURL); - var page = document.GetPage(0); + var documentURL = NSBundle.MainBundle.GetUrlForResource ("MyForm", "pdf"); + if (documentURL != null) { + var document = new PdfDocument (documentURL); + var page = document.GetPage (0); // Set our document to the view, center it, and set a background color PDFView.Document = document; @@ -49,137 +47,137 @@ public override void ViewDidLoad() PDFView.BackgroundColor = UIColor.LightGray; // Add Name: and Date: fields - InsertFormFields(page); + InsertFormFields (page); // Add Question 1 widgets: "Have you been to a music festival before?" - InsertRadioButtons(page); + InsertRadioButtons (page); // Add Question 2 widgets: "Which of the following music festivals have you attended?" - InsertCheckBoxes(page); + InsertCheckBoxes (page); // Question 3: "Give one recommendation to improve a music festival:" - InsertMultilineTextBox(page); + InsertMultilineTextBox (page); // Reset Form - InsertResetButton(page); + InsertResetButton (page); } } #endregion #region Private methods - private void InsertFormFields(PdfPage page){ + private void InsertFormFields (PdfPage page) + { - var bounds = page.GetBoundsForBox(PdfDisplayBox.Crop); + var bounds = page.GetBoundsForBox (PdfDisplayBox.Crop); - var textFieldNameBox = new CGRect(169, bounds.Height - 102, 371, 23); - var textFieldName = new PdfAnnotation(textFieldNameBox, PdfAnnotationSubtype.Widget.GetConstant(), null){ - WidgetFieldType = PdfAnnotationWidgetSubtype.Text.GetConstant(), - BackgroundColor = UIColor.Blue.ColorWithAlpha(0.25f), - Font = UIFont.SystemFontOfSize(18) + var textFieldNameBox = new CGRect (169, bounds.Height - 102, 371, 23); + var textFieldName = new PdfAnnotation (textFieldNameBox, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Text.GetConstant (), + BackgroundColor = UIColor.Blue.ColorWithAlpha (0.25f), + Font = UIFont.SystemFontOfSize (18) }; - page.AddAnnotation(textFieldName); + page.AddAnnotation (textFieldName); - var textFieldDateBounds = new CGRect(283, bounds.Height - 135, 257, 22); - var textFieldDate = new PdfAnnotation(textFieldDateBounds, PdfAnnotationSubtype.Widget.GetConstant(), null){ - WidgetFieldType = PdfAnnotationWidgetSubtype.Text.GetConstant(), - BackgroundColor = UIColor.Blue.ColorWithAlpha(0.25f), - Font = UIFont.SystemFontOfSize(18), + var textFieldDateBounds = new CGRect (283, bounds.Height - 135, 257, 22); + var textFieldDate = new PdfAnnotation (textFieldDateBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Text.GetConstant (), + BackgroundColor = UIColor.Blue.ColorWithAlpha (0.25f), + Font = UIFont.SystemFontOfSize (18), MaximumLength = 5, Comb = true }; - page.AddAnnotation(textFieldDate); + page.AddAnnotation (textFieldDate); } - private void InsertRadioButtons(PdfPage page) { + private void InsertRadioButtons (PdfPage page) + { - var bounds = page.GetBoundsForBox(PdfDisplayBox.Crop); + var bounds = page.GetBoundsForBox (PdfDisplayBox.Crop); // Yes button - var radioButtonYesBounds = new CGRect(135, bounds.Height - 249, 24, 24); - var radioButtonYes = new PdfAnnotation(radioButtonYesBounds, PdfAnnotationSubtype.Widget.GetConstant(), null){ - WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant(), + var radioButtonYesBounds = new CGRect (135, bounds.Height - 249, 24, 24); + var radioButtonYes = new PdfAnnotation (radioButtonYesBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant (), WidgetControlType = PdfWidgetControlType.RadioButton, - FieldName ="Radio Button", + FieldName = "Radio Button", ButtonWidgetStateString = "Yes" }; - page.AddAnnotation(radioButtonYes); + page.AddAnnotation (radioButtonYes); // Yes button - var radioButtonNoBounds = new CGRect(210, bounds.Height - 249, 24, 24); - var radioButtonNo = new PdfAnnotation(radioButtonNoBounds, PdfAnnotationSubtype.Widget.GetConstant(), null) - { - WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant(), + var radioButtonNoBounds = new CGRect (210, bounds.Height - 249, 24, 24); + var radioButtonNo = new PdfAnnotation (radioButtonNoBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant (), WidgetControlType = PdfWidgetControlType.RadioButton, FieldName = "Radio Button", ButtonWidgetStateString = "No" }; - page.AddAnnotation(radioButtonNo); + page.AddAnnotation (radioButtonNo); } - private void InsertCheckBoxes(PdfPage page){ + private void InsertCheckBoxes (PdfPage page) + { - var bounds = page.GetBoundsForBox(PdfDisplayBox.Crop); + var bounds = page.GetBoundsForBox (PdfDisplayBox.Crop); - var checkboxLoremFestivalBounds = new CGRect(255, bounds.Height - 370, 24, 24); - var checkboxLoremFestival = new PdfAnnotation(checkboxLoremFestivalBounds, PdfAnnotationSubtype.Widget.GetConstant(), null) { - WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant(), + var checkboxLoremFestivalBounds = new CGRect (255, bounds.Height - 370, 24, 24); + var checkboxLoremFestival = new PdfAnnotation (checkboxLoremFestivalBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant (), WidgetControlType = PdfWidgetControlType.CheckBox }; - page.AddAnnotation(checkboxLoremFestival); + page.AddAnnotation (checkboxLoremFestival); - var checkboxIpsumFestivalBounds = new CGRect(255, bounds.Height - 417, 24, 24); - var checkboxIpsumFestival = new PdfAnnotation(checkboxIpsumFestivalBounds, PdfAnnotationSubtype.Widget.GetConstant(), null) - { - WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant(), + var checkboxIpsumFestivalBounds = new CGRect (255, bounds.Height - 417, 24, 24); + var checkboxIpsumFestival = new PdfAnnotation (checkboxIpsumFestivalBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant (), WidgetControlType = PdfWidgetControlType.CheckBox }; - page.AddAnnotation(checkboxIpsumFestival); + page.AddAnnotation (checkboxIpsumFestival); - var checkboxDolumFestivalBounds = new CGRect(255, bounds.Height - 464, 24, 24); - var checkboxDolumFestival = new PdfAnnotation(checkboxDolumFestivalBounds, PdfAnnotationSubtype.Widget.GetConstant(), null) - { - WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant(), + var checkboxDolumFestivalBounds = new CGRect (255, bounds.Height - 464, 24, 24); + var checkboxDolumFestival = new PdfAnnotation (checkboxDolumFestivalBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant (), WidgetControlType = PdfWidgetControlType.CheckBox }; - page.AddAnnotation(checkboxDolumFestival); + page.AddAnnotation (checkboxDolumFestival); } - public void InsertMultilineTextBox(PdfPage page) { + public void InsertMultilineTextBox (PdfPage page) + { - var bounds = page.GetBoundsForBox(PdfDisplayBox.Crop); + var bounds = page.GetBoundsForBox (PdfDisplayBox.Crop); - var textFieldMultilineBox = new CGRect(90, bounds.Height - 632, 276, 80); - var textFieldMultiline = new PdfAnnotation(textFieldMultilineBox, PdfAnnotationSubtype.Widget.GetConstant(), null) - { - WidgetFieldType = PdfAnnotationWidgetSubtype.Text.GetConstant(), - BackgroundColor = UIColor.Blue.ColorWithAlpha(0.25f), - Font = UIFont.SystemFontOfSize(24), + var textFieldMultilineBox = new CGRect (90, bounds.Height - 632, 276, 80); + var textFieldMultiline = new PdfAnnotation (textFieldMultilineBox, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Text.GetConstant (), + BackgroundColor = UIColor.Blue.ColorWithAlpha (0.25f), + Font = UIFont.SystemFontOfSize (24), Multiline = true }; - page.AddAnnotation(textFieldMultiline); + page.AddAnnotation (textFieldMultiline); } - public void InsertResetButton(PdfPage page) { + public void InsertResetButton (PdfPage page) + { - var bounds = page.GetBoundsForBox(PdfDisplayBox.Crop); + var bounds = page.GetBoundsForBox (PdfDisplayBox.Crop); - var resetButtonBounds = new CGRect(90, bounds.Height - 680, 106, 32); - var resetButton = new PdfAnnotation(resetButtonBounds, PdfAnnotationSubtype.Widget.GetConstant(), null) - { - WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant(), + var resetButtonBounds = new CGRect (90, bounds.Height - 680, 106, 32); + var resetButton = new PdfAnnotation (resetButtonBounds, PdfAnnotationSubtype.Widget.GetConstant (), null) { + WidgetFieldType = PdfAnnotationWidgetSubtype.Button.GetConstant (), WidgetControlType = PdfWidgetControlType.PushButton, Caption = "Obliviate!" }; - page.AddAnnotation(resetButton); + page.AddAnnotation (resetButton); // Create PDFActionResetForm action to clear form fields. - var resetFormAction = new PdfActionResetForm(){ + var resetFormAction = new PdfActionResetForm () { FieldsIncludedAreCleared = false }; resetButton.Action = resetFormAction; - + } #endregion } diff --git a/ios11/PDFDocumentWatermark/DocumentWatermark/AppDelegate.cs b/ios11/PDFDocumentWatermark/DocumentWatermark/AppDelegate.cs index baa2bd0a9..13791e4cd 100644 --- a/ios11/PDFDocumentWatermark/DocumentWatermark/AppDelegate.cs +++ b/ios11/PDFDocumentWatermark/DocumentWatermark/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace DocumentWatermark -{ +namespace DocumentWatermark { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/PDFDocumentWatermark/DocumentWatermark/Classes/WatermarkPage.cs b/ios11/PDFDocumentWatermark/DocumentWatermark/Classes/WatermarkPage.cs index d4f91a223..7ece792c4 100644 --- a/ios11/PDFDocumentWatermark/DocumentWatermark/Classes/WatermarkPage.cs +++ b/ios11/PDFDocumentWatermark/DocumentWatermark/Classes/WatermarkPage.cs @@ -1,11 +1,10 @@ -using System; +using System; using Foundation; using UIKit; using PdfKit; using CoreGraphics; -namespace DocumentWatermark -{ +namespace DocumentWatermark { /** WatermarkPage subclasses PDFPage so that it can override the draw(with box: to context:) method. This method is called by PDFDocument to draw the page into a PDFView. All custom drawing for a PDF @@ -17,49 +16,46 @@ to draw the original PDFPage content. Custom drawing code can execute before or PDFPage content. Conversely, if your graphics run after the super-class call, they are drawn above the PDFPage. */ - [Register("WatermarkPage")] - public class WatermarkPage : PdfPage - { + [Register ("WatermarkPage")] + public class WatermarkPage : PdfPage { #region Constructors - protected WatermarkPage(IntPtr handle) : base(handle) - { + protected WatermarkPage (IntPtr handle) : base (handle) + { // Note: this .ctor should not contain any initialization logic. } - #endregion + #endregion - public override void Draw(PdfDisplayBox box, CoreGraphics.CGContext context) - { + public override void Draw (PdfDisplayBox box, CoreGraphics.CGContext context) + { // Draw original content - base.Draw(box, context); + base.Draw (box, context); - using (context) - { - // Draw watermark underlay - UIGraphics.PushContext(context); - context.SaveState(); + using (context) { + // Draw watermark underlay + UIGraphics.PushContext (context); + context.SaveState (); - var pageBounds = this.GetBoundsForBox(box); - context.TranslateCTM(0.0f, pageBounds.Size.Height); - context.ScaleCTM(1.0f, -1.0f); - context.RotateCTM((float)(Math.PI / 4.0f)); + var pageBounds = this.GetBoundsForBox (box); + context.TranslateCTM (0.0f, pageBounds.Size.Height); + context.ScaleCTM (1.0f, -1.0f); + context.RotateCTM ((float) (Math.PI / 4.0f)); - Console.WriteLine($"{pageBounds}"); + Console.WriteLine ($"{pageBounds}"); - var attributes = new UIStringAttributes() - { - ForegroundColor = UIColor.FromRGBA(255, 0, 0, 125), - Font = UIFont.BoldSystemFontOfSize(84) - }; + var attributes = new UIStringAttributes () { + ForegroundColor = UIColor.FromRGBA (255, 0, 0, 125), + Font = UIFont.BoldSystemFontOfSize (84) + }; - var text = new NSAttributedString("WATERMARK", attributes); + var text = new NSAttributedString ("WATERMARK", attributes); - text.DrawString(new CGPoint(250, 40)); + text.DrawString (new CGPoint (250, 40)); - context.RestoreState(); - UIGraphics.PopContext(); - } + context.RestoreState (); + UIGraphics.PopContext (); + } } } } diff --git a/ios11/PDFDocumentWatermark/DocumentWatermark/Main.cs b/ios11/PDFDocumentWatermark/DocumentWatermark/Main.cs index c36082bea..7a9be1f3d 100644 --- a/ios11/PDFDocumentWatermark/DocumentWatermark/Main.cs +++ b/ios11/PDFDocumentWatermark/DocumentWatermark/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace DocumentWatermark -{ - public class Application - { +namespace DocumentWatermark { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/PDFDocumentWatermark/DocumentWatermark/ViewController.cs b/ios11/PDFDocumentWatermark/DocumentWatermark/ViewController.cs index 60a0e4046..fd8c9d3e4 100644 --- a/ios11/PDFDocumentWatermark/DocumentWatermark/ViewController.cs +++ b/ios11/PDFDocumentWatermark/DocumentWatermark/ViewController.cs @@ -1,30 +1,26 @@ -using System; +using System; using Foundation; using UIKit; using PdfKit; -namespace DocumentWatermark -{ - public partial class ViewController : UIViewController, IPdfDocumentDelegate - { +namespace DocumentWatermark { + public partial class ViewController : UIViewController, IPdfDocumentDelegate { #region Constructors - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } #endregion #region Override Methods - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - var documentURL = NSBundle.MainBundle.GetUrlForResource("Sample", "pdf"); - if (documentURL != null) - { - var document = new PdfDocument(documentURL); - if (document != null) - { + var documentURL = NSBundle.MainBundle.GetUrlForResource ("Sample", "pdf"); + if (documentURL != null) { + var document = new PdfDocument (documentURL); + if (document != null) { // Center document on gray background PDFView.AutoScales = true; PDFView.BackgroundColor = UIColor.LightGray; @@ -38,10 +34,10 @@ public override void ViewDidLoad() #endregion #region PdfDocumentDelegate - [Export("classForPage")] - public ObjCRuntime.Class GetClassForPage() + [Export ("classForPage")] + public ObjCRuntime.Class GetClassForPage () { - return new ObjCRuntime.Class(typeof(WatermarkPage)); + return new ObjCRuntime.Class (typeof (WatermarkPage)); } #endregion } diff --git a/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/Main.cs b/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/Main.cs index 2d9281136..18d9fdfa4 100644 --- a/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/Main.cs +++ b/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace SamplePhotoApp.tvOS -{ - public class Application - { +namespace SamplePhotoApp.tvOS { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/ViewController.cs b/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/ViewController.cs index 2afb56cfb..d735516d4 100644 --- a/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/ViewController.cs +++ b/ios11/SamplePhotoApp/SamplePhotoApp.tvOS/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace SamplePhotoApp.tvOS -{ - public partial class ViewController : UIViewController - { +namespace SamplePhotoApp.tvOS { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } diff --git a/ios11/SamplePhotoApp/SamplePhotoApp/Main.cs b/ios11/SamplePhotoApp/SamplePhotoApp/Main.cs index eac973e63..976d4372c 100644 --- a/ios11/SamplePhotoApp/SamplePhotoApp/Main.cs +++ b/ios11/SamplePhotoApp/SamplePhotoApp/Main.cs @@ -1,10 +1,8 @@ -using UIKit; +using UIKit; -namespace SamplePhotoApp -{ - public class Application - { - static void Main (string[] args) +namespace SamplePhotoApp { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios11/SamplePhotoApp/Shared/AnimatedImage.cs b/ios11/SamplePhotoApp/Shared/AnimatedImage.cs index ed3593e6d..4b645d82d 100644 --- a/ios11/SamplePhotoApp/Shared/AnimatedImage.cs +++ b/ios11/SamplePhotoApp/Shared/AnimatedImage.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using CoreGraphics; using Foundation; @@ -6,12 +6,10 @@ using CGImageProperties = ImageIO.CGImageProperties; -namespace SamplePhotoApp -{ - public class AnimatedImage - { +namespace SamplePhotoApp { + public class AnimatedImage { private CGImageSource imageSource; - private double[] delays; + private double [] delays; public nint FrameCount { get; set; } public double Duration { get; set; } @@ -33,13 +31,10 @@ public AnimatedImage (CGImageSource source) imageSource = source; FrameCount = imageSource.ImageCount; - var imageProperties = source.CopyProperties (new CGImageOptions()); - if (imageProperties != null) - { + var imageProperties = source.CopyProperties (new CGImageOptions ()); + if (imageProperties != null) { LoopCount = LoopCountForProperties (imageProperties); - } - else - { + } else { // The default loop count for a GIF with no loop count specified is 1. // Infinite loops are indicated by an explicit value of 0 for this property. LoopCount = 1; @@ -51,20 +46,17 @@ public AnimatedImage (CGImageSource source) else Size = CGSize.Empty; - var delayTimes = Enumerable.Repeat (1.0 / 30.0, (int)FrameCount).ToArray (); + var delayTimes = Enumerable.Repeat (1.0 / 30.0, (int) FrameCount).ToArray (); var totalDuration = 0.0; - for (var index = 0; index < FrameCount; index++) - { - var properties = source.CopyProperties (new CGImageOptions(), index); - if (properties != null) - { + for (var index = 0; index < FrameCount; index++) { + var properties = source.CopyProperties (new CGImageOptions (), index); + if (properties != null) { var time = FrameDelayForProperties (properties); - if (time != null) - { - delayTimes[index] = time.Value; + if (time != null) { + delayTimes [index] = time.Value; } } - totalDuration += delayTimes[index]; + totalDuration += delayTimes [index]; } Duration = totalDuration; delays = delayTimes; @@ -73,21 +65,18 @@ public AnimatedImage (CGImageSource source) static double? FrameDelayForProperties (NSDictionary properties) { // Read the delay time for a GIF. - var gifDictionary = properties[CGImageProperties.GIFDictionary] as NSDictionary; - if (gifDictionary == null) - { + var gifDictionary = properties [CGImageProperties.GIFDictionary] as NSDictionary; + if (gifDictionary == null) { return null; } - var delay = (gifDictionary[CGImageProperties.GIFUnclampedDelayTime] as NSNumber)?.DoubleValue; - if (delay != null & delay > 0.0) - { + var delay = (gifDictionary [CGImageProperties.GIFUnclampedDelayTime] as NSNumber)?.DoubleValue; + if (delay != null & delay > 0.0) { return delay; } - delay = (gifDictionary[CGImageProperties.GIFDelayTime] as NSNumber)?.DoubleValue; - if (delay != null & delay > 0.0) - { + delay = (gifDictionary [CGImageProperties.GIFDelayTime] as NSNumber)?.DoubleValue; + if (delay != null & delay > 0.0) { return delay; } @@ -96,12 +85,10 @@ public AnimatedImage (CGImageSource source) static nint LoopCountForProperties (NSDictionary properties) { - var gifDictionary = properties[CGImageProperties.GIFDictionary] as NSDictionary; - if (gifDictionary != null) - { - var loopCount = (gifDictionary[CGImageProperties.GIFLoopCount] as NSNumber)?.NIntValue; - if (loopCount != null) - { + var gifDictionary = properties [CGImageProperties.GIFDictionary] as NSDictionary; + if (gifDictionary != null) { + var loopCount = (gifDictionary [CGImageProperties.GIFLoopCount] as NSNumber)?.NIntValue; + if (loopCount != null) { return loopCount.Value; } } @@ -112,19 +99,16 @@ static nint LoopCountForProperties (NSDictionary properties) public CGImage ImageAtIndex (int index) { - if (index < FrameCount) - { - return imageSource.CreateImage (index, (CGImageOptions)null); - } - else - { + if (index < FrameCount) { + return imageSource.CreateImage (index, (CGImageOptions) null); + } else { return null; } } public double DelayAtIndex (int index) { - return delays[index]; + return delays [index]; } } } diff --git a/ios11/SamplePhotoApp/Shared/AnimatedImageView.cs b/ios11/SamplePhotoApp/Shared/AnimatedImageView.cs index 527c5844d..7b1dc4d5e 100644 --- a/ios11/SamplePhotoApp/Shared/AnimatedImageView.cs +++ b/ios11/SamplePhotoApp/Shared/AnimatedImageView.cs @@ -1,23 +1,19 @@ -using System; +using System; using CoreAnimation; using CoreFoundation; using CoreGraphics; using Foundation; using UIKit; -namespace SamplePhotoApp -{ +namespace SamplePhotoApp { [Register (nameof (AnimatedImageView))] - public class AnimatedImageView : UIView - { + public class AnimatedImageView : UIView { AnimatedImage animatedImage; bool isPlaying; - public AnimatedImage AnimatedImage - { + public AnimatedImage AnimatedImage { get { return animatedImage; } - set - { + set { animatedImage = value; ResetAnimationState (); UpdateAnimation (); @@ -25,13 +21,10 @@ public AnimatedImage AnimatedImage } } - public bool IsPlaying - { + public bool IsPlaying { get { return isPlaying; } - set - { - if (isPlaying != value) - { + set { + if (isPlaying != value) { isPlaying = value; UpdateAnimation (); } @@ -72,50 +65,39 @@ public override void LayoutSubviews () base.LayoutSubviews (); nfloat viewAspect = 0.0f; - if (Bounds.Height > 0.0) - { + if (Bounds.Height > 0.0) { viewAspect = Bounds.Width / Bounds.Height; } nfloat imageAspect = 0.0f; - if (AnimatedImage != null) - { + if (AnimatedImage != null) { var imageSize = AnimatedImage.Size; - if (imageSize.Height > 0.0) - { + if (imageSize.Height > 0.0) { imageAspect = imageSize.Width / imageSize.Height; } } var viewFrame = new CGRect (0.0, 0.0, Bounds.Width, Bounds.Height); - if (imageAspect < viewAspect) - { + if (imageAspect < viewAspect) { viewFrame.Width = Bounds.Height * imageAspect; viewFrame.X = (Bounds.Width / 2.0f) - (0.5f * viewFrame.Width); - } - else if (imageAspect > 0.0) - { + } else if (imageAspect > 0.0) { viewFrame.Height = Bounds.Width / imageAspect; viewFrame.Y = (Bounds.Height / 2.0f) - (0.5f * viewFrame.Height); } - if (AnimatedImage != null) - { - if (displayView == null) - { + if (AnimatedImage != null) { + if (displayView == null) { var newView = new UIView (CGRect.Empty); AddSubview (newView); displayView = newView; UpdateImage (); } - } - else - { + } else { displayView?.RemoveFromSuperview (); displayView = null; } - if (displayView != null) - { + if (displayView != null) { displayView.Frame = viewFrame; } } @@ -132,21 +114,17 @@ public override void MovedToSuperview () UpdateAnimation (); } - public override nfloat Alpha - { + public override nfloat Alpha { get { return base.Alpha; } - set - { + set { base.Alpha = value; UpdateAnimation (); } } - public override bool Hidden - { + public override bool Hidden { get { return base.Hidden; } - set - { + set { base.Hidden = value; UpdateAnimation (); } @@ -165,8 +143,7 @@ void ResetAnimationState () hasFinishedAnimating = false; isInfiniteLoop = true; remainingLoopCount = 0; - if (AnimatedImage != null) - { + if (AnimatedImage != null) { isInfiniteLoop = AnimatedImage?.FrameCount == 0; remainingLoopCount = AnimatedImage.LoopCount; } @@ -176,14 +153,11 @@ void ResetAnimationState () void UpdateAnimation () { - if (ShouldAnimate ()) - { + if (ShouldAnimate ()) { displayLink = CADisplayLink.Create (TimerFired); displayLink.AddToRunLoop (NSRunLoop.Main, NSRunLoopMode.Common); displayLink.PreferredFramesPerSecond = 60; - } - else - { + } else { displayLink?.Invalidate (); displayLink = null; } @@ -192,8 +166,7 @@ void UpdateAnimation () void UpdateImage () { var image = AnimatedImage?.ImageAtIndex (displayedIndex); - if (image != null && displayView != null) - { + if (image != null && displayView != null) { displayView.Layer.Contents = image; } } @@ -206,8 +179,7 @@ void TimerFired () var timestamp = displayLink.Timestamp; // If this is the first callback, set things up - if (!hasStartedAnimating) - { + if (!hasStartedAnimating) { elapsedTime = 0.0; previousTime = timestamp; hasStartedAnimating = true; @@ -220,45 +192,34 @@ void TimerFired () // Aaccount for big gaps in playback by just resuming from now // e.g. user presses home button and comes back after a while. // Allow for the possibility of the current delay time being relatively long - if (elapsedTime >= Math.Max (10.0, currentDelayTime + 1.0)) - { + if (elapsedTime >= Math.Max (10.0, currentDelayTime + 1.0)) { elapsedTime = 0.0; } var changedFrame = false; - while (elapsedTime >= currentDelayTime) - { + while (elapsedTime >= currentDelayTime) { elapsedTime -= currentDelayTime; displayedIndex += 1; changedFrame = true; - if (displayedIndex >= AnimatedImage.FrameCount) - { + if (displayedIndex >= AnimatedImage.FrameCount) { // Time to loop. Start infinite loops over, otherwise decrement loop count and stop if done - if (isInfiniteLoop) - { + if (isInfiniteLoop) { displayedIndex = 0; - } - else - { + } else { remainingLoopCount -= 1; - if (remainingLoopCount == 0) - { + if (remainingLoopCount == 0) { hasFinishedAnimating = true; - DispatchQueue.MainQueue.DispatchAsync (() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { UpdateAnimation (); }); - } - else - { + } else { displayedIndex = 0; } } } } - if (changedFrame) - { + if (changedFrame) { UpdateImage (); } } diff --git a/ios11/SamplePhotoApp/Shared/AppDelegate.cs b/ios11/SamplePhotoApp/Shared/AppDelegate.cs index ccb05c193..9059aaae9 100644 --- a/ios11/SamplePhotoApp/Shared/AppDelegate.cs +++ b/ios11/SamplePhotoApp/Shared/AppDelegate.cs @@ -1,12 +1,10 @@ -using System.Linq; +using System.Linq; using Foundation; using UIKit; -namespace SamplePhotoApp -{ +namespace SamplePhotoApp { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate - { + public class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) diff --git a/ios11/SamplePhotoApp/Shared/AssetGridViewController.cs b/ios11/SamplePhotoApp/Shared/AssetGridViewController.cs index 2713f3e52..f11149891 100644 --- a/ios11/SamplePhotoApp/Shared/AssetGridViewController.cs +++ b/ios11/SamplePhotoApp/Shared/AssetGridViewController.cs @@ -8,10 +8,8 @@ using PhotosUI; using UIKit; -namespace SamplePhotoApp -{ - public partial class AssetGridViewController : UICollectionViewController, IPHPhotoLibraryChangeObserver - { +namespace SamplePhotoApp { + public partial class AssetGridViewController : UICollectionViewController, IPHPhotoLibraryChangeObserver { const string cellReuseIdentifier = "GridViewCell"; public PHFetchResult FetchResult { get; set; } @@ -41,11 +39,9 @@ public override void ViewDidLoad () // If we get here without a segue, it's because we're visible at app launch, // so match the behavior of segue from the default "All Photos" view. - if (FetchResult == null) - { - var allPhotosOptions = new PHFetchOptions - { - SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor ("creationDate", true) } + if (FetchResult == null) { + var allPhotosOptions = new PHFetchOptions { + SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor ("creationDate", true) } }; FetchResult = PHAsset.FetchAssets (allPhotosOptions); } @@ -89,8 +85,8 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (assetViewController == null) throw new InvalidProgramException ("unexpected view controller for segue"); - var indexPath = CollectionView.IndexPathForCell ((UICollectionViewCell)sender); - assetViewController.Asset = (PHAsset)FetchResult[indexPath.Item]; + var indexPath = CollectionView.IndexPathForCell ((UICollectionViewCell) sender); + assetViewController.Asset = (PHAsset) FetchResult [indexPath.Item]; assetViewController.AssetCollection = AssetCollection; } @@ -104,8 +100,7 @@ void UpdateItemSize () var itemWidth = Math.Floor ((viewWidth - (columns - 1f) * padding) / columns); var itemSize = new CGSize (itemWidth, itemWidth); - if (Layout is UICollectionViewFlowLayout layout) - { + if (Layout is UICollectionViewFlowLayout layout) { layout.ItemSize = itemSize; layout.MinimumInteritemSpacing = padding; layout.MinimumLineSpacing = padding; @@ -125,10 +120,10 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var asset = (PHAsset)FetchResult[indexPath.Item]; + var asset = (PHAsset) FetchResult [indexPath.Item]; // Dequeue an GridViewCell. - var cell = (GridViewCell)collectionView.DequeueReusableCell (cellReuseIdentifier, indexPath); + var cell = (GridViewCell) collectionView.DequeueReusableCell (cellReuseIdentifier, indexPath); // Add a badge to the cell if the PHAsset represents a Live Photo. if (asset.MediaSubtypes.HasFlag (PHAssetMediaSubtype.PhotoLive)) @@ -136,8 +131,7 @@ public override UICollectionViewCell GetCell (UICollectionView collectionView, N // Request an image for the asset from the PHCachingImageManager. cell.RepresentedAssetIdentifier = asset.LocalIdentifier; - imageManager.RequestImageForAsset (asset, thumbnailSize, PHImageContentMode.AspectFill, null, (image, info) => - { + imageManager.RequestImageForAsset (asset, thumbnailSize, PHImageContentMode.AspectFill, null, (image, info) => { // The cell may have been recycled by the time this handler gets called; // Set the cell's thumbnail image if it's still showing the same asset. if (cell.RepresentedAssetIdentifier == asset.LocalIdentifier && image != null) @@ -160,191 +154,179 @@ public override void Scrolled (UIScrollView scrollView) #endif { UpdateCachedAssets (); - } - - #endregion - - #region Asset Caching + } - void ResetCachedAssets () - { - imageManager.StopCaching (); - previousPreheatRect = CGRect.Empty; - } + #endregion - void UpdateCachedAssets () - { - // Update only if the view is visible. - bool isViewVisible = IsViewLoaded && View.Window != null; - if (!isViewVisible) - return; - - // The preheat window is twice the height of the visible rect. - var visibleRect = new CGRect (CollectionView.ContentOffset, CollectionView.Bounds.Size); - var preheatRect = visibleRect.Inset (0f, -0.5f * visibleRect.Height); - - // Update only if the visible area is significantly different from the last preheated area. - nfloat delta = NMath.Abs (preheatRect.GetMidY () - previousPreheatRect.GetMidY ()); - if (delta <= CollectionView.Bounds.Height / 3f) - return; - - // Compute the assets to start caching and to stop caching. - var rects = ComputeDifferenceBetweenRect (previousPreheatRect, preheatRect); - var addedAssets = rects.added - .SelectMany (rect => CollectionView.GetIndexPaths (rect)) - .Select (indexPath => FetchResult.ObjectAt (indexPath.Item)) - .Cast<PHAsset> () - .ToArray (); - - var removedAssets = rects.removed - .SelectMany (rect => CollectionView.GetIndexPaths (rect)) - .Select (indexPath => FetchResult.ObjectAt (indexPath.Item)) - .Cast<PHAsset> () - .ToArray (); - - // Update the assets the PHCachingImageManager is caching. - imageManager.StartCaching (addedAssets, thumbnailSize, PHImageContentMode.AspectFill, null); - imageManager.StopCaching (removedAssets, thumbnailSize, PHImageContentMode.AspectFill, null); - - // Store the preheat rect to compare against in the future. - previousPreheatRect = preheatRect; - } + #region Asset Caching - (IEnumerable<CGRect> added, IEnumerable<CGRect> removed) ComputeDifferenceBetweenRect (CGRect oldRect, CGRect newRect) - { - if (!oldRect.IntersectsWith (newRect)) - { - return (new CGRect[] { newRect }, new CGRect[] { oldRect }); - } + void ResetCachedAssets () + { + imageManager.StopCaching (); + previousPreheatRect = CGRect.Empty; + } - var oldMaxY = oldRect.GetMaxY (); - var oldMinY = oldRect.GetMinY (); - var newMaxY = newRect.GetMaxY (); - var newMinY = newRect.GetMinY (); + void UpdateCachedAssets () + { + // Update only if the view is visible. + bool isViewVisible = IsViewLoaded && View.Window != null; + if (!isViewVisible) + return; + + // The preheat window is twice the height of the visible rect. + var visibleRect = new CGRect (CollectionView.ContentOffset, CollectionView.Bounds.Size); + var preheatRect = visibleRect.Inset (0f, -0.5f * visibleRect.Height); + + // Update only if the visible area is significantly different from the last preheated area. + nfloat delta = NMath.Abs (preheatRect.GetMidY () - previousPreheatRect.GetMidY ()); + if (delta <= CollectionView.Bounds.Height / 3f) + return; + + // Compute the assets to start caching and to stop caching. + var rects = ComputeDifferenceBetweenRect (previousPreheatRect, preheatRect); + var addedAssets = rects.added + .SelectMany (rect => CollectionView.GetIndexPaths (rect)) + .Select (indexPath => FetchResult.ObjectAt (indexPath.Item)) + .Cast<PHAsset> () + .ToArray (); + + var removedAssets = rects.removed + .SelectMany (rect => CollectionView.GetIndexPaths (rect)) + .Select (indexPath => FetchResult.ObjectAt (indexPath.Item)) + .Cast<PHAsset> () + .ToArray (); + + // Update the assets the PHCachingImageManager is caching. + imageManager.StartCaching (addedAssets, thumbnailSize, PHImageContentMode.AspectFill, null); + imageManager.StopCaching (removedAssets, thumbnailSize, PHImageContentMode.AspectFill, null); + + // Store the preheat rect to compare against in the future. + previousPreheatRect = preheatRect; + } - var added = new List<CGRect> (); - var removed = new List<CGRect> (); + (IEnumerable<CGRect> added, IEnumerable<CGRect> removed) ComputeDifferenceBetweenRect (CGRect oldRect, CGRect newRect) + { + if (!oldRect.IntersectsWith (newRect)) { + return (new CGRect [] { newRect }, new CGRect [] { oldRect }); + } - if (newMaxY > oldMaxY) - added.Add (new CGRect (newRect.X, oldMaxY, newRect.Width, newMaxY - oldMaxY)); + var oldMaxY = oldRect.GetMaxY (); + var oldMinY = oldRect.GetMinY (); + var newMaxY = newRect.GetMaxY (); + var newMinY = newRect.GetMinY (); - if (oldMinY > newMinY) - added.Add (new CGRect (newRect.X, newMinY, newRect.Width, oldMinY - newMinY)); + var added = new List<CGRect> (); + var removed = new List<CGRect> (); - if (newMaxY < oldMaxY) - removed.Add (new CGRect (newRect.X, newMaxY, newRect.Width, oldMaxY - newMaxY)); + if (newMaxY > oldMaxY) + added.Add (new CGRect (newRect.X, oldMaxY, newRect.Width, newMaxY - oldMaxY)); - if (oldMinY < newMinY) - removed.Add (new CGRect (newRect.X, oldMinY, newRect.Width, newMinY - oldMinY)); + if (oldMinY > newMinY) + added.Add (new CGRect (newRect.X, newMinY, newRect.Width, oldMinY - newMinY)); - return (added, removed); - } + if (newMaxY < oldMaxY) + removed.Add (new CGRect (newRect.X, newMaxY, newRect.Width, oldMaxY - newMaxY)); - #endregion + if (oldMinY < newMinY) + removed.Add (new CGRect (newRect.X, oldMinY, newRect.Width, newMinY - oldMinY)); - #region UI Actions + return (added, removed); + } - partial void AddAsset (NSObject sender) - { - var rnd = new Random (); - - // Create a random dummy image. - var size = (rnd.Next (0, 2) == 0) - ? new CGSize (400f, 300f) - : new CGSize (300f, 400f); - - var renderer = new UIGraphicsImageRenderer (size); - var image = renderer.CreateImage (context => - { - UIColor.FromHSBA ((float)rnd.NextDouble (), 1, 1, 1).SetFill (); - context.FillRect (context.Format.Bounds); - }); + #endregion - // Add it to the photo library - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { - PHAssetChangeRequest creationRequest = PHAssetChangeRequest.FromImage (image); + #region UI Actions - if (AssetCollection != null) - { - var addAssetRequest = PHAssetCollectionChangeRequest.ChangeRequest (AssetCollection); - addAssetRequest.AddAssets (new PHObject[] { + partial void AddAsset (NSObject sender) + { + var rnd = new Random (); + + // Create a random dummy image. + var size = (rnd.Next (0, 2) == 0) + ? new CGSize (400f, 300f) + : new CGSize (300f, 400f); + + var renderer = new UIGraphicsImageRenderer (size); + var image = renderer.CreateImage (context => { + UIColor.FromHSBA ((float) rnd.NextDouble (), 1, 1, 1).SetFill (); + context.FillRect (context.Format.Bounds); + }); + + // Add it to the photo library + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { + PHAssetChangeRequest creationRequest = PHAssetChangeRequest.FromImage (image); + + if (AssetCollection != null) { + var addAssetRequest = PHAssetCollectionChangeRequest.ChangeRequest (AssetCollection); + addAssetRequest.AddAssets (new PHObject [] { creationRequest.PlaceholderForCreatedAsset }); - } - }, (success, error) => - { - if (!success) - Console.WriteLine (error.LocalizedDescription); - }); - } + } + }, (success, error) => { + if (!success) + Console.WriteLine (error.LocalizedDescription); + }); + } - #endregion + #endregion - #region IPHPhotoLibraryChangeObserver + #region IPHPhotoLibraryChangeObserver - public void PhotoLibraryDidChange (PHChange changeInstance) - { - var changes = changeInstance.GetFetchResultChangeDetails (FetchResult); - if (changes == null) - return; - - DispatchQueue.MainQueue.DispatchSync (() => - { - // Hang on to the new fetch result. - FetchResult = changes.FetchResultAfterChanges; - - if (changes.HasIncrementalChanges) - { - // If we have incremental diffs, animate them in the collection view. - CollectionView.PerformBatchUpdates (() => - { - // For indexes to make sense, updates must be in this order: - // delete, insert, reload, move - var removed = changes.RemovedIndexes; - if (removed != null && removed.Count > 0) - CollectionView.DeleteItems (ToNSIndexPaths (removed)); - - var inserted = changes.InsertedIndexes; - if (inserted != null && inserted.Count > 0) - CollectionView.InsertItems (ToNSIndexPaths (inserted)); - - var changed = changes.ChangedIndexes; - if (changed != null && changed.Count > 0) - CollectionView.ReloadItems (ToNSIndexPaths (changed)); - - changes.EnumerateMoves ((fromIndex, toIndex) => - { - var start = NSIndexPath.FromItemSection ((nint)fromIndex, 0); - var end = NSIndexPath.FromItemSection ((nint)toIndex, 0); - CollectionView.MoveItem (start, end); - }); - }, null); - - } - else - { - // Reload the collection view if incremental diffs are not available. - CollectionView.ReloadData (); - } - - ResetCachedAssets (); - }); - } + public void PhotoLibraryDidChange (PHChange changeInstance) + { + var changes = changeInstance.GetFetchResultChangeDetails (FetchResult); + if (changes == null) + return; + + DispatchQueue.MainQueue.DispatchSync (() => { + // Hang on to the new fetch result. + FetchResult = changes.FetchResultAfterChanges; + + if (changes.HasIncrementalChanges) { + // If we have incremental diffs, animate them in the collection view. + CollectionView.PerformBatchUpdates (() => { + // For indexes to make sense, updates must be in this order: + // delete, insert, reload, move + var removed = changes.RemovedIndexes; + if (removed != null && removed.Count > 0) + CollectionView.DeleteItems (ToNSIndexPaths (removed)); + + var inserted = changes.InsertedIndexes; + if (inserted != null && inserted.Count > 0) + CollectionView.InsertItems (ToNSIndexPaths (inserted)); + + var changed = changes.ChangedIndexes; + if (changed != null && changed.Count > 0) + CollectionView.ReloadItems (ToNSIndexPaths (changed)); + + changes.EnumerateMoves ((fromIndex, toIndex) => { + var start = NSIndexPath.FromItemSection ((nint) fromIndex, 0); + var end = NSIndexPath.FromItemSection ((nint) toIndex, 0); + CollectionView.MoveItem (start, end); + }); + }, null); - static NSIndexPath[] ToNSIndexPaths (NSIndexSet indexSet) - { - var cnt = indexSet.Count; - var result = new NSIndexPath[(int)cnt]; - int i = 0; - indexSet.EnumerateIndexes ((nuint idx, ref bool stop) => - { - stop = false; - result[i++] = NSIndexPath.FromItemSection ((nint)idx, 0); - }); - return result; - } + } else { + // Reload the collection view if incremental diffs are not available. + CollectionView.ReloadData (); + } - #endregion + ResetCachedAssets (); + }); } + + static NSIndexPath [] ToNSIndexPaths (NSIndexSet indexSet) + { + var cnt = indexSet.Count; + var result = new NSIndexPath [(int) cnt]; + int i = 0; + indexSet.EnumerateIndexes ((nuint idx, ref bool stop) => { + stop = false; + result [i++] = NSIndexPath.FromItemSection ((nint) idx, 0); + }); + return result; + } + + #endregion +} } diff --git a/ios11/SamplePhotoApp/Shared/AssetViewController.cs b/ios11/SamplePhotoApp/Shared/AssetViewController.cs index dc30ee2aa..c06de31f4 100644 --- a/ios11/SamplePhotoApp/Shared/AssetViewController.cs +++ b/ios11/SamplePhotoApp/Shared/AssetViewController.cs @@ -8,10 +8,8 @@ using PhotosUI; using UIKit; -namespace SamplePhotoApp -{ - public partial class AssetViewController : UIViewController, IPHPhotoLibraryChangeObserver, IPHLivePhotoViewDelegate - { +namespace SamplePhotoApp { + public partial class AssetViewController : UIViewController, IPHPhotoLibraryChangeObserver, IPHLivePhotoViewDelegate { AVPlayerLayer playerLayer; AVPlayerLooper playerLooper; bool isPlayingHint; @@ -70,8 +68,7 @@ partial void EditAsset (UIBarButtonItem sender) #if !__TVOS__ alertController.ModalPresentationStyle = UIModalPresentationStyle.Popover; var popoverController = alertController.PopoverPresentationController; - if (popoverController != null) - { + if (popoverController != null) { popoverController.BarButtonItem = sender; popoverController.PermittedArrowDirections = UIPopoverArrowDirection.Up; } @@ -80,15 +77,12 @@ partial void EditAsset (UIBarButtonItem sender) alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null)); // Allow editing only if the PHAsset supports edit operations. - if (Asset.CanPerformEditOperation (PHAssetEditOperation.Content)) - { + if (Asset.CanPerformEditOperation (PHAssetEditOperation.Content)) { // Add actions for some canned filters. - alertController.AddAction (UIAlertAction.Create ("Sepia Tone", UIAlertActionStyle.Default, _ => - { + alertController.AddAction (UIAlertAction.Create ("Sepia Tone", UIAlertActionStyle.Default, _ => { ApplyFilter (new CISepiaTone ()); })); - alertController.AddAction (UIAlertAction.Create ("Chrome", UIAlertActionStyle.Default, _ => - { + alertController.AddAction (UIAlertAction.Create ("Chrome", UIAlertActionStyle.Default, _ => { ApplyFilter (new CIPhotoEffectChrome ()); })); @@ -111,47 +105,36 @@ partial void PlayLivePhoto (NSObject sender) partial void Play (NSObject sender) { // An AVPlayerLayer has already been created for this asset; just play it. - if (playerLayer != null) - { + if (playerLayer != null) { playerLayer.Player.Play (); - } - else - { - var options = new PHVideoRequestOptions - { + } else { + var options = new PHVideoRequestOptions { NetworkAccessAllowed = true, DeliveryMode = PHVideoRequestOptionsDeliveryMode.Automatic, - ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => - { + ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => { stop = false; // Handler might not be called on the main queue, so re-dispatch for UI work. - DispatchQueue.MainQueue.DispatchSync (() => - { - ProgressView.Progress = (float)progress; + DispatchQueue.MainQueue.DispatchSync (() => { + ProgressView.Progress = (float) progress; }); } }; // Request an AVAsset for the displayed PHAsset and set up a layer for playing it. - PHImageManager.DefaultManager.RequestPlayerItem (Asset, options, (playerItem, info) => - { - DispatchQueue.MainQueue.DispatchSync (() => - { + PHImageManager.DefaultManager.RequestPlayerItem (Asset, options, (playerItem, info) => { + DispatchQueue.MainQueue.DispatchSync (() => { if (this.playerLayer != null || playerItem == null) return; // Create an AVPlayer and AVPlayerLayer with the AVPlayerItem. AVPlayer player; - if (Asset.PlaybackStyle == PHAssetPlaybackStyle.VideoLooping) - { - var queuePlayer = AVQueuePlayer.FromItems (new[] { playerItem }); + if (Asset.PlaybackStyle == PHAssetPlaybackStyle.VideoLooping) { + var queuePlayer = AVQueuePlayer.FromItems (new [] { playerItem }); playerLooper = AVPlayerLooper.FromPlayer (queuePlayer, playerItem); player = queuePlayer; - } - else - { + } else { player = AVPlayer.FromPlayerItem (playerItem); } @@ -173,51 +156,39 @@ partial void Play (NSObject sender) partial void RemoveAsset (NSObject sender) { - Action<bool, NSError> completion = (success, error) => - { - if (success) - { + Action<bool, NSError> completion = (success, error) => { + if (success) { PHPhotoLibrary.SharedPhotoLibrary.UnregisterChangeObserver (this); DispatchQueue.MainQueue.DispatchSync (() => NavigationController.PopViewController (true)); - } - else - { + } else { Console.WriteLine ($"can't remove asset: {error.LocalizedDescription}"); } }; - if (AssetCollection != null) - { + if (AssetCollection != null) { // Remove asset from album - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { var request = PHAssetCollectionChangeRequest.ChangeRequest (AssetCollection); - request.RemoveAssets (new PHObject[] { Asset }); + request.RemoveAssets (new PHObject [] { Asset }); }, completion); - } - else - { + } else { // Delete asset from library - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { - PHAssetChangeRequest.DeleteAssets (new[] { Asset }); + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { + PHAssetChangeRequest.DeleteAssets (new [] { Asset }); }, completion); } } partial void ToggleFavorite (UIBarButtonItem sender) { - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { var request = PHAssetChangeRequest.ChangeRequest (Asset); request.Favorite = !Asset.Favorite; - }, (success, error) => - { + }, (success, error) => { // Original sample updates FavoriteButton.Title here // but this doesn't work, because you have to wait PhotoLibraryDidChange notification. // At this point you just know is there any issue or everthing is ok. - if (!success) - { + if (!success) { Console.WriteLine ($"can't set favorite: {error.LocalizedDescription}"); } }); @@ -235,33 +206,32 @@ CGSize GetTargetSize () void UpdateContent () { - switch (Asset.PlaybackStyle) - { - case PHAssetPlaybackStyle.Unsupported: - var alertController = UIAlertController.Create ("Unsupported Format", null, UIAlertControllerStyle.Alert); - alertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); - PresentViewController (alertController, true, null); - break; - - case PHAssetPlaybackStyle.Image: - UpdateStillImage (); - break; - - case PHAssetPlaybackStyle.LivePhoto: - UpdateLivePhoto (); - break; - - case PHAssetPlaybackStyle.ImageAnimated: - UpdateAnimatedImage (); - break; - - case PHAssetPlaybackStyle.Video: - UpdateStillImage (); // as a placeholder until play is tapped - break; - - case PHAssetPlaybackStyle.VideoLooping: - Play (this); - break; + switch (Asset.PlaybackStyle) { + case PHAssetPlaybackStyle.Unsupported: + var alertController = UIAlertController.Create ("Unsupported Format", null, UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); + PresentViewController (alertController, true, null); + break; + + case PHAssetPlaybackStyle.Image: + UpdateStillImage (); + break; + + case PHAssetPlaybackStyle.LivePhoto: + UpdateLivePhoto (); + break; + + case PHAssetPlaybackStyle.ImageAnimated: + UpdateAnimatedImage (); + break; + + case PHAssetPlaybackStyle.Video: + UpdateStillImage (); // as a placeholder until play is tapped + break; + + case PHAssetPlaybackStyle.VideoLooping: + Play (this); + break; } } @@ -279,8 +249,7 @@ void UpdateToolbars () TrashButton.Enabled = Asset.CanPerformEditOperation (PHAssetEditOperation.Delete); // Set the appropriate toolbarItems based on the mediaType of the asset. - if (Asset.MediaType == PHAssetMediaType.Video) - { + if (Asset.MediaType == PHAssetMediaType.Video) { #if __TVOS__ NavigationItem.LeftBarButtonItems = new UIBarButtonItem[] { PlayButton, FavoriteButton, TrashButton }; #elif __IOS__ @@ -288,9 +257,7 @@ void UpdateToolbars () if (NavigationController != null) NavigationController.ToolbarHidden = false; #endif - } - else - { + } else { #if __TVOS__ // In tvOS, PHLivePhotoView doesn't do playback gestures, // so add a play button for Live Photos. @@ -311,24 +278,20 @@ void UpdateToolbars () void UpdateStillImage () { // Prepare the options to pass when fetching the (photo, or video preview) image. - var options = new PHImageRequestOptions - { + var options = new PHImageRequestOptions { DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat, NetworkAccessAllowed = true, - ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => - { + ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => { stop = false; // Handler might not be called on the main queue, so re-dispatch for UI work. - DispatchQueue.MainQueue.DispatchSync (() => - { - ProgressView.Progress = (float)progress; + DispatchQueue.MainQueue.DispatchSync (() => { + ProgressView.Progress = (float) progress; }); } }; ProgressView.Hidden = false; - PHImageManager.DefaultManager.RequestImageForAsset (Asset, GetTargetSize (), PHImageContentMode.AspectFit, options, (image, info) => - { + PHImageManager.DefaultManager.RequestImageForAsset (Asset, GetTargetSize (), PHImageContentMode.AspectFit, options, (image, info) => { // Hide the progress view now the request has completed. ProgressView.Hidden = true; @@ -345,22 +308,19 @@ void UpdateStillImage () void UpdateLivePhoto () { // Prepare the options to pass when fetching the live photo. - var options = new PHLivePhotoRequestOptions - { + var options = new PHLivePhotoRequestOptions { DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat, NetworkAccessAllowed = true, - ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary dictionary) => - { + ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary dictionary) => { stop = false; // Handler might not be called on the main queue, so re-dispatch for UI work. - DispatchQueue.MainQueue.DispatchSync (() => ProgressView.Progress = (float)progress); + DispatchQueue.MainQueue.DispatchSync (() => ProgressView.Progress = (float) progress); } }; ProgressView.Hidden = false; // Request the live photo for the asset from the default PHImageManager. - PHImageManager.DefaultManager.RequestLivePhoto (Asset, GetTargetSize (), PHImageContentMode.AspectFit, options, (livePhoto, info) => - { + PHImageManager.DefaultManager.RequestLivePhoto (Asset, GetTargetSize (), PHImageContentMode.AspectFit, options, (livePhoto, info) => { // Hide the progress view now the request has completed. ProgressView.Hidden = true; @@ -375,8 +335,7 @@ void UpdateLivePhoto () LivePhotoView.LivePhoto = livePhoto; // Playback a short section of the live photo; similar to the Photos share sheet. - if (!isPlayingHint) - { + if (!isPlayingHint) { isPlayingHint = true; LivePhotoView.StartPlayback (PHLivePhotoViewPlaybackStyle.Hint); } @@ -386,25 +345,21 @@ void UpdateLivePhoto () void UpdateAnimatedImage () { // Prepare the options to pass when fetching the (photo, or video preview) image. - var options = new PHImageRequestOptions - { + var options = new PHImageRequestOptions { DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat, Version = PHImageRequestOptionsVersion.Original, NetworkAccessAllowed = true, - ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => - { + ProgressHandler = (double progress, NSError error, out bool stop, NSDictionary info) => { stop = false; // Handler might not be called on the main queue, so re-dispatch for UI work. - DispatchQueue.MainQueue.DispatchSync (() => - { - ProgressView.Progress = (float)progress; + DispatchQueue.MainQueue.DispatchSync (() => { + ProgressView.Progress = (float) progress; }); } }; ProgressView.Hidden = false; - PHImageManager.DefaultManager.RequestImageData (Asset, options, (data, dataUti, orientation, info) => - { + PHImageManager.DefaultManager.RequestImageData (Asset, options, (data, dataUti, orientation, info) => { // Hide the progress view now the request has completed. ProgressView.Hidden = true; @@ -428,12 +383,10 @@ void UpdateAnimatedImage () void RevertAsset (UIAlertAction action) { - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { var request = PHAssetChangeRequest.ChangeRequest (Asset); request.RevertAssetContentToOriginal (); - }, (success, error) => - { + }, (success, error) => { if (!success) Console.WriteLine ($"can't revert asset: {error.LocalizedDescription}"); }); @@ -443,20 +396,17 @@ void ApplyFilter (CIFilter filter) { // Set up a handler to make sure we can handle prior edits. var options = new PHContentEditingInputRequestOptions (); - options.CanHandleAdjustmentData = (adjustmentData => - { + options.CanHandleAdjustmentData = (adjustmentData => { return adjustmentData.FormatIdentifier == formatIdentifier && adjustmentData.FormatVersion == formatVersion; }); // Prepare for editing. - Asset.RequestContentEditingInput (options, (input, requestStatusInfo) => - { + Asset.RequestContentEditingInput (options, (input, requestStatusInfo) => { if (input == null) throw new InvalidProgramException ($"can't get content editing input: {requestStatusInfo}"); // This handler gets called on the main thread; dispatch to a background queue for processing. - DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Default).DispatchAsync (() => - { + DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Default).DispatchAsync (() => { // Create a PHAdjustmentData object that describes the filter that was applied. var adjustmentData = new PHAdjustmentData ( formatIdentifier, @@ -475,8 +425,7 @@ void ApplyFilter (CIFilter filter) // format) could make use of it. // Create content editing output, write the adjustment data. - var output = new PHContentEditingOutput (input) - { + var output = new PHContentEditingOutput (input) { AdjustmentData = adjustmentData }; @@ -490,19 +439,16 @@ void ApplyFilter (CIFilter filter) applyFunc = ApplyVideoFilter; // Apply the filter. - applyFunc (filter, input, output, () => - { - // When rendering is done, commit the edit to the Photos library. - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { - var request = PHAssetChangeRequest.ChangeRequest (Asset); - request.ContentEditingOutput = output; - }, (success, error) => - { - if (!success) - Console.WriteLine ($"can't edit asset: {error.LocalizedDescription}"); - }); + applyFunc (filter, input, output, () => { + // When rendering is done, commit the edit to the Photos library. + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { + var request = PHAssetChangeRequest.ChangeRequest (Asset); + request.ContentEditingOutput = output; + }, (success, error) => { + if (!success) + Console.WriteLine ($"can't edit asset: {error.LocalizedDescription}"); }); + }); }); }); } @@ -534,20 +480,18 @@ void ApplyLivePhotoFilter (CIFilter filter, PHContentEditingInput input, PHConte // to render both for previewing and for final output. var livePhotoContext = new PHLivePhotoEditingContext (input); - livePhotoContext.FrameProcessor2 = (IPHLivePhotoFrame frame, ref NSError _) => - { + livePhotoContext.FrameProcessor2 = (IPHLivePhotoFrame frame, ref NSError _) => { filter.Image = frame.Image; return filter.OutputImage; }; - livePhotoContext.SaveLivePhoto (output, (PHLivePhotoEditingOption)null, (success, error) => - { + livePhotoContext.SaveLivePhoto (output, (PHLivePhotoEditingOption) null, (success, error) => { if (success) completion (); else Console.WriteLine ("can't output live photo"); }); - // Applying edits to a Live Photo currently crashes - // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=58227 + // Applying edits to a Live Photo currently crashes + // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=58227 } void ApplyVideoFilter (CIFilter filter, PHContentEditingInput input, PHContentEditingOutput output, Action completion) @@ -558,16 +502,14 @@ void ApplyVideoFilter (CIFilter filter, PHContentEditingInput input, PHContentEd throw new InvalidProgramException ("can't get AV asset to edit"); // Set up a video composition to apply the filter. - var composition = AVVideoComposition.CreateVideoComposition (avAsset, request => - { + var composition = AVVideoComposition.CreateVideoComposition (avAsset, request => { filter.Image = request.SourceImage; var filtered = filter.OutputImage; request.Finish (filtered, null); }); // Export the video composition to the output URL. - var export = new AVAssetExportSession (avAsset, AVAssetExportSessionPreset.HighestQuality) - { + var export = new AVAssetExportSession (avAsset, AVAssetExportSessionPreset.HighestQuality) { OutputFileType = AVFileType.QuickTimeMovie, OutputUrl = output.RenderedContentUrl, VideoComposition = composition @@ -582,8 +524,7 @@ void ApplyVideoFilter (CIFilter filter, PHContentEditingInput input, PHContentEd public void PhotoLibraryDidChange (PHChange changeInstance) { // Call might come on any background queue. Re-dispatch to the main queue to handle it. - DispatchQueue.MainQueue.DispatchAsync (() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { // Check if there are changes to the asset we're displaying. PHObjectChangeDetails changeDetails = changeInstance.GetObjectChangeDetails (Asset); if (changeDetails == null) @@ -594,16 +535,14 @@ public void PhotoLibraryDidChange (PHChange changeInstance) if (assetAfterChanges == null) return; - Asset = (PHAsset)assetAfterChanges; + Asset = (PHAsset) assetAfterChanges; - if (Asset != null) - { + if (Asset != null) { FavoriteButton.Title = Asset.Favorite ? "♥︎" : "♡"; } // If the asset's content changed, update the image and stop any video playback. - if (changeDetails.AssetContentChanged) - { + if (changeDetails.AssetContentChanged) { UpdateContent (); playerLayer?.RemoveFromSuperLayer (); @@ -631,4 +570,4 @@ public virtual void WillBeginPlayback (PHLivePhotoView livePhotoView, PHLivePhot #endregion } -} \ No newline at end of file +} diff --git a/ios11/SamplePhotoApp/Shared/GridViewCell.cs b/ios11/SamplePhotoApp/Shared/GridViewCell.cs index 4f6c87afc..83837a531 100644 --- a/ios11/SamplePhotoApp/Shared/GridViewCell.cs +++ b/ios11/SamplePhotoApp/Shared/GridViewCell.cs @@ -3,27 +3,21 @@ using Foundation; using UIKit; -namespace SamplePhotoApp -{ - public partial class GridViewCell : UICollectionViewCell - { +namespace SamplePhotoApp { + public partial class GridViewCell : UICollectionViewCell { UIImage thumbnailImage; - public UIImage ThumbnailImage - { + public UIImage ThumbnailImage { get { return thumbnailImage; } - set - { + set { thumbnailImage = value; ImageView.Image = thumbnailImage; } } UIImage livePhotoBadgeImage; - public UIImage LivePhotoBadgeImage - { + public UIImage LivePhotoBadgeImage { get { return livePhotoBadgeImage; } - set - { + set { livePhotoBadgeImage = value; LivePhotoBadgeImageView.Image = livePhotoBadgeImage; } diff --git a/ios11/SamplePhotoApp/Shared/MasterViewController.cs b/ios11/SamplePhotoApp/Shared/MasterViewController.cs index cb0d59358..79c3dce7d 100644 --- a/ios11/SamplePhotoApp/Shared/MasterViewController.cs +++ b/ios11/SamplePhotoApp/Shared/MasterViewController.cs @@ -1,16 +1,13 @@ -using System; +using System; using UIKit; using Photos; using Foundation; using CoreFoundation; -namespace SamplePhotoApp -{ - public partial class MasterViewController : UITableViewController, IPHPhotoLibraryChangeObserver - { - public enum Section - { +namespace SamplePhotoApp { + public partial class MasterViewController : UITableViewController, IPHPhotoLibraryChangeObserver { + public enum Section { AllPhotos, SmartAlbums, UserCollections @@ -26,7 +23,7 @@ public enum Section PHFetchResult smartAlbums; PHFetchResult userCollections; - readonly string[] sectionLocalizedTitles = { "", "Smart Albums", "Albums" }; + readonly string [] sectionLocalizedTitles = { "", "Smart Albums", "Albums" }; public MasterViewController (IntPtr handle) : base (handle) @@ -46,9 +43,8 @@ public override void ViewDidLoad () NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Add, AddAlbum); // Create a PHFetchResult object for each section in the table view. - var allPhotosOptions = new PHFetchOptions - { - SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor ("creationDate", true) }, + var allPhotosOptions = new PHFetchOptions { + SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor ("creationDate", true) }, }; allPhotos = PHAsset.FetchAssets (allPhotosOptions); @@ -73,24 +69,19 @@ public override void ViewWillAppear (bool animated) void AddAlbum (object sender, EventArgs args) { var alertController = UIAlertController.Create ("New Album", null, UIAlertControllerStyle.Alert); - alertController.AddTextField (textField => - { + alertController.AddTextField (textField => { textField.Placeholder = "Album Name"; }); - alertController.AddAction (UIAlertAction.Create ("Create", UIAlertActionStyle.Default, action => - { - var textField = alertController.TextFields[0]; + alertController.AddAction (UIAlertAction.Create ("Create", UIAlertActionStyle.Default, action => { + var textField = alertController.TextFields [0]; var title = textField.Text; - if (!string.IsNullOrEmpty (title)) - { + if (!string.IsNullOrEmpty (title)) { // Create a new album with the title entered. - PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => - { + PHPhotoLibrary.SharedPhotoLibrary.PerformChanges (() => { PHAssetCollectionChangeRequest.CreateAssetCollection (title); - }, (success, error) => - { + }, (success, error) => { if (!success) Console.WriteLine ($"error creating album: {error}"); }); @@ -113,35 +104,33 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) destination.Title = cell.TextLabel.Text; - switch (segue.Identifier) - { - case showAllPhotos: - destination.FetchResult = allPhotos; + switch (segue.Identifier) { + case showAllPhotos: + destination.FetchResult = allPhotos; + break; + + case showCollection: + // get the asset collection for the selected row + var indexPath = TableView.IndexPathForCell (cell); + PHCollection collection = null; + switch ((Section) indexPath.Section) { + case Section.SmartAlbums: + collection = (PHAssetCollection) smartAlbums.ObjectAt (indexPath.Row); break; - case showCollection: - // get the asset collection for the selected row - var indexPath = TableView.IndexPathForCell (cell); - PHCollection collection = null; - switch ((Section)indexPath.Section) - { - case Section.SmartAlbums: - collection = (PHAssetCollection)smartAlbums.ObjectAt (indexPath.Row); - break; - - case Section.UserCollections: - collection = (PHCollection)userCollections.ObjectAt (indexPath.Row); - break; - } - - // configure the view controller with the asset collection - var assetCollection = collection as PHAssetCollection; - if (assetCollection == null) - throw new InvalidProgramException ("expected asset collection"); - - destination.FetchResult = PHAsset.FetchAssets (assetCollection, null); - destination.AssetCollection = assetCollection; + case Section.UserCollections: + collection = (PHCollection) userCollections.ObjectAt (indexPath.Row); break; + } + + // configure the view controller with the asset collection + var assetCollection = collection as PHAssetCollection; + if (assetCollection == null) + throw new InvalidProgramException ("expected asset collection"); + + destination.FetchResult = PHAsset.FetchAssets (assetCollection, null); + destination.AssetCollection = assetCollection; + break; } } @@ -156,14 +145,13 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableView, nint section) { - switch ((Section)(int)section) - { - case Section.AllPhotos: - return 1; - case Section.SmartAlbums: - return smartAlbums.Count; - case Section.UserCollections: - return userCollections.Count; + switch ((Section) (int) section) { + case Section.AllPhotos: + return 1; + case Section.SmartAlbums: + return smartAlbums.Count; + case Section.UserCollections: + return userCollections.Count; } throw new InvalidProgramException (); @@ -171,29 +159,25 @@ public override nint RowsInSection (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - switch ((Section)indexPath.Section) - { - case Section.AllPhotos: - { - var cell = tableView.DequeueReusableCell (allPhotosIdentifier, indexPath); - cell.TextLabel.Text = "All Photos"; - return cell; - } - case Section.SmartAlbums: - { - var cell = tableView.DequeueReusableCell (collectionIdentifier, indexPath); - var collection = (PHCollection)smartAlbums.ObjectAt (indexPath.Row); - cell.TextLabel.Text = collection.LocalizedTitle; - return cell; - } - case Section.UserCollections: - { - var cell = tableView.DequeueReusableCell (collectionIdentifier, indexPath); - var collection = (PHCollection)userCollections.ObjectAt (indexPath.Row); - cell.TextLabel.Text = collection.LocalizedTitle; + switch ((Section) indexPath.Section) { + case Section.AllPhotos: { + var cell = tableView.DequeueReusableCell (allPhotosIdentifier, indexPath); + cell.TextLabel.Text = "All Photos"; + return cell; + } + case Section.SmartAlbums: { + var cell = tableView.DequeueReusableCell (collectionIdentifier, indexPath); + var collection = (PHCollection) smartAlbums.ObjectAt (indexPath.Row); + cell.TextLabel.Text = collection.LocalizedTitle; + return cell; + } + case Section.UserCollections: { + var cell = tableView.DequeueReusableCell (collectionIdentifier, indexPath); + var collection = (PHCollection) userCollections.ObjectAt (indexPath.Row); + cell.TextLabel.Text = collection.LocalizedTitle; - return cell; - } + return cell; + } } throw new InvalidProgramException (); @@ -201,7 +185,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override string TitleForHeader (UITableView tableView, nint section) { - return sectionLocalizedTitles[(int)section]; + return sectionLocalizedTitles [(int) section]; } #endregion @@ -212,14 +196,12 @@ public void PhotoLibraryDidChange (PHChange changeInstance) { // Change notifications may be made on a background queue. Re-dispatch to the // main queue before acting on the change as we'll be updating the UI. - DispatchQueue.MainQueue.DispatchSync (() => - { + DispatchQueue.MainQueue.DispatchSync (() => { // Check each of the three top-level fetches for changes. // Update the cached fetch result. var changeDetails = changeInstance.GetFetchResultChangeDetails (allPhotos); - if (changeDetails != null) - { + if (changeDetails != null) { // Update the cached fetch result. allPhotos = changeDetails.FetchResultAfterChanges; // (The table row for this one doesn't need updating, it always says "All Photos".) @@ -227,17 +209,15 @@ public void PhotoLibraryDidChange (PHChange changeInstance) // Update the cached fetch results, and reload the table sections to match. changeDetails = changeInstance.GetFetchResultChangeDetails (smartAlbums); - if (changeDetails != null) - { + if (changeDetails != null) { smartAlbums = changeDetails.FetchResultAfterChanges; - TableView.ReloadSections (NSIndexSet.FromIndex ((int)Section.SmartAlbums), UITableViewRowAnimation.Automatic); + TableView.ReloadSections (NSIndexSet.FromIndex ((int) Section.SmartAlbums), UITableViewRowAnimation.Automatic); } changeDetails = changeInstance.GetFetchResultChangeDetails (userCollections); - if (changeDetails != null) - { + if (changeDetails != null) { userCollections = changeDetails.FetchResultAfterChanges; - TableView.ReloadSections (NSIndexSet.FromIndex ((int)Section.UserCollections), UITableViewRowAnimation.Automatic); + TableView.ReloadSections (NSIndexSet.FromIndex ((int) Section.UserCollections), UITableViewRowAnimation.Automatic); } }); } diff --git a/ios11/SamplePhotoApp/Shared/UICollectionViewExtensions.cs b/ios11/SamplePhotoApp/Shared/UICollectionViewExtensions.cs index 488fe7883..32f0c8535 100644 --- a/ios11/SamplePhotoApp/Shared/UICollectionViewExtensions.cs +++ b/ios11/SamplePhotoApp/Shared/UICollectionViewExtensions.cs @@ -1,14 +1,12 @@ -using System.Linq; +using System.Linq; using System.Collections.Generic; using UIKit; using Foundation; using CoreGraphics; -namespace SamplePhotoApp -{ - public static class UICollectionViewExtensions - { +namespace SamplePhotoApp { + public static class UICollectionViewExtensions { public static IEnumerable<NSIndexPath> GetIndexPaths (this UICollectionView collectionView, CGRect rect) { return collectionView.CollectionViewLayout diff --git a/ios11/SiriKitSample/TasksNotes/AppDelegate.cs b/ios11/SiriKitSample/TasksNotes/AppDelegate.cs index 3eddb88fa..2ed09223b 100644 --- a/ios11/SiriKitSample/TasksNotes/AppDelegate.cs +++ b/ios11/SiriKitSample/TasksNotes/AppDelegate.cs @@ -1,30 +1,27 @@ -using Foundation; +using Foundation; using Intents; using UIKit; -namespace TasksNotes -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - public static INSiriAuthorizationStatus SiriAuthorizationStatus { get; set; } +namespace TasksNotes { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + public static INSiriAuthorizationStatus SiriAuthorizationStatus { get; set; } - public override UIWindow Window - { - get; - set; - } + public override UIWindow Window { + get; + set; + } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } + return true; + } + } } diff --git a/ios11/SiriKitSample/TasksNotes/Main.cs b/ios11/SiriKitSample/TasksNotes/Main.cs index d7281ae23..2946ec4cc 100644 --- a/ios11/SiriKitSample/TasksNotes/Main.cs +++ b/ios11/SiriKitSample/TasksNotes/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TasksNotes -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace TasksNotes { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios11/SiriKitSample/TasksNotes/ViewController.cs b/ios11/SiriKitSample/TasksNotes/ViewController.cs index bb31d65a9..18f34a10b 100644 --- a/ios11/SiriKitSample/TasksNotes/ViewController.cs +++ b/ios11/SiriKitSample/TasksNotes/ViewController.cs @@ -1,49 +1,46 @@ -using System; +using System; using Intents; using UIKit; -namespace TasksNotes -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } +namespace TasksNotes { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. // Request access to Siri - INPreferences.RequestSiriAuthorization((INSiriAuthorizationStatus status) => { + INPreferences.RequestSiriAuthorization ((INSiriAuthorizationStatus status) => { // Respond to returned status - switch (status) - { - case INSiriAuthorizationStatus.Authorized: - Console.WriteLine("SiriKit Authorized"); - break; - case INSiriAuthorizationStatus.Denied: - Console.WriteLine("SiriKit Denied"); - break; - case INSiriAuthorizationStatus.NotDetermined: - Console.WriteLine("SiriKit Not Determined"); - break; - case INSiriAuthorizationStatus.Restricted: - Console.WriteLine("SiriKit Restricted"); - break; + switch (status) { + case INSiriAuthorizationStatus.Authorized: + Console.WriteLine ("SiriKit Authorized"); + break; + case INSiriAuthorizationStatus.Denied: + Console.WriteLine ("SiriKit Denied"); + break; + case INSiriAuthorizationStatus.NotDetermined: + Console.WriteLine ("SiriKit Not Determined"); + break; + case INSiriAuthorizationStatus.Restricted: + Console.WriteLine ("SiriKit Restricted"); + break; } // Save status AppDelegate.SiriAuthorizationStatus = status; }); - } + } - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - // Release any cached data, images, etc that aren't in use. - } - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + // Release any cached data, images, etc that aren't in use. + } + } } diff --git a/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Notes.cs b/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Notes.cs index 36ce84b58..d2a174e22 100644 --- a/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Notes.cs +++ b/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Notes.cs @@ -1,28 +1,26 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using Intents; -namespace TasksNotesSiriIntent -{ - public partial class IntentHandler - { - public void HandleAppendToNote(INAppendToNoteIntent intent, Action<INAppendToNoteIntentResponse> completion) +namespace TasksNotesSiriIntent { + public partial class IntentHandler { + public void HandleAppendToNote (INAppendToNoteIntent intent, Action<INAppendToNoteIntentResponse> completion) { - throw new NotImplementedException(); + throw new NotImplementedException (); } - public void HandleCreateNote(INCreateNoteIntent intent, Action<INCreateNoteIntentResponse> completion) + public void HandleCreateNote (INCreateNoteIntent intent, Action<INCreateNoteIntentResponse> completion) { - throw new NotImplementedException(); + throw new NotImplementedException (); } - public void HandleSearchForNotebookItems(INSearchForNotebookItemsIntent intent, Action<INSearchForNotebookItemsIntentResponse> completion) + public void HandleSearchForNotebookItems (INSearchForNotebookItemsIntent intent, Action<INSearchForNotebookItemsIntentResponse> completion) { - Console.WriteLine("HandleSearchForNotebookItems"); - throw new NotImplementedException(); + Console.WriteLine ("HandleSearchForNotebookItems"); + throw new NotImplementedException (); } - } + } } diff --git a/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Tasks.cs b/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Tasks.cs index 6c421b619..736792252 100644 --- a/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Tasks.cs +++ b/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler+Tasks.cs @@ -1,36 +1,32 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using Intents; -namespace TasksNotesSiriIntent -{ - public partial class IntentHandler - { +namespace TasksNotesSiriIntent { + public partial class IntentHandler { /* https://developer.apple.com/documentation/sirikit/resolving_and_handling_intents/handling_an_intent */ - public void HandleAddTasks(INAddTasksIntent intent, Action<INAddTasksIntentResponse> completion) + public void HandleAddTasks (INAddTasksIntent intent, Action<INAddTasksIntentResponse> completion) { - Console.WriteLine("Add a task"); - var userActivity = new NSUserActivity("INAddTasksIntent"); // https://developer.apple.com/documentation/sirikit/resolving_and_handling_intents/confirming_the_details_of_an_intent + Console.WriteLine ("Add a task"); + var userActivity = new NSUserActivity ("INAddTasksIntent"); // https://developer.apple.com/documentation/sirikit/resolving_and_handling_intents/confirming_the_details_of_an_intent - var tasklist = TaskList.FromIntent(intent); + var tasklist = TaskList.FromIntent (intent); //if tasks array is empty but a group name is specified, maybe convert it into a task? - - // TODO: have to create the list and tasks... in your app data store - - var response = new INAddTasksIntentResponse(INAddTasksIntentResponseCode.Success, userActivity) - { - AddedTasks = tasklist.Tasks, + + // TODO: have to create the list and tasks... in your app data store + + var response = new INAddTasksIntentResponse (INAddTasksIntentResponseCode.Success, userActivity) { + AddedTasks = tasklist.Tasks, }; - if (intent.TargetTaskList != null) - { - response.ModifiedTaskList = tasklist; - } - completion(response); + if (intent.TargetTaskList != null) { + response.ModifiedTaskList = tasklist; + } + completion (response); } /// <summary> @@ -38,18 +34,17 @@ public void HandleAddTasks(INAddTasksIntent intent, Action<INAddTasksIntentRespo /// </summary> /// <remarks> /// "Make a grocery list with apples, bananas, and pears in TasksNotes" - /// </remarks> - public void HandleCreateTaskList(INCreateTaskListIntent intent, Action<INCreateTaskListIntentResponse> completion) + /// </remarks> + public void HandleCreateTaskList (INCreateTaskListIntent intent, Action<INCreateTaskListIntentResponse> completion) { - Console.WriteLine("Create a task list"); - var userActivity = new NSUserActivity("INCreateTaskListIntent"); - var list = TaskList.FromIntent(intent); - // TODO: have to create the list and tasks... in your app data store - var response = new INCreateTaskListIntentResponse(INCreateTaskListIntentResponseCode.Success, userActivity) - { - CreatedTaskList = list + Console.WriteLine ("Create a task list"); + var userActivity = new NSUserActivity ("INCreateTaskListIntent"); + var list = TaskList.FromIntent (intent); + // TODO: have to create the list and tasks... in your app data store + var response = new INCreateTaskListIntentResponse (INCreateTaskListIntentResponseCode.Success, userActivity) { + CreatedTaskList = list }; - completion(response); + completion (response); } @@ -59,20 +54,19 @@ public void HandleCreateTaskList(INCreateTaskListIntent intent, Action<INCreateT /// <remarks> /// "Mark buy iPhone as completed in TasksNotes" /// </remarks> - public void HandleSetTaskAttribute(INSetTaskAttributeIntent intent, Action<INSetTaskAttributeIntentResponse> completion) + public void HandleSetTaskAttribute (INSetTaskAttributeIntent intent, Action<INSetTaskAttributeIntentResponse> completion) { - Console.WriteLine("Set task attribute"); - var userActivity = new NSUserActivity("INSetTaskAttributeIntent"); + Console.WriteLine ("Set task attribute"); + var userActivity = new NSUserActivity ("INSetTaskAttributeIntent"); - var task = Task.FromIntent(intent); + var task = Task.FromIntent (intent); // TODO: have to actually confirm the task exists and then change its status... in your app data store task.Status = intent.Status; - var response = new INSetTaskAttributeIntentResponse(INSetTaskAttributeIntentResponseCode.Success, userActivity) - { - ModifiedTask = task.ForResponse() - }; - completion(response); + var response = new INSetTaskAttributeIntentResponse (INSetTaskAttributeIntentResponseCode.Success, userActivity) { + ModifiedTask = task.ForResponse () + }; + completion (response); } - } + } } diff --git a/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler.cs b/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler.cs index 2e558ca60..dc2a1f447 100644 --- a/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler.cs +++ b/ios11/SiriKitSample/TasksNotesSiriIntent/IntentHandler.cs @@ -1,17 +1,15 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using Intents; -namespace TasksNotesSiriIntent -{ +namespace TasksNotesSiriIntent { // As an example, this class is set up to handle Tasks and Lists intents. // // The intents you wish to handle must be declared in the extension's Info.plist. - [Register("IntentHandler")] - public partial class IntentHandler : INExtension, IINNotebookDomainHandling - { + [Register ("IntentHandler")] + public partial class IntentHandler : INExtension, IINNotebookDomainHandling { /* The IINNotebookDomainHandling interface includes all the following, which you could alternatively implement seperately: - IINAddTasksIntentHandling, - IINAppendToNoteIntentHandling, @@ -26,16 +24,16 @@ public partial class IntentHandler : INExtension, IINNotebookDomainHandling for the implmementations of these interfaces */ - protected IntentHandler(IntPtr handle) : base(handle) + protected IntentHandler (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override NSObject GetHandler(INIntent intent) + public override NSObject GetHandler (INIntent intent) { // This is the default implementation. If you want different objects to handle different intents, // you can override this and return the handler you want for that particular intent. return this; } - } + } } diff --git a/ios11/SiriKitSample/TasksNotesSiriIntent/Tasks.cs b/ios11/SiriKitSample/TasksNotesSiriIntent/Tasks.cs index 609cafeb2..377b79984 100644 --- a/ios11/SiriKitSample/TasksNotesSiriIntent/Tasks.cs +++ b/ios11/SiriKitSample/TasksNotesSiriIntent/Tasks.cs @@ -1,92 +1,84 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using Intents; -namespace TasksNotesSiriIntent -{ - /// <summary> - /// Helper class - /// </summary> - public class TaskList - { - //public TaskList() - //{ - //} +namespace TasksNotesSiriIntent { + /// <summary> + /// Helper class + /// </summary> + public class TaskList { + //public TaskList() + //{ + //} - //public INSpeakableString GroupName { get; set; } - //public INSpeakableString Title { get; set; } + //public INSpeakableString GroupName { get; set; } + //public INSpeakableString Title { get; set; } - //public INSpatialEventTrigger Place { get; set; } - //public INTemporalEventTrigger Time { get; set; } + //public INSpatialEventTrigger Place { get; set; } + //public INTemporalEventTrigger Time { get; set; } - //public List<INTask> Tasks { get; set; } + //public List<INTask> Tasks { get; set; } - //public INTaskList ForResponse() - //{ - // return new INTaskList(Title, Tasks.ToArray(), GroupName, null, null, "id"); - //} + //public INTaskList ForResponse() + //{ + // return new INTaskList(Title, Tasks.ToArray(), GroupName, null, null, "id"); + //} - public static INTaskList FromIntent(INCreateTaskListIntent intent) + public static INTaskList FromIntent (INCreateTaskListIntent intent) { - var tasks = new List<INTask>(); - if (intent.TaskTitles != null) - { - foreach (var t in intent.TaskTitles) - { - tasks.Add(new INTask(t, INTaskStatus.NotCompleted, INTaskType.Completable, null, null, null, null, "mytask")); + var tasks = new List<INTask> (); + if (intent.TaskTitles != null) { + foreach (var t in intent.TaskTitles) { + tasks.Add (new INTask (t, INTaskStatus.NotCompleted, INTaskType.Completable, null, null, null, null, "mytask")); } } - return new INTaskList(intent.Title, tasks.ToArray(), intent.GroupName, null, null, "mylist"); + return new INTaskList (intent.Title, tasks.ToArray (), intent.GroupName, null, null, "mylist"); } - public static INTaskList FromIntent (INAddTasksIntent intent) - { - var tasks = new List<INTask>(); - INSpeakableString title = new INSpeakableString(""); - INSpeakableString groupname = new INSpeakableString(""); - - if (intent.TargetTaskList != null) - { - title = intent.TargetTaskList.Title; + public static INTaskList FromIntent (INAddTasksIntent intent) + { + var tasks = new List<INTask> (); + INSpeakableString title = new INSpeakableString (""); + INSpeakableString groupname = new INSpeakableString (""); + + if (intent.TargetTaskList != null) { + title = intent.TargetTaskList.Title; } - if (intent.TaskTitles != null) - { - foreach (var t in intent.TaskTitles) - { - tasks.Add(new INTask (t, INTaskStatus.NotCompleted, INTaskType.Completable, null, null, null, null, "mytask")); + if (intent.TaskTitles != null) { + foreach (var t in intent.TaskTitles) { + tasks.Add (new INTask (t, INTaskStatus.NotCompleted, INTaskType.Completable, null, null, null, null, "mytask")); } } - - return new INTaskList(title, tasks.ToArray(), groupname, null, null, "mylist"); - } - } + + return new INTaskList (title, tasks.ToArray (), groupname, null, null, "mylist"); + } + } /// <summary> /// Helper class /// </summary> - public class Task - { - public Task () - { - } + public class Task { + public Task () + { + } - public INSpeakableString Title { get; set; } - public INTaskStatus Status { get; set; } = INTaskStatus.NotCompleted; - public INTaskType Type { get; set; } = INTaskType.Completable; + public INSpeakableString Title { get; set; } + public INTaskStatus Status { get; set; } = INTaskStatus.NotCompleted; + public INTaskType Type { get; set; } = INTaskType.Completable; - public INTask ForResponse() - { - return new INTask(Title, Status, Type, null, null, null, null, "id"); - } + public INTask ForResponse () + { + return new INTask (Title, Status, Type, null, null, null, null, "id"); + } - public static Task FromIntent (INSetTaskAttributeIntent intent) - { - var task = new Task(); - task.Title = intent.TargetTask.Title; - task.Status = intent.TargetTask.Status; - task.Type = intent.TargetTask.TaskType; - return task; - } - } + public static Task FromIntent (INSetTaskAttributeIntent intent) + { + var task = new Task (); + task.Title = intent.TargetTask.Title; + task.Status = intent.TargetTask.Status; + task.Type = intent.TargetTask.TaskType; + return task; + } + } } diff --git a/ios11/SiriKitSample/TasksNotesSiriIntentUI/IntentViewController.cs b/ios11/SiriKitSample/TasksNotesSiriIntentUI/IntentViewController.cs index 19cf3a2fb..6dce02556 100644 --- a/ios11/SiriKitSample/TasksNotesSiriIntentUI/IntentViewController.cs +++ b/ios11/SiriKitSample/TasksNotesSiriIntentUI/IntentViewController.cs @@ -1,52 +1,50 @@ -using System; +using System; using CoreGraphics; using Intents; using IntentsUI; using UIKit; -namespace TasksNotesSiriIntentUI -{ - /* +namespace TasksNotesSiriIntentUI { + /* This sample does not currently customize the IntentUI The project has been included for customization by you! */ - public partial class IntentViewController : UIViewController, IINUIHostedViewControlling - { - protected IntentViewController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Do any required interface initialization here. - } - - public override void DidReceiveMemoryWarning() - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning(); - - // Release any cached data, images, etc that aren't in use. - } - - public void Configure(INInteraction interaction, INUIHostedViewContext context, Action<CGSize> completion) - { - // Do configuration here, including preparing views and calculating a desired size for presentation. - - if (completion != null) - completion(DesiredSize()); - } - - CGSize DesiredSize() - { - return ExtensionContext.GetHostedViewMaximumAllowedSize(); - } - } + public partial class IntentViewController : UIViewController, IINUIHostedViewControlling { + protected IntentViewController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Do any required interface initialization here. + } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + public void Configure (INInteraction interaction, INUIHostedViewContext context, Action<CGSize> completion) + { + // Do configuration here, including preparing views and calculating a desired size for presentation. + + if (completion != null) + completion (DesiredSize ()); + } + + CGSize DesiredSize () + { + return ExtensionContext.GetHostedViewMaximumAllowedSize (); + } + } } diff --git a/ios11/VisionFaces/VisionFaces/AppDelegate.cs b/ios11/VisionFaces/VisionFaces/AppDelegate.cs index 60ee755b0..f3f850367 100644 --- a/ios11/VisionFaces/VisionFaces/AppDelegate.cs +++ b/ios11/VisionFaces/VisionFaces/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace VisionFramework -{ +namespace VisionFramework { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/VisionFaces/VisionFaces/ClassExtensions/CGPointExtensions.cs b/ios11/VisionFaces/VisionFaces/ClassExtensions/CGPointExtensions.cs index 6dbfaaad4..34283c533 100644 --- a/ios11/VisionFaces/VisionFaces/ClassExtensions/CGPointExtensions.cs +++ b/ios11/VisionFaces/VisionFaces/ClassExtensions/CGPointExtensions.cs @@ -1,13 +1,12 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace VisionFramework -{ - public static class CGPointExtensions - { - public static CGPoint Scaled(this CGPoint self, CGSize size) { - return new CGPoint(self.X * size.Width, self.Y * size.Height); +namespace VisionFramework { + public static class CGPointExtensions { + public static CGPoint Scaled (this CGPoint self, CGSize size) + { + return new CGPoint (self.X * size.Width, self.Y * size.Height); } } } diff --git a/ios11/VisionFaces/VisionFaces/ClassExtensions/CGRectExtensions.cs b/ios11/VisionFaces/VisionFaces/ClassExtensions/CGRectExtensions.cs index 6bb645172..920581d30 100644 --- a/ios11/VisionFaces/VisionFaces/ClassExtensions/CGRectExtensions.cs +++ b/ios11/VisionFaces/VisionFaces/ClassExtensions/CGRectExtensions.cs @@ -1,16 +1,15 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace VisionFramework -{ - public static class CGRectExtensions - { - public static CGRect Scaled(this CGRect self, CGSize size) { - return new CGRect(self.X * size.Width, - self.Y * size.Height, - self.Size.Width * size.Width, - self.Size.Height * size.Height); +namespace VisionFramework { + public static class CGRectExtensions { + public static CGRect Scaled (this CGRect self, CGSize size) + { + return new CGRect (self.X * size.Width, + self.Y * size.Height, + self.Size.Width * size.Width, + self.Size.Height * size.Height); } } } diff --git a/ios11/VisionFaces/VisionFaces/ClassExtensions/DictionaryExtensions.cs b/ios11/VisionFaces/VisionFaces/ClassExtensions/DictionaryExtensions.cs index 92deec4e6..249482120 100644 --- a/ios11/VisionFaces/VisionFaces/ClassExtensions/DictionaryExtensions.cs +++ b/ios11/VisionFaces/VisionFaces/ClassExtensions/DictionaryExtensions.cs @@ -1,44 +1,42 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using CoreGraphics; using CoreImage; -namespace VisionFramework -{ - public static class DictionaryExtensions - { - public static NSDictionary<NSString, CIVector> ToNSDictionary(this Dictionary<string, CGPoint> self){ +namespace VisionFramework { + public static class DictionaryExtensions { + public static NSDictionary<NSString, CIVector> ToNSDictionary (this Dictionary<string, CGPoint> self) + { - var keys = new List<NSString>(); - var values = new List<CIVector>(); + var keys = new List<NSString> (); + var values = new List<CIVector> (); // Process all keys in the dictionary - foreach(string key in self.Keys) { - keys.Add(new NSString(key)); - values.Add(new CIVector(self[key])); + foreach (string key in self.Keys) { + keys.Add (new NSString (key)); + values.Add (new CIVector (self [key])); } // Return results - return new NSDictionary<NSString, CIVector>(keys.ToArray(), values.ToArray()); + return new NSDictionary<NSString, CIVector> (keys.ToArray (), values.ToArray ()); } - public static NSDictionary<NSString, NSNumber> ToNSDictionary(this Dictionary<NSString, NSNumber> self) + public static NSDictionary<NSString, NSNumber> ToNSDictionary (this Dictionary<NSString, NSNumber> self) { - var keys = new List<NSString>(); - var values = new List<NSNumber>(); + var keys = new List<NSString> (); + var values = new List<NSNumber> (); // Process all keys in the dictionary - foreach (NSString key in self.Keys) - { - keys.Add(key); - values.Add(self[key]); + foreach (NSString key in self.Keys) { + keys.Add (key); + values.Add (self [key]); } // Return results - return new NSDictionary<NSString, NSNumber>(keys.ToArray(), values.ToArray()); + return new NSDictionary<NSString, NSNumber> (keys.ToArray (), values.ToArray ()); } } } diff --git a/ios11/VisionFaces/VisionFaces/ClassExtensions/UIImageOrientationExtensions.cs b/ios11/VisionFaces/VisionFaces/ClassExtensions/UIImageOrientationExtensions.cs index a461260fc..9bb25eb8d 100644 --- a/ios11/VisionFaces/VisionFaces/ClassExtensions/UIImageOrientationExtensions.cs +++ b/ios11/VisionFaces/VisionFaces/ClassExtensions/UIImageOrientationExtensions.cs @@ -1,60 +1,59 @@ -using System; +using System; using UIKit; using CoreGraphics; using CoreImage; using ImageIO; -namespace VisionFramework -{ - public static class UIImageOrientationExtensions - { - public static CGImagePropertyOrientation ToCGImagePropertyOrientation(this UIImageOrientation self) { +namespace VisionFramework { + public static class UIImageOrientationExtensions { + public static CGImagePropertyOrientation ToCGImagePropertyOrientation (this UIImageOrientation self) + { // Take action based on value - switch(self) { - case UIImageOrientation.Up: - return CGImagePropertyOrientation.Up; - case UIImageOrientation.UpMirrored: - return CGImagePropertyOrientation.UpMirrored; - case UIImageOrientation.Down: - return CGImagePropertyOrientation.Down; - case UIImageOrientation.DownMirrored: - return CGImagePropertyOrientation.DownMirrored; - case UIImageOrientation.Left: - return CGImagePropertyOrientation.Left; - case UIImageOrientation.LeftMirrored: - return CGImagePropertyOrientation.LeftMirrored; - case UIImageOrientation.Right: - return CGImagePropertyOrientation.Right; - case UIImageOrientation.RightMirrored: - return CGImagePropertyOrientation.RightMirrored; + switch (self) { + case UIImageOrientation.Up: + return CGImagePropertyOrientation.Up; + case UIImageOrientation.UpMirrored: + return CGImagePropertyOrientation.UpMirrored; + case UIImageOrientation.Down: + return CGImagePropertyOrientation.Down; + case UIImageOrientation.DownMirrored: + return CGImagePropertyOrientation.DownMirrored; + case UIImageOrientation.Left: + return CGImagePropertyOrientation.Left; + case UIImageOrientation.LeftMirrored: + return CGImagePropertyOrientation.LeftMirrored; + case UIImageOrientation.Right: + return CGImagePropertyOrientation.Right; + case UIImageOrientation.RightMirrored: + return CGImagePropertyOrientation.RightMirrored; } // Default to up return CGImagePropertyOrientation.Up; } - public static CIImageOrientation ToCIImageOrientation(this UIImageOrientation self) { + public static CIImageOrientation ToCIImageOrientation (this UIImageOrientation self) + { // Take action based on value - switch (self) - { - case UIImageOrientation.Up: - return CIImageOrientation.TopLeft; - case UIImageOrientation.UpMirrored: - return CIImageOrientation.TopRight; - case UIImageOrientation.Down: - return CIImageOrientation.BottomLeft; - case UIImageOrientation.DownMirrored: - return CIImageOrientation.BottomRight; - case UIImageOrientation.Left: - return CIImageOrientation.LeftTop; - case UIImageOrientation.LeftMirrored: - return CIImageOrientation.LeftBottom; - case UIImageOrientation.Right: - return CIImageOrientation.RightTop; - case UIImageOrientation.RightMirrored: - return CIImageOrientation.RightBottom; + switch (self) { + case UIImageOrientation.Up: + return CIImageOrientation.TopLeft; + case UIImageOrientation.UpMirrored: + return CIImageOrientation.TopRight; + case UIImageOrientation.Down: + return CIImageOrientation.BottomLeft; + case UIImageOrientation.DownMirrored: + return CIImageOrientation.BottomRight; + case UIImageOrientation.Left: + return CIImageOrientation.LeftTop; + case UIImageOrientation.LeftMirrored: + return CIImageOrientation.LeftBottom; + case UIImageOrientation.Right: + return CIImageOrientation.RightTop; + case UIImageOrientation.RightMirrored: + return CIImageOrientation.RightBottom; } // Default to up diff --git a/ios11/VisionFaces/VisionFaces/Main.cs b/ios11/VisionFaces/VisionFaces/Main.cs index 7a13e29ce..9d8e47b21 100644 --- a/ios11/VisionFaces/VisionFaces/Main.cs +++ b/ios11/VisionFaces/VisionFaces/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace VisionFramework -{ - public class Application - { +namespace VisionFramework { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/VisionFaces/VisionFaces/ViewController.cs b/ios11/VisionFaces/VisionFaces/ViewController.cs index bb6417149..381de741d 100644 --- a/ios11/VisionFaces/VisionFaces/ViewController.cs +++ b/ios11/VisionFaces/VisionFaces/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; using Vision; @@ -6,260 +6,249 @@ using CoreFoundation; using CoreGraphics; -namespace VisionFramework -{ - public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUINavigationControllerDelegate - { +namespace VisionFramework { + public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUINavigationControllerDelegate { CIImage InputImage; - UIImage RawImage; + UIImage RawImage; VNDetectFaceRectanglesRequest FaceRectangleRequest; - - protected ViewController(IntPtr handle) : base(handle) + + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - - public override void ViewDidLoad() + + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Configure UI - CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera); - GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum); + CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera); + GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum); + + // Setup Vision Faces Request + FaceRectangleRequest = new VNDetectFaceRectanglesRequest (HandleRectangles); + } - // Setup Vision Faces Request - FaceRectangleRequest = new VNDetectFaceRectanglesRequest(HandleRectangles); - } - - void HandleRectangles(VNRequest request, NSError error){ + void HandleRectangles (VNRequest request, NSError error) + { - var observations = request.GetResults<VNFaceObservation>(); + var observations = request.GetResults<VNFaceObservation> (); if (observations == null) { - ShowAlert("Processing Error","Unexpected result type from VNDetectFaceRectanglesRequest."); + ShowAlert ("Processing Error", "Unexpected result type from VNDetectFaceRectanglesRequest."); return; } if (observations.Length < 1) { - DispatchQueue.MainQueue.DispatchAsync(()=>{ + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "No faces detected."; }); return; - } - - var summary = ""; - var imageSize = InputImage.Extent.Size; - bool atLeastOneValid = false; - Console.WriteLine("Faces:"); - summary += "Faces:" + Environment.NewLine; - foreach (var o in observations){ - + } + + var summary = ""; + var imageSize = InputImage.Extent.Size; + bool atLeastOneValid = false; + Console.WriteLine ("Faces:"); + summary += "Faces:" + Environment.NewLine; + foreach (var o in observations) { + // Verify detected face rectangle is valid. - var boundingBox = o.BoundingBox.Scaled(imageSize); - if (!InputImage.Extent.Contains(boundingBox)) - { - Console.WriteLine(" --- Faces out of bounds: " + boundingBox); - summary += " --- Faces out of bounds:" + boundingBox + Environment.NewLine; - } else { - Console.WriteLine(o.BoundingBox); + var boundingBox = o.BoundingBox.Scaled (imageSize); + if (!InputImage.Extent.Contains (boundingBox)) { + Console.WriteLine (" --- Faces out of bounds: " + boundingBox); + summary += " --- Faces out of bounds:" + boundingBox + Environment.NewLine; + } else { + Console.WriteLine (o.BoundingBox); summary += o.BoundingBox + Environment.NewLine; - atLeastOneValid |= true; - } - } + atLeastOneValid |= true; + } + } - if (!atLeastOneValid) - { - DispatchQueue.MainQueue.DispatchAsync(() => { + if (!atLeastOneValid) { + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "No _valid_ faces detected." + Environment.NewLine + summary; }); - return; - } - - // Show the pre-processed image - DispatchQueue.MainQueue.DispatchAsync(() => - { - ClassificationLabel.Text = summary; - ClassificationLabel.Lines = 0; - ImageView.Image = OverlayRectangles(RawImage, imageSize, observations); + return; + } + + // Show the pre-processed image + DispatchQueue.MainQueue.DispatchAsync (() => { + ClassificationLabel.Text = summary; + ClassificationLabel.Lines = 0; + ImageView.Image = OverlayRectangles (RawImage, imageSize, observations); }); - + } - public static UIImage OverlayRectangles(UIImage uiImage, CGSize imageSize, VNFaceObservation[] observations) + public static UIImage OverlayRectangles (UIImage uiImage, CGSize imageSize, VNFaceObservation [] observations) { nfloat fWidth = uiImage.Size.Width; nfloat fHeight = uiImage.Size.Height; - CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); - - using (CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, (nint)fWidth, (nint)fHeight, 8, 4 * (nint)fWidth, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) - { - Console.WriteLine("Orientation:" +uiImage.Orientation); - - if (uiImage.Orientation == UIImageOrientation.Up) - { // correct orientation - ctx.DrawImage(new CGRect(0, 0, (double)fWidth, (double)fHeight), uiImage.CGImage); - } - else - { // need to rotate image so that rectangle overlays match - UIGraphics.BeginImageContextWithOptions(uiImage.Size, false, 0); - uiImage.Draw(new CGRect(0, 0, (double)fWidth, (double)fHeight)); - var img = UIGraphics.GetImageFromCurrentImageContext(); - UIGraphics.EndImageContext(); - ctx.DrawImage(new CGRect(0, 0, (double)fWidth, (double)fHeight), img.CGImage); - } + CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB (); + + using (CGBitmapContext ctx = new CGBitmapContext (IntPtr.Zero, (nint) fWidth, (nint) fHeight, 8, 4 * (nint) fWidth, CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { + Console.WriteLine ("Orientation:" + uiImage.Orientation); + + if (uiImage.Orientation == UIImageOrientation.Up) { // correct orientation + ctx.DrawImage (new CGRect (0, 0, (double) fWidth, (double) fHeight), uiImage.CGImage); + } else { // need to rotate image so that rectangle overlays match + UIGraphics.BeginImageContextWithOptions (uiImage.Size, false, 0); + uiImage.Draw (new CGRect (0, 0, (double) fWidth, (double) fHeight)); + var img = UIGraphics.GetImageFromCurrentImageContext (); + UIGraphics.EndImageContext (); + ctx.DrawImage (new CGRect (0, 0, (double) fWidth, (double) fHeight), img.CGImage); + } var count = 0; - foreach (var o in observations) - { + foreach (var o in observations) { // Draw rectangle - var text = "Face: " + count++.ToString(); - Console.WriteLine(o.BoundingBox + " " + o.Confidence); - - // Fudge/switch coordinates to match UIImage - var topLeft = new CGPoint(o.BoundingBox.Left, o.BoundingBox.Top).Scaled(imageSize); - var topRight = new CGPoint(o.BoundingBox.Left, o.BoundingBox.Bottom).Scaled(imageSize); - var bottomLeft = new CGPoint(o.BoundingBox.Right, o.BoundingBox.Top).Scaled(imageSize); - var bottomRight = new CGPoint(o.BoundingBox.Right, o.BoundingBox.Bottom).Scaled(imageSize); + var text = "Face: " + count++.ToString (); + Console.WriteLine (o.BoundingBox + " " + o.Confidence); + + // Fudge/switch coordinates to match UIImage + var topLeft = new CGPoint (o.BoundingBox.Left, o.BoundingBox.Top).Scaled (imageSize); + var topRight = new CGPoint (o.BoundingBox.Left, o.BoundingBox.Bottom).Scaled (imageSize); + var bottomLeft = new CGPoint (o.BoundingBox.Right, o.BoundingBox.Top).Scaled (imageSize); + var bottomRight = new CGPoint (o.BoundingBox.Right, o.BoundingBox.Bottom).Scaled (imageSize); - //set up drawing attributes - ctx.SetStrokeColor(UIColor.Red.CGColor); - ctx.SetLineWidth(10); + //set up drawing attributes + ctx.SetStrokeColor (UIColor.Red.CGColor); + ctx.SetLineWidth (10); - //create geometry - var path = new CGPath(); + //create geometry + var path = new CGPath (); - path.AddLines(new CGPoint[]{ - topLeft, topRight, bottomRight, bottomLeft - }); + path.AddLines (new CGPoint []{ + topLeft, topRight, bottomRight, bottomLeft + }); - path.CloseSubpath(); + path.CloseSubpath (); - //add geometry to graphics context and draw it - ctx.AddPath(path); - ctx.DrawPath(CGPathDrawingMode.Stroke); + //add geometry to graphics context and draw it + ctx.AddPath (path); + ctx.DrawPath (CGPathDrawingMode.Stroke); - // Draw text - ctx.SelectFont("Helvetica", 60, CGTextEncoding.MacRoman); + // Draw text + ctx.SelectFont ("Helvetica", 60, CGTextEncoding.MacRoman); //Measure the text's width - This involves drawing an invisible string to calculate the X position difference float start, end, textWidth; //Get the texts current position - start = (float)ctx.TextPosition.X; + start = (float) ctx.TextPosition.X; //Set the drawing mode to invisible - ctx.SetTextDrawingMode(CGTextDrawingMode.Invisible); + ctx.SetTextDrawingMode (CGTextDrawingMode.Invisible); //Draw the text at the current position - ctx.ShowText(text); + ctx.ShowText (text); //Get the end position - end = (float)ctx.TextPosition.X; + end = (float) ctx.TextPosition.X; //Subtract start from end to get the text's width textWidth = end - start; ctx.SetFillColor (UIColor.Red.CGColor); //Set the drawing mode back to something that will actually draw Fill for example - ctx.SetTextDrawingMode(CGTextDrawingMode.Fill); + ctx.SetTextDrawingMode (CGTextDrawingMode.Fill); //Draw the text at given coords. - ctx.ShowTextAtPoint (topLeft.X, topLeft.Y - 60, text); + ctx.ShowTextAtPoint (topLeft.X, topLeft.Y - 60, text); } - return UIImage.FromImage(ctx.ToImage()); + return UIImage.FromImage (ctx.ToImage ()); } } - void ShowAlert(string title, string message) + void ShowAlert (string title, string message) { //Create Alert - var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); + var okAlertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); //Add Action - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); // Present Alert - PresentViewController(okAlertController, true, null); + PresentViewController (okAlertController, true, null); } #region UIImagePickerControllerDelegate - [Export("imagePickerController:didFinishPickingMediaWithInfo:")] - public void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) + [Export ("imagePickerController:didFinishPickingMediaWithInfo:")] + public void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) { // Close the picker - picker.DismissViewController(true, null); + picker.DismissViewController (true, null); // Update UI - ClassificationLabel.Text = "Analyzing Image (please wait)..."; - + ClassificationLabel.Text = "Analyzing Image (please wait)..."; + // Read Image from returned data - var uiImage = info[UIImagePickerController.OriginalImage] as UIImage; + var uiImage = info [UIImagePickerController.OriginalImage] as UIImage; if (uiImage == null) { - ShowAlert("Processing Error","Unable to read image from picker."); + ShowAlert ("Processing Error", "Unable to read image from picker."); return; } // Convert to CIImage - var ciImage = new CIImage(uiImage); + var ciImage = new CIImage (uiImage); if (ciImage == null) { - ShowAlert("Processing Error", "Unable to create required CIImage from UIImage."); + ShowAlert ("Processing Error", "Unable to create required CIImage from UIImage."); return; } - InputImage = ciImage.CreateWithOrientation(uiImage.Orientation.ToCIImageOrientation()); + InputImage = ciImage.CreateWithOrientation (uiImage.Orientation.ToCIImageOrientation ()); // Show source image ImageView.Image = uiImage; - RawImage = uiImage; + RawImage = uiImage; // Run the face detector - var handler = new VNImageRequestHandler(ciImage, uiImage.Orientation.ToCGImagePropertyOrientation(), new VNImageOptions()); - DispatchQueue.DefaultGlobalQueue.DispatchAsync(()=>{ - NSError error; - handler.Perform(new VNRequest[] {FaceRectangleRequest}, out error); + var handler = new VNImageRequestHandler (ciImage, uiImage.Orientation.ToCGImagePropertyOrientation (), new VNImageOptions ()); + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + NSError error; + handler.Perform (new VNRequest [] { FaceRectangleRequest }, out error); }); } #endregion #region Custom Actions - [Action("TakePicture:")] - public void TakePicture(NSObject sender) { + [Action ("TakePicture:")] + public void TakePicture (NSObject sender) + { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable( UIImagePickerControllerSourceType.Camera)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = this, SourceType = UIImagePickerControllerSourceType.Camera, CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } - [Action("ChooseImage:")] - public void ChooseImage(NSObject senter) { + [Action ("ChooseImage:")] + public void ChooseImage (NSObject senter) + { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the camera is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the camera is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = this, SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } #endregion } diff --git a/ios11/VisionObjectTracker/ObjectTracker/AppDelegate.cs b/ios11/VisionObjectTracker/ObjectTracker/AppDelegate.cs index 565b88c32..28f39ee2e 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/AppDelegate.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/AppDelegate.cs @@ -1,27 +1,24 @@ -using Foundation; +using Foundation; using UIKit; -namespace ObjectTracker -{ +namespace ObjectTracker { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -29,25 +26,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/VisionObjectTracker/ObjectTracker/EventArgsT.cs b/ios11/VisionObjectTracker/ObjectTracker/EventArgsT.cs index 6a9b5aac5..094c468c7 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/EventArgsT.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/EventArgsT.cs @@ -1,13 +1,11 @@ -using System; +using System; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// Strongly typed EventArgs class /// </summary> - public class EventArgsT<T> : EventArgs - { + public class EventArgsT<T> : EventArgs { public T Value { get; } - public EventArgsT(T val) => Value = val; + public EventArgsT (T val) => Value = val; } } diff --git a/ios11/VisionObjectTracker/ObjectTracker/Extensions.cs b/ios11/VisionObjectTracker/ObjectTracker/Extensions.cs index 71c64f91b..3a7e505b4 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/Extensions.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/Extensions.cs @@ -1,21 +1,19 @@ -using CoreGraphics; +using CoreGraphics; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// Provides extensions methods for normalized points and rectangles (most Vision measurements are in /// units normalized to the range [0, 1]. /// </summary> - public static class Extensions - { - public static CGPoint Scaled(this CGPoint self, CGSize size) + public static class Extensions { + public static CGPoint Scaled (this CGPoint self, CGSize size) { - return new CGPoint(self.X * size.Width, self.Y * size.Height); + return new CGPoint (self.X * size.Width, self.Y * size.Height); } - public static CGRect Scaled(this CGRect self, CGSize size) + public static CGRect Scaled (this CGRect self, CGSize size) { - return new CGRect(self.X * size.Width, + return new CGRect (self.X * size.Width, self.Y * size.Height, self.Size.Width * size.Width, self.Size.Height * size.Height); diff --git a/ios11/VisionObjectTracker/ObjectTracker/Main.cs b/ios11/VisionObjectTracker/ObjectTracker/Main.cs index 910c29000..8f638dd9d 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/Main.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace ObjectTracker -{ - public class Application - { +namespace ObjectTracker { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/VisionObjectTracker/ObjectTracker/ObjectTracker.cs b/ios11/VisionObjectTracker/ObjectTracker/ObjectTracker.cs index 633e7f748..5e02b56e8 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/ObjectTracker.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/ObjectTracker.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using CoreGraphics; using CoreVideo; @@ -6,13 +6,11 @@ using UIKit; using Vision; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// Handles tracking an object over a sequence of frames (i.e., video-based tracking) /// </summary> - internal class ObjectTracker : NSObject, IRectangleViewer - { + internal class ObjectTracker : NSObject, IRectangleViewer { /// <summary> /// Drawing layer. /// </summary> @@ -28,34 +26,33 @@ internal class ObjectTracker : NSObject, IRectangleViewer /// </summary> VNDetectedObjectObservation trackedRectangle; - internal ObjectTracker(Overlay overlay) + internal ObjectTracker (Overlay overlay) { this.overlay = overlay; - trackingHandler = new VNSequenceRequestHandler(); + trackingHandler = new VNSequenceRequestHandler (); } /// <summary> /// Track the specified observation. /// </summary> - internal void Track(VNDetectedObjectObservation observation) => trackedRectangle = observation; + internal void Track (VNDetectedObjectObservation observation) => trackedRectangle = observation; /// <summary> /// Called by `ViewController.OnFrameCaptured` once per frame with the buffer processed by the image-processing pipeline in /// `VideoCaptureDelegate.DidOutputSampleBuffer` /// </summary> /// <param name="buffer">The captured video frame.</param> - public void OnFrameCaptured(CVPixelBuffer buffer) + public void OnFrameCaptured (CVPixelBuffer buffer) { // Run the tracker - var request = new VNTrackObjectRequest(trackedRectangle, ObjectTracked); + var request = new VNTrackObjectRequest (trackedRectangle, ObjectTracked); request.TrackingLevel = VNRequestTrackingLevel.Accurate; NSError error; - var requests = new[] { request }; - overlay.InvokeOnMainThread(() => overlay.Clear()); - trackingHandler.Perform(requests, buffer, out error); - if (error != null) - { - InvokeOnMainThread(() => overlay.Message = error.ToString()); + var requests = new [] { request }; + overlay.InvokeOnMainThread (() => overlay.Clear ()); + trackingHandler.Perform (requests, buffer, out error); + if (error != null) { + InvokeOnMainThread (() => overlay.Message = error.ToString ()); } } @@ -63,12 +60,11 @@ public void OnFrameCaptured(CVPixelBuffer buffer) /// Draws a quadrilateral on the overlay /// </summary> /// <param name="normalizedQuadrilateral">Normalized quadrilateral.</param> - private void ObjectTracked(CGPoint[] normalizedQuadrilateral) + private void ObjectTracked (CGPoint [] normalizedQuadrilateral) { - overlay.InvokeOnMainThread(() => - { - var rotatedQuadrilateral = normalizedQuadrilateral.Select(pt => new CGPoint(pt.X, 1.0 - pt.Y)).ToArray(); - overlay.AddQuad(rotatedQuadrilateral); + overlay.InvokeOnMainThread (() => { + var rotatedQuadrilateral = normalizedQuadrilateral.Select (pt => new CGPoint (pt.X, 1.0 - pt.Y)).ToArray (); + overlay.AddQuad (rotatedQuadrilateral); }); } @@ -77,44 +73,39 @@ private void ObjectTracked(CGPoint[] normalizedQuadrilateral) /// </summary> /// <param name="request">The request sent to the Vision subsystem.</param> /// <param name="err">If not null, describes an error in Vision.</param> - private void ObjectTracked(VNRequest request, NSError err) + private void ObjectTracked (VNRequest request, NSError err) { - if (err != null) - { - Console.Error.WriteLine(err); - InvokeOnMainThread(() => overlay.Message = err.ToString()); + if (err != null) { + Console.Error.WriteLine (err); + InvokeOnMainThread (() => overlay.Message = err.ToString ()); return; } - InvokeOnMainThread(() => - { - overlay.Clear(); + InvokeOnMainThread (() => { + overlay.Clear (); overlay.StrokeColor = UIColor.Green.CGColor; - var observations = request.GetResults<VNDetectedObjectObservation>(); - var o = observations.FirstOrDefault(); - if (o != null) - { + var observations = request.GetResults<VNDetectedObjectObservation> (); + var o = observations.FirstOrDefault (); + if (o != null) { // o is a succesfully tracked object, so draw it on the `overlay` overlay.Message = "Locked"; - if (o.Confidence < 0.5) - { + if (o.Confidence < 0.5) { overlay.StrokeColor = UIColor.Red.CGColor; } - if (o.Confidence < 0.8) - { + if (o.Confidence < 0.8) { overlay.StrokeColor = UIColor.Yellow.CGColor; } - var quad = new[] { + var quad = new [] { new CGPoint(o.BoundingBox.Left, o.BoundingBox.Top), new CGPoint(o.BoundingBox.Right, o.BoundingBox.Top), new CGPoint(o.BoundingBox.Right, o.BoundingBox.Bottom), new CGPoint(o.BoundingBox.Left, o.BoundingBox.Bottom) }; - ObjectTracked(quad); + ObjectTracked (quad); trackedRectangle = o; } }); } } -} \ No newline at end of file +} diff --git a/ios11/VisionObjectTracker/ObjectTracker/Overlay.cs b/ios11/VisionObjectTracker/ObjectTracker/Overlay.cs index c00c1e1e6..7093dc173 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/Overlay.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/Overlay.cs @@ -1,76 +1,66 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using CoreGraphics; using UIKit; -namespace ObjectTracker -{ - public class Overlay : UIView - { - List<CGPoint[]> quadrilaterals = new List<CGPoint[]>(); +namespace ObjectTracker { + public class Overlay : UIView { + List<CGPoint []> quadrilaterals = new List<CGPoint []> (); - public override void Draw(CGRect rect) + public override void Draw (CGRect rect) { - base.Draw(rect); + base.Draw (rect); - using (var ctxt = UIGraphics.GetCurrentContext()) - { - ctxt.SetStrokeColor(StrokeColor); - using (var path = new CGPath()) - { + using (var ctxt = UIGraphics.GetCurrentContext ()) { + ctxt.SetStrokeColor (StrokeColor); + using (var path = new CGPath ()) { var imageSize = this.Bounds.Size; - lock (quadrilaterals) - { - var scaled = quadrilaterals.Select(q => q.Select(pt => pt.Scaled(imageSize))); - foreach (var q in scaled) - { - path.AddLines(q.ToArray()); - path.CloseSubpath(); + lock (quadrilaterals) { + var scaled = quadrilaterals.Select (q => q.Select (pt => pt.Scaled (imageSize))); + foreach (var q in scaled) { + path.AddLines (q.ToArray ()); + path.CloseSubpath (); } } - ctxt.AddPath(path); - ctxt.StrokePath(); + ctxt.AddPath (path); + ctxt.StrokePath (); // Draw text } - ctxt.SaveState(); - ctxt.ScaleCTM(1, -1); - ctxt.SetFillColor(UIColor.Red.CGColor); - ctxt.SetTextDrawingMode(CGTextDrawingMode.Fill); - ctxt.SelectFont("Helvetica", 32, CGTextEncoding.MacRoman); + ctxt.SaveState (); + ctxt.ScaleCTM (1, -1); + ctxt.SetFillColor (UIColor.Red.CGColor); + ctxt.SetTextDrawingMode (CGTextDrawingMode.Fill); + ctxt.SelectFont ("Helvetica", 32, CGTextEncoding.MacRoman); //Draw the text at given coords. - ctxt.ShowTextAtPoint(25, -25, Message); - ctxt.RestoreState(); + ctxt.ShowTextAtPoint (25, -25, Message); + ctxt.RestoreState (); } } private string message = ""; - public string Message - { + public string Message { get => message; - set - { + set { message = value; - SetNeedsDisplay(); + SetNeedsDisplay (); } } - public void Clear() + public void Clear () { - lock (quadrilaterals) - { - quadrilaterals.Clear(); + lock (quadrilaterals) { + quadrilaterals.Clear (); } } - public void AddQuad(CGPoint[] quad) + public void AddQuad (CGPoint [] quad) { - lock (quadrilaterals) - { - quadrilaterals.Add(quad); + lock (quadrilaterals) { + quadrilaterals.Add (quad); } } diff --git a/ios11/VisionObjectTracker/ObjectTracker/RectangleScanner.cs b/ios11/VisionObjectTracker/ObjectTracker/RectangleScanner.cs index d3644995e..83b6419f0 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/RectangleScanner.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/RectangleScanner.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using CoreFoundation; using CoreGraphics; @@ -7,13 +7,11 @@ using UIKit; using Vision; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// Makes Vision requests in "scanning" mode -- looks for rectangles /// </summary> - internal class RectangleScanner : NSObject, IRectangleViewer - { + internal class RectangleScanner : NSObject, IRectangleViewer { /// <summary> /// Connection to the Vision subsystem /// </summary> @@ -22,18 +20,18 @@ internal class RectangleScanner : NSObject, IRectangleViewer /// <summary> /// The set of detected rectangles /// </summary> - VNRectangleObservation[] observations; + VNRectangleObservation [] observations; /// <summary> /// Display overlay /// </summary> Overlay overlay; - internal RectangleScanner(Overlay overlay) + internal RectangleScanner (Overlay overlay) { this.overlay = overlay; - rectangleRequest = new VNDetectRectanglesRequest(RectanglesDetected); + rectangleRequest = new VNDetectRectanglesRequest (RectanglesDetected); rectangleRequest.MaximumObservations = 10; } @@ -42,19 +40,18 @@ internal RectangleScanner(Overlay overlay) /// `VideoCaptureDelegate.DidOutputSampleBuffer` /// </summary> /// <param name="buffer">The captured video frame.</param> - public void OnFrameCaptured(CVPixelBuffer buffer) + public void OnFrameCaptured (CVPixelBuffer buffer) { - BeginInvokeOnMainThread(() => overlay.Message = $"Scanning..."); + BeginInvokeOnMainThread (() => overlay.Message = $"Scanning..."); // Run the rectangle detector - var handler = new VNImageRequestHandler(buffer, new NSDictionary()); + var handler = new VNImageRequestHandler (buffer, new NSDictionary ()); NSError error; - handler.Perform(new VNRequest[] { rectangleRequest }, out error); - if (error != null) - { - Console.Error.WriteLine(error); - BeginInvokeOnMainThread(() => overlay.Message = error.ToString()); + handler.Perform (new VNRequest [] { rectangleRequest }, out error); + if (error != null) { + Console.Error.WriteLine (error); + BeginInvokeOnMainThread (() => overlay.Message = error.ToString ()); } } @@ -63,45 +60,42 @@ public void OnFrameCaptured(CVPixelBuffer buffer) /// </summary> /// <param name="request">The request sent to the Vision subsystem.</param> /// <param name="err">If not null, describes an error in Vision.</param> - private void RectanglesDetected(VNRequest request, NSError err) + private void RectanglesDetected (VNRequest request, NSError err) { - if (err != null) - { - overlay.Message = err.ToString(); - Console.Error.WriteLine(err); + if (err != null) { + overlay.Message = err.ToString (); + Console.Error.WriteLine (err); return; } - overlay.Clear(); + overlay.Clear (); - observations = request.GetResults<VNRectangleObservation>(); + observations = request.GetResults<VNRectangleObservation> (); overlay.StrokeColor = UIColor.Blue.CGColor; //Draw all detected rectangles in blue - foreach (var o in observations) - { - var quad = new[] { o.TopLeft, o.TopRight, o.BottomRight, o.BottomLeft }; - RectangleDetected(quad); + foreach (var o in observations) { + var quad = new [] { o.TopLeft, o.TopRight, o.BottomRight, o.BottomLeft }; + RectangleDetected (quad); } } - private void RectangleDetected(CGPoint[] normalizedQuadrilateral) + private void RectangleDetected (CGPoint [] normalizedQuadrilateral) { - overlay.InvokeOnMainThread(() => - { + overlay.InvokeOnMainThread (() => { // Note conversion from inverted coordinate system! - var rotatedQuadrilateral = normalizedQuadrilateral.Select(pt => new CGPoint(pt.X, 1.0 - pt.Y)).ToArray(); - overlay.AddQuad(rotatedQuadrilateral); + var rotatedQuadrilateral = normalizedQuadrilateral.Select (pt => new CGPoint (pt.X, 1.0 - pt.Y)).ToArray (); + overlay.AddQuad (rotatedQuadrilateral); }); } - private static bool ObservationContainsPoint(VNRectangleObservation o, CGPoint normalizedPoint) + private static bool ObservationContainsPoint (VNRectangleObservation o, CGPoint normalizedPoint) { // Enhancement: This is actually wrong, since the touch could be within the bounding box but outside the quadrilateral. // For better accuracy, implement the Winding Rule algorithm - return o.BoundingBox.Contains(normalizedPoint); + return o.BoundingBox.Contains (normalizedPoint); } - internal VNRectangleObservation Containing(CGPoint normalizedPoint) => observations.FirstOrDefault(o => ObservationContainsPoint(o, normalizedPoint)); + internal VNRectangleObservation Containing (CGPoint normalizedPoint) => observations.FirstOrDefault (o => ObservationContainsPoint (o, normalizedPoint)); } } diff --git a/ios11/VisionObjectTracker/ObjectTracker/VideoCapture.cs b/ios11/VisionObjectTracker/ObjectTracker/VideoCapture.cs index b7ab372bb..10ea40a0f 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/VideoCapture.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/VideoCapture.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using AVFoundation; using CoreFoundation; @@ -7,13 +7,11 @@ using Foundation; using UIKit; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// Handles the capturing of video from the device's rear camera /// </summary> - public class VideoCapture : NSObject - { + public class VideoCapture : NSObject { /// <summary> /// The camera /// </summary> @@ -23,7 +21,7 @@ public class VideoCapture : NSObject /// Perform the capture and image-processing pipeline on a background queue (note that /// this is different than the Vision request /// </summary> - DispatchQueue queue = new DispatchQueue("videoQueue"); + DispatchQueue queue = new DispatchQueue ("videoQueue"); /// <summary> /// Used by `AVCaptureVideoPreviewLayer` in `ViewController` @@ -32,61 +30,55 @@ public class VideoCapture : NSObject public AVCaptureSession Session { get; } - AVCaptureVideoDataOutput videoOutput = new AVCaptureVideoDataOutput(); + AVCaptureVideoDataOutput videoOutput = new AVCaptureVideoDataOutput (); - public IAVCaptureVideoDataOutputSampleBufferDelegate Delegate { get; } + public IAVCaptureVideoDataOutputSampleBufferDelegate Delegate { get; } - public VideoCapture(IAVCaptureVideoDataOutputSampleBufferDelegate delegateObject) + public VideoCapture (IAVCaptureVideoDataOutputSampleBufferDelegate delegateObject) { Delegate = delegateObject; - Session = new AVCaptureSession(); - SetupCamera(); + Session = new AVCaptureSession (); + SetupCamera (); } /// <summary> /// Typical video-processing code. More advanced would allow user selection of camera, resolution, etc. /// </summary> - private void SetupCamera() + private void SetupCamera () { - var deviceDiscovery = AVCaptureDeviceDiscoverySession.Create( - new AVCaptureDeviceType[] { AVCaptureDeviceType.BuiltInWideAngleCamera }, AVMediaType.Video, AVCaptureDevicePosition.Back); + var deviceDiscovery = AVCaptureDeviceDiscoverySession.Create ( + new AVCaptureDeviceType [] { AVCaptureDeviceType.BuiltInWideAngleCamera }, AVMediaType.Video, AVCaptureDevicePosition.Back); - var device = deviceDiscovery.Devices.Last(); - if (device != null) - { + var device = deviceDiscovery.Devices.Last (); + if (device != null) { captureDevice = device; - BeginSession(); + BeginSession (); } } - private void BeginSession() + private void BeginSession () { - try - { - var settings = new CVPixelBufferAttributes - { + try { + var settings = new CVPixelBufferAttributes { PixelFormatType = CVPixelFormatType.CV32BGRA }; videoOutput.WeakVideoSettings = settings.Dictionary; videoOutput.AlwaysDiscardsLateVideoFrames = true; - videoOutput.SetSampleBufferDelegateQueue(Delegate, queue); + videoOutput.SetSampleBufferDelegateQueue (Delegate, queue); Session.SessionPreset = AVCaptureSession.Preset1920x1080; - Session.AddOutput(videoOutput); + Session.AddOutput (videoOutput); - var input = new AVCaptureDeviceInput(captureDevice, out var err); - if (err != null) - { - Console.Error.WriteLine("AVCapture error: " + err); + var input = new AVCaptureDeviceInput (captureDevice, out var err); + if (err != null) { + Console.Error.WriteLine ("AVCapture error: " + err); } - Session.AddInput(input); + Session.AddInput (input); - Session.StartRunning(); - Console.WriteLine("started AV capture session"); - } - catch - { - Console.Error.WriteLine("error connecting to the capture device"); + Session.StartRunning (); + Console.WriteLine ("started AV capture session"); + } catch { + Console.Error.WriteLine ("error connecting to the capture device"); } } @@ -95,9 +87,9 @@ private void BeginSession() /// </summary> /// <returns>The (processed) video frame, as a UIImage.</returns> /// <param name="imageBuffer">The (processed) video frame.</param> - public static UIImage ImageBufferToUIImage(CVPixelBuffer imageBuffer) + public static UIImage ImageBufferToUIImage (CVPixelBuffer imageBuffer) { - imageBuffer.Lock(CVPixelBufferLock.None); + imageBuffer.Lock (CVPixelBufferLock.None); var baseAddress = imageBuffer.BaseAddress; var bytesPerRow = imageBuffer.BytesPerRow; @@ -105,15 +97,14 @@ public static UIImage ImageBufferToUIImage(CVPixelBuffer imageBuffer) var width = imageBuffer.Width; var height = imageBuffer.Height; - var colorSpace = CGColorSpace.CreateDeviceRGB(); - var bitmapInfo = (uint)CGImageAlphaInfo.NoneSkipFirst | (uint)CGBitmapFlags.ByteOrder32Little; + var colorSpace = CGColorSpace.CreateDeviceRGB (); + var bitmapInfo = (uint) CGImageAlphaInfo.NoneSkipFirst | (uint) CGBitmapFlags.ByteOrder32Little; - using (var context = new CGBitmapContext(baseAddress, width, height, 8, bytesPerRow, colorSpace, (CGImageAlphaInfo)bitmapInfo)) - { - var quartzImage = context?.ToImage(); - imageBuffer.Unlock(CVPixelBufferLock.None); + using (var context = new CGBitmapContext (baseAddress, width, height, 8, bytesPerRow, colorSpace, (CGImageAlphaInfo) bitmapInfo)) { + var quartzImage = context?.ToImage (); + imageBuffer.Unlock (CVPixelBufferLock.None); - var image = new UIImage(quartzImage, 1.0f, UIImageOrientation.Up); + var image = new UIImage (quartzImage, 1.0f, UIImageOrientation.Up); return image; } diff --git a/ios11/VisionObjectTracker/ObjectTracker/VideoCaptureDelegate.cs b/ios11/VisionObjectTracker/ObjectTracker/VideoCaptureDelegate.cs index e04a1bdb1..df2a7bea5 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/VideoCaptureDelegate.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/VideoCaptureDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using AVFoundation; using CoreFoundation; using CoreGraphics; @@ -9,21 +9,19 @@ using UIKit; using Vision; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// Delegate-object for `VideoCapture`: Converts the sample buffer into a `CVPixelBuffer` processed for video analysis /// </summary> - public class VideoCaptureDelegate : NSObject, IAVCaptureVideoDataOutputSampleBufferDelegate - { + public class VideoCaptureDelegate : NSObject, IAVCaptureVideoDataOutputSampleBufferDelegate { DateTime lastAnalysis = DateTime.Now; // controlling the pace of the machine vision analysis - TimeSpan pace = new TimeSpan(0, 0, 0, 0, 333); // in milliseconds, classification will not repeat faster than this value + TimeSpan pace = new TimeSpan (0, 0, 0, 0, 333); // in milliseconds, classification will not repeat faster than this value /// <summary> /// Keep a single context around, to avoid per-frame allocation /// </summary> - CIContext context = CIContext.Create(); + CIContext context = CIContext.Create (); CIAffineTransform rotateTransform; @@ -37,62 +35,52 @@ public class VideoCaptureDelegate : NSObject, IAVCaptureVideoDataOutputSampleBuf CVPixelBuffer resultBuffer; - public event EventHandler<EventArgsT<CVPixelBuffer>> FrameCaptured = delegate {}; - - public VideoCaptureDelegate(EventHandler<EventArgsT<CVPixelBuffer>> callback) + public event EventHandler<EventArgsT<CVPixelBuffer>> FrameCaptured = delegate { }; + + public VideoCaptureDelegate (EventHandler<EventArgsT<CVPixelBuffer>> callback) { this.FrameCaptured = callback; } - [Export("captureOutput:didOutputSampleBuffer:fromConnection:")] - public void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + [Export ("captureOutput:didOutputSampleBuffer:fromConnection:")] + public void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) { - try - { + try { var currentDate = DateTime.Now; // control the pace of the machine vision to protect battery life - if (currentDate - lastAnalysis >= pace) - { + if (currentDate - lastAnalysis >= pace) { lastAnalysis = currentDate; - } - else - { + } else { return; // don't run the classifier more often than we need } // Crop and resize the image data. // Note, this uses a Core Image pipeline that could be appended with other pre-processing. // If we don't want to do anything custom, we can remove this step and let the Vision framework handle // crop and resize as long as we are careful to pass the orientation properly. - using (var croppedBuffer = CroppedSampleBuffer(sampleBuffer)) - { + using (var croppedBuffer = CroppedSampleBuffer (sampleBuffer)) { - if (croppedBuffer == null) - { + if (croppedBuffer == null) { return; } - FrameCaptured(this, new EventArgsT<CVPixelBuffer>(croppedBuffer)); + FrameCaptured (this, new EventArgsT<CVPixelBuffer> (croppedBuffer)); } - } - finally - { - sampleBuffer.Dispose(); + } finally { + sampleBuffer.Dispose (); } } bool alreadySet = false; - public CVPixelBuffer CroppedSampleBuffer(CMSampleBuffer sampleBuffer) + public CVPixelBuffer CroppedSampleBuffer (CMSampleBuffer sampleBuffer) { - var imageBuffer = sampleBuffer.GetImageBuffer(); - if (imageBuffer == null) - { - throw new ArgumentException("Cannot convert to CVImageBuffer"); + var imageBuffer = sampleBuffer.GetImageBuffer (); + if (imageBuffer == null) { + throw new ArgumentException ("Cannot convert to CVImageBuffer"); } // Only doing these calculations once for efficiency. // If the incoming images could change orientation or size during a session, this would need to be reset when that happens. - if (!alreadySet) - { + if (!alreadySet) { alreadySet = true; var imageSize = imageBuffer.EncodedSize; @@ -109,25 +97,23 @@ public CVPixelBuffer CroppedSampleBuffer(CMSampleBuffer sampleBuffer) between hardware */ - var rotatedSize = new CGSize(imageSize.Height, imageSize.Width); + var rotatedSize = new CGSize (imageSize.Height, imageSize.Width); var shorterSide = rotatedSize.Width < rotatedSize.Height ? rotatedSize.Width : rotatedSize.Height; - rotateTransform = new CIAffineTransform - { - Transform = new CGAffineTransform(0, -1, 1, 0, 0, shorterSide) + rotateTransform = new CIAffineTransform { + Transform = new CGAffineTransform (0, -1, 1, 0, 0, shorterSide) }; - cropTransform = new CIAffineTransform - { - Transform = CGAffineTransform.MakeTranslation(0, (int) (1920.0 / 5) + 60) // Translate down past the cropped area + manual tweak + cropTransform = new CIAffineTransform { + Transform = CGAffineTransform.MakeTranslation (0, (int) (1920.0 / 5) + 60) // Translate down past the cropped area + manual tweak }; - edgeDetector = new CIEdges(); + edgeDetector = new CIEdges (); } // Convert to CIImage because it is easier to manipulate - var ciImage = CIImage.FromImageBuffer(imageBuffer); + var ciImage = CIImage.FromImageBuffer (imageBuffer); rotateTransform.Image = ciImage; cropTransform.Image = rotateTransform.OutputImage; @@ -141,17 +127,16 @@ between hardware // the image manipulation in a single Core Image pipeline because it can be hardware optimized. // Only need to create this buffer one time and then we can reuse it for every frame - if (resultBuffer == null || resultBuffer.Handle == IntPtr.Zero) - { - var targetSize = new CGSize(1080, 1152); //1080, 3/5 * 1920 - byte[] data = new byte[(int)targetSize.Height * 4 * (int)targetSize.Width]; + if (resultBuffer == null || resultBuffer.Handle == IntPtr.Zero) { + var targetSize = new CGSize (1080, 1152); //1080, 3/5 * 1920 + byte [] data = new byte [(int) targetSize.Height * 4 * (int) targetSize.Width]; - resultBuffer = CVPixelBuffer.Create((nint)targetSize.Width, (nint)targetSize.Height, CVPixelFormatType.CV32BGRA, data, 4 * (nint)targetSize.Width, null); + resultBuffer = CVPixelBuffer.Create ((nint) targetSize.Width, (nint) targetSize.Height, CVPixelFormatType.CV32BGRA, data, 4 * (nint) targetSize.Width, null); - if (resultBuffer == null) throw new Exception("Can't allocate pixel buffer."); + if (resultBuffer == null) throw new Exception ("Can't allocate pixel buffer."); } - context.Render(cropped, resultBuffer); + context.Render (cropped, resultBuffer); // For debugging //var image = ImageBufferToUIImage(resultBuffer); @@ -161,18 +146,16 @@ between hardware } private bool disposed = false; - protected override void Dispose(bool disposing) + protected override void Dispose (bool disposing) { - if (disposed) - { + if (disposed) { return; } disposed = true; - if (context != null) - { - context.Dispose(); + if (context != null) { + context.Dispose (); } - base.Dispose(disposing); + base.Dispose (disposing); } } } diff --git a/ios11/VisionObjectTracker/ObjectTracker/ViewController.cs b/ios11/VisionObjectTracker/ObjectTracker/ViewController.cs index 4d0bb8afe..d94007d63 100644 --- a/ios11/VisionObjectTracker/ObjectTracker/ViewController.cs +++ b/ios11/VisionObjectTracker/ObjectTracker/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using AVFoundation; using CoreAnimation; @@ -11,22 +11,19 @@ using UIKit; using Vision; -namespace ObjectTracker -{ +namespace ObjectTracker { /// <summary> /// An object that receives frames for querying (i.e., `RectangleScanner`, `ObjectTracker`) /// </summary> - interface IRectangleViewer - { - void OnFrameCaptured(CVPixelBuffer buffer); + interface IRectangleViewer { + void OnFrameCaptured (CVPixelBuffer buffer); } /// <summary> /// Controller object for app: responsible for UX, coordinates video processing and querying /// </summary> - public partial class ViewController : UIViewController - { + public partial class ViewController : UIViewController { VideoCapture captureController; VideoCaptureDelegate captureDelegate; RectangleScanner scanner; @@ -38,106 +35,105 @@ public partial class ViewController : UIViewController UIView topBlurView; UIView bottomBlurView; UIView previewView; - UIImageView bufferImageView = new UIImageView(); + UIImageView bufferImageView = new UIImageView (); UIButton resetButton; - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); - previewView = new UIView(); + previewView = new UIView (); previewView.Frame = View.Bounds; - View.AddSubview(previewView); + View.AddSubview (previewView); - ConfigureBlurViews(View); - View.AddSubview(ConfigureResetButton()); - View.AddSubview(ConfigureOverlay(topBlurView, bottomBlurView)); - View.AddSubview(ConfigureBufferImageView()); + ConfigureBlurViews (View); + View.AddSubview (ConfigureResetButton ()); + View.AddSubview (ConfigureOverlay (topBlurView, bottomBlurView)); + View.AddSubview (ConfigureBufferImageView ()); - ConfigureInitialVisionTask(); + ConfigureInitialVisionTask (); - previewLayer = new AVCaptureVideoPreviewLayer(captureController.Session); - previewView.Layer.AddSublayer(previewLayer); + previewLayer = new AVCaptureVideoPreviewLayer (captureController.Session); + previewView.Layer.AddSublayer (previewLayer); } - private UIView ConfigureBufferImageView() + private UIView ConfigureBufferImageView () { - bufferImageView.Frame = new CGRect(10, 30, 108, 115); + bufferImageView.Frame = new CGRect (10, 30, 108, 115); return bufferImageView; } - private UIView ConfigureOverlay(UIView tbv, UIView bbv) + private UIView ConfigureOverlay (UIView tbv, UIView bbv) { //Configure layer on which we do our graphics - overlay = new Overlay - { - Frame = new CGRect(tbv.Frame.Left, tbv.Frame.Bottom + 5, tbv.Frame.Right, bbv.Frame.Top - tbv.Frame.Bottom - 10), + overlay = new Overlay { + Frame = new CGRect (tbv.Frame.Left, tbv.Frame.Bottom + 5, tbv.Frame.Right, bbv.Frame.Top - tbv.Frame.Bottom - 10), BackgroundColor = UIColor.Clear }; return overlay; } - private UIView ConfigureResetButton() + private UIView ConfigureResetButton () { - resetButton = new UIButton(); - resetButton.SetTitle("Reset", UIControlState.Normal); + resetButton = new UIButton (); + resetButton.SetTitle ("Reset", UIControlState.Normal); resetButton.Hidden = true; resetButton.TouchDown += ResetTracking; resetButton.TranslatesAutoresizingMaskIntoConstraints = false; - resetButton.Frame = new CGRect(View.Frame.Right - 180, 40, 150, 50); + resetButton.Frame = new CGRect (View.Frame.Right - 180, 40, 150, 50); return resetButton; } - void ConfigureInitialVisionTask() + void ConfigureInitialVisionTask () { // Assert overlay initialized - scanner = new RectangleScanner(overlay); - tracker = new ObjectTracker(overlay); + scanner = new RectangleScanner (overlay); + tracker = new ObjectTracker (overlay); activeViewer = scanner; - captureDelegate = new VideoCaptureDelegate(OnFrameCaptured); - captureController = new VideoCapture(captureDelegate); + captureDelegate = new VideoCaptureDelegate (OnFrameCaptured); + captureController = new VideoCapture (captureDelegate); } - void ResetTracking(Object sender, EventArgs e) + void ResetTracking (Object sender, EventArgs e) { overlay.Message = "Scanning"; activeViewer = scanner; resetButton.Hidden = true; } - private void ConfigureBlurViews(UIView mainView) + private void ConfigureBlurViews (UIView mainView) { - var blur = UIBlurEffect.FromStyle(UIBlurEffectStyle.Regular); - topBlurView = new UIVisualEffectView(blur); - mainView.AddSubview(topBlurView); - bottomBlurView = new UIVisualEffectView(blur); - mainView.AddSubview(bottomBlurView); + var blur = UIBlurEffect.FromStyle (UIBlurEffectStyle.Regular); + topBlurView = new UIVisualEffectView (blur); + mainView.AddSubview (topBlurView); + bottomBlurView = new UIVisualEffectView (blur); + mainView.AddSubview (bottomBlurView); } - public override void ViewDidLayoutSubviews() + public override void ViewDidLayoutSubviews () { - base.ViewDidLayoutSubviews(); + base.ViewDidLayoutSubviews (); previewLayer.Frame = previewView.Bounds; var oneFifthHeight = previewLayer.Frame.Height / 5; - topBlurView.Frame = new CGRect(previewLayer.Frame.Left, previewLayer.Frame.Top, previewLayer.Frame.Right, oneFifthHeight); - bottomBlurView.Frame = new CGRect(previewLayer.Frame.Left, previewLayer.Frame.Bottom - oneFifthHeight, previewLayer.Frame.Right, oneFifthHeight); - overlay.Frame = new CGRect(topBlurView.Frame.Left, topBlurView.Frame.Bottom, topBlurView.Frame.Right, bottomBlurView.Frame.Top - topBlurView.Frame.Bottom); - resetButton.Frame = new CGRect(View.Frame.Right - 180, 40, 150, 50); + topBlurView.Frame = new CGRect (previewLayer.Frame.Left, previewLayer.Frame.Top, previewLayer.Frame.Right, oneFifthHeight); + bottomBlurView.Frame = new CGRect (previewLayer.Frame.Left, previewLayer.Frame.Bottom - oneFifthHeight, previewLayer.Frame.Right, oneFifthHeight); + overlay.Frame = new CGRect (topBlurView.Frame.Left, topBlurView.Frame.Bottom, topBlurView.Frame.Right, bottomBlurView.Frame.Top - topBlurView.Frame.Bottom); + resetButton.Frame = new CGRect (View.Frame.Right - 180, 40, 150, 50); } - public override void DidReceiveMemoryWarning() + public override void DidReceiveMemoryWarning () { - base.DidReceiveMemoryWarning(); + base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } @@ -146,19 +142,17 @@ public override void DidReceiveMemoryWarning() /// </summary> /// <param name="touches">Touches.</param> /// <param name="evt">Evt.</param> - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); - - var touch = touches.First() as UITouch; - var pt = touch.LocationInView(overlay); - var normalizedPoint = new CGPoint(pt.X / overlay.Frame.Width, pt.Y / overlay.Frame.Height); - if (activeViewer == scanner) - { - var trackedRectangle = scanner.Containing(normalizedPoint); - if (trackedRectangle != null) - { - tracker.Track(trackedRectangle); + base.TouchesBegan (touches, evt); + + var touch = touches.First () as UITouch; + var pt = touch.LocationInView (overlay); + var normalizedPoint = new CGPoint (pt.X / overlay.Frame.Width, pt.Y / overlay.Frame.Height); + if (activeViewer == scanner) { + var trackedRectangle = scanner.Containing (normalizedPoint); + if (trackedRectangle != null) { + tracker.Track (trackedRectangle); overlay.Message = "Target acquired"; activeViewer = tracker; resetButton.Hidden = false; @@ -171,22 +165,20 @@ public override void TouchesBegan(NSSet touches, UIEvent evt) /// </summary> /// <param name="sender">The `VideoCaptureDelegate` delegate-object</param> /// <param name="args">EventArgsT containing the (processed) frame</param> - void OnFrameCaptured(Object sender, EventArgsT<CVPixelBuffer> args) + void OnFrameCaptured (Object sender, EventArgsT<CVPixelBuffer> args) { var buffer = args.Value; - activeViewer.OnFrameCaptured(buffer); + activeViewer.OnFrameCaptured (buffer); // Display it - var img = VideoCapture.ImageBufferToUIImage(buffer); - overlay.BeginInvokeOnMainThread(() => - { + var img = VideoCapture.ImageBufferToUIImage (buffer); + overlay.BeginInvokeOnMainThread (() => { var oldImg = bufferImageView.Image; - if (oldImg != null) - { - oldImg.Dispose(); + if (oldImg != null) { + oldImg.Dispose (); } bufferImageView.Image = img; - bufferImageView.SetNeedsDisplay(); + bufferImageView.SetNeedsDisplay (); }); } } diff --git a/ios11/VisionRectangles/VisionRects/AppDelegate.cs b/ios11/VisionRectangles/VisionRects/AppDelegate.cs index 60ee755b0..f3f850367 100644 --- a/ios11/VisionRectangles/VisionRects/AppDelegate.cs +++ b/ios11/VisionRectangles/VisionRects/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace VisionFramework -{ +namespace VisionFramework { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios11/VisionRectangles/VisionRects/ClassExtensions/CGPointExtensions.cs b/ios11/VisionRectangles/VisionRects/ClassExtensions/CGPointExtensions.cs index 6dbfaaad4..34283c533 100644 --- a/ios11/VisionRectangles/VisionRects/ClassExtensions/CGPointExtensions.cs +++ b/ios11/VisionRectangles/VisionRects/ClassExtensions/CGPointExtensions.cs @@ -1,13 +1,12 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace VisionFramework -{ - public static class CGPointExtensions - { - public static CGPoint Scaled(this CGPoint self, CGSize size) { - return new CGPoint(self.X * size.Width, self.Y * size.Height); +namespace VisionFramework { + public static class CGPointExtensions { + public static CGPoint Scaled (this CGPoint self, CGSize size) + { + return new CGPoint (self.X * size.Width, self.Y * size.Height); } } } diff --git a/ios11/VisionRectangles/VisionRects/ClassExtensions/CGRectExtensions.cs b/ios11/VisionRectangles/VisionRects/ClassExtensions/CGRectExtensions.cs index 6bb645172..920581d30 100644 --- a/ios11/VisionRectangles/VisionRects/ClassExtensions/CGRectExtensions.cs +++ b/ios11/VisionRectangles/VisionRects/ClassExtensions/CGRectExtensions.cs @@ -1,16 +1,15 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace VisionFramework -{ - public static class CGRectExtensions - { - public static CGRect Scaled(this CGRect self, CGSize size) { - return new CGRect(self.X * size.Width, - self.Y * size.Height, - self.Size.Width * size.Width, - self.Size.Height * size.Height); +namespace VisionFramework { + public static class CGRectExtensions { + public static CGRect Scaled (this CGRect self, CGSize size) + { + return new CGRect (self.X * size.Width, + self.Y * size.Height, + self.Size.Width * size.Width, + self.Size.Height * size.Height); } } } diff --git a/ios11/VisionRectangles/VisionRects/ClassExtensions/DictionaryExtensions.cs b/ios11/VisionRectangles/VisionRects/ClassExtensions/DictionaryExtensions.cs index 92deec4e6..249482120 100644 --- a/ios11/VisionRectangles/VisionRects/ClassExtensions/DictionaryExtensions.cs +++ b/ios11/VisionRectangles/VisionRects/ClassExtensions/DictionaryExtensions.cs @@ -1,44 +1,42 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; using CoreGraphics; using CoreImage; -namespace VisionFramework -{ - public static class DictionaryExtensions - { - public static NSDictionary<NSString, CIVector> ToNSDictionary(this Dictionary<string, CGPoint> self){ +namespace VisionFramework { + public static class DictionaryExtensions { + public static NSDictionary<NSString, CIVector> ToNSDictionary (this Dictionary<string, CGPoint> self) + { - var keys = new List<NSString>(); - var values = new List<CIVector>(); + var keys = new List<NSString> (); + var values = new List<CIVector> (); // Process all keys in the dictionary - foreach(string key in self.Keys) { - keys.Add(new NSString(key)); - values.Add(new CIVector(self[key])); + foreach (string key in self.Keys) { + keys.Add (new NSString (key)); + values.Add (new CIVector (self [key])); } // Return results - return new NSDictionary<NSString, CIVector>(keys.ToArray(), values.ToArray()); + return new NSDictionary<NSString, CIVector> (keys.ToArray (), values.ToArray ()); } - public static NSDictionary<NSString, NSNumber> ToNSDictionary(this Dictionary<NSString, NSNumber> self) + public static NSDictionary<NSString, NSNumber> ToNSDictionary (this Dictionary<NSString, NSNumber> self) { - var keys = new List<NSString>(); - var values = new List<NSNumber>(); + var keys = new List<NSString> (); + var values = new List<NSNumber> (); // Process all keys in the dictionary - foreach (NSString key in self.Keys) - { - keys.Add(key); - values.Add(self[key]); + foreach (NSString key in self.Keys) { + keys.Add (key); + values.Add (self [key]); } // Return results - return new NSDictionary<NSString, NSNumber>(keys.ToArray(), values.ToArray()); + return new NSDictionary<NSString, NSNumber> (keys.ToArray (), values.ToArray ()); } } } diff --git a/ios11/VisionRectangles/VisionRects/ClassExtensions/UIImageOrientationExtensions.cs b/ios11/VisionRectangles/VisionRects/ClassExtensions/UIImageOrientationExtensions.cs index a461260fc..9bb25eb8d 100644 --- a/ios11/VisionRectangles/VisionRects/ClassExtensions/UIImageOrientationExtensions.cs +++ b/ios11/VisionRectangles/VisionRects/ClassExtensions/UIImageOrientationExtensions.cs @@ -1,60 +1,59 @@ -using System; +using System; using UIKit; using CoreGraphics; using CoreImage; using ImageIO; -namespace VisionFramework -{ - public static class UIImageOrientationExtensions - { - public static CGImagePropertyOrientation ToCGImagePropertyOrientation(this UIImageOrientation self) { +namespace VisionFramework { + public static class UIImageOrientationExtensions { + public static CGImagePropertyOrientation ToCGImagePropertyOrientation (this UIImageOrientation self) + { // Take action based on value - switch(self) { - case UIImageOrientation.Up: - return CGImagePropertyOrientation.Up; - case UIImageOrientation.UpMirrored: - return CGImagePropertyOrientation.UpMirrored; - case UIImageOrientation.Down: - return CGImagePropertyOrientation.Down; - case UIImageOrientation.DownMirrored: - return CGImagePropertyOrientation.DownMirrored; - case UIImageOrientation.Left: - return CGImagePropertyOrientation.Left; - case UIImageOrientation.LeftMirrored: - return CGImagePropertyOrientation.LeftMirrored; - case UIImageOrientation.Right: - return CGImagePropertyOrientation.Right; - case UIImageOrientation.RightMirrored: - return CGImagePropertyOrientation.RightMirrored; + switch (self) { + case UIImageOrientation.Up: + return CGImagePropertyOrientation.Up; + case UIImageOrientation.UpMirrored: + return CGImagePropertyOrientation.UpMirrored; + case UIImageOrientation.Down: + return CGImagePropertyOrientation.Down; + case UIImageOrientation.DownMirrored: + return CGImagePropertyOrientation.DownMirrored; + case UIImageOrientation.Left: + return CGImagePropertyOrientation.Left; + case UIImageOrientation.LeftMirrored: + return CGImagePropertyOrientation.LeftMirrored; + case UIImageOrientation.Right: + return CGImagePropertyOrientation.Right; + case UIImageOrientation.RightMirrored: + return CGImagePropertyOrientation.RightMirrored; } // Default to up return CGImagePropertyOrientation.Up; } - public static CIImageOrientation ToCIImageOrientation(this UIImageOrientation self) { + public static CIImageOrientation ToCIImageOrientation (this UIImageOrientation self) + { // Take action based on value - switch (self) - { - case UIImageOrientation.Up: - return CIImageOrientation.TopLeft; - case UIImageOrientation.UpMirrored: - return CIImageOrientation.TopRight; - case UIImageOrientation.Down: - return CIImageOrientation.BottomLeft; - case UIImageOrientation.DownMirrored: - return CIImageOrientation.BottomRight; - case UIImageOrientation.Left: - return CIImageOrientation.LeftTop; - case UIImageOrientation.LeftMirrored: - return CIImageOrientation.LeftBottom; - case UIImageOrientation.Right: - return CIImageOrientation.RightTop; - case UIImageOrientation.RightMirrored: - return CIImageOrientation.RightBottom; + switch (self) { + case UIImageOrientation.Up: + return CIImageOrientation.TopLeft; + case UIImageOrientation.UpMirrored: + return CIImageOrientation.TopRight; + case UIImageOrientation.Down: + return CIImageOrientation.BottomLeft; + case UIImageOrientation.DownMirrored: + return CIImageOrientation.BottomRight; + case UIImageOrientation.Left: + return CIImageOrientation.LeftTop; + case UIImageOrientation.LeftMirrored: + return CIImageOrientation.LeftBottom; + case UIImageOrientation.Right: + return CIImageOrientation.RightTop; + case UIImageOrientation.RightMirrored: + return CIImageOrientation.RightBottom; } // Default to up diff --git a/ios11/VisionRectangles/VisionRects/Main.cs b/ios11/VisionRectangles/VisionRects/Main.cs index 7a13e29ce..9d8e47b21 100644 --- a/ios11/VisionRectangles/VisionRects/Main.cs +++ b/ios11/VisionRectangles/VisionRects/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace VisionFramework -{ - public class Application - { +namespace VisionFramework { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios11/VisionRectangles/VisionRects/ViewController.cs b/ios11/VisionRectangles/VisionRects/ViewController.cs index 852d2c9b9..7079a9129 100644 --- a/ios11/VisionRectangles/VisionRects/ViewController.cs +++ b/ios11/VisionRectangles/VisionRects/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; using Vision; @@ -6,265 +6,254 @@ using CoreFoundation; using CoreGraphics; -namespace VisionFramework -{ - public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUINavigationControllerDelegate - { +namespace VisionFramework { + public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUINavigationControllerDelegate { CIImage InputImage; - UIImage RawImage; + UIImage RawImage; VNDetectRectanglesRequest RectangleRequest; - - protected ViewController(IntPtr handle) : base(handle) + + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - - public override void ViewDidLoad() + + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Configure UI - CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera); - GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum); + CameraButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera); + GalleryButton.Enabled = UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum); // Setup Vision Rectangles - RectangleRequest = new VNDetectRectanglesRequest(HandleRectangles); - RectangleRequest.MaximumObservations = 10; // limit on the number of rectangles to look for - can increase "thinking time" + RectangleRequest = new VNDetectRectanglesRequest (HandleRectangles); + RectangleRequest.MaximumObservations = 10; // limit on the number of rectangles to look for - can increase "thinking time" } - private string ToShortString(CGRect rect) + private string ToShortString (CGRect rect) { return $"[X: {rect.X:F}, Y: {rect.Y:F} Width: {rect.Width:F} Height: {rect.Height:F}]"; } - void HandleRectangles(VNRequest request, NSError error){ - - var observations = request.GetResults<VNRectangleObservation>(); + void HandleRectangles (VNRequest request, NSError error) + { + + var observations = request.GetResults<VNRectangleObservation> (); if (observations == null) { - ShowAlert("Processing Error","Unexpected result type from VNDetectRectanglesRequest."); + ShowAlert ("Processing Error", "Unexpected result type from VNDetectRectanglesRequest."); return; } if (observations.Length < 1) { - DispatchQueue.MainQueue.DispatchAsync(()=>{ + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "No rectangles detected."; }); return; - } - - var summary = ""; - var imageSize = InputImage.Extent.Size; - bool atLeastOneValid = false; - Console.WriteLine("Rectangles:"); - summary += "Rectangles:" + Environment.NewLine; - foreach (var o in observations){ - + } + + var summary = ""; + var imageSize = InputImage.Extent.Size; + bool atLeastOneValid = false; + Console.WriteLine ("Rectangles:"); + summary += "Rectangles:" + Environment.NewLine; + foreach (var o in observations) { + // Verify detected rectangle is valid. - var boundingBox = o.BoundingBox.Scaled(imageSize); - if (!InputImage.Extent.Contains(boundingBox)) - { - Console.WriteLine(" --- Rectangle out of bounds: " + ToShortString(boundingBox)); - summary += " --- Rectangle out of bounds:" + ToShortString(boundingBox) + Environment.NewLine; - } else { - Console.WriteLine(ToShortString(o.BoundingBox)); - summary += ToShortString(o.BoundingBox) + Environment.NewLine; - atLeastOneValid |= true; - } - } - - if (!atLeastOneValid) - { - DispatchQueue.MainQueue.DispatchAsync(() => { + var boundingBox = o.BoundingBox.Scaled (imageSize); + if (!InputImage.Extent.Contains (boundingBox)) { + Console.WriteLine (" --- Rectangle out of bounds: " + ToShortString (boundingBox)); + summary += " --- Rectangle out of bounds:" + ToShortString (boundingBox) + Environment.NewLine; + } else { + Console.WriteLine (ToShortString (o.BoundingBox)); + summary += ToShortString (o.BoundingBox) + Environment.NewLine; + atLeastOneValid |= true; + } + } + + if (!atLeastOneValid) { + DispatchQueue.MainQueue.DispatchAsync (() => { ClassificationLabel.Text = "No _valid_ rectangles detected." + Environment.NewLine + summary; }); - return; - } - - // Show the pre-processed image - DispatchQueue.MainQueue.DispatchAsync(() => - { - ClassificationLabel.Text = summary; - ClassificationLabel.Lines = 0; - ImageView.Image = OverlayRectangles(RawImage, imageSize, observations); + return; + } + + // Show the pre-processed image + DispatchQueue.MainQueue.DispatchAsync (() => { + ClassificationLabel.Text = summary; + ClassificationLabel.Lines = 0; + ImageView.Image = OverlayRectangles (RawImage, imageSize, observations); }); - + } - public static UIImage OverlayRectangles(UIImage uiImage, CGSize imageSize, VNRectangleObservation[] observations) + public static UIImage OverlayRectangles (UIImage uiImage, CGSize imageSize, VNRectangleObservation [] observations) { nfloat fWidth = uiImage.Size.Width; nfloat fHeight = uiImage.Size.Height; - CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB(); - - using (CGBitmapContext ctx = new CGBitmapContext(IntPtr.Zero, (nint)fWidth, (nint)fHeight, 8, 4 * (nint)fWidth, CGColorSpace.CreateDeviceRGB(), CGImageAlphaInfo.PremultipliedFirst)) - { - Console.WriteLine("Orientation:" +uiImage.Orientation); - if (uiImage.Orientation == UIImageOrientation.Up) - { // correct orientation - ctx.DrawImage(new CGRect(0, 0, (double)fWidth, (double)fHeight), uiImage.CGImage); - } - else - { // need to rotate image so that rectangle overlays match - UIGraphics.BeginImageContextWithOptions(uiImage.Size, false, 0); - uiImage.Draw(new CGRect(0, 0, (double)fWidth, (double)fHeight)); - var img = UIGraphics.GetImageFromCurrentImageContext(); - UIGraphics.EndImageContext(); - ctx.DrawImage(new CGRect(0, 0, (double)fWidth, (double)fHeight), img.CGImage); - } + CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB (); + + using (CGBitmapContext ctx = new CGBitmapContext (IntPtr.Zero, (nint) fWidth, (nint) fHeight, 8, 4 * (nint) fWidth, CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { + Console.WriteLine ("Orientation:" + uiImage.Orientation); + if (uiImage.Orientation == UIImageOrientation.Up) { // correct orientation + ctx.DrawImage (new CGRect (0, 0, (double) fWidth, (double) fHeight), uiImage.CGImage); + } else { // need to rotate image so that rectangle overlays match + UIGraphics.BeginImageContextWithOptions (uiImage.Size, false, 0); + uiImage.Draw (new CGRect (0, 0, (double) fWidth, (double) fHeight)); + var img = UIGraphics.GetImageFromCurrentImageContext (); + UIGraphics.EndImageContext (); + ctx.DrawImage (new CGRect (0, 0, (double) fWidth, (double) fHeight), img.CGImage); + } var count = 0; - foreach (var o in observations) - { + foreach (var o in observations) { // Draw rectangle - var text = "Rectangle: " + count++.ToString(); - Console.WriteLine(o.BoundingBox + " " + o.Confidence); + var text = "Rectangle: " + count++.ToString (); + Console.WriteLine (o.BoundingBox + " " + o.Confidence); - var topLeft = o.TopLeft.Scaled(imageSize); - var topRight = o.TopRight.Scaled(imageSize); - var bottomLeft = o.BottomLeft.Scaled(imageSize); - var bottomRight = o.BottomRight.Scaled(imageSize); + var topLeft = o.TopLeft.Scaled (imageSize); + var topRight = o.TopRight.Scaled (imageSize); + var bottomLeft = o.BottomLeft.Scaled (imageSize); + var bottomRight = o.BottomRight.Scaled (imageSize); - //set up drawing attributes - ctx.SetStrokeColor(UIColor.Red.CGColor); - ctx.SetLineWidth(10); + //set up drawing attributes + ctx.SetStrokeColor (UIColor.Red.CGColor); + ctx.SetLineWidth (10); - //create geometry - var path = new CGPath(); + //create geometry + var path = new CGPath (); - path.AddLines(new CGPoint[]{ - topLeft, topRight, bottomRight, bottomLeft - }); + path.AddLines (new CGPoint []{ + topLeft, topRight, bottomRight, bottomLeft + }); - path.CloseSubpath(); + path.CloseSubpath (); - //add geometry to graphics context and draw it - ctx.AddPath(path); - ctx.DrawPath(CGPathDrawingMode.Stroke); + //add geometry to graphics context and draw it + ctx.AddPath (path); + ctx.DrawPath (CGPathDrawingMode.Stroke); - // Draw text - ctx.SelectFont("Helvetica", 60, CGTextEncoding.MacRoman); + // Draw text + ctx.SelectFont ("Helvetica", 60, CGTextEncoding.MacRoman); //Measure the text's width - This involves drawing an invisible string to calculate the X position difference float start, end, textWidth; //Get the texts current position - start = (float)ctx.TextPosition.X; + start = (float) ctx.TextPosition.X; //Set the drawing mode to invisible - ctx.SetTextDrawingMode(CGTextDrawingMode.Invisible); + ctx.SetTextDrawingMode (CGTextDrawingMode.Invisible); //Draw the text at the current position - ctx.ShowText(text); + ctx.ShowText (text); //Get the end position - end = (float)ctx.TextPosition.X; + end = (float) ctx.TextPosition.X; //Subtract start from end to get the text's width textWidth = end - start; ctx.SetFillColor (UIColor.Red.CGColor); //Set the drawing mode back to something that will actually draw Fill for example - ctx.SetTextDrawingMode(CGTextDrawingMode.Fill); + ctx.SetTextDrawingMode (CGTextDrawingMode.Fill); //Draw the text at given coords. - ctx.ShowTextAtPoint (topLeft.X + 60, topLeft.Y - 60, text); + ctx.ShowTextAtPoint (topLeft.X + 60, topLeft.Y - 60, text); } - return UIImage.FromImage(ctx.ToImage()); + return UIImage.FromImage (ctx.ToImage ()); } } - void ShowAlert(string title, string message) + void ShowAlert (string title, string message) { //Create Alert - var okAlertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); + var okAlertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); //Add Action - okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); + okAlertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); // Present Alert - PresentViewController(okAlertController, true, null); + PresentViewController (okAlertController, true, null); } #region UIImagePickerControllerDelegate - [Export("imagePickerController:didFinishPickingMediaWithInfo:")] - public void FinishedPickingMedia(UIImagePickerController picker, NSDictionary info) + [Export ("imagePickerController:didFinishPickingMediaWithInfo:")] + public void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) { // Close the picker - picker.DismissViewController(true, null); + picker.DismissViewController (true, null); // Update UI - ClassificationLabel.Text = "Analyzing Image (please wait)..."; - + ClassificationLabel.Text = "Analyzing Image (please wait)..."; + // Read Image from returned data - var uiImage = info[UIImagePickerController.OriginalImage] as UIImage; + var uiImage = info [UIImagePickerController.OriginalImage] as UIImage; if (uiImage == null) { - ShowAlert("Processing Error","Unable to read image from picker."); + ShowAlert ("Processing Error", "Unable to read image from picker."); return; } // Convert to CIImage - var ciImage = new CIImage(uiImage); + var ciImage = new CIImage (uiImage); if (ciImage == null) { - ShowAlert("Processing Error", "Unable to create required CIImage from UIImage."); + ShowAlert ("Processing Error", "Unable to create required CIImage from UIImage."); return; } - InputImage = ciImage.CreateWithOrientation(uiImage.Orientation.ToCIImageOrientation()); + InputImage = ciImage.CreateWithOrientation (uiImage.Orientation.ToCIImageOrientation ()); // Show source image ImageView.Image = uiImage; - RawImage = uiImage; + RawImage = uiImage; // Run the rectangle detector - var handler = new VNImageRequestHandler(ciImage, uiImage.Orientation.ToCGImagePropertyOrientation(), new VNImageOptions()); - DispatchQueue.DefaultGlobalQueue.DispatchAsync(()=>{ - NSError error; - handler.Perform(new VNRequest[] {RectangleRequest}, out error); + var handler = new VNImageRequestHandler (ciImage, uiImage.Orientation.ToCGImagePropertyOrientation (), new VNImageOptions ()); + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + NSError error; + handler.Perform (new VNRequest [] { RectangleRequest }, out error); }); } #endregion #region Custom Actions - [Action("TakePicture:")] - public void TakePicture(NSObject sender) { + [Action ("TakePicture:")] + public void TakePicture (NSObject sender) + { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable( UIImagePickerControllerSourceType.Camera)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.Camera)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the saved photos album is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = this, SourceType = UIImagePickerControllerSourceType.Camera, CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } - [Action("ChooseImage:")] - public void ChooseImage(NSObject senter) { + [Action ("ChooseImage:")] + public void ChooseImage (NSObject senter) + { // Is the camera available? - if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum)) - { + if (!UIImagePickerController.IsSourceTypeAvailable (UIImagePickerControllerSourceType.SavedPhotosAlbum)) { // No report to user and cancel - ShowAlert("Not Supported", "Sorry but the camera is not available on this iOS device."); + ShowAlert ("Not Supported", "Sorry but the camera is not available on this iOS device."); return; } // Create a picker to get the camera image - var picker = new UIImagePickerController() - { + var picker = new UIImagePickerController () { Delegate = this, SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum }; // Display the picker - PresentViewController(picker, true, null); + PresentViewController (picker, true, null); } #endregion } diff --git a/ios11/WeatherWidget/WeatherWidget.Shared/Weather.cs b/ios11/WeatherWidget/WeatherWidget.Shared/Weather.cs index 47a267351..bd5db636b 100644 --- a/ios11/WeatherWidget/WeatherWidget.Shared/Weather.cs +++ b/ios11/WeatherWidget/WeatherWidget.Shared/Weather.cs @@ -1,56 +1,50 @@ -using Foundation; +using Foundation; using System; using UIKit; -namespace WeatherWidget -{ - public enum Weather - { - Sun = 0, - Cloud = 1, - Wind = 2, - Rain = 3, - Storm = 4, - } +namespace WeatherWidget { + public enum Weather { + Sun = 0, + Cloud = 1, + Wind = 2, + Rain = 3, + Storm = 4, + } - public static class WeatherExtensions - { - public static string GetDescription(this Weather self) - { - switch (self) - { - case Weather.Sun: return "Sunny"; - case Weather.Cloud: return "Cloudy"; - case Weather.Wind: return "Windy"; - case Weather.Rain: return "Rainy"; - case Weather.Storm: return "Stormy"; - default: throw new NotImplementedException(); - } - } + public static class WeatherExtensions { + public static string GetDescription (this Weather self) + { + switch (self) { + case Weather.Sun: return "Sunny"; + case Weather.Cloud: return "Cloudy"; + case Weather.Wind: return "Windy"; + case Weather.Rain: return "Rainy"; + case Weather.Storm: return "Stormy"; + default: throw new NotImplementedException (); + } + } - public static string GetImageAssetName(this Weather self) - { - switch (self) - { - case Weather.Sun: return "Sun"; - case Weather.Cloud: return "Cloud"; - case Weather.Wind: return "Wind"; - case Weather.Rain: return "Rain"; - case Weather.Storm: return "Storm"; - default: throw new NotImplementedException(); - } - } + public static string GetImageAssetName (this Weather self) + { + switch (self) { + case Weather.Sun: return "Sun"; + case Weather.Cloud: return "Cloud"; + case Weather.Wind: return "Wind"; + case Weather.Rain: return "Rain"; + case Weather.Storm: return "Storm"; + default: throw new NotImplementedException (); + } + } - public static UIImage GetImageAsset(this Weather self) - { - var assetName = self.GetImageAssetName(); - var image = UIImage.FromBundle(assetName); - if (image == null) - { - throw new Exception($"Expected an image named {assetName}"); - } + public static UIImage GetImageAsset (this Weather self) + { + var assetName = self.GetImageAssetName (); + var image = UIImage.FromBundle (assetName); + if (image == null) { + throw new Exception ($"Expected an image named {assetName}"); + } - return image; - } - } -} \ No newline at end of file + return image; + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget.Shared/WeatherForecast.cs b/ios11/WeatherWidget/WeatherWidget.Shared/WeatherForecast.cs index df8e62f45..d4d265b16 100644 --- a/ios11/WeatherWidget/WeatherWidget.Shared/WeatherForecast.cs +++ b/ios11/WeatherWidget/WeatherWidget.Shared/WeatherForecast.cs @@ -1,96 +1,86 @@ -using Foundation; +using Foundation; using System; using System.Collections.Generic; -namespace WeatherWidget -{ - /// <summary> - /// A struct representing a single day of weather data. - /// </summary> - public class WeatherForecast - { - public int daysFromNow; +namespace WeatherWidget { + /// <summary> + /// A struct representing a single day of weather data. + /// </summary> + public class WeatherForecast { + public int daysFromNow; - public WeatherForecast(int daysFromNow, Weather forecast) - { - this.daysFromNow = daysFromNow; - this.Forecast = forecast; - } + public WeatherForecast (int daysFromNow, Weather forecast) + { + this.daysFromNow = daysFromNow; + this.Forecast = forecast; + } - /// <summary> - /// The weather forecast for the day. - /// </summary> - public Weather Forecast { get; set; } + /// <summary> + /// The weather forecast for the day. + /// </summary> + public Weather Forecast { get; set; } - /// <summary> - /// The number of days from now as a text description. - /// </summary> - public string DaysFromNowDescription - { - get - { - switch (this.daysFromNow) - { - case 0: return "Today"; - case 1: return "Tomorrow"; - default: return $"In {daysFromNow} Days"; - } - } - } + /// <summary> + /// The number of days from now as a text description. + /// </summary> + public string DaysFromNowDescription { + get { + switch (this.daysFromNow) { + case 0: return "Today"; + case 1: return "Tomorrow"; + default: return $"In {daysFromNow} Days"; + } + } + } - public static List<WeatherForecast> LoadSharedData() - { - // In case this is the first time the app has been run, create some initial data. - if (!NSFileManager.DefaultManager.FileExists(SharedDataFileUrl.Path)) - { - SaveSharedData(GenerateRandomForecastData()); - } + public static List<WeatherForecast> LoadSharedData () + { + // In case this is the first time the app has been run, create some initial data. + if (!NSFileManager.DefaultManager.FileExists (SharedDataFileUrl.Path)) { + SaveSharedData (GenerateRandomForecastData ()); + } - var json = System.IO.File.ReadAllText(SharedDataFileUrl.Path); - return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeatherForecast>>(json); - } + var json = System.IO.File.ReadAllText (SharedDataFileUrl.Path); + return Newtonsoft.Json.JsonConvert.DeserializeObject<List<WeatherForecast>> (json); + } - /// <summary> - /// Saves weather forecast data from the App Group container. - /// </summary> - public static void SaveSharedData(List<WeatherForecast> data) - { - var json = Newtonsoft.Json.JsonConvert.SerializeObject(data); - System.IO.File.WriteAllText(SharedDataFileUrl.Path, json); - } + /// <summary> + /// Saves weather forecast data from the App Group container. + /// </summary> + public static void SaveSharedData (List<WeatherForecast> data) + { + var json = Newtonsoft.Json.JsonConvert.SerializeObject (data); + System.IO.File.WriteAllText (SharedDataFileUrl.Path, json); + } - /// <summary> - /// Returns the URL of a data file in the shared App Group container. - /// </summary> - internal static NSUrl SharedDataFileUrl - { - get - { + /// <summary> + /// Returns the URL of a data file in the shared App Group container. + /// </summary> + internal static NSUrl SharedDataFileUrl { + get { - var appGroupIdentifier = "group.com.xamarin.weather-widget"; - var url = NSFileManager.DefaultManager.GetContainerUrl(appGroupIdentifier); - if (url == null) - { - throw new Exception("Expected a valid app group container"); - } + var appGroupIdentifier = "group.com.xamarin.weather-widget"; + var url = NSFileManager.DefaultManager.GetContainerUrl (appGroupIdentifier); + if (url == null) { + throw new Exception ("Expected a valid app group container"); + } - return url.Append("Data.plist", false); - } - } + return url.Append ("Data.plist", false); + } + } - public static List<WeatherForecast> GenerateRandomForecastData() - { - var random = new Random(); - var maximum = Enum.GetNames(typeof(Weather)).Length; + public static List<WeatherForecast> GenerateRandomForecastData () + { + var random = new Random (); + var maximum = Enum.GetNames (typeof (Weather)).Length; - var data = new List<WeatherForecast>(); - for (var daysFromNow = 0; daysFromNow < 4; daysFromNow++) - { - var randomWeather = (Weather)random.Next(maximum); - data.Add(new WeatherForecast(daysFromNow, randomWeather)); - } + var data = new List<WeatherForecast> (); + for (var daysFromNow = 0; daysFromNow < 4; daysFromNow++) { + var randomWeather = (Weather) random.Next (maximum); + data.Add (new WeatherForecast (daysFromNow, randomWeather)); + } - return data; - } - } -} \ No newline at end of file + return data; + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget.Today/ForecastExtensionViewController.cs b/ios11/WeatherWidget/WeatherWidget.Today/ForecastExtensionViewController.cs index 803ab6efe..64d9414fd 100644 --- a/ios11/WeatherWidget/WeatherWidget.Today/ForecastExtensionViewController.cs +++ b/ios11/WeatherWidget/WeatherWidget.Today/ForecastExtensionViewController.cs @@ -5,175 +5,159 @@ using System.Collections.Generic; using UIKit; -namespace WeatherWidget.Today -{ - /// <summary> - /// The widget view controller to show either today's weather forecast or a whole week of forecasts. - /// </summary> - public partial class ForecastExtensionViewController : UITableViewController, INCWidgetProviding - { - private List<WeatherForecast> weatherForecastData = WeatherForecast.LoadSharedData(); - - public ForecastExtensionViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Allow the today widget to be expanded or contracted. - base.ExtensionContext?.SetWidgetLargestAvailableDisplayMode(NCWidgetDisplayMode.Expanded); - - // Register the table view cell. - var weatherForecastTableViewCellNib = UINib.FromName("ForecastTableViewCell", null); - base.TableView.RegisterNibForCellReuse(weatherForecastTableViewCellNib, ForecastTableViewCell.ReuseIdentifier); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - base.TableView.ReloadData(); - } - - #region Widget provider protocol - - [Export("widgetPerformUpdateWithCompletionHandler:")] - public void WidgetPerformUpdate(Action<NCUpdateResult> completionHandler) - { - // Reload the data from disk - this.weatherForecastData = WeatherForecast.LoadSharedData(); - completionHandler(NCUpdateResult.NewData); - } - - [Export("widgetActiveDisplayModeDidChange:withMaximumSize:")] - public void WidgetActiveDisplayModeDidChange(NCWidgetDisplayMode activeDisplayMode, CGSize maxSize) - { - switch (activeDisplayMode) - { - case NCWidgetDisplayMode.Compact: - // The compact view is a fixed size. - base.PreferredContentSize = maxSize; - break; - - case NCWidgetDisplayMode.Expanded: - // Dynamically calculate the height of the cells for the extended height. - var height = 0f; - for (var index = 0; index < this.weatherForecastData.Count; index++) - { - switch (index) - { - case 0: - height += ForecastTableViewCell.TodayCellHeight; - break; - - default: - height += ForecastTableViewCell.StandardCellHeight; - break; - } - } - - base.PreferredContentSize = new CGSize(maxSize.Width, NMath.Min(height, maxSize.Height)); - break; - } - } - - #endregion - - #region Content container protocol - - public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) - { - base.ViewWillTransitionToSize(toSize, coordinator); - - var updatedVisibleCellCount = this.NumberOfTableRowsToDisplay(); - var currentVisibleCellCount = base.TableView.VisibleCells.Length; - var cellCountDifference = updatedVisibleCellCount - currentVisibleCellCount; - - // If the number of visible cells has changed, animate them in/out along with the resize animation. - if (cellCountDifference != 0) - { - coordinator.AnimateAlongsideTransition((_) => - { - base.TableView.PerformBatchUpdates(() => - { - var indexPaths = new List<NSIndexPath>(); - // Build an array of IndexPath objects representing the rows to be inserted or deleted. - for (int i = 1; i <= Math.Abs(cellCountDifference); i++) - { - indexPaths.Add(NSIndexPath.FromRowSection(i, 0)); - } - - // Animate the insertion or deletion of the rows. - if (cellCountDifference > 0) - { - base.TableView.InsertRows(indexPaths.ToArray(), UITableViewRowAnimation.Fade); - } - else - { - base.TableView.DeleteRows(indexPaths.ToArray(), UITableViewRowAnimation.Fade); - } - }, null); - }, null); - } - } - - #endregion - - #region Table view data source - - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.NumberOfTableRowsToDisplay(); - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(ForecastTableViewCell.ReuseIdentifier, indexPath) as ForecastTableViewCell; - - var weatherForecast = weatherForecastData[indexPath.Row]; - cell.Label = weatherForecast.DaysFromNowDescription; - cell.Image = weatherForecast.Forecast.GetImageAsset(); - cell.ForecastLabel = weatherForecast.Forecast.GetDescription(); - return cell; - } - - #endregion - - #region Table view delegate - - public override nfloat GetHeightForRow(UITableView tableView, NSIndexPath indexPath) - { - switch (indexPath.Row) - { - case 0: - return ForecastTableViewCell.TodayCellHeight; - default: - return ForecastTableViewCell.StandardCellHeight; - } - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - // Open the main app at the correct page for the day tapped in the widget. - var weatherForecast = this.weatherForecastData[indexPath.Row]; - var appURL = new NSUrl($"weatherwidget://?daysFromNow={weatherForecast.daysFromNow}"); - base.ExtensionContext?.OpenUrl(appURL, null); - - // Don't leave the today extension with a selected row. - tableView.DeselectRow(indexPath, true); - } - - #endregion - - private int NumberOfTableRowsToDisplay() - { - if (base.ExtensionContext?.GetWidgetActiveDisplayMode() == NCWidgetDisplayMode.Compact) - { - return 1; - } - else - { - return this.weatherForecastData.Count; - } - } - } -} \ No newline at end of file +namespace WeatherWidget.Today { + /// <summary> + /// The widget view controller to show either today's weather forecast or a whole week of forecasts. + /// </summary> + public partial class ForecastExtensionViewController : UITableViewController, INCWidgetProviding { + private List<WeatherForecast> weatherForecastData = WeatherForecast.LoadSharedData (); + + public ForecastExtensionViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Allow the today widget to be expanded or contracted. + base.ExtensionContext?.SetWidgetLargestAvailableDisplayMode (NCWidgetDisplayMode.Expanded); + + // Register the table view cell. + var weatherForecastTableViewCellNib = UINib.FromName ("ForecastTableViewCell", null); + base.TableView.RegisterNibForCellReuse (weatherForecastTableViewCellNib, ForecastTableViewCell.ReuseIdentifier); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + base.TableView.ReloadData (); + } + + #region Widget provider protocol + + [Export ("widgetPerformUpdateWithCompletionHandler:")] + public void WidgetPerformUpdate (Action<NCUpdateResult> completionHandler) + { + // Reload the data from disk + this.weatherForecastData = WeatherForecast.LoadSharedData (); + completionHandler (NCUpdateResult.NewData); + } + + [Export ("widgetActiveDisplayModeDidChange:withMaximumSize:")] + public void WidgetActiveDisplayModeDidChange (NCWidgetDisplayMode activeDisplayMode, CGSize maxSize) + { + switch (activeDisplayMode) { + case NCWidgetDisplayMode.Compact: + // The compact view is a fixed size. + base.PreferredContentSize = maxSize; + break; + + case NCWidgetDisplayMode.Expanded: + // Dynamically calculate the height of the cells for the extended height. + var height = 0f; + for (var index = 0; index < this.weatherForecastData.Count; index++) { + switch (index) { + case 0: + height += ForecastTableViewCell.TodayCellHeight; + break; + + default: + height += ForecastTableViewCell.StandardCellHeight; + break; + } + } + + base.PreferredContentSize = new CGSize (maxSize.Width, NMath.Min (height, maxSize.Height)); + break; + } + } + + #endregion + + #region Content container protocol + + public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerTransitionCoordinator coordinator) + { + base.ViewWillTransitionToSize (toSize, coordinator); + + var updatedVisibleCellCount = this.NumberOfTableRowsToDisplay (); + var currentVisibleCellCount = base.TableView.VisibleCells.Length; + var cellCountDifference = updatedVisibleCellCount - currentVisibleCellCount; + + // If the number of visible cells has changed, animate them in/out along with the resize animation. + if (cellCountDifference != 0) { + coordinator.AnimateAlongsideTransition ((_) => { + base.TableView.PerformBatchUpdates (() => { + var indexPaths = new List<NSIndexPath> (); + // Build an array of IndexPath objects representing the rows to be inserted or deleted. + for (int i = 1; i <= Math.Abs (cellCountDifference); i++) { + indexPaths.Add (NSIndexPath.FromRowSection (i, 0)); + } + + // Animate the insertion or deletion of the rows. + if (cellCountDifference > 0) { + base.TableView.InsertRows (indexPaths.ToArray (), UITableViewRowAnimation.Fade); + } else { + base.TableView.DeleteRows (indexPaths.ToArray (), UITableViewRowAnimation.Fade); + } + }, null); + }, null); + } + } + + #endregion + + #region Table view data source + + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.NumberOfTableRowsToDisplay (); + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (ForecastTableViewCell.ReuseIdentifier, indexPath) as ForecastTableViewCell; + + var weatherForecast = weatherForecastData [indexPath.Row]; + cell.Label = weatherForecast.DaysFromNowDescription; + cell.Image = weatherForecast.Forecast.GetImageAsset (); + cell.ForecastLabel = weatherForecast.Forecast.GetDescription (); + return cell; + } + + #endregion + + #region Table view delegate + + public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) + { + switch (indexPath.Row) { + case 0: + return ForecastTableViewCell.TodayCellHeight; + default: + return ForecastTableViewCell.StandardCellHeight; + } + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + // Open the main app at the correct page for the day tapped in the widget. + var weatherForecast = this.weatherForecastData [indexPath.Row]; + var appURL = new NSUrl ($"weatherwidget://?daysFromNow={weatherForecast.daysFromNow}"); + base.ExtensionContext?.OpenUrl (appURL, null); + + // Don't leave the today extension with a selected row. + tableView.DeselectRow (indexPath, true); + } + + #endregion + + private int NumberOfTableRowsToDisplay () + { + if (base.ExtensionContext?.GetWidgetActiveDisplayMode () == NCWidgetDisplayMode.Compact) { + return 1; + } else { + return this.weatherForecastData.Count; + } + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget.Today/ForecastTableViewCell.cs b/ios11/WeatherWidget/WeatherWidget.Today/ForecastTableViewCell.cs index 6b32ba880..af52cc1d4 100644 --- a/ios11/WeatherWidget/WeatherWidget.Today/ForecastTableViewCell.cs +++ b/ios11/WeatherWidget/WeatherWidget.Today/ForecastTableViewCell.cs @@ -1,39 +1,34 @@ -using Foundation; +using Foundation; using System; using UIKit; -namespace WeatherWidget -{ - /// <summary> - /// A table view cell to show a single day's weather forecast in the today extension. - /// </summary> - public partial class ForecastTableViewCell : UITableViewCell - { - protected ForecastTableViewCell(IntPtr handle) : base(handle) { } +namespace WeatherWidget { + /// <summary> + /// A table view cell to show a single day's weather forecast in the today extension. + /// </summary> + public partial class ForecastTableViewCell : UITableViewCell { + protected ForecastTableViewCell (IntPtr handle) : base (handle) { } - public new static string ReuseIdentifier { get; } = "ForecastTableViewCell"; + public new static string ReuseIdentifier { get; } = "ForecastTableViewCell"; - // Heights for the two styles of cell display. - public static float TodayCellHeight { get; } = 110f; + // Heights for the two styles of cell display. + public static float TodayCellHeight { get; } = 110f; - public static float StandardCellHeight { get; } = 55f; + public static float StandardCellHeight { get; } = 55f; - public string Label - { - get => this.dateLabel.Text; - set => this.dateLabel.Text = value; - } + public string Label { + get => this.dateLabel.Text; + set => this.dateLabel.Text = value; + } - public UIImage Image - { - get => this.forecastImageView.Image; - set => this.forecastImageView.Image = value; - } + public UIImage Image { + get => this.forecastImageView.Image; + set => this.forecastImageView.Image = value; + } - public string ForecastLabel - { - get => this.forecastLabel.Text; - set => this.forecastLabel.Text = value; - } - } -} \ No newline at end of file + public string ForecastLabel { + get => this.forecastLabel.Text; + set => this.forecastLabel.Text = value; + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget/AppDelegate.cs b/ios11/WeatherWidget/WeatherWidget/AppDelegate.cs index c0965087f..b1706e26a 100644 --- a/ios11/WeatherWidget/WeatherWidget/AppDelegate.cs +++ b/ios11/WeatherWidget/WeatherWidget/AppDelegate.cs @@ -1,51 +1,42 @@ -using Foundation; +using Foundation; using System; using System.Linq; using UIKit; -namespace WeatherWidget -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace WeatherWidget { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } + return true; + } - public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) - { - if (this.Window?.RootViewController is UINavigationController navigationController && - navigationController?.ViewControllers?.FirstOrDefault() is ForecastViewController initialViewController) - { - // Extract the daysFromNow query string parameter from the incoming URL. - var components = NSUrlComponents.FromUrl(url, false); - var daysFromNowValue = components?.QueryItems?.FirstOrDefault(item => item.Name == "daysFromNow")?.Value; - if (string.IsNullOrEmpty(daysFromNowValue)) - { - throw new Exception("Expected daysFromNow parameter to have a value"); - } + public override bool OpenUrl (UIApplication app, NSUrl url, NSDictionary options) + { + if (this.Window?.RootViewController is UINavigationController navigationController && + navigationController?.ViewControllers?.FirstOrDefault () is ForecastViewController initialViewController) { + // Extract the daysFromNow query string parameter from the incoming URL. + var components = NSUrlComponents.FromUrl (url, false); + var daysFromNowValue = components?.QueryItems?.FirstOrDefault (item => item.Name == "daysFromNow")?.Value; + if (string.IsNullOrEmpty (daysFromNowValue)) { + throw new Exception ("Expected daysFromNow parameter to have a value"); + } - if (int.TryParse(daysFromNowValue, out int daysFromNow)) - { - // Scroll the initial view controller to the correct index. - initialViewController.ScrollToForecast(daysFromNow); - return true; - } - else - { - throw new Exception("Expected daysFromNow to be an integer"); - } - } - else - { - throw new Exception("Expected the root view controller to be a UINavigationController"); - } - } - } -} \ No newline at end of file + if (int.TryParse (daysFromNowValue, out int daysFromNow)) { + // Scroll the initial view controller to the correct index. + initialViewController.ScrollToForecast (daysFromNow); + return true; + } else { + throw new Exception ("Expected daysFromNow to be an integer"); + } + } else { + throw new Exception ("Expected the root view controller to be a UINavigationController"); + } + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget/ForecastCollectionViewCell.cs b/ios11/WeatherWidget/WeatherWidget/ForecastCollectionViewCell.cs index b371cfee4..fb84fe357 100644 --- a/ios11/WeatherWidget/WeatherWidget/ForecastCollectionViewCell.cs +++ b/ios11/WeatherWidget/WeatherWidget/ForecastCollectionViewCell.cs @@ -1,34 +1,29 @@ -using System; +using System; using UIKit; -namespace WeatherWidget -{ - /// <summary> - /// A collection view cell to show a single day's weather forecast in the main app. - /// </summary> - public partial class ForecastCollectionViewCell : UICollectionViewCell - { - protected ForecastCollectionViewCell(IntPtr handle) : base(handle) { } +namespace WeatherWidget { + /// <summary> + /// A collection view cell to show a single day's weather forecast in the main app. + /// </summary> + public partial class ForecastCollectionViewCell : UICollectionViewCell { + protected ForecastCollectionViewCell (IntPtr handle) : base (handle) { } - /// The reuse identifier for this collection view cell. - public new static string ReuseIdentifier { get; } = "ForecastCollectionViewCell"; + /// The reuse identifier for this collection view cell. + public new static string ReuseIdentifier { get; } = "ForecastCollectionViewCell"; - public string Label - { - get => this.dateLabel.Text; - set => this.dateLabel.Text = value; - } + public string Label { + get => this.dateLabel.Text; + set => this.dateLabel.Text = value; + } - public UIImage Image - { - get => this.forecastImageView.Image; - set => this.forecastImageView.Image = value; - } + public UIImage Image { + get => this.forecastImageView.Image; + set => this.forecastImageView.Image = value; + } - public string ForecastLabel - { - get => this.forecastLabel.Text; - set => this.forecastLabel.Text = value; - } - } -} \ No newline at end of file + public string ForecastLabel { + get => this.forecastLabel.Text; + set => this.forecastLabel.Text = value; + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget/ForecastViewController.cs b/ios11/WeatherWidget/WeatherWidget/ForecastViewController.cs index 4231d3414..5ad85d5d5 100644 --- a/ios11/WeatherWidget/WeatherWidget/ForecastViewController.cs +++ b/ios11/WeatherWidget/WeatherWidget/ForecastViewController.cs @@ -3,66 +3,64 @@ using System.Collections.Generic; using UIKit; -namespace WeatherWidget -{ - /// <summary> - /// The initial view controller for the app to display weather forecast data in a collection view. - /// </summary> - public partial class ForecastViewController : UICollectionViewController, IUICollectionViewDelegateFlowLayout - { - private List<WeatherForecast> weatherForecastData = WeatherForecast.LoadSharedData(); +namespace WeatherWidget { + /// <summary> + /// The initial view controller for the app to display weather forecast data in a collection view. + /// </summary> + public partial class ForecastViewController : UICollectionViewController, IUICollectionViewDelegateFlowLayout { + private List<WeatherForecast> weatherForecastData = WeatherForecast.LoadSharedData (); - public ForecastViewController(IntPtr handle) : base(handle) { } + public ForecastViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - // Register the collection view cells. - var weatherForecastCellNib = UINib.FromName("ForecastCollectionViewCell", null); - base.CollectionView.RegisterNibForCell(weatherForecastCellNib, ForecastCollectionViewCell.ReuseIdentifier); - } + // Register the collection view cells. + var weatherForecastCellNib = UINib.FromName ("ForecastCollectionViewCell", null); + base.CollectionView.RegisterNibForCell (weatherForecastCellNib, ForecastCollectionViewCell.ReuseIdentifier); + } - #region Collection view data source + #region Collection view data source - public override nint GetItemsCount(UICollectionView collectionView, nint section) - { - return this.weatherForecastData.Count; - } + public override nint GetItemsCount (UICollectionView collectionView, nint section) + { + return this.weatherForecastData.Count; + } - public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) - { - var cell = collectionView.DequeueReusableCell(ForecastCollectionViewCell.ReuseIdentifier, indexPath) as ForecastCollectionViewCell; + public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) + { + var cell = collectionView.DequeueReusableCell (ForecastCollectionViewCell.ReuseIdentifier, indexPath) as ForecastCollectionViewCell; - var weatherForecast = this.weatherForecastData[(int)indexPath.Item]; - cell.Label = weatherForecast.DaysFromNowDescription; - cell.Image = weatherForecast.Forecast.GetImageAsset(); - cell.ForecastLabel = weatherForecast.Forecast.GetDescription(); + var weatherForecast = this.weatherForecastData [(int) indexPath.Item]; + cell.Label = weatherForecast.DaysFromNowDescription; + cell.Image = weatherForecast.Forecast.GetImageAsset (); + cell.ForecastLabel = weatherForecast.Forecast.GetDescription (); - return cell; - } + return cell; + } - #endregion + #endregion - partial void RefreshForecast(NSObject sender) - { - // Generate new forecast data, save it to disk and reload the collection view. - this.weatherForecastData = WeatherForecast.GenerateRandomForecastData(); - WeatherForecast.SaveSharedData(this.weatherForecastData); - base.CollectionView.ReloadData(); - } + partial void RefreshForecast (NSObject sender) + { + // Generate new forecast data, save it to disk and reload the collection view. + this.weatherForecastData = WeatherForecast.GenerateRandomForecastData (); + WeatherForecast.SaveSharedData (this.weatherForecastData); + base.CollectionView.ReloadData (); + } - [Export("collectionView:layout:sizeForItemAtIndexPath:")] - public CoreGraphics.CGSize GetSizeForItem(UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath) - { - // The full size of the collection view minus any top or bottom bars. - return collectionView.AdjustedContentInset.InsetRect(collectionView.Bounds).Size; - } + [Export ("collectionView:layout:sizeForItemAtIndexPath:")] + public CoreGraphics.CGSize GetSizeForItem (UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath) + { + // The full size of the collection view minus any top or bottom bars. + return collectionView.AdjustedContentInset.InsetRect (collectionView.Bounds).Size; + } - public void ScrollToForecast(int index) - { - var indexPath = NSIndexPath.FromItemSection(index, 0); - base.CollectionView.ScrollToItem(indexPath, UICollectionViewScrollPosition.CenteredHorizontally, false); - } - } -} \ No newline at end of file + public void ScrollToForecast (int index) + { + var indexPath = NSIndexPath.FromItemSection (index, 0); + base.CollectionView.ScrollToItem (indexPath, UICollectionViewScrollPosition.CenteredHorizontally, false); + } + } +} diff --git a/ios11/WeatherWidget/WeatherWidget/Main.cs b/ios11/WeatherWidget/WeatherWidget/Main.cs index 6d1ec5da2..20c62462d 100644 --- a/ios11/WeatherWidget/WeatherWidget/Main.cs +++ b/ios11/WeatherWidget/WeatherWidget/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace WeatherWidget -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace WeatherWidget { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/ARKitVision/ARKitVision/AppDelegate.cs b/ios12/ARKitVision/ARKitVision/AppDelegate.cs index 92bfced81..41b8aa889 100644 --- a/ios12/ARKitVision/ARKitVision/AppDelegate.cs +++ b/ios12/ARKitVision/ARKitVision/AppDelegate.cs @@ -1,33 +1,30 @@ - -namespace ARKitVision -{ - using ARKit; - using Foundation; - using System; - using UIKit; - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace ARKitVision { + using ARKit; + using Foundation; + using System; + using UIKit; - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - if(!ARConfiguration.IsSupported) - { - throw new Exception("ARKit is not available on this device.For apps that require ARKit " + - "for core functionality, use the `arkit` key in the key in the " + - "`UIRequiredDeviceCapabilities` section of the Info.plist to prevent " + - "the app from installing. (If the app can't be installed, this error " + - "can't be triggered in a production scenario.)" + - "In apps where AR is an additive feature, use `isSupported` to " + - "determine whether to show UI for launching AR experiences."); - // For details, see https://developer.apple.com/documentation/arkit - } + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - return true; - } - } -} \ No newline at end of file + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + if (!ARConfiguration.IsSupported) { + throw new Exception ("ARKit is not available on this device.For apps that require ARKit " + + "for core functionality, use the `arkit` key in the key in the " + + "`UIRequiredDeviceCapabilities` section of the Info.plist to prevent " + + "the app from installing. (If the app can't be installed, this error " + + "can't be triggered in a production scenario.)" + + "In apps where AR is an additive feature, use `isSupported` to " + + "determine whether to show UI for launching AR experiences."); + // For details, see https://developer.apple.com/documentation/arkit + } + + return true; + } + } +} diff --git a/ios12/ARKitVision/ARKitVision/Enums/MessageType.cs b/ios12/ARKitVision/ARKitVision/Enums/MessageType.cs index 66f3dfbc3..bcc43d0ff 100644 --- a/ios12/ARKitVision/ARKitVision/Enums/MessageType.cs +++ b/ios12/ARKitVision/ARKitVision/Enums/MessageType.cs @@ -1,11 +1,9 @@ - -namespace ARKitVision -{ - public enum MessageType - { - TrackingStateEscalation, - PlaneEstimation, - ContentPlacement, - FocusSquare - } -} \ No newline at end of file + +namespace ARKitVision { + public enum MessageType { + TrackingStateEscalation, + PlaneEstimation, + ContentPlacement, + FocusSquare + } +} diff --git a/ios12/ARKitVision/ARKitVision/Main.cs b/ios12/ARKitVision/ARKitVision/Main.cs index 56523b70e..2f8020e40 100644 --- a/ios12/ARKitVision/ARKitVision/Main.cs +++ b/ios12/ARKitVision/ARKitVision/Main.cs @@ -1,16 +1,14 @@ - -namespace ARKitVision -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace ARKitVision { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/ARKitVision/ARKitVision/Resources/Inceptionv3.cs b/ios12/ARKitVision/ARKitVision/Resources/Inceptionv3.cs index feaf116fc..de3ab8278 100644 --- a/ios12/ARKitVision/ARKitVision/Resources/Inceptionv3.cs +++ b/ios12/ARKitVision/ARKitVision/Resources/Inceptionv3.cs @@ -16,8 +16,7 @@ namespace ARKitVision { /// <summary> /// Model Prediction Input Type /// </summary> - public class Inceptionv3Input : NSObject, IMLFeatureProvider - { + public class Inceptionv3Input : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("image") ); @@ -64,8 +63,7 @@ public Inceptionv3Input (CVPixelBuffer image) /// <summary> /// Model Prediction Output Type /// </summary> - public class Inceptionv3Output : NSObject, IMLFeatureProvider - { + public class Inceptionv3Output : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("classLabelProbs"), new NSString ("classLabel") ); @@ -139,8 +137,7 @@ public Inceptionv3Output (NSDictionary<NSObject, NSNumber> classLabelProbs, stri /// <summary> /// Class for model loading and prediction /// </summary> - public class Inceptionv3 : NSObject - { + public class Inceptionv3 : NSObject { public Inceptionv3 () { var url = NSBundle.MainBundle.GetUrlForResource ("Inceptionv3", "mlmodelc"); @@ -154,9 +151,9 @@ public Inceptionv3 () this.Model = model; } - public MLModel Model { get; private set; } + public MLModel Model { get; private set; } - public static Inceptionv3 Create (NSUrl url, out NSError error) + public static Inceptionv3 Create (NSUrl url, out NSError error) { if (url == null) throw new ArgumentNullException (nameof (url)); diff --git a/ios12/ARKitVision/ARKitVision/StatusViewController.cs b/ios12/ARKitVision/ARKitVision/StatusViewController.cs index 8f5618a9f..c2f9ebe24 100644 --- a/ios12/ARKitVision/ARKitVision/StatusViewController.cs +++ b/ios12/ARKitVision/ARKitVision/StatusViewController.cs @@ -1,151 +1,139 @@ - -/* - Displayed at the top of the main interface of the app that allows users to see - the status of the AR experience, as well as the ability to control restarting - the experience altogether. - */ - -namespace ARKitVision -{ - using ARKit; - using Foundation; - using System; - using System.Collections.Generic; - using UIKit; - - /// <summary> - /// Utility class for showing messages above the AR view. - /// </summary> - public partial class StatusViewController : UIViewController - { - /// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages. - private const double DisplayDuration = 6d; - - private Dictionary<MessageType, NSTimer> timers = new Dictionary<MessageType, NSTimer>(); - - // Timer for hiding messages. - private NSTimer messageHideTimer; - - public StatusViewController (IntPtr handle) : base (handle) { } - - /// <summary> - /// Trigerred when the "Restart Experience" button is tapped. - /// </summary> - public Action RestartExperienceHandler { get; set; } - - #region Message Handling - - public void ShowMessage(string text, bool autoHide = true) - { - // Cancel any previous hide timer. - this.messageHideTimer?.Invalidate(); - - this.messageLabel.Text = text; - - // Make sure status is showing. - this.SetMessageHidden(false, true); - - if (autoHide) - { - this.messageHideTimer = NSTimer.CreateScheduledTimer(DisplayDuration, false, (timer) => - { - this.SetMessageHidden(true, true); - }); - } - } - - public void ScheduleMessage(string text, double seconds, MessageType messageType) - { - this.CancelScheduledMessage(messageType); - - var timer = NSTimer.CreateScheduledTimer(seconds, false, (internalTimer) => - { - this.ShowMessage(text); - internalTimer.Invalidate(); - }); - - this.timers[messageType] = timer; - } - - public void CancelScheduledMessage(MessageType messageType) - { - if (this.timers.TryGetValue(messageType, out NSTimer timer)) - { - timer.Invalidate(); - this.timers.Remove(messageType); - } - } - - public void CancelAllScheduledMessages() - { - foreach (MessageType messageType in Enum.GetValues(typeof(MessageType))) - { - this.CancelScheduledMessage(messageType); - } - } - - #endregion - - #region ARKit - - public void ShowTrackingQualityInfo(ARCamera camera, bool autoHide) - { - this.ShowMessage(camera.GetPresentationString(), autoHide); - } - - public void EscalateFeedback(ARCamera camera, double seconds) - { - this.CancelScheduledMessage(MessageType.TrackingStateEscalation); - - var timer = NSTimer.CreateScheduledTimer(seconds, false, (internalTimer) => - { - this.CancelScheduledMessage(MessageType.TrackingStateEscalation); - - var message = camera.GetPresentationString(); - var recommendation = camera.GetRecommendation(); - if (!string.IsNullOrEmpty(recommendation)) - { - message += $": {recommendation}"; - } - - this.ShowMessage(message, false); - }); - - this.timers[MessageType.TrackingStateEscalation] = timer; - } - - #endregion - - #region IBActions - - partial void restartExperience(UIButton sender) - { - this.RestartExperienceHandler(); - } - - #endregion - - #region Panel Visibility - - private void SetMessageHidden(bool hide, bool animated) - { - // The panel starts out hidden, so show it before animating opacity. - messagePanel.Hidden = false; - - if(animated) - { - UIView.Animate(0.2d, - 0d, - UIViewAnimationOptions.BeginFromCurrentState, - () => this.messagePanel.Alpha = hide ? 0f : 1f, - null); - } - else - { - this.messagePanel.Alpha = hide ? 0f : 1f; - } - } - - #endregion - } -} \ No newline at end of file + +/* + Displayed at the top of the main interface of the app that allows users to see + the status of the AR experience, as well as the ability to control restarting + the experience altogether. + */ + +namespace ARKitVision { + using ARKit; + using Foundation; + using System; + using System.Collections.Generic; + using UIKit; + + /// <summary> + /// Utility class for showing messages above the AR view. + /// </summary> + public partial class StatusViewController : UIViewController { + /// Seconds before the timer message should fade out. Adjust if the app needs longer transient messages. + private const double DisplayDuration = 6d; + + private Dictionary<MessageType, NSTimer> timers = new Dictionary<MessageType, NSTimer> (); + + // Timer for hiding messages. + private NSTimer messageHideTimer; + + public StatusViewController (IntPtr handle) : base (handle) { } + + /// <summary> + /// Trigerred when the "Restart Experience" button is tapped. + /// </summary> + public Action RestartExperienceHandler { get; set; } + + #region Message Handling + + public void ShowMessage (string text, bool autoHide = true) + { + // Cancel any previous hide timer. + this.messageHideTimer?.Invalidate (); + + this.messageLabel.Text = text; + + // Make sure status is showing. + this.SetMessageHidden (false, true); + + if (autoHide) { + this.messageHideTimer = NSTimer.CreateScheduledTimer (DisplayDuration, false, (timer) => { + this.SetMessageHidden (true, true); + }); + } + } + + public void ScheduleMessage (string text, double seconds, MessageType messageType) + { + this.CancelScheduledMessage (messageType); + + var timer = NSTimer.CreateScheduledTimer (seconds, false, (internalTimer) => { + this.ShowMessage (text); + internalTimer.Invalidate (); + }); + + this.timers [messageType] = timer; + } + + public void CancelScheduledMessage (MessageType messageType) + { + if (this.timers.TryGetValue (messageType, out NSTimer timer)) { + timer.Invalidate (); + this.timers.Remove (messageType); + } + } + + public void CancelAllScheduledMessages () + { + foreach (MessageType messageType in Enum.GetValues (typeof (MessageType))) { + this.CancelScheduledMessage (messageType); + } + } + + #endregion + + #region ARKit + + public void ShowTrackingQualityInfo (ARCamera camera, bool autoHide) + { + this.ShowMessage (camera.GetPresentationString (), autoHide); + } + + public void EscalateFeedback (ARCamera camera, double seconds) + { + this.CancelScheduledMessage (MessageType.TrackingStateEscalation); + + var timer = NSTimer.CreateScheduledTimer (seconds, false, (internalTimer) => { + this.CancelScheduledMessage (MessageType.TrackingStateEscalation); + + var message = camera.GetPresentationString (); + var recommendation = camera.GetRecommendation (); + if (!string.IsNullOrEmpty (recommendation)) { + message += $": {recommendation}"; + } + + this.ShowMessage (message, false); + }); + + this.timers [MessageType.TrackingStateEscalation] = timer; + } + + #endregion + + #region IBActions + + partial void restartExperience (UIButton sender) + { + this.RestartExperienceHandler (); + } + + #endregion + + #region Panel Visibility + + private void SetMessageHidden (bool hide, bool animated) + { + // The panel starts out hidden, so show it before animating opacity. + messagePanel.Hidden = false; + + if (animated) { + UIView.Animate (0.2d, + 0d, + UIViewAnimationOptions.BeginFromCurrentState, + () => this.messagePanel.Alpha = hide ? 0f : 1f, + null); + } else { + this.messagePanel.Alpha = hide ? 0f : 1f; + } + } + + #endregion + } +} diff --git a/ios12/ARKitVision/ARKitVision/TemplateLabelNode.cs b/ios12/ARKitVision/ARKitVision/TemplateLabelNode.cs index 5aae79e21..04caeeee3 100644 --- a/ios12/ARKitVision/ARKitVision/TemplateLabelNode.cs +++ b/ios12/ARKitVision/ARKitVision/TemplateLabelNode.cs @@ -1,54 +1,49 @@ - -namespace ARKitVision -{ - using Foundation; - using SpriteKit; - using System; - - /// <summary> - /// Instantiates styled label nodes based on a template node in a scene file. - /// </summary> - public class TemplateLabelNode : SKReferenceNode - { - private readonly string text; - - private bool isUpdated; - - private SKNode localParent; - - public TemplateLabelNode(string text) : base("LabelScene") - { - this.text = text; - this.UpdateText(); - } - - public TemplateLabelNode(NSCoder coder) : base(coder) => throw new Exception("init(coder:) has not been implemented"); - - public override void DidLoadReferenceNode(SKNode node) - { - base.DidLoadReferenceNode(node); - - // Apply text to both labels loaded from the template. - this.localParent = node?.GetChildNode("LabelNode"); - if(this.localParent == null) - { - throw new Exception("misconfigured SpriteKit template file"); - } - - this.UpdateText(); - } - - private void UpdateText() - { - if (!this.isUpdated) - { - this.isUpdated = !string.IsNullOrEmpty(this.text); - foreach (SKLabelNode label in this.localParent.Children) - { - label.Name = this.text; - label.Text = this.text; - } - } - } - } -} \ No newline at end of file + +namespace ARKitVision { + using Foundation; + using SpriteKit; + using System; + + /// <summary> + /// Instantiates styled label nodes based on a template node in a scene file. + /// </summary> + public class TemplateLabelNode : SKReferenceNode { + private readonly string text; + + private bool isUpdated; + + private SKNode localParent; + + public TemplateLabelNode (string text) : base ("LabelScene") + { + this.text = text; + this.UpdateText (); + } + + public TemplateLabelNode (NSCoder coder) : base (coder) => throw new Exception ("init(coder:) has not been implemented"); + + public override void DidLoadReferenceNode (SKNode node) + { + base.DidLoadReferenceNode (node); + + // Apply text to both labels loaded from the template. + this.localParent = node?.GetChildNode ("LabelNode"); + if (this.localParent == null) { + throw new Exception ("misconfigured SpriteKit template file"); + } + + this.UpdateText (); + } + + private void UpdateText () + { + if (!this.isUpdated) { + this.isUpdated = !string.IsNullOrEmpty (this.text); + foreach (SKLabelNode label in this.localParent.Children) { + label.Name = this.text; + label.Text = this.text; + } + } + } + } +} diff --git a/ios12/ARKitVision/ARKitVision/Utilities.cs b/ios12/ARKitVision/ARKitVision/Utilities.cs index 2fbaf702f..0f6e915db 100644 --- a/ios12/ARKitVision/ARKitVision/Utilities.cs +++ b/ios12/ARKitVision/ARKitVision/Utilities.cs @@ -1,105 +1,97 @@ - -namespace ARKitVision -{ - using ARKit; - using ImageIO; - using UIKit; - public static class ARTrackingStateExtensions - { - public static string GetPresentationString(this ARCamera self) - { - string result = null; +namespace ARKitVision { + using ARKit; + using ImageIO; + using UIKit; - switch (self.TrackingState) - { - case ARTrackingState.NotAvailable: - result = "TRACKING UNAVAILABLE"; - break; + public static class ARTrackingStateExtensions { + public static string GetPresentationString (this ARCamera self) + { + string result = null; - case ARTrackingState.Normal: - result = "TRACKING NORMAL"; - break; + switch (self.TrackingState) { + case ARTrackingState.NotAvailable: + result = "TRACKING UNAVAILABLE"; + break; - case ARTrackingState.Limited: - switch (self.TrackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: - result = "TRACKING LIMITED\nExcessive motion"; - break; - case ARTrackingStateReason.InsufficientFeatures: - result = "TRACKING LIMITED\nLow detail"; - break; - case ARTrackingStateReason.Initializing: - result = "Initializing"; - break; - case ARTrackingStateReason.Relocalizing: - result = "Recovering from interruption"; - break; - } - break; - } + case ARTrackingState.Normal: + result = "TRACKING NORMAL"; + break; - return result; - } + case ARTrackingState.Limited: + switch (self.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: + result = "TRACKING LIMITED\nExcessive motion"; + break; + case ARTrackingStateReason.InsufficientFeatures: + result = "TRACKING LIMITED\nLow detail"; + break; + case ARTrackingStateReason.Initializing: + result = "Initializing"; + break; + case ARTrackingStateReason.Relocalizing: + result = "Recovering from interruption"; + break; + } + break; + } - public static string GetRecommendation(this ARCamera self) - { - string result = null; + return result; + } - switch (self.TrackingState) - { - case ARTrackingState.Limited: - switch (self.TrackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: - result = "Try slowing down your movement, or reset the session."; - break; - case ARTrackingStateReason.InsufficientFeatures: - result = "Try pointing at a flat surface, or reset the session."; - break; - case ARTrackingStateReason.Relocalizing: - result = "Return to the location where you left off or try resetting the session."; - break; - } - break; - } + public static string GetRecommendation (this ARCamera self) + { + string result = null; - return result; - } - } + switch (self.TrackingState) { + case ARTrackingState.Limited: + switch (self.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: + result = "Try slowing down your movement, or reset the session."; + break; + case ARTrackingStateReason.InsufficientFeatures: + result = "Try pointing at a flat surface, or reset the session."; + break; + case ARTrackingStateReason.Relocalizing: + result = "Return to the location where you left off or try resetting the session."; + break; + } + break; + } - /// <summary> - /// Utility functions and type extensions used throughout the projects. - /// </summary> - public static class CGImagePropertyOrientationExtensions - { - /// <summary> - /// Convert device orientation to image orientation for use by Vision analysis. - /// </summary> - public static CGImagePropertyOrientation ConvertFrom(UIDeviceOrientation deviceOrientation) - { - CGImagePropertyOrientation result; - switch (deviceOrientation) - { - case UIDeviceOrientation.PortraitUpsideDown: - result = CGImagePropertyOrientation.Left; - break; + return result; + } + } - case UIDeviceOrientation.LandscapeLeft: - result = CGImagePropertyOrientation.Up; - break; + /// <summary> + /// Utility functions and type extensions used throughout the projects. + /// </summary> + public static class CGImagePropertyOrientationExtensions { + /// <summary> + /// Convert device orientation to image orientation for use by Vision analysis. + /// </summary> + public static CGImagePropertyOrientation ConvertFrom (UIDeviceOrientation deviceOrientation) + { + CGImagePropertyOrientation result; + switch (deviceOrientation) { + case UIDeviceOrientation.PortraitUpsideDown: + result = CGImagePropertyOrientation.Left; + break; - case UIDeviceOrientation.LandscapeRight: - result = CGImagePropertyOrientation.Down; - break; + case UIDeviceOrientation.LandscapeLeft: + result = CGImagePropertyOrientation.Up; + break; - default: - result = CGImagePropertyOrientation.Right; - break; - } + case UIDeviceOrientation.LandscapeRight: + result = CGImagePropertyOrientation.Down; + break; - return result; - } - } -} \ No newline at end of file + default: + result = CGImagePropertyOrientation.Right; + break; + } + + return result; + } + } +} diff --git a/ios12/ARKitVision/ARKitVision/ViewController.cs b/ios12/ARKitVision/ARKitVision/ViewController.cs index 9a3f4593d..fb68a6b68 100644 --- a/ios12/ARKitVision/ARKitVision/ViewController.cs +++ b/ios12/ARKitVision/ARKitVision/ViewController.cs @@ -1,328 +1,305 @@ - -namespace ARKitVision -{ - using ARKit; - using CoreFoundation; - using CoreVideo; - using Foundation; - using SpriteKit; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - using Vision; - - /// <summary> - /// Main view controller for the ARKitVision sample. - /// </summary> - public partial class ViewController : UIViewController, IUIGestureRecognizerDelegate, IARSKViewDelegate, IARSessionDelegate - { - // The view controller that displays the status and "restart experience" UI. - private StatusViewController statusViewController; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.statusViewController = this.ChildViewControllers.FirstOrDefault(controller => controller is StatusViewController) as StatusViewController; - - // Configiure and present the SpriteKit scene that draws overlay content. - var overlayScene = new SKScene { ScaleMode = SKSceneScaleMode.AspectFill }; - - this.sceneView.Delegate = this; - this.sceneView.PresentScene(overlayScene); - this.sceneView.Session.Delegate = this; - - // Hook up status view controller callback. - this.statusViewController.RestartExperienceHandler = () => this.RestartSession(); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - // Create a session configuration - var configuration = new ARWorldTrackingConfiguration(); - - // Run the view's session - this.sceneView.Session.Run(configuration); - } - - public override void ViewWillDisappear(bool animated) - { - base.ViewWillDisappear(animated); - - // Pause the view's session - this.sceneView.Session.Pause(); - } - - #region IARSessionDelegate - - /// <summary> - /// Pass camera frames received from ARKit to Vision (when not already processing one) - /// </summary> - [Export("session:didUpdateFrame:")] - public void DidUpdateFrame(ARSession session, ARFrame frame) - { - // Do not enqueue other buffers for processing while another Vision task is still running. - // The camera stream has only a finite amount of buffers available; holding too many buffers for analysis would starve the camera. - if (this.currentBuffer == null && frame.Camera.TrackingState == ARTrackingState.Normal) - { - // Retain the image buffer for Vision processing. - this.currentBuffer = frame.CapturedImage; - this.ClassifyCurrentImage(); - } - - frame.Dispose(); - } - - #endregion - - #region Vision classification - - // Queue for dispatching vision classification requests - private readonly DispatchQueue visionQueue = new DispatchQueue("com.example.apple-samplecode.ARKitVision.serialVisionQueue"); - - // The pixel buffer being held for analysis; used to serialize Vision requests. - private CVPixelBuffer currentBuffer; - - /// <summary> - /// Vision classification request and model - /// </summary> - private VNCoreMLRequest ClassificationRequest() - { - var model = VNCoreMLModel.FromMLModel(new Inceptionv3().Model, out NSError error); - if (error == null) - { - var request = new VNCoreMLRequest(model, (internalRequest, internalError) => - { - this.ProcessClassifications(internalRequest, internalError); - }); - - // Crop input images to square area at center, matching the way the ML model was trained. - request.ImageCropAndScaleOption = VNImageCropAndScaleOption.CenterCrop; - - // Use CPU for Vision processing to ensure that there are adequate GPU resources for rendering. - request.UsesCpuOnly = true; - - return request; - } - else - { - throw new Exception($"Failed to load Vision ML model: {error}"); - } - } - - private void ClassifyCurrentImage() - { - // Most computer vision tasks are not rotation agnostic so it is important to pass in the orientation of the image with respect to device. - var orientation = CGImagePropertyOrientationExtensions.ConvertFrom(UIDevice.CurrentDevice.Orientation); - - var requestHandler = new VNImageRequestHandler(this.currentBuffer, orientation, new VNImageOptions()); - visionQueue.DispatchAsync(() => - { - requestHandler.Perform(new VNRequest[] { this.ClassificationRequest() }, out NSError error); - if (error != null) - { - Console.WriteLine($"Error: Vision request failed with error \"{error}\""); - } - - // Release the pixel buffer when done, allowing the next buffer to be processed. - this.currentBuffer.Dispose(); - this.currentBuffer = null; - }); - } - - // Classification results - private string identifierString = string.Empty; - private float confidence = 0f; - - /// <summary> - /// Handle completion of the Vision request and choose results to display. - /// </summary> - private void ProcessClassifications(VNRequest request, NSError error) - { - var classifications = request.GetResults<VNClassificationObservation>(); - if (classifications == null) - { - Console.WriteLine($"Unable to classify image.\n{error.LocalizedDescription}"); - } - - // Show a label for the highest-confidence result (but only above a minimum confidence threshold). - var bestResult = classifications.FirstOrDefault(result => result.Confidence > 0.5f); - if (bestResult != null) - { - this.identifierString = bestResult.Identifier.Split(',')[0]; - this.confidence = bestResult.Confidence; - } - else - { - this.identifierString = string.Empty; - this.confidence = 0f; - } - - DispatchQueue.MainQueue.DispatchAsync(() => this.DisplayClassifierResults()); - } - - /// <summary> - /// Show the classification results in the UI. - /// </summary> - private void DisplayClassifierResults() - { - if (!string.IsNullOrEmpty(this.identifierString)) - { - var message = $"Detected {this.identifierString} with {this.confidence * 100f}% confidence"; - this.statusViewController.ShowMessage(message); - } - } - - #endregion - - #region Tap gesture handler & ARSKViewDelegate - - // Labels for classified objects by ARAnchor UUID - private Dictionary<NSUuid, string> anchorLabels = new Dictionary<NSUuid, string>(); - - /// <summary> - /// When the user taps, add an anchor associated with the current classification result. - /// </summary> - partial void placeLabelInLocationWithSender(UITapGestureRecognizer sender) - { - var hitLocationInView = sender.LocationInView(this.sceneView); - var result = this.sceneView.HitTest(hitLocationInView, ARHitTestResultType.FeaturePoint | ARHitTestResultType.EstimatedHorizontalPlane).FirstOrDefault(); - if (result != null) - { - // Add a new anchor at the tap location. - var anchor = new ARAnchor(result.WorldTransform); - this.sceneView.Session.AddAnchor(anchor); - - // Track anchor ID to associate text with the anchor after ARKit creates a corresponding SKNode. - this.anchorLabels[anchor.Identifier] = this.identifierString; - } - } - - /// <summary> - /// When an anchor is added, provide a SpriteKit node for it and set its text to the classification label. - /// </summary> - [Export("view:didAddNode:forAnchor:")] - public void DidAddNode(ARSKView view, SKNode node, ARAnchor anchor) - { - if (!this.anchorLabels.TryGetValue(anchor.Identifier, out string labelText)) - { - throw new Exception("missing expected associated label for anchor"); - } - - node.AddChild(new TemplateLabelNode(labelText)); - } - - #endregion - - #region AR Session Handling - - [Export("session:cameraDidChangeTrackingState:")] - public void CameraDidChangeTrackingState(ARSession session, ARCamera camera) - { - this.statusViewController.ShowTrackingQualityInfo(camera, true); - - switch (camera.TrackingState) - { - case ARTrackingState.NotAvailable: - case ARTrackingState.Limited: - this.statusViewController.EscalateFeedback(camera, 3.0); - break; - - case ARTrackingState.Normal: - this.statusViewController.CancelScheduledMessage(MessageType.TrackingStateEscalation); - // Unhide content after successful relocalization. - this.SetOverlaysHidden(false); - break; - } - } - - [Export("session:didFailWithError:")] - public void DidFail(ARSession session, NSError error) - { - string[] messages = - { - error.LocalizedDescription, - error.LocalizedFailureReason, - error.LocalizedRecoverySuggestion - }; - - // Filter out optional error messages. - var errorMessage = string.Join("\n", messages); - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.DisplayErrorMessage("The AR session failed.", errorMessage); - }); - } - - [Export("sessionWasInterrupted:")] - public void WasInterrupted(ARSession session) - { - this.SetOverlaysHidden(true); - } - - [Export("sessionShouldAttemptRelocalization:")] - public bool ShouldAttemptRelocalization(ARSession session) - { - /* + +namespace ARKitVision { + using ARKit; + using CoreFoundation; + using CoreVideo; + using Foundation; + using SpriteKit; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + using Vision; + + /// <summary> + /// Main view controller for the ARKitVision sample. + /// </summary> + public partial class ViewController : UIViewController, IUIGestureRecognizerDelegate, IARSKViewDelegate, IARSessionDelegate { + // The view controller that displays the status and "restart experience" UI. + private StatusViewController statusViewController; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.statusViewController = this.ChildViewControllers.FirstOrDefault (controller => controller is StatusViewController) as StatusViewController; + + // Configiure and present the SpriteKit scene that draws overlay content. + var overlayScene = new SKScene { ScaleMode = SKSceneScaleMode.AspectFill }; + + this.sceneView.Delegate = this; + this.sceneView.PresentScene (overlayScene); + this.sceneView.Session.Delegate = this; + + // Hook up status view controller callback. + this.statusViewController.RestartExperienceHandler = () => this.RestartSession (); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + // Create a session configuration + var configuration = new ARWorldTrackingConfiguration (); + + // Run the view's session + this.sceneView.Session.Run (configuration); + } + + public override void ViewWillDisappear (bool animated) + { + base.ViewWillDisappear (animated); + + // Pause the view's session + this.sceneView.Session.Pause (); + } + + #region IARSessionDelegate + + /// <summary> + /// Pass camera frames received from ARKit to Vision (when not already processing one) + /// </summary> + [Export ("session:didUpdateFrame:")] + public void DidUpdateFrame (ARSession session, ARFrame frame) + { + // Do not enqueue other buffers for processing while another Vision task is still running. + // The camera stream has only a finite amount of buffers available; holding too many buffers for analysis would starve the camera. + if (this.currentBuffer == null && frame.Camera.TrackingState == ARTrackingState.Normal) { + // Retain the image buffer for Vision processing. + this.currentBuffer = frame.CapturedImage; + this.ClassifyCurrentImage (); + } + + frame.Dispose (); + } + + #endregion + + #region Vision classification + + // Queue for dispatching vision classification requests + private readonly DispatchQueue visionQueue = new DispatchQueue ("com.example.apple-samplecode.ARKitVision.serialVisionQueue"); + + // The pixel buffer being held for analysis; used to serialize Vision requests. + private CVPixelBuffer currentBuffer; + + /// <summary> + /// Vision classification request and model + /// </summary> + private VNCoreMLRequest ClassificationRequest () + { + var model = VNCoreMLModel.FromMLModel (new Inceptionv3 ().Model, out NSError error); + if (error == null) { + var request = new VNCoreMLRequest (model, (internalRequest, internalError) => { + this.ProcessClassifications (internalRequest, internalError); + }); + + // Crop input images to square area at center, matching the way the ML model was trained. + request.ImageCropAndScaleOption = VNImageCropAndScaleOption.CenterCrop; + + // Use CPU for Vision processing to ensure that there are adequate GPU resources for rendering. + request.UsesCpuOnly = true; + + return request; + } else { + throw new Exception ($"Failed to load Vision ML model: {error}"); + } + } + + private void ClassifyCurrentImage () + { + // Most computer vision tasks are not rotation agnostic so it is important to pass in the orientation of the image with respect to device. + var orientation = CGImagePropertyOrientationExtensions.ConvertFrom (UIDevice.CurrentDevice.Orientation); + + var requestHandler = new VNImageRequestHandler (this.currentBuffer, orientation, new VNImageOptions ()); + visionQueue.DispatchAsync (() => { + requestHandler.Perform (new VNRequest [] { this.ClassificationRequest () }, out NSError error); + if (error != null) { + Console.WriteLine ($"Error: Vision request failed with error \"{error}\""); + } + + // Release the pixel buffer when done, allowing the next buffer to be processed. + this.currentBuffer.Dispose (); + this.currentBuffer = null; + }); + } + + // Classification results + private string identifierString = string.Empty; + private float confidence = 0f; + + /// <summary> + /// Handle completion of the Vision request and choose results to display. + /// </summary> + private void ProcessClassifications (VNRequest request, NSError error) + { + var classifications = request.GetResults<VNClassificationObservation> (); + if (classifications == null) { + Console.WriteLine ($"Unable to classify image.\n{error.LocalizedDescription}"); + } + + // Show a label for the highest-confidence result (but only above a minimum confidence threshold). + var bestResult = classifications.FirstOrDefault (result => result.Confidence > 0.5f); + if (bestResult != null) { + this.identifierString = bestResult.Identifier.Split (',') [0]; + this.confidence = bestResult.Confidence; + } else { + this.identifierString = string.Empty; + this.confidence = 0f; + } + + DispatchQueue.MainQueue.DispatchAsync (() => this.DisplayClassifierResults ()); + } + + /// <summary> + /// Show the classification results in the UI. + /// </summary> + private void DisplayClassifierResults () + { + if (!string.IsNullOrEmpty (this.identifierString)) { + var message = $"Detected {this.identifierString} with {this.confidence * 100f}% confidence"; + this.statusViewController.ShowMessage (message); + } + } + + #endregion + + #region Tap gesture handler & ARSKViewDelegate + + // Labels for classified objects by ARAnchor UUID + private Dictionary<NSUuid, string> anchorLabels = new Dictionary<NSUuid, string> (); + + /// <summary> + /// When the user taps, add an anchor associated with the current classification result. + /// </summary> + partial void placeLabelInLocationWithSender (UITapGestureRecognizer sender) + { + var hitLocationInView = sender.LocationInView (this.sceneView); + var result = this.sceneView.HitTest (hitLocationInView, ARHitTestResultType.FeaturePoint | ARHitTestResultType.EstimatedHorizontalPlane).FirstOrDefault (); + if (result != null) { + // Add a new anchor at the tap location. + var anchor = new ARAnchor (result.WorldTransform); + this.sceneView.Session.AddAnchor (anchor); + + // Track anchor ID to associate text with the anchor after ARKit creates a corresponding SKNode. + this.anchorLabels [anchor.Identifier] = this.identifierString; + } + } + + /// <summary> + /// When an anchor is added, provide a SpriteKit node for it and set its text to the classification label. + /// </summary> + [Export ("view:didAddNode:forAnchor:")] + public void DidAddNode (ARSKView view, SKNode node, ARAnchor anchor) + { + if (!this.anchorLabels.TryGetValue (anchor.Identifier, out string labelText)) { + throw new Exception ("missing expected associated label for anchor"); + } + + node.AddChild (new TemplateLabelNode (labelText)); + } + + #endregion + + #region AR Session Handling + + [Export ("session:cameraDidChangeTrackingState:")] + public void CameraDidChangeTrackingState (ARSession session, ARCamera camera) + { + this.statusViewController.ShowTrackingQualityInfo (camera, true); + + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + case ARTrackingState.Limited: + this.statusViewController.EscalateFeedback (camera, 3.0); + break; + + case ARTrackingState.Normal: + this.statusViewController.CancelScheduledMessage (MessageType.TrackingStateEscalation); + // Unhide content after successful relocalization. + this.SetOverlaysHidden (false); + break; + } + } + + [Export ("session:didFailWithError:")] + public void DidFail (ARSession session, NSError error) + { + string [] messages = + { + error.LocalizedDescription, + error.LocalizedFailureReason, + error.LocalizedRecoverySuggestion + }; + + // Filter out optional error messages. + var errorMessage = string.Join ("\n", messages); + DispatchQueue.MainQueue.DispatchAsync (() => { + this.DisplayErrorMessage ("The AR session failed.", errorMessage); + }); + } + + [Export ("sessionWasInterrupted:")] + public void WasInterrupted (ARSession session) + { + this.SetOverlaysHidden (true); + } + + [Export ("sessionShouldAttemptRelocalization:")] + public bool ShouldAttemptRelocalization (ARSession session) + { + /* * Allow the session to attempt to resume after an interruption. * This process may not succeed, so the app must be prepared * to reset the session if the relocalizing status continues * for a long time -- see `escalateFeedback` in `StatusViewController`. */ - return true; - } - - private void SetOverlaysHidden(bool shouldHide) - { - foreach(var node in this.sceneView.Scene) - { - if (shouldHide) - { - // Hide overlay content immediately during relocalization. - node.Alpha = 0f; - } - else - { - // Fade overlay content in after relocalization succeeds. - node.RunAction(SKAction.FadeInWithDuration(0.5d)); - } - } - } - - private void RestartSession() - { - this.statusViewController.CancelAllScheduledMessages(); - this.statusViewController.ShowMessage("RESTARTING SESSION"); - - this.anchorLabels = new Dictionary<NSUuid, string>(); - - var configuration = new ARWorldTrackingConfiguration(); - this.sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - } - - #endregion - - #region Error handling - - private void DisplayErrorMessage(string title, string message) - { - // Present an alert informing about the error that has occurred. - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - var restartAction = UIAlertAction.Create("Restart Session", UIAlertActionStyle.Default, (_) => - { - alertController.DismissViewController(true, null); - this.RestartSession(); - }); - - alertController.AddAction(restartAction); - this.PresentViewController(alertController, true, null); - } - - #endregion - } -} \ No newline at end of file + return true; + } + + private void SetOverlaysHidden (bool shouldHide) + { + foreach (var node in this.sceneView.Scene) { + if (shouldHide) { + // Hide overlay content immediately during relocalization. + node.Alpha = 0f; + } else { + // Fade overlay content in after relocalization succeeds. + node.RunAction (SKAction.FadeInWithDuration (0.5d)); + } + } + } + + private void RestartSession () + { + this.statusViewController.CancelAllScheduledMessages (); + this.statusViewController.ShowMessage ("RESTARTING SESSION"); + + this.anchorLabels = new Dictionary<NSUuid, string> (); + + var configuration = new ARWorldTrackingConfiguration (); + this.sceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + } + + #endregion + + #region Error handling + + private void DisplayErrorMessage (string title, string message) + { + // Present an alert informing about the error that has occurred. + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + var restartAction = UIAlertAction.Create ("Restart Session", UIAlertActionStyle.Default, (_) => { + alertController.DismissViewController (true, null); + this.RestartSession (); + }); + + alertController.AddAction (restartAction); + this.PresentViewController (alertController, true, null); + } + + #endregion + } +} diff --git a/ios12/ARMultiuser/ARMultiuser/AppDelegate.cs b/ios12/ARMultiuser/ARMultiuser/AppDelegate.cs index 03b35c459..fc1f40ccc 100644 --- a/ios12/ARMultiuser/ARMultiuser/AppDelegate.cs +++ b/ios12/ARMultiuser/ARMultiuser/AppDelegate.cs @@ -1,22 +1,20 @@ - -namespace ARMultiuser -{ - using Foundation; - using UIKit; - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace ARMultiuser { + using Foundation; + using UIKit; - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - return true; - } - } -} \ No newline at end of file + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + } +} diff --git a/ios12/ARMultiuser/ARMultiuser/Main.cs b/ios12/ARMultiuser/ARMultiuser/Main.cs index 50663db82..a65776b8f 100644 --- a/ios12/ARMultiuser/ARMultiuser/Main.cs +++ b/ios12/ARMultiuser/ARMultiuser/Main.cs @@ -1,16 +1,14 @@ - -namespace ARMultiuser -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace ARMultiuser { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/ARMultiuser/ARMultiuser/MultipeerSession.cs b/ios12/ARMultiuser/ARMultiuser/MultipeerSession.cs index 525a28806..67da58610 100644 --- a/ios12/ARMultiuser/ARMultiuser/MultipeerSession.cs +++ b/ios12/ARMultiuser/ARMultiuser/MultipeerSession.cs @@ -1,108 +1,105 @@ - -namespace ARMultiuser -{ - using Foundation; - using MultipeerConnectivity; - using System; - using System.Collections.Generic; - using UIKit; - - /// <summary> - /// A simple abstraction of the MultipeerConnectivity API as used in this app. - /// </summary> - public class MultipeerSession : NSObject, - IMCSessionDelegate, - IMCNearbyServiceBrowserDelegate, - IMCNearbyServiceAdvertiserDelegate - { - private const string ServiceType = "ar-multi-sample"; - - private readonly MCPeerID myPeerID = new MCPeerID(UIDevice.CurrentDevice.Name); - private readonly MCNearbyServiceAdvertiser serviceAdvertiser; - private readonly MCNearbyServiceBrowser serviceBrowser; - private readonly MCSession session; - - private readonly Action<NSData, MCPeerID> receivedDataHandler; - - public MultipeerSession(Action<NSData, MCPeerID> receivedDataHandler) : base() - { - this.receivedDataHandler = receivedDataHandler; - - this.session = new MCSession(this.myPeerID, null, MCEncryptionPreference.Required); - this.session.Delegate = this; - - this.serviceAdvertiser = new MCNearbyServiceAdvertiser(this.myPeerID, null, ServiceType); - this.serviceAdvertiser.Delegate = this; - this.serviceAdvertiser.StartAdvertisingPeer(); - - this.serviceBrowser = new MCNearbyServiceBrowser(this.myPeerID, ServiceType); - this.serviceBrowser.Delegate = this; - this.serviceBrowser.StartBrowsingForPeers(); - } - - public IList<MCPeerID> ConnectedPeers => this.session.ConnectedPeers; - - public void SendToAllPeers(NSData data) - { - this.session.SendData(data, this.session.ConnectedPeers, MCSessionSendDataMode.Reliable, out NSError error); - if (error != null) - { - Console.WriteLine($"error sending data to peers: {error.LocalizedDescription}"); - } - } - - #region IMCSessionDelegate - - public void DidChangeState(MCSession session, MCPeerID peerID, MCSessionState state) - { - // not used - } - - public void DidFinishReceivingResource(MCSession session, string resourceName, MCPeerID fromPeer, NSUrl localUrl, NSError error) - { - throw new Exception("This service does not send/receive resources."); - } - - public void DidReceiveData(MCSession session, NSData data, MCPeerID peerID) - { - this.receivedDataHandler(data, peerID); - } - - public void DidReceiveStream(MCSession session, NSInputStream stream, string streamName, MCPeerID peerID) - { - throw new Exception("This service does not send/receive streams."); - } - - public void DidStartReceivingResource(MCSession session, string resourceName, MCPeerID fromPeer, NSProgress progress) - { - throw new Exception("This service does not send/receive resources."); - } - - #endregion - - #region IMCNearbyServiceBrowserDelegate - - public void FoundPeer(MCNearbyServiceBrowser browser, MCPeerID peerID, NSDictionary info) - { - // Invite the new peer to the session. - browser.InvitePeer(peerID, this.session, null, 10); - } - - public void LostPeer(MCNearbyServiceBrowser browser, MCPeerID peerID) - { - // This app doesn't do anything with non-invited peers, so there's nothing to do here. - } - - #endregion - - #region IMCNearbyServiceAdvertiserDelegate - - public void DidReceiveInvitationFromPeer(MCNearbyServiceAdvertiser advertiser, MCPeerID peerID, NSData context, MCNearbyServiceAdvertiserInvitationHandler invitationHandler) - { - // Call handler to accept invitation and join the session. - invitationHandler(true, this.session); - } - - #endregion - } + +namespace ARMultiuser { + using Foundation; + using MultipeerConnectivity; + using System; + using System.Collections.Generic; + using UIKit; + + /// <summary> + /// A simple abstraction of the MultipeerConnectivity API as used in this app. + /// </summary> + public class MultipeerSession : NSObject, + IMCSessionDelegate, + IMCNearbyServiceBrowserDelegate, + IMCNearbyServiceAdvertiserDelegate { + private const string ServiceType = "ar-multi-sample"; + + private readonly MCPeerID myPeerID = new MCPeerID (UIDevice.CurrentDevice.Name); + private readonly MCNearbyServiceAdvertiser serviceAdvertiser; + private readonly MCNearbyServiceBrowser serviceBrowser; + private readonly MCSession session; + + private readonly Action<NSData, MCPeerID> receivedDataHandler; + + public MultipeerSession (Action<NSData, MCPeerID> receivedDataHandler) : base () + { + this.receivedDataHandler = receivedDataHandler; + + this.session = new MCSession (this.myPeerID, null, MCEncryptionPreference.Required); + this.session.Delegate = this; + + this.serviceAdvertiser = new MCNearbyServiceAdvertiser (this.myPeerID, null, ServiceType); + this.serviceAdvertiser.Delegate = this; + this.serviceAdvertiser.StartAdvertisingPeer (); + + this.serviceBrowser = new MCNearbyServiceBrowser (this.myPeerID, ServiceType); + this.serviceBrowser.Delegate = this; + this.serviceBrowser.StartBrowsingForPeers (); + } + + public IList<MCPeerID> ConnectedPeers => this.session.ConnectedPeers; + + public void SendToAllPeers (NSData data) + { + this.session.SendData (data, this.session.ConnectedPeers, MCSessionSendDataMode.Reliable, out NSError error); + if (error != null) { + Console.WriteLine ($"error sending data to peers: {error.LocalizedDescription}"); + } + } + + #region IMCSessionDelegate + + public void DidChangeState (MCSession session, MCPeerID peerID, MCSessionState state) + { + // not used + } + + public void DidFinishReceivingResource (MCSession session, string resourceName, MCPeerID fromPeer, NSUrl localUrl, NSError error) + { + throw new Exception ("This service does not send/receive resources."); + } + + public void DidReceiveData (MCSession session, NSData data, MCPeerID peerID) + { + this.receivedDataHandler (data, peerID); + } + + public void DidReceiveStream (MCSession session, NSInputStream stream, string streamName, MCPeerID peerID) + { + throw new Exception ("This service does not send/receive streams."); + } + + public void DidStartReceivingResource (MCSession session, string resourceName, MCPeerID fromPeer, NSProgress progress) + { + throw new Exception ("This service does not send/receive resources."); + } + + #endregion + + #region IMCNearbyServiceBrowserDelegate + + public void FoundPeer (MCNearbyServiceBrowser browser, MCPeerID peerID, NSDictionary info) + { + // Invite the new peer to the session. + browser.InvitePeer (peerID, this.session, null, 10); + } + + public void LostPeer (MCNearbyServiceBrowser browser, MCPeerID peerID) + { + // This app doesn't do anything with non-invited peers, so there's nothing to do here. + } + + #endregion + + #region IMCNearbyServiceAdvertiserDelegate + + public void DidReceiveInvitationFromPeer (MCNearbyServiceAdvertiser advertiser, MCPeerID peerID, NSData context, MCNearbyServiceAdvertiserInvitationHandler invitationHandler) + { + // Call handler to accept invitation and join the session. + invitationHandler (true, this.session); + } + + #endregion + } } diff --git a/ios12/ARMultiuser/ARMultiuser/RoundedButton.cs b/ios12/ARMultiuser/ARMultiuser/RoundedButton.cs index 71392983b..5218bf4b8 100644 --- a/ios12/ARMultiuser/ARMultiuser/RoundedButton.cs +++ b/ios12/ARMultiuser/ARMultiuser/RoundedButton.cs @@ -1,49 +1,44 @@ - -namespace ARMultiuser -{ - using CoreGraphics; - using Foundation; - using UIKit; - /// <summary> - /// A custom button that stands out over the camera view. - /// </summary> - [Register("RoundedButton")] - public class RoundedButton : UIButton - { - [Export("initWithCoder:")] - public RoundedButton(NSCoder coder) : base(coder) - { - this.Setup(); - } +namespace ARMultiuser { + using CoreGraphics; + using Foundation; + using UIKit; - [Export("initWithFrame:")] - public RoundedButton(CGRect frame) : base(frame) - { - this.Setup(); - } + /// <summary> + /// A custom button that stands out over the camera view. + /// </summary> + [Register ("RoundedButton")] + public class RoundedButton : UIButton { + [Export ("initWithCoder:")] + public RoundedButton (NSCoder coder) : base (coder) + { + this.Setup (); + } - private void Setup() - { - this.BackgroundColor = this.TintColor; - this.Layer.CornerRadius = 8f; - this.ClipsToBounds = true; - this.SetTitleColor(UIColor.White, UIControlState.Normal); - if (this.TitleLabel != null) - { - this.TitleLabel.Font = UIFont.BoldSystemFontOfSize(17f); - } - } + [Export ("initWithFrame:")] + public RoundedButton (CGRect frame) : base (frame) + { + this.Setup (); + } - public override bool Enabled - { - get => base.Enabled; + private void Setup () + { + this.BackgroundColor = this.TintColor; + this.Layer.CornerRadius = 8f; + this.ClipsToBounds = true; + this.SetTitleColor (UIColor.White, UIControlState.Normal); + if (this.TitleLabel != null) { + this.TitleLabel.Font = UIFont.BoldSystemFontOfSize (17f); + } + } - set - { - base.Enabled = value; - this.BackgroundColor = value ? this.TintColor : UIColor.Gray; - } - } - } + public override bool Enabled { + get => base.Enabled; + + set { + base.Enabled = value; + this.BackgroundColor = value ? this.TintColor : UIColor.Gray; + } + } + } } diff --git a/ios12/ARMultiuser/ARMultiuser/Utils.cs b/ios12/ARMultiuser/ARMultiuser/Utils.cs index f451242a6..970e83b80 100644 --- a/ios12/ARMultiuser/ARMultiuser/Utils.cs +++ b/ios12/ARMultiuser/ARMultiuser/Utils.cs @@ -1,34 +1,31 @@ - -namespace ARMultiuser -{ - using ARKit; - public static class ARWorldMappingStatusExtensions - { - public static string GetDescription(this ARWorldMappingStatus status) - { - string result = null; +namespace ARMultiuser { + using ARKit; - switch (status) - { - case ARWorldMappingStatus.NotAvailable: - result = "Not Available"; - break; + public static class ARWorldMappingStatusExtensions { + public static string GetDescription (this ARWorldMappingStatus status) + { + string result = null; - case ARWorldMappingStatus.Limited: - result = "Limited"; - break; + switch (status) { + case ARWorldMappingStatus.NotAvailable: + result = "Not Available"; + break; - case ARWorldMappingStatus.Extending: - result = "Extending"; - break; + case ARWorldMappingStatus.Limited: + result = "Limited"; + break; - case ARWorldMappingStatus.Mapped: - result = "Mapped"; - break; - } + case ARWorldMappingStatus.Extending: + result = "Extending"; + break; - return result; - } - } -} \ No newline at end of file + case ARWorldMappingStatus.Mapped: + result = "Mapped"; + break; + } + + return result; + } + } +} diff --git a/ios12/ARMultiuser/ARMultiuser/ViewController.cs b/ios12/ARMultiuser/ARMultiuser/ViewController.cs index 4b0165518..463e2845f 100644 --- a/ios12/ARMultiuser/ARMultiuser/ViewController.cs +++ b/ios12/ARMultiuser/ARMultiuser/ViewController.cs @@ -1,314 +1,286 @@ - -namespace ARMultiuser -{ - using ARKit; - using Foundation; - using MultipeerConnectivity; - using SceneKit; - using System; - using System.Linq; - using UIKit; - - public partial class ViewController : UIViewController, IARSCNViewDelegate, IARSessionDelegate - { - private MultipeerSession multipeerSession; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.sceneView.Delegate = this; - this.multipeerSession = new MultipeerSession(this.ReceivedData); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - if (!ARConfiguration.IsSupported) - { - throw new Exception("ARKit is not available on this device. For apps that require ARKit" + - "for core functionality, use the `arkit` key in the key in the" + - "`UIRequiredDeviceCapabilities` section of the Info.plist to prevent" + - "the app from installing. (If the app can't be installed, this error" + - "can't be triggered in a production scenario.)" + - "In apps where AR is an additive feature, use `isSupported` to" + - "determine whether to show UI for launching AR experiences."); - // For details, see https://developer.apple.com/documentation/arkit - } - - // Start the view's AR session. - var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; - this.sceneView.Session.Run(configuration); - - // Set a delegate to track the number of plane anchors for providing UI feedback. - this.sceneView.Session.Delegate = this; - this.sceneView.DebugOptions = ARSCNDebugOptions.ShowFeaturePoints; - - // Prevent the screen from being dimmed after a while as users will likely - // have long periods of interaction without touching the screen or buttons. - UIApplication.SharedApplication.IdleTimerDisabled = true; - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - - // Pause the view's AR session. - this.sceneView.Session.Pause(); - } - - #region IARSCNViewDelegate - - [Export("renderer:didAddNode:forAnchor:")] - public void DidAddNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) - { - if (!string.IsNullOrEmpty(anchor.Name) && - anchor.Name.StartsWith("panda", StringComparison.InvariantCulture)) - { - node.AddChildNode(this.LoadRedPandaModel()); - } - } - - #endregion - - #region IARSessionDelegate - - [Export("session:cameraDidChangeTrackingState:")] - public void CameraDidChangeTrackingState(ARSession session, ARCamera camera) - { - this.UpdateSessionInfoLabel(session.CurrentFrame, camera.TrackingState, camera.TrackingStateReason); - } - - [Export("session:didUpdateFrame:")] - public void DidUpdateFrame(ARSession session, ARFrame frame) - { - switch (frame.WorldMappingStatus) - { - case ARWorldMappingStatus.NotAvailable: - case ARWorldMappingStatus.Limited: - this.sendMapButton.Enabled = false; - break; - - case ARWorldMappingStatus.Extending: - this.sendMapButton.Enabled = this.multipeerSession.ConnectedPeers.Any(); - break; - - case ARWorldMappingStatus.Mapped: - this.sendMapButton.Enabled = this.multipeerSession.ConnectedPeers.Any(); - break; - } - - this.mappingStatusLabel.Text = frame.WorldMappingStatus.GetDescription(); - this.UpdateSessionInfoLabel(frame, frame.Camera.TrackingState, frame.Camera.TrackingStateReason); - - frame?.Dispose(); - } - - #endregion - - #region ARSessionObserver - - [Export("sessionWasInterrupted:")] - public void WasInterrupted(ARSession session) - { - // Inform the user that the session has been interrupted, for example, by presenting an overlay. - this.sessionInfoLabel.Text = "Session was interrupted"; - } - - [Export("sessionInterruptionEnded:")] - public void InterruptionEnded(ARSession session) - { - // Reset tracking and/or remove existing anchors if consistent tracking is required. - this.sessionInfoLabel.Text = "Session interruption ended"; - } - - [Export("session:didFailWithError:")] - public void DidFail(ARSession session, NSError error) - { - // Present an error message to the user. - this.sessionInfoLabel.Text = $"Session failed: {error.LocalizedDescription}"; - this.resetTracking(null); - } - - [Export("sessionShouldAttemptRelocalization:")] - public bool ShouldAttemptRelocalization(ARSession session) - { - return true; - } - - #endregion - - #region Multiuser shared session - - partial void handleSceneTap(UITapGestureRecognizer sender) - { - // Hit test to find a place for a virtual object. - var types = ARHitTestResultType.ExistingPlaneUsingGeometry | ARHitTestResultType.EstimatedHorizontalPlane; - var hitTestResult = this.sceneView.HitTest(sender.LocationInView(this.sceneView), types).FirstOrDefault(); - if (hitTestResult != null) - { - // Place an anchor for a virtual character. The model appears in renderer(_:didAdd:for:). - var anchor = new ARAnchor("panda", hitTestResult.WorldTransform); - this.sceneView.Session.AddAnchor(anchor); - - // Send the anchor info to peers, so they can place the same content. - var data = NSKeyedArchiver.ArchivedDataWithRootObject(anchor, true, out NSError error); - if (error != null) - { - throw new Exception("can't encode anchor"); - } - - this.multipeerSession.SendToAllPeers(data); - } - } - - // GetWorldMap - partial void shareSession(RoundedButton sender) - { - this.sceneView.Session.GetCurrentWorldMap((worldMap, error) => - { - if (worldMap != null) - { - var data = NSKeyedArchiver.ArchivedDataWithRootObject(worldMap, true, out NSError archivError); - if (archivError != null) - { - throw new Exception("can't encode map"); - } - - this.multipeerSession.SendToAllPeers(data); - } - else if(error != null) - { - Console.WriteLine($"Error: {error.LocalizedDescription}"); - } - }); - } - - private MCPeerID mapProvider; - - private void ReceivedData(NSData data, MCPeerID peer) - { - if (NSKeyedUnarchiver.GetUnarchivedObject(typeof(ARWorldMap), data, out NSError error) is ARWorldMap worldMap) - { - // Run the session with the received world map. - var configuration = new ARWorldTrackingConfiguration(); - configuration.PlaneDetection = ARPlaneDetection.Horizontal; - configuration.InitialWorldMap = worldMap; - this.sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - - // Remember who provided the map for showing UI feedback. - this.mapProvider = peer; - } - else if (NSKeyedUnarchiver.GetUnarchivedObject(typeof(ARAnchor), data, out NSError anchorError) is ARAnchor anchor) - { - // Add anchor to the session, ARSCNView delegate adds visible content. - this.sceneView.Session.AddAnchor(anchor); - } - else - { - Console.WriteLine($"Unknown data was recieved from {peer}"); - } - } - - #endregion - - #region AR session management - - private void UpdateSessionInfoLabel(ARFrame frame, ARTrackingState trackingState, ARTrackingStateReason trackingStateReason) - { - // Update the UI to provide feedback on the state of the AR experience. - string message = null; - - switch (trackingState) - { - case ARTrackingState.Normal: - if (!frame.Anchors.Any() && !this.multipeerSession.ConnectedPeers.Any()) - { - // No planes detected; provide instructions for this app's AR interactions. - message = "Move around to map the environment, or wait to join a shared session."; - } - else if (this.multipeerSession.ConnectedPeers.Any() && this.mapProvider == null) - { - var peerNames = this.multipeerSession.ConnectedPeers.Select(peer => peer.DisplayName); - message = $"Connected with {string.Join(", ", peerNames)}."; - } - break; - - case ARTrackingState.NotAvailable: - message = "Tracking unavailable."; - break; - - case ARTrackingState.Limited: - switch (trackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: - message = "Tracking limited - Move the device more slowly."; - break; - case ARTrackingStateReason.InsufficientFeatures: - message = "Tracking limited - Point the device at an area with visible surface detail, or improve lighting conditions."; - break; - - case ARTrackingStateReason.Initializing: - if (this.mapProvider != null) - { - message = $"Received map from {this.mapProvider.DisplayName}."; - } - else - { - message = "Initializing AR session."; - } - break; - - case ARTrackingStateReason.Relocalizing: - - if (this.mapProvider != null) - { - message = $"Received map from {this.mapProvider.DisplayName}."; - } - else - { - message = "Resuming session — move to where you were when the session was interrupted."; - } - break; - - default: - break; - } - - break; - - default: - // No feedback needed when tracking is normal and planes are visible. - // (Nor when in unreachable limited-tracking states.) - message = ""; - break; - } - - this.sessionInfoLabel.Text = message; - this.sessionInfoView.Hidden = string.IsNullOrEmpty(message); - } - - partial void resetTracking(UIButton sender) - { - var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; - this.sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); - } - - #endregion - - #region AR session management - - private SCNNode LoadRedPandaModel() - { - var sceneURL = NSBundle.MainBundle.GetUrlForResource("max", "scn", "art.scnassets"); - var referenceNode = SCNReferenceNode.CreateFromUrl(sceneURL); - referenceNode.Load(); - - return referenceNode; - } - - #endregion - } -} \ No newline at end of file + +namespace ARMultiuser { + using ARKit; + using Foundation; + using MultipeerConnectivity; + using SceneKit; + using System; + using System.Linq; + using UIKit; + + public partial class ViewController : UIViewController, IARSCNViewDelegate, IARSessionDelegate { + private MultipeerSession multipeerSession; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.sceneView.Delegate = this; + this.multipeerSession = new MultipeerSession (this.ReceivedData); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + if (!ARConfiguration.IsSupported) { + throw new Exception ("ARKit is not available on this device. For apps that require ARKit" + + "for core functionality, use the `arkit` key in the key in the" + + "`UIRequiredDeviceCapabilities` section of the Info.plist to prevent" + + "the app from installing. (If the app can't be installed, this error" + + "can't be triggered in a production scenario.)" + + "In apps where AR is an additive feature, use `isSupported` to" + + "determine whether to show UI for launching AR experiences."); + // For details, see https://developer.apple.com/documentation/arkit + } + + // Start the view's AR session. + var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; + this.sceneView.Session.Run (configuration); + + // Set a delegate to track the number of plane anchors for providing UI feedback. + this.sceneView.Session.Delegate = this; + this.sceneView.DebugOptions = ARSCNDebugOptions.ShowFeaturePoints; + + // Prevent the screen from being dimmed after a while as users will likely + // have long periods of interaction without touching the screen or buttons. + UIApplication.SharedApplication.IdleTimerDisabled = true; + } + + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + + // Pause the view's AR session. + this.sceneView.Session.Pause (); + } + + #region IARSCNViewDelegate + + [Export ("renderer:didAddNode:forAnchor:")] + public void DidAddNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + { + if (!string.IsNullOrEmpty (anchor.Name) && + anchor.Name.StartsWith ("panda", StringComparison.InvariantCulture)) { + node.AddChildNode (this.LoadRedPandaModel ()); + } + } + + #endregion + + #region IARSessionDelegate + + [Export ("session:cameraDidChangeTrackingState:")] + public void CameraDidChangeTrackingState (ARSession session, ARCamera camera) + { + this.UpdateSessionInfoLabel (session.CurrentFrame, camera.TrackingState, camera.TrackingStateReason); + } + + [Export ("session:didUpdateFrame:")] + public void DidUpdateFrame (ARSession session, ARFrame frame) + { + switch (frame.WorldMappingStatus) { + case ARWorldMappingStatus.NotAvailable: + case ARWorldMappingStatus.Limited: + this.sendMapButton.Enabled = false; + break; + + case ARWorldMappingStatus.Extending: + this.sendMapButton.Enabled = this.multipeerSession.ConnectedPeers.Any (); + break; + + case ARWorldMappingStatus.Mapped: + this.sendMapButton.Enabled = this.multipeerSession.ConnectedPeers.Any (); + break; + } + + this.mappingStatusLabel.Text = frame.WorldMappingStatus.GetDescription (); + this.UpdateSessionInfoLabel (frame, frame.Camera.TrackingState, frame.Camera.TrackingStateReason); + + frame?.Dispose (); + } + + #endregion + + #region ARSessionObserver + + [Export ("sessionWasInterrupted:")] + public void WasInterrupted (ARSession session) + { + // Inform the user that the session has been interrupted, for example, by presenting an overlay. + this.sessionInfoLabel.Text = "Session was interrupted"; + } + + [Export ("sessionInterruptionEnded:")] + public void InterruptionEnded (ARSession session) + { + // Reset tracking and/or remove existing anchors if consistent tracking is required. + this.sessionInfoLabel.Text = "Session interruption ended"; + } + + [Export ("session:didFailWithError:")] + public void DidFail (ARSession session, NSError error) + { + // Present an error message to the user. + this.sessionInfoLabel.Text = $"Session failed: {error.LocalizedDescription}"; + this.resetTracking (null); + } + + [Export ("sessionShouldAttemptRelocalization:")] + public bool ShouldAttemptRelocalization (ARSession session) + { + return true; + } + + #endregion + + #region Multiuser shared session + + partial void handleSceneTap (UITapGestureRecognizer sender) + { + // Hit test to find a place for a virtual object. + var types = ARHitTestResultType.ExistingPlaneUsingGeometry | ARHitTestResultType.EstimatedHorizontalPlane; + var hitTestResult = this.sceneView.HitTest (sender.LocationInView (this.sceneView), types).FirstOrDefault (); + if (hitTestResult != null) { + // Place an anchor for a virtual character. The model appears in renderer(_:didAdd:for:). + var anchor = new ARAnchor ("panda", hitTestResult.WorldTransform); + this.sceneView.Session.AddAnchor (anchor); + + // Send the anchor info to peers, so they can place the same content. + var data = NSKeyedArchiver.ArchivedDataWithRootObject (anchor, true, out NSError error); + if (error != null) { + throw new Exception ("can't encode anchor"); + } + + this.multipeerSession.SendToAllPeers (data); + } + } + + // GetWorldMap + partial void shareSession (RoundedButton sender) + { + this.sceneView.Session.GetCurrentWorldMap ((worldMap, error) => { + if (worldMap != null) { + var data = NSKeyedArchiver.ArchivedDataWithRootObject (worldMap, true, out NSError archivError); + if (archivError != null) { + throw new Exception ("can't encode map"); + } + + this.multipeerSession.SendToAllPeers (data); + } else if (error != null) { + Console.WriteLine ($"Error: {error.LocalizedDescription}"); + } + }); + } + + private MCPeerID mapProvider; + + private void ReceivedData (NSData data, MCPeerID peer) + { + if (NSKeyedUnarchiver.GetUnarchivedObject (typeof (ARWorldMap), data, out NSError error) is ARWorldMap worldMap) { + // Run the session with the received world map. + var configuration = new ARWorldTrackingConfiguration (); + configuration.PlaneDetection = ARPlaneDetection.Horizontal; + configuration.InitialWorldMap = worldMap; + this.sceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + + // Remember who provided the map for showing UI feedback. + this.mapProvider = peer; + } else if (NSKeyedUnarchiver.GetUnarchivedObject (typeof (ARAnchor), data, out NSError anchorError) is ARAnchor anchor) { + // Add anchor to the session, ARSCNView delegate adds visible content. + this.sceneView.Session.AddAnchor (anchor); + } else { + Console.WriteLine ($"Unknown data was recieved from {peer}"); + } + } + + #endregion + + #region AR session management + + private void UpdateSessionInfoLabel (ARFrame frame, ARTrackingState trackingState, ARTrackingStateReason trackingStateReason) + { + // Update the UI to provide feedback on the state of the AR experience. + string message = null; + + switch (trackingState) { + case ARTrackingState.Normal: + if (!frame.Anchors.Any () && !this.multipeerSession.ConnectedPeers.Any ()) { + // No planes detected; provide instructions for this app's AR interactions. + message = "Move around to map the environment, or wait to join a shared session."; + } else if (this.multipeerSession.ConnectedPeers.Any () && this.mapProvider == null) { + var peerNames = this.multipeerSession.ConnectedPeers.Select (peer => peer.DisplayName); + message = $"Connected with {string.Join (", ", peerNames)}."; + } + break; + + case ARTrackingState.NotAvailable: + message = "Tracking unavailable."; + break; + + case ARTrackingState.Limited: + switch (trackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: + message = "Tracking limited - Move the device more slowly."; + break; + case ARTrackingStateReason.InsufficientFeatures: + message = "Tracking limited - Point the device at an area with visible surface detail, or improve lighting conditions."; + break; + + case ARTrackingStateReason.Initializing: + if (this.mapProvider != null) { + message = $"Received map from {this.mapProvider.DisplayName}."; + } else { + message = "Initializing AR session."; + } + break; + + case ARTrackingStateReason.Relocalizing: + + if (this.mapProvider != null) { + message = $"Received map from {this.mapProvider.DisplayName}."; + } else { + message = "Resuming session — move to where you were when the session was interrupted."; + } + break; + + default: + break; + } + + break; + + default: + // No feedback needed when tracking is normal and planes are visible. + // (Nor when in unreachable limited-tracking states.) + message = ""; + break; + } + + this.sessionInfoLabel.Text = message; + this.sessionInfoView.Hidden = string.IsNullOrEmpty (message); + } + + partial void resetTracking (UIButton sender) + { + var configuration = new ARWorldTrackingConfiguration { PlaneDetection = ARPlaneDetection.Horizontal }; + this.sceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors); + } + + #endregion + + #region AR session management + + private SCNNode LoadRedPandaModel () + { + var sceneURL = NSBundle.MainBundle.GetUrlForResource ("max", "scn", "art.scnassets"); + var referenceNode = SCNReferenceNode.CreateFromUrl (sceneURL); + referenceNode.Load (); + + return referenceNode; + } + + #endregion + } +} diff --git a/ios12/BreakfastFinder/AppDelegate.cs b/ios12/BreakfastFinder/AppDelegate.cs index 184609672..393b466e3 100644 --- a/ios12/BreakfastFinder/AppDelegate.cs +++ b/ios12/BreakfastFinder/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace BreakfastFinder -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace BreakfastFinder { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios12/BreakfastFinder/Main.cs b/ios12/BreakfastFinder/Main.cs index 8cf9df91b..dd5e0b86f 100644 --- a/ios12/BreakfastFinder/Main.cs +++ b/ios12/BreakfastFinder/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace BreakfastFinder -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace BreakfastFinder { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios12/BreakfastFinder/ObjectDetector.cs b/ios12/BreakfastFinder/ObjectDetector.cs index ad63910a2..36516512b 100644 --- a/ios12/BreakfastFinder/ObjectDetector.cs +++ b/ios12/BreakfastFinder/ObjectDetector.cs @@ -16,8 +16,7 @@ namespace BreakfastFinder { /// <summary> /// Model Prediction Input Type /// </summary> - public class ObjectDetectorInput : NSObject, IMLFeatureProvider - { + public class ObjectDetectorInput : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("image"), new NSString ("iouThreshold"), new NSString ("confidenceThreshold") ); @@ -94,8 +93,7 @@ public ObjectDetectorInput (CVPixelBuffer image, double iouThreshold, double con /// <summary> /// Model Prediction Output Type /// </summary> - public class ObjectDetectorOutput : NSObject, IMLFeatureProvider - { + public class ObjectDetectorOutput : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("confidence"), new NSString ("coordinates") ); @@ -163,8 +161,7 @@ public ObjectDetectorOutput (MLMultiArray confidence, MLMultiArray coordinates) /// <summary> /// Class for model loading and prediction /// </summary> - public class ObjectDetector : NSObject - { + public class ObjectDetector : NSObject { public readonly MLModel model; public ObjectDetector () diff --git a/ios12/BreakfastFinder/ViewController.cs b/ios12/BreakfastFinder/ViewController.cs index 6c752f3a1..0b1b41ed3 100644 --- a/ios12/BreakfastFinder/ViewController.cs +++ b/ios12/BreakfastFinder/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using AVFoundation; using Foundation; @@ -10,146 +10,132 @@ using CoreVideo; using ImageIO; -namespace BreakfastFinder -{ - [Register("ViewController")] - public class ViewController : UIViewController, IAVCaptureVideoDataOutputSampleBufferDelegate - { - public ViewController(IntPtr handle) : base(handle) { } - - protected CGSize bufferSize = CGSize.Empty; - protected CALayer rootLayer = null; - - public virtual UIView previewView { get; } - AVCaptureSession session = new AVCaptureSession(); - AVCaptureVideoPreviewLayer previewLayer = null; - AVCaptureVideoDataOutput videoDataOutput = new AVCaptureVideoDataOutput(); - - DispatchQueue videoDataOutputQueue = new DispatchQueue("videoDataOutputQueue"); - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - try - { - SetupAVCapture(); - } - catch - { - TeardownAVCapture(); - } - } - - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - } - - protected virtual void SetupAVCapture() - { - AVCaptureDeviceInput deviceInput; - - // Select a video device, make an input - var videoDevice = AVCaptureDeviceDiscoverySession.Create( - new AVCaptureDeviceType[] { AVCaptureDeviceType.BuiltInWideAngleCamera }, - AVMediaType.Video, - AVCaptureDevicePosition.Back - ).Devices.FirstOrDefault(); - - deviceInput = new AVCaptureDeviceInput(videoDevice, out NSError error); - if (error != null) - { - Console.WriteLine($"Could not create video device input: {error.LocalizedDescription}"); - return; - } - - session.BeginConfiguration(); - session.SessionPreset = AVCaptureSession.Preset640x480; // Model image size is smaller - - // Add a video input - if (!session.CanAddInput(deviceInput)) - { - Console.WriteLine("Could not add video device input to the session"); - session.CommitConfiguration(); - return; - } - session.AddInput(deviceInput); - - if (session.CanAddOutput(videoDataOutput)) - { - session.AddOutput(videoDataOutput); - // Add a video data ouptut - videoDataOutput.AlwaysDiscardsLateVideoFrames = true; - videoDataOutput.WeakVideoSettings = new NSDictionary(CVPixelBuffer.PixelFormatTypeKey, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); - videoDataOutput.SetSampleBufferDelegateQueue(this, videoDataOutputQueue); - } - else - { - Console.WriteLine("Could not add video data output to the session"); - session.CommitConfiguration(); - return; - } - - var captureConnection = videoDataOutput.ConnectionFromMediaType(AVMediaType.Video); - // Always process the frames - captureConnection.Enabled = true; - videoDevice.LockForConfiguration(out NSError error2); - if (error2 == null) - { - var formatDescription = videoDevice.ActiveFormat.FormatDescription as CMVideoFormatDescription; - CMVideoDimensions dimensions = formatDescription.Dimensions; - bufferSize.Width = dimensions.Width; - bufferSize.Height = dimensions.Height; - videoDevice.UnlockForConfiguration(); - } - else - { - Console.WriteLine($"{error2.LocalizedDescription}"); - } - session.CommitConfiguration(); - previewLayer = AVCaptureVideoPreviewLayer.FromSession(session); - previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; - rootLayer = previewView.Layer; - previewLayer.Frame = rootLayer.Bounds; - rootLayer.AddSublayer(previewLayer); - } - - protected void StartCaptureSession() - { - session.StartRunning(); - } - - void TeardownAVCapture() - { - previewLayer.RemoveFromSuperLayer(); - previewLayer = null; - } - - protected CGImagePropertyOrientation ExifOrientationFromDeviceOrientation() - { - UIDeviceOrientation curDeviceOrientation = UIDevice.CurrentDevice.Orientation; - CGImagePropertyOrientation exifOrientation; - - switch (curDeviceOrientation) - { - case UIDeviceOrientation.PortraitUpsideDown: - exifOrientation = CGImagePropertyOrientation.Left; - break; - case UIDeviceOrientation.LandscapeLeft: - exifOrientation = CGImagePropertyOrientation.UpMirrored; - break; - case UIDeviceOrientation.LandscapeRight: - exifOrientation = CGImagePropertyOrientation.Down; - break; - case UIDeviceOrientation.Portrait: - exifOrientation = CGImagePropertyOrientation.Up; - break; - default: - exifOrientation = CGImagePropertyOrientation.Left; - break; - } - - return exifOrientation; - } - } +namespace BreakfastFinder { + [Register ("ViewController")] + public class ViewController : UIViewController, IAVCaptureVideoDataOutputSampleBufferDelegate { + public ViewController (IntPtr handle) : base (handle) { } + + protected CGSize bufferSize = CGSize.Empty; + protected CALayer rootLayer = null; + + public virtual UIView previewView { get; } + AVCaptureSession session = new AVCaptureSession (); + AVCaptureVideoPreviewLayer previewLayer = null; + AVCaptureVideoDataOutput videoDataOutput = new AVCaptureVideoDataOutput (); + + DispatchQueue videoDataOutputQueue = new DispatchQueue ("videoDataOutputQueue"); + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + try { + SetupAVCapture (); + } catch { + TeardownAVCapture (); + } + } + + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + } + + protected virtual void SetupAVCapture () + { + AVCaptureDeviceInput deviceInput; + + // Select a video device, make an input + var videoDevice = AVCaptureDeviceDiscoverySession.Create ( + new AVCaptureDeviceType [] { AVCaptureDeviceType.BuiltInWideAngleCamera }, + AVMediaType.Video, + AVCaptureDevicePosition.Back + ).Devices.FirstOrDefault (); + + deviceInput = new AVCaptureDeviceInput (videoDevice, out NSError error); + if (error != null) { + Console.WriteLine ($"Could not create video device input: {error.LocalizedDescription}"); + return; + } + + session.BeginConfiguration (); + session.SessionPreset = AVCaptureSession.Preset640x480; // Model image size is smaller + + // Add a video input + if (!session.CanAddInput (deviceInput)) { + Console.WriteLine ("Could not add video device input to the session"); + session.CommitConfiguration (); + return; + } + session.AddInput (deviceInput); + + if (session.CanAddOutput (videoDataOutput)) { + session.AddOutput (videoDataOutput); + // Add a video data ouptut + videoDataOutput.AlwaysDiscardsLateVideoFrames = true; + videoDataOutput.WeakVideoSettings = new NSDictionary (CVPixelBuffer.PixelFormatTypeKey, CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange); + videoDataOutput.SetSampleBufferDelegateQueue (this, videoDataOutputQueue); + } else { + Console.WriteLine ("Could not add video data output to the session"); + session.CommitConfiguration (); + return; + } + + var captureConnection = videoDataOutput.ConnectionFromMediaType (AVMediaType.Video); + // Always process the frames + captureConnection.Enabled = true; + videoDevice.LockForConfiguration (out NSError error2); + if (error2 == null) { + var formatDescription = videoDevice.ActiveFormat.FormatDescription as CMVideoFormatDescription; + CMVideoDimensions dimensions = formatDescription.Dimensions; + bufferSize.Width = dimensions.Width; + bufferSize.Height = dimensions.Height; + videoDevice.UnlockForConfiguration (); + } else { + Console.WriteLine ($"{error2.LocalizedDescription}"); + } + session.CommitConfiguration (); + previewLayer = AVCaptureVideoPreviewLayer.FromSession (session); + previewLayer.VideoGravity = AVLayerVideoGravity.ResizeAspectFill; + rootLayer = previewView.Layer; + previewLayer.Frame = rootLayer.Bounds; + rootLayer.AddSublayer (previewLayer); + } + + protected void StartCaptureSession () + { + session.StartRunning (); + } + + void TeardownAVCapture () + { + previewLayer.RemoveFromSuperLayer (); + previewLayer = null; + } + + protected CGImagePropertyOrientation ExifOrientationFromDeviceOrientation () + { + UIDeviceOrientation curDeviceOrientation = UIDevice.CurrentDevice.Orientation; + CGImagePropertyOrientation exifOrientation; + + switch (curDeviceOrientation) { + case UIDeviceOrientation.PortraitUpsideDown: + exifOrientation = CGImagePropertyOrientation.Left; + break; + case UIDeviceOrientation.LandscapeLeft: + exifOrientation = CGImagePropertyOrientation.UpMirrored; + break; + case UIDeviceOrientation.LandscapeRight: + exifOrientation = CGImagePropertyOrientation.Down; + break; + case UIDeviceOrientation.Portrait: + exifOrientation = CGImagePropertyOrientation.Up; + break; + default: + exifOrientation = CGImagePropertyOrientation.Left; + break; + } + + return exifOrientation; + } + } } diff --git a/ios12/BreakfastFinder/VisionObjectRecognitionViewController.cs b/ios12/BreakfastFinder/VisionObjectRecognitionViewController.cs index 549df4cf0..114ce4424 100644 --- a/ios12/BreakfastFinder/VisionObjectRecognitionViewController.cs +++ b/ios12/BreakfastFinder/VisionObjectRecognitionViewController.cs @@ -1,234 +1,213 @@ -using Foundation; -using System; -using UIKit; -using CoreAnimation; -using Vision; -using CoreFoundation; -using System.Linq; +using Foundation; +using System; +using UIKit; +using CoreAnimation; +using Vision; +using CoreFoundation; +using System.Linq; using AVFoundation; using CoreMedia; -using CoreVideo; -using CoreGraphics; -using CoreText; - -namespace BreakfastFinder -{ - public partial class VisionObjectRecognitionViewController : ViewController - { - public VisionObjectRecognitionViewController (IntPtr handle) : base (handle) { } - public override UIView previewView { get => PreviewView; } - NSDictionary options = new NSDictionary(); - - CALayer detectionOverlay = null; - - // Vision parts - VNRequest[] requests; - - NSError SetupVision() - { - // Setup Vision parts - var visionModel = VNCoreMLModel.FromMLModel( - new ObjectDetector().model, - out NSError error - ); - - if (error != null) - { - Console.WriteLine($"Model loading went wrong: {error.LocalizedDescription}"); - return error; - } - - var objectRecognition = new VNCoreMLRequest(visionModel, (VNRequest request, NSError requestError) => - { - if (requestError == null) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var results = request.GetResults<VNObservation>(); - if (results != null) - { - this.DrawVisionRequestResults(results); - } - }); - } - else - { - Console.WriteLine($"{error.LocalizedDescription}"); - } - }); - - this.requests = new VNRequest[] { objectRecognition }; - - return error; - } - - void DrawVisionRequestResults(VNObservation[] results) - { - CATransaction.Begin(); - CATransaction.SetValueForKey(NSNumber.FromBoolean(true), CATransaction.DisableActionsKey); - detectionOverlay.Sublayers = null; // remove all the old recognized objects - results.OfType<VNRecognizedObjectObservation>() - .ToList() - .ForEach((VNRecognizedObjectObservation objectObservation) => - { - // Select only the label with the highest confidence - VNClassificationObservation topLabelObservation = objectObservation.Labels[0]; - CGRect objectBounds = VNUtils.GetImageRect( - objectObservation.BoundingBox, - (nuint)bufferSize.Width, - (nuint)bufferSize.Height - ); - - - CALayer shapeLayer = this.CreateRoundedRectLayerWithBounds(objectBounds); - CALayer textLayer = this.CreateTextSubLayerInBounds( - objectBounds, - topLabelObservation.Identifier, - topLabelObservation.Confidence - ); - - shapeLayer.AddSublayer(textLayer); - detectionOverlay.AddSublayer(shapeLayer); - }); - this.UpdateLayerGeometry(); - CATransaction.Commit(); - } - - [Export("captureOutput:didOutputSampleBuffer:fromConnection:")] - public virtual void DidOutputSampleBuffer(AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) - { - CVPixelBuffer pixelBuffer = null; - VNImageRequestHandler imageRequestHandler = null; - - try - { - pixelBuffer = sampleBuffer.GetImageBuffer() as CVPixelBuffer; - if (pixelBuffer == null) - { - return; - } - - var exifOrientation = ExifOrientationFromDeviceOrientation(); - - imageRequestHandler = new VNImageRequestHandler(pixelBuffer, exifOrientation, options); - imageRequestHandler.Perform(this.requests, out NSError error); - if (error != null) - { - Console.WriteLine($"{error.LocalizedDescription}"); - } - } - catch (Exception x) - { - Console.WriteLine(x.Message); - } - finally - { - if (sampleBuffer != null) - { - sampleBuffer.Dispose(); - } - - if (pixelBuffer != null) - { - pixelBuffer.Dispose(); - } - - if (imageRequestHandler != null) - { - imageRequestHandler.Dispose(); - } - } - } - - override protected void SetupAVCapture() - { - base.SetupAVCapture(); - - // setup Vision parts - SetupLayers(); - UpdateLayerGeometry(); - SetupVision(); - - // start the capture - StartCaptureSession(); - } - - void SetupLayers() - { - detectionOverlay = new CALayer(); // container layer that has all the renderings of the observations - detectionOverlay.Name = "DetectionOverlay"; - detectionOverlay.Bounds = new CGRect(0.0, 0.0, bufferSize.Width, bufferSize.Height); - detectionOverlay.Position = new CGPoint(rootLayer.Bounds.GetMidX(), rootLayer.Bounds.GetMidY()); - rootLayer.AddSublayer(detectionOverlay); - } - - void UpdateLayerGeometry() - { - // let bounds = rootLayer.bounds - var bounds = rootLayer.Bounds; - nfloat scale; - - nfloat xScale = bounds.Size.Width / bufferSize.Height; - nfloat yScale = bounds.Size.Height / bufferSize.Width; - scale = NMath.Max(xScale, yScale); - - if (nfloat.IsInfinity(scale)) - { - scale = 1.0f; - } - CATransaction.Begin(); - CATransaction.SetValueForKey(NSNumber.FromBoolean(true), CATransaction.DisableActionsKey); - - // rotate the layer into screen orientation and scale and mirror - var affineTransform = CGAffineTransform.MakeScale(scale, -1 * scale); - affineTransform.Rotate((nfloat)Math.PI / 2.0f); - detectionOverlay.AffineTransform = affineTransform; - - // center the layer - detectionOverlay.Position = new CGPoint(bounds.GetMidX(), bounds.GetMidY()); - - CATransaction.Commit(); - } - - CATextLayer CreateTextSubLayerInBounds(CGRect bounds, string Identifier, float confidence) - { - var textLayer = new CATextLayer(); - textLayer.Name = "Object Label"; - var formattedString = new NSMutableAttributedString($"{Identifier}\nConfidence: {confidence:F2}"); - var largeFont = UIFont.FromName("Helvetica", 24.0f); - formattedString.AddAttributes( - new UIStringAttributes() { Font = largeFont }, - new NSRange(0, Identifier.Length) - ); - textLayer.AttributedString = formattedString; - textLayer.Bounds = new CGRect(0, 0, bounds.Size.Height - 10, bounds.Size.Width - 10); - textLayer.Position = new CGPoint(bounds.GetMidX(), bounds.GetMidY()); - textLayer.ShadowOpacity = 0.7f; - textLayer.ShadowOffset = new CGSize(2, 2); - textLayer.ForegroundColor = new CGColor( - CGColorSpace.CreateDeviceRGB(), - new nfloat[] { 0.0f, 0.0f, 0.0f, 1.0f } - ); - textLayer.ContentsScale = 2.0f; // retina rendering - // rotate the layer into screen orientation and scale and mirror - var affineTransform = CGAffineTransform.MakeScale(1.0f, -1.0f); - affineTransform.Rotate((nfloat)Math.PI / 2.0f); - textLayer.AffineTransform = affineTransform; - return textLayer; - } - - CALayer CreateRoundedRectLayerWithBounds(CGRect bounds) - { - var shapeLayer = new CALayer(); - shapeLayer.Bounds = bounds; - shapeLayer.Position = new CGPoint(bounds.GetMidX(), bounds.GetMidY()); - shapeLayer.Name = "Found Object"; - shapeLayer.BackgroundColor = new CGColor( - CGColorSpace.CreateDeviceRGB(), - new nfloat[] { 1.0f, 1.0f, 0.2f, 0.4f } - ); - shapeLayer.CornerRadius = 7; - return shapeLayer; - } - } -} \ No newline at end of file +using CoreVideo; +using CoreGraphics; +using CoreText; + +namespace BreakfastFinder { + public partial class VisionObjectRecognitionViewController : ViewController { + public VisionObjectRecognitionViewController (IntPtr handle) : base (handle) { } + public override UIView previewView { get => PreviewView; } + NSDictionary options = new NSDictionary (); + + CALayer detectionOverlay = null; + + // Vision parts + VNRequest [] requests; + + NSError SetupVision () + { + // Setup Vision parts + var visionModel = VNCoreMLModel.FromMLModel ( + new ObjectDetector ().model, + out NSError error + ); + + if (error != null) { + Console.WriteLine ($"Model loading went wrong: {error.LocalizedDescription}"); + return error; + } + + var objectRecognition = new VNCoreMLRequest (visionModel, (VNRequest request, NSError requestError) => { + if (requestError == null) { + DispatchQueue.MainQueue.DispatchAsync (() => { + var results = request.GetResults<VNObservation> (); + if (results != null) { + this.DrawVisionRequestResults (results); + } + }); + } else { + Console.WriteLine ($"{error.LocalizedDescription}"); + } + }); + + this.requests = new VNRequest [] { objectRecognition }; + + return error; + } + + void DrawVisionRequestResults (VNObservation [] results) + { + CATransaction.Begin (); + CATransaction.SetValueForKey (NSNumber.FromBoolean (true), CATransaction.DisableActionsKey); + detectionOverlay.Sublayers = null; // remove all the old recognized objects + results.OfType<VNRecognizedObjectObservation> () + .ToList () + .ForEach ((VNRecognizedObjectObservation objectObservation) => { + // Select only the label with the highest confidence + VNClassificationObservation topLabelObservation = objectObservation.Labels [0]; + CGRect objectBounds = VNUtils.GetImageRect ( + objectObservation.BoundingBox, + (nuint) bufferSize.Width, + (nuint) bufferSize.Height + ); + + + CALayer shapeLayer = this.CreateRoundedRectLayerWithBounds (objectBounds); + CALayer textLayer = this.CreateTextSubLayerInBounds ( + objectBounds, + topLabelObservation.Identifier, + topLabelObservation.Confidence + ); + + shapeLayer.AddSublayer (textLayer); + detectionOverlay.AddSublayer (shapeLayer); + }); + this.UpdateLayerGeometry (); + CATransaction.Commit (); + } + + [Export ("captureOutput:didOutputSampleBuffer:fromConnection:")] + public virtual void DidOutputSampleBuffer (AVCaptureOutput captureOutput, CMSampleBuffer sampleBuffer, AVCaptureConnection connection) + { + CVPixelBuffer pixelBuffer = null; + VNImageRequestHandler imageRequestHandler = null; + + try { + pixelBuffer = sampleBuffer.GetImageBuffer () as CVPixelBuffer; + if (pixelBuffer == null) { + return; + } + + var exifOrientation = ExifOrientationFromDeviceOrientation (); + + imageRequestHandler = new VNImageRequestHandler (pixelBuffer, exifOrientation, options); + imageRequestHandler.Perform (this.requests, out NSError error); + if (error != null) { + Console.WriteLine ($"{error.LocalizedDescription}"); + } + } catch (Exception x) { + Console.WriteLine (x.Message); + } finally { + if (sampleBuffer != null) { + sampleBuffer.Dispose (); + } + + if (pixelBuffer != null) { + pixelBuffer.Dispose (); + } + + if (imageRequestHandler != null) { + imageRequestHandler.Dispose (); + } + } + } + + override protected void SetupAVCapture () + { + base.SetupAVCapture (); + + // setup Vision parts + SetupLayers (); + UpdateLayerGeometry (); + SetupVision (); + + // start the capture + StartCaptureSession (); + } + + void SetupLayers () + { + detectionOverlay = new CALayer (); // container layer that has all the renderings of the observations + detectionOverlay.Name = "DetectionOverlay"; + detectionOverlay.Bounds = new CGRect (0.0, 0.0, bufferSize.Width, bufferSize.Height); + detectionOverlay.Position = new CGPoint (rootLayer.Bounds.GetMidX (), rootLayer.Bounds.GetMidY ()); + rootLayer.AddSublayer (detectionOverlay); + } + + void UpdateLayerGeometry () + { + // let bounds = rootLayer.bounds + var bounds = rootLayer.Bounds; + nfloat scale; + + nfloat xScale = bounds.Size.Width / bufferSize.Height; + nfloat yScale = bounds.Size.Height / bufferSize.Width; + scale = NMath.Max (xScale, yScale); + + if (nfloat.IsInfinity (scale)) { + scale = 1.0f; + } + CATransaction.Begin (); + CATransaction.SetValueForKey (NSNumber.FromBoolean (true), CATransaction.DisableActionsKey); + + // rotate the layer into screen orientation and scale and mirror + var affineTransform = CGAffineTransform.MakeScale (scale, -1 * scale); + affineTransform.Rotate ((nfloat) Math.PI / 2.0f); + detectionOverlay.AffineTransform = affineTransform; + + // center the layer + detectionOverlay.Position = new CGPoint (bounds.GetMidX (), bounds.GetMidY ()); + + CATransaction.Commit (); + } + + CATextLayer CreateTextSubLayerInBounds (CGRect bounds, string Identifier, float confidence) + { + var textLayer = new CATextLayer (); + textLayer.Name = "Object Label"; + var formattedString = new NSMutableAttributedString ($"{Identifier}\nConfidence: {confidence:F2}"); + var largeFont = UIFont.FromName ("Helvetica", 24.0f); + formattedString.AddAttributes ( + new UIStringAttributes () { Font = largeFont }, + new NSRange (0, Identifier.Length) + ); + textLayer.AttributedString = formattedString; + textLayer.Bounds = new CGRect (0, 0, bounds.Size.Height - 10, bounds.Size.Width - 10); + textLayer.Position = new CGPoint (bounds.GetMidX (), bounds.GetMidY ()); + textLayer.ShadowOpacity = 0.7f; + textLayer.ShadowOffset = new CGSize (2, 2); + textLayer.ForegroundColor = new CGColor ( + CGColorSpace.CreateDeviceRGB (), + new nfloat [] { 0.0f, 0.0f, 0.0f, 1.0f } + ); + textLayer.ContentsScale = 2.0f; // retina rendering + // rotate the layer into screen orientation and scale and mirror + var affineTransform = CGAffineTransform.MakeScale (1.0f, -1.0f); + affineTransform.Rotate ((nfloat) Math.PI / 2.0f); + textLayer.AffineTransform = affineTransform; + return textLayer; + } + + CALayer CreateRoundedRectLayerWithBounds (CGRect bounds) + { + var shapeLayer = new CALayer (); + shapeLayer.Bounds = bounds; + shapeLayer.Position = new CGPoint (bounds.GetMidX (), bounds.GetMidY ()); + shapeLayer.Name = "Found Object"; + shapeLayer.BackgroundColor = new CGColor ( + CGColorSpace.CreateDeviceRGB (), + new nfloat [] { 1.0f, 1.0f, 0.2f, 0.4f } + ); + shapeLayer.CornerRadius = 7; + return shapeLayer; + } + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/AppDelegate.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/AppDelegate.cs index d741abc07..18a57e4e6 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/AppDelegate.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/AppDelegate.cs @@ -1,22 +1,20 @@ - -namespace ExceptionalAccessibility -{ - using Foundation; - using UIKit; - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace ExceptionalAccessibility { + using Foundation; + using UIKit; - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - return true; - } - } -} \ No newline at end of file + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCarouselContainerView.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCarouselContainerView.cs index 5e2efeaa6..582a49918 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCarouselContainerView.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCarouselContainerView.cs @@ -1,75 +1,63 @@ -namespace ExceptionalAccessibility -{ - using Foundation; - using System; - using System.Collections.Generic; - using UIKit; - - /// <summary> - /// The carousel container is a container view for the carousel collection view and the favorite and gallery button. - /// We subclass it so that we can override its `accessibilityElements` to exclude the collection view - /// and use our custom element instead, and so that we can add and remove the gallery buton as - /// an accessibility element as it appears and disappears. - /// </summary> - public partial class DogCarouselContainerView : UIView, IUIAccessibilityContainer - { - private CarouselAccessibilityElement carouselAccessibilityElement; - - private Dog currentDog; - - public DogCarouselContainerView(IntPtr handle) : base(handle) { } - - public List<Dog> Dogs { get; set; } - - public Dog CurrentDog - { - get => this.currentDog; - set - { - this.currentDog = value; - this.SetAccessibilityElements(NSArray.FromNSObjects(this.GetAccessibilityElements()?.ToArray())); - - if (this.currentDog != null && this.carouselAccessibilityElement != null) - { - this.carouselAccessibilityElement.CurrentDog = this.currentDog; - } - } - } - - #region Accessibility - - private List<NSObject> GetAccessibilityElements() - { - List<NSObject> result = null; - if (this.currentDog != null) - { - CarouselAccessibilityElement accessibilityElement; - if (this.carouselAccessibilityElement != null) - { - accessibilityElement = this.carouselAccessibilityElement; - } - else - { - accessibilityElement = new CarouselAccessibilityElement(this, this.currentDog); - accessibilityElement.AccessibilityFrameInContainerSpace = dogCollectionView.Frame; - this.carouselAccessibilityElement = accessibilityElement; - } - - // Only show the gallery button if we have multiple images. - if (this.currentDog.Images.Count > 1) - { - result = new List<NSObject> { this.carouselAccessibilityElement, this.galleryButton }; - } - else - { - result = new List<NSObject> { this.carouselAccessibilityElement }; - } - } - - return result; - } - - #endregion - } -} \ No newline at end of file +namespace ExceptionalAccessibility { + using Foundation; + using System; + using System.Collections.Generic; + using UIKit; + + /// <summary> + /// The carousel container is a container view for the carousel collection view and the favorite and gallery button. + /// We subclass it so that we can override its `accessibilityElements` to exclude the collection view + /// and use our custom element instead, and so that we can add and remove the gallery buton as + /// an accessibility element as it appears and disappears. + /// </summary> + public partial class DogCarouselContainerView : UIView, IUIAccessibilityContainer { + private CarouselAccessibilityElement carouselAccessibilityElement; + + private Dog currentDog; + + public DogCarouselContainerView (IntPtr handle) : base (handle) { } + + public List<Dog> Dogs { get; set; } + + public Dog CurrentDog { + get => this.currentDog; + set { + this.currentDog = value; + this.SetAccessibilityElements (NSArray.FromNSObjects (this.GetAccessibilityElements ()?.ToArray ())); + + if (this.currentDog != null && this.carouselAccessibilityElement != null) { + this.carouselAccessibilityElement.CurrentDog = this.currentDog; + } + } + } + + #region Accessibility + + private List<NSObject> GetAccessibilityElements () + { + List<NSObject> result = null; + if (this.currentDog != null) { + CarouselAccessibilityElement accessibilityElement; + if (this.carouselAccessibilityElement != null) { + accessibilityElement = this.carouselAccessibilityElement; + } else { + accessibilityElement = new CarouselAccessibilityElement (this, this.currentDog); + accessibilityElement.AccessibilityFrameInContainerSpace = dogCollectionView.Frame; + this.carouselAccessibilityElement = accessibilityElement; + } + + // Only show the gallery button if we have multiple images. + if (this.currentDog.Images.Count > 1) { + result = new List<NSObject> { this.carouselAccessibilityElement, this.galleryButton }; + } else { + result = new List<NSObject> { this.carouselAccessibilityElement }; + } + } + + return result; + } + + #endregion + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCollectionViewCell.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCollectionViewCell.cs index dc7c443d0..97cb1195f 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCollectionViewCell.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogCollectionViewCell.cs @@ -1,14 +1,12 @@ -namespace ExceptionalAccessibility -{ - using System; - using UIKit; +namespace ExceptionalAccessibility { + using System; + using UIKit; - /// <summary> - /// Subclass of `UICollectionViewCell`; represents a particular dog in the collection view. - /// </summary> - public partial class DogCollectionViewCell : UICollectionViewCell - { - public DogCollectionViewCell(IntPtr handle) : base(handle) { } - } -} \ No newline at end of file + /// <summary> + /// Subclass of `UICollectionViewCell`; represents a particular dog in the collection view. + /// </summary> + public partial class DogCollectionViewCell : UICollectionViewCell { + public DogCollectionViewCell (IntPtr handle) : base (handle) { } + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogModalView.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogModalView.cs index 6e7fa44ac..6959a40ea 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogModalView.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogModalView.cs @@ -1,46 +1,41 @@ -namespace ExceptionalAccessibility -{ - using System; - using UIKit; +namespace ExceptionalAccessibility { + using System; + using UIKit; - /// <summary> - /// This modal view displays a gallery of images for the dog, and has a dark transparent background so that - /// you can still see the content of the view below it.It is meant to be a full screen modal view, - /// but it creates problems for VoiceOver because it isn't a view controller that is presented modally. - /// Because it's simply a view that's added on top of everything else, and because it has a transparent background so the - /// views behind are still visible, VoiceOver doesn't inherently know that the views behind it should no longer - /// be accessible.So the user can still swipe to access those views behind it while this view is presented. - /// This creates a confusing, bad experience, so we override `accessibilityViewIsModal` to indicate - /// this view and its contents are the only thing on screen VoiceOver should currently care about. - /// </summary> - public partial class DogModalView : UIView - { - public DogModalView(IntPtr handle) : base(handle) { } + /// <summary> + /// This modal view displays a gallery of images for the dog, and has a dark transparent background so that + /// you can still see the content of the view below it.It is meant to be a full screen modal view, + /// but it creates problems for VoiceOver because it isn't a view controller that is presented modally. + /// Because it's simply a view that's added on top of everything else, and because it has a transparent background so the + /// views behind are still visible, VoiceOver doesn't inherently know that the views behind it should no longer + /// be accessible.So the user can still swipe to access those views behind it while this view is presented. + /// This creates a confusing, bad experience, so we override `accessibilityViewIsModal` to indicate + /// this view and its contents are the only thing on screen VoiceOver should currently care about. + /// </summary> + public partial class DogModalView : UIView { + public DogModalView (IntPtr handle) : base (handle) { } - public override bool AccessibilityViewIsModal { get => true; set { /* ignore */ _ = value; } } + public override bool AccessibilityViewIsModal { get => true; set { /* ignore */ _ = value; } } - public override void LayoutSubviews() - { - base.LayoutSubviews(); + public override void LayoutSubviews () + { + base.LayoutSubviews (); - this.closeButton.Layer.CornerRadius = this.closeButton.Bounds.Width / 2f; - this.closeButton.Layer.BorderWidth = 1f; - this.closeButton.Layer.BorderColor = UIColor.LightGray.CGColor; - } + this.closeButton.Layer.CornerRadius = this.closeButton.Bounds.Width / 2f; + this.closeButton.Layer.BorderWidth = 1f; + this.closeButton.Layer.BorderColor = UIColor.LightGray.CGColor; + } - partial void closeButtonTapped(UIButton sender) - { - UIView.AnimateNotify(0.25d, () => - { - this.Alpha = 0f; - }, (bool finished) => - { - if (finished) - { - this.RemoveFromSuperview(); - } - }); - } - } -} \ No newline at end of file + partial void closeButtonTapped (UIButton sender) + { + UIView.AnimateNotify (0.25d, () => { + this.Alpha = 0f; + }, (bool finished) => { + if (finished) { + this.RemoveFromSuperview (); + } + }); + } + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogStatsView.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogStatsView.cs index 6ceed8988..d82df5399 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogStatsView.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Controls/DogStatsView.cs @@ -1,53 +1,48 @@ -namespace ExceptionalAccessibility -{ - using CoreGraphics; - using Foundation; - using System; - using System.Collections.Generic; - using UIKit; - - /// <summary> - /// This view is a collection of labels that house the data for each dog. - /// There are 4 properties that each dog has, so 8 labels in total: a title label for what the data is - /// and then a content label for the value. - /// </summary> - public partial class DogStatsView : UIView, IUIAccessibilityContainer - { - private Dog dog; - - public DogStatsView(IntPtr handle) : base(handle) { } - - public Dog Dog - { - get => this.dog; - set - { - this.dog = value; - if (this.dog != null) - { - this.nameLabel.Text = dog.Name; - this.breedLabel.Text = dog.Breed; - this.ageLabel.Text = $"{dog.Age} years"; - this.weightLabel.Text = $"{dog.Weight} lbs"; - - this.SetAccessibilityElements(NSArray.FromNSObjects(this.GetAccessibilityElements().ToArray())); - } - } - } - - #region Accessibility Logic - - /* +namespace ExceptionalAccessibility { + using CoreGraphics; + using Foundation; + using System; + using System.Collections.Generic; + using UIKit; + + /// <summary> + /// This view is a collection of labels that house the data for each dog. + /// There are 4 properties that each dog has, so 8 labels in total: a title label for what the data is + /// and then a content label for the value. + /// </summary> + public partial class DogStatsView : UIView, IUIAccessibilityContainer { + private Dog dog; + + public DogStatsView (IntPtr handle) : base (handle) { } + + public Dog Dog { + get => this.dog; + set { + this.dog = value; + if (this.dog != null) { + this.nameLabel.Text = dog.Name; + this.breedLabel.Text = dog.Breed; + this.ageLabel.Text = $"{dog.Age} years"; + this.weightLabel.Text = $"{dog.Weight} lbs"; + + this.SetAccessibilityElements (NSArray.FromNSObjects (this.GetAccessibilityElements ().ToArray ())); + } + } + } + + #region Accessibility Logic + + /* VoiceOver relies on `accessibilityElements` returning an array of consistent objects that persist as the user swipes through an app. We therefore have to cache our array of computed `accessibilityElements` so that we don't get into an infinite loop of swiping. We reset this cached array whenever a new dog object is set so that `accessibilityElements` can be recomputed. */ - private List<UIAccessibilityElement> GetAccessibilityElements() - { - /* + private List<UIAccessibilityElement> GetAccessibilityElements () + { + /* We want to create a custom accessibility element that represents a grouping of each title and content label pair so that the VoiceOver user can interact with them as a unified element. This is important because it reduces the amount of times the user has to swipe through the display @@ -55,37 +50,37 @@ This is important because it reduces the amount of times the user has to swipe t the content labels lose the context of what they represent. */ - var elements = new List<UIAccessibilityElement>(); - var nameElement = new UIAccessibilityElement(this); - nameElement.AccessibilityLabel = $"{this.nameTitleLabel.Text}, {this.nameLabel.Text}"; + var elements = new List<UIAccessibilityElement> (); + var nameElement = new UIAccessibilityElement (this); + nameElement.AccessibilityLabel = $"{this.nameTitleLabel.Text}, {this.nameLabel.Text}"; - /* + /* This tells VoiceOver where the object should be onscreen. As the user touches around with their finger, we can determine if an element is below their finger. */ - nameElement.AccessibilityFrameInContainerSpace = CGRect.Union(this.nameTitleLabel.Frame, this.nameLabel.Frame); - elements.Add(nameElement); + nameElement.AccessibilityFrameInContainerSpace = CGRect.Union (this.nameTitleLabel.Frame, this.nameLabel.Frame); + elements.Add (nameElement); - var ageElement = new UIAccessibilityElement(this); - ageElement.AccessibilityLabel = $"{this.ageTitleLabel.Text}, {this.ageLabel.Text}"; - ageElement.AccessibilityFrameInContainerSpace = CGRect.Union(this.ageTitleLabel.Frame, this.ageLabel.Frame); - elements.Add(ageElement); + var ageElement = new UIAccessibilityElement (this); + ageElement.AccessibilityLabel = $"{this.ageTitleLabel.Text}, {this.ageLabel.Text}"; + ageElement.AccessibilityFrameInContainerSpace = CGRect.Union (this.ageTitleLabel.Frame, this.ageLabel.Frame); + elements.Add (ageElement); - var breedElement = new UIAccessibilityElement(this); - breedElement.AccessibilityLabel = $"{this.breedTitleLabel.Text}, {this.breedLabel.Text}"; - breedElement.AccessibilityFrameInContainerSpace = CGRect.Union(this.breedTitleLabel.Frame, this.breedLabel.Frame); - elements.Add(breedElement); + var breedElement = new UIAccessibilityElement (this); + breedElement.AccessibilityLabel = $"{this.breedTitleLabel.Text}, {this.breedLabel.Text}"; + breedElement.AccessibilityFrameInContainerSpace = CGRect.Union (this.breedTitleLabel.Frame, this.breedLabel.Frame); + elements.Add (breedElement); - var weightElement = new UIAccessibilityElement(this); - weightElement.AccessibilityLabel = $"{this.weightTitleLabel.Text}, {this.weightLabel.Text}"; - weightElement.AccessibilityFrameInContainerSpace = CGRect.Union(this.weightTitleLabel.Frame, this.weightLabel.Frame); - elements.Add(weightElement); + var weightElement = new UIAccessibilityElement (this); + weightElement.AccessibilityLabel = $"{this.weightTitleLabel.Text}, {this.weightLabel.Text}"; + weightElement.AccessibilityFrameInContainerSpace = CGRect.Union (this.weightTitleLabel.Frame, this.weightLabel.Frame); + elements.Add (weightElement); - return elements; - } + return elements; + } - #endregion - } -} \ No newline at end of file + #endregion + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/CarouselAccessibilityElement.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/CarouselAccessibilityElement.cs index 3d176f28f..664873738 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/CarouselAccessibilityElement.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/CarouselAccessibilityElement.cs @@ -1,147 +1,134 @@ - -namespace ExceptionalAccessibility -{ - using Foundation; - using UIKit; - - /// <summary> - /// The custom carousel accessibility element is a core part of this sample. - /// It is illustrating a way in which we choose to tweak the accessibility experience in a unique and interesting way. - /// If we leave the collection view as is, then the VoiceOver user has to swipe to the end of the carousel - /// before they can reach either button or the data for the dogs, meaning that they will only ever be able to - /// get to the data for the last dog in the carousel through swiping alone.We instead create this custom element, - /// and make it an adjustable element that responds to `accessibilityIncrement` and `accessibilityDecrement`, - /// so that when a user swipes from it, they swipe immediately to the favorite and gallery buttons, then on to the data, - /// for the specific dog.In some ways, we've transformed the collection view into acting more like a picker. - /// </summary> - public class CarouselAccessibilityElement : UIAccessibilityElement - { - public CarouselAccessibilityElement(NSObject accessibilityContainer, Dog dog) : base(accessibilityContainer) - { - this.CurrentDog = dog; - } - - public Dog CurrentDog { get; set; } - - /// <summary> - /// This indicates to the user what exactly this element is supposed to be. - /// </summary> - public override string AccessibilityLabel - { - get => "Dog Picker"; - set => base.AccessibilityLabel = value; - } - - public override string AccessibilityValue - { - get => this.CurrentDog != null ? this.CurrentDog.Name : base.AccessibilityValue; - set => base.AccessibilityValue = value; - } - - /// <summary> - /// This tells VoiceOver that our element will support the increment and decrement callbacks. - /// </summary> - public override ulong AccessibilityTraits { get => (ulong)UIAccessibilityTrait.Adjustable; set => base.AccessibilityTraits = value; } - - /// <summary> - /// A convenience for forward scrolling in both `accessibilityIncrement` and `accessibilityScroll`. - /// It returns a `Bool` because `accessibilityScroll` needs to know if the scroll was successful. - /// </summary> - private bool AccessibilityScrollForward() - { - var result = false; - - // Initialize the container view which will house the collection view. - if (this.AccessibilityContainer is DogCarouselContainerView containerView) - { - // Store the currently focused dog and the list of all dogs. - if (this.CurrentDog != null && containerView.Dogs != null) - { - // Get the index of the currently focused dog from the list of dogs (if it's a valid index). - var index = containerView.Dogs.IndexOf(this.CurrentDog); - if (index > -1 && index < containerView.Dogs.Count - 1) - { - // Scroll the collection view to the currently focused dog. - containerView.dogCollectionView.ScrollToItem(NSIndexPath.FromRowSection(index + 1, 0), - UICollectionViewScrollPosition.CenteredHorizontally, - true); - - result = true; - } - } - } - - return result; - } - - /// <summary> - /// A convenience for backward scrolling in both `accessibilityIncrement` and `accessibilityScroll`. - /// It returns a `Bool` because `accessibilityScroll` needs to know if the scroll was successful. - /// </summary> - private bool AccessibilityScrollBackward() - { - var result = false; - if (this.AccessibilityContainer is DogCarouselContainerView containerView) - { - if (this.CurrentDog != null && containerView.Dogs != null) - { - var index = containerView.Dogs.IndexOf(this.CurrentDog); - if (index != -1) - { - containerView.dogCollectionView.ScrollToItem(NSIndexPath.FromRowSection(index - 1, 0), - UICollectionViewScrollPosition.CenteredHorizontally, - true); - - result = true; - } - } - } - - return result; - } - - #region Accessibility - - /* + +namespace ExceptionalAccessibility { + using Foundation; + using UIKit; + + /// <summary> + /// The custom carousel accessibility element is a core part of this sample. + /// It is illustrating a way in which we choose to tweak the accessibility experience in a unique and interesting way. + /// If we leave the collection view as is, then the VoiceOver user has to swipe to the end of the carousel + /// before they can reach either button or the data for the dogs, meaning that they will only ever be able to + /// get to the data for the last dog in the carousel through swiping alone.We instead create this custom element, + /// and make it an adjustable element that responds to `accessibilityIncrement` and `accessibilityDecrement`, + /// so that when a user swipes from it, they swipe immediately to the favorite and gallery buttons, then on to the data, + /// for the specific dog.In some ways, we've transformed the collection view into acting more like a picker. + /// </summary> + public class CarouselAccessibilityElement : UIAccessibilityElement { + public CarouselAccessibilityElement (NSObject accessibilityContainer, Dog dog) : base (accessibilityContainer) + { + this.CurrentDog = dog; + } + + public Dog CurrentDog { get; set; } + + /// <summary> + /// This indicates to the user what exactly this element is supposed to be. + /// </summary> + public override string AccessibilityLabel { + get => "Dog Picker"; + set => base.AccessibilityLabel = value; + } + + public override string AccessibilityValue { + get => this.CurrentDog != null ? this.CurrentDog.Name : base.AccessibilityValue; + set => base.AccessibilityValue = value; + } + + /// <summary> + /// This tells VoiceOver that our element will support the increment and decrement callbacks. + /// </summary> + public override ulong AccessibilityTraits { get => (ulong) UIAccessibilityTrait.Adjustable; set => base.AccessibilityTraits = value; } + + /// <summary> + /// A convenience for forward scrolling in both `accessibilityIncrement` and `accessibilityScroll`. + /// It returns a `Bool` because `accessibilityScroll` needs to know if the scroll was successful. + /// </summary> + private bool AccessibilityScrollForward () + { + var result = false; + + // Initialize the container view which will house the collection view. + if (this.AccessibilityContainer is DogCarouselContainerView containerView) { + // Store the currently focused dog and the list of all dogs. + if (this.CurrentDog != null && containerView.Dogs != null) { + // Get the index of the currently focused dog from the list of dogs (if it's a valid index). + var index = containerView.Dogs.IndexOf (this.CurrentDog); + if (index > -1 && index < containerView.Dogs.Count - 1) { + // Scroll the collection view to the currently focused dog. + containerView.dogCollectionView.ScrollToItem (NSIndexPath.FromRowSection (index + 1, 0), + UICollectionViewScrollPosition.CenteredHorizontally, + true); + + result = true; + } + } + } + + return result; + } + + /// <summary> + /// A convenience for backward scrolling in both `accessibilityIncrement` and `accessibilityScroll`. + /// It returns a `Bool` because `accessibilityScroll` needs to know if the scroll was successful. + /// </summary> + private bool AccessibilityScrollBackward () + { + var result = false; + if (this.AccessibilityContainer is DogCarouselContainerView containerView) { + if (this.CurrentDog != null && containerView.Dogs != null) { + var index = containerView.Dogs.IndexOf (this.CurrentDog); + if (index != -1) { + containerView.dogCollectionView.ScrollToItem (NSIndexPath.FromRowSection (index - 1, 0), + UICollectionViewScrollPosition.CenteredHorizontally, + true); + + result = true; + } + } + } + + return result; + } + + #region Accessibility + + /* Overriding the following two methods allows the user to perform increment and decrement actions (done by swiping up or down). */ - [Export("accessibilityIncrement")] - public void AccessibilityIncrement() - { - // This causes the picker to move forward one if the user swipes up. - _ = this.AccessibilityScrollForward(); - } - - [Export("accessibilityDecrement")] - public void AccessibilityDecrement() - { - // This causes the picker to move back one if the user swipes down. - _ = this.AccessibilityScrollBackward(); - } - - /// <summary> - /// This will cause the picker to move forward or backwards on when the user does a 3-finger swipe, - /// depending on the direction of the swipe.The return value indicates whether or not the scroll was successful, - /// so that VoiceOver can alert the user if it was not. - /// </summary> - [Export("accessibilityScroll:")] - public bool AccessibilityScroll(UIAccessibilityScrollDirection direction) - { - var result = false; - if (direction == UIAccessibilityScrollDirection.Left) - { - result = this.AccessibilityScrollForward(); - } - else if (direction == UIAccessibilityScrollDirection.Right) - { - result = this.AccessibilityScrollBackward(); - } - - return result; - } - - #endregion - } + [Export ("accessibilityIncrement")] + public void AccessibilityIncrement () + { + // This causes the picker to move forward one if the user swipes up. + _ = this.AccessibilityScrollForward (); + } + + [Export ("accessibilityDecrement")] + public void AccessibilityDecrement () + { + // This causes the picker to move back one if the user swipes down. + _ = this.AccessibilityScrollBackward (); + } + + /// <summary> + /// This will cause the picker to move forward or backwards on when the user does a 3-finger swipe, + /// depending on the direction of the swipe.The return value indicates whether or not the scroll was successful, + /// so that VoiceOver can alert the user if it was not. + /// </summary> + [Export ("accessibilityScroll:")] + public bool AccessibilityScroll (UIAccessibilityScrollDirection direction) + { + var result = false; + if (direction == UIAccessibilityScrollDirection.Left) { + result = this.AccessibilityScrollForward (); + } else if (direction == UIAccessibilityScrollDirection.Right) { + result = this.AccessibilityScrollBackward (); + } + + return result; + } + + #endregion + } } diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/Dog.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/Dog.cs index 0fefb8239..7e4a28918 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/Dog.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Helpers/Dog.cs @@ -1,61 +1,59 @@ - -namespace ExceptionalAccessibility -{ - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - /// <summary> - /// Dog model housing all of the data for each different dog up for adoption. - /// </summary> - public class Dog : IEquatable<Dog> - { - private readonly static UIImage DefaultImage = UIImage.FromBundle("husky"); - - public Dog(string name, List<UIImage> images, string breed, float age, float weight, string shelterName) - { - this.Name = name; - this.Images = images; - this.Breed = breed; - this.Age = age; - this.Weight = weight; - this.ShelterName = shelterName; - } - - public UIImage FeaturedImage => this.Images.FirstOrDefault(); - - public string Name { get; private set; } - - public List<UIImage> Images { get; set; } - - public string Breed { get; private set; } - - public float Age { get; private set; } - - public float Weight { get; private set; } - - public string ShelterName { get; private set; } - - /// <summary> - /// Convenience initializer for faked data - /// </summary> - public static List<Dog> All { get; } = new List<Dog> - { - new Dog("Lilly", new List<UIImage> { DefaultImage, DefaultImage, DefaultImage }, "Corgi", 5, 26, "Cupertino Animal Shelter"), - new Dog("Mr. Hammond", new List<UIImage> { DefaultImage }, "Pug", 2, 23, "Cupertino Animal Shelter"), - new Dog("Bubbles", new List<UIImage> { DefaultImage, DefaultImage, DefaultImage }, "Golden Retriever", 8, 65, "Cupertino Animal Shelter"), - new Dog("Pinky", new List<UIImage> { DefaultImage }, "Maltese", 4, 28, "Cupertino Animal Shelter") - }; - - public bool Equals(Dog other) - { - return this.Name == other.Name && - this.Images == other.Images && - this.Breed == other.Breed && - this.Age == other.Age && - this.Weight == other.Weight && - this.ShelterName == other.ShelterName; - } - } -} \ No newline at end of file + +namespace ExceptionalAccessibility { + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + /// <summary> + /// Dog model housing all of the data for each different dog up for adoption. + /// </summary> + public class Dog : IEquatable<Dog> { + private readonly static UIImage DefaultImage = UIImage.FromBundle ("husky"); + + public Dog (string name, List<UIImage> images, string breed, float age, float weight, string shelterName) + { + this.Name = name; + this.Images = images; + this.Breed = breed; + this.Age = age; + this.Weight = weight; + this.ShelterName = shelterName; + } + + public UIImage FeaturedImage => this.Images.FirstOrDefault (); + + public string Name { get; private set; } + + public List<UIImage> Images { get; set; } + + public string Breed { get; private set; } + + public float Age { get; private set; } + + public float Weight { get; private set; } + + public string ShelterName { get; private set; } + + /// <summary> + /// Convenience initializer for faked data + /// </summary> + public static List<Dog> All { get; } = new List<Dog> + { + new Dog("Lilly", new List<UIImage> { DefaultImage, DefaultImage, DefaultImage }, "Corgi", 5, 26, "Cupertino Animal Shelter"), + new Dog("Mr. Hammond", new List<UIImage> { DefaultImage }, "Pug", 2, 23, "Cupertino Animal Shelter"), + new Dog("Bubbles", new List<UIImage> { DefaultImage, DefaultImage, DefaultImage }, "Golden Retriever", 8, 65, "Cupertino Animal Shelter"), + new Dog("Pinky", new List<UIImage> { DefaultImage }, "Maltese", 4, 28, "Cupertino Animal Shelter") + }; + + public bool Equals (Dog other) + { + return this.Name == other.Name && + this.Images == other.Images && + this.Breed == other.Breed && + this.Age == other.Age && + this.Weight == other.Weight && + this.ShelterName == other.ShelterName; + } + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Main.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Main.cs index ed1119312..7d7fd0a2f 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Main.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/Main.cs @@ -1,16 +1,14 @@ - -namespace ExceptionalAccessibility -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace ExceptionalAccessibility { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/ViewController.cs b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/ViewController.cs index 7e6bacd9d..a404a3c69 100644 --- a/ios12/ExceptionalAccessibility/ExceptionalAccessibility/ViewController.cs +++ b/ios12/ExceptionalAccessibility/ExceptionalAccessibility/ViewController.cs @@ -1,228 +1,201 @@ - -namespace ExceptionalAccessibility -{ - using CoreGraphics; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - /// <summary> - /// This view controller manages the displayed views, links up the data by syncing dog objects - /// across the relevant views, handles displaying and removing the modal view as well as responding - /// to button presses in the carousel.It also serves as the data source for the collection view. - /// </summary> - public partial class ViewController : UIViewController, IUICollectionViewDataSource, IUICollectionViewDelegateFlowLayout - { - private const string CellIdentifier = "dog collection view cell"; - - private readonly List<Dog> dogs = Dog.All; - - private Dog currentlyFocusedDog; - - protected ViewController(IntPtr handle) : base(handle) { } - - protected Dog CurrentlyFocusedDog - { - get => this.currentlyFocusedDog; - - // Every time we update our Dog object, we need to relay that change to all the views that care. - set - { - if (this.currentlyFocusedDog != value) - { - this.currentlyFocusedDog = value; - if (this.dogStatsView != null) - { - this.dogStatsView.Dog = this.currentlyFocusedDog; - } - - this.carouselContainerView.CurrentDog = this.currentlyFocusedDog; - this.shelterNameLabel.Text = this.currentlyFocusedDog?.ShelterName; - this.shelterInfoView.AccessibilityLabel = this.currentlyFocusedDog?.ShelterName; - } - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - if (this.dogs.Any()) - { - this.CurrentlyFocusedDog = this.dogs.First(); - this.carouselContainerView.Dogs = this.dogs; - } - - this.galleryButton.AccessibilityLabel = "Show Gallery"; - - this.shelterInfoView.IsAccessibilityElement = true; - this.shelterInfoView.AccessibilityCustomActions = new UIAccessibilityCustomAction[] - { - new UIAccessibilityCustomAction("Call", probe: ActivateCallButton), - new UIAccessibilityCustomAction("Open address in Maps", probe: ActivateLocationButton) - }; - } - - /// <summary> - /// Called as a result of activating the "Call" custom action. - /// </summary> - private bool ActivateCallButton(UIAccessibilityCustomAction arg) - { - return true; - } - - /// <summary> - /// Called as a result of activating the "Open address in Maps" custom action. - /// </summary> - private bool ActivateLocationButton(UIAccessibilityCustomAction arg) - { - return true; - } - - partial void galleryButtonPressed(UIButton sender) - { - var dogModalViewController = base.Storyboard?.InstantiateViewController("DogModalViewController"); - if (dogModalViewController == null) - { - throw new Exception("Could not create a \"DogModalViewController\" from the storyboard."); - } - - if (dogModalViewController.View is DogModalView dogModalView) - { - // The gallery button shouldn't do anything if the currently focused dog doesn't have 2 or more images. - if (this.currentlyFocusedDog != null && this.currentlyFocusedDog.Images.Count >= 2) - { - // Make the images of the modal view accessible and add accessibility labels to these images and the close button. - dogModalView.closeButton.AccessibilityLabel = "Close"; - dogModalView.firstImageView.IsAccessibilityElement = true; - dogModalView.firstImageView.AccessibilityLabel = "Image 1"; - dogModalView.firstImageView.Image = currentlyFocusedDog.Images[0]; - - dogModalView.secondImageView.IsAccessibilityElement = true; - dogModalView.secondImageView.AccessibilityLabel = "Image 2"; - dogModalView.secondImageView.Image = currentlyFocusedDog.Images[1]; - - dogModalView.Alpha = 0f; - View.AddSubview(dogModalView); - - UIView.AnimateNotify(0.25d, () => - { - dogModalView.Alpha = 1f; - }, (finished) => - { - if (finished) - { - /* + +namespace ExceptionalAccessibility { + using CoreGraphics; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + /// <summary> + /// This view controller manages the displayed views, links up the data by syncing dog objects + /// across the relevant views, handles displaying and removing the modal view as well as responding + /// to button presses in the carousel.It also serves as the data source for the collection view. + /// </summary> + public partial class ViewController : UIViewController, IUICollectionViewDataSource, IUICollectionViewDelegateFlowLayout { + private const string CellIdentifier = "dog collection view cell"; + + private readonly List<Dog> dogs = Dog.All; + + private Dog currentlyFocusedDog; + + protected ViewController (IntPtr handle) : base (handle) { } + + protected Dog CurrentlyFocusedDog { + get => this.currentlyFocusedDog; + + // Every time we update our Dog object, we need to relay that change to all the views that care. + set { + if (this.currentlyFocusedDog != value) { + this.currentlyFocusedDog = value; + if (this.dogStatsView != null) { + this.dogStatsView.Dog = this.currentlyFocusedDog; + } + + this.carouselContainerView.CurrentDog = this.currentlyFocusedDog; + this.shelterNameLabel.Text = this.currentlyFocusedDog?.ShelterName; + this.shelterInfoView.AccessibilityLabel = this.currentlyFocusedDog?.ShelterName; + } + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + if (this.dogs.Any ()) { + this.CurrentlyFocusedDog = this.dogs.First (); + this.carouselContainerView.Dogs = this.dogs; + } + + this.galleryButton.AccessibilityLabel = "Show Gallery"; + + this.shelterInfoView.IsAccessibilityElement = true; + this.shelterInfoView.AccessibilityCustomActions = new UIAccessibilityCustomAction [] + { + new UIAccessibilityCustomAction("Call", probe: ActivateCallButton), + new UIAccessibilityCustomAction("Open address in Maps", probe: ActivateLocationButton) + }; + } + + /// <summary> + /// Called as a result of activating the "Call" custom action. + /// </summary> + private bool ActivateCallButton (UIAccessibilityCustomAction arg) + { + return true; + } + + /// <summary> + /// Called as a result of activating the "Open address in Maps" custom action. + /// </summary> + private bool ActivateLocationButton (UIAccessibilityCustomAction arg) + { + return true; + } + + partial void galleryButtonPressed (UIButton sender) + { + var dogModalViewController = base.Storyboard?.InstantiateViewController ("DogModalViewController"); + if (dogModalViewController == null) { + throw new Exception ("Could not create a \"DogModalViewController\" from the storyboard."); + } + + if (dogModalViewController.View is DogModalView dogModalView) { + // The gallery button shouldn't do anything if the currently focused dog doesn't have 2 or more images. + if (this.currentlyFocusedDog != null && this.currentlyFocusedDog.Images.Count >= 2) { + // Make the images of the modal view accessible and add accessibility labels to these images and the close button. + dogModalView.closeButton.AccessibilityLabel = "Close"; + dogModalView.firstImageView.IsAccessibilityElement = true; + dogModalView.firstImageView.AccessibilityLabel = "Image 1"; + dogModalView.firstImageView.Image = currentlyFocusedDog.Images [0]; + + dogModalView.secondImageView.IsAccessibilityElement = true; + dogModalView.secondImageView.AccessibilityLabel = "Image 2"; + dogModalView.secondImageView.Image = currentlyFocusedDog.Images [1]; + + dogModalView.Alpha = 0f; + View.AddSubview (dogModalView); + + UIView.AnimateNotify (0.25d, () => { + dogModalView.Alpha = 1f; + }, (finished) => { + if (finished) { + /* Once the modal gallery view has been animated in, we need to post a notification to VoiceOver that the screen has changed so that it knows to update its focus to the new content now displayed on top of the older content. */ - UIAccessibility.PostNotification(UIAccessibilityPostNotification.ScreenChanged, null); - } - }); - } - else - { - return; - } - } - else - { - throw new Exception("\"DogModalViewController\" not configured with a \"DogModalView\"."); - } - } - - #region IUICollectionViewDataSource - - public UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) - { - if (collectionView.DequeueReusableCell(CellIdentifier, indexPath) is DogCollectionViewCell cell) - { - var dog = this.dogs[(int)indexPath.Item]; - cell.dogImageView.Image = dog.FeaturedImage; - cell.IsAccessibilityElement = true; - cell.AccessibilityLabel = dog.Name; - - return cell; - } - else - { - throw new Exception($"Expected a `{nameof(DogCollectionViewCell)}` but did not receive one."); - } - } - - public nint GetItemsCount(UICollectionView collectionView, nint section) - { - return this.dogs.Count; - } - - #endregion - - #region IUIScrollViewDelegate - - /// <summary> - /// This keeps the cells of the collection view centered. - /// </summary> - [Export("scrollViewWillEndDragging:withVelocity:targetContentOffset:")] - public void WillEndDragging(UIScrollView scrollView, CoreGraphics.CGPoint velocity, ref CoreGraphics.CGPoint targetContentOffset) - { - if (this.dogCollectionView?.CollectionViewLayout is UICollectionViewFlowLayout layout) - { - var cellWidthIncludingSpacing = layout.ItemSize.Width + layout.MinimumLineSpacing; - - var offset = targetContentOffset; - var index = Math.Round((offset.X + scrollView.ContentInset.Left) / cellWidthIncludingSpacing); - offset = new CGPoint(index * cellWidthIncludingSpacing - scrollView.ContentInset.Left, - -scrollView.ContentInset.Top); - - targetContentOffset = offset; - } - } - - /// <summary> - /// In `scrollViewDidScroll`, we calculate our new centered cell's index, then find the corresponding `Dog` - /// in our array and update our current `Dog`. We also animate in or out the gallery button based on - /// whether or not we want to show it for the new dog. - /// </summary> - [Export("scrollViewDidScroll:")] - public void Scrolled(UIScrollView scrollView) - { - if (this.dogCollectionView.CollectionViewLayout is UICollectionViewFlowLayout flowLayout) - { - var itemWidth = flowLayout.ItemSize.Width; - var offset = this.dogCollectionView.ContentOffset.X / itemWidth; - var index = (int)Math.Round(offset); - - if (index >= 0 && index < this.dogs.Count) - { - var focusedDog = this.dogs[index]; - this.CurrentlyFocusedDog = focusedDog; - - if (focusedDog.Images.Count > 1) - { - if (this.galleryButton.Alpha == 0f) - { - UIView.Animate(0.25d, () => this.galleryButton.Alpha = 1f); - } - } - else if (this.galleryButton.Alpha == 1f) - { - UIView.Animate(0.25d, () => this.galleryButton.Alpha = 0f); - } - - /* + UIAccessibility.PostNotification (UIAccessibilityPostNotification.ScreenChanged, null); + } + }); + } else { + return; + } + } else { + throw new Exception ("\"DogModalViewController\" not configured with a \"DogModalView\"."); + } + } + + #region IUICollectionViewDataSource + + public UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) + { + if (collectionView.DequeueReusableCell (CellIdentifier, indexPath) is DogCollectionViewCell cell) { + var dog = this.dogs [(int) indexPath.Item]; + cell.dogImageView.Image = dog.FeaturedImage; + cell.IsAccessibilityElement = true; + cell.AccessibilityLabel = dog.Name; + + return cell; + } else { + throw new Exception ($"Expected a `{nameof (DogCollectionViewCell)}` but did not receive one."); + } + } + + public nint GetItemsCount (UICollectionView collectionView, nint section) + { + return this.dogs.Count; + } + + #endregion + + #region IUIScrollViewDelegate + + /// <summary> + /// This keeps the cells of the collection view centered. + /// </summary> + [Export ("scrollViewWillEndDragging:withVelocity:targetContentOffset:")] + public void WillEndDragging (UIScrollView scrollView, CoreGraphics.CGPoint velocity, ref CoreGraphics.CGPoint targetContentOffset) + { + if (this.dogCollectionView?.CollectionViewLayout is UICollectionViewFlowLayout layout) { + var cellWidthIncludingSpacing = layout.ItemSize.Width + layout.MinimumLineSpacing; + + var offset = targetContentOffset; + var index = Math.Round ((offset.X + scrollView.ContentInset.Left) / cellWidthIncludingSpacing); + offset = new CGPoint (index * cellWidthIncludingSpacing - scrollView.ContentInset.Left, + -scrollView.ContentInset.Top); + + targetContentOffset = offset; + } + } + + /// <summary> + /// In `scrollViewDidScroll`, we calculate our new centered cell's index, then find the corresponding `Dog` + /// in our array and update our current `Dog`. We also animate in or out the gallery button based on + /// whether or not we want to show it for the new dog. + /// </summary> + [Export ("scrollViewDidScroll:")] + public void Scrolled (UIScrollView scrollView) + { + if (this.dogCollectionView.CollectionViewLayout is UICollectionViewFlowLayout flowLayout) { + var itemWidth = flowLayout.ItemSize.Width; + var offset = this.dogCollectionView.ContentOffset.X / itemWidth; + var index = (int) Math.Round (offset); + + if (index >= 0 && index < this.dogs.Count) { + var focusedDog = this.dogs [index]; + this.CurrentlyFocusedDog = focusedDog; + + if (focusedDog.Images.Count > 1) { + if (this.galleryButton.Alpha == 0f) { + UIView.Animate (0.25d, () => this.galleryButton.Alpha = 1f); + } + } else if (this.galleryButton.Alpha == 1f) { + UIView.Animate (0.25d, () => this.galleryButton.Alpha = 0f); + } + + /* The information for the dog displayed below the collection view updates as you scroll, but VoiceOver isn't aware that the views have changed their values. So we need to post a layout changed notification to let VoiceOver know it needs to update its current understanding of what's on screen. */ - UIAccessibility.PostNotification(UIAccessibilityPostNotification.LayoutChanged, null); - } - } - } - - #endregion - } -} \ No newline at end of file + UIAccessibility.PostNotification (UIAccessibilityPostNotification.LayoutChanged, null); + } + } + } + + #endregion + } +} diff --git a/ios12/GroupedNotifications/AppDelegate.cs b/ios12/GroupedNotifications/AppDelegate.cs index 0e0e9bf4d..64dc0b203 100644 --- a/ios12/GroupedNotifications/AppDelegate.cs +++ b/ios12/GroupedNotifications/AppDelegate.cs @@ -1,69 +1,66 @@ -using System; +using System; using Foundation; using UIKit; using UserNotifications; -namespace GroupedNotifications -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate, IUNUserNotificationCenterDelegate - { - // class-level declarations - public override UIWindow Window - { - get; - set; - } +namespace GroupedNotifications { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate, IUNUserNotificationCenterDelegate { + // class-level declarations + public override UIWindow Window { + get; + set; + } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - UNUserNotificationCenter center = UNUserNotificationCenter.Current; - center.RequestAuthorization(UNAuthorizationOptions.Alert, (bool success, NSError error) => { - // Set the Delegate regardless of success; users can modify their notification - // preferences at any time in the Settings app. - center.Delegate = this; - }); - return true; - } + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + UNUserNotificationCenter center = UNUserNotificationCenter.Current; + center.RequestAuthorization (UNAuthorizationOptions.Alert, (bool success, NSError error) => { + // Set the Delegate regardless of success; users can modify their notification + // preferences at any time in the Settings app. + center.Delegate = this; + }); + return true; + } - [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")] - public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler) - { - completionHandler(UNNotificationPresentationOptions.Alert); - } + [Export ("userNotificationCenter:willPresentNotification:withCompletionHandler:")] + public void WillPresentNotification (UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler) + { + completionHandler (UNNotificationPresentationOptions.Alert); + } - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios12/GroupedNotifications/Main.cs b/ios12/GroupedNotifications/Main.cs index 0ccffcf9f..5fb538116 100644 --- a/ios12/GroupedNotifications/Main.cs +++ b/ios12/GroupedNotifications/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace GroupedNotifications -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace GroupedNotifications { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios12/GroupedNotifications/ViewController.cs b/ios12/GroupedNotifications/ViewController.cs index 888fa249d..547e49b44 100644 --- a/ios12/GroupedNotifications/ViewController.cs +++ b/ios12/GroupedNotifications/ViewController.cs @@ -1,135 +1,126 @@ -using System; +using System; using UIKit; using UserNotifications; using Foundation; using System.Linq; -namespace GroupedNotifications -{ - public partial class ViewController : UIViewController - { - string[] appointments = new string[] { "Dentist", "Doctor", "Salon", "Gym", "Plumber", "Roofer", "Mechanic" }; - string[] friends = new string[] { "Alice", "Bob", "Candace", "David", "Emily", "Frank", "Georgia", "Harry", "Isabelle" }; - string[] messages = new string[] - { - "Hey {0}!", - "Oh hi, what's up?", - "Let's go to the movies today at 2:00.", - "I'd rather go hiking.", - "But it's raining!", - "How about a board game?", - "Not in the mood. Bowling?", - "I already went bowling today. Get some ice cream?", - "No thanks. Let's clean my basement!", - "What? That's a terrible idea." - }; - int unthreadedMessagesSent = 0; - int threadNumber = 0; - int threadMessagesSent = 0; - string friend; - string threadId; - - protected ViewController(IntPtr handle) : base(handle) { } - - partial void UpdateThreadId(UIButton sender) - { - StartNewThread(); - } - - async partial void ScheduleUnthreadedNotification(UIButton sender) - { - var center = UNUserNotificationCenter.Current; - - UNNotificationSettings settings = await center.GetNotificationSettingsAsync(); - if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized) - { - return; - } - - string appointment = appointments[unthreadedMessagesSent % appointments.Length]; - - var content = new UNMutableNotificationContent() - { - Title = appointment, - Body = "See you for your appointment today at 2:00pm!", - SummaryArgument = appointment - }; - - var request = UNNotificationRequest.FromIdentifier( - Guid.NewGuid().ToString(), - content, - UNTimeIntervalNotificationTrigger.CreateTrigger(1, false) - ); - - center.AddNotificationRequest(request, null); - - unthreadedMessagesSent += 1; - } - - async partial void ScheduleThreadedNotification(UIButton sender) - { - var center = UNUserNotificationCenter.Current; - - UNNotificationSettings settings = await center.GetNotificationSettingsAsync(); - if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized) - { - return; - } - - string author = friend; - if (threadMessagesSent % 2 == 0) - { - author = "Me"; - } - - string message = "Fine!"; - if (threadMessagesSent < messages.Length) - { - message = messages[threadMessagesSent % messages.Length]; - if (threadMessagesSent == 0) - { - message = String.Format(message, friend); - } - } - - var content = new UNMutableNotificationContent() - { - ThreadIdentifier = threadId, - Title = author, - Body = message, - SummaryArgument = author - }; - - var request = UNNotificationRequest.FromIdentifier( - Guid.NewGuid().ToString(), - content, - UNTimeIntervalNotificationTrigger.CreateTrigger(1, false) - ); - - center.AddNotificationRequest(request, null); - - threadMessagesSent += 1; - } - - void StartNewThread() - { - threadId = $"message-{friend}"; - threadMessagesSent = 0; - friend = friends[threadNumber % friends.Length]; - MessageWithFriendButton.SetTitle($"Message with {friend}", UIControlState.Normal); - threadNumber += 1; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - StartNewThread(); - } - - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - } - } +namespace GroupedNotifications { + public partial class ViewController : UIViewController { + string [] appointments = new string [] { "Dentist", "Doctor", "Salon", "Gym", "Plumber", "Roofer", "Mechanic" }; + string [] friends = new string [] { "Alice", "Bob", "Candace", "David", "Emily", "Frank", "Georgia", "Harry", "Isabelle" }; + string [] messages = new string [] + { + "Hey {0}!", + "Oh hi, what's up?", + "Let's go to the movies today at 2:00.", + "I'd rather go hiking.", + "But it's raining!", + "How about a board game?", + "Not in the mood. Bowling?", + "I already went bowling today. Get some ice cream?", + "No thanks. Let's clean my basement!", + "What? That's a terrible idea." + }; + int unthreadedMessagesSent = 0; + int threadNumber = 0; + int threadMessagesSent = 0; + string friend; + string threadId; + + protected ViewController (IntPtr handle) : base (handle) { } + + partial void UpdateThreadId (UIButton sender) + { + StartNewThread (); + } + + async partial void ScheduleUnthreadedNotification (UIButton sender) + { + var center = UNUserNotificationCenter.Current; + + UNNotificationSettings settings = await center.GetNotificationSettingsAsync (); + if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized) { + return; + } + + string appointment = appointments [unthreadedMessagesSent % appointments.Length]; + + var content = new UNMutableNotificationContent () { + Title = appointment, + Body = "See you for your appointment today at 2:00pm!", + SummaryArgument = appointment + }; + + var request = UNNotificationRequest.FromIdentifier ( + Guid.NewGuid ().ToString (), + content, + UNTimeIntervalNotificationTrigger.CreateTrigger (1, false) + ); + + center.AddNotificationRequest (request, null); + + unthreadedMessagesSent += 1; + } + + async partial void ScheduleThreadedNotification (UIButton sender) + { + var center = UNUserNotificationCenter.Current; + + UNNotificationSettings settings = await center.GetNotificationSettingsAsync (); + if (settings.AuthorizationStatus != UNAuthorizationStatus.Authorized) { + return; + } + + string author = friend; + if (threadMessagesSent % 2 == 0) { + author = "Me"; + } + + string message = "Fine!"; + if (threadMessagesSent < messages.Length) { + message = messages [threadMessagesSent % messages.Length]; + if (threadMessagesSent == 0) { + message = String.Format (message, friend); + } + } + + var content = new UNMutableNotificationContent () { + ThreadIdentifier = threadId, + Title = author, + Body = message, + SummaryArgument = author + }; + + var request = UNNotificationRequest.FromIdentifier ( + Guid.NewGuid ().ToString (), + content, + UNTimeIntervalNotificationTrigger.CreateTrigger (1, false) + ); + + center.AddNotificationRequest (request, null); + + threadMessagesSent += 1; + } + + void StartNewThread () + { + threadId = $"message-{friend}"; + threadMessagesSent = 0; + friend = friends [threadNumber % friends.Length]; + MessageWithFriendButton.SetTitle ($"Message with {friend}", UIControlState.Normal); + threadNumber += 1; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + StartNewThread (); + } + + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + } + } } diff --git a/ios12/MarsHabitatCoreMLTimer/AppDelegate.cs b/ios12/MarsHabitatCoreMLTimer/AppDelegate.cs index a36584738..335d15b4b 100644 --- a/ios12/MarsHabitatCoreMLTimer/AppDelegate.cs +++ b/ios12/MarsHabitatCoreMLTimer/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace MarsHabitatCoreMLTimer -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace MarsHabitatCoreMLTimer { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios12/MarsHabitatCoreMLTimer/CoreMLModel/MarsHabitatPricer.cs b/ios12/MarsHabitatCoreMLTimer/CoreMLModel/MarsHabitatPricer.cs index 52cbb68ce..309aadd25 100644 --- a/ios12/MarsHabitatCoreMLTimer/CoreMLModel/MarsHabitatPricer.cs +++ b/ios12/MarsHabitatCoreMLTimer/CoreMLModel/MarsHabitatPricer.cs @@ -16,8 +16,7 @@ namespace MarsHabitatCoreMLTimer { /// <summary> /// Model Prediction Input Type /// </summary> - public class MarsHabitatPricerInput : NSObject, IMLFeatureProvider - { + public class MarsHabitatPricerInput : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("solarPanels"), new NSString ("greenhouses"), new NSString ("size") ); @@ -88,8 +87,7 @@ public MarsHabitatPricerInput (double solarPanels, double greenhouses, double si /// <summary> /// Model Prediction Output Type /// </summary> - public class MarsHabitatPricerOutput : NSObject, IMLFeatureProvider - { + public class MarsHabitatPricerOutput : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("price") ); @@ -130,8 +128,7 @@ public MarsHabitatPricerOutput (double price) /// <summary> /// Class for model loading and prediction /// </summary> - public class MarsHabitatPricer : NSObject - { + public class MarsHabitatPricer : NSObject { readonly MLModel model; public MarsHabitatPricer () diff --git a/ios12/MarsHabitatCoreMLTimer/Main.cs b/ios12/MarsHabitatCoreMLTimer/Main.cs index 356be979e..e256887a0 100644 --- a/ios12/MarsHabitatCoreMLTimer/Main.cs +++ b/ios12/MarsHabitatCoreMLTimer/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace MarsHabitatCoreMLTimer -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace MarsHabitatCoreMLTimer { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios12/MarsHabitatCoreMLTimer/ViewController.cs b/ios12/MarsHabitatCoreMLTimer/ViewController.cs index 23075082c..041cdd709 100644 --- a/ios12/MarsHabitatCoreMLTimer/ViewController.cs +++ b/ios12/MarsHabitatCoreMLTimer/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using CoreML; using Foundation; @@ -8,143 +8,132 @@ using System.Threading.Tasks; using System.Diagnostics; -namespace MarsHabitatCoreMLTimer -{ - public partial class ViewController : UIViewController - { - #region constants - const int numberOfInputs = 100000; - const int smallNumber = numberOfInputs / 4; - const int mediumNumber = numberOfInputs / 2; - const int MaxSolarPanels = 100; - const int MaxGreenHouses = 100; - const int MaxAcres = 10000; - #endregion - - #region fields - MLModel model; - MarsHabitatPricerInput[] inputs = new MarsHabitatPricerInput[numberOfInputs]; - long batchMilliseconds; - long nonBatchMilliseconds; - #endregion - - #region constructors - protected ViewController(IntPtr handle) : base(handle) { } - #endregion - - #region view controller overrides - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - SetupUI(false, ""); - SmallTestButton.SetTitle($"Timer: {smallNumber} predictions", UIControlState.Normal); - MediumTestButton.SetTitle($"Timer: {mediumNumber} predictions", UIControlState.Normal); - LargeTestButton.SetTitle($"Timer: {numberOfInputs} predictions", UIControlState.Normal); - - LoadMLModel(); - CreateInputs(numberOfInputs); - } - #endregion - - #region event handlers - partial void LargeTestButton_TouchUpInside(UIButton sender) - { - RunTest(numberOfInputs); - } - - partial void MediumTestButton_TouchUpInside(UIButton sender) - { - RunTest(mediumNumber); - } - - partial void SmallTestButton_TouchUpInside(UIButton sender) - { - RunTest(smallNumber); - } - #endregion - - #region private methods - void LoadMLModel() - { - var assetPath = NSBundle.MainBundle.GetUrlForResource("CoreMLModel/MarsHabitatPricer", "mlmodelc"); - model = MLModel.Create(assetPath, out NSError mlErr); - } - - void SetupUI(bool busy, string statusLabelText) - { - if (busy) - { - Spinner.StartAnimating(); - } - else - { - Spinner.StopAnimating(); - } - - SmallTestButton.Enabled = !busy; - MediumTestButton.Enabled = !busy; - LargeTestButton.Enabled = !busy; - - StatusLabel.Text = statusLabelText; - } - - async void CreateInputs(int num) - { - SetupUI(true, "Generating sample data..."); - Random r = new Random(); - await Task.Run(() => - { - for (int i = 0; i < num; i++) - { - double solarPanels = r.NextDouble() * MaxSolarPanels; - double greenHouses = r.NextDouble() * MaxGreenHouses; - double acres = r.NextDouble() * MaxAcres; - inputs[i] = new MarsHabitatPricerInput(solarPanels, greenHouses, acres); - } - }); - SetupUI(false, ""); - } - - async void RunTest(int num) - { - SetupUI(true, $"Fetching {num} predictions with a loop..."); - await FetchNonBatchResults(num); - SetupUI(true, $"Fetching {num} predictions with batch API..."); - await FetchBatchResults(num); - SetupUI(false, $"Loop: {(float)nonBatchMilliseconds / 1000} sec; Batch: {(float)batchMilliseconds / 1000} sec"); - } - - async Task FetchNonBatchResults(int num) - { - Stopwatch stopWatch = Stopwatch.StartNew(); - await Task.Run(() => - { - for (int i = 0; i < num; i++) - { - model.GetPrediction(inputs[i], out NSError error); - } - }); - stopWatch.Stop(); - nonBatchMilliseconds = stopWatch.ElapsedMilliseconds; - } - - async Task FetchBatchResults(int num) - { - var batch = new MLArrayBatchProvider(inputs.Take(num).ToArray()); - var options = new MLPredictionOptions() - { - UsesCpuOnly = false - }; - - Stopwatch stopWatch = Stopwatch.StartNew(); - await Task.Run(() => - { - model.GetPredictions(batch, options, out NSError error); - }); - stopWatch.Stop(); - batchMilliseconds = stopWatch.ElapsedMilliseconds; - } - #endregion - } +namespace MarsHabitatCoreMLTimer { + public partial class ViewController : UIViewController { + #region constants + const int numberOfInputs = 100000; + const int smallNumber = numberOfInputs / 4; + const int mediumNumber = numberOfInputs / 2; + const int MaxSolarPanels = 100; + const int MaxGreenHouses = 100; + const int MaxAcres = 10000; + #endregion + + #region fields + MLModel model; + MarsHabitatPricerInput [] inputs = new MarsHabitatPricerInput [numberOfInputs]; + long batchMilliseconds; + long nonBatchMilliseconds; + #endregion + + #region constructors + protected ViewController (IntPtr handle) : base (handle) { } + #endregion + + #region view controller overrides + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + SetupUI (false, ""); + SmallTestButton.SetTitle ($"Timer: {smallNumber} predictions", UIControlState.Normal); + MediumTestButton.SetTitle ($"Timer: {mediumNumber} predictions", UIControlState.Normal); + LargeTestButton.SetTitle ($"Timer: {numberOfInputs} predictions", UIControlState.Normal); + + LoadMLModel (); + CreateInputs (numberOfInputs); + } + #endregion + + #region event handlers + partial void LargeTestButton_TouchUpInside (UIButton sender) + { + RunTest (numberOfInputs); + } + + partial void MediumTestButton_TouchUpInside (UIButton sender) + { + RunTest (mediumNumber); + } + + partial void SmallTestButton_TouchUpInside (UIButton sender) + { + RunTest (smallNumber); + } + #endregion + + #region private methods + void LoadMLModel () + { + var assetPath = NSBundle.MainBundle.GetUrlForResource ("CoreMLModel/MarsHabitatPricer", "mlmodelc"); + model = MLModel.Create (assetPath, out NSError mlErr); + } + + void SetupUI (bool busy, string statusLabelText) + { + if (busy) { + Spinner.StartAnimating (); + } else { + Spinner.StopAnimating (); + } + + SmallTestButton.Enabled = !busy; + MediumTestButton.Enabled = !busy; + LargeTestButton.Enabled = !busy; + + StatusLabel.Text = statusLabelText; + } + + async void CreateInputs (int num) + { + SetupUI (true, "Generating sample data..."); + Random r = new Random (); + await Task.Run (() => { + for (int i = 0; i < num; i++) { + double solarPanels = r.NextDouble () * MaxSolarPanels; + double greenHouses = r.NextDouble () * MaxGreenHouses; + double acres = r.NextDouble () * MaxAcres; + inputs [i] = new MarsHabitatPricerInput (solarPanels, greenHouses, acres); + } + }); + SetupUI (false, ""); + } + + async void RunTest (int num) + { + SetupUI (true, $"Fetching {num} predictions with a loop..."); + await FetchNonBatchResults (num); + SetupUI (true, $"Fetching {num} predictions with batch API..."); + await FetchBatchResults (num); + SetupUI (false, $"Loop: {(float) nonBatchMilliseconds / 1000} sec; Batch: {(float) batchMilliseconds / 1000} sec"); + } + + async Task FetchNonBatchResults (int num) + { + Stopwatch stopWatch = Stopwatch.StartNew (); + await Task.Run (() => { + for (int i = 0; i < num; i++) { + model.GetPrediction (inputs [i], out NSError error); + } + }); + stopWatch.Stop (); + nonBatchMilliseconds = stopWatch.ElapsedMilliseconds; + } + + async Task FetchBatchResults (int num) + { + var batch = new MLArrayBatchProvider (inputs.Take (num).ToArray ()); + var options = new MLPredictionOptions () { + UsesCpuOnly = false + }; + + Stopwatch stopWatch = Stopwatch.StartNew (); + await Task.Run (() => { + model.GetPredictions (batch, options, out NSError error); + }); + stopWatch.Stop (); + batchMilliseconds = stopWatch.ElapsedMilliseconds; + } + #endregion + } } diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/AppDelegate.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/AppDelegate.cs index b2bb5068f..14390a952 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/AppDelegate.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace MarsHabitatPricePredictor -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace MarsHabitatPricePredictor { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/GreenhousesDataSource.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/GreenhousesDataSource.cs index aef5447dd..d12e4ecfc 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/GreenhousesDataSource.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/GreenhousesDataSource.cs @@ -1,36 +1,32 @@ - -namespace MarsHabitatPricePredictor.DataSources -{ - /// <summary> - /// Data source for the number of greenhouses. - /// </summary> - public class GreenhousesDataSource - { - /// <summary> - /// Possible values for greenhouses in the habitat - /// </summary> - public double[] Values { get; } = { 1, 2, 3, 4, 5 }; - public string Title(int index) - { - string result = null; - if (index < this.Values.Length) - { - result = this.Values[index].ToString(); - } +namespace MarsHabitatPricePredictor.DataSources { + /// <summary> + /// Data source for the number of greenhouses. + /// </summary> + public class GreenhousesDataSource { + /// <summary> + /// Possible values for greenhouses in the habitat + /// </summary> + public double [] Values { get; } = { 1, 2, 3, 4, 5 }; - return result; - } + public string Title (int index) + { + string result = null; + if (index < this.Values.Length) { + result = this.Values [index].ToString (); + } - public double? Value(int index) - { - double? result = null; - if (index < this.Values.Length) - { - result = this.Values[index]; - } + return result; + } - return result; - } - } -} \ No newline at end of file + public double? Value (int index) + { + double? result = null; + if (index < this.Values.Length) { + result = this.Values [index]; + } + + return result; + } + } +} diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/PickerDataSource.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/PickerDataSource.cs index c2e3515ba..5edb7be49 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/PickerDataSource.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/PickerDataSource.cs @@ -1,85 +1,80 @@ -using System; +using System; using UIKit; -namespace MarsHabitatPricePredictor.DataSources -{ - /// <summary> - /// The common data source for the three features and their picker values. Decouples - /// the user interface and the feature specific values. - /// </summary> - public class PickerDataSource : UIPickerViewDataSource - { - private readonly SolarPanelDataSource solarPanelsDataSource = new SolarPanelDataSource(); - private readonly GreenhousesDataSource greenhousesDataSource = new GreenhousesDataSource(); - private readonly SizeDataSource sizeDataSource = new SizeDataSource(); +namespace MarsHabitatPricePredictor.DataSources { + /// <summary> + /// The common data source for the three features and their picker values. Decouples + /// the user interface and the feature specific values. + /// </summary> + public class PickerDataSource : UIPickerViewDataSource { + private readonly SolarPanelDataSource solarPanelsDataSource = new SolarPanelDataSource (); + private readonly GreenhousesDataSource greenhousesDataSource = new GreenhousesDataSource (); + private readonly SizeDataSource sizeDataSource = new SizeDataSource (); - /// <summary> - /// Find the title for the given feature. - /// </summary> - public string Title(int row, Feature feature) - { - string result = null; - switch (feature) - { - case Feature.SolarPanels: - result = this.solarPanelsDataSource.Title(row); - break; - case Feature.Greenhouses: - result = this.greenhousesDataSource.Title(row); - break; - case Feature.Size: - result = this.sizeDataSource.Title(row); - break; - } + /// <summary> + /// Find the title for the given feature. + /// </summary> + public string Title (int row, Feature feature) + { + string result = null; + switch (feature) { + case Feature.SolarPanels: + result = this.solarPanelsDataSource.Title (row); + break; + case Feature.Greenhouses: + result = this.greenhousesDataSource.Title (row); + break; + case Feature.Size: + result = this.sizeDataSource.Title (row); + break; + } - return result; - } + return result; + } - /// <summary> - /// For the given feature, find the value for the given row. - /// </summary> - public double Value(int row, Feature feature) - { - double? result = null; + /// <summary> + /// For the given feature, find the value for the given row. + /// </summary> + public double Value (int row, Feature feature) + { + double? result = null; - switch (feature) - { - case Feature.SolarPanels: - result = this.solarPanelsDataSource.Value(row); - break; - case Feature.Greenhouses: - result = this.greenhousesDataSource.Value(row); - break; - case Feature.Size: - result = this.sizeDataSource.Value(row); - break; - } + switch (feature) { + case Feature.SolarPanels: + result = this.solarPanelsDataSource.Value (row); + break; + case Feature.Greenhouses: + result = this.greenhousesDataSource.Value (row); + break; + case Feature.Size: + result = this.sizeDataSource.Value (row); + break; + } - return result.Value; - } + return result.Value; + } - #region UIPickerViewDataSource + #region UIPickerViewDataSource - public override nint GetComponentCount(UIPickerView pickerView) - { - return 3; - } + public override nint GetComponentCount (UIPickerView pickerView) + { + return 3; + } - public override nint GetRowsInComponent(UIPickerView pickerView, nint component) - { - switch ((Feature)(int)component) - { - case Feature.SolarPanels: - return this.solarPanelsDataSource.Values.Length; - case Feature.Greenhouses: - return this.greenhousesDataSource.Values.Length; - case Feature.Size: - return this.sizeDataSource.Values.Length; - default: - throw new NotImplementedException(); - } - } + public override nint GetRowsInComponent (UIPickerView pickerView, nint component) + { + switch ((Feature) (int) component) { + case Feature.SolarPanels: + return this.solarPanelsDataSource.Values.Length; + case Feature.Greenhouses: + return this.greenhousesDataSource.Values.Length; + case Feature.Size: + return this.sizeDataSource.Values.Length; + default: + throw new NotImplementedException (); + } + } - #endregion - } -} \ No newline at end of file + #endregion + } +} diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SizeDataSource.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SizeDataSource.cs index 81652e3ea..52bd54577 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SizeDataSource.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SizeDataSource.cs @@ -1,46 +1,41 @@ - -namespace MarsHabitatPricePredictor.DataSources -{ - using Foundation; - /// <summary> - /// Data source for the size field on the UIPicker. - /// </summary> - public class SizeDataSource - { - // Helper formatter to represent large nubmers in the picker - private static NSNumberFormatter numberFormatter = new NSNumberFormatter - { - Locale = NSLocale.CurrentLocale, - NumberStyle = NSNumberFormatterStyle.Decimal, - UsesGroupingSeparator = true - }; +namespace MarsHabitatPricePredictor.DataSources { + using Foundation; - /// <summary> - /// Possible values for size of the habitat. - /// </summary> - public double[] Values { get; } = { 750, 1000, 1500, 2000, 3000, 4000, 5000, 10000 }; + /// <summary> + /// Data source for the size field on the UIPicker. + /// </summary> + public class SizeDataSource { + // Helper formatter to represent large nubmers in the picker + private static NSNumberFormatter numberFormatter = new NSNumberFormatter { + Locale = NSLocale.CurrentLocale, + NumberStyle = NSNumberFormatterStyle.Decimal, + UsesGroupingSeparator = true + }; - public string Title(int index) - { - string result = null; - if (index < this.Values.Length) - { - result = numberFormatter.StringFor(NSNumber.FromDouble(this.Values[index])); - } + /// <summary> + /// Possible values for size of the habitat. + /// </summary> + public double [] Values { get; } = { 750, 1000, 1500, 2000, 3000, 4000, 5000, 10000 }; - return result; - } + public string Title (int index) + { + string result = null; + if (index < this.Values.Length) { + result = numberFormatter.StringFor (NSNumber.FromDouble (this.Values [index])); + } - public double? Value(int index) - { - double? result = null; - if (index < this.Values.Length) - { - result = this.Values[index]; - } + return result; + } - return result; - } - } -} \ No newline at end of file + public double? Value (int index) + { + double? result = null; + if (index < this.Values.Length) { + result = this.Values [index]; + } + + return result; + } + } +} diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SolarPanelDataSource.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SolarPanelDataSource.cs index e7ad62088..6754b56ca 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SolarPanelDataSource.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/DataSources/SolarPanelDataSource.cs @@ -1,36 +1,32 @@ - -namespace MarsHabitatPricePredictor.DataSources -{ - /// <summary> - /// Data source for the number of solar panels in the habitat. - /// </summary> - public class SolarPanelDataSource - { - /// <summary> - /// Possible values for solar panels in the habitat - /// </summary> - public double[] Values { get; } = { 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 }; - public string Title(int index) - { - string result = null; - if (index < this.Values.Length) - { - result = this.Values[index].ToString(); - } +namespace MarsHabitatPricePredictor.DataSources { + /// <summary> + /// Data source for the number of solar panels in the habitat. + /// </summary> + public class SolarPanelDataSource { + /// <summary> + /// Possible values for solar panels in the habitat + /// </summary> + public double [] Values { get; } = { 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5 }; - return result; - } + public string Title (int index) + { + string result = null; + if (index < this.Values.Length) { + result = this.Values [index].ToString (); + } - public double? Value(int index) - { - double? result = null; - if (index < this.Values.Length) - { - result = this.Values[index]; - } + return result; + } - return result; - } - } -} \ No newline at end of file + public double? Value (int index) + { + double? result = null; + if (index < this.Values.Length) { + result = this.Values [index]; + } + + return result; + } + } +} diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Main.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Main.cs index 2d1211682..8dd33457e 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Main.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace MarsHabitatPricePredictor -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace MarsHabitatPricePredictor { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Resources/MarsHabitatPricer.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Resources/MarsHabitatPricer.cs index c7d69269a..99b883f1c 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Resources/MarsHabitatPricer.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/Resources/MarsHabitatPricer.cs @@ -16,8 +16,7 @@ namespace MarsHabitatPricePredictor { /// <summary> /// Model Prediction Input Type /// </summary> - public class MarsHabitatPricerInput : NSObject, IMLFeatureProvider - { + public class MarsHabitatPricerInput : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("solarPanels"), new NSString ("greenhouses"), new NSString ("size") ); @@ -88,8 +87,7 @@ public MarsHabitatPricerInput (double solarPanels, double greenhouses, double si /// <summary> /// Model Prediction Output Type /// </summary> - public class MarsHabitatPricerOutput : NSObject, IMLFeatureProvider - { + public class MarsHabitatPricerOutput : NSObject, IMLFeatureProvider { static readonly NSSet<NSString> featureNames = new NSSet<NSString> ( new NSString ("price") ); @@ -130,8 +128,7 @@ public MarsHabitatPricerOutput (double price) /// <summary> /// Class for model loading and prediction /// </summary> - public class MarsHabitatPricer : NSObject - { + public class MarsHabitatPricer : NSObject { readonly MLModel model; static NSUrl GetModelUrl () diff --git a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/ViewController.cs b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/ViewController.cs index a2cbb5590..c9afb319c 100644 --- a/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/ViewController.cs +++ b/ios12/MarsHabitatPricePredictor/MarsHabitatPricePredictor/ViewController.cs @@ -1,104 +1,98 @@ -using Foundation; +using Foundation; using MarsHabitatPricePredictor.DataSources; using System; using System.Linq; using UIKit; -namespace MarsHabitatPricePredictor -{ - /// <summary> - /// Main view controller for the MarsHabitatPricer app. Uses a `UIPickerView` to gather user inputs. The model's output is the predicted price. - /// </summary> - public partial class ViewController : UIViewController, IUIPickerViewDelegate - { - private readonly MarsHabitatPricer model = new MarsHabitatPricer(); - - // Data source for the picker. - private readonly PickerDataSource pickerDataSource = new PickerDataSource(); - - // Formatter for the output. - private readonly NSNumberFormatter priceFormatter = new NSNumberFormatter - { - NumberStyle = NSNumberFormatterStyle.Currency, - MaximumFractionDigits = 0, - UsesGroupingSeparator = true, - Locale = new NSLocale("en_US") - }; - - protected ViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.pickerView.Delegate = this; - this.pickerView.DataSource = this.pickerDataSource; - - // set default values - var features = Enum.GetValues(typeof(Feature)).Cast<Feature>(); - foreach (var feature in features) - { - this.pickerView.Select(2, (int)feature, false); - } - - this.UpdatePredictedPrice(); - } - - /// <summary> - /// The main logic for the app, performing the integration with Core ML. - /// First gather the values for input to the model. Then have the model generate - /// a prediction with those inputs. Finally, present the predicted value to the user. - /// </summary> - private void UpdatePredictedPrice() - { - var solarPanels = this.pickerDataSource.Value(SelectedRow(Feature.SolarPanels), Feature.SolarPanels); - var greenhouses = this.pickerDataSource.Value(SelectedRow(Feature.Greenhouses), Feature.Greenhouses); - var size = this.pickerDataSource.Value(SelectedRow(Feature.Size), Feature.Size); - - var marsHabitatPricerOutput = this.model.GetPrediction(solarPanels, greenhouses, size, out NSError error); - if (error != null) - { - throw new Exception("Unexpected runtime error."); - } - - var price = marsHabitatPricerOutput.Price; - this.priceLabel.Text = this.priceFormatter.StringFor(NSNumber.FromDouble(price)); - - int SelectedRow(Feature feature) - { - return (int)this.pickerView.SelectedRowInComponent((int)feature); - } - } - - #region IUIPickerViewDelegate - - [Export("pickerView:didSelectRow:inComponent:")] - public void Selected(UIPickerView pickerView, nint row, nint component) - { - // When values are changed, update the predicted price. - this.UpdatePredictedPrice(); - } - - [Export("pickerView:titleForRow:forComponent:")] - public string GetTitle(UIPickerView pickerView, nint row, nint component) - { - // Accessor for picker values. - var feature = (Feature)(int)component; - return this.pickerDataSource.Title((int)row, feature); - } - - #endregion - } - - /// <summary> - /// Represents the different features used by this model. Each feature - /// of solar panels, # of greenhouses, or size) is an input value to the - /// model. So each needs an appropriate `UIPicker` as well. - /// </summary> - public enum Feature - { - SolarPanels = 0, - Greenhouses = 1, - Size = 2 - } -} \ No newline at end of file +namespace MarsHabitatPricePredictor { + /// <summary> + /// Main view controller for the MarsHabitatPricer app. Uses a `UIPickerView` to gather user inputs. The model's output is the predicted price. + /// </summary> + public partial class ViewController : UIViewController, IUIPickerViewDelegate { + private readonly MarsHabitatPricer model = new MarsHabitatPricer (); + + // Data source for the picker. + private readonly PickerDataSource pickerDataSource = new PickerDataSource (); + + // Formatter for the output. + private readonly NSNumberFormatter priceFormatter = new NSNumberFormatter { + NumberStyle = NSNumberFormatterStyle.Currency, + MaximumFractionDigits = 0, + UsesGroupingSeparator = true, + Locale = new NSLocale ("en_US") + }; + + protected ViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.pickerView.Delegate = this; + this.pickerView.DataSource = this.pickerDataSource; + + // set default values + var features = Enum.GetValues (typeof (Feature)).Cast<Feature> (); + foreach (var feature in features) { + this.pickerView.Select (2, (int) feature, false); + } + + this.UpdatePredictedPrice (); + } + + /// <summary> + /// The main logic for the app, performing the integration with Core ML. + /// First gather the values for input to the model. Then have the model generate + /// a prediction with those inputs. Finally, present the predicted value to the user. + /// </summary> + private void UpdatePredictedPrice () + { + var solarPanels = this.pickerDataSource.Value (SelectedRow (Feature.SolarPanels), Feature.SolarPanels); + var greenhouses = this.pickerDataSource.Value (SelectedRow (Feature.Greenhouses), Feature.Greenhouses); + var size = this.pickerDataSource.Value (SelectedRow (Feature.Size), Feature.Size); + + var marsHabitatPricerOutput = this.model.GetPrediction (solarPanels, greenhouses, size, out NSError error); + if (error != null) { + throw new Exception ("Unexpected runtime error."); + } + + var price = marsHabitatPricerOutput.Price; + this.priceLabel.Text = this.priceFormatter.StringFor (NSNumber.FromDouble (price)); + + int SelectedRow (Feature feature) + { + return (int) this.pickerView.SelectedRowInComponent ((int) feature); + } + } + + #region IUIPickerViewDelegate + + [Export ("pickerView:didSelectRow:inComponent:")] + public void Selected (UIPickerView pickerView, nint row, nint component) + { + // When values are changed, update the predicted price. + this.UpdatePredictedPrice (); + } + + [Export ("pickerView:titleForRow:forComponent:")] + public string GetTitle (UIPickerView pickerView, nint row, nint component) + { + // Accessor for picker values. + var feature = (Feature) (int) component; + return this.pickerDataSource.Title ((int) row, feature); + } + + #endregion + } + + /// <summary> + /// Represents the different features used by this model. Each feature + /// of solar panels, # of greenhouses, or size) is an input value to the + /// model. So each needs an appropriate `UIPicker` as well. + /// </summary> + public enum Feature { + SolarPanels = 0, + Greenhouses = 1, + Size = 2 + } +} diff --git a/ios12/RedGreenNotifications/AppDelegate.cs b/ios12/RedGreenNotifications/AppDelegate.cs index 4b7242a31..df6542387 100644 --- a/ios12/RedGreenNotifications/AppDelegate.cs +++ b/ios12/RedGreenNotifications/AppDelegate.cs @@ -1,129 +1,118 @@ -using Foundation; +using Foundation; using UIKit; using UserNotifications; using System; -namespace RedGreenNotifications -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate, IUNUserNotificationCenterDelegate - { - public const string InitializedNotificationSettingsKey = "InitializedNotificationSettings"; - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Request authorization to send notifications - UNUserNotificationCenter center = UNUserNotificationCenter.Current; - var options = UNAuthorizationOptions.ProvidesAppNotificationSettings | UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Provisional; - center.RequestAuthorization(options, (bool success, NSError error) => - { - center.Delegate = this; - - var rotateTwentyDegreesAction = UNNotificationAction.FromIdentifier("rotate-twenty-degrees-action", "Rotate 20°", UNNotificationActionOptions.None); - - var redCategory = UNNotificationCategory.FromIdentifier( - "red-category", - new UNNotificationAction[] { rotateTwentyDegreesAction }, - new string[] { }, - UNNotificationCategoryOptions.CustomDismissAction - ); - - var greenCategory = UNNotificationCategory.FromIdentifier( - "green-category", - new UNNotificationAction[] { rotateTwentyDegreesAction }, - new string[] { }, - UNNotificationCategoryOptions.CustomDismissAction - ); - - var set = new NSSet<UNNotificationCategory>(redCategory, greenCategory); - center.SetNotificationCategories(set); - }); - - // Initialize granular notification settings on first run - bool initializedNotificationSettings = NSUserDefaults.StandardUserDefaults.BoolForKey(InitializedNotificationSettingsKey); - if (!initializedNotificationSettings) - { - NSUserDefaults.StandardUserDefaults.SetBool(true, ManageNotificationsViewController.RedNotificationsEnabledKey); - NSUserDefaults.StandardUserDefaults.SetBool(true, ManageNotificationsViewController.GreenNotificationsEnabledKey); - NSUserDefaults.StandardUserDefaults.SetBool(true, InitializedNotificationSettingsKey); - } - return true; - } - - [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")] - public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler) - { - if (response.IsDefaultAction) - { - Console.WriteLine("ACTION: Default"); - } - if (response.IsDismissAction) - { - Console.WriteLine("ACTION: Dismiss"); - } - else - { - Console.WriteLine($"ACTION: {response.ActionIdentifier}"); - } - - completionHandler(); - } - - [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")] - public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler) - { - completionHandler(UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound); - } - - [Export("userNotificationCenter:openSettingsForNotification:")] - public void OpenSettings(UNUserNotificationCenter center, UNNotification notification) - { - var navigationController = Window.RootViewController as UINavigationController; - if (navigationController != null) - { - var currentViewController = navigationController.VisibleViewController; - if (currentViewController is ViewController) - { - currentViewController.PerformSegue(ManageNotificationsViewController.ShowManageNotificationsSegue, this); - } - } - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace RedGreenNotifications { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate, IUNUserNotificationCenterDelegate { + public const string InitializedNotificationSettingsKey = "InitializedNotificationSettings"; + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Request authorization to send notifications + UNUserNotificationCenter center = UNUserNotificationCenter.Current; + var options = UNAuthorizationOptions.ProvidesAppNotificationSettings | UNAuthorizationOptions.Alert | UNAuthorizationOptions.Sound | UNAuthorizationOptions.Provisional; + center.RequestAuthorization (options, (bool success, NSError error) => { + center.Delegate = this; + + var rotateTwentyDegreesAction = UNNotificationAction.FromIdentifier ("rotate-twenty-degrees-action", "Rotate 20°", UNNotificationActionOptions.None); + + var redCategory = UNNotificationCategory.FromIdentifier ( + "red-category", + new UNNotificationAction [] { rotateTwentyDegreesAction }, + new string [] { }, + UNNotificationCategoryOptions.CustomDismissAction + ); + + var greenCategory = UNNotificationCategory.FromIdentifier ( + "green-category", + new UNNotificationAction [] { rotateTwentyDegreesAction }, + new string [] { }, + UNNotificationCategoryOptions.CustomDismissAction + ); + + var set = new NSSet<UNNotificationCategory> (redCategory, greenCategory); + center.SetNotificationCategories (set); + }); + + // Initialize granular notification settings on first run + bool initializedNotificationSettings = NSUserDefaults.StandardUserDefaults.BoolForKey (InitializedNotificationSettingsKey); + if (!initializedNotificationSettings) { + NSUserDefaults.StandardUserDefaults.SetBool (true, ManageNotificationsViewController.RedNotificationsEnabledKey); + NSUserDefaults.StandardUserDefaults.SetBool (true, ManageNotificationsViewController.GreenNotificationsEnabledKey); + NSUserDefaults.StandardUserDefaults.SetBool (true, InitializedNotificationSettingsKey); + } + return true; + } + + [Export ("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")] + public void DidReceiveNotificationResponse (UNUserNotificationCenter center, UNNotificationResponse response, System.Action completionHandler) + { + if (response.IsDefaultAction) { + Console.WriteLine ("ACTION: Default"); + } + if (response.IsDismissAction) { + Console.WriteLine ("ACTION: Dismiss"); + } else { + Console.WriteLine ($"ACTION: {response.ActionIdentifier}"); + } + + completionHandler (); + } + + [Export ("userNotificationCenter:willPresentNotification:withCompletionHandler:")] + public void WillPresentNotification (UNUserNotificationCenter center, UNNotification notification, System.Action<UNNotificationPresentationOptions> completionHandler) + { + completionHandler (UNNotificationPresentationOptions.Alert | UNNotificationPresentationOptions.Sound); + } + + [Export ("userNotificationCenter:openSettingsForNotification:")] + public void OpenSettings (UNUserNotificationCenter center, UNNotification notification) + { + var navigationController = Window.RootViewController as UINavigationController; + if (navigationController != null) { + var currentViewController = navigationController.VisibleViewController; + if (currentViewController is ViewController) { + currentViewController.PerformSegue (ManageNotificationsViewController.ShowManageNotificationsSegue, this); + } + } + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios12/RedGreenNotifications/Main.cs b/ios12/RedGreenNotifications/Main.cs index 8f3899379..bfa1137d1 100644 --- a/ios12/RedGreenNotifications/Main.cs +++ b/ios12/RedGreenNotifications/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace RedGreenNotifications -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace RedGreenNotifications { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios12/RedGreenNotifications/ManageNotificationsViewController.cs b/ios12/RedGreenNotifications/ManageNotificationsViewController.cs index f2b6caa6d..75b54f924 100644 --- a/ios12/RedGreenNotifications/ManageNotificationsViewController.cs +++ b/ios12/RedGreenNotifications/ManageNotificationsViewController.cs @@ -1,86 +1,79 @@ -using Foundation; -using System; -using UIKit; -using UserNotifications; - -namespace RedGreenNotifications -{ - public partial class ManageNotificationsViewController : UIViewController - { - public const string RedNotificationsEnabledKey = "redNotificationsEnabledKey"; - public const string GreenNotificationsEnabledKey = "greenNotificationsEnabledKey"; - public const string ShowManageNotificationsSegue = "ShowManageNotificationsSegue"; +using Foundation; +using System; +using UIKit; +using UserNotifications; - NSObject observer; +namespace RedGreenNotifications { + public partial class ManageNotificationsViewController : UIViewController { + public const string RedNotificationsEnabledKey = "redNotificationsEnabledKey"; + public const string GreenNotificationsEnabledKey = "greenNotificationsEnabledKey"; + public const string ShowManageNotificationsSegue = "ShowManageNotificationsSegue"; - public ManageNotificationsViewController(IntPtr handle) : base(handle) { } + NSObject observer; - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - UpdateUserInterface(); - if (observer == null) - { - observer = NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.WillEnterForegroundNotification, HandleEnterForegroundNotification); - } - } - - public override void ViewDidDisappear(bool animated) - { - base.ViewDidDisappear(animated); - observer.Dispose(); - observer = null; - } + public ManageNotificationsViewController (IntPtr handle) : base (handle) { } - void HandleEnterForegroundNotification(NSNotification notification) - { - UpdateUserInterface(); - } + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + UpdateUserInterface (); + if (observer == null) { + observer = NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.WillEnterForegroundNotification, HandleEnterForegroundNotification); + } + } - partial void HandleRedNotificationsSwitchValueChange(UISwitch sender) - { - NSUserDefaults.StandardUserDefaults.SetBool(sender.On, RedNotificationsEnabledKey); - } - - partial void HandleGreenNotificationsSwitchValueChange(UISwitch sender) - { - NSUserDefaults.StandardUserDefaults.SetBool(sender.On, GreenNotificationsEnabledKey); - } - - async void UpdateUserInterface() - { - UNNotificationSettings settings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync(); - BeginInvokeOnMainThread(() => - { - if (settings.AuthorizationStatus == UNAuthorizationStatus.Authorized || settings.AuthorizationStatus == UNAuthorizationStatus.Provisional) - { - RedNotificationsSwitch.Enabled = true; - RedNotificationsSwitch.On = NSUserDefaults.StandardUserDefaults.BoolForKey(RedNotificationsEnabledKey); - RedNotificationsSwitch.Hidden = false; - RedNotificationsLabel.Hidden = false; - - GreenNotificationsSwitch.Enabled = true; - GreenNotificationsSwitch.On = NSUserDefaults.StandardUserDefaults.BoolForKey(GreenNotificationsEnabledKey); - GreenNotificationsSwitch.Hidden = false; - GreenNotificationsLabel.Hidden = false; - - ManageNotificationsStatusLabel.Text = ""; - } - else - { - RedNotificationsSwitch.Enabled = false; - RedNotificationsSwitch.On = false; - RedNotificationsSwitch.Hidden = true; - RedNotificationsLabel.Hidden = true; - - GreenNotificationsSwitch.Enabled = false; - GreenNotificationsSwitch.On = false; - GreenNotificationsSwitch.Hidden = true; - GreenNotificationsLabel.Hidden = true; - - ManageNotificationsStatusLabel.Text = "Enable notifications in Settings app."; - } - }); - } - } -} \ No newline at end of file + public override void ViewDidDisappear (bool animated) + { + base.ViewDidDisappear (animated); + observer.Dispose (); + observer = null; + } + + void HandleEnterForegroundNotification (NSNotification notification) + { + UpdateUserInterface (); + } + + partial void HandleRedNotificationsSwitchValueChange (UISwitch sender) + { + NSUserDefaults.StandardUserDefaults.SetBool (sender.On, RedNotificationsEnabledKey); + } + + partial void HandleGreenNotificationsSwitchValueChange (UISwitch sender) + { + NSUserDefaults.StandardUserDefaults.SetBool (sender.On, GreenNotificationsEnabledKey); + } + + async void UpdateUserInterface () + { + UNNotificationSettings settings = await UNUserNotificationCenter.Current.GetNotificationSettingsAsync (); + BeginInvokeOnMainThread (() => { + if (settings.AuthorizationStatus == UNAuthorizationStatus.Authorized || settings.AuthorizationStatus == UNAuthorizationStatus.Provisional) { + RedNotificationsSwitch.Enabled = true; + RedNotificationsSwitch.On = NSUserDefaults.StandardUserDefaults.BoolForKey (RedNotificationsEnabledKey); + RedNotificationsSwitch.Hidden = false; + RedNotificationsLabel.Hidden = false; + + GreenNotificationsSwitch.Enabled = true; + GreenNotificationsSwitch.On = NSUserDefaults.StandardUserDefaults.BoolForKey (GreenNotificationsEnabledKey); + GreenNotificationsSwitch.Hidden = false; + GreenNotificationsLabel.Hidden = false; + + ManageNotificationsStatusLabel.Text = ""; + } else { + RedNotificationsSwitch.Enabled = false; + RedNotificationsSwitch.On = false; + RedNotificationsSwitch.Hidden = true; + RedNotificationsLabel.Hidden = true; + + GreenNotificationsSwitch.Enabled = false; + GreenNotificationsSwitch.On = false; + GreenNotificationsSwitch.Hidden = true; + GreenNotificationsLabel.Hidden = true; + + ManageNotificationsStatusLabel.Text = "Enable notifications in Settings app."; + } + }); + } + } +} diff --git a/ios12/RedGreenNotifications/RedGreenNotificationsContentExtension/NotificationViewController.cs b/ios12/RedGreenNotifications/RedGreenNotificationsContentExtension/NotificationViewController.cs index e618c000b..b39088f8e 100644 --- a/ios12/RedGreenNotifications/RedGreenNotificationsContentExtension/NotificationViewController.cs +++ b/ios12/RedGreenNotifications/RedGreenNotificationsContentExtension/NotificationViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using UserNotifications; using UserNotificationsUI; @@ -6,92 +6,82 @@ using System.Drawing; using Foundation; -namespace RedGreenNotificationsContentExtension -{ - public partial class NotificationViewController : UIViewController, IUNNotificationContentExtension - { - int rotationButtonTaps = 0; - UNNotification notification; - - protected NotificationViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - } - - - public void DidReceiveNotification(UNNotification notification) - { - this.notification = notification; - if (notification.Request.Content.CategoryIdentifier == "red-category") - { - View.BackgroundColor = new UIColor(red: 0.55f, green: 0.00f, blue: 0.00f, alpha: 1.0f); - } - else - { - View.BackgroundColor = new UIColor(red: 0.40f, green: 0.47f, blue: 0.22f, alpha: 1.0f); - } - } - - [Export("didReceiveNotificationResponse:completionHandler:")] - public void DidReceiveNotificationResponse(UNNotificationResponse response, Action<UNNotificationContentExtensionResponseOption> completionHandler) - { - var rotationAction = ExtensionContext.GetNotificationActions()[0]; - - if (response.ActionIdentifier == "rotate-twenty-degrees-action") - { - rotationButtonTaps += 1; - - double radians = (20 * rotationButtonTaps) * (2 * Math.PI / 360.0); - Xamagon.Transform = CGAffineTransform.MakeRotation((float)radians); - - // 9 rotations * 20 degrees = 180 degrees. No reason to - // show the reset rotation button when the image is half - // or fully rotated. - if (rotationButtonTaps % 9 == 0) - { - ExtensionContext.SetNotificationActions(new UNNotificationAction[] { rotationAction }); - } - else if (rotationButtonTaps % 9 == 1) - { - var resetRotationAction = UNNotificationAction.FromIdentifier("reset-rotation-action", "Reset rotation", UNNotificationActionOptions.None); - ExtensionContext.SetNotificationActions(new UNNotificationAction[] { rotationAction, resetRotationAction }); - } - } - - if (response.ActionIdentifier == "reset-rotation-action") - { - rotationButtonTaps = 0; - - double radians = (20 * rotationButtonTaps) * (2 * Math.PI / 360.0); - Xamagon.Transform = CGAffineTransform.MakeRotation((float)radians); - - ExtensionContext.SetNotificationActions(new UNNotificationAction[] { rotationAction }); - } - - completionHandler(UNNotificationContentExtensionResponseOption.DoNotDismiss); - } - - partial void HandleLaunchAppButtonTap(UIButton sender) - { - ExtensionContext.PerformNotificationDefaultAction(); - } - - partial void HandleDismissNotificationButtonTap(UIButton sender) - { - ExtensionContext.DismissNotificationContentExtension(); - } - - partial void HandleRemoveNotificationButtonTap(UIButton sender) - { - ExtensionContext.DismissNotificationContentExtension(); - UNUserNotificationCenter.Current.RemoveDeliveredNotifications(new string[] { notification.Request.Identifier }); - } - - partial void HandleSliderValueChanged(UISlider sender) - { - Xamagon.Alpha = sender.Value; - } - } +namespace RedGreenNotificationsContentExtension { + public partial class NotificationViewController : UIViewController, IUNNotificationContentExtension { + int rotationButtonTaps = 0; + UNNotification notification; + + protected NotificationViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + } + + + public void DidReceiveNotification (UNNotification notification) + { + this.notification = notification; + if (notification.Request.Content.CategoryIdentifier == "red-category") { + View.BackgroundColor = new UIColor (red: 0.55f, green: 0.00f, blue: 0.00f, alpha: 1.0f); + } else { + View.BackgroundColor = new UIColor (red: 0.40f, green: 0.47f, blue: 0.22f, alpha: 1.0f); + } + } + + [Export ("didReceiveNotificationResponse:completionHandler:")] + public void DidReceiveNotificationResponse (UNNotificationResponse response, Action<UNNotificationContentExtensionResponseOption> completionHandler) + { + var rotationAction = ExtensionContext.GetNotificationActions () [0]; + + if (response.ActionIdentifier == "rotate-twenty-degrees-action") { + rotationButtonTaps += 1; + + double radians = (20 * rotationButtonTaps) * (2 * Math.PI / 360.0); + Xamagon.Transform = CGAffineTransform.MakeRotation ((float) radians); + + // 9 rotations * 20 degrees = 180 degrees. No reason to + // show the reset rotation button when the image is half + // or fully rotated. + if (rotationButtonTaps % 9 == 0) { + ExtensionContext.SetNotificationActions (new UNNotificationAction [] { rotationAction }); + } else if (rotationButtonTaps % 9 == 1) { + var resetRotationAction = UNNotificationAction.FromIdentifier ("reset-rotation-action", "Reset rotation", UNNotificationActionOptions.None); + ExtensionContext.SetNotificationActions (new UNNotificationAction [] { rotationAction, resetRotationAction }); + } + } + + if (response.ActionIdentifier == "reset-rotation-action") { + rotationButtonTaps = 0; + + double radians = (20 * rotationButtonTaps) * (2 * Math.PI / 360.0); + Xamagon.Transform = CGAffineTransform.MakeRotation ((float) radians); + + ExtensionContext.SetNotificationActions (new UNNotificationAction [] { rotationAction }); + } + + completionHandler (UNNotificationContentExtensionResponseOption.DoNotDismiss); + } + + partial void HandleLaunchAppButtonTap (UIButton sender) + { + ExtensionContext.PerformNotificationDefaultAction (); + } + + partial void HandleDismissNotificationButtonTap (UIButton sender) + { + ExtensionContext.DismissNotificationContentExtension (); + } + + partial void HandleRemoveNotificationButtonTap (UIButton sender) + { + ExtensionContext.DismissNotificationContentExtension (); + UNUserNotificationCenter.Current.RemoveDeliveredNotifications (new string [] { notification.Request.Identifier }); + } + + partial void HandleSliderValueChanged (UISlider sender) + { + Xamagon.Alpha = sender.Value; + } + } } diff --git a/ios12/RedGreenNotifications/ViewController.cs b/ios12/RedGreenNotifications/ViewController.cs index fdaa678bf..3421c957d 100644 --- a/ios12/RedGreenNotifications/ViewController.cs +++ b/ios12/RedGreenNotifications/ViewController.cs @@ -1,63 +1,57 @@ -using System; +using System; using UIKit; using Foundation; using UserNotifications; -namespace RedGreenNotifications -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) { } +namespace RedGreenNotifications { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + } - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + } - partial void HandleTapRedNotificationButton(UIButton sender) - { - bool redEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey(ManageNotificationsViewController.RedNotificationsEnabledKey); - if (redEnabled) - { - var content = new UNMutableNotificationContent() - { - Title = "Red Notification", - Body = "This is a red notification", - CategoryIdentifier = "red-category" - }; - var request = UNNotificationRequest.FromIdentifier( - Guid.NewGuid().ToString(), - content, - UNTimeIntervalNotificationTrigger.CreateTrigger(1, false) - ); - UNUserNotificationCenter.Current.AddNotificationRequest(request, null); - } - } + partial void HandleTapRedNotificationButton (UIButton sender) + { + bool redEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey (ManageNotificationsViewController.RedNotificationsEnabledKey); + if (redEnabled) { + var content = new UNMutableNotificationContent () { + Title = "Red Notification", + Body = "This is a red notification", + CategoryIdentifier = "red-category" + }; + var request = UNNotificationRequest.FromIdentifier ( + Guid.NewGuid ().ToString (), + content, + UNTimeIntervalNotificationTrigger.CreateTrigger (1, false) + ); + UNUserNotificationCenter.Current.AddNotificationRequest (request, null); + } + } - partial void HandleTapGreenNotificationButton(UIButton sender) - { - bool greenEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey(ManageNotificationsViewController.GreenNotificationsEnabledKey); - if (greenEnabled) - { - var content = new UNMutableNotificationContent() - { - Title = "Green Notification", - Body = "This is a green notification", - CategoryIdentifier = "green-category" - }; - var request = UNNotificationRequest.FromIdentifier( - Guid.NewGuid().ToString(), - content, - UNTimeIntervalNotificationTrigger.CreateTrigger(1, false) - ); - UNUserNotificationCenter.Current.AddNotificationRequest(request, null); - } - } - } + partial void HandleTapGreenNotificationButton (UIButton sender) + { + bool greenEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey (ManageNotificationsViewController.GreenNotificationsEnabledKey); + if (greenEnabled) { + var content = new UNMutableNotificationContent () { + Title = "Green Notification", + Body = "This is a green notification", + CategoryIdentifier = "green-category" + }; + var request = UNNotificationRequest.FromIdentifier ( + Guid.NewGuid ().ToString (), + content, + UNTimeIntervalNotificationTrigger.CreateTrigger (1, false) + ); + UNUserNotificationCenter.Current.AddNotificationRequest (request, null); + } + } + } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBox.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBox.cs index bf63be2e8..7f0473369 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBox.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBox.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreGraphics; using SceneKit; using OpenTK; @@ -8,15 +8,13 @@ using ARKit; using System.Linq; -namespace ScanningAndDetecting3DObjects -{ - internal class BoundingBox : SCNNode - { - internal static readonly NSString ScanPercentageUserKey = new NSString("ScanPercentage"); //typeof(value) == NSNumber wrapping a double in range [0. ... 100.] - internal static readonly NSString BoxExtentUserInfoKey = new NSString("BoxExtent"); //typeof(value) = SimpleBox<NVector3> - internal static readonly NSString ScanPercentageChangedNotificationName = new NSString("ScanPercentageChanged"); - internal static readonly NSString ExtentChangedNotificationName = new NSString("BoundingBoxExtentChanged"); - internal static readonly NSString PositionChangedNotificationName = new NSString("BoundingBoxPositionChanged"); +namespace ScanningAndDetecting3DObjects { + internal class BoundingBox : SCNNode { + internal static readonly NSString ScanPercentageUserKey = new NSString ("ScanPercentage"); //typeof(value) == NSNumber wrapping a double in range [0. ... 100.] + internal static readonly NSString BoxExtentUserInfoKey = new NSString ("BoxExtent"); //typeof(value) = SimpleBox<NVector3> + internal static readonly NSString ScanPercentageChangedNotificationName = new NSString ("ScanPercentageChanged"); + internal static readonly NSString ExtentChangedNotificationName = new NSString ("BoundingBoxExtentChanged"); + internal static readonly NSString PositionChangedNotificationName = new NSString ("BoundingBoxPositionChanged"); private double minSize = 0.1; @@ -24,46 +22,40 @@ internal class BoundingBox : SCNNode private double maxDistanceToFocusPoint = 0.05; - private NVector3 extent = new NVector3(0.1F, 0.1F, 0.1F); - internal NVector3 Extent - { + private NVector3 extent = new NVector3 (0.1F, 0.1F, 0.1F); + internal NVector3 Extent { get => extent; - set - { - extent = Max(value, minSize); - UpdateVisualization(); - var notification = NSNotification.FromName(ExtentChangedNotificationName, this, NSDictionary.FromObjectAndKey(new SimpleBox<NVector3>(extent), BoxExtentUserInfoKey)); - NSNotificationCenter.DefaultCenter.PostNotification(notification); + set { + extent = Max (value, minSize); + UpdateVisualization (); + var notification = NSNotification.FromName (ExtentChangedNotificationName, this, NSDictionary.FromObjectAndKey (new SimpleBox<NVector3> (extent), BoxExtentUserInfoKey)); + NSNotificationCenter.DefaultCenter.PostNotification (notification); } } - public override SCNVector3 Position - { + public override SCNVector3 Position { get => base.Position; - set - { - if (value.Distance(base.Position) > 0.001) - { - var notification = NSNotification.FromName(PositionChangedNotificationName, this); - NSNotificationCenter.DefaultCenter.PostNotification(notification); + set { + if (value.Distance (base.Position) > 0.001) { + var notification = NSNotification.FromName (PositionChangedNotificationName, this); + NSNotificationCenter.DefaultCenter.PostNotification (notification); } base.Position = value; } } - private NVector3 Max(NVector3 value, double min) + private NVector3 Max (NVector3 value, double min) { - return new NVector3((float)Math.Max(value.X, min), (float)Math.Max(value.Y, min), (float)Math.Max(value.Z, min)); + return new NVector3 ((float) Math.Max (value.X, min), (float) Math.Max (value.Y, min), (float) Math.Max (value.Z, min)); } - struct SideDrag - { + struct SideDrag { internal NMatrix4 PlaneTransform; internal BoundingBoxSide Side; internal SCNVector3 BeginWorldPos; internal NVector3 BeginExtent; - internal SideDrag(BoundingBoxSide side, NMatrix4 transform, SCNVector3 worldPosition, NVector3 extent) : this() + internal SideDrag (BoundingBoxSide side, NMatrix4 transform, SCNVector3 worldPosition, NVector3 extent) : this () { this.Side = side; this.PlaneTransform = transform; @@ -78,12 +70,12 @@ internal SideDrag(BoundingBoxSide side, NMatrix4 transform, SCNVector3 worldPosi private Wireframe wireframe; - private SCNNode sidesNode = new SCNNode(); - private Dictionary<BoundingBoxSide.PositionName, BoundingBoxSide> sides = new Dictionary<BoundingBoxSide.PositionName, BoundingBoxSide>(); + private SCNNode sidesNode = new SCNNode (); + private Dictionary<BoundingBoxSide.PositionName, BoundingBoxSide> sides = new Dictionary<BoundingBoxSide.PositionName, BoundingBoxSide> (); private UIColor color = Utilities.AppYellow; - private List<(Ray, NVector3)> cameraRaysAndHitLocations = new List<(Ray, NVector3)>(); + private List<(Ray, NVector3)> cameraRaysAndHitLocations = new List<(Ray, NVector3)> (); private int frameCounter = 0; @@ -97,196 +89,171 @@ internal SideDrag(BoundingBoxSide side, NMatrix4 transform, SCNVector3 worldPosi private NSObject notificationObserverHandle; - internal BoundingBox(ARSCNView sceneView) + internal BoundingBox (ARSCNView sceneView) { this.sceneView = sceneView; - base.Init(); + base.Init (); - notificationObserverHandle = NSNotificationCenter.DefaultCenter.AddObserver(Scan.ScanningStateChangedNotificationName, ScanningStateChanged); - UpdateVisualization(); + notificationObserverHandle = NSNotificationCenter.DefaultCenter.AddObserver (Scan.ScanningStateChangedNotificationName, ScanningStateChanged); + UpdateVisualization (); } - void ScanningStateChanged(NSNotification notification) + void ScanningStateChanged (NSNotification notification) { - var scanState = notification.UserInfo[Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; - if (scanState == null) - { + var scanState = notification.UserInfo [Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; + if (scanState == null) { return; } - switch (scanState.Value) - { - case Scan.ScanState.Ready: - case Scan.ScanState.DefineBoundingBox: - ResetCapturingProgress(); - foreach (var s in sides.Values) - { - s.Hidden = false; - } - break; - case Scan.ScanState.Scanning: - foreach (var s in sides.Values) - { - s.Hidden = false; - } - break; - case Scan.ScanState.AdjustingOrigin: - // Hide the sides while adjusting the origin - foreach (var s in sides.Values) - { - s.Hidden = true; - } - break; + switch (scanState.Value) { + case Scan.ScanState.Ready: + case Scan.ScanState.DefineBoundingBox: + ResetCapturingProgress (); + foreach (var s in sides.Values) { + s.Hidden = false; + } + break; + case Scan.ScanState.Scanning: + foreach (var s in sides.Values) { + s.Hidden = false; + } + break; + case Scan.ScanState.AdjustingOrigin: + // Hide the sides while adjusting the origin + foreach (var s in sides.Values) { + s.Hidden = true; + } + break; } } //Performance Note: O(pointCould.Points.Length^2) - internal void FitOverPointCloud(ARPointCloud pointCloud, NVector3 focusPoint) + internal void FitOverPointCloud (ARPointCloud pointCloud, NVector3 focusPoint) { - var filteredPoints = new List<NVector3>(); + var filteredPoints = new List<NVector3> (); - foreach (var point in pointCloud.Points) - { + foreach (var point in pointCloud.Points) { // Skip this point if it is more than maxDistanceToFocusPoint meters away from the focus point. - var distanceToFocusPoint = point.Minus(focusPoint).Length(); - if (distanceToFocusPoint > maxDistanceToFocusPoint) - { + var distanceToFocusPoint = point.Minus (focusPoint).Length (); + if (distanceToFocusPoint > maxDistanceToFocusPoint) { continue; } // Skip this point if it is an outlier (not at least 3 other points closer than 3 cm) var nearbyPoints = 0; - foreach (var otherPoint in pointCloud.Points) - { - if (otherPoint != point && point.Distance(otherPoint) < 0.03) - { + foreach (var otherPoint in pointCloud.Points) { + if (otherPoint != point && point.Distance (otherPoint) < 0.03) { ++nearbyPoints; - if (nearbyPoints >= 3) - { - filteredPoints.Append(point); + if (nearbyPoints >= 3) { + filteredPoints.Append (point); break; } } } } - if (filteredPoints.Count == 0) - { + if (filteredPoints.Count == 0) { return; } - var localMin = extent.Times(-0.5f); - var localMax = extent.Times(0.5f); + var localMin = extent.Times (-0.5f); + var localMax = extent.Times (0.5f); - foreach (var point in filteredPoints) - { + foreach (var point in filteredPoints) { // The bounding box is in local coordinates, so convert to local, too. - var localPointScnVector3 = ConvertPositionFromNode(new SCNVector3(point.X, point.Y, point.Z), null); - var localPoint = new NVector3(localPointScnVector3.X, localPointScnVector3.Y, localPointScnVector3.Z); - localMin = localMin.Min(localPoint); - localMax = localMax.Max(localPoint); + var localPointScnVector3 = ConvertPositionFromNode (new SCNVector3 (point.X, point.Y, point.Z), null); + var localPoint = new NVector3 (localPointScnVector3.X, localPointScnVector3.Y, localPointScnVector3.Z); + localMin = localMin.Min (localPoint); + localMax = localMax.Max (localPoint); } // Update the position & extent of the bounding box based on the new min and max values - Position = Position.Plus(localMin.Plus(localMax).Times(0.5f)); - Extent = localMax.Minus(localMin); + Position = Position.Plus (localMin.Plus (localMax).Times (0.5f)); + Extent = localMax.Minus (localMin); } - private void UpdateVisualization() + private void UpdateVisualization () { - UpdateSides(); - UpdateWireframe(); + UpdateSides (); + UpdateWireframe (); } - private void UpdateSides() + private void UpdateSides () { // When this method is called the first time, create the sides and them to the sideNodes - if (sides.Count != 6) - { - CreateSides(); - AddChildNode(sidesNode); + if (sides.Count != 6) { + CreateSides (); + AddChildNode (sidesNode); return; - } - else - { + } else { // Otherwise just update the geometry's size and position - foreach (var s in sides.Values) - { - s.UpdateBoundingBoxExtent(Extent); + foreach (var s in sides.Values) { + s.UpdateBoundingBoxExtent (Extent); } } } - private void CreateSides() + private void CreateSides () { - var allSides = new[] + var allSides = new [] { BoundingBoxSide.PositionName.Back, BoundingBoxSide.PositionName.Front, BoundingBoxSide.PositionName.Left, BoundingBoxSide.PositionName.Right, BoundingBoxSide.PositionName.Bottom, BoundingBoxSide.PositionName.Top }; - foreach (var position in allSides) - { - sides[position] = new BoundingBoxSide(position, Extent, color); - sidesNode.AddChildNode(sides[position]); + foreach (var position in allSides) { + sides [position] = new BoundingBoxSide (position, Extent, color); + sidesNode.AddChildNode (sides [position]); } } - private void UpdateWireframe() + private void UpdateWireframe () { // When this method is called the first time, create the wireframe and add as child node - if (wireframe == null) - { - wireframe = new Wireframe(Extent, color); - AddChildNode(wireframe); - } - else - { - wireframe.Update(Extent); + if (wireframe == null) { + wireframe = new Wireframe (Extent, color); + AddChildNode (wireframe); + } else { + wireframe.Update (Extent); } } - internal void StartSideDrag(CGPoint screenPos) + internal void StartSideDrag (CGPoint screenPos) { var camera = sceneView.PointOfView; - if (camera == null) - { + if (camera == null) { return; } // Check if the user is starting the drag on one of the sides. If so, pull/push that side - var options = new SCNHitTestOptions(); + var options = new SCNHitTestOptions (); options.RootNode = sidesNode; options.IgnoreHiddenNodes = false; - var hitResults = sceneView.HitTest(screenPos, options); + var hitResults = sceneView.HitTest (screenPos, options); - foreach (var result in hitResults) - { - if(result.Node.ParentNode is BoundingBoxSide side) - { - side.ShowZAxisExtensions(); + foreach (var result in hitResults) { + if (result.Node.ParentNode is BoundingBoxSide side) { + side.ShowZAxisExtensions (); - var sideNormalInWorld = ConvertVectorToNode(side.Normal, null).Normalized() - ConvertVectorToNode(SCNVector3.Zero, null); - var ray = new Ray(result.WorldCoordinates, sideNormalInWorld); - var transform = ray.DragPlaneTransform(camera.WorldPosition); + var sideNormalInWorld = ConvertVectorToNode (side.Normal, null).Normalized () - ConvertVectorToNode (SCNVector3.Zero, null); + var ray = new Ray (result.WorldCoordinates, sideNormalInWorld); + var transform = ray.DragPlaneTransform (camera.WorldPosition); - currentSideDrag = new SideDrag(side, transform, WorldPosition, Extent); + currentSideDrag = new SideDrag (side, transform, WorldPosition, Extent); HasBeenAdjustedByUser = true; return; } } } - internal void UpdateSideDrag(CGPoint screenPos) + internal void UpdateSideDrag (CGPoint screenPos) { - if (currentSideDrag.HasValue) - { + if (currentSideDrag.HasValue) { var drag = currentSideDrag.Value; // Compute a new position for this side of the bounding box based on the given screen position. - SCNVector3? hitPos = sceneView.UnprojectPointLocal(screenPos, drag.PlaneTransform); - if (hitPos != null) - { + SCNVector3? hitPos = sceneView.UnprojectPointLocal (screenPos, drag.PlaneTransform); + if (hitPos != null) { var movementAlongRay = hitPos.Value.X; // First column of the planeTransform is the ray along which the box @@ -295,10 +262,9 @@ internal void UpdateSideDrag(CGPoint screenPos) var originOffset = (drag.PlaneTransform.Column0 * (movementAlongRay / 2)).Xyz; - var extentOffset = drag.Side.DragAxis.Normal().Times(movementAlongRay); - var newExtent = drag.BeginExtent.Plus(extentOffset); - if (newExtent.X >= minSize && newExtent.Y >= minSize && newExtent.Z >= minSize) - { + var extentOffset = drag.Side.DragAxis.Normal ().Times (movementAlongRay); + var newExtent = drag.BeginExtent.Plus (extentOffset); + if (newExtent.X >= minSize && newExtent.Y >= minSize && newExtent.Z >= minSize) { // Push/pull a single side of the bounding box by a combination // of moving & changing the extent of the box WorldPosition = drag.BeginWorldPos + originOffset; @@ -308,61 +274,54 @@ internal void UpdateSideDrag(CGPoint screenPos) } } - internal void EndSideDrag() + internal void EndSideDrag () { - if (currentSideDrag.HasValue) - { - currentSideDrag.Value.Side.HideZAxisExtensions(); + if (currentSideDrag.HasValue) { + currentSideDrag.Value.Side.HideZAxisExtensions (); currentSideDrag = null; } } - BoundingBoxSide AncestralBoundingBox(SCNNode node) + BoundingBoxSide AncestralBoundingBox (SCNNode node) { - if (node.ParentNode == null) - { + if (node.ParentNode == null) { return null; } - if (node.ParentNode is BoundingBoxSide) - { + if (node.ParentNode is BoundingBoxSide) { return node.ParentNode as BoundingBoxSide; } - return AncestralBoundingBox(node); + return AncestralBoundingBox (node); } - internal void StartSidePlaneDrag(CGPoint screenPos) + internal void StartSidePlaneDrag (CGPoint screenPos) { var camera = sceneView.PointOfView; - if (camera == null) - { + if (camera == null) { return; } - var options = new SCNHitTestOptions - { + var options = new SCNHitTestOptions { RootNode = sidesNode, IgnoreChildNodes = false, IgnoreHiddenNodes = false }; - var hitResults = sceneView.HitTest(screenPos, options); + var hitResults = sceneView.HitTest (screenPos, options); - foreach (var result in hitResults) - { - var side = AncestralBoundingBox(result.Node); - if (side != null) - { - side.ShowYAxisExtensions(); - side.ShowXAxisExtensions(); - - var sideNormalInWorld = (ConvertVectorToNode(side.DragAxis.Normal().ToSCNVector3(), null) - ConvertVectorToNode(SCNVector3.Zero, null)).Normalized(); - var planeNormalRay = new Ray(result.WorldCoordinates, sideNormalInWorld); - var transform = planeNormalRay.DragPlaneTransform(camera); - - var offset = new NVector3(); - NVector3 hitPos = sceneView.Unproject(screenPos, transform); - offset = WorldPosition.Minus(hitPos); - currentSidePlaneDrag = new PlaneDrag(transform, offset); + foreach (var result in hitResults) { + var side = AncestralBoundingBox (result.Node); + if (side != null) { + side.ShowYAxisExtensions (); + side.ShowXAxisExtensions (); + + var sideNormalInWorld = (ConvertVectorToNode (side.DragAxis.Normal ().ToSCNVector3 (), null) - ConvertVectorToNode (SCNVector3.Zero, null)).Normalized (); + var planeNormalRay = new Ray (result.WorldCoordinates, sideNormalInWorld); + var transform = planeNormalRay.DragPlaneTransform (camera); + + var offset = new NVector3 (); + NVector3 hitPos = sceneView.Unproject (screenPos, transform); + offset = WorldPosition.Minus (hitPos); + currentSidePlaneDrag = new PlaneDrag (transform, offset); HasBeenAdjustedByUser = true; return; } @@ -370,171 +329,155 @@ internal void StartSidePlaneDrag(CGPoint screenPos) } - internal void UpdateSidePlaneDrag(CGPoint screenPos) + internal void UpdateSidePlaneDrag (CGPoint screenPos) { - if (!currentSidePlaneDrag.HasValue) - { + if (!currentSidePlaneDrag.HasValue) { return; } var drag = currentSidePlaneDrag.Value; - var hitPos = sceneView.Unproject(screenPos, drag.PlaneTransform); - WorldPosition = hitPos.Plus(drag.Offset).ToSCNVector3(); - SnapToHorizontalPlane(); + var hitPos = sceneView.Unproject (screenPos, drag.PlaneTransform); + WorldPosition = hitPos.Plus (drag.Offset).ToSCNVector3 (); + SnapToHorizontalPlane (); } - internal void EndSidePlaneDrag() + internal void EndSidePlaneDrag () { currentSidePlaneDrag = null; - HideExtensionsOnAllAxes(); + HideExtensionsOnAllAxes (); snappedToHorizontalPlane = false; } - private void HideExtensionsOnAllAxes() + private void HideExtensionsOnAllAxes () { - foreach (var side in sides.Values) - { - side.HideXAxisExtensions(); - side.HideYAxisExtensions(); - side.HideZAxisExtensions(); + foreach (var side in sides.Values) { + side.HideXAxisExtensions (); + side.HideYAxisExtensions (); + side.HideZAxisExtensions (); } } - internal void StartGroundPlaneDrag(CGPoint screenPos) + internal void StartGroundPlaneDrag (CGPoint screenPos) { - var dragPlane = WorldTransform.ToNMatrix4(); - var offset = new NVector3(); - var hitPos = sceneView.Unproject(screenPos, dragPlane); + var dragPlane = WorldTransform.ToNMatrix4 (); + var offset = new NVector3 (); + var hitPos = sceneView.Unproject (screenPos, dragPlane); - offset = WorldPosition.Minus(hitPos); + offset = WorldPosition.Minus (hitPos); - currentGroundPlaneDrag = new PlaneDrag(dragPlane, offset); + currentGroundPlaneDrag = new PlaneDrag (dragPlane, offset); HasBeenAdjustedByUser = true; } - internal void UpdateGroundPlaneDrag(CGPoint screenPos) + internal void UpdateGroundPlaneDrag (CGPoint screenPos) { - sides[BoundingBoxSide.PositionName.Bottom].ShowXAxisExtensions(); - sides[BoundingBoxSide.PositionName.Bottom].ShowYAxisExtensions(); + sides [BoundingBoxSide.PositionName.Bottom].ShowXAxisExtensions (); + sides [BoundingBoxSide.PositionName.Bottom].ShowYAxisExtensions (); - if (currentGroundPlaneDrag.HasValue) - { + if (currentGroundPlaneDrag.HasValue) { var drag = currentGroundPlaneDrag.Value; - var hitPos = sceneView.Unproject(screenPos, drag.PlaneTransform); + var hitPos = sceneView.Unproject (screenPos, drag.PlaneTransform); - WorldPosition = hitPos.Plus(drag.Offset).ToSCNVector3(); + WorldPosition = hitPos.Plus (drag.Offset).ToSCNVector3 (); } } - internal void EndGroundPlaneDrag() + internal void EndGroundPlaneDrag () { currentGroundPlaneDrag = null; - sides[BoundingBoxSide.PositionName.Bottom].HideXAxisExtensions(); - sides[BoundingBoxSide.PositionName.Bottom].HideYAxisExtensions(); + sides [BoundingBoxSide.PositionName.Bottom].HideXAxisExtensions (); + sides [BoundingBoxSide.PositionName.Bottom].HideYAxisExtensions (); } - internal bool IsHit(CGPoint screenPos) + internal bool IsHit (CGPoint screenPos) { - var options = new SCNHitTestOptions(); + var options = new SCNHitTestOptions (); options.RootNode = sidesNode; options.IgnoreHiddenNodes = false; - var hitResults = sceneView.HitTest(screenPos, options); - return hitResults.Any(r => r.Node.ParentNode is BoundingBoxSide); + var hitResults = sceneView.HitTest (screenPos, options); + return hitResults.Any (r => r.Node.ParentNode is BoundingBoxSide); } - private void ResetCapturingProgress() + private void ResetCapturingProgress () { - cameraRaysAndHitLocations.Clear(); - foreach (var side in sides.Values) - { - foreach (var tile in side.Tiles) - { + cameraRaysAndHitLocations.Clear (); + foreach (var side in sides.Values) { + foreach (var tile in side.Tiles) { tile.Captured = false; tile.Highlighted = false; - tile.UpdateVisualization(); + tile.UpdateVisualization (); } } } - internal void HighlightCurrentTitle() + internal void HighlightCurrentTitle () { var camera = sceneView.PointOfView; - if (camera != null || Contains(camera.WorldPosition)) - { + if (camera != null || Contains (camera.WorldPosition)) { return; } // Create a new hit test ray. A line segment defined by its start and end point // is used to hit test against bounding box tiles. The ray's length allows for // intersectins if the user is no more than five meters away from the bounding box - var ray = new Ray(camera, 5.0f); + var ray = new Ray (camera, 5.0f); - foreach (var side in sides.Values) - { - foreach (var tile in side.Tiles) - { - if (tile.Highlighted) - { + foreach (var side in sides.Values) { + foreach (var tile in side.Tiles) { + if (tile.Highlighted) { tile.Highlighted = false; } } } - var tileAndCoords = TileHitBy(ray); - if (tileAndCoords.HasValue) - { + var tileAndCoords = TileHitBy (ray); + if (tileAndCoords.HasValue) { var hitTile = tileAndCoords.Value.Item1; hitTile.Highlighted = true; } // Update the opacity of all tiles - foreach (var side in sides.Values) - { - foreach (var tile in side.Tiles) - { - tile.UpdateVisualization(); + foreach (var side in sides.Values) { + foreach (var tile in side.Tiles) { + tile.UpdateVisualization (); } } } - private (Tile, NVector3)? TileHitBy(Ray ray) + private (Tile, NVector3)? TileHitBy (Ray ray) { // Perform hit test with given ray - var options = new SCNHitTestOptions(); + var options = new SCNHitTestOptions (); options.IgnoreHiddenNodes = false; options.BoundingBoxOnly = true; // Immutable `Dictionary` is known defect. Until fix: - options.Dictionary[SCNHitTest.OptionSearchModeKey] = new NSNumber((int)SCNHitTestSearchMode.All); + options.Dictionary [SCNHitTest.OptionSearchModeKey] = new NSNumber ((int) SCNHitTestSearchMode.All); - var hitResults = sceneView.Scene.RootNode.HitTest(ray.Origin, ray.Direction, options); + var hitResults = sceneView.Scene.RootNode.HitTest (ray.Origin, ray.Direction, options); // We cannot just look at the first result because we might have hits with other than the tile geometries - foreach (var result in hitResults) - { - if (result.Node is Tile) - { + foreach (var result in hitResults) { + if (result.Node is Tile) { var tile = result.Node as Tile; var side = tile.ParentNode as BoundingBoxSide; - if (side == null || side.IsBusyUpdatingTiles) - { + if (side == null || side.IsBusyUpdatingTiles) { continue; } // Each ray should only hit one tile, so we can stop iterating through results if a hit was successful. - return (tile, result.WorldCoordinates.ToNVector3()); + return (tile, result.WorldCoordinates.ToNVector3 ()); } } return null; } - internal void UpdateCapturingProcess() + internal void UpdateCapturingProcess () { var camera = sceneView.PointOfView; - if (camera == null || Contains(camera.WorldPosition)) - { + if (camera == null || Contains (camera.WorldPosition)) { return; } @@ -542,85 +485,71 @@ internal void UpdateCapturingProcess() // Add new hit test rays at a lower frame rate to keep the list of previous rays // at a reasonable size. - if (frameCounter % 20 == 0) - { + if (frameCounter % 20 == 0) { frameCounter = 0; // Create a new hit test ray. A line segment defined by its start and end point // is used to hit test against bounding box tiles. The ray's length allows for // intersections if the user is no more than five meters away from the bounding box. - var currentRay = new Ray(camera, 5.0F); + var currentRay = new Ray (camera, 5.0F); // Only remember the ray if it hit the bounding box, // and the hit location is significantly different from all previous hit locations. - var tuple = TileHitBy(currentRay); - if (tuple.HasValue) - { + var tuple = TileHitBy (currentRay); + if (tuple.HasValue) { var hitLocation = tuple.Value.Item2; - if (HitLocationDifferentFromPreviousRayHitTests(hitLocation)) - { - cameraRaysAndHitLocations.Add((currentRay, hitLocation)); + if (HitLocationDifferentFromPreviousRayHitTests (hitLocation)) { + cameraRaysAndHitLocations.Add ((currentRay, hitLocation)); } } } // Update tiles at a frame rate that provides a trade-off between responsiveness and performance. - if (frameCounter % 10 != 0 || updatingCaptureProcess) - { + if (frameCounter % 10 != 0 || updatingCaptureProcess) { return; } updatingCaptureProcess = true; - var capturedTiles = new List<Tile>(); + var capturedTiles = new List<Tile> (); // Perform hit test with all previous rays. - foreach(var hitTest in cameraRaysAndHitLocations) - { - var tuple = TileHitBy(hitTest.Item1); - if (tuple.HasValue) - { + foreach (var hitTest in cameraRaysAndHitLocations) { + var tuple = TileHitBy (hitTest.Item1); + if (tuple.HasValue) { var tile = tuple.Value.Item1; - capturedTiles.Add(tile); + capturedTiles.Add (tile); tile.Captured = true; } } - foreach(var side in sides.Values) - { - foreach(var tile in side.Tiles) - { - if (! capturedTiles.Contains(tile)) - { + foreach (var side in sides.Values) { + foreach (var tile in side.Tiles) { + if (!capturedTiles.Contains (tile)) { tile.Captured = false; } } } // Update the opacity of all tiles - foreach (var side in sides.Values) - { - foreach (var tile in side.Tiles) - { - tile.UpdateVisualization(); + foreach (var side in sides.Values) { + foreach (var tile in side.Tiles) { + tile.UpdateVisualization (); } } // Update scan percentage for all sides, except the bottom var sum = 0.0; - foreach(var (pos, side) in sides) - { - if (pos != BoundingBoxSide.PositionName.Bottom) - { + foreach (var (pos, side) in sides) { + if (pos != BoundingBoxSide.PositionName.Bottom) { sum += side.Completion / 5.0; } } - var progressPercentage = (int)Math.Min((int)Math.Floor(sum * 100), 100); - if (progressPercentage != this.ProgressPercentage) - { + var progressPercentage = (int) Math.Min ((int) Math.Floor (sum * 100), 100); + if (progressPercentage != this.ProgressPercentage) { this.ProgressPercentage = progressPercentage; - var notification = NSNotification.FromName(BoundingBox.ScanPercentageChangedNotificationName, this, NSDictionary.FromObjectAndKey(new NSNumber(progressPercentage), BoundingBox.ScanPercentageUserKey)); - NSNotificationCenter.DefaultCenter.PostNotification(notification); + var notification = NSNotification.FromName (BoundingBox.ScanPercentageChangedNotificationName, this, NSDictionary.FromObjectAndKey (new NSNumber (progressPercentage), BoundingBox.ScanPercentageUserKey)); + NSNotificationCenter.DefaultCenter.PostNotification (notification); } updatingCaptureProcess = false; @@ -628,77 +557,68 @@ internal void UpdateCapturingProcess() // Returns true if the given location differs from all hit locations in the cameraRaysAndHitLocation collection // by at least the threshold differenec - private bool HitLocationDifferentFromPreviousRayHitTests(NVector3 location) + private bool HitLocationDifferentFromPreviousRayHitTests (NVector3 location) { var distThreshold = 0.03; // Clone cameraRaysAndHitLocations since Reverse() is in-place - var reversed = new List<(Ray, NVector3)>(cameraRaysAndHitLocations); - reversed.Reverse(); + var reversed = new List<(Ray, NVector3)> (cameraRaysAndHitLocations); + reversed.Reverse (); - foreach(var hitTest in reversed) - { - if (hitTest.Item2.Distance(location) < distThreshold) - { + foreach (var hitTest in reversed) { + if (hitTest.Item2.Distance (location) < distThreshold) { return false; } } return true; } - BoundingBoxSide[] SidesForAxis(Axis axis) + BoundingBoxSide [] SidesForAxis (Axis axis) { - switch (axis) - { - case Axis.X: return new[] { sides[BoundingBoxSide.PositionName.Left], sides[BoundingBoxSide.PositionName.Right] }; - case Axis.Y: return new[] { sides[BoundingBoxSide.PositionName.Top], sides[BoundingBoxSide.PositionName.Bottom] }; - case Axis.Z: return new[] { sides[BoundingBoxSide.PositionName.Front], sides[BoundingBoxSide.PositionName.Back] }; + switch (axis) { + case Axis.X: return new [] { sides [BoundingBoxSide.PositionName.Left], sides [BoundingBoxSide.PositionName.Right] }; + case Axis.Y: return new [] { sides [BoundingBoxSide.PositionName.Top], sides [BoundingBoxSide.PositionName.Bottom] }; + case Axis.Z: return new [] { sides [BoundingBoxSide.PositionName.Front], sides [BoundingBoxSide.PositionName.Back] }; } - throw new ArgumentOutOfRangeException("axis"); + throw new ArgumentOutOfRangeException ("axis"); } - internal void UpdateOnEveryFrame() + internal void UpdateOnEveryFrame () { var frame = sceneView.Session.CurrentFrame; - if (frame != null) - { - TryToAlignWithPlanes(frame.Anchors); + if (frame != null) { + TryToAlignWithPlanes (frame.Anchors); } - foreach(var side in sides.Values) - { - side.UpdateVisualizationIfNeeded(); + foreach (var side in sides.Values) { + side.UpdateVisualizationIfNeeded (); } } - internal void TryToAlignWithPlanes(ARAnchor[] anchors) + internal void TryToAlignWithPlanes (ARAnchor [] anchors) { - if (HasBeenAdjustedByUser || ViewController.Instance?.CurrentScan?.State == Scan.ScanState.DefineBoundingBox) - { + if (HasBeenAdjustedByUser || ViewController.Instance?.CurrentScan?.State == Scan.ScanState.DefineBoundingBox) { return; } - var bottomCenter = new SCNVector3(Position.X, Position.Y - Extent.Y / 2, Position.Z); + var bottomCenter = new SCNVector3 (Position.X, Position.Y - Extent.Y / 2, Position.Z); var distanceToNearestPlane = float.MaxValue; var offsetToNearestPlaneOnY = 0.0F; var planeFound = false; // Check which plane is nearest to the bounding box - foreach(var anchor in anchors) - { + foreach (var anchor in anchors) { var plane = anchor as ARPlaneAnchor; - if (plane == null) - { + if (plane == null) { continue; } - var planeNode = sceneView.GetNode(plane); - if (planeNode == null) - { + var planeNode = sceneView.GetNode (plane); + if (planeNode == null) { continue; } // Get the position of the bottom center of this bounding box in the plane's coordinate system - var bottomCenterInPlaneCoords = planeNode.ConvertPositionFromNode(bottomCenter, ParentNode); + var bottomCenterInPlaneCoords = planeNode.ConvertPositionFromNode (bottomCenter, ParentNode); // Add 10% tolerance to the corner of the plane. var tolerance = 0.1; @@ -707,56 +627,51 @@ internal void TryToAlignWithPlanes(ARAnchor[] anchors) var minZ = plane.Center.Z - plane.Extent.Z / 2 - plane.Extent.Z * tolerance; var maxZ = plane.Center.Z + plane.Extent.Z / 2 + plane.Extent.Z * tolerance; - if (bottomCenterInPlaneCoords.X < minX || bottomCenterInPlaneCoords.X > maxX + if (bottomCenterInPlaneCoords.X < minX || bottomCenterInPlaneCoords.X > maxX || bottomCenterInPlaneCoords.Z < minZ || bottomCenterInPlaneCoords.Z > minZ - ) - { + ) { continue; } var offsetToPlaneOnY = bottomCenterInPlaneCoords.Y; - var distanceToPlane = Math.Abs(offsetToPlaneOnY); + var distanceToPlane = Math.Abs (offsetToPlaneOnY); - if (distanceToPlane < distanceToNearestPlane) - { + if (distanceToPlane < distanceToNearestPlane) { distanceToNearestPlane = distanceToPlane; offsetToNearestPlaneOnY = offsetToPlaneOnY; planeFound = true; } } - if ( ! planeFound) - { + if (!planeFound) { return; } // Check that the object is not already on the nearest plane (closer than 1mm). var epsilon = 0.001; - if (distanceToNearestPlane <= epsilon) - { + if (distanceToNearestPlane <= epsilon) { return; } // Check if the nearest plane is close enough to the bounding box to "snap" to that // plane. The threshold is half of the bounding box extent on the y axis. var maxDistance = Extent.Y / 2; - if (distanceToNearestPlane < maxDistance && offsetToNearestPlaneOnY > 0) - { + if (distanceToNearestPlane < maxDistance && offsetToNearestPlaneOnY > 0) { // Adjust the bounding box position & extent such that the bottom of the box // aligns with the plane - Position = new SCNVector3(Position.X, Position.Y - offsetToNearestPlaneOnY / 2, Position.Z); + Position = new SCNVector3 (Position.X, Position.Y - offsetToNearestPlaneOnY / 2, Position.Z); // Note that assigning to Extent triggers additional behavior (see `set`) - Extent = new NVector3(Extent.X, Extent.Y + offsetToNearestPlaneOnY, Extent.Z); + Extent = new NVector3 (Extent.X, Extent.Y + offsetToNearestPlaneOnY, Extent.Z); } } - private bool Contains(SCNVector3 pointInWorld) + private bool Contains (SCNVector3 pointInWorld) { - var localMin = Extent.Times(-0.5F); - var localMax = Extent.Times(0.5F); + var localMin = Extent.Times (-0.5F); + var localMax = Extent.Times (0.5F); // The bounding box in local coordinates, so convert point to local, too. - var localPoint = ConvertPositionFromNode(pointInWorld, null); + var localPoint = ConvertPositionFromNode (pointInWorld, null); return localMin.X <= localPoint.X && localMax.X >= localPoint.X @@ -768,7 +683,7 @@ private bool Contains(SCNVector3 pointInWorld) - private void SnapToHorizontalPlane() + private void SnapToHorizontalPlane () { // Snap to align with horizontal plane if y-position is close enough var snapThreshold = 0.01; @@ -776,35 +691,29 @@ private void SnapToHorizontalPlane() var bottomY = WorldPosition.Y - Extent.Y / 2; var currentFrame = ViewController.Instance?.SceneView?.Session?.CurrentFrame; - if (currentFrame == null) - { + if (currentFrame == null) { return; } - foreach(var anyAnchor in currentFrame.Anchors) - { - if (anyAnchor is ARPlaneAnchor) - { + foreach (var anyAnchor in currentFrame.Anchors) { + if (anyAnchor is ARPlaneAnchor) { var anchor = anyAnchor as ARPlaneAnchor; - var distanceFromHorizontalPlane = Math.Abs(bottomY - anchor.Transform.Position().Y); + var distanceFromHorizontalPlane = Math.Abs (bottomY - anchor.Transform.Position ().Y); - if (distanceFromHorizontalPlane < snapThreshold) - { + if (distanceFromHorizontalPlane < snapThreshold) { withinSnapThreshold = true; - WorldPosition = new SCNVector3(WorldPosition.X, anchor.Transform.Position().Y + Extent.Y / 2, WorldPosition.Z); + WorldPosition = new SCNVector3 (WorldPosition.X, anchor.Transform.Position ().Y + Extent.Y / 2, WorldPosition.Z); // Provide haptic feedback when reaching the snapThreshold for the first time - if (!snappedToHorizontalPlane) - { + if (!snappedToHorizontalPlane) { snappedToHorizontalPlane = true; - Snapping.PlayHapticFeedback(); + Snapping.PlayHapticFeedback (); } } } } - if (! withinSnapThreshold) - { + if (!withinSnapThreshold) { snappedToHorizontalPlane = false; } } @@ -812,31 +721,27 @@ private void SnapToHorizontalPlane() // Dispose pattern for debugging purposes private bool disposed = false; - internal bool IsDisposed - { - get - { + internal bool IsDisposed { + get { return disposed; } } - override protected void Dispose(bool disposing) + override protected void Dispose (bool disposing) { - if (!disposed) - { + if (!disposed) { disposed = true; - if (disposing) - { - base.Dispose(); + if (disposing) { + base.Dispose (); } - NSNotificationCenter.DefaultCenter.RemoveObserver(notificationObserverHandle); -} + NSNotificationCenter.DefaultCenter.RemoveObserver (notificationObserverHandle); + } } - internal void Dispose() + internal void Dispose () { - Dispose(true); + Dispose (true); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBoxSide.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBoxSide.cs index f9d0de2c6..7a01081d0 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBoxSide.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/BoundingBoxSide.cs @@ -1,371 +1,342 @@ -using System; +using System; using System.Collections.Generic; using CoreGraphics; using OpenTK; using SceneKit; using UIKit; -using System.Linq; - -namespace ScanningAndDetecting3DObjects -{ - internal class BoundingBoxSide : SCNNode - { - internal enum PositionName - { - Front, - Back, - Left, - Right, - Bottom, - Top - } - - // The bounding box face that is represented by this node - private PositionName face; - - internal bool IsBusyUpdatingTiles { - get; - private set; - } - - // The completion of this side in range [0,1] - internal double Completion { - get { - if (Tiles.Count == 0) - { - return 0; - } - var capturedTiles = Tiles.FindAll(t => t.Captured); - return (double)capturedTiles.Count / Tiles.Count; - } +using System.Linq; + +namespace ScanningAndDetecting3DObjects { + internal class BoundingBoxSide : SCNNode { + internal enum PositionName { + Front, + Back, + Left, + Right, + Bottom, + Top + } + + // The bounding box face that is represented by this node + private PositionName face; + + internal bool IsBusyUpdatingTiles { + get; + private set; + } + + // The completion of this side in range [0,1] + internal double Completion { + get { + if (Tiles.Count == 0) { + return 0; + } + var capturedTiles = Tiles.FindAll (t => t.Captured); + return (double) capturedTiles.Count / Tiles.Count; + } } - + // The normal vector of this side. - internal SCNVector3 Normal - { - get - { - switch (face) - { - case PositionName.Front: - case PositionName.Right: - case PositionName.Top: - return DragAxis.Normal().ToSCNVector3(); - case PositionName.Back: - case PositionName.Left: - case PositionName.Bottom: - return -DragAxis.Normal().ToSCNVector3(); - } - throw new ArgumentOutOfRangeException(); - } - } - - // The drag axis for this side - internal Axis DragAxis { - get - { - switch(face) - { - case PositionName.Left : - case PositionName.Right : - return Axis.X; - case PositionName.Bottom : - case PositionName.Top : - return Axis.Y; - case PositionName.Front : - case PositionName.Back : - return Axis.Z; - } - throw new ArgumentOutOfRangeException(); - } + internal SCNVector3 Normal { + get { + switch (face) { + case PositionName.Front: + case PositionName.Right: + case PositionName.Top: + return DragAxis.Normal ().ToSCNVector3 (); + case PositionName.Back: + case PositionName.Left: + case PositionName.Bottom: + return -DragAxis.Normal ().ToSCNVector3 (); + } + throw new ArgumentOutOfRangeException (); + } } - + + // The drag axis for this side + internal Axis DragAxis { + get { + switch (face) { + case PositionName.Left: + case PositionName.Right: + return Axis.X; + case PositionName.Bottom: + case PositionName.Top: + return Axis.Y; + case PositionName.Front: + case PositionName.Back: + return Axis.Z; + } + throw new ArgumentOutOfRangeException (); + } + } + // The tiles of this side - internal List<Tile> Tiles - { + internal List<Tile> Tiles { get; - private set; - } - - private CGSize size = CGSize.Empty; - private readonly UIColor color = Utilities.AppYellow; - - // Maximum width or height of a tile. If the size of the side exceeds this value, a new row or column is added - private const double maxTileSize = 0.1; - - // Maximum number of tiles per row / column - private const int maxTileCount = 4; - - private const double lineThickness = 0.002; - private const double extensionLength = 0.05; - - // The size of the bounding box side when the tiles were updated the last time - private CGSize sizeOnLastTileUpdate = CGSize.Empty; - - private bool TilesNeedUpdateForChangedSize => sizeOnLastTileUpdate != size; - - private readonly SCNNode xAxisExtNode = new SCNNode(); - private readonly List<SCNNode> xAxisExtLines = new List<SCNNode>(); - private readonly SCNNode yAxisExtNode = new SCNNode(); - private readonly List<SCNNode> yAxisExtLines = new List<SCNNode>(); - private readonly SCNNode zAxisExtNode = new SCNNode(); - private readonly List<SCNNode> zAxisExtLines = new List<SCNNode>(); - - - internal BoundingBoxSide(PositionName position, NVector3 extent, UIColor color = null) : base() - { - if (color == null) - { - color = Utilities.AppYellow; - } - Tiles = new List<Tile>(); - this.color = color; + private set; + } + + private CGSize size = CGSize.Empty; + private readonly UIColor color = Utilities.AppYellow; + + // Maximum width or height of a tile. If the size of the side exceeds this value, a new row or column is added + private const double maxTileSize = 0.1; + + // Maximum number of tiles per row / column + private const int maxTileCount = 4; + + private const double lineThickness = 0.002; + private const double extensionLength = 0.05; + + // The size of the bounding box side when the tiles were updated the last time + private CGSize sizeOnLastTileUpdate = CGSize.Empty; + + private bool TilesNeedUpdateForChangedSize => sizeOnLastTileUpdate != size; + + private readonly SCNNode xAxisExtNode = new SCNNode (); + private readonly List<SCNNode> xAxisExtLines = new List<SCNNode> (); + private readonly SCNNode yAxisExtNode = new SCNNode (); + private readonly List<SCNNode> yAxisExtLines = new List<SCNNode> (); + private readonly SCNNode zAxisExtNode = new SCNNode (); + private readonly List<SCNNode> zAxisExtLines = new List<SCNNode> (); + + + internal BoundingBoxSide (PositionName position, NVector3 extent, UIColor color = null) : base () + { + if (color == null) { + color = Utilities.AppYellow; + } + Tiles = new List<Tile> (); + this.color = color; this.face = position; // inline Swift setup() and setupExtensions() functions - size = Size(extent); - - var yAxis = Axis.Y.Normal().ToSCNVector3(); - var xAxis = Axis.X.Normal().ToSCNVector3(); - var zAxis = Axis.Z.Normal().ToSCNVector3(); - float halfTurn = (float)Math.PI; - float quarterTurn = (float)Math.PI / 2; - - switch(face) - { - case PositionName.Front : - LocalTranslate(new SCNVector3(0, 0, extent.Z / 2)); - break; - case PositionName.Back : - LocalTranslate(new SCNVector3(0, 0, -extent.Z / 2)); - LocalRotate(SCNQuaternion.FromAxisAngle(yAxis, halfTurn)); - break; - case PositionName.Left : - LocalTranslate(new SCNVector3(-extent.X / 2, 0, 0)); - LocalRotate(SCNQuaternion.FromAxisAngle(yAxis, -quarterTurn)); - break; - case PositionName.Right : - LocalTranslate(new SCNVector3(extent.X / 2, 0, 0)); - LocalRotate(SCNQuaternion.FromAxisAngle(yAxis, quarterTurn)); - break; - case PositionName.Bottom : - LocalTranslate(new SCNVector3(0, -extent.Y / 2, 0)); - LocalRotate(SCNQuaternion.FromAxisAngle(xAxis, halfTurn)); - break; - case PositionName.Top : - LocalTranslate(new SCNVector3(0, extent.Y / 2, 0)); - LocalRotate(SCNQuaternion.FromAxisAngle(xAxis, -quarterTurn)); - break; - } - - for (int index = 0; index < 12; index++) - { - var line = new SCNNode(); - line.Geometry = Cylinder(lineThickness, extensionLength); - if (index < 4) - { - xAxisExtLines.Add(line); - line.LocalRotate(SCNQuaternion.FromAxisAngle(zAxis, -quarterTurn)); - if (index == 2 || index == 3) - { - line.LocalRotate(SCNQuaternion.FromAxisAngle(xAxis, halfTurn)); - } - xAxisExtNode.AddChildNode(line); - } - else if (index < 8) - { - yAxisExtLines.Add(line); - if (index == 5 || index == 7) - { - line.LocalRotate(SCNQuaternion.FromAxisAngle(xAxis, halfTurn)); - } - yAxisExtNode.AddChildNode(line); - } - else - { - zAxisExtLines.Add(line); - line.LocalRotate(SCNQuaternion.FromAxisAngle(xAxis, -quarterTurn)); - zAxisExtNode.AddChildNode(line); - } - } - - UpdateExtensions(); - HideXAxisExtensions(); - HideYAxisExtensions(); - HideZAxisExtensions(); - - AddChildNode(xAxisExtNode); - AddChildNode(yAxisExtNode); - AddChildNode(zAxisExtNode); + size = Size (extent); + + var yAxis = Axis.Y.Normal ().ToSCNVector3 (); + var xAxis = Axis.X.Normal ().ToSCNVector3 (); + var zAxis = Axis.Z.Normal ().ToSCNVector3 (); + float halfTurn = (float) Math.PI; + float quarterTurn = (float) Math.PI / 2; + + switch (face) { + case PositionName.Front: + LocalTranslate (new SCNVector3 (0, 0, extent.Z / 2)); + break; + case PositionName.Back: + LocalTranslate (new SCNVector3 (0, 0, -extent.Z / 2)); + LocalRotate (SCNQuaternion.FromAxisAngle (yAxis, halfTurn)); + break; + case PositionName.Left: + LocalTranslate (new SCNVector3 (-extent.X / 2, 0, 0)); + LocalRotate (SCNQuaternion.FromAxisAngle (yAxis, -quarterTurn)); + break; + case PositionName.Right: + LocalTranslate (new SCNVector3 (extent.X / 2, 0, 0)); + LocalRotate (SCNQuaternion.FromAxisAngle (yAxis, quarterTurn)); + break; + case PositionName.Bottom: + LocalTranslate (new SCNVector3 (0, -extent.Y / 2, 0)); + LocalRotate (SCNQuaternion.FromAxisAngle (xAxis, halfTurn)); + break; + case PositionName.Top: + LocalTranslate (new SCNVector3 (0, extent.Y / 2, 0)); + LocalRotate (SCNQuaternion.FromAxisAngle (xAxis, -quarterTurn)); + break; + } + + for (int index = 0; index < 12; index++) { + var line = new SCNNode (); + line.Geometry = Cylinder (lineThickness, extensionLength); + if (index < 4) { + xAxisExtLines.Add (line); + line.LocalRotate (SCNQuaternion.FromAxisAngle (zAxis, -quarterTurn)); + if (index == 2 || index == 3) { + line.LocalRotate (SCNQuaternion.FromAxisAngle (xAxis, halfTurn)); + } + xAxisExtNode.AddChildNode (line); + } else if (index < 8) { + yAxisExtLines.Add (line); + if (index == 5 || index == 7) { + line.LocalRotate (SCNQuaternion.FromAxisAngle (xAxis, halfTurn)); + } + yAxisExtNode.AddChildNode (line); + } else { + zAxisExtLines.Add (line); + line.LocalRotate (SCNQuaternion.FromAxisAngle (xAxis, -quarterTurn)); + zAxisExtNode.AddChildNode (line); + } + } + + UpdateExtensions (); + HideXAxisExtensions (); + HideYAxisExtensions (); + HideZAxisExtensions (); + + AddChildNode (xAxisExtNode); + AddChildNode (yAxisExtNode); + AddChildNode (zAxisExtNode); } - private SCNGeometry Cylinder(double width, double height) - { - var cylinderGeometry = SCNCylinder.Create((nfloat) width / 2, (nfloat) height); - var gradYellowMat = Utilities.Material(UIImage.FromBundle("yellowimage")); - var clearMaterial = Utilities.Material(UIColor.Clear); - cylinderGeometry.Materials = new[] { gradYellowMat, clearMaterial, clearMaterial }; + private SCNGeometry Cylinder (double width, double height) + { + var cylinderGeometry = SCNCylinder.Create ((nfloat) width / 2, (nfloat) height); + var gradYellowMat = Utilities.Material (UIImage.FromBundle ("yellowimage")); + var clearMaterial = Utilities.Material (UIColor.Clear); + cylinderGeometry.Materials = new [] { gradYellowMat, clearMaterial, clearMaterial }; return cylinderGeometry; } - private void UpdateExtensions() + private void UpdateExtensions () { - if ( xAxisExtLines.Count != 4 || yAxisExtLines.Count != 4 || zAxisExtLines.Count != 4) - { - return; - } - - var halfWidth = (float) size.Width / 2; - var halfHeight = (float) size.Height / 2; - var halfLength = (float) extensionLength / 2; - - xAxisExtLines[0].Position = new SCNVector3(-halfWidth - halfLength, -halfHeight, 0); - yAxisExtLines[0].Position = new SCNVector3(-halfWidth, -halfHeight - halfLength, 0); - zAxisExtLines[0].Position = new SCNVector3(-halfWidth, -halfHeight, halfLength); - - xAxisExtLines[1].Position = new SCNVector3(-halfWidth - halfLength, halfHeight, 0); - yAxisExtLines[1].Position = new SCNVector3(-halfWidth, halfHeight + halfLength, 0); - zAxisExtLines[1].Position = new SCNVector3(-halfWidth, halfHeight, halfLength); - - xAxisExtLines[2].Position = new SCNVector3(halfWidth + halfLength, -halfHeight, 0); - yAxisExtLines[2].Position = new SCNVector3(halfWidth, -halfHeight - halfLength, 0); - zAxisExtLines[2].Position = new SCNVector3(halfWidth, -halfHeight, halfLength); - - xAxisExtLines[3].Position = new SCNVector3(halfWidth + halfLength, halfHeight, 0); - yAxisExtLines[3].Position = new SCNVector3(halfWidth, halfHeight + halfLength, 0); - zAxisExtLines[3].Position = new SCNVector3(halfWidth, halfHeight, halfLength); + if (xAxisExtLines.Count != 4 || yAxisExtLines.Count != 4 || zAxisExtLines.Count != 4) { + return; + } + + var halfWidth = (float) size.Width / 2; + var halfHeight = (float) size.Height / 2; + var halfLength = (float) extensionLength / 2; + + xAxisExtLines [0].Position = new SCNVector3 (-halfWidth - halfLength, -halfHeight, 0); + yAxisExtLines [0].Position = new SCNVector3 (-halfWidth, -halfHeight - halfLength, 0); + zAxisExtLines [0].Position = new SCNVector3 (-halfWidth, -halfHeight, halfLength); + + xAxisExtLines [1].Position = new SCNVector3 (-halfWidth - halfLength, halfHeight, 0); + yAxisExtLines [1].Position = new SCNVector3 (-halfWidth, halfHeight + halfLength, 0); + zAxisExtLines [1].Position = new SCNVector3 (-halfWidth, halfHeight, halfLength); + + xAxisExtLines [2].Position = new SCNVector3 (halfWidth + halfLength, -halfHeight, 0); + yAxisExtLines [2].Position = new SCNVector3 (halfWidth, -halfHeight - halfLength, 0); + zAxisExtLines [2].Position = new SCNVector3 (halfWidth, -halfHeight, halfLength); + + xAxisExtLines [3].Position = new SCNVector3 (halfWidth + halfLength, halfHeight, 0); + yAxisExtLines [3].Position = new SCNVector3 (halfWidth, halfHeight + halfLength, 0); + zAxisExtLines [3].Position = new SCNVector3 (halfWidth, halfHeight, halfLength); } - private CGSize Size(NVector3 extent) + private CGSize Size (NVector3 extent) { - switch (face) - { - case PositionName.Front : - case PositionName. Back: - return new CGSize(extent.X, extent.Y); - case PositionName.Left : - case PositionName.Right : - return new CGSize(extent.Z, extent.Y); - case PositionName.Bottom : - case PositionName.Top : - return new CGSize(extent.X, extent.Z); - - } - throw new Exception("Somehow fell through switch statement that should be exhaustive."); + switch (face) { + case PositionName.Front: + case PositionName.Back: + return new CGSize (extent.X, extent.Y); + case PositionName.Left: + case PositionName.Right: + return new CGSize (extent.Z, extent.Y); + case PositionName.Bottom: + case PositionName.Top: + return new CGSize (extent.X, extent.Z); + + } + throw new Exception ("Somehow fell through switch statement that should be exhaustive."); } - internal void UpdateBoundingBoxExtent(NVector3 extent) + internal void UpdateBoundingBoxExtent (NVector3 extent) { - switch (face) - { - case PositionName.Front : - Position = new SCNVector3(0, 0, extent.Z / 2); - break; - case PositionName.Back : - Position = new SCNVector3(0, 0, -extent.Z / 2); - break; - case PositionName.Left : - Position = new SCNVector3(-extent.X / 2, 0, 0); - break; - case PositionName.Right : - Position = new SCNVector3(extent.X / 2, 0, 0); - break; - case PositionName.Bottom : - Position = new SCNVector3(0, -extent.Y / 2, 0); - break; - case PositionName.Top : - Position = new SCNVector3(0, extent.Y / 2, 0); - break; + switch (face) { + case PositionName.Front: + Position = new SCNVector3 (0, 0, extent.Z / 2); + break; + case PositionName.Back: + Position = new SCNVector3 (0, 0, -extent.Z / 2); + break; + case PositionName.Left: + Position = new SCNVector3 (-extent.X / 2, 0, 0); + break; + case PositionName.Right: + Position = new SCNVector3 (extent.X / 2, 0, 0); + break; + case PositionName.Bottom: + Position = new SCNVector3 (0, -extent.Y / 2, 0); + break; + case PositionName.Top: + Position = new SCNVector3 (0, extent.Y / 2, 0); + break; } // Update extensions if the size has changed. - var newSize = Size(extent); - if (newSize != size) - { - size = newSize; - UpdateExtensions(); - } + var newSize = Size (extent); + if (newSize != size) { + size = newSize; + UpdateExtensions (); + } } - internal void ShowZAxisExtensions() + internal void ShowZAxisExtensions () { zAxisExtNode.Hidden = false; } - internal void HideZAxisExtensions() + internal void HideZAxisExtensions () { zAxisExtNode.Hidden = true; } - internal void ShowYAxisExtensions() + internal void ShowYAxisExtensions () { yAxisExtNode.Hidden = false; - } - - internal void HideYAxisExtensions() - { - yAxisExtNode.Hidden = true; } - internal void ShowXAxisExtensions() + internal void HideYAxisExtensions () + { + yAxisExtNode.Hidden = true; + } + + internal void ShowXAxisExtensions () { xAxisExtNode.Hidden = false; } - internal void HideXAxisExtensions() + internal void HideXAxisExtensions () { xAxisExtNode.Hidden = true; } - internal void UpdateVisualizationIfNeeded() + internal void UpdateVisualizationIfNeeded () { - if (! IsBusyUpdatingTiles && TilesNeedUpdateForChangedSize) - { - SetupTiles(); + if (!IsBusyUpdatingTiles && TilesNeedUpdateForChangedSize) { + SetupTiles (); } } - private void SetupTiles() + private void SetupTiles () { IsBusyUpdatingTiles = true; // Determine number of rows and columns - var numRows = Math.Min(maxTileCount, (int) (Math.Ceiling(size.Height / maxTileSize))); - var numColumns = Math.Min(maxTileCount, (int)(Math.Ceiling(size.Width / maxTileSize))); - - var newTiles = new List<Tile>(); + var numRows = Math.Min (maxTileCount, (int) (Math.Ceiling (size.Height / maxTileSize))); + var numColumns = Math.Min (maxTileCount, (int) (Math.Ceiling (size.Width / maxTileSize))); + + var newTiles = new List<Tile> (); // Create updates tiles and lay them out - for (var row = 0; row < numRows; row++) - { - for (var col = 0; col < numColumns; col++) - { - var plane = SCNPlane.Create(size.Width / numColumns, size.Height / numRows); - plane.Materials = new[] { Utilities.Material(color, false, false) }; - - var xPos = -size.Width / 2 + plane.Width / 2 + col * plane.Width; - var yPos = size.Height / 2 - plane.Height / 2 - row * plane.Height; - - var tileNode = new Tile(plane); - tileNode.Position = new SCNVector3((float)xPos, (float)yPos, 0); - newTiles.Add(tileNode); - } - } - - // Replace the nodes in the scene graph. - foreach(var tile in Tiles) - { - tile.RemoveFromParentNode(); - } - foreach(var tile in newTiles) - { - AddChildNode(tile); - } - Tiles = newTiles; - - sizeOnLastTileUpdate = size; + for (var row = 0; row < numRows; row++) { + for (var col = 0; col < numColumns; col++) { + var plane = SCNPlane.Create (size.Width / numColumns, size.Height / numRows); + plane.Materials = new [] { Utilities.Material (color, false, false) }; + + var xPos = -size.Width / 2 + plane.Width / 2 + col * plane.Width; + var yPos = size.Height / 2 - plane.Height / 2 - row * plane.Height; + + var tileNode = new Tile (plane); + tileNode.Position = new SCNVector3 ((float) xPos, (float) yPos, 0); + newTiles.Add (tileNode); + } + } + + // Replace the nodes in the scene graph. + foreach (var tile in Tiles) { + tile.RemoveFromParentNode (); + } + foreach (var tile in newTiles) { + AddChildNode (tile); + } + Tiles = newTiles; + + sizeOnLastTileUpdate = size; IsBusyUpdatingTiles = false; } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedBoundingBox.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedBoundingBox.cs index 164479540..eaa0d741e 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedBoundingBox.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedBoundingBox.cs @@ -1,37 +1,33 @@ -using System; +using System; using System.Collections.Generic; using OpenTK; using SceneKit; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // A simple visualization of a 3D bounding box, used when testing detection of a scanned object - internal class DetectedBoundingBox : SCNNode - { - internal DetectedBoundingBox(NVector3[] points, double scale, UIColor color = null) : base() + internal class DetectedBoundingBox : SCNNode { + internal DetectedBoundingBox (NVector3 [] points, double scale, UIColor color = null) : base () { // Cannot use asset-group defined color as default in args (since not compile-time constant), // so assign it now if default - if (color == null) - { + if (color == null) { color = Utilities.AppYellow; } - var localMin = new SCNVector3(float.MaxValue, float.MaxValue, float.MaxValue); - var localMax = new SCNVector3(float.MinValue, float.MinValue, float.MinValue); + var localMin = new SCNVector3 (float.MaxValue, float.MaxValue, float.MaxValue); + var localMax = new SCNVector3 (float.MinValue, float.MinValue, float.MinValue); - foreach(var point in points) - { - var scnVector = point.ToSCNVector3(); - localMin = localMin.Min(scnVector); - localMax = localMax.Max(scnVector); + foreach (var point in points) { + var scnVector = point.ToSCNVector3 (); + localMin = localMin.Min (scnVector); + localMax = localMax.Max (scnVector); } Position = Position + (localMax + localMin) / 2; var extent = localMax - localMin; - var wireframe = new Wireframe(extent.ToNVector3(), color, scale); - AddChildNode(wireframe); + var wireframe = new Wireframe (extent.ToNVector3 (), color, scale); + AddChildNode (wireframe); } } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedObject.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedObject.cs index 1740ee0d5..54e290959 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedObject.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedObject.cs @@ -1,15 +1,13 @@ -using System; +using System; using ARKit; using Foundation; using OpenTK; using SceneKit; -namespace ScanningAndDetecting3DObjects -{ - internal class DetectedObject : SCNNode - { +namespace ScanningAndDetecting3DObjects { + internal class DetectedObject : SCNNode { // How long, in seconds, this visualization is displayed after an update - private TimeSpan displayDuration = new TimeSpan((long)(1.5 * TimeSpan.TicksPerSecond)); + private TimeSpan displayDuration = new TimeSpan ((long) (1.5 * TimeSpan.TicksPerSecond)); private NSTimer detectedObjectVisualizationTimer; @@ -22,101 +20,89 @@ internal class DetectedObject : SCNNode private ARReferenceObject referenceObject; - internal DetectedObject(ARReferenceObject referenceObject) : base() + internal DetectedObject (ARReferenceObject referenceObject) : base () { this.referenceObject = referenceObject; - pointCloudVisualization = new DetectedPointCloud(referenceObject.RawFeaturePoints, referenceObject.Center, referenceObject.Extent); - var scene = SCNScene.FromFile("axes.scn", "art.scnassets", new NSDictionary()); - if (scene != null) - { - originVis = new SCNNode(); - foreach(var child in scene.RootNode.ChildNodes) - { - originVis.AddChildNode(child); + pointCloudVisualization = new DetectedPointCloud (referenceObject.RawFeaturePoints, referenceObject.Center, referenceObject.Extent); + var scene = SCNScene.FromFile ("axes.scn", "art.scnassets", new NSDictionary ()); + if (scene != null) { + originVis = new SCNNode (); + foreach (var child in scene.RootNode.ChildNodes) { + originVis.AddChildNode (child); } - } - else - { - originVis = new SCNNode(); - Console.WriteLine("Error: Coordinate system visualization missing."); + } else { + originVis = new SCNNode (); + Console.WriteLine ("Error: Coordinate system visualization missing."); } - AddChildNode(pointCloudVisualization); + AddChildNode (pointCloudVisualization); Hidden = true; - Set3DModel(ViewController.Instance?.ModelUrl); + Set3DModel (ViewController.Instance?.ModelUrl); } - internal void Set3DModel(NSUrl modelUrl) + internal void Set3DModel (NSUrl modelUrl) { var url = modelUrl; SCNNode model = null; - if (url != null) - { - model = Utilities.Load3DModel(url); + if (url != null) { + model = Utilities.Load3DModel (url); } - if (url != null && model != null) - { + if (url != null && model != null) { - customModel?.RemoveFromParentNode(); - customModel?.Dispose(); + customModel?.RemoveFromParentNode (); + customModel?.Dispose (); customModel = null; - originVis.RemoveFromParentNode(); - ViewController.Instance?.SceneView?.Prepare(model, () => - { - AddChildNode(model); + originVis.RemoveFromParentNode (); + ViewController.Instance?.SceneView?.Prepare (model, () => { + AddChildNode (model); return true; }); customModel = model; pointCloudVisualization.Hidden = true; - if (boundingBox != null) - { + if (boundingBox != null) { boundingBox.Hidden = true; } - } - else - { - customModel?.RemoveFromParentNode(); - customModel?.Dispose(); + } else { + customModel?.RemoveFromParentNode (); + customModel?.Dispose (); customModel = null; - AddChildNode(originVis); + AddChildNode (originVis); pointCloudVisualization.Hidden = false; - if (boundingBox != null) - { + if (boundingBox != null) { boundingBox.Hidden = false; } } } - internal TimeSpan DisplayDuration { get => displayDuration; set => displayDuration = value; } + internal TimeSpan DisplayDuration { get => displayDuration; set => displayDuration = value; } - internal void UpdateVisualization(NMatrix4 transform, ARPointCloud currentPointCloud) + internal void UpdateVisualization (NMatrix4 transform, ARPointCloud currentPointCloud) { // Update the transform - Transform = transform.ToSCNMatrix4(); + Transform = transform.ToSCNMatrix4 (); // Update the point cloud visualization - UpdatePointCloud(currentPointCloud); + UpdatePointCloud (currentPointCloud); - if (boundingBox == null) - { + if (boundingBox == null) { var scale = referenceObject.Scale.X; - var newBoundingBox = new DetectedBoundingBox(referenceObject.RawFeaturePoints.Points, scale); + var newBoundingBox = new DetectedBoundingBox (referenceObject.RawFeaturePoints.Points, scale); newBoundingBox.Hidden = customModel != null; - AddChildNode(newBoundingBox); + AddChildNode (newBoundingBox); boundingBox = newBoundingBox; } // This visualization should only display for displayDuration seconds on every update - detectedObjectVisualizationTimer?.Invalidate(); + detectedObjectVisualizationTimer?.Invalidate (); Hidden = false; - detectedObjectVisualizationTimer = NSTimer.CreateScheduledTimer(DisplayDuration, (_) => Hidden = true); + detectedObjectVisualizationTimer = NSTimer.CreateScheduledTimer (DisplayDuration, (_) => Hidden = true); } - internal void UpdatePointCloud(ARPointCloud currentPointCloud) + internal void UpdatePointCloud (ARPointCloud currentPointCloud) { - pointCloudVisualization.UpdateVisualization(currentPointCloud); + pointCloudVisualization.UpdateVisualization (currentPointCloud); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedPointCloud.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedPointCloud.cs index efdc6af88..42baabdee 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedPointCloud.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/DetectedPointCloud.cs @@ -1,57 +1,52 @@ -using ARKit; +using ARKit; using OpenTK; using SceneKit; -using System; +using System; using System.Collections.Generic; using System.Linq; -namespace ScanningAndDetecting3DObjects -{ - internal class DetectedPointCloud : SCNNode - { - private ARPointCloud ReferenceObjectPointCloud { get; } - private SCNVector3 Center { get; } - private SCNVector3 Extent { get; } - internal DetectedPointCloud(ARPointCloud referenceObjectPointCloud, NVector3 center, NVector3 extent) - { - ReferenceObjectPointCloud = referenceObjectPointCloud; - Center = center.ToSCNVector3(); - Extent = extent.ToSCNVector3(); - - base.Init(); +namespace ScanningAndDetecting3DObjects { + internal class DetectedPointCloud : SCNNode { + private ARPointCloud ReferenceObjectPointCloud { get; } + private SCNVector3 Center { get; } + private SCNVector3 Extent { get; } + internal DetectedPointCloud (ARPointCloud referenceObjectPointCloud, NVector3 center, NVector3 extent) + { + ReferenceObjectPointCloud = referenceObjectPointCloud; + Center = center.ToSCNVector3 (); + Extent = extent.ToSCNVector3 (); + + base.Init (); // Semitransparently visualize the reference object's points. - var referenceObjectPoints = new SCNNode(); - referenceObjectPoints.Geometry = PointCloud.CreateVisualization(referenceObjectPointCloud.Points, Utilities.AppYellow, 12); - AddChildNode(referenceObjectPoints); - } - - internal void UpdateVisualization(ARPointCloud currentPointCloud) - { - Func<double, double, double, bool> RangeContains = (low, high, val) => val >= low && val <= high; - if (Hidden) - { - return; - } - - var min = Position + Center - Extent / 2; - var max = Position + Center + Extent / 2; - var inlierPoints = new List<SCNVector3>(); - - foreach(var point in currentPointCloud.Points) - { - var localPoint = ConvertPositionFromNode(point.ToSCNVector3(), null); - if (RangeContains(min.X, max.X, localPoint.X) - && RangeContains(min.Y, max.Y, localPoint.Y) - && RangeContains(min.Z, max.Z, localPoint.Z)) - { - inlierPoints.Add(localPoint); - } - } - - var currentPointCloudInliers = inlierPoints.Select(s => s.ToNVector3()).ToArray(); - Geometry?.Dispose(); - Geometry = PointCloud.CreateVisualization(currentPointCloudInliers, Utilities.AppGreen, 12); + var referenceObjectPoints = new SCNNode (); + referenceObjectPoints.Geometry = PointCloud.CreateVisualization (referenceObjectPointCloud.Points, Utilities.AppYellow, 12); + AddChildNode (referenceObjectPoints); + } + + internal void UpdateVisualization (ARPointCloud currentPointCloud) + { + Func<double, double, double, bool> RangeContains = (low, high, val) => val >= low && val <= high; + if (Hidden) { + return; + } + + var min = Position + Center - Extent / 2; + var max = Position + Center + Extent / 2; + var inlierPoints = new List<SCNVector3> (); + + foreach (var point in currentPointCloud.Points) { + var localPoint = ConvertPositionFromNode (point.ToSCNVector3 (), null); + if (RangeContains (min.X, max.X, localPoint.X) + && RangeContains (min.Y, max.Y, localPoint.Y) + && RangeContains (min.Z, max.Z, localPoint.Z)) { + inlierPoints.Add (localPoint); + } + } + + var currentPointCloudInliers = inlierPoints.Select (s => s.ToNVector3 ()).ToArray (); + Geometry?.Dispose (); + Geometry = PointCloud.CreateVisualization (currentPointCloudInliers, Utilities.AppGreen, 12); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOrigin.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOrigin.cs index 3545fc481..34cf73a2d 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOrigin.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOrigin.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using ARKit; using CoreGraphics; @@ -7,533 +7,478 @@ using SceneKit; using static System.Math; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // An interactive visualization of x/y/z coordinate axes for use in placing the origin/anchor point of a scanned object. - internal class ObjectOrigin : SCNNode - { - internal static readonly NSString PositionChangedNotificationName = new NSString("ObjectOriginPositionChanged"); - internal static readonly NSString MovedOutsideBoxNotificiationName = new NSString("ObjectOriginMovedOutsideBoundingBox"); - - private const float axisLength = 1.0F; + internal class ObjectOrigin : SCNNode { + internal static readonly NSString PositionChangedNotificationName = new NSString ("ObjectOriginPositionChanged"); + internal static readonly NSString MovedOutsideBoxNotificiationName = new NSString ("ObjectOriginMovedOutsideBoundingBox"); + + private const float axisLength = 1.0F; private const float axisThickness = 6.0F; // Axis thickness in percentage of length. - private const float axisSizeToObjectSizeRatio = 0.25F; - private const float minAxisSize = 0.05F; - private const float maxAxisSize = 0.2F; - - private ObjectOriginAxis xAxis; - private ObjectOriginAxis yAxis; - private ObjectOriginAxis zAxis; - - private SCNNode customModel; - - private PlaneDrag? currentAxisDrag; - private PlaneDrag? currentPlaneDrag; - - private ARSCNView sceneView; - + private const float axisSizeToObjectSizeRatio = 0.25F; + private const float minAxisSize = 0.05F; + private const float maxAxisSize = 0.2F; + + private ObjectOriginAxis xAxis; + private ObjectOriginAxis yAxis; + private ObjectOriginAxis zAxis; + + private SCNNode customModel; + + private PlaneDrag? currentAxisDrag; + private PlaneDrag? currentPlaneDrag; + + private ARSCNView sceneView; + internal bool PositionHasBeenAdjustedByUser { get; private set; } // Variables related to current snapping state - private bool snappedToSide = false; - private bool snappedToBottomCenter = false; - private bool snappedTo90DegreeRotation = false; - private float totalRotationSinceLastSnap = 0; - - private NSObject[] notificationObserverHandles; - - private bool DisplayingCustom3DModel { get => customModel != null; } - - internal ObjectOrigin(NVector3 extent, ARSCNView sceneView) : base() - { - this.sceneView = sceneView; - - var length = axisLength; - var thickness = (axisLength / 100.0F) * axisThickness; - var radius = axisThickness / 2; - var handleSize = axisLength / 4; - - xAxis = new ObjectOriginAxis(Axis.X, length, thickness, radius, handleSize); - yAxis = new ObjectOriginAxis(Axis.Y, length, thickness, radius, handleSize); - zAxis = new ObjectOriginAxis(Axis.Z, length, thickness, radius, handleSize); - - AddChildNode(xAxis); - AddChildNode(yAxis); - AddChildNode(zAxis); - - Set3DModel(ViewController.Instance?.ModelUrl, extent); - - notificationObserverHandles = new NSObject[2]; - notificationObserverHandles[0] = NSNotificationCenter.DefaultCenter.AddObserver(Scan.ScanningStateChangedNotificationName, ScanningStateChanged); - notificationObserverHandles[1] = NSNotificationCenter.DefaultCenter.AddObserver(BoundingBox.ExtentChangedNotificationName, BoundingBoxExtentChanged); - - Hidden = true; + private bool snappedToSide = false; + private bool snappedToBottomCenter = false; + private bool snappedTo90DegreeRotation = false; + private float totalRotationSinceLastSnap = 0; + + private NSObject [] notificationObserverHandles; + + private bool DisplayingCustom3DModel { get => customModel != null; } + + internal ObjectOrigin (NVector3 extent, ARSCNView sceneView) : base () + { + this.sceneView = sceneView; + + var length = axisLength; + var thickness = (axisLength / 100.0F) * axisThickness; + var radius = axisThickness / 2; + var handleSize = axisLength / 4; + + xAxis = new ObjectOriginAxis (Axis.X, length, thickness, radius, handleSize); + yAxis = new ObjectOriginAxis (Axis.Y, length, thickness, radius, handleSize); + zAxis = new ObjectOriginAxis (Axis.Z, length, thickness, radius, handleSize); + + AddChildNode (xAxis); + AddChildNode (yAxis); + AddChildNode (zAxis); + + Set3DModel (ViewController.Instance?.ModelUrl, extent); + + notificationObserverHandles = new NSObject [2]; + notificationObserverHandles [0] = NSNotificationCenter.DefaultCenter.AddObserver (Scan.ScanningStateChangedNotificationName, ScanningStateChanged); + notificationObserverHandles [1] = NSNotificationCenter.DefaultCenter.AddObserver (BoundingBox.ExtentChangedNotificationName, BoundingBoxExtentChanged); + + Hidden = true; } - internal void Set3DModel(NSUrl url, NVector3 extent) + internal void Set3DModel (NSUrl url, NVector3 extent) { - customModel?.RemoveFromParentNode(); - customModel?.Dispose(); - customModel = null; - - SCNNode model = null; - if (url != null) - { - model = Utilities.Load3DModel(url); - } - if (model != null) - { - ViewController.Instance?.SceneView.Prepare(model, () => - { - AddChildNode(model); - return true; - }); - customModel = model; - - xAxis.DisplayNodeHierarchyOnTop(true); - yAxis.DisplayNodeHierarchyOnTop(true); - zAxis.DisplayNodeHierarchyOnTop(true); - } - else - { - xAxis.DisplayNodeHierarchyOnTop(false); - yAxis.DisplayNodeHierarchyOnTop(false); - zAxis.DisplayNodeHierarchyOnTop(false); - } - - AdjustToExtent(extent); + customModel?.RemoveFromParentNode (); + customModel?.Dispose (); + customModel = null; + + SCNNode model = null; + if (url != null) { + model = Utilities.Load3DModel (url); + } + if (model != null) { + ViewController.Instance?.SceneView.Prepare (model, () => { + AddChildNode (model); + return true; + }); + customModel = model; + + xAxis.DisplayNodeHierarchyOnTop (true); + yAxis.DisplayNodeHierarchyOnTop (true); + zAxis.DisplayNodeHierarchyOnTop (true); + } else { + xAxis.DisplayNodeHierarchyOnTop (false); + yAxis.DisplayNodeHierarchyOnTop (false); + zAxis.DisplayNodeHierarchyOnTop (false); + } + + AdjustToExtent (extent); } - private void AdjustToExtent(NVector3 extent) + private void AdjustToExtent (NVector3 extent) { - if (extent == null) - { - Scale = new SCNVector3(1, 1, 1); - xAxis.Scale = new SCNVector3(1, 1, 1); - yAxis.Scale = new SCNVector3(1, 1, 1); - zAxis.Scale = new SCNVector3(1, 1, 1); + if (extent == null) { + Scale = new SCNVector3 (1, 1, 1); + xAxis.Scale = new SCNVector3 (1, 1, 1); + yAxis.Scale = new SCNVector3 (1, 1, 1); + zAxis.Scale = new SCNVector3 (1, 1, 1); } // By default the origin's scale is 1x. - Scale = new SCNVector3(1, 1, 1); + Scale = new SCNVector3 (1, 1, 1); // Compute a good scale for the axes based on the extent of the bounding box, // but stay within a reasonable range. - var axesScale = new[] { extent.X, extent.Y, extent.Z }.Min() * axisSizeToObjectSizeRatio; - axesScale = Max(Min(axesScale, maxAxisSize), minAxisSize); + var axesScale = new [] { extent.X, extent.Y, extent.Z }.Min () * axisSizeToObjectSizeRatio; + axesScale = Max (Min (axesScale, maxAxisSize), minAxisSize); // Adjust the scale of the axes (not the origin itself!) - xAxis.Scale = new SCNVector3(axesScale, axesScale, axesScale); - yAxis.Scale = new SCNVector3(axesScale, axesScale, axesScale); - zAxis.Scale = new SCNVector3(axesScale, axesScale, axesScale); - - if (customModel != null) - { + xAxis.Scale = new SCNVector3 (axesScale, axesScale, axesScale); + yAxis.Scale = new SCNVector3 (axesScale, axesScale, axesScale); + zAxis.Scale = new SCNVector3 (axesScale, axesScale, axesScale); + + if (customModel != null) { // Scale the origin such that the custom 3D model fits into the given extent. - SCNVector3 center = default(SCNVector3); - nfloat radius = default(nfloat); - customModel.GetBoundingSphere(ref center, ref radius); - var modelExtent = radius * 2; - var originScale = (float)(new[] { extent.X, extent.Y, extent.Z }.Min() / modelExtent); + SCNVector3 center = default (SCNVector3); + nfloat radius = default (nfloat); + customModel.GetBoundingSphere (ref center, ref radius); + var modelExtent = radius * 2; + var originScale = (float) (new [] { extent.X, extent.Y, extent.Z }.Min () / modelExtent); // Scale the origin itself, so that the scale will be preserved in the *.arobject file - Scale = new SCNVector3(originScale, originScale, originScale); + Scale = new SCNVector3 (originScale, originScale, originScale); // Correct the scale of the axes to be the same size as before - var div = (float)(1.0 / originScale); + var div = (float) (1.0 / originScale); // This is probably too fussy, as the scales are (certainly?) even along axes and I think all are equivalent - xAxis.Scale = new SCNVector3(xAxis.Scale.X * div, xAxis.Scale.Y * div, xAxis.Scale.Z * div); - yAxis.Scale = new SCNVector3(yAxis.Scale.X * div, yAxis.Scale.Y * div, yAxis.Scale.Z * div); - zAxis.Scale = new SCNVector3(zAxis.Scale.X * div, zAxis.Scale.Y * div, zAxis.Scale.Z * div); + xAxis.Scale = new SCNVector3 (xAxis.Scale.X * div, xAxis.Scale.Y * div, xAxis.Scale.Z * div); + yAxis.Scale = new SCNVector3 (yAxis.Scale.X * div, yAxis.Scale.Y * div, yAxis.Scale.Z * div); + zAxis.Scale = new SCNVector3 (zAxis.Scale.X * div, zAxis.Scale.Y * div, zAxis.Scale.Z * div); } - } - - internal void UpdateScale(float scale) + } + + internal void UpdateScale (float scale) { - /* - If a 3D model is being displayed, users should be able to change the scale - of the origin. This ensures that the scale at which the 3D model is displayed - will be preserved in the *.arobject file + /* + If a 3D model is being displayed, users should be able to change the scale + of the origin. This ensures that the scale at which the 3D model is displayed + will be preserved in the *.arobject file */ - if (DisplayingCustom3DModel) - { - Scale = new SCNVector3(Scale.X * scale, Scale.Y * scale, Scale.Z * scale); + if (DisplayingCustom3DModel) { + Scale = new SCNVector3 (Scale.X * scale, Scale.Y * scale, Scale.Z * scale); // Correct the scale of the axes to be displayed at the same size as before. - var div = (1.0F / scale); - xAxis.Scale = new SCNVector3(xAxis.Scale.X * div, xAxis.Scale.Y * div, xAxis.Scale.Z * div); - yAxis.Scale = new SCNVector3(yAxis.Scale.X * div, yAxis.Scale.Y * div, yAxis.Scale.Z * div); - xAxis.Scale = new SCNVector3(zAxis.Scale.X * div, zAxis.Scale.Y * div, zAxis.Scale.Z * div); - } - - } - - internal void StartAxisDrag(CGPoint screenPos) + var div = (1.0F / scale); + xAxis.Scale = new SCNVector3 (xAxis.Scale.X * div, xAxis.Scale.Y * div, xAxis.Scale.Z * div); + yAxis.Scale = new SCNVector3 (yAxis.Scale.X * div, yAxis.Scale.Y * div, yAxis.Scale.Z * div); + xAxis.Scale = new SCNVector3 (zAxis.Scale.X * div, zAxis.Scale.Y * div, zAxis.Scale.Z * div); + } + + } + + internal void StartAxisDrag (CGPoint screenPos) { - var camera = sceneView.PointOfView; - if (camera == null) - { - return; + var camera = sceneView.PointOfView; + if (camera == null) { + return; } // Check if the user is starting the drag on one of the axes. If so, drag along that axis - var options = new SCNHitTestOptions(); - options.RootNode = this; - options.BoundingBoxOnly = true; - var hitResults = sceneView.HitTest(screenPos, options); - - foreach (var result in hitResults) - { - var hitAxis = result.Node.ParentNode as ObjectOriginAxis; - if (hitAxis != null) - { - hitAxis.Highlighted = true; - - var worldAxis = hitAxis.ConvertVectorFromNode(hitAxis.Axis.Normal().ToSCNVector3(), null); - var worldPosition = hitAxis.ConvertVectorFromNode(new SCNVector3(), null); - var hitAxisNormalInWorld = (worldAxis - worldPosition).Normalized(); - - var dragRay = new Ray(WorldPosition, hitAxisNormalInWorld); - var transform = dragRay.DragPlaneTransform(camera.WorldPosition); - - var offset = new SCNVector3(); - var hitPos = sceneView.UnprojectPointLocal(screenPos, transform); - if (hitPos != null) - { + var options = new SCNHitTestOptions (); + options.RootNode = this; + options.BoundingBoxOnly = true; + var hitResults = sceneView.HitTest (screenPos, options); + + foreach (var result in hitResults) { + var hitAxis = result.Node.ParentNode as ObjectOriginAxis; + if (hitAxis != null) { + hitAxis.Highlighted = true; + + var worldAxis = hitAxis.ConvertVectorFromNode (hitAxis.Axis.Normal ().ToSCNVector3 (), null); + var worldPosition = hitAxis.ConvertVectorFromNode (new SCNVector3 (), null); + var hitAxisNormalInWorld = (worldAxis - worldPosition).Normalized (); + + var dragRay = new Ray (WorldPosition, hitAxisNormalInWorld); + var transform = dragRay.DragPlaneTransform (camera.WorldPosition); + + var offset = new SCNVector3 (); + var hitPos = sceneView.UnprojectPointLocal (screenPos, transform); + if (hitPos != null) { // Project the result onto the plane's X axis & transform into world coordinates - var posOnPlaneXAxis = new SCNVector4(hitPos.Value.X, 0, 0, 1); - var worldPosOnPlaneXAxis = transform.ToSCNMatrix4().Times(posOnPlaneXAxis); - - offset = WorldPosition - worldPosOnPlaneXAxis.Xyz; - } - - currentAxisDrag = new PlaneDrag(transform, offset.ToNVector3()); - PositionHasBeenAdjustedByUser = true; - return; - } + var posOnPlaneXAxis = new SCNVector4 (hitPos.Value.X, 0, 0, 1); + var worldPosOnPlaneXAxis = transform.ToSCNMatrix4 ().Times (posOnPlaneXAxis); + + offset = WorldPosition - worldPosOnPlaneXAxis.Xyz; + } + + currentAxisDrag = new PlaneDrag (transform, offset.ToNVector3 ()); + PositionHasBeenAdjustedByUser = true; + return; + } } } - internal void UpdateAxisDrag(CGPoint screenPos) - { - if (!currentAxisDrag.HasValue) - { - return; - } - var drag = currentAxisDrag.Value; - - var hitPos = sceneView.UnprojectPointLocal(screenPos, drag.PlaneTransform); - if (!hitPos.HasValue) - { - return; + internal void UpdateAxisDrag (CGPoint screenPos) + { + if (!currentAxisDrag.HasValue) { + return; + } + var drag = currentAxisDrag.Value; + + var hitPos = sceneView.UnprojectPointLocal (screenPos, drag.PlaneTransform); + if (!hitPos.HasValue) { + return; } // Project the result onto the plane's X axis & transform into world coordinates - var posOnPlaneXAxis = new SCNVector4(hitPos.Value.X, 0, 0, 1); - var worldPosOnPlaneXAxis = drag.PlaneTransform.ToSCNMatrix4().Times(posOnPlaneXAxis); - - WorldPosition = worldPosOnPlaneXAxis.Xyz.Plus(drag.Offset); - - if (customModel == null) - { + var posOnPlaneXAxis = new SCNVector4 (hitPos.Value.X, 0, 0, 1); + var worldPosOnPlaneXAxis = drag.PlaneTransform.ToSCNMatrix4 ().Times (posOnPlaneXAxis); + + WorldPosition = worldPosOnPlaneXAxis.Xyz.Plus (drag.Offset); + + if (customModel == null) { // Snap origin to any side of the bounding box and to the bottom center. - SnapToBoundingBoxSide(); - } - - NSNotificationCenter.DefaultCenter.PostNotification(NSNotification.FromName(ObjectOrigin.PositionChangedNotificationName, this)); - - if (OutsideBoundingBox()) - { - NSNotificationCenter.DefaultCenter.PostNotification(NSNotification.FromName(ObjectOrigin.MovedOutsideBoxNotificiationName, this)); + SnapToBoundingBoxSide (); + } + + NSNotificationCenter.DefaultCenter.PostNotification (NSNotification.FromName (ObjectOrigin.PositionChangedNotificationName, this)); + + if (OutsideBoundingBox ()) { + NSNotificationCenter.DefaultCenter.PostNotification (NSNotification.FromName (ObjectOrigin.MovedOutsideBoxNotificiationName, this)); } } - internal void EndAxisDrag() - { - currentAxisDrag = null; - xAxis.Highlighted = false; - yAxis.Highlighted = false; + internal void EndAxisDrag () + { + currentAxisDrag = null; + xAxis.Highlighted = false; + yAxis.Highlighted = false; zAxis.Highlighted = false; } - internal void StartPlaneDrag(CGPoint screenPos) + internal void StartPlaneDrag (CGPoint screenPos) { // Reposition the origin in the XZ-plane. - var dragPlane = WorldTransform.ToNMatrix4(); - var offset = new SCNVector3(); - var hitPos = sceneView.Unproject(screenPos, dragPlane); - - offset = WorldPosition - hitPos.ToSCNVector3(); - currentPlaneDrag = new PlaneDrag(dragPlane, offset.ToNVector3()); + var dragPlane = WorldTransform.ToNMatrix4 (); + var offset = new SCNVector3 (); + var hitPos = sceneView.Unproject (screenPos, dragPlane); + + offset = WorldPosition - hitPos.ToSCNVector3 (); + currentPlaneDrag = new PlaneDrag (dragPlane, offset.ToNVector3 ()); PositionHasBeenAdjustedByUser = true; } - internal void UpdatePlaneDrag(CGPoint screenPos) - { - if (!currentPlaneDrag.HasValue) - { - return; - } - var drag = currentPlaneDrag.Value; - - var hitPos = sceneView.Unproject(screenPos, drag.PlaneTransform); - - WorldPosition = hitPos.Plus(drag.Offset).ToSCNVector3(); - - if (customModel == null) - { - SnapToBoundingBoxCenter(); - } - - NSNotificationCenter.DefaultCenter.PostNotificationName(ObjectOrigin.PositionChangedNotificationName, this); - - if (OutsideBoundingBox()) - { - NSNotificationCenter.DefaultCenter.PostNotificationName(ObjectOrigin.MovedOutsideBoxNotificiationName, this); + internal void UpdatePlaneDrag (CGPoint screenPos) + { + if (!currentPlaneDrag.HasValue) { + return; + } + var drag = currentPlaneDrag.Value; + + var hitPos = sceneView.Unproject (screenPos, drag.PlaneTransform); + + WorldPosition = hitPos.Plus (drag.Offset).ToSCNVector3 (); + + if (customModel == null) { + SnapToBoundingBoxCenter (); + } + + NSNotificationCenter.DefaultCenter.PostNotificationName (ObjectOrigin.PositionChangedNotificationName, this); + + if (OutsideBoundingBox ()) { + NSNotificationCenter.DefaultCenter.PostNotificationName (ObjectOrigin.MovedOutsideBoxNotificiationName, this); } } - internal void EndPlaneDrag() - { - currentPlaneDrag = null; - snappedToSide = false; + internal void EndPlaneDrag () + { + currentPlaneDrag = null; + snappedToSide = false; snappedToBottomCenter = false; } - internal void FlashOrReposition(CGPoint screenPos) + internal void FlashOrReposition (CGPoint screenPos) { // Check if the user tapped on one of the axes. If so, highlight it. - var options = new SCNHitTestOptions(); - options.RootNode = this; + var options = new SCNHitTestOptions (); + options.RootNode = this; options.BoundingBoxOnly = true; - var hitResults = sceneView.HitTest(screenPos, options); - - foreach (var result in hitResults) - { - var hitAxis = result.Node.ParentNode as ObjectOriginAxis; - if (hitAxis != null) - { - hitAxis.Flash(); - return; - } + var hitResults = sceneView.HitTest (screenPos, options); + + foreach (var result in hitResults) { + var hitAxis = result.Node.ParentNode as ObjectOriginAxis; + if (hitAxis != null) { + hitAxis.Flash (); + return; + } } // If no axis was hit, reposition the origin in the XZ-plane. - var hitPos = sceneView.Unproject(screenPos, WorldTransform.ToNMatrix4()); - WorldPosition = hitPos.ToSCNVector3(); - - if (OutsideBoundingBox()) - { - NSNotificationCenter.DefaultCenter.PostNotificationName(ObjectOrigin.MovedOutsideBoxNotificiationName, this); - } - - } - - - internal void RotateWithSnappingOnYAxis(float angle) - { - var snapInterval = PI / 2; + var hitPos = sceneView.Unproject (screenPos, WorldTransform.ToNMatrix4 ()); + WorldPosition = hitPos.ToSCNVector3 (); + + if (OutsideBoundingBox ()) { + NSNotificationCenter.DefaultCenter.PostNotificationName (ObjectOrigin.MovedOutsideBoxNotificiationName, this); + } + + } + + + internal void RotateWithSnappingOnYAxis (float angle) + { + var snapInterval = PI / 2; var snapThreshold = PI / 30; // ~6° // Compute the snap angle, being the closest multiple of the snap interval. - var snapAngle = Round(EulerAngles.Y / snapInterval) * snapInterval; - - if (!snappedTo90DegreeRotation) - { + var snapAngle = Round (EulerAngles.Y / snapInterval) * snapInterval; + + if (!snappedTo90DegreeRotation) { // Compute the delta between current angle and computed snap angle. - var deltaToSnapAngle = Abs(snapAngle - EulerAngles.Y); + var deltaToSnapAngle = Abs (snapAngle - EulerAngles.Y); // Snap if the delta is below the snap threshold, otherwise rotate by the angle // received from teh gesture - if (deltaToSnapAngle < snapThreshold) - { - LocalRotate(SCNQuaternion.FromAxisAngle(Axis.Y.Normal().ToSCNVector3(), (float)(Sign(angle) * deltaToSnapAngle))); - snappedTo90DegreeRotation = true; - totalRotationSinceLastSnap = 0; - Snapping.PlayHapticFeedback(); - } - else - { - LocalRotate(SCNQuaternion.FromAxisAngle(Axis.Y.Normal().ToSCNVector3(), totalRotationSinceLastSnap)); - } - } - else - { + if (deltaToSnapAngle < snapThreshold) { + LocalRotate (SCNQuaternion.FromAxisAngle (Axis.Y.Normal ().ToSCNVector3 (), (float) (Sign (angle) * deltaToSnapAngle))); + snappedTo90DegreeRotation = true; + totalRotationSinceLastSnap = 0; + Snapping.PlayHapticFeedback (); + } else { + LocalRotate (SCNQuaternion.FromAxisAngle (Axis.Y.Normal ().ToSCNVector3 (), totalRotationSinceLastSnap)); + } + } else { totalRotationSinceLastSnap += angle; // Unsnap if the total rotation since the snap exceeds the snap threshold. - if (Abs(totalRotationSinceLastSnap) > snapThreshold) - { - LocalRotate(SCNQuaternion.FromAxisAngle(Axis.Y.Normal().ToSCNVector3(), totalRotationSinceLastSnap)); - snappedTo90DegreeRotation = false; - } - } + if (Abs (totalRotationSinceLastSnap) > snapThreshold) { + LocalRotate (SCNQuaternion.FromAxisAngle (Axis.Y.Normal ().ToSCNVector3 (), totalRotationSinceLastSnap)); + snappedTo90DegreeRotation = false; + } + } } - - private bool OutsideBoundingBox() - { - var boundingBox = ParentNode as BoundingBox; - if (boundingBox == null) - { - return true; - } - - var threshold = 0.002F; - var extent = new SCNVector3(boundingBox.Extent.X + threshold, boundingBox.Extent.Y + threshold, boundingBox.Extent.Z + threshold); - - var pos = Position; - return pos.X < -extent.X / 2 - || pos.Y < -extent.Y / 2 + + private bool OutsideBoundingBox () + { + var boundingBox = ParentNode as BoundingBox; + if (boundingBox == null) { + return true; + } + + var threshold = 0.002F; + var extent = new SCNVector3 (boundingBox.Extent.X + threshold, boundingBox.Extent.Y + threshold, boundingBox.Extent.Z + threshold); + + var pos = Position; + return pos.X < -extent.X / 2 + || pos.Y < -extent.Y / 2 || pos.Z < -extent.Z / 2 || pos.X > extent.X / 2 || pos.Y > extent.Y / 2 - || pos.Z > extent.Z / 2; - } - - private void SnapToBoundingBoxSide() - { - var boundingBox = ParentNode as BoundingBox; - if (boundingBox == null) - { - return; - } - var extent = boundingBox.Extent; - - var snapThreshold = 0.01; - var withinSnapThreshold = false; - - if (Abs(extent.X / 2 - Position.X) < snapThreshold) - { - Position = new SCNVector3(extent.X / 2, Position.Y, Position.Z); - withinSnapThreshold = true; - } - else if (Abs(-extent.X / 2 - Position.X) < snapThreshold) - { - Position = new SCNVector3(-extent.X / 2, Position.Y, Position.Z); - withinSnapThreshold = true; - } - - if (Abs(extent.Y / 2 - Position.Y) < snapThreshold) - { - Position = new SCNVector3(Position.X, extent.Y / 2, Position.Z); - withinSnapThreshold = true; - } - else if (Abs(-extent.Y / 2 - Position.Y) < snapThreshold) - { - Position = new SCNVector3(Position.X, -extent.Y / 2, Position.Z); - withinSnapThreshold = true; - } - - if (Abs(extent.Z / 2 - Position.Z) < snapThreshold) - { - Position = new SCNVector3(Position.X, Position.Y, extent.Z / 2); - withinSnapThreshold = true; - } - else if (Abs(-extent.Z / 2 - Position.Z) < snapThreshold) - { - Position = new SCNVector3(Position.X, Position.Y, -extent.Z / 2); - withinSnapThreshold = true; + || pos.Z > extent.Z / 2; + } + + private void SnapToBoundingBoxSide () + { + var boundingBox = ParentNode as BoundingBox; + if (boundingBox == null) { + return; + } + var extent = boundingBox.Extent; + + var snapThreshold = 0.01; + var withinSnapThreshold = false; + + if (Abs (extent.X / 2 - Position.X) < snapThreshold) { + Position = new SCNVector3 (extent.X / 2, Position.Y, Position.Z); + withinSnapThreshold = true; + } else if (Abs (-extent.X / 2 - Position.X) < snapThreshold) { + Position = new SCNVector3 (-extent.X / 2, Position.Y, Position.Z); + withinSnapThreshold = true; + } + + if (Abs (extent.Y / 2 - Position.Y) < snapThreshold) { + Position = new SCNVector3 (Position.X, extent.Y / 2, Position.Z); + withinSnapThreshold = true; + } else if (Abs (-extent.Y / 2 - Position.Y) < snapThreshold) { + Position = new SCNVector3 (Position.X, -extent.Y / 2, Position.Z); + withinSnapThreshold = true; + } + + if (Abs (extent.Z / 2 - Position.Z) < snapThreshold) { + Position = new SCNVector3 (Position.X, Position.Y, extent.Z / 2); + withinSnapThreshold = true; + } else if (Abs (-extent.Z / 2 - Position.Z) < snapThreshold) { + Position = new SCNVector3 (Position.X, Position.Y, -extent.Z / 2); + withinSnapThreshold = true; } // Provide haptic feedback when reaching the snapThreshold for the first time - if (withinSnapThreshold && !snappedToSide) - { - snappedToSide = true; - Snapping.PlayHapticFeedback(); - } - else if (!withinSnapThreshold) - { - snappedToSide = false; - } - } - - - private void SnapToBoundingBoxCenter() - { - var boundingBox = ParentNode as BoundingBox; - if (boundingBox == null) - { - return; - } - - var snapThreshold = 0.01F; - var boundingBoxPos = boundingBox.Position; - - var withinSnapThreshold = false; - - if (Abs(boundingBox.Position.X - Position.X) < snapThreshold - && Abs(boundingBox.Position.Z - Position.Z) < snapThreshold) - { - Position = new SCNVector3(boundingBoxPos.X, Position.Y, boundingBoxPos.Z); - withinSnapThreshold = true; + if (withinSnapThreshold && !snappedToSide) { + snappedToSide = true; + Snapping.PlayHapticFeedback (); + } else if (!withinSnapThreshold) { + snappedToSide = false; + } + } + + + private void SnapToBoundingBoxCenter () + { + var boundingBox = ParentNode as BoundingBox; + if (boundingBox == null) { + return; + } + + var snapThreshold = 0.01F; + var boundingBoxPos = boundingBox.Position; + + var withinSnapThreshold = false; + + if (Abs (boundingBox.Position.X - Position.X) < snapThreshold + && Abs (boundingBox.Position.Z - Position.Z) < snapThreshold) { + Position = new SCNVector3 (boundingBoxPos.X, Position.Y, boundingBoxPos.Z); + withinSnapThreshold = true; } // Provide haptic feedback when reaching the snapThreshold for the first time - if (withinSnapThreshold && !snappedToBottomCenter) - { - snappedToBottomCenter = true; - Snapping.PlayHapticFeedback(); - } - else - { - snappedToBottomCenter = false; - } - } - - - private void BoundingBoxExtentChanged(NSNotification notification) - { - var boundingBox = notification.Object as BoundingBox; - if (boundingBox == null) - { - return; - } - AdjustToExtent(boundingBox.Extent); - } - - private void ScanningStateChanged(NSNotification notification) - { - var state = notification.UserInfo?[Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; - if (state == null) - { - return; - } - - switch (state.Value) - { - case Scan.ScanState.Ready: - case Scan.ScanState.DefineBoundingBox: - case Scan.ScanState.Scanning: - Hidden = true; - break; - case Scan.ScanState.AdjustingOrigin: - Hidden = false; - break; - } - } - - internal new void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - private bool disposed = false; - override protected void Dispose(bool disposing) - { - if (!disposed) - { - disposed = true; - - if (disposing) - { - base.Dispose(); - } - - NSNotificationCenter.DefaultCenter.RemoveObserver(notificationObserverHandles[0]); - NSNotificationCenter.DefaultCenter.RemoveObserver(notificationObserverHandles[1]); - } + if (withinSnapThreshold && !snappedToBottomCenter) { + snappedToBottomCenter = true; + Snapping.PlayHapticFeedback (); + } else { + snappedToBottomCenter = false; + } + } + + + private void BoundingBoxExtentChanged (NSNotification notification) + { + var boundingBox = notification.Object as BoundingBox; + if (boundingBox == null) { + return; + } + AdjustToExtent (boundingBox.Extent); + } + + private void ScanningStateChanged (NSNotification notification) + { + var state = notification.UserInfo? [Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; + if (state == null) { + return; + } + + switch (state.Value) { + case Scan.ScanState.Ready: + case Scan.ScanState.DefineBoundingBox: + case Scan.ScanState.Scanning: + Hidden = true; + break; + case Scan.ScanState.AdjustingOrigin: + Hidden = false; + break; + } + } + + internal new void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + private bool disposed = false; + override protected void Dispose (bool disposing) + { + if (!disposed) { + disposed = true; + + if (disposing) { + base.Dispose (); + } + + NSNotificationCenter.DefaultCenter.RemoveObserver (notificationObserverHandles [0]); + NSNotificationCenter.DefaultCenter.RemoveObserver (notificationObserverHandles [1]); + } } - } -} \ No newline at end of file + } +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOriginAxis.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOriginAxis.cs index 21c5b72eb..c76b113ff 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOriginAxis.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ObjectOriginAxis.cs @@ -1,126 +1,117 @@ -using System; +using System; using Foundation; using OpenTK; using SceneKit; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // An interactive visualization a single x/y/z coordinate axis for use in placing the origin/anchor point of a scanned object. - internal class ObjectOriginAxis : SCNNode - { + internal class ObjectOriginAxis : SCNNode { private Axis axis; - - private NSTimer flashTimer; + + private NSTimer flashTimer; private const double flashDuration = 0.1; - internal ObjectOriginAxis(Axis axis, float length, float thickness, float radius, float handleSize) + internal ObjectOriginAxis (Axis axis, float length, float thickness, float radius, float handleSize) { - this.axis = axis; - - base.Init(); - - UIColor color = default(UIColor); - UIImage texture = default(UIImage); - SCNVector3 dimensions = default(SCNVector3); - var position = new SCNVector3((float)(axis.Normal().X * (length / 2.0)), (float)(axis.Normal().Y * (length / 2.0)), (float)(axis.Normal().Z * (length / 2.0))); - var axisHandlePosition = new SCNVector3((float)(axis.Normal().X * length), (float)(axis.Normal().Y * length), (float)(axis.Normal().Z * length)); - - switch(axis) - { - case Axis.X : - color = UIColor.Red; - texture = UIImage.FromFile("handle_red"); - dimensions = new SCNVector3(length, thickness, thickness); - break; - case Axis.Y : - color = UIColor.Green; - texture = UIImage.FromFile("handle_green"); - dimensions = new SCNVector3(thickness, length, thickness); - break; - case Axis.Z : - color = UIColor.Blue; - texture = UIImage.FromFile("handle_blue"); - dimensions = new SCNVector3(thickness, thickness, length); - break; - } - - var axisGeo = SCNBox.Create(dimensions.X, dimensions.Y, dimensions.Z, radius); - axisGeo.Materials = new[] { Utilities.Material(color) }; - var axisNode = SCNNode.FromGeometry(axisGeo); - - var axisHandleGeo = SCNPlane.Create(handleSize, handleSize); - axisHandleGeo.Materials = new[] { Utilities.Material(texture, false) }; - var axisHandle = SCNNode.FromGeometry(axisHandleGeo); - axisHandle.Constraints = new[] { new SCNBillboardConstraint() }; - - axisNode.Position = position; + this.axis = axis; + + base.Init (); + + UIColor color = default (UIColor); + UIImage texture = default (UIImage); + SCNVector3 dimensions = default (SCNVector3); + var position = new SCNVector3 ((float) (axis.Normal ().X * (length / 2.0)), (float) (axis.Normal ().Y * (length / 2.0)), (float) (axis.Normal ().Z * (length / 2.0))); + var axisHandlePosition = new SCNVector3 ((float) (axis.Normal ().X * length), (float) (axis.Normal ().Y * length), (float) (axis.Normal ().Z * length)); + + switch (axis) { + case Axis.X: + color = UIColor.Red; + texture = UIImage.FromFile ("handle_red"); + dimensions = new SCNVector3 (length, thickness, thickness); + break; + case Axis.Y: + color = UIColor.Green; + texture = UIImage.FromFile ("handle_green"); + dimensions = new SCNVector3 (thickness, length, thickness); + break; + case Axis.Z: + color = UIColor.Blue; + texture = UIImage.FromFile ("handle_blue"); + dimensions = new SCNVector3 (thickness, thickness, length); + break; + } + + var axisGeo = SCNBox.Create (dimensions.X, dimensions.Y, dimensions.Z, radius); + axisGeo.Materials = new [] { Utilities.Material (color) }; + var axisNode = SCNNode.FromGeometry (axisGeo); + + var axisHandleGeo = SCNPlane.Create (handleSize, handleSize); + axisHandleGeo.Materials = new [] { Utilities.Material (texture, false) }; + var axisHandle = SCNNode.FromGeometry (axisHandleGeo); + axisHandle.Constraints = new [] { new SCNBillboardConstraint () }; + + axisNode.Position = position; axisHandle.Position = axisHandlePosition; // Increase the axis handle geometry's bounding box that is used for hit testing to make it easier to hit - SCNVector3 min = default(SCNVector3); - SCNVector3 max = default(SCNVector3); - axisHandle.GetBoundingBox(ref min, ref max); - var padding = handleSize * 0.8F; - var newMin = new SCNVector3(min.X - padding, min.Y - padding, min.Z - padding); - var newMax = new SCNVector3(max.X + padding, max.Y + padding, max.Z + padding); - axisHandle.SetBoundingBox(ref newMin, ref newMax); - - AddChildNode(axisNode); - AddChildNode(axisHandle); + SCNVector3 min = default (SCNVector3); + SCNVector3 max = default (SCNVector3); + axisHandle.GetBoundingBox (ref min, ref max); + var padding = handleSize * 0.8F; + var newMin = new SCNVector3 (min.X - padding, min.Y - padding, min.Z - padding); + var newMax = new SCNVector3 (max.X + padding, max.Y + padding, max.Z + padding); + axisHandle.SetBoundingBox (ref newMin, ref newMax); + + AddChildNode (axisNode); + AddChildNode (axisHandle); } - - private bool highlighted = false; - internal bool Highlighted - { + + private bool highlighted = false; + internal bool Highlighted { get => highlighted; - set - { - highlighted = value; - var emissionColor = highlighted ? UIColor.White : UIColor.Black; - foreach(var child in ChildNodes) - { - var emission = child.Geometry?.FirstMaterial?.Emission; - if (emission != null) - { - emission.ContentColor = emissionColor; - } - } + set { + highlighted = value; + var emissionColor = highlighted ? UIColor.White : UIColor.Black; + foreach (var child in ChildNodes) { + var emission = child.Geometry?.FirstMaterial?.Emission; + if (emission != null) { + emission.ContentColor = emissionColor; + } + } } - } - - internal Axis Axis { get => axis; } - - private void UpdateRenderOrder(SCNNode node, bool isOnTop) - { - node.RenderingOrder = isOnTop ? 2 : 0; - - foreach (var material in node.Geometry?.Materials ?? new SCNMaterial[] { }) - { - material.ReadsFromDepthBuffer = !isOnTop; - } - - foreach (var child in node.ChildNodes) - { - // recurse - UpdateRenderOrder(child, isOnTop); - } - } - - internal void DisplayNodeHierarchyOnTop(bool isOnTop) + } + + internal Axis Axis { get => axis; } + + private void UpdateRenderOrder (SCNNode node, bool isOnTop) + { + node.RenderingOrder = isOnTop ? 2 : 0; + + foreach (var material in node.Geometry?.Materials ?? new SCNMaterial [] { }) { + material.ReadsFromDepthBuffer = !isOnTop; + } + + foreach (var child in node.ChildNodes) { + // recurse + UpdateRenderOrder (child, isOnTop); + } + } + + internal void DisplayNodeHierarchyOnTop (bool isOnTop) { // Recursively traverse the node's children to update the rendering order // depening on the `isOnTop` parameter - UpdateRenderOrder(this, isOnTop); + UpdateRenderOrder (this, isOnTop); } - internal void Flash() + internal void Flash () { - Highlighted = true; - - flashTimer?.Invalidate(); - flashTimer = NSTimer.CreateScheduledTimer(flashDuration, (_) => Highlighted = false); + Highlighted = true; + + flashTimer?.Invalidate (); + flashTimer = NSTimer.CreateScheduledTimer (flashDuration, (_) => Highlighted = false); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PlaneDrag.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PlaneDrag.cs index 1e49f34b3..d3c7de5f3 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PlaneDrag.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PlaneDrag.cs @@ -1,13 +1,11 @@ -using System; +using System; using OpenTK; -namespace ScanningAndDetecting3DObjects -{ - internal struct PlaneDrag - { +namespace ScanningAndDetecting3DObjects { + internal struct PlaneDrag { internal NMatrix4 PlaneTransform { get; } internal NVector3 Offset { get; } - internal PlaneDrag(NMatrix4 planeTransform, NVector3 offset) + internal PlaneDrag (NMatrix4 planeTransform, NVector3 offset) { this.PlaneTransform = planeTransform; this.Offset = offset; diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PointCloud.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PointCloud.cs index 0a47d0a3e..76226dc83 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PointCloud.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/PointCloud.cs @@ -1,4 +1,4 @@ -using System; +using System; using SceneKit; using System.Collections; using System.Collections.Generic; @@ -7,36 +7,31 @@ using OpenTK; using Foundation; -namespace ScanningAndDetecting3DObjects -{ - internal static class PointCloud - { - internal static SCNGeometry CreateVisualization(NVector3[] points, UIColor color, float size) +namespace ScanningAndDetecting3DObjects { + internal static class PointCloud { + internal static SCNGeometry CreateVisualization (NVector3 [] points, UIColor color, float size) { - if (points.Length == 0) - { + if (points.Length == 0) { return null; } - unsafe - { - var stride = sizeof(float) * 3; + unsafe { + var stride = sizeof (float) * 3; // Pin the data down so that it doesn't move - fixed (NVector3* pPoints = &points[0]) - { + fixed (NVector3* pPoints = &points [0]) { // Grab a pointer to the data and treat it as a byte buffer of the appropriate length - var intPtr = new IntPtr(pPoints); - var pointData = NSData.FromBytes(intPtr, (System.nuint) (stride * points.Length)); + var intPtr = new IntPtr (pPoints); + var pointData = NSData.FromBytes (intPtr, (System.nuint) (stride * points.Length)); // Create a geometry source (factory) configured properly for the data (3 vertices) - var source = SCNGeometrySource.FromData( + var source = SCNGeometrySource.FromData ( pointData, SCNGeometrySourceSemantics.Vertex, points.Length, true, 3, - sizeof(float), + sizeof (float), 0, stride ); @@ -45,14 +40,14 @@ internal static SCNGeometry CreateVisualization(NVector3[] points, UIColor color // Create geometry element // The null and bytesPerElement = 0 look odd, but this is just a template object - var element = SCNGeometryElement.FromData(null, SCNGeometryPrimitiveType.Point, points.Length, 0); + var element = SCNGeometryElement.FromData (null, SCNGeometryPrimitiveType.Point, points.Length, 0); element.PointSize = 0.001F; element.MinimumPointScreenSpaceRadius = size; element.MaximumPointScreenSpaceRadius = size; // Stitch the data (source) together with the template (element) to create the new object - var pointsGeometry = SCNGeometry.Create(new[] { source }, new[] { element }); - pointsGeometry.Materials = new[] { Utilities.Material(color) }; + var pointsGeometry = SCNGeometry.Create (new [] { source }, new [] { element }); + pointsGeometry.Materials = new [] { Utilities.Material (color) }; return pointsGeometry; } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Ray.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Ray.cs index 114dffce5..9ff92bc32 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Ray.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Ray.cs @@ -1,38 +1,36 @@ -using System; +using System; using OpenTK; using SceneKit; -namespace ScanningAndDetecting3DObjects -{ - internal struct Ray - { +namespace ScanningAndDetecting3DObjects { + internal struct Ray { internal SCNVector3 Origin { get; private set; } internal SCNVector3 Direction { get; private set; } - internal Ray(SCNVector3 origin, SCNVector3 sideNormalInWorld) + internal Ray (SCNVector3 origin, SCNVector3 sideNormalInWorld) { this.Origin = origin; this.Direction = sideNormalInWorld; } - Ray(SCNVector3 origin, NVector3 direction) + Ray (SCNVector3 origin, NVector3 direction) { this.Origin = origin; - this.Direction = direction.ToSCNVector3(); + this.Direction = direction.ToSCNVector3 (); } - internal Ray(SCNNode pointOfView, float length) + internal Ray (SCNNode pointOfView, float length) { - pointOfView.WorldFront.NormalizeFast(); - var cameraNormal = pointOfView.WorldFront.Times(length); + pointOfView.WorldFront.NormalizeFast (); + var cameraNormal = pointOfView.WorldFront.Times (length); Origin = pointOfView.WorldPosition; - Direction = cameraNormal.ToSCNVector3(); + Direction = cameraNormal.ToSCNVector3 (); } - internal NMatrix4 DragPlaneTransform(SCNVector3 cameraPos) + internal NMatrix4 DragPlaneTransform (SCNVector3 cameraPos) { var camToRayOrigin = this.Origin - cameraPos; - camToRayOrigin.NormalizeFast(); + camToRayOrigin.NormalizeFast (); // Create a transform for a XZ-plane. This transform can be passed to unproject() to // map the user's touch position in screen space onto that plane in 3D space. @@ -53,36 +51,36 @@ internal NMatrix4 DragPlaneTransform(SCNVector3 cameraPos) // possible when dragging along an axis which is pointing at the camera. For that case // we try to find a plane which covers as much screen space as possible. var xVector = Direction; - var zVector = SCNVector3.Cross(xVector, camToRayOrigin).Normalized(); - var yVector = SCNVector3.Cross(xVector, zVector).Normalized(); + var zVector = SCNVector3.Cross (xVector, camToRayOrigin).Normalized (); + var yVector = SCNVector3.Cross (xVector, zVector).Normalized (); - var asIfSimd4x4 = Utilities.NMatrix4Create(new[] { + var asIfSimd4x4 = Utilities.NMatrix4Create (new [] { Utilities.SCNVector4Create(xVector, 0), Utilities.SCNVector4Create(yVector, 0), Utilities.SCNVector4Create(zVector, 0), Utilities.SCNVector4Create(Origin, 1) }); // But we're not, so transpose - asIfSimd4x4.Transpose(); + asIfSimd4x4.Transpose (); return asIfSimd4x4; } - internal NMatrix4 DragPlaneTransform(SCNNode camera) + internal NMatrix4 DragPlaneTransform (SCNNode camera) { // Create a transform for a XZ-plane. This transform can be passed to unproject() to // map the user's touch position in screen space onto that plane in 3D space. // The plane's transform is constructed from a given normal. - var yVector = Direction.Normalized(); - var xVector = SCNVector3.Cross(yVector, camera.WorldRight); - var zVector = SCNVector3.Cross(xVector, yVector).Normalized(); - var asIfsimd4x4 = Utilities.NMatrix4Create(new[] { + var yVector = Direction.Normalized (); + var xVector = SCNVector3.Cross (yVector, camera.WorldRight); + var zVector = SCNVector3.Cross (xVector, yVector).Normalized (); + var asIfsimd4x4 = Utilities.NMatrix4Create (new [] { Utilities.SCNVector4Create(xVector, 0), Utilities.SCNVector4Create(yVector, 0), Utilities.SCNVector4Create(zVector, 0), Utilities.SCNVector4Create(Origin, 1) }); // But we're not, so transpose - asIfsimd4x4.Transpose(); + asIfsimd4x4.Transpose (); return asIfsimd4x4; } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedObject.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedObject.cs index ed0caa6db..06cf2b0e9 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedObject.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedObject.cs @@ -1,365 +1,330 @@ -using ARKit; +using ARKit; using CoreGraphics; using Foundation; using SceneKit; -using System; -using OpenTK; - -namespace ScanningAndDetecting3DObjects -{ - internal class ScannedObject : SCNNode - { - private ARSCNView sceneView; - - internal static readonly NSString PositionChangedNotificationName = new NSString("ScannedObjectPositionChanged"); - internal static readonly NSString BoundingBoxCreatedNotificationName = new NSString("BoundingBoxWasCreated"); - internal static readonly NSString GhostBoundingBoxCreatedNotificationName = new NSString("GhostBoundingBoxWasCreated"); - internal static readonly NSString GhostBoundingBoxRemovedNotificationName = new NSString("GhostBoundingBoxWasRemoved"); - - private NSObject notificationObserverHandle; - - internal ScannedObject(ARSCNView sceneView) +using System; +using OpenTK; + +namespace ScanningAndDetecting3DObjects { + internal class ScannedObject : SCNNode { + private ARSCNView sceneView; + + internal static readonly NSString PositionChangedNotificationName = new NSString ("ScannedObjectPositionChanged"); + internal static readonly NSString BoundingBoxCreatedNotificationName = new NSString ("BoundingBoxWasCreated"); + internal static readonly NSString GhostBoundingBoxCreatedNotificationName = new NSString ("GhostBoundingBoxWasCreated"); + internal static readonly NSString GhostBoundingBoxRemovedNotificationName = new NSString ("GhostBoundingBoxWasRemoved"); + + private NSObject notificationObserverHandle; + + internal ScannedObject (ARSCNView sceneView) { - this.sceneView = sceneView; - - ScanName = $"Scan_{DateTime.Now.ToString("s").Replace('-', '_').Replace(':', '_')}"; - base.Init(); - - Console.WriteLine("Creating a new ScannedObject"); - notificationObserverHandle = NSNotificationCenter.DefaultCenter.AddObserver(Scan.ScanningStateChangedNotificationName, ScanningStateChanged); + this.sceneView = sceneView; + + ScanName = $"Scan_{DateTime.Now.ToString ("s").Replace ('-', '_').Replace (':', '_')}"; + base.Init (); + + Console.WriteLine ("Creating a new ScannedObject"); + notificationObserverHandle = NSNotificationCenter.DefaultCenter.AddObserver (Scan.ScanningStateChangedNotificationName, ScanningStateChanged); } - private BoundingBox boundingBox; + private BoundingBox boundingBox; private BoundingBox ghostBoundingBox; - - internal ObjectOrigin Origin { get; private set; } + + internal ObjectOrigin Origin { get; private set; } internal BoundingBox EitherBoundingBox { get => boundingBox ?? GhostBoundingBox; } - internal BoundingBox BoundingBox { get => boundingBox; private set => boundingBox = value; } - internal BoundingBox GhostBoundingBox { get => ghostBoundingBox; private set => ghostBoundingBox = value; } + internal BoundingBox BoundingBox { get => boundingBox; private set => boundingBox = value; } + internal BoundingBox GhostBoundingBox { get => ghostBoundingBox; private set => ghostBoundingBox = value; } internal string ScanName { get; private set; } - - public override SCNVector3 Position - { + + public override SCNVector3 Position { get => base.Position; - set - { - base.Position = value; - NSNotificationCenter.DefaultCenter.PostNotificationName(PositionChangedNotificationName, this); - } - } - - internal void RotateOnYAxis(float angle) + set { + base.Position = value; + NSNotificationCenter.DefaultCenter.PostNotificationName (PositionChangedNotificationName, this); + } + } + + internal void RotateOnYAxis (float angle) { - LocalRotate(SCNQuaternion.FromAxisAngle(Axis.Y.Normal().ToSCNVector3(), angle)); + LocalRotate (SCNQuaternion.FromAxisAngle (Axis.Y.Normal ().ToSCNVector3 (), angle)); BoundingBox.HasBeenAdjustedByUser = true; - } - - internal void Set3DModel(NSUrl url) - { - Origin?.Set3DModel(url, boundingBox.Extent); } - internal void CreateOrMoveBoundingBox(CGPoint screenPos) + internal void Set3DModel (NSUrl url) + { + Origin?.Set3DModel (url, boundingBox.Extent); + } + + internal void CreateOrMoveBoundingBox (CGPoint screenPos) { - if (boundingBox != null) - { - if (!boundingBox.IsHit(screenPos)) - { + if (boundingBox != null) { + if (!boundingBox.IsHit (screenPos)) { // Perform a hit test against the feature point cloud. - var result = sceneView.SmartHitTest(screenPos); - if (result == null) - { - Console.WriteLine("Warning: Failed to find a position for the bounding box."); - return; - } - WorldPosition = result.WorldTransform.Position(); - } - } - else - { - CreateBoundingBox(screenPos); + var result = sceneView.SmartHitTest (screenPos); + if (result == null) { + Console.WriteLine ("Warning: Failed to find a position for the bounding box."); + return; + } + WorldPosition = result.WorldTransform.Position (); + } + } else { + CreateBoundingBox (screenPos); + } + } + + + private void CreateBoundingBoxFromGhost () + { + if (ghostBoundingBox == null) { + return; + } + boundingBox = ghostBoundingBox; + boundingBox.Opacity = 1.0F; + if (Constraints != null) { + foreach (var constraint in Constraints) { + constraint.Dispose (); + } } - } - - - private void CreateBoundingBoxFromGhost() - { - if (ghostBoundingBox == null) - { - return; - } - boundingBox = ghostBoundingBox; - boundingBox.Opacity = 1.0F; - if (Constraints != null) - { - foreach (var constraint in Constraints) - { - constraint.Dispose(); - } - } Constraints = null; // No call to Dispose() because `ghostBoundingBox` object reference is now held by `boundingBox`. - ghostBoundingBox = null; - - Origin = new ObjectOrigin(boundingBox.Extent, sceneView); - boundingBox.AddChildNode(Origin); - - NSNotificationCenter.DefaultCenter.PostNotificationName(ScannedObject.BoundingBoxCreatedNotificationName, null); - } - - internal void FitOverPointCloud(ARPointCloud pointCloud) + ghostBoundingBox = null; + + Origin = new ObjectOrigin (boundingBox.Extent, sceneView); + boundingBox.AddChildNode (Origin); + + NSNotificationCenter.DefaultCenter.PostNotificationName (ScannedObject.BoundingBoxCreatedNotificationName, null); + } + + internal void FitOverPointCloud (ARPointCloud pointCloud) { // Do the automatic adjustment of the bounding box only if the user // hasn't adjusted it yet. - if (boundingBox == null || boundingBox.HasBeenAdjustedByUser) - { - return; - } - - var hitTestResults = sceneView.HitTest(ViewController.Instance.ScreenCenter, ARHitTestResultType.FeaturePoint); - if (hitTestResults == null || hitTestResults.Length == 0) - { - return; - } - - var userFocusPoint = hitTestResults[0].WorldTransform.Position(); - var nUserFocusPoint = new NVector3(userFocusPoint.X, userFocusPoint.Y, userFocusPoint.Z); - boundingBox.FitOverPointCloud(pointCloud, nUserFocusPoint); - } - - internal void TryToAlignWithPlanes(ARPlaneAnchor[] anchors) - { - if (boundingBox != null) - { - boundingBox.TryToAlignWithPlanes(anchors); - } + if (boundingBox == null || boundingBox.HasBeenAdjustedByUser) { + return; + } + + var hitTestResults = sceneView.HitTest (ViewController.Instance.ScreenCenter, ARHitTestResultType.FeaturePoint); + if (hitTestResults == null || hitTestResults.Length == 0) { + return; + } + + var userFocusPoint = hitTestResults [0].WorldTransform.Position (); + var nUserFocusPoint = new NVector3 (userFocusPoint.X, userFocusPoint.Y, userFocusPoint.Z); + boundingBox.FitOverPointCloud (pointCloud, nUserFocusPoint); + } + + internal void TryToAlignWithPlanes (ARPlaneAnchor [] anchors) + { + if (boundingBox != null) { + boundingBox.TryToAlignWithPlanes (anchors); + } } - private void CreateBoundingBox(CGPoint screenPos) + private void CreateBoundingBox (CGPoint screenPos) { // Perform a hit test against the feature point cloud. - var result = sceneView.SmartHitTest(screenPos); - if (result == null) - { - Console.WriteLine("Warning: failed to find a position for the bounding box."); - return; - } - - if (boundingBox != null) - { - boundingBox.Dispose(); - } - boundingBox = new BoundingBox(sceneView); - Console.WriteLine($"boundingBox newed {boundingBox}"); - AddChildNode(boundingBox); + var result = sceneView.SmartHitTest (screenPos); + if (result == null) { + Console.WriteLine ("Warning: failed to find a position for the bounding box."); + return; + } + + if (boundingBox != null) { + boundingBox.Dispose (); + } + boundingBox = new BoundingBox (sceneView); + Console.WriteLine ($"boundingBox newed {boundingBox}"); + AddChildNode (boundingBox); // Set the initial extent of the bounding box based on the direction of the camera. - var newExtent = (float)result.Distance / 3; - boundingBox.Extent = new NVector3(newExtent, newExtent, newExtent); + var newExtent = (float) result.Distance / 3; + boundingBox.Extent = new NVector3 (newExtent, newExtent, newExtent); // Set the position of scanned object to a point on the ray which is offset // from the hit test result by half of the bounding box's extent. - var cameraToHit = result.WorldTransform.Position() - sceneView.PointOfView.WorldPosition; - var normalizedDirection = cameraToHit.Normalized(); - var boundingBoxOffset = normalizedDirection * (float)newExtent / 2; - WorldPosition = result.WorldTransform.Position() + boundingBoxOffset; - - Origin = new ObjectOrigin(boundingBox.Extent, sceneView); - boundingBox.AddChildNode(Origin); - - NSNotificationCenter.DefaultCenter.PostNotificationName(ScannedObject.BoundingBoxCreatedNotificationName, null); + var cameraToHit = result.WorldTransform.Position () - sceneView.PointOfView.WorldPosition; + var normalizedDirection = cameraToHit.Normalized (); + var boundingBoxOffset = normalizedDirection * (float) newExtent / 2; + WorldPosition = result.WorldTransform.Position () + boundingBoxOffset; + + Origin = new ObjectOrigin (boundingBox.Extent, sceneView); + boundingBox.AddChildNode (Origin); + + NSNotificationCenter.DefaultCenter.PostNotificationName (ScannedObject.BoundingBoxCreatedNotificationName, null); } - - private void UpdateOrCreateGhostBoundingBox() + + private void UpdateOrCreateGhostBoundingBox () { // Perform a hit test against the feature point cloud. - var result = sceneView.SmartHitTest(ViewController.Instance.ScreenCenter); - if (result == null) - { + var result = sceneView.SmartHitTest (ViewController.Instance.ScreenCenter); + if (result == null) { // No feature points in range (20cm to 3m), so remove ghostBoundingBox from display, if it exists at all // unless the `Scan` object has passed a reference to the ghostBoundingBox in to the asynch function `CreateReferenceObject` - if (ghostBoundingBox != null && !busyCreatingReferenceObject) - { - ghostBoundingBox.RemoveFromParentNode(); - Console.WriteLine($"Disposing ghostBoundingBox because there are no feature points"); - ghostBoundingBox.Dispose(); - ghostBoundingBox = null; - NSNotificationCenter.DefaultCenter.PostNotificationName(ScannedObject.GhostBoundingBoxRemovedNotificationName, null); - } - return; + if (ghostBoundingBox != null && !busyCreatingReferenceObject) { + ghostBoundingBox.RemoveFromParentNode (); + Console.WriteLine ($"Disposing ghostBoundingBox because there are no feature points"); + ghostBoundingBox.Dispose (); + ghostBoundingBox = null; + NSNotificationCenter.DefaultCenter.PostNotificationName (ScannedObject.GhostBoundingBoxRemovedNotificationName, null); + } + return; } //There are some feature points in range - var newExtent = (float)result.Distance / 3; + var newExtent = (float) result.Distance / 3; // Set the position of scanned object to a point on the ray which is offset // from the hit test result by half the bounding box's extent. - var cameraToHit = result.WorldTransform.Position() - sceneView.PointOfView.WorldPosition; - var normalizedDirection = cameraToHit.Normalized(); - var boundingBoxOffset = normalizedDirection * newExtent / 2; - WorldPosition = result.WorldTransform.Position() + boundingBoxOffset; - - if (ghostBoundingBox != null) - { + var cameraToHit = result.WorldTransform.Position () - sceneView.PointOfView.WorldPosition; + var normalizedDirection = cameraToHit.Normalized (); + var boundingBoxOffset = normalizedDirection * newExtent / 2; + WorldPosition = result.WorldTransform.Position () + boundingBoxOffset; + + if (ghostBoundingBox != null) { // Update the ghostBoundingBox's Extent and rotate it so that it faces the user - Console.WriteLine("Updating ghostBoundingBox Extent"); - ghostBoundingBox.Extent = new NVector3(newExtent, newExtent, newExtent); + Console.WriteLine ("Updating ghostBoundingBox Extent"); + ghostBoundingBox.Extent = new NVector3 (newExtent, newExtent, newExtent); // Change the orientation of the bounding box to always face the user. - var currentFrame = sceneView.Session.CurrentFrame; - if (currentFrame != null) - { - var cameraY = currentFrame.Camera.EulerAngles.Y; - Rotation = new SCNVector4(0, 1, 0, cameraY); - } - } - else - { + var currentFrame = sceneView.Session.CurrentFrame; + if (currentFrame != null) { + var cameraY = currentFrame.Camera.EulerAngles.Y; + Rotation = new SCNVector4 (0, 1, 0, cameraY); + } + } else { // Create a new ghostBoundingBox - ghostBoundingBox = new BoundingBox(sceneView); - Console.WriteLine($"ghostBoundingBox alloced {ghostBoundingBox}"); - ghostBoundingBox.Opacity = 0.25F; - AddChildNode(ghostBoundingBox); - ghostBoundingBox.Extent = new NVector3(newExtent, newExtent, newExtent); - NSNotificationCenter.DefaultCenter.PostNotificationName(ScannedObject.GhostBoundingBoxCreatedNotificationName, null); - } - } - - void MoveOriginToBottomOfBoundingBox() + ghostBoundingBox = new BoundingBox (sceneView); + Console.WriteLine ($"ghostBoundingBox alloced {ghostBoundingBox}"); + ghostBoundingBox.Opacity = 0.25F; + AddChildNode (ghostBoundingBox); + ghostBoundingBox.Extent = new NVector3 (newExtent, newExtent, newExtent); + NSNotificationCenter.DefaultCenter.PostNotificationName (ScannedObject.GhostBoundingBoxCreatedNotificationName, null); + } + } + + void MoveOriginToBottomOfBoundingBox () { // Only move the origin to the bottom of the bounding box if it hasn't been // repositioned by the user yet. - if (boundingBox == null || Origin == null || Origin.PositionHasBeenAdjustedByUser) - { - return; - } - - Origin.Position = new SCNVector3(Position.X, -boundingBox.Extent.Y / 2, Position.Z); - } - - void UpdatePosition(SCNVector3 worldPos) - { - var offset = worldPos - WorldPosition; - WorldPosition = worldPos; - - if (boundingBox != null) - { + if (boundingBox == null || Origin == null || Origin.PositionHasBeenAdjustedByUser) { + return; + } + + Origin.Position = new SCNVector3 (Position.X, -boundingBox.Extent.Y / 2, Position.Z); + } + + void UpdatePosition (SCNVector3 worldPos) + { + var offset = worldPos - WorldPosition; + WorldPosition = worldPos; + + if (boundingBox != null) { // Adjust the position of the bounding box to compensate for the // move, so that the bounding box stays where it was. - boundingBox.WorldPosition -= offset; - } + boundingBox.WorldPosition -= offset; + } } - - internal void UpdateOnEveryFrame() - { - if (boundingBox != null) - { - boundingBox.UpdateOnEveryFrame(); + + internal void UpdateOnEveryFrame () + { + if (boundingBox != null) { + boundingBox.UpdateOnEveryFrame (); // Note: SCNVector3 supports value equality & floating-point comparison, so the following is okay. - if (boundingBox.Position != new SCNVector3(0, 0, 0)) - { + if (boundingBox.Position != new SCNVector3 (0, 0, 0)) { // Make sure the position of the ScannedObject and its nested // BoundingBox is always identical. - UpdatePosition(boundingBox.WorldPosition); - } - } - else - { - UpdateOrCreateGhostBoundingBox(); - } - } - - internal void ScaleBoundingBox(float scale) + UpdatePosition (boundingBox.WorldPosition); + } + } else { + UpdateOrCreateGhostBoundingBox (); + } + } + + internal void ScaleBoundingBox (float scale) { - if (boundingBox == null) - { - return; - } - - var oldYExtent = boundingBox.Extent.Y; - - boundingBox.Extent = boundingBox.Extent.Times(scale); + if (boundingBox == null) { + return; + } + + var oldYExtent = boundingBox.Extent.Y; + + boundingBox.Extent = boundingBox.Extent.Times (scale); boundingBox.HasBeenAdjustedByUser = true; // Correct y position so that the floor of the box remains at the same position. - var diffOnY = oldYExtent - boundingBox.Extent.Y; - var bbwp = boundingBox.WorldPosition; - boundingBox.WorldPosition = new SCNVector3(bbwp.X, bbwp.Y - diffOnY / 2, bbwp.Z); + var diffOnY = oldYExtent - boundingBox.Extent.Y; + var bbwp = boundingBox.WorldPosition; + boundingBox.WorldPosition = new SCNVector3 (bbwp.X, bbwp.Y - diffOnY / 2, bbwp.Z); } - - - - private void ScanningStateChanged(NSNotification notification) - { - var state = notification.UserInfo[Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; - if (state == null) - { - return; - } - switch (state.Value) - { - case Scan.ScanState.Ready: - boundingBox?.RemoveFromParentNode(); - boundingBox?.Dispose(); - boundingBox = null; - break; - case Scan.ScanState.DefineBoundingBox: - if (boundingBox == null) - { - CreateBoundingBoxFromGhost(); - } - ghostBoundingBox?.RemoveFromParentNode(); - Console.WriteLine("Disposing ghostBoundingBox because I am defining the real bounding box"); - ghostBoundingBox?.Dispose(); - ghostBoundingBox = null; - break; - case Scan.ScanState.Scanning: - break; - case Scan.ScanState.AdjustingOrigin: - MoveOriginToBottomOfBoundingBox(); - break; - } + + + + private void ScanningStateChanged (NSNotification notification) + { + var state = notification.UserInfo [Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; + if (state == null) { + return; + } + switch (state.Value) { + case Scan.ScanState.Ready: + boundingBox?.RemoveFromParentNode (); + boundingBox?.Dispose (); + boundingBox = null; + break; + case Scan.ScanState.DefineBoundingBox: + if (boundingBox == null) { + CreateBoundingBoxFromGhost (); + } + ghostBoundingBox?.RemoveFromParentNode (); + Console.WriteLine ("Disposing ghostBoundingBox because I am defining the real bounding box"); + ghostBoundingBox?.Dispose (); + ghostBoundingBox = null; + break; + case Scan.ScanState.Scanning: + break; + case Scan.ScanState.AdjustingOrigin: + MoveOriginToBottomOfBoundingBox (); + break; + } } -#region Microsoft additions + #region Microsoft additions + + bool busyCreatingReferenceObject = false; - bool busyCreatingReferenceObject = false; - - // While asynchronous `SceneView.CreateSynchronousObject` is running, do not change refs or `Dispose()` bounding boxes + // While asynchronous `SceneView.CreateSynchronousObject` is running, do not change refs or `Dispose()` bounding boxes // (See README.MD "Avoiding ghostBoundingBox Dispose() asynch defect" - internal void LockBoundingBoxForReferenceObjectCreation(bool isBusyCreatingReferenceObject) + internal void LockBoundingBoxForReferenceObjectCreation (bool isBusyCreatingReferenceObject) { this.busyCreatingReferenceObject = isBusyCreatingReferenceObject; - } - - internal new void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - private bool disposed = false; - override protected void Dispose(bool disposing) - { - if (!disposed) - { - disposed = true; - if (disposing) - { - base.Dispose(); - } - - NSNotificationCenter.DefaultCenter.RemoveObserver(notificationObserverHandle); - Origin?.Dispose(); - BoundingBox?.Dispose(); - GhostBoundingBox?.Dispose(); - - } } -#endregion + internal new void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + private bool disposed = false; + override protected void Dispose (bool disposing) + { + if (!disposed) { + disposed = true; + if (disposing) { + base.Dispose (); + } + + NSNotificationCenter.DefaultCenter.RemoveObserver (notificationObserverHandle); + Origin?.Dispose (); + BoundingBox?.Dispose (); + GhostBoundingBox?.Dispose (); + + } + } + + #endregion } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedPointCloud.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedPointCloud.cs index a8ac58d75..d303980cc 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedPointCloud.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/ScannedPointCloud.cs @@ -1,4 +1,4 @@ -using SceneKit; +using SceneKit; using ARKit; using System; using OpenTK; @@ -7,119 +7,109 @@ using System.Linq; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { //A visualization of a 3D point cloud during object scanning - internal class ScannedPointCloud : SCNNode - { - private readonly SCNNode pointNode = new SCNNode(); + internal class ScannedPointCloud : SCNNode { + private readonly SCNNode pointNode = new SCNNode (); //The latest known set of points inside the reference object. - private List<SCNVector3> referenceObjectPoints = new List<SCNVector3>(); + private List<SCNVector3> referenceObjectPoints = new List<SCNVector3> (); // The set of currently rendered points, in world coordinates, // Note: We render them in world coordinates instead of local coordinates to // prevent rendering issues with points jittering e.g. when the bounding box // is rotated. - private List<SCNVector3> renderedPoints = new List<SCNVector3>(); + private List<SCNVector3> renderedPoints = new List<SCNVector3> (); private BoundingBox boundingBox; - private NSObject[] notificationObservationHandles; + private NSObject [] notificationObservationHandles; internal int Count { get => renderedPoints.Count; } - internal ScannedPointCloud() + internal ScannedPointCloud () { - base.Init(); + base.Init (); - AddChildNode(pointNode); + AddChildNode (pointNode); - notificationObservationHandles = new NSObject[4]; + notificationObservationHandles = new NSObject [4]; - notificationObservationHandles[0] = NSNotificationCenter.DefaultCenter.AddObserver(Scan.ScanningStateChangedNotificationName, ScanningStateChanged); - notificationObservationHandles[1] = NSNotificationCenter.DefaultCenter.AddObserver(BoundingBox.ExtentChangedNotificationName, BoundingBoxPositionOrExtentChanged); - notificationObservationHandles[2] = NSNotificationCenter.DefaultCenter.AddObserver(BoundingBox.PositionChangedNotificationName, BoundingBoxPositionOrExtentChanged); - notificationObservationHandles[3] = NSNotificationCenter.DefaultCenter.AddObserver(ScannedObject.PositionChangedNotificationName, ScannedObjectPositionChanged); + notificationObservationHandles [0] = NSNotificationCenter.DefaultCenter.AddObserver (Scan.ScanningStateChangedNotificationName, ScanningStateChanged); + notificationObservationHandles [1] = NSNotificationCenter.DefaultCenter.AddObserver (BoundingBox.ExtentChangedNotificationName, BoundingBoxPositionOrExtentChanged); + notificationObservationHandles [2] = NSNotificationCenter.DefaultCenter.AddObserver (BoundingBox.PositionChangedNotificationName, BoundingBoxPositionOrExtentChanged); + notificationObservationHandles [3] = NSNotificationCenter.DefaultCenter.AddObserver (ScannedObject.PositionChangedNotificationName, ScannedObjectPositionChanged); } - private void BoundingBoxPositionOrExtentChanged(NSNotification notification) + private void BoundingBoxPositionOrExtentChanged (NSNotification notification) { var boundingBox = notification.Object as BoundingBox; - if (boundingBox == null || boundingBox.IsDisposed) - { + if (boundingBox == null || boundingBox.IsDisposed) { return; } - UpdateBoundingBox(boundingBox); + UpdateBoundingBox (boundingBox); } - private void ScannedObjectPositionChanged(NSNotification notification) + private void ScannedObjectPositionChanged (NSNotification notification) { var scannedObject = notification.Object as ScannedObject; - if (scannedObject == null) - { + if (scannedObject == null) { return; } var boundingBox = scannedObject.BoundingBox != null ? scannedObject.BoundingBox : scannedObject.GhostBoundingBox; - if (!boundingBox.IsDisposed) - { - UpdateBoundingBox(boundingBox); + if (!boundingBox.IsDisposed) { + UpdateBoundingBox (boundingBox); } } - private void ScanningStateChanged(NSNotification notification) + private void ScanningStateChanged (NSNotification notification) { - var state = notification.UserInfo?[Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; - if (state == null) - { + var state = notification.UserInfo? [Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; + if (state == null) { return; } - switch (state.Value) - { - case Scan.ScanState.Ready: - case Scan.ScanState.Scanning: - case Scan.ScanState.DefineBoundingBox: - Hidden = false; - break; - case Scan.ScanState.AdjustingOrigin: - Hidden = true; - break; + switch (state.Value) { + case Scan.ScanState.Ready: + case Scan.ScanState.Scanning: + case Scan.ScanState.DefineBoundingBox: + Hidden = false; + break; + case Scan.ScanState.AdjustingOrigin: + Hidden = true; + break; } } - private void UpdateBoundingBox(BoundingBox boundingBox) => this.boundingBox = boundingBox; + private void UpdateBoundingBox (BoundingBox boundingBox) => this.boundingBox = boundingBox; - internal void Update(ARPointCloud pointCloud, BoundingBox boundingBox) + internal void Update (ARPointCloud pointCloud, BoundingBox boundingBox) { // Convert the points to world coordinates because we display them // in world coordinates. - var pointsInWorld = pointCloud.Points.Select(pt => boundingBox.ConvertPositionToNode(pt.ToSCNVector3(), null)); - referenceObjectPoints = pointsInWorld.ToList(); + var pointsInWorld = pointCloud.Points.Select (pt => boundingBox.ConvertPositionToNode (pt.ToSCNVector3 (), null)); + referenceObjectPoints = pointsInWorld.ToList (); } - internal void UpdateOnEveryFrame() + internal void UpdateOnEveryFrame () { - if (Hidden) - { + if (Hidden) { return; } - if (referenceObjectPoints.Count == 0 || boundingBox == null || boundingBox.IsDisposed) - { - pointNode.Geometry?.Dispose(); + if (referenceObjectPoints.Count == 0 || boundingBox == null || boundingBox.IsDisposed) { + pointNode.Geometry?.Dispose (); pointNode.Geometry = null; return; } - renderedPoints = new List<SCNVector3>(); + renderedPoints = new List<SCNVector3> (); - var min = -boundingBox.Extent.ToSCNVector3() / 2; - var max = boundingBox.Extent.ToSCNVector3() / 2; + var min = -boundingBox.Extent.ToSCNVector3 () / 2; + var max = boundingBox.Extent.ToSCNVector3 () / 2; // Abort if the bounding box has no extent yet - if (max.X <= float.Epsilon) - { + if (max.X <= float.Epsilon) { return; } @@ -127,40 +117,35 @@ internal void UpdateOnEveryFrame() // Note: The creation of the latest ARReferenceObject happens at a lower frequency // than rendering and updates of the bounding box, so some of the points may no longer // be in the inside of the box. - foreach (var point in referenceObjectPoints) - { + foreach (var point in referenceObjectPoints) { //See where point lies, relative to the bounding box - var localPoint = boundingBox.ConvertPositionFromNode(point, null); + var localPoint = boundingBox.ConvertPositionFromNode (point, null); if (localPoint.X >= min.X && localPoint.X <= max.X && localPoint.Y >= min.Y && localPoint.Y <= max.Y - && localPoint.Z >= min.Z && localPoint.Z <= max.Z) - { + && localPoint.Z >= min.Z && localPoint.Z <= max.Z) { // Add the point (not the localPoint!) to the visualization - renderedPoints.Add(point); + renderedPoints.Add (point); } } - pointNode.Geometry?.Dispose(); - pointNode.Geometry = PointCloud.CreateVisualization(renderedPoints.Select(p => p.ToNVector3()).ToArray(), Utilities.AppYellow, 12); + pointNode.Geometry?.Dispose (); + pointNode.Geometry = PointCloud.CreateVisualization (renderedPoints.Select (p => p.ToNVector3 ()).ToArray (), Utilities.AppYellow, 12); } private bool disposed = false; - override protected void Dispose(bool disposing) + override protected void Dispose (bool disposing) { - if (!disposed) - { + if (!disposed) { disposed = true; - if (disposing) - { - base.Dispose(); + if (disposing) { + base.Dispose (); } - foreach (var notificationObserverHandle in notificationObservationHandles) - { - NSNotificationCenter.DefaultCenter.RemoveObserver(notificationObserverHandle); + foreach (var notificationObserverHandle in notificationObservationHandles) { + NSNotificationCenter.DefaultCenter.RemoveObserver (notificationObserverHandle); } } } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Snapping.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Snapping.cs index 1e797b513..4ce66ee28 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Snapping.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Snapping.cs @@ -1,14 +1,12 @@ -using System; +using System; using Foundation; -using UIKit; -namespace ScanningAndDetecting3DObjects -{ - internal class Snapping - { - internal static void PlayHapticFeedback() - { - var feedbackGenerator = new UIImpactFeedbackGenerator(UIImpactFeedbackStyle.Light); - feedbackGenerator.ImpactOccurred(); +using UIKit; +namespace ScanningAndDetecting3DObjects { + internal class Snapping { + internal static void PlayHapticFeedback () + { + var feedbackGenerator = new UIImpactFeedbackGenerator (UIImpactFeedbackStyle.Light); + feedbackGenerator.ImpactOccurred (); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Tile.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Tile.cs index 7d00eaeee..eb32f7593 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Tile.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Tile.cs @@ -1,38 +1,35 @@ -using System; +using System; using SceneKit; using System.Linq; using System.Net; -namespace ScanningAndDetecting3DObjects -{ - internal class Tile : SCNNode - { - internal bool Captured { get; set; } +namespace ScanningAndDetecting3DObjects { + internal class Tile : SCNNode { + internal bool Captured { get; set; } - internal bool Highlighted { get; set; } + internal bool Highlighted { get; set; } - internal Tile(SCNPlane plane) + internal Tile (SCNPlane plane) { - base.Init(); + base.Init (); Geometry = plane; - Opacity = 0F; + Opacity = 0F; // Create a child node with another plane of the same size, but a darker color to stand out better // This helps users see captured tiles from the back. - if (ChildNodes.Length == 0) - { - var innerPlane = SCNPlane.Create(plane.Width, plane.Height); - innerPlane.Materials = new[] { Utilities.Material(Utilities.AppBrown.ColorWithAlpha(0.8F), false, false) }; - var innerNode = SCNNode.FromGeometry(innerPlane); - innerNode.EulerAngles = new SCNVector3(0, (float) Math.PI, 0); - AddChildNode(innerNode); + if (ChildNodes.Length == 0) { + var innerPlane = SCNPlane.Create (plane.Width, plane.Height); + innerPlane.Materials = new [] { Utilities.Material (Utilities.AppBrown.ColorWithAlpha (0.8F), false, false) }; + var innerNode = SCNNode.FromGeometry (innerPlane); + innerNode.EulerAngles = new SCNVector3 (0, (float) Math.PI, 0); + AddChildNode (innerNode); } } - internal void UpdateVisualization() + internal void UpdateVisualization () { var newOpacity = Captured ? 0.5 : 0.0; newOpacity += Highlighted ? 0.35 : 0.0; Opacity = (System.nfloat) newOpacity; } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Wireframe.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Wireframe.cs index 3d7f49756..27ca2e396 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Wireframe.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/3D_UI/Wireframe.cs @@ -1,177 +1,164 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using OpenTK; using SceneKit; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // A visualization of the edges of a 3D box. - internal class Wireframe : SCNNode - { - private double lineThickness = 0.002; - private List<SCNNode> lineNodes = new List<SCNNode>(); - private UIColor color = Utilities.AppYellow; - private NSTimer flashTimer; - private const double flashDuration = 0.1; - - - internal Wireframe(NVector3 extent, UIColor color, double scale = 1.0) - { - base.Init(); - - this.color = color; - lineThickness *= scale; - - // Repeat 12x - for (int i = 1; i <= 12; i++) - { - var line = new SCNNode(); - lineNodes.Add(line); - AddChildNode(line); - } - - Setup(extent); - - NSNotificationCenter.DefaultCenter.AddObserver(ObjectOrigin.MovedOutsideBoxNotificiationName, Flash); + internal class Wireframe : SCNNode { + private double lineThickness = 0.002; + private List<SCNNode> lineNodes = new List<SCNNode> (); + private UIColor color = Utilities.AppYellow; + private NSTimer flashTimer; + private const double flashDuration = 0.1; + + + internal Wireframe (NVector3 extent, UIColor color, double scale = 1.0) + { + base.Init (); + + this.color = color; + lineThickness *= scale; + + // Repeat 12x + for (int i = 1; i <= 12; i++) { + var line = new SCNNode (); + lineNodes.Add (line); + AddChildNode (line); + } + + Setup (extent); + + NSNotificationCenter.DefaultCenter.AddObserver (ObjectOrigin.MovedOutsideBoxNotificiationName, Flash); } - private void Setup(NVector3 extent) + private void Setup (NVector3 extent) { // Translate and rotate line nodes to the correct transform - var halfX = extent.X / 2; - var halfY = extent.Y / 2; - var halfZ = extent.Z / 2; - - // Two helper functions to isolate the allocations and casts - Action<SCNNode,float, float, float> xlat = (node, extentX, extentY, extentZ) => node.LocalTranslate(new SCNVector3(extentX, extentY, extentZ)); - - Action<SCNNode, float, float, float, Axis> xlatAndRot = (node, extentX, extentY, extentZ, axis) => - { - xlat(node, extentX, extentY, extentZ); - node.LocalRotate(SCNQuaternion.FromAxisAngle(axis.Normal().ToSCNVector3(), (float) -Math.PI / 2)); - }; - - var halfWidth = extent.X / 2; - var halfHeight = extent.Y / 2; - var halfDepth = extent.Z / 2; - xlatAndRot( lineNodes[0], 0, -halfHeight, -halfDepth, Axis.Z); - xlatAndRot( lineNodes[1], -halfWidth, -halfHeight, 0, Axis.X); - xlatAndRot( lineNodes[2], 0, -halfHeight, halfDepth, Axis.Z); - xlatAndRot( lineNodes[3], halfWidth, -halfHeight, 0, Axis.X); - xlat( lineNodes[4], -extent.X, 0, -halfDepth); - xlat( lineNodes[5], -halfWidth, 0, halfDepth); - xlat( lineNodes[6], halfWidth, 0, -halfDepth); - xlat( lineNodes[7], halfWidth, 0, halfDepth); - xlatAndRot( lineNodes[8], 0, halfHeight, -halfDepth, Axis.Z); - xlatAndRot( lineNodes[9], -halfWidth, halfHeight, 0, Axis.X); - xlatAndRot(lineNodes[10], 0, halfHeight, halfDepth, Axis.Z); - xlatAndRot(lineNodes[11], halfWidth, halfHeight, 0, Axis.X); + var halfX = extent.X / 2; + var halfY = extent.Y / 2; + var halfZ = extent.Z / 2; + + // Two helper functions to isolate the allocations and casts + Action<SCNNode, float, float, float> xlat = (node, extentX, extentY, extentZ) => node.LocalTranslate (new SCNVector3 (extentX, extentY, extentZ)); + + Action<SCNNode, float, float, float, Axis> xlatAndRot = (node, extentX, extentY, extentZ, axis) => { + xlat (node, extentX, extentY, extentZ); + node.LocalRotate (SCNQuaternion.FromAxisAngle (axis.Normal ().ToSCNVector3 (), (float) -Math.PI / 2)); + }; + + var halfWidth = extent.X / 2; + var halfHeight = extent.Y / 2; + var halfDepth = extent.Z / 2; + xlatAndRot (lineNodes [0], 0, -halfHeight, -halfDepth, Axis.Z); + xlatAndRot (lineNodes [1], -halfWidth, -halfHeight, 0, Axis.X); + xlatAndRot (lineNodes [2], 0, -halfHeight, halfDepth, Axis.Z); + xlatAndRot (lineNodes [3], halfWidth, -halfHeight, 0, Axis.X); + xlat (lineNodes [4], -extent.X, 0, -halfDepth); + xlat (lineNodes [5], -halfWidth, 0, halfDepth); + xlat (lineNodes [6], halfWidth, 0, -halfDepth); + xlat (lineNodes [7], halfWidth, 0, halfDepth); + xlatAndRot (lineNodes [8], 0, halfHeight, -halfDepth, Axis.Z); + xlatAndRot (lineNodes [9], -halfWidth, halfHeight, 0, Axis.X); + xlatAndRot (lineNodes [10], 0, halfHeight, halfDepth, Axis.Z); + xlatAndRot (lineNodes [11], halfWidth, halfHeight, 0, Axis.X); // Assign geometries - lineNodes[0].Geometry = Cylinder(extent.X); - lineNodes[1].Geometry = Cylinder(extent.Z); - lineNodes[2].Geometry = Cylinder(extent.X); - lineNodes[3].Geometry = Cylinder(extent.Z); - lineNodes[4].Geometry = Cylinder(extent.Y); - lineNodes[5].Geometry = Cylinder(extent.Y); - lineNodes[6].Geometry = Cylinder(extent.Y); - lineNodes[7].Geometry = Cylinder(extent.Y); - lineNodes[8].Geometry = Cylinder(extent.X); - lineNodes[9].Geometry = Cylinder(extent.Z); - lineNodes[10].Geometry = Cylinder(extent.X); - lineNodes[11].Geometry = Cylinder(extent.Z); + lineNodes [0].Geometry = Cylinder (extent.X); + lineNodes [1].Geometry = Cylinder (extent.Z); + lineNodes [2].Geometry = Cylinder (extent.X); + lineNodes [3].Geometry = Cylinder (extent.Z); + lineNodes [4].Geometry = Cylinder (extent.Y); + lineNodes [5].Geometry = Cylinder (extent.Y); + lineNodes [6].Geometry = Cylinder (extent.Y); + lineNodes [7].Geometry = Cylinder (extent.Y); + lineNodes [8].Geometry = Cylinder (extent.X); + lineNodes [9].Geometry = Cylinder (extent.Z); + lineNodes [10].Geometry = Cylinder (extent.X); + lineNodes [11].Geometry = Cylinder (extent.Z); } - private SCNGeometry Cylinder(float height, float? width = null, UIColor colorArg = null ){ - var radius = width == null ? (float)lineThickness / 2 : width.Value / 2; - var clr = colorArg ?? this.color; - var cylinderGeometry = SCNCylinder.Create(radius, height); - cylinderGeometry.Materials = new[] { Utilities.Material(clr) }; + private SCNGeometry Cylinder (float height, float? width = null, UIColor colorArg = null) + { + var radius = width == null ? (float) lineThickness / 2 : width.Value / 2; + var clr = colorArg ?? this.color; + var cylinderGeometry = SCNCylinder.Create (radius, height); + cylinderGeometry.Materials = new [] { Utilities.Material (clr) }; return cylinderGeometry; } - bool highlighted; - internal bool Highlighted - { - get => highlighted; - set - { - highlighted = value; - if (highlighted) - { - foreach (var child in ChildNodes) - { - if (child.Geometry != null) - { - child.Geometry.Materials = new[] { Utilities.Material(UIColor.Red) }; - } - } - } - else - { - foreach (var child in ChildNodes) - { - if (child.Geometry != null) - { - child.Geometry.Materials = new[] { Utilities.Material(color) }; - } - } - } - } + bool highlighted; + internal bool Highlighted { + get => highlighted; + set { + highlighted = value; + if (highlighted) { + foreach (var child in ChildNodes) { + if (child.Geometry != null) { + child.Geometry.Materials = new [] { Utilities.Material (UIColor.Red) }; + } + } + } else { + foreach (var child in ChildNodes) { + if (child.Geometry != null) { + child.Geometry.Materials = new [] { Utilities.Material (color) }; + } + } + } + } } - internal void Update(NVector3 extent) + internal void Update (NVector3 extent) { - if (lineNodes.Count != 12) - { - return; + if (lineNodes.Count != 12) { + return; } - - var halfWidth = extent.X / 2; - var halfHeight = extent.Y / 2; + + var halfWidth = extent.X / 2; + var halfHeight = extent.Y / 2; var halfDepth = extent.Z / 2; // Translate and rotate line nodes to the right transform - lineNodes[0].Position = new SCNVector3(0, -halfHeight, -halfDepth); - lineNodes[1].Position = new SCNVector3(-halfWidth, -halfHeight, 0); - lineNodes[2].Position = new SCNVector3(0, -halfHeight, halfDepth); - lineNodes[3].Position = new SCNVector3(halfWidth, -halfHeight, 0); - lineNodes[4].Position = new SCNVector3(-halfWidth, 0, -halfDepth); - lineNodes[5].Position = new SCNVector3(-halfWidth, 0, halfDepth); - lineNodes[6].Position = new SCNVector3(halfWidth, 0, -halfDepth); - lineNodes[7].Position = new SCNVector3(halfWidth, 0, halfDepth); - lineNodes[8].Position = new SCNVector3(0, halfHeight, -halfDepth); - lineNodes[9].Position = new SCNVector3(-halfWidth, halfHeight, 0); - lineNodes[10].Position = new SCNVector3(0, halfHeight, halfDepth); - lineNodes[11].Position = new SCNVector3(halfWidth, halfHeight, 0); + lineNodes [0].Position = new SCNVector3 (0, -halfHeight, -halfDepth); + lineNodes [1].Position = new SCNVector3 (-halfWidth, -halfHeight, 0); + lineNodes [2].Position = new SCNVector3 (0, -halfHeight, halfDepth); + lineNodes [3].Position = new SCNVector3 (halfWidth, -halfHeight, 0); + lineNodes [4].Position = new SCNVector3 (-halfWidth, 0, -halfDepth); + lineNodes [5].Position = new SCNVector3 (-halfWidth, 0, halfDepth); + lineNodes [6].Position = new SCNVector3 (halfWidth, 0, -halfDepth); + lineNodes [7].Position = new SCNVector3 (halfWidth, 0, halfDepth); + lineNodes [8].Position = new SCNVector3 (0, halfHeight, -halfDepth); + lineNodes [9].Position = new SCNVector3 (-halfWidth, halfHeight, 0); + lineNodes [10].Position = new SCNVector3 (0, halfHeight, halfDepth); + lineNodes [11].Position = new SCNVector3 (halfWidth, halfHeight, 0); // Update the line's heights - Action<SCNNode, float> ht = (node, height) => (node.Geometry as SCNCylinder).Height = height; - ht(lineNodes[0], extent.X); - ht(lineNodes[1], extent.Z); - ht(lineNodes[2], extent.X); - ht(lineNodes[3], extent.Z); - - ht(lineNodes[4], extent.Y); - ht(lineNodes[5], extent.Y); - ht(lineNodes[6], extent.Y); - ht(lineNodes[7], extent.Y); - - ht(lineNodes[8], extent.X); - ht(lineNodes[9], extent.Z); - ht(lineNodes[10], extent.X); - ht(lineNodes[11], extent.Z); - } - - - private void Flash(NSNotification notification) - { - Highlighted = true; - - flashTimer?.Invalidate(); - flashTimer = NSTimer.CreateScheduledTimer(flashDuration, (_) => Highlighted = false); + Action<SCNNode, float> ht = (node, height) => (node.Geometry as SCNCylinder).Height = height; + ht (lineNodes [0], extent.X); + ht (lineNodes [1], extent.Z); + ht (lineNodes [2], extent.X); + ht (lineNodes [3], extent.Z); + + ht (lineNodes [4], extent.Y); + ht (lineNodes [5], extent.Y); + ht (lineNodes [6], extent.Y); + ht (lineNodes [7], extent.Y); + + ht (lineNodes [8], extent.X); + ht (lineNodes [9], extent.Z); + ht (lineNodes [10], extent.X); + ht (lineNodes [11], extent.Z); + } + + + private void Flash (NSNotification notification) + { + Highlighted = true; + + flashTimer?.Invalidate (); + flashTimer = NSTimer.CreateScheduledTimer (flashDuration, (_) => Highlighted = false); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/AppDelegate.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/AppDelegate.cs index 18464dca7..2ede32bdf 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/AppDelegate.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/AppDelegate.cs @@ -1,86 +1,76 @@ -using ARKit; -using Foundation; -using UIKit; -using System; -using System.Xml.Serialization; - -namespace ScanningAndDetecting3DObjects -{ - [Register("AppDelegate")] - internal class AppDelegate : UIApplicationDelegate - { - internal static void FatalError(string msg) - { - Console.WriteLine(msg); - throw new Exception(msg); - } - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - //Note regarding the compiler warning: These are valid C# warnings, as these will resolve against ARConfiguration's static property. Needs library fix. - // - if (! (ARObjectScanningConfiguration.IsSupported && ARWorldTrackingConfiguration.IsSupported) ) - { - FatalError(@" - ARKit is not available on this device.For apps that require ARKit - for core functionality, use the `arkit` key in the key in the - `UIRequiredDeviceCapabilities` section of the Info.plist to prevent - the app from installing. (If the app can't be installed, this error - can't be triggered in a production scenario.) - - In apps where AR is an additive feature, use `isSupported` to - determine whether to show UI for launching AR experiences. - "); - } - return true; - } - - public override bool OpenUrl(UIApplication application, NSUrl url, NSDictionary options) - { - var viewController = Window.RootViewController as ViewController; - if (viewController != null) - { - viewController.ModelUrl = url; - return true; - } - else - { - return false; - } - } - - public override void WillEnterForeground(UIApplication application) - { - var viewController = Window.RootViewController as ViewController; - if (viewController != null) - { - viewController.BackFromBackground(); - } - } - - public override void OnResignActivation(UIApplication application) +using ARKit; +using Foundation; +using UIKit; +using System; +using System.Xml.Serialization; + +namespace ScanningAndDetecting3DObjects { + [Register ("AppDelegate")] + internal class AppDelegate : UIApplicationDelegate { + internal static void FatalError (string msg) { - var viewController = Window.RootViewController as ViewController; - if (viewController != null) - { - viewController.ShowBlurView(false); + Console.WriteLine (msg); + throw new Exception (msg); + } + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + //Note regarding the compiler warning: These are valid C# warnings, as these will resolve against ARConfiguration's static property. Needs library fix. + // + if (!(ARObjectScanningConfiguration.IsSupported && ARWorldTrackingConfiguration.IsSupported)) { + FatalError (@" + ARKit is not available on this device.For apps that require ARKit + for core functionality, use the `arkit` key in the key in the + `UIRequiredDeviceCapabilities` section of the Info.plist to prevent + the app from installing. (If the app can't be installed, this error + can't be triggered in a production scenario.) + + In apps where AR is an additive feature, use `isSupported` to + determine whether to show UI for launching AR experiences. + "); + } + return true; + } + + public override bool OpenUrl (UIApplication application, NSUrl url, NSDictionary options) + { + var viewController = Window.RootViewController as ViewController; + if (viewController != null) { + viewController.ModelUrl = url; + return true; + } else { + return false; + } + } + + public override void WillEnterForeground (UIApplication application) + { + var viewController = Window.RootViewController as ViewController; + if (viewController != null) { + viewController.BackFromBackground (); + } + } + + public override void OnResignActivation (UIApplication application) + { + var viewController = Window.RootViewController as ViewController; + if (viewController != null) { + viewController.ShowBlurView (false); } - } - - public override void OnActivated(UIApplication application) + } + + public override void OnActivated (UIApplication application) { - var viewController = Window.RootViewController as ViewController; - if (viewController != null) - { - viewController.ShowBlurView(true); + var viewController = Window.RootViewController as ViewController; + if (viewController != null) { + viewController.ShowBlurView (true); } - } - } -} - + } + } +} + diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/Scan.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/Scan.cs index 778bb0d25..41958cdd6 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/Scan.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/Scan.cs @@ -1,132 +1,113 @@ -using System; +using System; using Foundation; using SceneKit; using ARKit; using UIKit; using CoreVideo; using CoreImage; -namespace ScanningAndDetecting3DObjects -{ - internal class Scan : NSObject, IDisposable - { - internal enum ScanState - { +namespace ScanningAndDetecting3DObjects { + internal class Scan : NSObject, IDisposable { + internal enum ScanState { Ready, DefineBoundingBox, Scanning, AdjustingOrigin, } - internal static readonly NSString ScanningStateChangedNotificationName = new NSString("ScanningStateChanged"); - internal static readonly NSString StateUserInfoKey = new NSString("ScanState"); + internal static readonly NSString ScanningStateChangedNotificationName = new NSString ("ScanningStateChanged"); + internal static readonly NSString StateUserInfoKey = new NSString ("ScanState"); ScanState state = ScanState.Ready; - internal ScanState State - { + internal ScanState State { get => state; - set - { - Action tooBigOrSmall = () => - { + set { + Action tooBigOrSmall = () => { var title = "Scanned object too big or small"; var message = @""" Each dimension of the bounding box should be at least 1 cm and not exceed 5 meters. In addition, the volume of the bounding box should be at least 500 cubic cm. Do you want to go back and adjust the bounding box of the scanned object?"""; var prevState = state; - ViewController.Instance?.ShowAlert(title, message, "Yes", true, (_) => this.State = prevState); + ViewController.Instance?.ShowAlert (title, message, "Yes", true, (_) => this.State = prevState); }; // Check that the preconditions for the state change are met. - switch (value) - { - case ScanState.Ready: break; - case ScanState.DefineBoundingBox: - if (!BoundingBoxExists && !GhostBoundingBoxExists) - { - Console.WriteLine("Error: Ghost bounding box not yet created."); - return; - } + switch (value) { + case ScanState.Ready: break; + case ScanState.DefineBoundingBox: + if (!BoundingBoxExists && !GhostBoundingBoxExists) { + Console.WriteLine ("Error: Ghost bounding box not yet created."); + return; + } + break; + case ScanState.Scanning: + if (!BoundingBoxExists) { + Console.WriteLine ("Error: Bounding box not yet created."); + return; + } + if (state == ScanState.DefineBoundingBox && !IsReasonablySized ()) { + tooBigOrSmall (); break; - case ScanState.Scanning: - if (!BoundingBoxExists) - { - Console.WriteLine("Error: Bounding box not yet created."); - return; - } - if (state == ScanState.DefineBoundingBox && !IsReasonablySized()) - { - tooBigOrSmall(); - break; - } - // When entering the scanning state, take a screenshot of the object to be scanned. - // This screenshot will later be saved in the *.arbobject file - CreateScreenshot(); + } + // When entering the scanning state, take a screenshot of the object to be scanned. + // This screenshot will later be saved in the *.arbobject file + CreateScreenshot (); + break; + case ScanState.AdjustingOrigin: + if (!BoundingBoxExists) { + Console.WriteLine ("Error: Bounding box not yet created."); + return; + } + if (state == ScanState.Scanning && !IsReasonablySized ()) { + tooBigOrSmall (); break; - case ScanState.AdjustingOrigin: - if (!BoundingBoxExists) - { - Console.WriteLine("Error: Bounding box not yet created."); - return; - } - if (state == ScanState.Scanning && !IsReasonablySized()) - { - tooBigOrSmall(); - break; - } - if (state == ScanState.Scanning && QualityIsLow) - { - var title = "Not enough detail"; - var message = $"This scan has not enough detail (it contains {pointCloud.Count} features -- " + - $"aim for at least {minFeatureCount}).\n" + - "It is unlikely that a good reference object can be generated.\n" + + } + if (state == ScanState.Scanning && QualityIsLow) { + var title = "Not enough detail"; + var message = $"This scan has not enough detail (it contains {pointCloud.Count} features -- " + + $"aim for at least {minFeatureCount}).\n" + + "It is unlikely that a good reference object can be generated.\n" + + "Do you want to go back and continue the scan?"; + ViewController.Instance?.ShowAlert (title, message, "Yes", true, (_) => State = ScanState.Scanning); + break; + } + if (state == ScanState.Scanning) { + var boundingBox = scannedObject.BoundingBox; + if (boundingBox != null && boundingBox.ProgressPercentage < 100) { + var title = "Scan not complete"; + var message = $"The object was not scanned from all sides, scanning progress is {boundingBox.ProgressPercentage}%.\n" + + "It is likely that it won't detect from all angles.\n" + "Do you want to go back and continue the scan?"; - ViewController.Instance?.ShowAlert(title, message, "Yes", true, (_) => State = ScanState.Scanning); - break; + ViewController.Instance?.ShowAlert (title, message, "Yes", true, (_) => State = ScanState.Scanning); } - if (state == ScanState.Scanning) - { - var boundingBox = scannedObject.BoundingBox; - if (boundingBox != null && boundingBox.ProgressPercentage < 100) - { - var title = "Scan not complete"; - var message = $"The object was not scanned from all sides, scanning progress is {boundingBox.ProgressPercentage}%.\n" + - "It is likely that it won't detect from all angles.\n" + - "Do you want to go back and continue the scan?"; - ViewController.Instance?.ShowAlert(title, message, "Yes", true, (_) => State = ScanState.Scanning); - } - } - break; - default: break; + } + break; + default: break; } //Apply the new state state = value; - var userInfo = NSDictionary.FromObjectAndKey(new SimpleBox<ScanState>(state), Scan.StateUserInfoKey); - var notification = NSNotification.FromName(Scan.ScanningStateChangedNotificationName, this, userInfo); - NSNotificationCenter.DefaultCenter.PostNotification(notification); + var userInfo = NSDictionary.FromObjectAndKey (new SimpleBox<ScanState> (state), Scan.StateUserInfoKey); + var notification = NSNotification.FromName (Scan.ScanningStateChangedNotificationName, this, userInfo); + NSNotificationCenter.DefaultCenter.PostNotification (notification); } } // The object which we want to scan ScannedObject scannedObject; - internal ScannedObject ScannedObject - { + internal ScannedObject ScannedObject { get => scannedObject; } - internal SCNNode ObjectToManipulate - { - get - { - switch (state) - { - case ScanState.AdjustingOrigin: return scannedObject.Origin; - default: return scannedObject.EitherBoundingBox; + internal SCNNode ObjectToManipulate { + get { + switch (state) { + case ScanState.AdjustingOrigin: return scannedObject.Origin; + default: return scannedObject.EitherBoundingBox; } } } @@ -141,367 +122,332 @@ internal SCNNode ObjectToManipulate bool isBusyCreatingReferenceObject = false; - UIImage screenshot = new UIImage(); + UIImage screenshot = new UIImage (); internal UIImage Screenshot { get => screenshot; } bool hasWarnedAboutLowLight = false; const int minFeatureCount = 100; - internal Scan(ARSCNView scnView) + internal Scan (ARSCNView scnView) { this.sceneView = scnView; - scannedObject = new ScannedObject(sceneView); - pointCloud = new ScannedPointCloud(); + scannedObject = new ScannedObject (sceneView); + pointCloud = new ScannedPointCloud (); - NSNotificationCenter.DefaultCenter.AddObserver(ViewControllerApplicationState.ApplicationStateChangedNotificationName, ApplicationStateChanged); - sceneView.Scene.RootNode.AddChildNode(scannedObject); - sceneView.Scene.RootNode.AddChildNode(pointCloud); + NSNotificationCenter.DefaultCenter.AddObserver (ViewControllerApplicationState.ApplicationStateChangedNotificationName, ApplicationStateChanged); + sceneView.Scene.RootNode.AddChildNode (scannedObject); + sceneView.Scene.RootNode.AddChildNode (pointCloud); } - internal new void Dispose() + internal new void Dispose () { - Dispose(true); - GC.SuppressFinalize(this); + Dispose (true); + GC.SuppressFinalize (this); } - protected override void Dispose(bool disposing) + protected override void Dispose (bool disposing) { - if (disposing) - { - scannedObject?.RemoveFromParentNode(); - pointCloud?.RemoveFromParentNode(); + if (disposing) { + scannedObject?.RemoveFromParentNode (); + pointCloud?.RemoveFromParentNode (); - scannedObject?.Dispose(); - pointCloud?.Dispose(); + scannedObject?.Dispose (); + pointCloud?.Dispose (); } } - private void ApplicationStateChanged(NSNotification notification) + private void ApplicationStateChanged (NSNotification notification) { - var newAppState = notification.UserInfo[ViewControllerApplicationState.AppStateUserInfoKey] as SimpleBox<AppState>; - switch (newAppState.Value) - { - case AppState.Scanning: - scannedObject.Hidden = false; - pointCloud.Hidden = false; - break; - default: - scannedObject.Hidden = true; - pointCloud.Hidden = true; - break; + var newAppState = notification.UserInfo [ViewControllerApplicationState.AppStateUserInfoKey] as SimpleBox<AppState>; + switch (newAppState.Value) { + case AppState.Scanning: + scannedObject.Hidden = false; + pointCloud.Hidden = false; + break; + default: + scannedObject.Hidden = true; + pointCloud.Hidden = true; + break; } } - internal void DidOneFingerPan(UIPanGestureRecognizer gesture) + internal void DidOneFingerPan (UIPanGestureRecognizer gesture) { - var gesturePos = gesture.LocationInView(sceneView); - switch (State) - { - case ScanState.Ready: - State = ScanState.DefineBoundingBox; - // Recurse (note that state has changed, so DefineBoundingBox clause will execute) - DidOneFingerPan(gesture); + var gesturePos = gesture.LocationInView (sceneView); + switch (State) { + case ScanState.Ready: + State = ScanState.DefineBoundingBox; + // Recurse (note that state has changed, so DefineBoundingBox clause will execute) + DidOneFingerPan (gesture); + break; + case ScanState.DefineBoundingBox: + case ScanState.Scanning: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: break; - case ScanState.DefineBoundingBox: - case ScanState.Scanning: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: - break; - case UIGestureRecognizerState.Began: - scannedObject.BoundingBox?.StartSidePlaneDrag(gesturePos); - break; - case UIGestureRecognizerState.Changed: - scannedObject.BoundingBox?.UpdateSidePlaneDrag(gesturePos); - break; - default: - scannedObject.BoundingBox?.EndSidePlaneDrag(); - break; - } + case UIGestureRecognizerState.Began: + scannedObject.BoundingBox?.StartSidePlaneDrag (gesturePos); break; - case ScanState.AdjustingOrigin: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: - break; - case UIGestureRecognizerState.Began: - scannedObject.Origin?.StartAxisDrag(gesturePos); - break; - case UIGestureRecognizerState.Changed: - scannedObject.Origin?.UpdateAxisDrag(gesturePos); - break; - default: - scannedObject.Origin?.EndAxisDrag(); - break; - } + case UIGestureRecognizerState.Changed: + scannedObject.BoundingBox?.UpdateSidePlaneDrag (gesturePos); + break; + default: + scannedObject.BoundingBox?.EndSidePlaneDrag (); + break; + } + break; + case ScanState.AdjustingOrigin: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: break; + case UIGestureRecognizerState.Began: + scannedObject.Origin?.StartAxisDrag (gesturePos); + break; + case UIGestureRecognizerState.Changed: + scannedObject.Origin?.UpdateAxisDrag (gesturePos); + break; + default: + scannedObject.Origin?.EndAxisDrag (); + break; + } + break; } } - internal void DidTwoFingerPan(ThresholdPanGestureRecognizer gesture) + internal void DidTwoFingerPan (ThresholdPanGestureRecognizer gesture) { - var gestureOffsetPos = gesture.OffsetLocationIn(sceneView); - Action<Action> RunIfTwoTouch = (fn) => - { - if (gesture.NumberOfTouches == 2) fn(); + var gestureOffsetPos = gesture.OffsetLocationIn (sceneView); + Action<Action> RunIfTwoTouch = (fn) => { + if (gesture.NumberOfTouches == 2) fn (); }; - switch (State) - { - case ScanState.Ready: - State = ScanState.DefineBoundingBox; - // Recurse (note that state has changed, so DefineBoundingBox clause will execute) - DidTwoFingerPan(gesture); + switch (State) { + case ScanState.Ready: + State = ScanState.DefineBoundingBox; + // Recurse (note that state has changed, so DefineBoundingBox clause will execute) + DidTwoFingerPan (gesture); + break; + case ScanState.DefineBoundingBox: + case ScanState.Scanning: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: break; + case UIGestureRecognizerState.Began: + RunIfTwoTouch (() => scannedObject.BoundingBox?.StartGroundPlaneDrag (gestureOffsetPos)); break; - case ScanState.DefineBoundingBox: - case ScanState.Scanning: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: break; - case UIGestureRecognizerState.Began: - RunIfTwoTouch(() => scannedObject.BoundingBox?.StartGroundPlaneDrag(gestureOffsetPos)); - break; - case UIGestureRecognizerState.Changed: - if (gesture.ThresholdExceeded) - { - RunIfTwoTouch(() => scannedObject.BoundingBox?.UpdateGroundPlaneDrag(gestureOffsetPos)); - } - break; - default: - scannedObject.BoundingBox?.EndGroundPlaneDrag(); - break; + case UIGestureRecognizerState.Changed: + if (gesture.ThresholdExceeded) { + RunIfTwoTouch (() => scannedObject.BoundingBox?.UpdateGroundPlaneDrag (gestureOffsetPos)); } break; - case ScanState.AdjustingOrigin: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: break; - case UIGestureRecognizerState.Began: - RunIfTwoTouch(() => scannedObject.Origin?.StartPlaneDrag(gestureOffsetPos)); - break; - case UIGestureRecognizerState.Changed: - if (gesture.ThresholdExceeded) - { - RunIfTwoTouch(() => scannedObject.Origin?.UpdatePlaneDrag(gestureOffsetPos)); - } - break; - default: - scannedObject.Origin?.EndPlaneDrag(); - break; - } + default: + scannedObject.BoundingBox?.EndGroundPlaneDrag (); break; - } - } - - internal void DidRotate(ThresholdRotationGestureRecognizer gesture) - { - switch (State) - { - case ScanState.Ready: - State = ScanState.DefineBoundingBox; - // Recurse (note that state has changed, so DefineBoundingBox clause will execute) - DidRotate(gesture); + } + break; + case ScanState.AdjustingOrigin: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: break; + case UIGestureRecognizerState.Began: + RunIfTwoTouch (() => scannedObject.Origin?.StartPlaneDrag (gestureOffsetPos)); break; - case ScanState.DefineBoundingBox: - case ScanState.Scanning: - if (gesture.State == UIGestureRecognizerState.Changed) - { - scannedObject.RotateOnYAxis((float)-gesture.RotationDelta); + case UIGestureRecognizerState.Changed: + if (gesture.ThresholdExceeded) { + RunIfTwoTouch (() => scannedObject.Origin?.UpdatePlaneDrag (gestureOffsetPos)); } break; - case ScanState.AdjustingOrigin: - if (gesture.State == UIGestureRecognizerState.Changed) - { - scannedObject.Origin?.RotateWithSnappingOnYAxis((float)-gesture.RotationDelta); - } + default: + scannedObject.Origin?.EndPlaneDrag (); break; + } + break; } } - internal void DidLongPress(UILongPressGestureRecognizer gesture) + internal void DidRotate (ThresholdRotationGestureRecognizer gesture) { - var gesturePos = gesture.LocationInView(sceneView); - switch (State) - { - case ScanState.Ready: - State = ScanState.DefineBoundingBox; - // Recurse (note that state has changed, so DefineBoundingBox clause will execute) - DidLongPress(gesture); - break; - case ScanState.DefineBoundingBox: - case ScanState.Scanning: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: - break; - case UIGestureRecognizerState.Began: - scannedObject.BoundingBox?.StartSideDrag(gesturePos); - break; - case UIGestureRecognizerState.Changed: - scannedObject.BoundingBox?.UpdateSideDrag(gesturePos); - break; - default: - scannedObject.BoundingBox?.EndSideDrag(); - break; - } - break; - case ScanState.AdjustingOrigin: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: break; - case UIGestureRecognizerState.Began: - scannedObject.Origin?.StartAxisDrag(gesturePos); - break; - case UIGestureRecognizerState.Changed: - scannedObject.Origin?.UpdateAxisDrag(gesturePos); - break; - default: - scannedObject.Origin?.EndAxisDrag(); - break; - } - break; + switch (State) { + case ScanState.Ready: + State = ScanState.DefineBoundingBox; + // Recurse (note that state has changed, so DefineBoundingBox clause will execute) + DidRotate (gesture); + break; + case ScanState.DefineBoundingBox: + case ScanState.Scanning: + if (gesture.State == UIGestureRecognizerState.Changed) { + scannedObject.RotateOnYAxis ((float) -gesture.RotationDelta); + } + break; + case ScanState.AdjustingOrigin: + if (gesture.State == UIGestureRecognizerState.Changed) { + scannedObject.Origin?.RotateWithSnappingOnYAxis ((float) -gesture.RotationDelta); + } + break; } } - internal void DidTap(UITapGestureRecognizer gesture) + internal void DidLongPress (UILongPressGestureRecognizer gesture) { - var gesturePos = gesture.LocationInView(sceneView); - switch (State) - { - case ScanState.Ready: - State = ScanState.DefineBoundingBox; - // Recurse (note that state has changed, so DefineBoundingBox clause will execute) - DidTap(gesture); + var gesturePos = gesture.LocationInView (sceneView); + switch (State) { + case ScanState.Ready: + State = ScanState.DefineBoundingBox; + // Recurse (note that state has changed, so DefineBoundingBox clause will execute) + DidLongPress (gesture); + break; + case ScanState.DefineBoundingBox: + case ScanState.Scanning: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: break; - case ScanState.DefineBoundingBox: - case ScanState.Scanning: - if (gesture.State == UIGestureRecognizerState.Ended) - { - scannedObject.CreateOrMoveBoundingBox(gesturePos); - } + case UIGestureRecognizerState.Began: + scannedObject.BoundingBox?.StartSideDrag (gesturePos); break; - case ScanState.AdjustingOrigin: - if (gesture.State == UIGestureRecognizerState.Ended) - { - scannedObject.Origin?.FlashOrReposition(gesturePos); - } + case UIGestureRecognizerState.Changed: + scannedObject.BoundingBox?.UpdateSideDrag (gesturePos); break; default: + scannedObject.BoundingBox?.EndSideDrag (); break; + } + break; + case ScanState.AdjustingOrigin: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: break; + case UIGestureRecognizerState.Began: + scannedObject.Origin?.StartAxisDrag (gesturePos); + break; + case UIGestureRecognizerState.Changed: + scannedObject.Origin?.UpdateAxisDrag (gesturePos); + break; + default: + scannedObject.Origin?.EndAxisDrag (); + break; + } + break; } } - internal void DidPinch(ThresholdPinchGestureRecognizer gesture) + internal void DidTap (UITapGestureRecognizer gesture) { - switch (State) - { - case ScanState.Ready: - State = ScanState.DefineBoundingBox; - // Recurse (note that state has changed, so DefineBoundingBox clause will execute) - DidPinch(gesture); + var gesturePos = gesture.LocationInView (sceneView); + switch (State) { + case ScanState.Ready: + State = ScanState.DefineBoundingBox; + // Recurse (note that state has changed, so DefineBoundingBox clause will execute) + DidTap (gesture); + break; + case ScanState.DefineBoundingBox: + case ScanState.Scanning: + if (gesture.State == UIGestureRecognizerState.Ended) { + scannedObject.CreateOrMoveBoundingBox (gesturePos); + } + break; + case ScanState.AdjustingOrigin: + if (gesture.State == UIGestureRecognizerState.Ended) { + scannedObject.Origin?.FlashOrReposition (gesturePos); + } + break; + default: + break; + } + } + + internal void DidPinch (ThresholdPinchGestureRecognizer gesture) + { + switch (State) { + case ScanState.Ready: + State = ScanState.DefineBoundingBox; + // Recurse (note that state has changed, so DefineBoundingBox clause will execute) + DidPinch (gesture); + break; + case ScanState.DefineBoundingBox: + case ScanState.Scanning: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: + case UIGestureRecognizerState.Began: break; - case ScanState.DefineBoundingBox: - case ScanState.Scanning: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: - case UIGestureRecognizerState.Began: - break; - case UIGestureRecognizerState.Changed: - if (gesture.ThresholdExceeded) - { - scannedObject.ScaleBoundingBox((float) gesture.Scale); - gesture.Scale = 1; - } - break; - default: - break; + case UIGestureRecognizerState.Changed: + if (gesture.ThresholdExceeded) { + scannedObject.ScaleBoundingBox ((float) gesture.Scale); + gesture.Scale = 1; } break; - case ScanState.AdjustingOrigin: - switch (gesture.State) - { - case UIGestureRecognizerState.Possible: - case UIGestureRecognizerState.Began: - break; - case UIGestureRecognizerState.Changed: - if (gesture.ThresholdExceeded) - { - scannedObject.Origin?.UpdateScale((float) gesture.Scale); - gesture.Scale = 1; - } - break; - default: - break; + default: + break; + } + break; + case ScanState.AdjustingOrigin: + switch (gesture.State) { + case UIGestureRecognizerState.Possible: + case UIGestureRecognizerState.Began: + break; + case UIGestureRecognizerState.Changed: + if (gesture.ThresholdExceeded) { + scannedObject.Origin?.UpdateScale ((float) gesture.Scale); + gesture.Scale = 1; } break; + default: + break; + } + break; } } - internal void UpdateOnEveryFrame(ARFrame frame) + internal void UpdateOnEveryFrame (ARFrame frame) { // Note: unlike gesture recognizer handlers above, this function is not structured with a switch, since multiple clauses execute - if (State == ScanState.Ready || State == ScanState.DefineBoundingBox) - { - if (frame.RawFeaturePoints != null) - { + if (State == ScanState.Ready || State == ScanState.DefineBoundingBox) { + if (frame.RawFeaturePoints != null) { //Automatically adjust the size of the bounding box - scannedObject.FitOverPointCloud(frame.RawFeaturePoints); + scannedObject.FitOverPointCloud (frame.RawFeaturePoints); } } - if (State == ScanState.Ready || State == ScanState.DefineBoundingBox || State == ScanState.Scanning) - { - if (frame.LightEstimate != null) - { + if (State == ScanState.Ready || State == ScanState.DefineBoundingBox || State == ScanState.Scanning) { + if (frame.LightEstimate != null) { var lightEstimate = frame.LightEstimate; - if (lightEstimate.AmbientIntensity < 500 && !hasWarnedAboutLowLight) - { + if (lightEstimate.AmbientIntensity < 500 && !hasWarnedAboutLowLight) { hasWarnedAboutLowLight = true; var title = "Too dark for scanning"; var message = "Consider moving to an environment with more light."; - ViewController.Instance.ShowAlert(title, message); + ViewController.Instance.ShowAlert (title, message); } } // Try a preliminary creation of the reference object based off the current // bounding box & update the point cloud visualization based on that. - if (scannedObject.EitherBoundingBox != null) - { + if (scannedObject.EitherBoundingBox != null) { var boundingBox = scannedObject.EitherBoundingBox; // Note: Creating the reference object is asynchronous and likely // takes some time to complete. Avoid calling it again while we // still wait for the previous call to complete - if (!isBusyCreatingReferenceObject) - { + if (!isBusyCreatingReferenceObject) { isBusyCreatingReferenceObject = true; - scannedObject.LockBoundingBoxForReferenceObjectCreation(isBusyCreatingReferenceObject); - sceneView.Session.CreateReferenceObject(boundingBox.WorldTransform.ToNMatrix4(), new OpenTK.NVector3(), boundingBox.Extent, (referenceObject, error) => - { + scannedObject.LockBoundingBoxForReferenceObjectCreation (isBusyCreatingReferenceObject); + sceneView.Session.CreateReferenceObject (boundingBox.WorldTransform.ToNMatrix4 (), new OpenTK.NVector3 (), boundingBox.Extent, (referenceObject, error) => { // Ignoring error because most of the time, it's a "Too few features" message (i.e., not an exception, just an error). - if (referenceObject != null) - { - pointCloud.Update(referenceObject.RawFeaturePoints, boundingBox); + if (referenceObject != null) { + pointCloud.Update (referenceObject.RawFeaturePoints, boundingBox); } isBusyCreatingReferenceObject = false; - scannedObject.LockBoundingBoxForReferenceObjectCreation(isBusyCreatingReferenceObject); + scannedObject.LockBoundingBoxForReferenceObjectCreation (isBusyCreatingReferenceObject); }); } } } // Update bounding box side coloring to visualize scanning coverage - if (State == ScanState.Scanning) - { - scannedObject.BoundingBox?.HighlightCurrentTitle(); - scannedObject.BoundingBox?.UpdateCapturingProcess(); + if (State == ScanState.Scanning) { + scannedObject.BoundingBox?.HighlightCurrentTitle (); + scannedObject.BoundingBox?.UpdateCapturingProcess (); } - scannedObject.UpdateOnEveryFrame(); - pointCloud.UpdateOnEveryFrame(); + scannedObject.UpdateOnEveryFrame (); + pointCloud.UpdateOnEveryFrame (); } bool QualityIsLow => pointCloud.Count < Scan.minFeatureCount; @@ -510,10 +456,9 @@ internal void UpdateOnEveryFrame(ARFrame frame) internal bool GhostBoundingBoxExists => scannedObject.GhostBoundingBox != null; - bool IsReasonablySized() + bool IsReasonablySized () { - if (scannedObject.BoundingBox == null) - { + if (scannedObject.BoundingBox == null) { return false; } @@ -521,10 +466,9 @@ bool IsReasonablySized() // The bounding box should not be too small and not too large. // Note: 3D object detection is optimized for tabletop scenarios. Func<double, bool> validSizeRange = (sz) => sz > 0.01 && sz < 5.0; - if (validSizeRange(boundingBox.Extent.X) - && validSizeRange(boundingBox.Extent.Y) - && validSizeRange(boundingBox.Extent.Z)) - { + if (validSizeRange (boundingBox.Extent.X) + && validSizeRange (boundingBox.Extent.Y) + && validSizeRange (boundingBox.Extent.Z)) { // Check that the volume of the bounding box is at least 500 cubic centimeters. var volume = boundingBox.Extent.X * boundingBox.Extent.Y * boundingBox.Extent.Z; return volume >= 0.0005; @@ -533,60 +477,51 @@ bool IsReasonablySized() return false; } - internal void CreateReferenceObject(Action<ARReferenceObject> creationFinished) + internal void CreateReferenceObject (Action<ARReferenceObject> creationFinished) { - if (scannedObject.BoundingBox == null || scannedObject.Origin == null) - { - Console.WriteLine("Error: No bounding box or object origin present."); - creationFinished(null); + if (scannedObject.BoundingBox == null || scannedObject.Origin == null) { + Console.WriteLine ("Error: No bounding box or object origin present."); + creationFinished (null); return; } var boundingBox = scannedObject.BoundingBox; var origin = scannedObject.Origin; // Extract the reference object based on the position & orientation of the bounding box. - sceneView.Session.CreateReferenceObject(boundingBox.WorldTransform.ToNMatrix4(), new OpenTK.NVector3(), boundingBox.Extent, (referenceObject, err) => - { - if (referenceObject != null) - { + sceneView.Session.CreateReferenceObject (boundingBox.WorldTransform.ToNMatrix4 (), new OpenTK.NVector3 (), boundingBox.Extent, (referenceObject, err) => { + if (referenceObject != null) { // Adjust the object's origin with the user-provided transform - scannedReferenceObject = referenceObject.ApplyTransform(origin.Transform.ToNMatrix4()); + scannedReferenceObject = referenceObject.ApplyTransform (origin.Transform.ToNMatrix4 ()); scannedReferenceObject.Name = scannedObject.ScanName; - creationFinished(scannedReferenceObject); - } - else - { - Console.WriteLine($"Error: Failed to create reference object. ({err.LocalizedDescription})"); - creationFinished(null); + creationFinished (scannedReferenceObject); + } else { + Console.WriteLine ($"Error: Failed to create reference object. ({err.LocalizedDescription})"); + creationFinished (null); } }); } - void CreateScreenshot() + void CreateScreenshot () { - if (sceneView.Session.CurrentFrame == null) - { - Console.WriteLine("Error: Failed to create a screenshot - no current ARFrame exists."); + if (sceneView.Session.CurrentFrame == null) { + Console.WriteLine ("Error: Failed to create a screenshot - no current ARFrame exists."); return; } var frame = sceneView.Session.CurrentFrame; var orientation = UIImageOrientation.Right; - switch (UIDevice.CurrentDevice.Orientation) - { - case UIDeviceOrientation.Portrait: orientation = UIImageOrientation.Right; break; - case UIDeviceOrientation.PortraitUpsideDown: orientation = UIImageOrientation.Left; break; - case UIDeviceOrientation.LandscapeLeft: orientation = UIImageOrientation.Up; break; - case UIDeviceOrientation.LandscapeRight: orientation = UIImageOrientation.Down; break; - default: break; + switch (UIDevice.CurrentDevice.Orientation) { + case UIDeviceOrientation.Portrait: orientation = UIImageOrientation.Right; break; + case UIDeviceOrientation.PortraitUpsideDown: orientation = UIImageOrientation.Left; break; + case UIDeviceOrientation.LandscapeLeft: orientation = UIImageOrientation.Up; break; + case UIDeviceOrientation.LandscapeRight: orientation = UIImageOrientation.Down; break; + default: break; } - var ciImage = new CIImage(frame.CapturedImage); - using (var ctxt = new CIContext(new CIContextOptions())) - { - using (var cgImage = ctxt.CreateCGImage(ciImage, ciImage.Extent)) - { - screenshot = UIImage.FromImage(cgImage, 1.0f, orientation); + var ciImage = new CIImage (frame.CapturedImage); + using (var ctxt = new CIContext (new CIContextOptions ())) { + using (var cgImage = ctxt.CreateCGImage (ciImage, ciImage.Extent)) { + screenshot = UIImage.FromImage (cgImage, 1.0f, orientation); } } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ShareScanViewController.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ShareScanViewController.cs index ab3f19a46..90d01ff5b 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ShareScanViewController.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ShareScanViewController.cs @@ -1,20 +1,18 @@ -using Foundation; +using Foundation; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // Customized share sheet for exporting scanned AR reference objects. - internal class ShareScanViewController : UIActivityViewController - { - internal ShareScanViewController(UIView sourceView, NSObject any) - : base(new[] { any }, null) + internal class ShareScanViewController : UIActivityViewController { + internal ShareScanViewController (UIView sourceView, NSObject any) + : base (new [] { any }, null) { // Set up popover presentation style ModalPresentationStyle = UIModalPresentationStyle.Popover; PopoverPresentationController.SourceView = sourceView; PopoverPresentationController.SourceRect = sourceView.Bounds; - ExcludedActivityTypes = new[] + ExcludedActivityTypes = new [] { UIActivityType.MarkupAsPdf, UIActivityType.OpenInIBooks, @@ -33,4 +31,4 @@ internal ShareScanViewController(UIView sourceView, NSObject any) }; } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/TestRun.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/TestRun.cs index 569bb4666..da1aaa552 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/TestRun.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/TestRun.cs @@ -1,13 +1,11 @@ -using System; +using System; using ARKit; using Foundation; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // Manages the process of testing detection after scanning an object - internal class TestRun : NSObject, IDisposable - { + internal class TestRun : NSObject, IDisposable { private ViewControllerSessionInfo sessionInfo; private ARSCNView sceneView; private int detections = 0; @@ -19,36 +17,34 @@ internal class TestRun : NSObject, IDisposable internal DetectedObject DetectedObject { get; private set; } internal ARReferenceObject ReferenceObject { get; private set; } - internal UIImage PreviewImage { get; private set; } + internal UIImage PreviewImage { get; private set; } - internal TestRun(ViewControllerSessionInfo sessionInfo, ARSCNView sceneView) + internal TestRun (ViewControllerSessionInfo sessionInfo, ARSCNView sceneView) { this.sessionInfo = sessionInfo; this.sceneView = sceneView; - StartNoDetectionTimer(); + StartNoDetectionTimer (); } - internal TimeSpan ResultDisplayDuration { - get - { + internal TimeSpan ResultDisplayDuration { + get { // The recommended display duration for detection results // is the average time it takes to detect it, plus 200ms buffer - return new TimeSpan((long)(TimeSpan.TicksPerSecond * (averageDetectionDelayInSeconds + 0.2))); - } - } + return new TimeSpan ((long) (TimeSpan.TicksPerSecond * (averageDetectionDelayInSeconds + 0.2))); + } + } internal string Statistics { - get - { + get { var lastDelay = $"{lastDetectionDelayInSeconds * 1000:F0}"; var avgDelay = $"{averageDetectionDelayInSeconds * 1000:F0}"; return $"Detected after {lastDelay} ms. Avg: {avgDelay}"; } } - internal void SetReferenceObject(ARReferenceObject obj, UIImage screenshot) + internal void SetReferenceObject (ARReferenceObject obj, UIImage screenshot) { ReferenceObject = obj; PreviewImage = screenshot; @@ -56,18 +52,18 @@ internal void SetReferenceObject(ARReferenceObject obj, UIImage screenshot) lastDetectionDelayInSeconds = 0; averageDetectionDelayInSeconds = 0; - DetectedObject = new DetectedObject(ReferenceObject); - sceneView.Scene.RootNode.AddChildNode(DetectedObject); + DetectedObject = new DetectedObject (ReferenceObject); + sceneView.Scene.RootNode.AddChildNode (DetectedObject); lastDetectionStartTime = DateTime.Now; - var config = new ARWorldTrackingConfiguration(); - config.DetectionObjects = new NSSet<ARReferenceObject>( new[] { ReferenceObject }); + var config = new ARWorldTrackingConfiguration (); + config.DetectionObjects = new NSSet<ARReferenceObject> (new [] { ReferenceObject }); // ARSessionRunOptions.None should be coming in a future binding. In the meantime, the following cast - sceneView.Session.Run(config, (ARSessionRunOptions) 0); + sceneView.Session.Run (config, (ARSessionRunOptions) 0); } - internal void SuccessfulDetection(ARObjectAnchor objectAnchor) + internal void SuccessfulDetection (ARObjectAnchor objectAnchor) { // Compute the time it took to detect this object & the average lastDetectionDelayInSeconds = (DateTime.Now - lastDetectionStartTime).TotalSeconds; @@ -79,66 +75,60 @@ internal void SuccessfulDetection(ARObjectAnchor objectAnchor) // Immediately remove the anchor from the session again to force a re-detection. lastDetectionStartTime = DateTime.Now; - sceneView.Session.RemoveAnchor(objectAnchor); + sceneView.Session.RemoveAnchor (objectAnchor); - if (sceneView.Session.CurrentFrame?.RawFeaturePoints != null) - { + if (sceneView.Session.CurrentFrame?.RawFeaturePoints != null) { var currentPointCloud = sceneView.Session.CurrentFrame?.RawFeaturePoints; - DetectedObject?.UpdateVisualization(objectAnchor.Transform, currentPointCloud); + DetectedObject?.UpdateVisualization (objectAnchor.Transform, currentPointCloud); } - StartNoDetectionTimer(); + StartNoDetectionTimer (); } - internal void UpdateOnEveryFrame() + internal void UpdateOnEveryFrame () { - if (DetectedObject != null) - { - if (sceneView.Session.CurrentFrame?.RawFeaturePoints != null) - { - DetectedObject.UpdatePointCloud(sceneView.Session.CurrentFrame?.RawFeaturePoints); + if (DetectedObject != null) { + if (sceneView.Session.CurrentFrame?.RawFeaturePoints != null) { + DetectedObject.UpdatePointCloud (sceneView.Session.CurrentFrame?.RawFeaturePoints); } } } - void StartNoDetectionTimer() + void StartNoDetectionTimer () { - CancelNoDetectionTimer(); - noDetectionTimer = NSTimer.CreateScheduledTimer(5.0, (timer) => - { - CancelNoDetectionTimer(); - sessionInfo.DisplayMessage("Unable to detect the object. Please point the device at the scanned object or rescan.", 5.0); + CancelNoDetectionTimer (); + noDetectionTimer = NSTimer.CreateScheduledTimer (5.0, (timer) => { + CancelNoDetectionTimer (); + sessionInfo.DisplayMessage ("Unable to detect the object. Please point the device at the scanned object or rescan.", 5.0); }); } - void CancelNoDetectionTimer() + void CancelNoDetectionTimer () { - noDetectionTimer?.Invalidate(); - noDetectionTimer?.Dispose(); + noDetectionTimer?.Invalidate (); + noDetectionTimer?.Dispose (); noDetectionTimer = null; } - internal new void Dispose() + internal new void Dispose () { - Dispose(true); - GC.SuppressFinalize(this); + Dispose (true); + GC.SuppressFinalize (this); } - protected override void Dispose(bool disposing) + protected override void Dispose (bool disposing) { - if (disposing) - { - DetectedObject?.RemoveFromParentNode(); + if (disposing) { + DetectedObject?.RemoveFromParentNode (); - if (sceneView.Session.Configuration as ARWorldTrackingConfiguration != null) - { + if (sceneView.Session.Configuration as ARWorldTrackingConfiguration != null) { // Make sure we switch back to an object scanning configuration & no longer // try to detect the object. - var configuration = new ARObjectScanningConfiguration(); + var configuration = new ARObjectScanningConfiguration (); configuration.PlaneDetection = ARPlaneDetection.Horizontal; - sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking); + sceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking); } } } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewController.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewController.cs index 87f6d4a0f..5951103fd 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewController.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; using ARKit; @@ -8,10 +8,8 @@ using CoreFoundation; using OpenTK; -namespace ScanningAndDetecting3DObjects -{ - internal partial class ViewController : UIViewController, IUIGestureRecognizerDelegate - { +namespace ScanningAndDetecting3DObjects { + internal partial class ViewController : UIViewController, IUIGestureRecognizerDelegate { private ViewControllerApplicationState state; internal ViewControllerApplicationState State { get => state; } @@ -23,7 +21,7 @@ internal partial class ViewController : UIViewController, IUIGestureRecognizerDe private TestRun testRun; - internal void ShowSessionInfo(string message, bool visible) + internal void ShowSessionInfo (string message, bool visible) { sessionInfoLabel.Text = message; sessionInfoView.Hidden = !visible; @@ -31,12 +29,12 @@ internal void ShowSessionInfo(string message, bool visible) internal TestRun ActiveTestRun { get => testRun; } - internal ARSCNView SceneView { get => sceneView; } + internal ARSCNView SceneView { get => sceneView; } NSTimer limitedTrackingTimer; NSTimer maxScanTimeTimer; - internal CGPoint ScreenCenter { get; private set; } + internal CGPoint ScreenCenter { get; private set; } // ViewController helper instances ViewControllerNavigationBar navigationBarController; @@ -45,19 +43,16 @@ internal void ShowSessionInfo(string message, bool visible) private NSUrl modelUrl; - internal NSUrl ModelUrl - { + internal NSUrl ModelUrl { get => modelUrl; - set - { - if (value != null) - { + set { + if (value != null) { modelUrl = value; - sessionInfo.DisplayMessage($"3D Model \"{modelUrl.LastPathComponent}\" received.", 3.0); + sessionInfo.DisplayMessage ($"3D Model \"{modelUrl.LastPathComponent}\" received.", 3.0); } - scan?.ScannedObject?.Set3DModel(modelUrl); - testRun?.DetectedObject?.Set3DModel(modelUrl); + scan?.ScannedObject?.Set3DModel (modelUrl); + testRun?.DetectedObject?.Set3DModel (modelUrl); } } @@ -65,111 +60,110 @@ internal NSUrl ModelUrl // This is a common cause of "frame freeze" in AR apps. (Symptom: app seems to run, but image // is frozen. This is because the iOS system sees there is still a reference to the current frame // and declines to provide a new frame because it figures "current frame is still being used"! (see README.MD) - internal ARFrame SessionFrame() + internal ARFrame SessionFrame () { return sceneView?.Session?.CurrentFrame; } - protected ViewController(IntPtr handle) : base(handle) + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - internal void EnterStateStartARSession() + internal void EnterStateStartARSession () { - scan?.Dispose(); + scan?.Dispose (); scan = null; - testRun?.Dispose(); + testRun?.Dispose (); testRun = null; - modelUrl?.Dispose(); + modelUrl?.Dispose (); modelUrl = null; - navigationBarController.SetNavigationBarTitle(""); - navigationBarController.ShowBackButton(false); + navigationBarController.SetNavigationBarTitle (""); + navigationBarController.ShowBackButton (false); instructionView.Hidden = true; nextButton.Enabled = false; loadModelButton.Hidden = true; flashlightButton.Hidden = true; // Make sure the SCNScene is cleared of any SCNNodes from previous scans. - sceneView.Scene = new SceneKit.SCNScene(); + sceneView.Scene = new SceneKit.SCNScene (); - var configuration = new ARObjectScanningConfiguration(); + var configuration = new ARObjectScanningConfiguration (); configuration.PlaneDetection = ARPlaneDetection.Horizontal; - sceneView.Session.Run(configuration, ARSessionRunOptions.ResetTracking); - CancelMaxScanTimeTimer(); - sessionInfo.CancelMessageExpirationTimer(); + sceneView.Session.Run (configuration, ARSessionRunOptions.ResetTracking); + CancelMaxScanTimeTimer (); + sessionInfo.CancelMessageExpirationTimer (); } - internal void EnterStateTesting() + internal void EnterStateTesting () { - navigationBarController.SetNavigationBarTitle("Testing"); - navigationBarController.ShowBackButton(false); + navigationBarController.SetNavigationBarTitle ("Testing"); + navigationBarController.ShowBackButton (false); loadModelButton.Hidden = true; flashlightButton.Hidden = false; nextButton.Enabled = true; - nextButton.SetTitle("Share", UIControlState.Normal); + nextButton.SetTitle ("Share", UIControlState.Normal); - testRun = new TestRun(sessionInfo, sceneView); - TestObjectDetection(); - CancelMaxScanTimeTimer(); + testRun = new TestRun (sessionInfo, sceneView); + TestObjectDetection (); + CancelMaxScanTimeTimer (); } - internal void EnterStateScanning() + internal void EnterStateScanning () { - if (scan == null) - { - scan = new Scan(sceneView); + if (scan == null) { + scan = new Scan (sceneView); scan.State = Scan.ScanState.Ready; } - testRun?.Dispose(); + testRun?.Dispose (); testRun = null; - StartMaxScanTimeTimer(); + StartMaxScanTimeTimer (); } - internal void EnterStateNotReady() + internal void EnterStateNotReady () { - scan?.Dispose(); + scan?.Dispose (); scan = null; - testRun?.Dispose(); + testRun?.Dispose (); testRun = null; - navigationBarController.SetNavigationBarTitle(""); - navigationBarController.ShowBackButton(false); + navigationBarController.SetNavigationBarTitle (""); + navigationBarController.ShowBackButton (false); loadModelButton.Hidden = true; flashlightButton.Hidden = true; nextButton.Enabled = false; - nextButton.SetTitle("Next", UIControlState.Normal); - DisplayInstruction(new Message("Please wait for stable tracking")); - CancelMaxScanTimeTimer(); + nextButton.SetTitle ("Next", UIControlState.Normal); + DisplayInstruction (new Message ("Please wait for stable tracking")); + CancelMaxScanTimeTimer (); } - public override void ViewWillAppear(bool animated) + public override void ViewWillAppear (bool animated) { - base.ViewWillAppear(animated); + base.ViewWillAppear (animated); Instance = this; } - public override void ViewWillDisappear(bool animated) + public override void ViewWillDisappear (bool animated) { - base.ViewWillDisappear(animated); - sceneView.Session.Pause(); + base.ViewWillDisappear (animated); + sceneView.Session.Pause (); } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Member initialization order is important! Primirily because there is logic assoc'd w changing the state. (see EnterState* functions) - navigationBarController = new ViewControllerNavigationBar(this.navigationBar, PreviousButtonTapped, RestartButtonTapped); - sessionInfo = new ViewControllerSessionInfo(this); + navigationBarController = new ViewControllerNavigationBar (this.navigationBar, PreviousButtonTapped, RestartButtonTapped); + sessionInfo = new ViewControllerSessionInfo (this); - state = new ViewControllerApplicationState(this); + state = new ViewControllerApplicationState (this); - sceneView.Delegate = new ViewControllerSCNViewDelegate(this, sessionInfo); - sceneView.Session.Delegate = new ViewControllerSessionDelegate(this, State, sessionInfo); + sceneView.Delegate = new ViewControllerSCNViewDelegate (this, sessionInfo); + sceneView.Session.Delegate = new ViewControllerSessionDelegate (this, State, sessionInfo); // Prevent the screen from being dimmed after a while UIApplication.SharedApplication.IdleTimerDisabled = true; @@ -178,237 +172,208 @@ public override void ViewDidLoad() // Configure notifications for application state changes var notificationCenter = NSNotificationCenter.DefaultCenter; - notificationCenter.AddObserver(Scan.ScanningStateChangedNotificationName, State.ScanningStateChanged); - notificationCenter.AddObserver(ScannedObject.GhostBoundingBoxCreatedNotificationName, State.GhostBoundingBoxWasCreated); - notificationCenter.AddObserver(ScannedObject.GhostBoundingBoxRemovedNotificationName, State.GhostBoundingBoxWasRemoved); - notificationCenter.AddObserver(ScannedObject.BoundingBoxCreatedNotificationName, State.BoundingBoxWasCreated); - notificationCenter.AddObserver(BoundingBox.ScanPercentageChangedNotificationName, ScanPercentageChanged); - notificationCenter.AddObserver(BoundingBox.ExtentChangedNotificationName, BoundingBoxExtentChanged); - notificationCenter.AddObserver(BoundingBox.PositionChangedNotificationName, BoundingBoxPositionChanged); - notificationCenter.AddObserver(ObjectOrigin.PositionChangedNotificationName, ObjectOriginPositionChanged); - notificationCenter.AddObserver(NSProcessInfo.PowerStateDidChangeNotification, DisplayWarningIfInLowPowerMode); + notificationCenter.AddObserver (Scan.ScanningStateChangedNotificationName, State.ScanningStateChanged); + notificationCenter.AddObserver (ScannedObject.GhostBoundingBoxCreatedNotificationName, State.GhostBoundingBoxWasCreated); + notificationCenter.AddObserver (ScannedObject.GhostBoundingBoxRemovedNotificationName, State.GhostBoundingBoxWasRemoved); + notificationCenter.AddObserver (ScannedObject.BoundingBoxCreatedNotificationName, State.BoundingBoxWasCreated); + notificationCenter.AddObserver (BoundingBox.ScanPercentageChangedNotificationName, ScanPercentageChanged); + notificationCenter.AddObserver (BoundingBox.ExtentChangedNotificationName, BoundingBoxExtentChanged); + notificationCenter.AddObserver (BoundingBox.PositionChangedNotificationName, BoundingBoxPositionChanged); + notificationCenter.AddObserver (ObjectOrigin.PositionChangedNotificationName, ObjectOriginPositionChanged); + notificationCenter.AddObserver (NSProcessInfo.PowerStateDidChangeNotification, DisplayWarningIfInLowPowerMode); - DisplayWarningIfInLowPowerMode(null); + DisplayWarningIfInLowPowerMode (null); // Make sure the application launches in AppStat.StartARSession state // Entering this state launches the ARSession State.CurrentState = AppState.StartARSession; } - internal void EnableNextButton(bool b) + internal void EnableNextButton (bool b) { nextButton.Enabled = b; } - internal void EnterStateAdjustingOrigin() + internal void EnterStateAdjustingOrigin () { - DisplayInstruction(new Message("Adjust origin using gestures.\nYou can load a *.usdz 3D model overlay")); - navigationBarController.SetNavigationBarTitle("Adjust origin"); - navigationBarController.ShowBackButton(true); + DisplayInstruction (new Message ("Adjust origin using gestures.\nYou can load a *.usdz 3D model overlay")); + navigationBarController.SetNavigationBarTitle ("Adjust origin"); + navigationBarController.ShowBackButton (true); nextButton.Enabled = true; loadModelButton.Hidden = false; flashlightButton.Hidden = true; - nextButton.SetTitle("Test", UIControlState.Normal); + nextButton.SetTitle ("Test", UIControlState.Normal); } - internal void EnterStateScanningContinue() + internal void EnterStateScanningContinue () { - DisplayInstruction(new Message("Scan the object from all sides in which you are interested. Do not move the object while scanning!")); + DisplayInstruction (new Message ("Scan the object from all sides in which you are interested. Do not move the object while scanning!")); var boundingBox = scan.ScannedObject.BoundingBox; - if (boundingBox != null) - { - navigationBarController.SetNavigationBarTitle($"Scan ({boundingBox.ProgressPercentage}%)"); - } - else - { - navigationBarController.SetNavigationBarTitle("Scan 0%"); + if (boundingBox != null) { + navigationBarController.SetNavigationBarTitle ($"Scan ({boundingBox.ProgressPercentage}%)"); + } else { + navigationBarController.SetNavigationBarTitle ("Scan 0%"); } - navigationBarController.ShowBackButton(true); + navigationBarController.ShowBackButton (true); nextButton.Enabled = true; loadModelButton.Hidden = true; flashlightButton.Hidden = true; - nextButton.SetTitle("Finish", UIControlState.Normal); + nextButton.SetTitle ("Finish", UIControlState.Normal); } - internal void EnterStateDefineBoundingBox() + internal void EnterStateDefineBoundingBox () { - DisplayInstruction(new Message("Position and resize bounding box using gestures.\nLong press sides to push/pull them in or out.")); - navigationBarController.SetNavigationBarTitle("Define bounding box"); - navigationBarController.ShowBackButton(true); + DisplayInstruction (new Message ("Position and resize bounding box using gestures.\nLong press sides to push/pull them in or out.")); + navigationBarController.SetNavigationBarTitle ("Define bounding box"); + navigationBarController.ShowBackButton (true); nextButton.Enabled = scan.BoundingBoxExists; loadModelButton.Hidden = true; flashlightButton.Hidden = true; - nextButton.SetTitle("Scan", UIControlState.Normal); + nextButton.SetTitle ("Scan", UIControlState.Normal); } - internal void EnterStateScanReady() + internal void EnterStateScanReady () { - navigationBarController.SetNavigationBarTitle("Ready to scan"); - navigationBarController.ShowBackButton(false); - nextButton.SetTitle("Next", UIControlState.Normal); + navigationBarController.SetNavigationBarTitle ("Ready to scan"); + navigationBarController.ShowBackButton (false); + nextButton.SetTitle ("Next", UIControlState.Normal); loadModelButton.Hidden = true; flashlightButton.Hidden = true; - if (scan.GhostBoundingBoxExists) - { - DisplayInstruction(new Message("Tap 'Next' to create an approximate bounding box around the object you want to scan.")); + if (scan.GhostBoundingBoxExists) { + DisplayInstruction (new Message ("Tap 'Next' to create an approximate bounding box around the object you want to scan.")); nextButton.Enabled = true; - } - else - { - DisplayInstruction(new Message("Point at a nearby object to scan.")); + } else { + DisplayInstruction (new Message ("Point at a nearby object to scan.")); nextButton.Enabled = false; } } - public override void ViewDidLayoutSubviews() + public override void ViewDidLayoutSubviews () { - base.ViewDidLayoutSubviews(); + base.ViewDidLayoutSubviews (); // Store the screen center location after the view's bounds did change, // so it can be retrieved from outside the main thread ScreenCenter = sceneView.Center; } - internal void RestartButtonTapped(Object sender, EventArgs args) + internal void RestartButtonTapped (Object sender, EventArgs args) { - Action startOverAlert = () => - { + Action startOverAlert = () => { var title = "Start over?"; var message = "Discard the current scan and start over?"; - ShowAlert(title, message, "Yes", true, (o) => State.CurrentState = AppState.StartARSession); + ShowAlert (title, message, "Yes", true, (o) => State.CurrentState = AppState.StartARSession); }; - if (scan != null && scan.BoundingBoxExists) - { - startOverAlert(); - } - else - { - if (testRun != null) - { - startOverAlert(); - } - else - { + if (scan != null && scan.BoundingBoxExists) { + startOverAlert (); + } else { + if (testRun != null) { + startOverAlert (); + } else { State.CurrentState = AppState.StartARSession; } } } - internal void PreviousButtonTapped(Object sender, EventArgs args) + internal void PreviousButtonTapped (Object sender, EventArgs args) { - State.SwitchToPreviousState(); + State.SwitchToPreviousState (); } - partial void NextButtonTapped(RoundedButton sender) + partial void NextButtonTapped (RoundedButton sender) { - if (nextButton.Hidden || !nextButton.Enabled) - { + if (nextButton.Hidden || !nextButton.Enabled) { return; } - State.SwitchToNextState(); + State.SwitchToNextState (); } - partial void LoadModelButtonTouched(NSObject sender) + partial void LoadModelButtonTouched (NSObject sender) { - if (loadModelButton.Hidden || !loadModelButton.Enabled) - { + if (loadModelButton.Hidden || !loadModelButton.Enabled) { return; } - var documentPicker = new UIDocumentPickerViewController(new[] { "com.pixar.universal-scene-description-mobile" }, UIDocumentPickerMode.Import); - documentPicker.Delegate = new ViewControllerDocumentPickerDelegate((url) => modelUrl = url); + var documentPicker = new UIDocumentPickerViewController (new [] { "com.pixar.universal-scene-description-mobile" }, UIDocumentPickerMode.Import); + documentPicker.Delegate = new ViewControllerDocumentPickerDelegate ((url) => modelUrl = url); documentPicker.ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext; - if (documentPicker.PopoverPresentationController != null) - { + if (documentPicker.PopoverPresentationController != null) { documentPicker.PopoverPresentationController.SourceView = loadModelButton; documentPicker.PopoverPresentationController.SourceRect = loadModelButton.Bounds; } - DispatchQueue.MainQueue.DispatchAsync(() => - { - PresentViewController(documentPicker, true, () => { }); - }); + DispatchQueue.MainQueue.DispatchAsync (() => { + PresentViewController (documentPicker, true, () => { }); + }); } - partial void LeftButtonTouchAreaTapped(NSObject sender) + partial void LeftButtonTouchAreaTapped (NSObject sender) { // A tap in the extended hit area on the lower left should cause a tap // on the button that is currently visible at that location. - if (!loadModelButton.Hidden) - { - LoadModelButtonTouched(this); - } - else - { - if (!flashlightButton.Hidden) - { - ToggleFlashlightButtonTapped(flashlightButton); + if (!loadModelButton.Hidden) { + LoadModelButtonTouched (this); + } else { + if (!flashlightButton.Hidden) { + ToggleFlashlightButtonTapped (flashlightButton); } } } - partial void ToggleFlashlightButtonTapped(FlashlightButton sender) + partial void ToggleFlashlightButtonTapped (FlashlightButton sender) { - if (flashlightButton.Hidden || !flashlightButton.Enabled) - { + if (flashlightButton.Hidden || !flashlightButton.Enabled) { return; } flashlightButton.ToggledOn = !flashlightButton.ToggledOn; } - partial void toggleInstructionsButtonTapped(RoundedButton sender) + partial void toggleInstructionsButtonTapped (RoundedButton sender) { - if (toggleInstructionsButton.Hidden || !toggleInstructionsButton.Enabled) - { + if (toggleInstructionsButton.Hidden || !toggleInstructionsButton.Enabled) { return; } - if (toggleInstructionsButton.ToggledOn) - { - HideInstructions(); - } - else - { - ShowInstructions(); + if (toggleInstructionsButton.ToggledOn) { + HideInstructions (); + } else { + ShowInstructions (); } } - internal void DisplayInstruction(Message msg) + internal void DisplayInstruction (Message msg) { - instructionLabel.Display(msg); - ShowInstructions(); + instructionLabel.Display (msg); + ShowInstructions (); } - void HideInstructions() + void HideInstructions () { instructionView.Hidden = true; toggleInstructionsButton.ToggledOn = false; } - void ShowInstructions() + void ShowInstructions () { instructionView.Hidden = false; toggleInstructionsButton.ToggledOn = true; } - void TestObjectDetection() + void TestObjectDetection () { - if (scan == null || scan.BoundingBoxExists == false) - { - Console.WriteLine("Error: Bounding Box not yet created"); + if (scan == null || scan.BoundingBoxExists == false) { + Console.WriteLine ("Error: Bounding Box not yet created"); return; } - scan.CreateReferenceObject((scannedObject) => - { + scan.CreateReferenceObject ((scannedObject) => { var localRef = scannedObject; - if (localRef != null) - { - testRun?.SetReferenceObject(localRef, scan.Screenshot); + if (localRef != null) { + testRun?.SetReferenceObject (localRef, scan.Screenshot); // Delete the scan to make sure that users cannot go back from // testing to scanning, because: @@ -416,335 +381,294 @@ void TestObjectDetection() // thus the scanned environment is lost when starting a test. // 2. We encourage users to move the scanned object during testing, which invalidates // the feature point cloud which was captured during scanning. - scan?.Dispose(); + scan?.Dispose (); scan = null; - DisplayInstruction(new Message("Test detection of the object from different angles. Consider moving the object to different environments and test there.")); - } - else - { + DisplayInstruction (new Message ("Test detection of the object from different angles. Consider moving the object to different environments and test there.")); + } else { var title = "Scan failed"; var message = "Saving the scan failed."; var buttonTitle = "Restart Scan"; - ShowAlert(title, message, buttonTitle, false, (_) => { State.CurrentState = AppState.StartARSession; }); + ShowAlert (title, message, buttonTitle, false, (_) => { State.CurrentState = AppState.StartARSession; }); } }); } - internal void CreateAndShareReferenceObject() + internal void CreateAndShareReferenceObject () { - if (testRun == null || testRun.ReferenceObject == null || testRun.ReferenceObject.Name == null) - { - Console.WriteLine("Error: Missing scanned object."); + if (testRun == null || testRun.ReferenceObject == null || testRun.ReferenceObject.Name == null) { + Console.WriteLine ("Error: Missing scanned object."); return; } var referenceObject = testRun.ReferenceObject; var name = referenceObject.Name; - var documentUrl = NSFileManager.DefaultManager.GetTemporaryDirectory().Append($"{name}.arobject", false); + var documentUrl = NSFileManager.DefaultManager.GetTemporaryDirectory ().Append ($"{name}.arobject", false); - DispatchQueue.MainQueue.DispatchAsync(() => - { - try - { + DispatchQueue.MainQueue.DispatchAsync (() => { + try { NSError err = null; - referenceObject.Export(documentUrl, testRun.PreviewImage, out err); - if (err != null) - { - Console.WriteLine($"Error writing reference object : ({err})"); + referenceObject.Export (documentUrl, testRun.PreviewImage, out err); + if (err != null) { + Console.WriteLine ($"Error writing reference object : ({err})"); } - } - catch (Exception x) - { - AppDelegate.FatalError($"Failed to save the file to '{documentUrl}'"); + } catch (Exception x) { + AppDelegate.FatalError ($"Failed to save the file to '{documentUrl}'"); } // Initiate a share sheet for the scanned object - var airdropShareSheet = new ShareScanViewController(nextButton, documentUrl); - DispatchQueue.MainQueue.DispatchAsync(() => - { - PresentViewController(airdropShareSheet, true, () => { }); + var airdropShareSheet = new ShareScanViewController (nextButton, documentUrl); + DispatchQueue.MainQueue.DispatchAsync (() => { + PresentViewController (airdropShareSheet, true, () => { }); }); }); } - internal void StartLimitedTrackingTimer() + internal void StartLimitedTrackingTimer () { - if (limitedTrackingTimer != null) - { + if (limitedTrackingTimer != null) { // Cannot have more than one going return; } - limitedTrackingTimer = NSTimer.CreateScheduledTimer(2.0, (_) => - { - CancelLimitedTrackingTimer(); - if (scan == null) - { + limitedTrackingTimer = NSTimer.CreateScheduledTimer (2.0, (_) => { + CancelLimitedTrackingTimer (); + if (scan == null) { return; } if (scan.State == Scan.ScanState.DefineBoundingBox || scan.State == Scan.ScanState.Scanning || scan.State == Scan.ScanState.AdjustingOrigin - ) - { + ) { var title = "Limited Tracking"; var message = "Low tracking quality - it is unlikely that a good reference object can be generated from this scan."; var buttonTitle = "Restart Scan"; - ShowAlert(title, message, buttonTitle, true, (x) => State.CurrentState = AppState.StartARSession); + ShowAlert (title, message, buttonTitle, true, (x) => State.CurrentState = AppState.StartARSession); } }); } - internal void CancelLimitedTrackingTimer() + internal void CancelLimitedTrackingTimer () { - limitedTrackingTimer?.Invalidate(); - limitedTrackingTimer?.Dispose(); + limitedTrackingTimer?.Invalidate (); + limitedTrackingTimer?.Dispose (); limitedTrackingTimer = null; } - void StartMaxScanTimeTimer() + void StartMaxScanTimeTimer () { - if (maxScanTimeTimer != null) - { + if (maxScanTimeTimer != null) { // Cannot have more than one return; } var timeout = 60.0 * 5; - maxScanTimeTimer = NSTimer.CreateScheduledTimer(timeout, (_) => - { - CancelMaxScanTimeTimer(); - if (state.CurrentState != AppState.Scanning) - { + maxScanTimeTimer = NSTimer.CreateScheduledTimer (timeout, (_) => { + CancelMaxScanTimeTimer (); + if (state.CurrentState != AppState.Scanning) { return; } var title = "Scan is taking too long"; - var message = $"Scanning consumes a lot of resources. This scan has been running for {(int)timeout}s. " + + var message = $"Scanning consumes a lot of resources. This scan has been running for {(int) timeout}s. " + "Consider closing the app and letting the device rest for a few minutes."; var buttonTitle = "OK"; - ShowAlert(title, message, buttonTitle, true, (x) => { }); + ShowAlert (title, message, buttonTitle, true, (x) => { }); }); } - private void CancelMaxScanTimeTimer() + private void CancelMaxScanTimeTimer () { - maxScanTimeTimer?.Invalidate(); - maxScanTimeTimer?.Dispose(); + maxScanTimeTimer?.Invalidate (); + maxScanTimeTimer?.Dispose (); maxScanTimeTimer = null; } - private T TryGet<T>(NSDictionary dict, NSObject key) where T : NSObject + private T TryGet<T> (NSDictionary dict, NSObject key) where T : NSObject { - if (dict.ContainsKey(key)) - { - return dict[key] as T; + if (dict.ContainsKey (key)) { + return dict [key] as T; } return null; } - private void DisplayWarningIfInLowPowerMode(NSNotification notification) + private void DisplayWarningIfInLowPowerMode (NSNotification notification) { - if (NSProcessInfo.ProcessInfo.LowPowerModeEnabled) - { + if (NSProcessInfo.ProcessInfo.LowPowerModeEnabled) { var title = "Low Power Mode is enabled"; var message = "Performance may be impacted. For best results, disable " + "Low Power Mode in Settings > Battery, and restart the scan."; - ShowAlert(title, message); + ShowAlert (title, message); } } - private void ObjectOriginPositionChanged(NSNotification notification) + private void ObjectOriginPositionChanged (NSNotification notification) { var origin = notification.Object as ObjectOrigin; - if (origin == null) - { + if (origin == null) { return; } var pos = origin.Position; var message = $"Current local origin position in meters: [{pos.X:F2}, {pos.Y:F2}, {pos.Z:F2}]"; - sessionInfo.DisplayMessage(message, 1.5); + sessionInfo.DisplayMessage (message, 1.5); } - private void BoundingBoxPositionChanged(NSNotification notification) + private void BoundingBoxPositionChanged (NSNotification notification) { var boundingBox = notification.Object as BoundingBox; var cameraPos = sceneView.PointOfView?.WorldPosition; - if (boundingBox == null || !cameraPos.HasValue) - { + if (boundingBox == null || !cameraPos.HasValue) { return; } - var distanceFromCamera = $"{boundingBox.WorldPosition.Distance(cameraPos.Value):2F}"; - sessionInfo.DisplayMessage($"Current bounding box distance: ({distanceFromCamera}) m", 1.5); + var distanceFromCamera = $"{boundingBox.WorldPosition.Distance (cameraPos.Value):2F}"; + sessionInfo.DisplayMessage ($"Current bounding box distance: ({distanceFromCamera}) m", 1.5); } - private void BoundingBoxExtentChanged(NSNotification notification) + private void BoundingBoxExtentChanged (NSNotification notification) { - var boxedExtent = TryGet<SimpleBox<NVector3>>(notification.UserInfo, BoundingBox.BoxExtentUserInfoKey); - if (boxedExtent == null) - { + var boxedExtent = TryGet<SimpleBox<NVector3>> (notification.UserInfo, BoundingBox.BoxExtentUserInfoKey); + if (boxedExtent == null) { return; } var extent = boxedExtent.Value; var message = $"Current bounding box in meters:\n (x : {extent.X:F2}) (y : {extent.Y:F2}) ( z : {extent.Z:F2})"; - sessionInfo.DisplayMessage(message, 1.5); + sessionInfo.DisplayMessage (message, 1.5); } - private void ScanPercentageChanged(NSNotification notification) + private void ScanPercentageChanged (NSNotification notification) { - var pctNum = TryGet<NSNumber>(notification.UserInfo, BoundingBox.ScanPercentageUserKey); - if (pctNum == null) - { + var pctNum = TryGet<NSNumber> (notification.UserInfo, BoundingBox.ScanPercentageUserKey); + if (pctNum == null) { return; } double percentage = pctNum.DoubleValue; // Switch to the next state if scan is complete - if (percentage >= 100.0) - { - State.SwitchToNextState(); - } - else - { - DispatchQueue.MainQueue.DispatchAsync(() => navigationBarController.SetNavigationBarTitle($"Scan ({percentage})")); + if (percentage >= 100.0) { + State.SwitchToNextState (); + } else { + DispatchQueue.MainQueue.DispatchAsync (() => navigationBarController.SetNavigationBarTitle ($"Scan ({percentage})")); } } - internal void BackFromBackground() + internal void BackFromBackground () { - if (state.CurrentState == AppState.Scanning) - { + if (state.CurrentState == AppState.Scanning) { var title = "Warning: Scan may be broken"; var message = "The scan was interrupted. It is recommended to restart the scan."; var buttonTitle = "Restart scan"; - ShowAlert(title, message, buttonTitle, true, (_) => State.CurrentState = AppState.NotReady); + ShowAlert (title, message, buttonTitle, true, (_) => State.CurrentState = AppState.NotReady); } } - internal void ShowBlurView(bool visible) + internal void ShowBlurView (bool visible) { this.blurView.Hidden = visible; } - internal void ShowAlert(string title, string message, string buttonTitle = "OK", bool showCancel = false, Action<UIAlertAction> handler = null) + internal void ShowAlert (string title, string message, string buttonTitle = "OK", bool showCancel = false, Action<UIAlertAction> handler = null) { - Console.WriteLine($"{title}\n{message}"); - InvokeOnMainThread(() => - { - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - alertController.AddAction(UIAlertAction.Create(buttonTitle, UIAlertActionStyle.Default, handler)); - if (showCancel) - { - alertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (_) => { })); + Console.WriteLine ($"{title}\n{message}"); + InvokeOnMainThread (() => { + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create (buttonTitle, UIAlertActionStyle.Default, handler)); + if (showCancel) { + alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (_) => { })); } - DispatchQueue.MainQueue.DispatchAsync(() => - { - PresentViewController(alertController, true, () => { }); + DispatchQueue.MainQueue.DispatchAsync (() => { + PresentViewController (alertController, true, () => { }); }); }); } - internal ARCamera CurrentFrameCamera() + internal ARCamera CurrentFrameCamera () { return sceneView?.Session?.CurrentFrame?.Camera; } - partial void didTap(UITapGestureRecognizer sender) + partial void didTap (UITapGestureRecognizer sender) { - if (State.CurrentState == AppState.Scanning) - { - scan?.DidTap(sender); + if (State.CurrentState == AppState.Scanning) { + scan?.DidTap (sender); } - HideInstructions(); + HideInstructions (); } - partial void didOneFingerPan(UIPanGestureRecognizer sender) + partial void didOneFingerPan (UIPanGestureRecognizer sender) { - if (State.CurrentState == AppState.Scanning) - { - scan?.DidOneFingerPan(sender); + if (State.CurrentState == AppState.Scanning) { + scan?.DidOneFingerPan (sender); } - HideInstructions(); + HideInstructions (); } - partial void didTwoFingerPan(ThresholdPanGestureRecognizer sender) + partial void didTwoFingerPan (ThresholdPanGestureRecognizer sender) { - if (State.CurrentState == AppState.Scanning) - { - scan?.DidTwoFingerPan(sender); + if (State.CurrentState == AppState.Scanning) { + scan?.DidTwoFingerPan (sender); } - HideInstructions(); + HideInstructions (); } - partial void didRotate(ThresholdRotationGestureRecognizer sender) + partial void didRotate (ThresholdRotationGestureRecognizer sender) { - if (State.CurrentState == AppState.Scanning) - { - scan?.DidRotate(sender); + if (State.CurrentState == AppState.Scanning) { + scan?.DidRotate (sender); } - HideInstructions(); + HideInstructions (); } - partial void didLongPress(UILongPressGestureRecognizer sender) + partial void didLongPress (UILongPressGestureRecognizer sender) { - if (State.CurrentState == AppState.Scanning) - { - scan?.DidLongPress(sender); + if (State.CurrentState == AppState.Scanning) { + scan?.DidLongPress (sender); } - HideInstructions(); + HideInstructions (); } - partial void didPinch(ThresholdPinchGestureRecognizer sender) + partial void didPinch (ThresholdPinchGestureRecognizer sender) { - if (State.CurrentState == AppState.Scanning) - { - scan?.DidPinch(sender); + if (State.CurrentState == AppState.Scanning) { + scan?.DidPinch (sender); } - HideInstructions(); + HideInstructions (); } // IUIGestureRecognizerDelegate - [Export("gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:")] - internal bool ShouldRecognizeSimultaneously(UIGestureRecognizer first, UIGestureRecognizer second) + [Export ("gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:")] + internal bool ShouldRecognizeSimultaneously (UIGestureRecognizer first, UIGestureRecognizer second) { - if (first is UIRotationGestureRecognizer && second is UIPinchGestureRecognizer) - { + if (first is UIRotationGestureRecognizer && second is UIPinchGestureRecognizer) { return true; } - if (first is UIRotationGestureRecognizer && second is UIPanGestureRecognizer) - { + if (first is UIRotationGestureRecognizer && second is UIPanGestureRecognizer) { return true; } - if (first is UIPinchGestureRecognizer && second is UIRotationGestureRecognizer) - { + if (first is UIPinchGestureRecognizer && second is UIRotationGestureRecognizer) { return true; } - if (first is UIPinchGestureRecognizer && second is UIPanGestureRecognizer) - { + if (first is UIPinchGestureRecognizer && second is UIPanGestureRecognizer) { return true; } - if (first is UIPanGestureRecognizer && second is UIPinchGestureRecognizer) - { + if (first is UIPanGestureRecognizer && second is UIPinchGestureRecognizer) { return true; } - if (first is UIPanGestureRecognizer && second is UIRotationGestureRecognizer) - { + if (first is UIPanGestureRecognizer && second is UIRotationGestureRecognizer) { return true; } return false; diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerApplicationState.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerApplicationState.cs index b79d67ace..a716c4425 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerApplicationState.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerApplicationState.cs @@ -1,290 +1,253 @@ -using Foundation; +using Foundation; using System; using ARKit; using CoreFoundation; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { - enum AppState - { - StartARSession, + enum AppState { + StartARSession, NotReady, Scanning, Testing } - internal class ViewControllerApplicationState : NSObject - { - internal static readonly NSString ApplicationStateChangedNotificationName = new NSString("ApplicationStateChanged"); - internal static readonly NSString AppStateUserInfoKey = new NSString("AppState"); + internal class ViewControllerApplicationState : NSObject { + internal static readonly NSString ApplicationStateChangedNotificationName = new NSString ("ApplicationStateChanged"); + internal static readonly NSString AppStateUserInfoKey = new NSString ("AppState"); // Type of UserInfo[AppStateUserInfoKey] : ViewControllerApplicationState; - private NSNotification StateChangedNotification(AppState state) + private NSNotification StateChangedNotification (AppState state) { - NSDictionary userInfo = NSDictionary.FromObjectAndKey(new SimpleBox<AppState>(state), AppStateUserInfoKey); - return NSNotification.FromName(ApplicationStateChangedNotificationName, this, userInfo); + NSDictionary userInfo = NSDictionary.FromObjectAndKey (new SimpleBox<AppState> (state), AppStateUserInfoKey); + return NSNotification.FromName (ApplicationStateChangedNotificationName, this, userInfo); } private ViewController source; private AppState internalState; - internal AppState CurrentState { + internal AppState CurrentState { get => internalState; - set - { + set { // 1. Check that the preconditions for the state change are met. var newState = value; - switch(value) - { - case AppState.StartARSession : break; - case AppState.NotReady : - // Immediately switch to Ready if tracking state is normal - var camera = source.CurrentFrameCamera(); - if (camera != null) - { - switch (camera.TrackingState) - { - case ARTrackingState.Normal : - newState = AppState.Scanning; - break; - default : - break; - } + switch (value) { + case AppState.StartARSession: break; + case AppState.NotReady: + // Immediately switch to Ready if tracking state is normal + var camera = source.CurrentFrameCamera (); + if (camera != null) { + switch (camera.TrackingState) { + case ARTrackingState.Normal: + newState = AppState.Scanning; + break; + default: + break; } - else - { - newState = AppState.StartARSession; - } - break; - case AppState.Scanning : - // Immediately switch to NotReady if tracking state is not normal - var cameraS = source.CurrentFrameCamera(); - if (cameraS != null) - { - switch (cameraS.TrackingState) - { - case ARTrackingState.Normal : break; - default : - newState = AppState.NotReady; - break; - } - } - else - { - newState = AppState.StartARSession; - } - break; - case AppState.Testing : - var scan = source.CurrentScan; - if (scan == null || ! scan.BoundingBoxExists) - { - Console.WriteLine("Error: Scan is not ready to be tested"); - //Note: return, not break - return; + } else { + newState = AppState.StartARSession; + } + break; + case AppState.Scanning: + // Immediately switch to NotReady if tracking state is not normal + var cameraS = source.CurrentFrameCamera (); + if (cameraS != null) { + switch (cameraS.TrackingState) { + case ARTrackingState.Normal: break; + default: + newState = AppState.NotReady; + break; } - break; + } else { + newState = AppState.StartARSession; + } + break; + case AppState.Testing: + var scan = source.CurrentScan; + if (scan == null || !scan.BoundingBoxExists) { + Console.WriteLine ("Error: Scan is not ready to be tested"); + //Note: return, not break + return; + } + break; } // 2. Apply changes as needed per state internalState = newState; - switch(newState) - { - case AppState.StartARSession : - Console.WriteLine("State : Starting ARSession"); - source.EnterStateStartARSession(); - break; - case AppState.NotReady : - Console.WriteLine("State : Not ready to scan"); - source.EnterStateNotReady(); - break; - case AppState.Scanning : - Console.WriteLine("State : Scanning"); - source.EnterStateScanning(); - break; - case AppState.Testing : - Console.WriteLine("State : Testing"); - source.EnterStateTesting(); - break; + switch (newState) { + case AppState.StartARSession: + Console.WriteLine ("State : Starting ARSession"); + source.EnterStateStartARSession (); + break; + case AppState.NotReady: + Console.WriteLine ("State : Not ready to scan"); + source.EnterStateNotReady (); + break; + case AppState.Scanning: + Console.WriteLine ("State : Scanning"); + source.EnterStateScanning (); + break; + case AppState.Testing: + Console.WriteLine ("State : Testing"); + source.EnterStateTesting (); + break; } - NSNotificationCenter.DefaultCenter.PostNotification(StateChangedNotification(newState)); + NSNotificationCenter.DefaultCenter.PostNotification (StateChangedNotification (newState)); } } - internal ViewControllerApplicationState(ViewController source) + internal ViewControllerApplicationState (ViewController source) { this.source = source; this.CurrentState = AppState.StartARSession; } - internal void SwitchToNextState() + internal void SwitchToNextState () { - switch (CurrentState) - { - case AppState.StartARSession : - CurrentState = AppState.NotReady; - break; - case AppState.NotReady : - CurrentState = AppState.Scanning; - break; - case AppState.Scanning : - var scan = source.CurrentScan; - if (scan != null) - { - switch (scan.State) - { - case Scan.ScanState.Ready : - scan.State = Scan.ScanState.DefineBoundingBox; - break; - case Scan.ScanState.DefineBoundingBox : - scan.State = Scan.ScanState.Scanning; - break; - case Scan.ScanState.Scanning : - scan.State = Scan.ScanState.AdjustingOrigin; - break; - case Scan.ScanState.AdjustingOrigin : - CurrentState = AppState.Testing; - break; - } + switch (CurrentState) { + case AppState.StartARSession: + CurrentState = AppState.NotReady; + break; + case AppState.NotReady: + CurrentState = AppState.Scanning; + break; + case AppState.Scanning: + var scan = source.CurrentScan; + if (scan != null) { + switch (scan.State) { + case Scan.ScanState.Ready: + scan.State = Scan.ScanState.DefineBoundingBox; + break; + case Scan.ScanState.DefineBoundingBox: + scan.State = Scan.ScanState.Scanning; + break; + case Scan.ScanState.Scanning: + scan.State = Scan.ScanState.AdjustingOrigin; + break; + case Scan.ScanState.AdjustingOrigin: + CurrentState = AppState.Testing; + break; } - break; - case AppState.Testing : - // Testing is the last state, show the share sheet at the end. - source.CreateAndShareReferenceObject(); - break; + } + break; + case AppState.Testing: + // Testing is the last state, show the share sheet at the end. + source.CreateAndShareReferenceObject (); + break; } } - internal void SwitchToPreviousState() + internal void SwitchToPreviousState () { - switch (CurrentState) - { - case AppState.StartARSession : break; - case AppState.NotReady : - CurrentState = AppState.StartARSession; - break; - case AppState.Scanning : - var scan = source.CurrentScan; - if (scan != null) - { - switch (scan.State) - { - case Scan.ScanState.Ready : - source.RestartButtonTapped(this, new EventArgs()); - break; - case Scan.ScanState.DefineBoundingBox : - scan.State = Scan.ScanState.Ready; - break; - case Scan.ScanState.Scanning : - scan.State = Scan.ScanState.DefineBoundingBox; - break; - case Scan.ScanState.AdjustingOrigin : - scan.State = Scan.ScanState.Scanning; - break; - } - } - break; - case AppState.Testing : - CurrentState = AppState.Scanning; - var scanT = source.CurrentScan; - if (scanT != null) - { - scanT.State = Scan.ScanState.AdjustingOrigin; + switch (CurrentState) { + case AppState.StartARSession: break; + case AppState.NotReady: + CurrentState = AppState.StartARSession; + break; + case AppState.Scanning: + var scan = source.CurrentScan; + if (scan != null) { + switch (scan.State) { + case Scan.ScanState.Ready: + source.RestartButtonTapped (this, new EventArgs ()); + break; + case Scan.ScanState.DefineBoundingBox: + scan.State = Scan.ScanState.Ready; + break; + case Scan.ScanState.Scanning: + scan.State = Scan.ScanState.DefineBoundingBox; + break; + case Scan.ScanState.AdjustingOrigin: + scan.State = Scan.ScanState.Scanning; + break; } - break; + } + break; + case AppState.Testing: + CurrentState = AppState.Scanning; + var scanT = source.CurrentScan; + if (scanT != null) { + scanT.State = Scan.ScanState.AdjustingOrigin; + } + break; } } - internal void BoundingBoxWasCreated(NSNotification notification) + internal void BoundingBoxWasCreated (NSNotification notification) { - if (source.CurrentScan == null) - { + if (source.CurrentScan == null) { return; } - if (source.CurrentScan.State == Scan.ScanState.DefineBoundingBox) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - source.EnableNextButton(true); + if (source.CurrentScan.State == Scan.ScanState.DefineBoundingBox) { + DispatchQueue.MainQueue.DispatchAsync (() => { + source.EnableNextButton (true); }); } } - internal void GhostBoundingBoxWasRemoved(NSNotification notification) + internal void GhostBoundingBoxWasRemoved (NSNotification notification) { - if (source.CurrentScan == null) - { + if (source.CurrentScan == null) { return; } - if (source.CurrentScan.State == Scan.ScanState.Ready) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - source.EnableNextButton(false); - source.DisplayInstruction(new Message("Point at a nearby object to scan.")); + if (source.CurrentScan.State == Scan.ScanState.Ready) { + DispatchQueue.MainQueue.DispatchAsync (() => { + source.EnableNextButton (false); + source.DisplayInstruction (new Message ("Point at a nearby object to scan.")); }); } } - internal void GhostBoundingBoxWasCreated(NSNotification notification) + internal void GhostBoundingBoxWasCreated (NSNotification notification) { - if (source.CurrentScan == null) - { + if (source.CurrentScan == null) { return; } - if (source.CurrentScan.State == Scan.ScanState.Ready) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - source.EnableNextButton(true); - source.DisplayInstruction(new Message("Tap 'Next' to create an approximate bounding box around the object you want to scan")); + if (source.CurrentScan.State == Scan.ScanState.Ready) { + DispatchQueue.MainQueue.DispatchAsync (() => { + source.EnableNextButton (true); + source.DisplayInstruction (new Message ("Tap 'Next' to create an approximate bounding box around the object you want to scan")); }); } } - internal void ScanningStateChanged(NSNotification notification) + internal void ScanningStateChanged (NSNotification notification) { // Guard condition is complex, so break it down into multiple steps - if (CurrentState != AppState.Scanning) - { + if (CurrentState != AppState.Scanning) { return; } var notificationObject = notification.Object as Scan; - if (notificationObject == null) - { + if (notificationObject == null) { return; } - if (notificationObject != source.CurrentScan) - { + if (notificationObject != source.CurrentScan) { return; } - var scanState = notification.UserInfo[Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; - if (scanState == null) - { + var scanState = notification.UserInfo [Scan.StateUserInfoKey] as SimpleBox<Scan.ScanState>; + if (scanState == null) { return; } - DispatchQueue.MainQueue.DispatchAsync(() => - { - switch(scanState.Value) - { - case Scan.ScanState.Ready : - Console.WriteLine("State: Ready to scan"); - source.EnterStateScanReady(); - break; - case Scan.ScanState.DefineBoundingBox : - Console.WriteLine("State : Define bounding box"); - source.EnterStateDefineBoundingBox(); - break; - case Scan.ScanState.Scanning : - source.EnterStateScanningContinue(); - break; - case Scan.ScanState.AdjustingOrigin : - Console.WriteLine("State : Adjusting origin"); - source.EnterStateAdjustingOrigin(); - break; + DispatchQueue.MainQueue.DispatchAsync (() => { + switch (scanState.Value) { + case Scan.ScanState.Ready: + Console.WriteLine ("State: Ready to scan"); + source.EnterStateScanReady (); + break; + case Scan.ScanState.DefineBoundingBox: + Console.WriteLine ("State : Define bounding box"); + source.EnterStateDefineBoundingBox (); + break; + case Scan.ScanState.Scanning: + source.EnterStateScanningContinue (); + break; + case Scan.ScanState.AdjustingOrigin: + Console.WriteLine ("State : Adjusting origin"); + source.EnterStateAdjustingOrigin (); + break; } }); } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerDocumentPickerDelegate.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerDocumentPickerDelegate.cs index 869921d9a..4ef0206fe 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerDocumentPickerDelegate.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerDocumentPickerDelegate.cs @@ -1,21 +1,19 @@ -using System; +using System; using Foundation; using UIKit; -namespace ScanningAndDetecting3DObjects -{ - internal class ViewControllerDocumentPickerDelegate : UIDocumentPickerDelegate - { +namespace ScanningAndDetecting3DObjects { + internal class ViewControllerDocumentPickerDelegate : UIDocumentPickerDelegate { Action<NSUrl> handler; - internal ViewControllerDocumentPickerDelegate(Action<NSUrl> handler) - { + internal ViewControllerDocumentPickerDelegate (Action<NSUrl> handler) + { this.handler = handler; } - public override void DidPickDocument(UIDocumentPickerViewController controller, NSUrl url) - { - handler(url); - } + public override void DidPickDocument (UIDocumentPickerViewController controller, NSUrl url) + { + handler (url); + } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerNavigationBar.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerNavigationBar.cs index 1317772f1..fec03f2a4 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerNavigationBar.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerNavigationBar.cs @@ -1,56 +1,49 @@ -using System; +using System; using Foundation; using UIKit; -namespace ScanningAndDetecting3DObjects -{ - internal class ViewControllerNavigationBar - { +namespace ScanningAndDetecting3DObjects { + internal class ViewControllerNavigationBar { UINavigationBar navigationBar; UIBarButtonItem backButton; UIBarButtonItem startOverButton; - internal ViewControllerNavigationBar(UINavigationBar navigationBar, EventHandler previousButtonTapped, EventHandler restartButtonTapped) + internal ViewControllerNavigationBar (UINavigationBar navigationBar, EventHandler previousButtonTapped, EventHandler restartButtonTapped) { this.navigationBar = navigationBar; - backButton = new UIBarButtonItem("Back", UIBarButtonItemStyle.Plain, previousButtonTapped); - startOverButton = new UIBarButtonItem("Restart", UIBarButtonItemStyle.Plain, restartButtonTapped); + backButton = new UIBarButtonItem ("Back", UIBarButtonItemStyle.Plain, previousButtonTapped); + startOverButton = new UIBarButtonItem ("Restart", UIBarButtonItemStyle.Plain, restartButtonTapped); - var navigationItem = new UINavigationItem("Start"); + var navigationItem = new UINavigationItem ("Start"); navigationItem.LeftBarButtonItem = backButton; navigationItem.RightBarButtonItem = startOverButton; - navigationBar.Items = new[] { navigationItem }; + navigationBar.Items = new [] { navigationItem }; - navigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default); - navigationBar.ShadowImage = new UIImage(); + navigationBar.SetBackgroundImage (new UIImage (), UIBarMetrics.Default); + navigationBar.ShadowImage = new UIImage (); navigationBar.Translucent = true; } - internal void SetNavigationBarTitle(string title) + internal void SetNavigationBarTitle (string title) { - var navItem = navigationBar.Items[0]; - if (navItem == null) - { + var navItem = navigationBar.Items [0]; + if (navItem == null) { return; } navItem.Title = title; } - internal void ShowBackButton(bool show) + internal void ShowBackButton (bool show) { - var navItem = navigationBar.Items[0]; - if (navItem == null) - { + var navItem = navigationBar.Items [0]; + if (navItem == null) { return; } - if (show) - { + if (show) { navItem.LeftBarButtonItem = backButton; - } - else - { - navItem.LeftBarButtonItem?.Dispose(); + } else { + navItem.LeftBarButtonItem?.Dispose (); navItem.LeftBarButtonItem = null; } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSCNViewDelegate.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSCNViewDelegate.cs index 348d66830..912f286c2 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSCNViewDelegate.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSCNViewDelegate.cs @@ -1,63 +1,53 @@ -using ARKit; +using ARKit; using SceneKit; -namespace ScanningAndDetecting3DObjects -{ - internal class ViewControllerSCNViewDelegate : ARSCNViewDelegate - { +namespace ScanningAndDetecting3DObjects { + internal class ViewControllerSCNViewDelegate : ARSCNViewDelegate { ViewController source; ViewControllerSessionInfo sessionInfo; - internal ViewControllerSCNViewDelegate(ViewController source, ViewControllerSessionInfo sessionInfo) + internal ViewControllerSCNViewDelegate (ViewController source, ViewControllerSessionInfo sessionInfo) { this.source = source; this.sessionInfo = sessionInfo; } - public override void Update(ISCNSceneRenderer renderer, double timeInSeconds) + public override void Update (ISCNSceneRenderer renderer, double timeInSeconds) { // Note: Always a super-tricky thing in ARKit : must get rid of the managed reference to the Frame object ASAP. - using (var frame = source.SessionFrame()) - { - if (frame == null) - { + using (var frame = source.SessionFrame ()) { + if (frame == null) { return; } - source.CurrentScan?.UpdateOnEveryFrame(frame); - source.ActiveTestRun?.UpdateOnEveryFrame(); + source.CurrentScan?.UpdateOnEveryFrame (frame); + source.ActiveTestRun?.UpdateOnEveryFrame (); } } - public override void DidAddNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + public override void DidAddNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { - if (anchor != null && anchor is ARObjectAnchor) - { + if (anchor != null && anchor is ARObjectAnchor) { var objectAnchor = anchor as ARObjectAnchor; - if (source.ActiveTestRun != null && objectAnchor.ReferenceObject == source.ActiveTestRun.ReferenceObject) - { - source.ActiveTestRun.SuccessfulDetection(objectAnchor); + if (source.ActiveTestRun != null && objectAnchor.ReferenceObject == source.ActiveTestRun.ReferenceObject) { + source.ActiveTestRun.SuccessfulDetection (objectAnchor); var messageText = $"Object successfully detected from this angle.\n{source.ActiveTestRun.Statistics}"; - sessionInfo.DisplayMessage(messageText, source.ActiveTestRun.ResultDisplayDuration.TotalSeconds); + sessionInfo.DisplayMessage (messageText, source.ActiveTestRun.ResultDisplayDuration.TotalSeconds); } - } - else - { - if (source.State.CurrentState == AppState.Scanning && anchor is ARPlaneAnchor) - { + } else { + if (source.State.CurrentState == AppState.Scanning && anchor is ARPlaneAnchor) { var planeAnchor = anchor as ARPlaneAnchor; - source.CurrentScan?.ScannedObject.TryToAlignWithPlanes(new[] { planeAnchor }); + source.CurrentScan?.ScannedObject.TryToAlignWithPlanes (new [] { planeAnchor }); } } } - public override void DidUpdateNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + public override void DidUpdateNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) { - if (source.State.CurrentState == AppState.Scanning && anchor is ARPlaneAnchor) - { + if (source.State.CurrentState == AppState.Scanning && anchor is ARPlaneAnchor) { var planeAnchor = anchor as ARPlaneAnchor; - source.CurrentScan?.ScannedObject.TryToAlignWithPlanes(new[] { planeAnchor }); + source.CurrentScan?.ScannedObject.TryToAlignWithPlanes (new [] { planeAnchor }); } } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionDelegate.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionDelegate.cs index c67165f4b..573de8645 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionDelegate.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionDelegate.cs @@ -1,96 +1,85 @@ -using ARKit; +using ARKit; using System.ComponentModel.Design.Serialization; using System; -namespace ScanningAndDetecting3DObjects -{ - internal class ViewControllerSessionDelegate : ARSessionDelegate - { +namespace ScanningAndDetecting3DObjects { + internal class ViewControllerSessionDelegate : ARSessionDelegate { ViewController source; ViewControllerApplicationState appState; ViewControllerSessionInfo sessionInfo; - internal ViewControllerSessionDelegate(ViewController source, ViewControllerApplicationState appState, ViewControllerSessionInfo sessionInfo) + internal ViewControllerSessionDelegate (ViewController source, ViewControllerApplicationState appState, ViewControllerSessionInfo sessionInfo) { this.source = source; this.appState = appState; this.sessionInfo = sessionInfo; } - public override void CameraDidChangeTrackingState(ARSession session, ARCamera camera) + public override void CameraDidChangeTrackingState (ARSession session, ARCamera camera) { - sessionInfo.UpdateSessionInfoLabel(camera); + sessionInfo.UpdateSessionInfoLabel (camera); - switch (camera.TrackingState) - { - case ARTrackingState.NotAvailable : + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + appState.CurrentState = AppState.NotReady; + break; + case ARTrackingState.Limited: + switch (appState.CurrentState) { + case AppState.StartARSession: appState.CurrentState = AppState.NotReady; break; - case ARTrackingState.Limited : - switch (appState.CurrentState) - { - case AppState.StartARSession: + case AppState.NotReady: + case AppState.Testing: + break; + case AppState.Scanning: + var scan = source.CurrentScan; + if (scan != null) { + switch (scan.State) { + case Scan.ScanState.Ready: appState.CurrentState = AppState.NotReady; break; - case AppState.NotReady: - case AppState.Testing: - break; - case AppState.Scanning: - var scan = source.CurrentScan; - if (scan != null) - { - switch (scan.State) - { - case Scan.ScanState.Ready: - appState.CurrentState = AppState.NotReady; - break; - case Scan.ScanState.DefineBoundingBox: - case Scan.ScanState.Scanning: - case Scan.ScanState.AdjustingOrigin: - var reason = camera.TrackingStateReason; - if (reason == ARTrackingStateReason.Relocalizing) - { - // If ARKit is relocalizing we should abort the current scan - // as this can cause unpredictable distortions of the map. - Console.WriteLine("Warning: ARKit is relocalizing"); + case Scan.ScanState.DefineBoundingBox: + case Scan.ScanState.Scanning: + case Scan.ScanState.AdjustingOrigin: + var reason = camera.TrackingStateReason; + if (reason == ARTrackingStateReason.Relocalizing) { + // If ARKit is relocalizing we should abort the current scan + // as this can cause unpredictable distortions of the map. + Console.WriteLine ("Warning: ARKit is relocalizing"); - var title = "Warning: Scan may be broken"; - var message = "A gap in tracking has occurred. It is recommended to restart the scan."; - var buttonTitle = "Restart Scan"; - source.ShowAlert(title, message, buttonTitle, true, (_) => - { - appState.CurrentState = AppState.NotReady; - }); + var title = "Warning: Scan may be broken"; + var message = "A gap in tracking has occurred. It is recommended to restart the scan."; + var buttonTitle = "Restart Scan"; + source.ShowAlert (title, message, buttonTitle, true, (_) => { + appState.CurrentState = AppState.NotReady; + }); - } - else - { - // Suggest the user restart tracking after a while - source.StartLimitedTrackingTimer(); - } - break; - } + } else { + // Suggest the user restart tracking after a while + source.StartLimitedTrackingTimer (); } break; + } } break; - case ARTrackingState.Normal : - source.CancelLimitedTrackingTimer(); + } + break; + case ARTrackingState.Normal: + source.CancelLimitedTrackingTimer (); - switch (appState.CurrentState) - { - case AppState.StartARSession : - case AppState.NotReady : - appState.CurrentState = AppState.Scanning; - break; - case AppState.Scanning : - case AppState.Testing : - break; + switch (appState.CurrentState) { + case AppState.StartARSession: + case AppState.NotReady: + appState.CurrentState = AppState.Scanning; + break; + case AppState.Scanning: + case AppState.Testing: + break; - } - break; + } + break; } } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionInfo.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionInfo.cs index 558e9e390..f82666d87 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionInfo.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Controllers/ViewControllerSessionInfo.cs @@ -1,93 +1,85 @@ -using System; +using System; using ARKit; using Foundation; using CoreFoundation; -namespace ScanningAndDetecting3DObjects -{ - internal class ViewControllerSessionInfo - { +namespace ScanningAndDetecting3DObjects { + internal class ViewControllerSessionInfo { ViewController source; DateTime startTimeOfLastMessage; double expirationTimeOfLastMessage; NSTimer messageExpirationTimer; - internal ViewControllerSessionInfo(ViewController source) + internal ViewControllerSessionInfo (ViewController source) { this.source = source; } - internal void UpdateSessionInfoLabel(ARCamera camera) + internal void UpdateSessionInfoLabel (ARCamera camera) { // Update the UI to provide feedback on the state of the AR experience var message = ""; var stateString = source.State.CurrentState == AppState.Testing ? "Detecting" : "Scanning"; - switch (camera.TrackingState) - { - case ARTrackingState.NotAvailable : - message = $"{stateString} not possible : {camera.PresentationString()}"; - startTimeOfLastMessage = DateTime.Now; - expirationTimeOfLastMessage = 3.0; - break; - case ARTrackingState.Limited : - message = $"{stateString} might not work : {camera.PresentationString()}"; - startTimeOfLastMessage = DateTime.Now; - expirationTimeOfLastMessage = 3.0; - break; - default : - // No feedback needed when tracking is normal. - // Defer clearing the info label if the last message hasn't reached its expiration time. - var now = DateTime.Now; - if ((now - startTimeOfLastMessage).TotalSeconds < expirationTimeOfLastMessage) - { - var timeToKeepLastMessageOnScreen = expirationTimeOfLastMessage - (now - startTimeOfLastMessage).TotalSeconds; - StartMessageExpirationTimer(timeToKeepLastMessageOnScreen); - } - else - { - // Otherwise hide the info label immediately - source.ShowSessionInfo("", false); - } - //Note return not break - return; + switch (camera.TrackingState) { + case ARTrackingState.NotAvailable: + message = $"{stateString} not possible : {camera.PresentationString ()}"; + startTimeOfLastMessage = DateTime.Now; + expirationTimeOfLastMessage = 3.0; + break; + case ARTrackingState.Limited: + message = $"{stateString} might not work : {camera.PresentationString ()}"; + startTimeOfLastMessage = DateTime.Now; + expirationTimeOfLastMessage = 3.0; + break; + default: + // No feedback needed when tracking is normal. + // Defer clearing the info label if the last message hasn't reached its expiration time. + var now = DateTime.Now; + if ((now - startTimeOfLastMessage).TotalSeconds < expirationTimeOfLastMessage) { + var timeToKeepLastMessageOnScreen = expirationTimeOfLastMessage - (now - startTimeOfLastMessage).TotalSeconds; + StartMessageExpirationTimer (timeToKeepLastMessageOnScreen); + } else { + // Otherwise hide the info label immediately + source.ShowSessionInfo ("", false); + } + //Note return not break + return; } - source.ShowSessionInfo(message, true); + source.ShowSessionInfo (message, true); } - internal void DisplayMessage(string message, double expirationTime) + internal void DisplayMessage (string message, double expirationTime) { startTimeOfLastMessage = DateTime.Now; expirationTimeOfLastMessage = expirationTime; - DispatchQueue.MainQueue.DispatchAsync(() => - { - source.ShowSessionInfo(message, true); - StartMessageExpirationTimer(expirationTime); + DispatchQueue.MainQueue.DispatchAsync (() => { + source.ShowSessionInfo (message, true); + StartMessageExpirationTimer (expirationTime); }); } - private void StartMessageExpirationTimer(double duration) + private void StartMessageExpirationTimer (double duration) { - CancelMessageExpirationTimer(); + CancelMessageExpirationTimer (); - messageExpirationTimer = NSTimer.CreateScheduledTimer(duration, (timer) => - { - CancelMessageExpirationTimer(); - source.ShowSessionInfo("", false); + messageExpirationTimer = NSTimer.CreateScheduledTimer (duration, (timer) => { + CancelMessageExpirationTimer (); + source.ShowSessionInfo ("", false); - startTimeOfLastMessage = default(DateTime); - expirationTimeOfLastMessage = default(double); + startTimeOfLastMessage = default (DateTime); + expirationTimeOfLastMessage = default (double); }); } - internal void CancelMessageExpirationTimer() + internal void CancelMessageExpirationTimer () { - messageExpirationTimer?.Invalidate(); - messageExpirationTimer?.Dispose(); + messageExpirationTimer?.Invalidate (); + messageExpirationTimer?.Dispose (); messageExpirationTimer = null; } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPanGestureRecognizer.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPanGestureRecognizer.cs index 718c96e74..cd1aeb6a1 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPanGestureRecognizer.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPanGestureRecognizer.cs @@ -1,4 +1,4 @@ -// This file has been autogenerated from a class added in the UI designer. +// This file has been autogenerated from a class added in the UI designer. using System; using ARKit; @@ -6,11 +6,9 @@ using UIKit; using CoreGraphics; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // A custom pan gesture recognizer that fires only when a threshold is passed - internal partial class ThresholdPanGestureRecognizer : UIPanGestureRecognizer - { + internal partial class ThresholdPanGestureRecognizer : UIPanGestureRecognizer { // The threshold in screen pixels after which this gesture is detected private const double threshold = 30; @@ -28,74 +26,67 @@ internal ThresholdPanGestureRecognizer (IntPtr handle) : base (handle) { } - public override UIGestureRecognizerState State - { + public override UIGestureRecognizerState State { get => base.State; - set - { + set { base.State = value; - switch (value) - { - case UIGestureRecognizerState.Possible : - case UIGestureRecognizerState.Began : - case UIGestureRecognizerState.Changed : - break; - default : - // Reset variables - ThresholdExceeded = true; - initialLocation = CGPoint.Empty; - break; + switch (value) { + case UIGestureRecognizerState.Possible: + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + break; + default: + // Reset variables + ThresholdExceeded = true; + initialLocation = CGPoint.Empty; + break; } } } - public override void TouchesBegan(NSSet touches, UIEvent evt) + public override void TouchesBegan (NSSet touches, UIEvent evt) { - base.TouchesBegan(touches, evt); + base.TouchesBegan (touches, evt); - initialLocation = LocationInView(View); + initialLocation = LocationInView (View); var vc = ViewController.Instance; - if (vc != null) - { + if (vc != null) { var obj = vc.CurrentScan?.ObjectToManipulate; - if (obj != null) - { - var objectPos = vc.SceneView.ProjectPoint(obj.WorldPosition); + if (obj != null) { + var objectPos = vc.SceneView.ProjectPoint (obj.WorldPosition); offsetToObject.X = objectPos.X - initialLocation.X; offsetToObject.Y = objectPos.Y - initialLocation.Y; } } } - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); - var translationMagnitude = TranslationInView(View).Length(); + var translationMagnitude = TranslationInView (View).Length (); - if (! ThresholdExceeded && translationMagnitude > threshold) - { + if (!ThresholdExceeded && translationMagnitude > threshold) { thresholdExceeded = true; // Set the overall translation to zero as the gesture should now begin - SetTranslation(CGPoint.Empty, View); + SetTranslation (CGPoint.Empty, View); } } - public override CGPoint LocationInView(UIView view) + public override CGPoint LocationInView (UIView view) { - switch (State) - { - case UIGestureRecognizerState.Began : - case UIGestureRecognizerState.Changed : - var correctedLocation = new CGPoint(initialLocation.X + TranslationInView(view).X, initialLocation.Y + TranslationInView(view).Y); - return correctedLocation; - default : - return base.LocationInView(view); + switch (State) { + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + var correctedLocation = new CGPoint (initialLocation.X + TranslationInView (view).X, initialLocation.Y + TranslationInView (view).Y); + return correctedLocation; + default: + return base.LocationInView (view); } } - internal CGPoint OffsetLocationIn(UIView view) => LocationInView(view).Add(offsetToObject); + internal CGPoint OffsetLocationIn (UIView view) => LocationInView (view).Add (offsetToObject); } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPinchGestureRecognizer.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPinchGestureRecognizer.cs index a20471728..ebd665616 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPinchGestureRecognizer.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdPinchGestureRecognizer.cs @@ -1,4 +1,4 @@ -// This file has been autogenerated from a class added in the UI designer. +// This file has been autogenerated from a class added in the UI designer. using System; @@ -8,11 +8,9 @@ using System.Linq; using System.Collections.Generic; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // A custom pinch gesture recognizer that fires only when a threshold is reached - internal partial class ThresholdPinchGestureRecognizer : UIPinchGestureRecognizer - { + internal partial class ThresholdPinchGestureRecognizer : UIPinchGestureRecognizer { // The threshold in screen pixels after which this gesture is detected. const double threshold = 50; @@ -26,57 +24,50 @@ internal ThresholdPinchGestureRecognizer (IntPtr handle) : base (handle) { } - public override UIGestureRecognizerState State - { + public override UIGestureRecognizerState State { get => base.State; - set - { + set { base.State = value; - switch (value) - { - case UIGestureRecognizerState.Began : - case UIGestureRecognizerState.Changed : - break; - default : - // Reset threshold check - ThresholdExceeded = false; - break; + switch (value) { + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + break; + default: + // Reset threshold check + ThresholdExceeded = false; + break; } } } - double TouchDistance(CGPoint t1, CGPoint t2) => Math.Sqrt(Math.Pow(t1.X - t2.X, 2) + Math.Pow(t1.Y - t2.Y, 2)); + double TouchDistance (CGPoint t1, CGPoint t2) => Math.Sqrt (Math.Pow (t1.X - t2.X, 2) + Math.Pow (t1.Y - t2.Y, 2)); - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - if (touches.Count != 2) - { + if (touches.Count != 2) { return; } - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); - IEnumerable<CGPoint> tPoints = touches.ToArray<UITouch>().Select(t => t.LocationInView(View)); - var t0 = tPoints.First(); - var t1 = tPoints.Skip(1).First(); + IEnumerable<CGPoint> tPoints = touches.ToArray<UITouch> ().Select (t => t.LocationInView (View)); + var t0 = tPoints.First (); + var t1 = tPoints.Skip (1).First (); - switch (State) - { - case UIGestureRecognizerState.Began : - initialTouchDistance = TouchDistance(t0, t1); - break; - case UIGestureRecognizerState.Changed : - var touchDistance = TouchDistance(t0, t1); - if (Math.Abs(touchDistance - initialTouchDistance) > threshold) - { - thresholdExceeded = true; - } - break; - default : - break; + switch (State) { + case UIGestureRecognizerState.Began: + initialTouchDistance = TouchDistance (t0, t1); + break; + case UIGestureRecognizerState.Changed: + var touchDistance = TouchDistance (t0, t1); + if (Math.Abs (touchDistance - initialTouchDistance) > threshold) { + thresholdExceeded = true; + } + break; + default: + break; } - if (! thresholdExceeded) - { + if (!thresholdExceeded) { Scale = 1.0f; } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdRotationGestureRecognizer.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdRotationGestureRecognizer.cs index 465d4f90a..a34219c7c 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdRotationGestureRecognizer.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Gesture_Recognizers/ThresholdRotationGestureRecognizer.cs @@ -1,15 +1,13 @@ -// This file has been autogenerated from a class added in the UI designer. +// This file has been autogenerated from a class added in the UI designer. using System; using Foundation; using UIKit; -namespace ScanningAndDetecting3DObjects -{ +namespace ScanningAndDetecting3DObjects { // A custom rotation gesture recognizer that fires only when a threshold is passed - internal partial class ThresholdRotationGestureRecognizer : UIRotationGestureRecognizer - { + internal partial class ThresholdRotationGestureRecognizer : UIRotationGestureRecognizer { // The threshold after which this gesture is detected. const double threshold = Math.PI / 15; // (12°) @@ -19,45 +17,40 @@ internal partial class ThresholdRotationGestureRecognizer : UIRotationGestureRec private double previousRotation = 0; internal double RotationDelta { get; private set; } - internal ThresholdRotationGestureRecognizer(IntPtr handle) : base(handle) + internal ThresholdRotationGestureRecognizer (IntPtr handle) : base (handle) { } // Observe when the gesture's state changes to reset the threshold - public override UIGestureRecognizerState State - { + public override UIGestureRecognizerState State { get => base.State; - set - { + set { base.State = value; - switch(value) - { - case UIGestureRecognizerState.Began : - case UIGestureRecognizerState.Changed : - break; - default : - // Reset threshold check - thresholdExceeded = false; - previousRotation = 0; - RotationDelta = 0; - break; + switch (value) { + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + break; + default: + // Reset threshold check + thresholdExceeded = false; + previousRotation = 0; + RotationDelta = 0; + break; } } } - public override void TouchesMoved(NSSet touches, UIEvent evt) + public override void TouchesMoved (NSSet touches, UIEvent evt) { - base.TouchesMoved(touches, evt); + base.TouchesMoved (touches, evt); - if (thresholdExceeded) - { + if (thresholdExceeded) { RotationDelta = Rotation - previousRotation; previousRotation = Rotation; } - if (! thresholdExceeded && Math.Abs(Rotation) > threshold) - { + if (!thresholdExceeded && Math.Abs (Rotation) > threshold) { thresholdExceeded = true; previousRotation = Rotation; } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Main.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Main.cs index 08082846f..109996c10 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Main.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace ScanningAndDetecting3DObjects -{ - internal class Application - { +namespace ScanningAndDetecting3DObjects { + internal class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARCamera_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARCamera_Extensions.cs index 7dfca51a6..75ffafeae 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARCamera_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARCamera_Extensions.cs @@ -1,40 +1,34 @@ -using ARKit; +using ARKit; -namespace ScanningAndDetecting3DObjects -{ - internal static class ARCamera_Extensions - { - internal static string PresentationString(this ARCamera self) +namespace ScanningAndDetecting3DObjects { + internal static class ARCamera_Extensions { + internal static string PresentationString (this ARCamera self) { var tracking = self.TrackingState; - switch (tracking) - { - case ARTrackingState.NotAvailable: return "ARKit tracking UNAVAILABLE"; - case ARTrackingState.Normal: return "ARKit tracking NORMAL"; - case ARTrackingState.Limited: - switch (self.TrackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: return "ARKit tracking LIMITED : Excessive motion"; - case ARTrackingStateReason.InsufficientFeatures: return "ARKit tracking LIMITED : Low detail"; - case ARTrackingStateReason.Initializing: return "ARKit is initializing"; - case ARTrackingStateReason.Relocalizing: return "ARKit is relocalizing"; - } - break; + switch (tracking) { + case ARTrackingState.NotAvailable: return "ARKit tracking UNAVAILABLE"; + case ARTrackingState.Normal: return "ARKit tracking NORMAL"; + case ARTrackingState.Limited: + switch (self.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: return "ARKit tracking LIMITED : Excessive motion"; + case ARTrackingStateReason.InsufficientFeatures: return "ARKit tracking LIMITED : Low detail"; + case ARTrackingStateReason.Initializing: return "ARKit is initializing"; + case ARTrackingStateReason.Relocalizing: return "ARKit is relocalizing"; + } + break; } // Can't actually get here return ""; } - internal static string Recommendation(this ARCamera self) + internal static string Recommendation (this ARCamera self) { - if (self.TrackingState == ARTrackingState.Limited) - { - switch (self.TrackingStateReason) - { - case ARTrackingStateReason.ExcessiveMotion: return "Try slowing down your movement or reset the session."; - case ARTrackingStateReason.InsufficientFeatures: return "Try pointing at a flat surface or reset the session."; - case ARTrackingStateReason.Initializing: return "Try moving left or right or reset the session."; - case ARTrackingStateReason.Relocalizing: return "Try returning to the location where you left off."; + if (self.TrackingState == ARTrackingState.Limited) { + switch (self.TrackingStateReason) { + case ARTrackingStateReason.ExcessiveMotion: return "Try slowing down your movement or reset the session."; + case ARTrackingStateReason.InsufficientFeatures: return "Try pointing at a flat surface or reset the session."; + case ARTrackingStateReason.Initializing: return "Try moving left or right or reset the session."; + case ARTrackingStateReason.Relocalizing: return "Try returning to the location where you left off."; } } return null; diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARSCNView_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARSCNView_Extensions.cs index a51afd6d7..ab47027da 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARSCNView_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/ARSCNView_Extensions.cs @@ -1,37 +1,32 @@ -using System; +using System; using CoreGraphics; using OpenTK; using ARKit; using SceneKit; -namespace ScanningAndDetecting3DObjects -{ - internal static class ARSCNView_Extensions - { - internal static SCNVector3? UnprojectPointLocal(this ARSCNView self, CGPoint point, NMatrix4 planeTransform) +namespace ScanningAndDetecting3DObjects { + internal static class ARSCNView_Extensions { + internal static SCNVector3? UnprojectPointLocal (this ARSCNView self, CGPoint point, NMatrix4 planeTransform) { - var result = self.Unproject(point, planeTransform); + var result = self.Unproject (point, planeTransform); // Convert the result into the plane's local coordinate system. - var pt = new SCNVector4(result.X, result.Y, result.Z, 1); - var invertedPlane = planeTransform.ToSCNMatrix4(); - invertedPlane.Invert(); - var localResult = invertedPlane.Times(pt); + var pt = new SCNVector4 (result.X, result.Y, result.Z, 1); + var invertedPlane = planeTransform.ToSCNMatrix4 (); + invertedPlane.Invert (); + var localResult = invertedPlane.Times (pt); return localResult.Xyz; } - internal static ARHitTestResult SmartHitTest(this ARSCNView self, CGPoint point) + internal static ARHitTestResult SmartHitTest (this ARSCNView self, CGPoint point) { - var hitTestResults = self.HitTest(point, ARHitTestResultType.FeaturePoint); - if (hitTestResults == null || hitTestResults.Length == 0) - { + var hitTestResults = self.HitTest (point, ARHitTestResultType.FeaturePoint); + if (hitTestResults == null || hitTestResults.Length == 0) { return null; } - foreach(var result in hitTestResults) - { + foreach (var result in hitTestResults) { // Return the first result which is between 20 cm and 3 m away from the user. - if (result.Distance > 0.2 && result.Distance < 3) - { + if (result.Distance > 0.2 && result.Distance < 3) { return result; } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Axis.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Axis.cs index ec76c04de..ab4f33d0c 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Axis.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Axis.cs @@ -1,26 +1,22 @@ -using OpenTK; +using OpenTK; using System; -namespace ScanningAndDetecting3DObjects -{ - internal enum Axis - { +namespace ScanningAndDetecting3DObjects { + internal enum Axis { X, Y, Z } - static class Axis_Extensions - { - internal static NVector3 Normal(this Axis self) + static class Axis_Extensions { + internal static NVector3 Normal (this Axis self) { - switch(self) - { - case Axis.X : return new NVector3(1, 0, 0); - case Axis.Y : return new NVector3(0, 1, 0); - case Axis.Z : return new NVector3(0, 0, 1); + switch (self) { + case Axis.X: return new NVector3 (1, 0, 0); + case Axis.Y: return new NVector3 (0, 1, 0); + case Axis.Z: return new NVector3 (0, 0, 1); } - throw new ArgumentException("Should never reach here."); + throw new ArgumentException ("Should never reach here."); } } -} \ No newline at end of file +} diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/CGPoint_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/CGPoint_Extensions.cs index 10cab00b3..69d1d0514 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/CGPoint_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/CGPoint_Extensions.cs @@ -1,16 +1,14 @@ -using System; +using System; using CoreGraphics; -namespace ScanningAndDetecting3DObjects -{ - internal static class CGPoint_Extensions - { - internal static double Length(this CGPoint self) +namespace ScanningAndDetecting3DObjects { + internal static class CGPoint_Extensions { + internal static double Length (this CGPoint self) { - return Math.Sqrt(self.X * self.X + self.Y * self.Y); + return Math.Sqrt (self.X * self.X + self.Y * self.Y); } // No operator overloading in extension methods until C# 8 - internal static CGPoint Add(this CGPoint self, CGPoint other) => new CGPoint(self.X + other.X, self.Y + other.Y); + internal static CGPoint Add (this CGPoint self, CGPoint other) => new CGPoint (self.X + other.X, self.Y + other.Y); } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NMatrix4_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NMatrix4_Extensions.cs index 30fd569fe..dcd19d74a 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NMatrix4_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NMatrix4_Extensions.cs @@ -1,13 +1,11 @@ -using SceneKit; +using SceneKit; using OpenTK; -namespace ScanningAndDetecting3DObjects -{ - internal static class NMatrix4_Extensions - { - internal static SCNMatrix4 ToSCNMatrix4(this NMatrix4 self) +namespace ScanningAndDetecting3DObjects { + internal static class NMatrix4_Extensions { + internal static SCNMatrix4 ToSCNMatrix4 (this NMatrix4 self) { - var newMatrix = new SCNMatrix4( + var newMatrix = new SCNMatrix4 ( self.M11, self.M21, self.M31, self.M41, self.M12, self.M22, self.M32, self.M42, self.M13, self.M23, self.M33, self.M43, @@ -18,6 +16,6 @@ internal static SCNMatrix4 ToSCNMatrix4(this NMatrix4 self) } // Important: This is transposed from SCNMatrix4! (See, for instance, Ray.DragPlaneTransform() functions) - internal static Vector3 Position(this NMatrix4 self) => self.Column3.Xyz; + internal static Vector3 Position (this NMatrix4 self) => self.Column3.Xyz; } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NVector3_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NVector3_Extensions.cs index 11ef9866e..41c45f33a 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NVector3_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/NVector3_Extensions.cs @@ -1,49 +1,47 @@ -using System; +using System; using SceneKit; using OpenTK; using static System.Math; -namespace ScanningAndDetecting3DObjects -{ - internal static class NVector3_Extensions - { - internal static SCNVector3 ToSCNVector3(this NVector3 self) => new SCNVector3(self.X, self.Y, self.Z); +namespace ScanningAndDetecting3DObjects { + internal static class NVector3_Extensions { + internal static SCNVector3 ToSCNVector3 (this NVector3 self) => new SCNVector3 (self.X, self.Y, self.Z); - internal static float Distance(this NVector3 self, NVector3 other) + internal static float Distance (this NVector3 self, NVector3 other) { - var distanceSquared = Pow(self.X - other.X, 2) + Pow(self.Y - other.Y, 2) + Pow(self.Z - other.Z, 2); - return (float)Sqrt(distanceSquared); + var distanceSquared = Pow (self.X - other.X, 2) + Pow (self.Y - other.Y, 2) + Pow (self.Z - other.Z, 2); + return (float) Sqrt (distanceSquared); } - internal static NVector3 Minus(this NVector3 self, NVector3 other) + internal static NVector3 Minus (this NVector3 self, NVector3 other) { - return new NVector3(self.X - other.X, self.Y - other.Y, self.Z - other.Z); + return new NVector3 (self.X - other.X, self.Y - other.Y, self.Z - other.Z); } - internal static NVector3 Plus(this NVector3 self, NVector3 other) => new NVector3(self.X + other.X, self.Y + other.Y, self.Z + other.Z); + internal static NVector3 Plus (this NVector3 self, NVector3 other) => new NVector3 (self.X + other.X, self.Y + other.Y, self.Z + other.Z); // Euclidean norm - internal static float Length(this NVector3 self) + internal static float Length (this NVector3 self) { - return (float)Sqrt(self.X * self.X + self.Y * self.Y + self.Z * self.Z); + return (float) Sqrt (self.X * self.X + self.Y * self.Y + self.Z * self.Z); } - internal static NVector3 Times(this NVector3 self, float scale) + internal static NVector3 Times (this NVector3 self, float scale) { - return new NVector3(self.X * scale, self.Y * scale, self.Z * scale); + return new NVector3 (self.X * scale, self.Y * scale, self.Z * scale); } // Element-wise minimum - internal static NVector3 Min(this NVector3 self, NVector3 other) + internal static NVector3 Min (this NVector3 self, NVector3 other) { - return new NVector3(Math.Min(self.X, other.X), Math.Min(self.Y, other.Y), Math.Min(self.Y, other.Y)); + return new NVector3 (Math.Min (self.X, other.X), Math.Min (self.Y, other.Y), Math.Min (self.Y, other.Y)); } // Element-wise maximum - internal static NVector3 Max(this NVector3 self, NVector3 other) + internal static NVector3 Max (this NVector3 self, NVector3 other) { - return new NVector3(Math.Max(self.X, other.X), Math.Max(self.Y, other.Y), Math.Max(self.Y, other.Y)); + return new NVector3 (Math.Max (self.X, other.X), Math.Max (self.Y, other.Y), Math.Max (self.Y, other.Y)); } } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNMatrix4_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNMatrix4_Extensions.cs index c18f079a5..3a810bdfd 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNMatrix4_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNMatrix4_Extensions.cs @@ -1,15 +1,13 @@ -using System; +using System; using SceneKit; using UIKit; -namespace ScanningAndDetecting3DObjects -{ - internal static class SCNMatrix4_Extensions - { +namespace ScanningAndDetecting3DObjects { + internal static class SCNMatrix4_Extensions { // Note that this just straight-across converts, does _not_ transpose, (see README.MD for discussion) - internal static OpenTK.NMatrix4 ToNMatrix4(this SCNMatrix4 self) + internal static OpenTK.NMatrix4 ToNMatrix4 (this SCNMatrix4 self) { - var newMatrix = new OpenTK.NMatrix4( + var newMatrix = new OpenTK.NMatrix4 ( self.M11, self.M21, self.M31, self.M41, self.M12, self.M22, self.M32, self.M42, self.M13, self.M23, self.M33, self.M43, @@ -22,15 +20,15 @@ internal static OpenTK.NMatrix4 ToNMatrix4(this SCNMatrix4 self) /// `FloatNxM` where `N` is the number of *columns* and `M` is the number of /// *rows*, so we multiply a `Float3x2 * Float3` to get a `Float2`, for /// example. - internal static SCNVector4 Times(this SCNMatrix4 self, SCNVector4 vec) + internal static SCNVector4 Times (this SCNMatrix4 self, SCNVector4 vec) { Func<SCNVector4, float> elementSum = v => v.X + v.Y + v.Z + v.W; - Func<SCNVector4, float, float> rowTimesVecEl = (row, s) => elementSum(SCNVector4.Multiply(row, s)); - var x = rowTimesVecEl(self.Row0, vec.X); - var y = rowTimesVecEl(self.Row1, vec.Y); - var z = rowTimesVecEl(self.Row2, vec.Z); - var w = rowTimesVecEl(self.Row3, vec.W); - return new SCNVector4(x, y, z, w); + Func<SCNVector4, float, float> rowTimesVecEl = (row, s) => elementSum (SCNVector4.Multiply (row, s)); + var x = rowTimesVecEl (self.Row0, vec.X); + var y = rowTimesVecEl (self.Row1, vec.Y); + var z = rowTimesVecEl (self.Row2, vec.Z); + var w = rowTimesVecEl (self.Row3, vec.W); + return new SCNVector4 (x, y, z, w); } } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNVector3_Extensions.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNVector3_Extensions.cs index 05a3218f4..1a771c568 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNVector3_Extensions.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SCNVector3_Extensions.cs @@ -1,42 +1,40 @@ -using System; +using System; using SceneKit; using OpenTK; using static System.Math; -namespace ScanningAndDetecting3DObjects -{ - internal static class SCNVector3_Extensions - { - internal static float Distance(this SCNVector3 self, SCNVector3 other) +namespace ScanningAndDetecting3DObjects { + internal static class SCNVector3_Extensions { + internal static float Distance (this SCNVector3 self, SCNVector3 other) { - var distanceSquared = Pow(self.X - other.X, 2) + Pow(self.Y - other.Y, 2) + Pow(self.Z - other.Z, 2); - return (float) Sqrt(distanceSquared); + var distanceSquared = Pow (self.X - other.X, 2) + Pow (self.Y - other.Y, 2) + Pow (self.Z - other.Z, 2); + return (float) Sqrt (distanceSquared); } - internal static NVector3 Times(this SCNVector3 self, float scale) + internal static NVector3 Times (this SCNVector3 self, float scale) { - return new NVector3(self.X * scale, self.Y * scale, self.Z * scale); + return new NVector3 (self.X * scale, self.Y * scale, self.Z * scale); } - internal static SCNVector3 Normalized(this SCNVector3 self) + internal static SCNVector3 Normalized (this SCNVector3 self) { - var copy = new SCNVector3(self); - copy.Normalize(); + var copy = new SCNVector3 (self); + copy.Normalize (); return copy; } // Elementwise minimum - internal static SCNVector3 Min(this SCNVector3 self, SCNVector3 other) => new SCNVector3(Math.Min(self.X, other.X), Math.Min(self.Y, other.Y), Math.Min(self.Z, other.Z)); + internal static SCNVector3 Min (this SCNVector3 self, SCNVector3 other) => new SCNVector3 (Math.Min (self.X, other.X), Math.Min (self.Y, other.Y), Math.Min (self.Z, other.Z)); // Elementwise maximum - internal static SCNVector3 Max(this SCNVector3 self, SCNVector3 other) => new SCNVector3(Math.Max(self.X, other.X), Math.Max(self.Y, other.Y), Math.Max(self.Z, other.Z)); + internal static SCNVector3 Max (this SCNVector3 self, SCNVector3 other) => new SCNVector3 (Math.Max (self.X, other.X), Math.Max (self.Y, other.Y), Math.Max (self.Z, other.Z)); - internal static NVector3 ToNVector3(this SCNVector3 self) => new NVector3(self.X, self.Y, self.Z); + internal static NVector3 ToNVector3 (this SCNVector3 self) => new NVector3 (self.X, self.Y, self.Z); - internal static NVector3 Minus(this SCNVector3 self, NVector3 other) => new NVector3(self.X - other.X, self.Y - other.Y, self.Z - other.Z); + internal static NVector3 Minus (this SCNVector3 self, NVector3 other) => new NVector3 (self.X - other.X, self.Y - other.Y, self.Z - other.Z); - internal static SCNVector3 Plus(this SCNVector3 self, NVector3 other) => new SCNVector3(self.X + other.X, self.Y + other.Y, self.Z + other.Z); + internal static SCNVector3 Plus (this SCNVector3 self, NVector3 other) => new SCNVector3 (self.X + other.X, self.Y + other.Y, self.Z + other.Z); - internal static SCNVector3 Plus(this SCNVector3 self, Vector3d other) => new SCNVector3(self.X + (float)other.X, self.Y + (float)other.Y, self.Z + (float)other.Z); + internal static SCNVector3 Plus (this SCNVector3 self, Vector3d other) => new SCNVector3 (self.X + (float) other.X, self.Y + (float) other.Y, self.Z + (float) other.Z); } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SimpleBox.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SimpleBox.cs index f5cea74a5..d1d3b259d 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SimpleBox.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/SimpleBox.cs @@ -1,12 +1,10 @@ -using System; -namespace ScanningAndDetecting3DObjects -{ +using System; +namespace ScanningAndDetecting3DObjects { // See README.MD - internal class SimpleBox<T> : Foundation.NSObject - { + internal class SimpleBox<T> : Foundation.NSObject { internal T Value { get; } - internal SimpleBox(T v) + internal SimpleBox (T v) { this.Value = v; } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Utilities.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Utilities.cs index 40c905ce0..0b309708d 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Utilities.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Utility_Extensions/Utilities.cs @@ -1,33 +1,28 @@ -using System; +using System; using UIKit; using SceneKit; using Foundation; using OpenTK; using System.Linq; -namespace ScanningAndDetecting3DObjects -{ - internal static class Utilities - { +namespace ScanningAndDetecting3DObjects { + internal static class Utilities { // Colors defined in Asset Catalog - internal readonly static UIColor AppYellow = UIColor.FromName("appYellow"); - internal readonly static UIColor AppBrown = UIColor.FromName("appBrown"); - internal readonly static UIColor AppGreen = UIColor.FromName("appGreen"); - internal readonly static UIColor AppBlue = UIColor.FromName("appBlue"); - internal readonly static UIColor AppLightBlue = UIColor.FromName("appLightBlue"); - internal readonly static UIColor AppGray = UIColor.FromName("appGray"); + internal readonly static UIColor AppYellow = UIColor.FromName ("appYellow"); + internal readonly static UIColor AppBrown = UIColor.FromName ("appBrown"); + internal readonly static UIColor AppGreen = UIColor.FromName ("appGreen"); + internal readonly static UIColor AppBlue = UIColor.FromName ("appBlue"); + internal readonly static UIColor AppLightBlue = UIColor.FromName ("appLightBlue"); + internal readonly static UIColor AppGray = UIColor.FromName ("appGray"); - internal static SCNMaterial Material(NSObject diffuse, bool respondsToLighting = false, bool isDoubleSided = true) + internal static SCNMaterial Material (NSObject diffuse, bool respondsToLighting = false, bool isDoubleSided = true) { - var material = new SCNMaterial(); + var material = new SCNMaterial (); material.Diffuse.Contents = diffuse; material.DoubleSided = isDoubleSided; - if (respondsToLighting) - { + if (respondsToLighting) { material.LocksAmbientWithDiffuse = true; - } - else - { + } else { material.LocksAmbientWithDiffuse = false; material.Ambient.ContentColor = UIColor.Black; material.LightingModelName = SCNLightingModel.Constant; @@ -35,52 +30,46 @@ internal static SCNMaterial Material(NSObject diffuse, bool respondsToLighting = return material; } - internal static SCNNode Load3DModel(NSUrl url) + internal static SCNNode Load3DModel (NSUrl url) { - var scene = SCNScene.FromUrl(url, new NSDictionary(), out var err); - if(scene == null) - { - Console.WriteLine($"Error: failed to load 3D model from file {url}."); - if (err != null) - { - Console.WriteLine(err.ToString()); + var scene = SCNScene.FromUrl (url, new NSDictionary (), out var err); + if (scene == null) { + Console.WriteLine ($"Error: failed to load 3D model from file {url}."); + if (err != null) { + Console.WriteLine (err.ToString ()); } return null; } - var node = new SCNNode(); - foreach(var child in scene.RootNode.ChildNodes) - { - node.AddChildNode(child); + var node = new SCNNode (); + foreach (var child in scene.RootNode.ChildNodes) { + node.AddChildNode (child); } // If there are no light sources in the model, add some - var lightNodes = node.ChildNodes.Where(child => child.Light != null); - if (lightNodes.Count() == 0) - { - var ambientLight = new SCNLight - { + var lightNodes = node.ChildNodes.Where (child => child.Light != null); + if (lightNodes.Count () == 0) { + var ambientLight = new SCNLight { LightType = SCNLightType.Ambient, Intensity = 100 }; - var ambientLightNode = new SCNNode(); + var ambientLightNode = new SCNNode (); ambientLightNode.Light = ambientLight; - node.AddChildNode(ambientLightNode); + node.AddChildNode (ambientLightNode); - var directionLight = new SCNLight - { + var directionLight = new SCNLight { LightType = SCNLightType.Directional, Intensity = 500 }; - var directionalLightNode = new SCNNode(); + var directionalLightNode = new SCNNode (); directionalLightNode.Light = directionLight; - node.AddChildNode(directionalLightNode); + node.AddChildNode (directionalLightNode); } return node; } - internal static Vector4 SCNVector4Create(SCNVector3 float3, int last) => new Vector4(float3.X, float3.Y, float3.Z, last); + internal static Vector4 SCNVector4Create (SCNVector3 float3, int last) => new Vector4 (float3.X, float3.Y, float3.Z, last); - internal static NMatrix4 NMatrix4Create(Vector4[] rows) => new NMatrix4(rows[0], rows[1], rows[2], rows[3]); + internal static NMatrix4 NMatrix4Create (Vector4 [] rows) => new NMatrix4 (rows [0], rows [1], rows [2], rows [3]); } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/FlashlightButton.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/FlashlightButton.cs index 93b2ed4a6..fc49920ed 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/FlashlightButton.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/FlashlightButton.cs @@ -1,4 +1,4 @@ -// This file has been autogenerated from a class added in the UI designer. +// This file has been autogenerated from a class added in the UI designer. using System; @@ -6,67 +6,53 @@ using UIKit; using AVFoundation; -namespace ScanningAndDetecting3DObjects -{ - internal partial class FlashlightButton : UIButton - { +namespace ScanningAndDetecting3DObjects { + internal partial class FlashlightButton : UIButton { internal FlashlightButton (IntPtr handle) : base (handle) { } private bool toggledOn; - internal bool ToggledOn { + internal bool ToggledOn { get => toggledOn; - set - { + set { toggledOn = value; // Update UI - if (toggledOn) - { - SetTitle("Light Off", UIControlState.Normal); + if (toggledOn) { + SetTitle ("Light Off", UIControlState.Normal); BackgroundColor = Utilities.AppLightBlue; - } - else - { - SetTitle("Light On", UIControlState.Normal); + } else { + SetTitle ("Light On", UIControlState.Normal); BackgroundColor = Utilities.AppLightBlue; } // Toggle flashlight - var captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaTypes.Video); - if (captureDevice == null) - { + var captureDevice = AVCaptureDevice.GetDefaultDevice (AVMediaTypes.Video); + if (captureDevice == null) { return; } - if (! captureDevice.HasTorch) - { - if (toggledOn) - { + if (!captureDevice.HasTorch) { + if (toggledOn) { toggledOn = false; } return; } - try - { + try { NSError err = null; - var locked = captureDevice.LockForConfiguration(out err); - if (!locked || err != null) - { - Console.WriteLine("Error while attempting to access flashlight."); + var locked = captureDevice.LockForConfiguration (out err); + if (!locked || err != null) { + Console.WriteLine ("Error while attempting to access flashlight."); return; } var mode = toggledOn ? AVCaptureTorchMode.On : AVCaptureTorchMode.Off; - if (captureDevice.IsTorchModeSupported(mode)) - { + if (captureDevice.IsTorchModeSupported (mode)) { captureDevice.TorchMode = mode; } - captureDevice.UnlockForConfiguration(); - } - catch(Exception x) - { - Console.WriteLine("Error while attempting to access flashlight."); + captureDevice.UnlockForConfiguration (); + } catch (Exception x) { + Console.WriteLine ("Error while attempting to access flashlight."); } } } diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/MessageLabel.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/MessageLabel.cs index 192004632..a4566693c 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/MessageLabel.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/MessageLabel.cs @@ -1,4 +1,4 @@ -// This file has been autogenerated from a class added in the UI designer. +// This file has been autogenerated from a class added in the UI designer. using System; using CoreGraphics; @@ -6,46 +6,37 @@ using UIKit; using CoreFoundation; -namespace ScanningAndDetecting3DObjects -{ - internal class Message - { - internal NSMutableAttributedString Text - { +namespace ScanningAndDetecting3DObjects { + internal class Message { + internal NSMutableAttributedString Text { get; } - internal Message(string body, string title = "") + internal Message (string body, string title = "") { - if (title != null) - { + if (title != null) { // make the title bold - Text = new NSMutableAttributedString($"{title}\n{body}"); - var titleRange = new NSRange(0, title.Length); - Text.AddAttribute(new NSString("NSFont"), UIFont.BoldSystemFontOfSize(17), titleRange); - } - else - { - Text = new NSMutableAttributedString(body); + Text = new NSMutableAttributedString ($"{title}\n{body}"); + var titleRange = new NSRange (0, title.Length); + Text.AddAttribute (new NSString ("NSFont"), UIFont.BoldSystemFontOfSize (17), titleRange); + } else { + Text = new NSMutableAttributedString (body); } } - void PrintToConsole() + void PrintToConsole () { - Console.WriteLine(Text.Value); + Console.WriteLine (Text.Value); } } - internal partial class MessageLabel : UILabel - { + internal partial class MessageLabel : UILabel { internal MessageLabel (IntPtr handle) : base (handle) { } - public override CGSize IntrinsicContentSize - { - get - { + public override CGSize IntrinsicContentSize { + get { var contentSize = base.IntrinsicContentSize; contentSize.Width += 20; contentSize.Height += 20; @@ -53,19 +44,17 @@ public override CGSize IntrinsicContentSize } } - internal void Display(Message msg) + internal void Display (Message msg) { - DispatchQueue.MainQueue.DispatchAsync(() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { AttributedText = msg.Text; Hidden = false; }); } - internal void Clear() + internal void Clear () { - DispatchQueue.MainQueue.DispatchAsync(() => - { + DispatchQueue.MainQueue.DispatchAsync (() => { // Note that setting `Text` clears `AttributedText` Text = ""; Hidden = true; diff --git a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/RoundedButton.cs b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/RoundedButton.cs index c468ae506..463484685 100644 --- a/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/RoundedButton.cs +++ b/ios12/ScanningAndDetecting3DObjects/ScanningApp/Views/RoundedButton.cs @@ -1,30 +1,28 @@ -// This file has been autogenerated from a class added in the UI designer. +// This file has been autogenerated from a class added in the UI designer. using System; using Foundation; using UIKit; -namespace ScanningAndDetecting3DObjects -{ - internal partial class RoundedButton : UIButton - { +namespace ScanningAndDetecting3DObjects { + internal partial class RoundedButton : UIButton { internal RoundedButton (IntPtr handle) : base (handle) { - Setup(); + Setup (); } - protected void Setup() + protected void Setup () { BackgroundColor = Utilities.AppBlue; Layer.CornerRadius = 8; ClipsToBounds = true; - SetTitleColor(UIColor.White, UIControlState.Normal); - TitleLabel.Font = UIFont.BoldSystemFontOfSize(17); + SetTitleColor (UIColor.White, UIControlState.Normal); + TitleLabel.Font = UIFont.BoldSystemFontOfSize (17); } - public override bool Enabled { - get => base.Enabled; + public override bool Enabled { + get => base.Enabled; set { base.Enabled = value; BackgroundColor = value ? Utilities.AppBlue : Utilities.AppGray; @@ -32,13 +30,11 @@ public override bool Enabled { } private bool toggledOn; - internal bool ToggledOn { - get => toggledOn; - set - { + internal bool ToggledOn { + get => toggledOn; + set { toggledOn = value; - if (! value) - { + if (!value) { BackgroundColor = Utilities.AppGray; return; } diff --git a/ios12/SoupChef/OrderSoupIntentBinding/ApiDefinitions.cs b/ios12/SoupChef/OrderSoupIntentBinding/ApiDefinitions.cs index 265fbb90e..337e03e60 100644 --- a/ios12/SoupChef/OrderSoupIntentBinding/ApiDefinitions.cs +++ b/ios12/SoupChef/OrderSoupIntentBinding/ApiDefinitions.cs @@ -3,13 +3,11 @@ using Intents; using ObjCRuntime; -namespace SoupChef -{ +namespace SoupChef { // @interface OrderSoupIntent : INIntent // [Watch (5,0), iOS (12,0)] - [BaseType (typeof(INIntent))] - interface OrderSoupIntent - { + [BaseType (typeof (INIntent))] + interface OrderSoupIntent { // @property (readwrite, copy, nonatomic) INObject * _Nullable soup; [NullAllowed, Export ("soup", ArgumentSemantic.Copy)] INObject Soup { get; set; } @@ -20,15 +18,14 @@ interface OrderSoupIntent // @property (readwrite, copy, nonatomic) NSArray<INObject *> * _Nullable options; [NullAllowed, Export ("options", ArgumentSemantic.Copy)] - INObject[] Options { get; set; } + INObject [] Options { get; set; } } // @protocol OrderSoupIntentHandling <NSObject> // [Watch (5,0), iOS (12,0)] [Protocol, Model] - [BaseType (typeof(NSObject))] - interface OrderSoupIntentHandling - { + [BaseType (typeof (NSObject))] + interface OrderSoupIntentHandling { // @required -(void)handleOrderSoup:(OrderSoupIntent * _Nonnull)intent completion:(void (^ _Nonnull)(OrderSoupIntentResponse * _Nonnull))completion; [Abstract] [Export ("handleOrderSoup:completion:")] @@ -41,10 +38,9 @@ interface OrderSoupIntentHandling // @interface OrderSoupIntentResponse : INIntentResponse // [Watch (5,0), iOS (12,0)] - [BaseType (typeof(INIntentResponse))] + [BaseType (typeof (INIntentResponse))] [DisableDefaultCtor] - interface OrderSoupIntentResponse - { + interface OrderSoupIntentResponse { // -(instancetype _Nonnull)initWithCode:(OrderSoupIntentResponseCode)code userActivity:(NSUserActivity * _Nullable)userActivity __attribute__((objc_designated_initializer)); [Export ("initWithCode:userActivity:")] [DesignatedInitializer] diff --git a/ios12/SoupChef/OrderSoupIntentBinding/Properties/AssemblyInfo.cs b/ios12/SoupChef/OrderSoupIntentBinding/Properties/AssemblyInfo.cs index 1af06a73a..9e6b06fab 100644 --- a/ios12/SoupChef/OrderSoupIntentBinding/Properties/AssemblyInfo.cs +++ b/ios12/SoupChef/OrderSoupIntentBinding/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using Foundation; @@ -12,20 +12,20 @@ // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. -[assembly: AssemblyTitle("OrderSoupIntentBinding")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("OrderSoupIntentBinding")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("")] +[assembly: AssemblyCopyright ("")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. diff --git a/ios12/SoupChef/OrderSoupIntentBinding/StructsAndEnums.cs b/ios12/SoupChef/OrderSoupIntentBinding/StructsAndEnums.cs index 3ab48c649..14f8d33bf 100644 --- a/ios12/SoupChef/OrderSoupIntentBinding/StructsAndEnums.cs +++ b/ios12/SoupChef/OrderSoupIntentBinding/StructsAndEnums.cs @@ -1,12 +1,10 @@ using System; using ObjCRuntime; -namespace SoupChef -{ +namespace SoupChef { // [Watch (5,0), iOS (12,0)] [Native] - public enum OrderSoupIntentResponseCode : long - { + public enum OrderSoupIntentResponseCode : long { Unspecified = 0, Ready, ContinueInApp, diff --git a/ios12/SoupChef/SoupChef/Main.cs b/ios12/SoupChef/SoupChef/Main.cs index 635c0e348..591d0de51 100644 --- a/ios12/SoupChef/SoupChef/Main.cs +++ b/ios12/SoupChef/SoupChef/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace SoupChef -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace SoupChef { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios12/SoupChef/SoupChef/UI/AppDelegate.cs b/ios12/SoupChef/SoupChef/UI/AppDelegate.cs index f67e07124..9833404bd 100644 --- a/ios12/SoupChef/SoupChef/UI/AppDelegate.cs +++ b/ios12/SoupChef/SoupChef/UI/AppDelegate.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -14,56 +14,48 @@ The application delegate. using SoupKit.Support; using SoupKit; -namespace SoupChef -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window - { - get; - set; - } +namespace SoupChef { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { + get; + set; + } - public override bool ContinueUserActivity(UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler) - { - var intent = userActivity.GetInteraction()?.Intent as OrderSoupIntent; - if (!(intent is null)) - { - HandleIntent(intent); - return true; - } - else if (userActivity.ActivityType == NSUserActivityHelper.ViewMenuActivityType) - { - HandleUserActivity(); - return true; - } - return false; - } + public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler) + { + var intent = userActivity.GetInteraction ()?.Intent as OrderSoupIntent; + if (!(intent is null)) { + HandleIntent (intent); + return true; + } else if (userActivity.ActivityType == NSUserActivityHelper.ViewMenuActivityType) { + HandleUserActivity (); + return true; + } + return false; + } - void HandleIntent(OrderSoupIntent intent) - { - var handler = new OrderSoupIntentHandler(); - handler.HandleOrderSoup(intent, (response) => { - if( response.Code != OrderSoupIntentResponseCode.Success ) - { - Console.WriteLine("Quantity must be greater than 0 to add to order"); - } - }); - } + void HandleIntent (OrderSoupIntent intent) + { + var handler = new OrderSoupIntentHandler (); + handler.HandleOrderSoup (intent, (response) => { + if (response.Code != OrderSoupIntentResponseCode.Success) { + Console.WriteLine ("Quantity must be greater than 0 to add to order"); + } + }); + } - void HandleUserActivity() - { - var rootViewController = Window?.RootViewController as UINavigationController; - var orderHistoryViewController = rootViewController?.ViewControllers?.FirstOrDefault() as OrderHistoryTableViewController; - if (orderHistoryViewController is null) - { - Console.WriteLine("Failed to access OrderHistoryTableViewController."); - return; - } - var segue = OrderHistoryTableViewController.SegueIdentifiers.SoupMenu; - orderHistoryViewController.PerformSegue(segue, null); - } - } + void HandleUserActivity () + { + var rootViewController = Window?.RootViewController as UINavigationController; + var orderHistoryViewController = rootViewController?.ViewControllers?.FirstOrDefault () as OrderHistoryTableViewController; + if (orderHistoryViewController is null) { + Console.WriteLine ("Failed to access OrderHistoryTableViewController."); + return; + } + var segue = OrderHistoryTableViewController.SegueIdentifiers.SoupMenu; + orderHistoryViewController.PerformSegue (segue, null); + } + } } diff --git a/ios12/SoupChef/SoupChef/UI/Cells/QuantityCell.cs b/ios12/SoupChef/SoupChef/UI/Cells/QuantityCell.cs index 06b7c9366..a7cfdaf0f 100644 --- a/ios12/SoupChef/SoupChef/UI/Cells/QuantityCell.cs +++ b/ios12/SoupChef/SoupChef/UI/Cells/QuantityCell.cs @@ -1,28 +1,26 @@ -using System; -using UIKit; - -namespace SoupChef -{ - public partial class QuantityCell : UITableViewCell - { - public const string CellIdentifier = "Quantity Cell"; - - // Used by OrderDetailViewController - public UILabel GetQuantityLabel() - { - return this.QuantityLabel; - } - - // Used by OrderDetailViewController - public UIStepper GetStepper() - { - return this.Stepper; - } +using System; +using UIKit; - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public QuantityCell(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +namespace SoupChef { + public partial class QuantityCell : UITableViewCell { + public const string CellIdentifier = "Quantity Cell"; + + // Used by OrderDetailViewController + public UILabel GetQuantityLabel () + { + return this.QuantityLabel; + } + + // Used by OrderDetailViewController + public UIStepper GetStepper () + { + return this.Stepper; + } + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public QuantityCell (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChef/UI/Cells/SoupMenuItemDetailCell.cs b/ios12/SoupChef/SoupChef/UI/Cells/SoupMenuItemDetailCell.cs index 3f9b1d140..9dcba939e 100644 --- a/ios12/SoupChef/SoupChef/UI/Cells/SoupMenuItemDetailCell.cs +++ b/ios12/SoupChef/SoupChef/UI/Cells/SoupMenuItemDetailCell.cs @@ -1,19 +1,17 @@ using SoupKit.UI; -using System; -using UIKit; - -namespace SoupChef -{ - public partial class SoupMenuItemDetailCell : UITableViewCell - { - public const string CellIdentifier = "SoupMenuItemDetailCell"; +using System; +using UIKit; - public MenuItemView DetailView => detailView; - - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public SoupMenuItemDetailCell(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +namespace SoupChef { + public partial class SoupMenuItemDetailCell : UITableViewCell { + public const string CellIdentifier = "SoupMenuItemDetailCell"; + + public MenuItemView DetailView => detailView; + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public SoupMenuItemDetailCell (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChef/UI/Cells/SoupOrderDetailCell.cs b/ios12/SoupChef/SoupChef/UI/Cells/SoupOrderDetailCell.cs index 8fcc8bd31..aca47b00c 100644 --- a/ios12/SoupChef/SoupChef/UI/Cells/SoupOrderDetailCell.cs +++ b/ios12/SoupChef/SoupChef/UI/Cells/SoupOrderDetailCell.cs @@ -1,19 +1,17 @@ -using System; -using UIKit; -using SoupKit.UI; - -namespace SoupChef -{ - public partial class SoupOrderDetailCell : UITableViewCell - { - public const string CellIdentifier = "SoupOrderDetailCell"; - - public MenuItemView DetailView => detailView; - - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public SoupOrderDetailCell(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +using System; +using UIKit; +using SoupKit.UI; + +namespace SoupChef { + public partial class SoupOrderDetailCell : UITableViewCell { + public const string CellIdentifier = "SoupOrderDetailCell"; + + public MenuItemView DetailView => detailView; + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public SoupOrderDetailCell (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChef/UI/ConfigureMenuTableViewController.cs b/ios12/SoupChef/SoupChef/UI/ConfigureMenuTableViewController.cs index 40371f6d0..c6cc4fec9 100644 --- a/ios12/SoupChef/SoupChef/UI/ConfigureMenuTableViewController.cs +++ b/ios12/SoupChef/SoupChef/UI/ConfigureMenuTableViewController.cs @@ -13,126 +13,119 @@ donated actions associated with the menu item are deleted from the system. using SoupKit.Data; using System.Linq; -namespace SoupChef -{ - public partial class ConfigureMenuTableViewController : UITableViewController - { - enum SectionType - { - RegularItems, - SpecialItems - }; - - struct SectionModel - { - public SectionType SectionType { get; set; } - public string SectionHeaderText { get; set; } - public string SectionFooterText { get; set; } - public MenuItem[] RowContent { get; set; } - - public SectionModel(SectionType sectionType, string sectionHeaderText, string sectionFooterText, MenuItem[] rowContent) - { - SectionType = sectionType; - SectionHeaderText = sectionHeaderText; - SectionFooterText = sectionFooterText; - RowContent = rowContent; - } - } - - public SoupMenuManager SoupMenuManager { get; set; } - - SoupOrderDataManager _soupOrderDataManager; - public SoupOrderDataManager SoupOrderDataManager - { - get - { - return _soupOrderDataManager; - } - set - { - _soupOrderDataManager = value; - SoupMenuManager.OrderManager = _soupOrderDataManager; - } - } - - SectionModel[] SectionData; - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - ReloadData(); - } - - void ReloadData() - { - MenuItem[] SortedRegularMenuItems = - SoupMenuManager.AllRegularItems.OrderBy( - arg => arg.LocalizedString, StringComparer.CurrentCultureIgnoreCase - ).ToArray<MenuItem>(); - - SectionData = new SectionModel[] { - new SectionModel( - SectionType.RegularItems, - "Regular Menu Items", - "Uncheck a row to delete any donated shortcuts associated with the menu item.", - SortedRegularMenuItems - ), - new SectionModel( - SectionType.SpecialItems, - "Daily Special Menu Items", - "Check a row in this section to provide a relevant shortcut.", - SoupMenuManager.DailySpecialItems - ), - }; - TableView.ReloadData(); - } - - #region table view data source - public override nint NumberOfSections(UITableView tableView) - { - return SectionData.Length; - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return SectionData[section].RowContent.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = TableView.DequeueReusableCell("Basic Cell", indexPath); - var menuItem = SectionData[indexPath.Section].RowContent[indexPath.Row]; - cell.TextLabel.Text = menuItem.LocalizedString; - cell.Accessory = menuItem.IsAvailable ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; - return cell; - } - #endregion - - #region table delegate - public override string TitleForHeader(UITableView tableView, nint section) - { - return SectionData[section].SectionHeaderText; - } - - public override string TitleForFooter(UITableView tableView, nint section) - { - return SectionData[section].SectionFooterText; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var sectionModel = SectionData[indexPath.Section]; - var currentMenuItem = sectionModel.RowContent[indexPath.Row]; - var newMenuItem = currentMenuItem.Clone(); - newMenuItem.IsAvailable = !newMenuItem.IsAvailable; - - SoupMenuManager.ReplaceMenuItem(currentMenuItem, newMenuItem); - ReloadData(); - } - #endregion - - #region xamarin - public ConfigureMenuTableViewController(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +namespace SoupChef { + public partial class ConfigureMenuTableViewController : UITableViewController { + enum SectionType { + RegularItems, + SpecialItems + }; + + struct SectionModel { + public SectionType SectionType { get; set; } + public string SectionHeaderText { get; set; } + public string SectionFooterText { get; set; } + public MenuItem [] RowContent { get; set; } + + public SectionModel (SectionType sectionType, string sectionHeaderText, string sectionFooterText, MenuItem [] rowContent) + { + SectionType = sectionType; + SectionHeaderText = sectionHeaderText; + SectionFooterText = sectionFooterText; + RowContent = rowContent; + } + } + + public SoupMenuManager SoupMenuManager { get; set; } + + SoupOrderDataManager _soupOrderDataManager; + public SoupOrderDataManager SoupOrderDataManager { + get { + return _soupOrderDataManager; + } + set { + _soupOrderDataManager = value; + SoupMenuManager.OrderManager = _soupOrderDataManager; + } + } + + SectionModel [] SectionData; + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + ReloadData (); + } + + void ReloadData () + { + MenuItem [] SortedRegularMenuItems = + SoupMenuManager.AllRegularItems.OrderBy ( + arg => arg.LocalizedString, StringComparer.CurrentCultureIgnoreCase + ).ToArray<MenuItem> (); + + SectionData = new SectionModel [] { + new SectionModel( + SectionType.RegularItems, + "Regular Menu Items", + "Uncheck a row to delete any donated shortcuts associated with the menu item.", + SortedRegularMenuItems + ), + new SectionModel( + SectionType.SpecialItems, + "Daily Special Menu Items", + "Check a row in this section to provide a relevant shortcut.", + SoupMenuManager.DailySpecialItems + ), + }; + TableView.ReloadData (); + } + + #region table view data source + public override nint NumberOfSections (UITableView tableView) + { + return SectionData.Length; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return SectionData [section].RowContent.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = TableView.DequeueReusableCell ("Basic Cell", indexPath); + var menuItem = SectionData [indexPath.Section].RowContent [indexPath.Row]; + cell.TextLabel.Text = menuItem.LocalizedString; + cell.Accessory = menuItem.IsAvailable ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + return cell; + } + #endregion + + #region table delegate + public override string TitleForHeader (UITableView tableView, nint section) + { + return SectionData [section].SectionHeaderText; + } + + public override string TitleForFooter (UITableView tableView, nint section) + { + return SectionData [section].SectionFooterText; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var sectionModel = SectionData [indexPath.Section]; + var currentMenuItem = sectionModel.RowContent [indexPath.Row]; + var newMenuItem = currentMenuItem.Clone (); + newMenuItem.IsAvailable = !newMenuItem.IsAvailable; + + SoupMenuManager.ReplaceMenuItem (currentMenuItem, newMenuItem); + ReloadData (); + } + #endregion + + #region xamarin + public ConfigureMenuTableViewController (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChef/UI/OrderDetailTableConfiguration.cs b/ios12/SoupChef/SoupChef/UI/OrderDetailTableConfiguration.cs index dbf80e02a..10a06b80d 100644 --- a/ios12/SoupChef/SoupChef/UI/OrderDetailTableConfiguration.cs +++ b/ios12/SoupChef/SoupChef/UI/OrderDetailTableConfiguration.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -7,78 +7,69 @@ This struct encapsulates the configuration of the `UITableView` in `OrderDetailV using SoupKit.Data; -namespace SoupChef -{ - public struct OrderDetailTableConfiguration - { - public enum OrderTypeEnum - { - New, - Historical - } +namespace SoupChef { + public struct OrderDetailTableConfiguration { + public enum OrderTypeEnum { + New, + Historical + } - public static class SectionType - { - public const string Price = "Price"; - public const string Quantity = "Quantity"; - public const string Options = "Options"; - public const string Total = "Total"; - public const string VoiceShortcut = "Shortcut Phrase"; - } + public static class SectionType { + public const string Price = "Price"; + public const string Quantity = "Quantity"; + public const string Options = "Options"; + public const string Total = "Total"; + public const string VoiceShortcut = "Shortcut Phrase"; + } - public static class BasicCellType - { - public const string Basic = "Basic Cell"; - public const string VoiceShortcut = "Voice Shortcut"; - } + public static class BasicCellType { + public const string Basic = "Basic Cell"; + public const string VoiceShortcut = "Voice Shortcut"; + } - public OrderTypeEnum OrderType { get; private set; } + public OrderTypeEnum OrderType { get; private set; } - public OrderDetailTableConfiguration(OrderTypeEnum orderType) - { - OrderType = orderType; - } + public OrderDetailTableConfiguration (OrderTypeEnum orderType) + { + OrderType = orderType; + } - public struct SectionModel - { - public string Type { get; private set; } - public int RowCount { get; private set; } - public string CellReuseIdentifier { get; private set; } + public struct SectionModel { + public string Type { get; private set; } + public int RowCount { get; private set; } + public string CellReuseIdentifier { get; private set; } - public SectionModel(string type, int rowCount, string cellReuseIdentifier) - { - this.Type = type; - this.RowCount = rowCount; - this.CellReuseIdentifier = cellReuseIdentifier; - } - } + public SectionModel (string type, int rowCount, string cellReuseIdentifier) + { + this.Type = type; + this.RowCount = rowCount; + this.CellReuseIdentifier = cellReuseIdentifier; + } + } - static SectionModel[] NewOrderSectionModel = { - new SectionModel(SectionType.Price, 1, BasicCellType.Basic), - new SectionModel(SectionType.Quantity, 1, QuantityCell.CellIdentifier), - new SectionModel(SectionType.Options, MenuItemOption.All.Length, BasicCellType.Basic), - new SectionModel(SectionType.Total, 1, BasicCellType.Basic), - }; + static SectionModel [] NewOrderSectionModel = { + new SectionModel(SectionType.Price, 1, BasicCellType.Basic), + new SectionModel(SectionType.Quantity, 1, QuantityCell.CellIdentifier), + new SectionModel(SectionType.Options, MenuItemOption.All.Length, BasicCellType.Basic), + new SectionModel(SectionType.Total, 1, BasicCellType.Basic), + }; - static SectionModel[] HistoricalOrderSectionModel = { - new SectionModel(SectionType.Quantity, 1, QuantityCell.CellIdentifier), - new SectionModel(SectionType.Options, MenuItemOption.All.Length, BasicCellType.Basic), - new SectionModel(SectionType.Total, 1, BasicCellType.Basic), - new SectionModel(SectionType.VoiceShortcut, 1, BasicCellType.VoiceShortcut), - }; + static SectionModel [] HistoricalOrderSectionModel = { + new SectionModel(SectionType.Quantity, 1, QuantityCell.CellIdentifier), + new SectionModel(SectionType.Options, MenuItemOption.All.Length, BasicCellType.Basic), + new SectionModel(SectionType.Total, 1, BasicCellType.Basic), + new SectionModel(SectionType.VoiceShortcut, 1, BasicCellType.VoiceShortcut), + }; - public SectionModel[] Sections - { - get - { - switch (OrderType) - { - case OrderTypeEnum.New: - return NewOrderSectionModel; - default: - return HistoricalOrderSectionModel; - } - } - } - } + public SectionModel [] Sections { + get { + switch (OrderType) { + case OrderTypeEnum.New: + return NewOrderSectionModel; + default: + return HistoricalOrderSectionModel; + } + } + } + } } diff --git a/ios12/SoupChef/SoupChef/UI/OrderDetailViewController.cs b/ios12/SoupChef/SoupChef/UI/OrderDetailViewController.cs index c3cd97547..8d46e72dc 100644 --- a/ios12/SoupChef/SoupChef/UI/OrderDetailViewController.cs +++ b/ios12/SoupChef/SoupChef/UI/OrderDetailViewController.cs @@ -1,303 +1,269 @@ -/* -See LICENSE folder for this sample’s licensing information. - -Abstract: -This class shows soup order details. It can be configured for two possible order types. - When configured with a 'new' order type, the view controller collects details of a new order. - When configured with a 'historical' order type, the view controller displays details of a previously placed order. -*/ - -using Foundation; -using System; -using UIKit; -using SoupKit.Data; -using System.Collections.Generic; -using SoupKit.Support; -using CoreFoundation; +/* +See LICENSE folder for this sample’s licensing information. + +Abstract: +This class shows soup order details. It can be configured for two possible order types. + When configured with a 'new' order type, the view controller collects details of a new order. + When configured with a 'historical' order type, the view controller displays details of a previously placed order. +*/ + +using Foundation; +using System; +using UIKit; +using SoupKit.Data; +using System.Collections.Generic; +using SoupKit.Support; +using CoreFoundation; using System.Threading; -using IntentsUI; -using Intents; - -namespace SoupChef -{ - public partial class OrderDetailViewController : UITableViewController, IINUIAddVoiceShortcutViewControllerDelegate, IINUIEditVoiceShortcutViewControllerDelegate - { - public Order Order { get; private set; } - - OrderDetailTableConfiguration TableConfiguration = new OrderDetailTableConfiguration(OrderDetailTableConfiguration.OrderTypeEnum.New); - - UILabel QuantityLabel; - - UILabel TotalLabel; - - Dictionary<string, string> OptionMap = new Dictionary<string, string>(); - - VoiceShortcutDataManager VoiceShortcutDataManager; - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - if (TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.Historical) - { - NavigationItem.RightBarButtonItem = null; - } - ConfigureTableViewHeader(); - } - - void ConfigureTableViewHeader() - { - SoupDetailView.ImageView.Image = UIImage.FromBundle(Order.MenuItem.IconImageName); - SoupDetailView.TitleLabel.Text = Order.MenuItem.LocalizedString; - TableView.TableHeaderView = TableViewHeader; - } - - public void Configure(OrderDetailTableConfiguration tableConfiguration, Order order, VoiceShortcutDataManager voiceShortcutDataManager) - { - TableConfiguration = tableConfiguration; - Order = order; - VoiceShortcutDataManager = voiceShortcutDataManager; - } - - partial void PlaceOrder(UIBarButtonItem sender) - { - if (Order.Quantity == 0) - { - Console.WriteLine("Quantity must be greater than 0 to add to order"); - return; - - } - PerformSegue("Place Order Segue", this); - } - - protected void StepperDidChange(object sender, EventArgs args) - { - var stepper = sender as UIStepper; - if (!(stepper is null)) - { - Order.Quantity = (int)(stepper.Value); - QuantityLabel.Text = $"{Order.Quantity}"; - UpdateTotalLabel(); - } - } - - void UpdateTotalLabel() - { - if (!(TotalLabel is null)) - { - TotalLabel.Text = NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber(Order.Total); - } - } - - void UpdateVoiceShortcuts() - { - var weakThis = new WeakReference<OrderDetailViewController>(this); - VoiceShortcutDataManager.UpdateVoiceShortcuts(() => - { - var indexPath = NSIndexPath.FromRowSection(0, 3); - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (weakThis.TryGetTarget(out var orderDetailViewController)) - { - orderDetailViewController.TableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); - } - }); - }); - DismissViewController(true, null); - } - - #region table view data source - public override nint NumberOfSections(UITableView tableView) - { - return TableConfiguration.Sections.Length; - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return TableConfiguration.Sections[section].RowCount; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var sectionModel = TableConfiguration.Sections[indexPath.Section]; - var reuseIdentifier = sectionModel.CellReuseIdentifier; - var cell = TableView.DequeueReusableCell(reuseIdentifier, indexPath); - Configure(cell, indexPath, sectionModel); - return cell; - } - - private void Configure(UITableViewCell cell, NSIndexPath indexPath, OrderDetailTableConfiguration.SectionModel sectionModel) - { - switch (sectionModel.Type) - { - case OrderDetailTableConfiguration.SectionType.Price: - if (!(cell.TextLabel is null)) - { - cell.TextLabel.Text = NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber(Order.MenuItem.Price); - } - break; - case OrderDetailTableConfiguration.SectionType.Quantity: - var quantityCell = cell as QuantityCell; - if (!(quantityCell is null)) - { - if (TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.New) - { - QuantityLabel = quantityCell.GetQuantityLabel(); - UIStepper stepper = quantityCell.GetStepper(); - if (!(stepper is null)) - { - stepper.AddTarget(StepperDidChange, UIControlEvent.ValueChanged); - } - } - else - { - quantityCell.GetQuantityLabel().Text = $"{Order.Quantity}"; - quantityCell.GetStepper().Hidden = true; - } - } - break; - case OrderDetailTableConfiguration.SectionType.Options: - // Maintains a mapping of values to localized values in - // order to help instantiate Order.MenuItemOption later - // when an option is selected in the table view - var option = new MenuItemOption(MenuItemOption.All[indexPath.Row]); - var localizedValue = - Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase( - option.LocalizedString - ); - OptionMap[localizedValue] = option.Value; - - if (!(cell.TextLabel is null)) - { - cell.TextLabel.Text = localizedValue; - } - - if (TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.Historical) - { - cell.Accessory = Order.MenuItemOptions.Contains(option) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; - } - break; - case OrderDetailTableConfiguration.SectionType.Total: - TotalLabel = cell.TextLabel; - - UpdateTotalLabel(); - break; - case OrderDetailTableConfiguration.SectionType.VoiceShortcut: - if (!(cell.TextLabel is null)) - { - cell.TextLabel.TextColor = TableView.TintColor; - var shortcut = VoiceShortcutDataManager.VoiceShortcutForOrder(Order); - if (!(shortcut is null)) - { - cell.TextLabel.Text = $"“{shortcut.InvocationPhrase}”"; - } - else - { - cell.TextLabel.Text = "Add to Siri"; - } - } - break; - default: - return; - } - } - #endregion - - #region table view delegate - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - if (TableConfiguration.Sections[indexPath.Section].Type == OrderDetailTableConfiguration.SectionType.Options && TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.New) - { - var cell = TableView.CellAt(indexPath); - if (cell is null) { return; } - - var cellText = cell.TextLabel?.Text; - if (cellText is null) { return; } - - var optionRawValue = OptionMap[cellText]; - if (optionRawValue is null) { return; } - - var option = new MenuItemOption(optionRawValue); - if (option is null) { return; } - - if (Order.MenuItemOptions.Contains(option)) - { - Order.MenuItemOptions.Remove(option); - cell.Accessory = UITableViewCellAccessory.None; - } - else - { - Order.MenuItemOptions.Add(option); - cell.Accessory = UITableViewCellAccessory.Checkmark; - } - } - else if (TableConfiguration.Sections[indexPath.Section].Type == OrderDetailTableConfiguration.SectionType.VoiceShortcut) - { - INVoiceShortcut existingShortcut = VoiceShortcutDataManager?.VoiceShortcutForOrder(Order); - if (!(existingShortcut is null)) - { - var editVoiceShortcutViewController = new INUIEditVoiceShortcutViewController(existingShortcut); - editVoiceShortcutViewController.Delegate = this; - PresentViewController(editVoiceShortcutViewController, true, null); - } - else - { - // Since the app isn't yet managing a voice shortcut for - // this order, present the add view controller - INShortcut newShortcut = new INShortcut(Order.Intent); - if (!(newShortcut is null)) - { - var addVoiceShortcutVC = new INUIAddVoiceShortcutViewController(newShortcut); - addVoiceShortcutVC.Delegate = this; - PresentViewController(addVoiceShortcutVC, true, null); - } - } - } - } - #endregion - - #region INUIAddVoiceShortcutViewControllerDelegate - public void DidFinish(INUIAddVoiceShortcutViewController controller, INVoiceShortcut voiceShortcut, NSError error) - { - if (!(error is null)) - { - Console.WriteLine($"error adding voice shortcut", error); - return; - } - UpdateVoiceShortcuts(); - } - - public void DidCancel(INUIAddVoiceShortcutViewController controller) - { - DismissViewController(true, null); - } - #endregion - - #region INUIEditVoiceShortcutViewControllerDelegate - public void DidUpdate(INUIEditVoiceShortcutViewController controller, INVoiceShortcut voiceShortcut, NSError error) - { - if (!(error is null)) - { - Console.WriteLine($"error updating voice shortcut", error); - return; - } - UpdateVoiceShortcuts(); - } - - public void DidDelete(INUIEditVoiceShortcutViewController controller, NSUuid deletedVoiceShortcutIdentifier) - { - UpdateVoiceShortcuts(); - } - - public void DidCancel(INUIEditVoiceShortcutViewController controller) - { - DismissViewController(true, null); - } - #endregion - - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public OrderDetailViewController(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +using IntentsUI; +using Intents; + +namespace SoupChef { + public partial class OrderDetailViewController : UITableViewController, IINUIAddVoiceShortcutViewControllerDelegate, IINUIEditVoiceShortcutViewControllerDelegate { + public Order Order { get; private set; } + + OrderDetailTableConfiguration TableConfiguration = new OrderDetailTableConfiguration (OrderDetailTableConfiguration.OrderTypeEnum.New); + + UILabel QuantityLabel; + + UILabel TotalLabel; + + Dictionary<string, string> OptionMap = new Dictionary<string, string> (); + + VoiceShortcutDataManager VoiceShortcutDataManager; + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + if (TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.Historical) { + NavigationItem.RightBarButtonItem = null; + } + ConfigureTableViewHeader (); + } + + void ConfigureTableViewHeader () + { + SoupDetailView.ImageView.Image = UIImage.FromBundle (Order.MenuItem.IconImageName); + SoupDetailView.TitleLabel.Text = Order.MenuItem.LocalizedString; + TableView.TableHeaderView = TableViewHeader; + } + + public void Configure (OrderDetailTableConfiguration tableConfiguration, Order order, VoiceShortcutDataManager voiceShortcutDataManager) + { + TableConfiguration = tableConfiguration; + Order = order; + VoiceShortcutDataManager = voiceShortcutDataManager; + } + + partial void PlaceOrder (UIBarButtonItem sender) + { + if (Order.Quantity == 0) { + Console.WriteLine ("Quantity must be greater than 0 to add to order"); + return; + + } + PerformSegue ("Place Order Segue", this); + } + + protected void StepperDidChange (object sender, EventArgs args) + { + var stepper = sender as UIStepper; + if (!(stepper is null)) { + Order.Quantity = (int) (stepper.Value); + QuantityLabel.Text = $"{Order.Quantity}"; + UpdateTotalLabel (); + } + } + + void UpdateTotalLabel () + { + if (!(TotalLabel is null)) { + TotalLabel.Text = NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber (Order.Total); + } + } + + void UpdateVoiceShortcuts () + { + var weakThis = new WeakReference<OrderDetailViewController> (this); + VoiceShortcutDataManager.UpdateVoiceShortcuts (() => { + var indexPath = NSIndexPath.FromRowSection (0, 3); + DispatchQueue.MainQueue.DispatchAsync (() => { + if (weakThis.TryGetTarget (out var orderDetailViewController)) { + orderDetailViewController.TableView.ReloadRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); + } + }); + }); + DismissViewController (true, null); + } + + #region table view data source + public override nint NumberOfSections (UITableView tableView) + { + return TableConfiguration.Sections.Length; + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return TableConfiguration.Sections [section].RowCount; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var sectionModel = TableConfiguration.Sections [indexPath.Section]; + var reuseIdentifier = sectionModel.CellReuseIdentifier; + var cell = TableView.DequeueReusableCell (reuseIdentifier, indexPath); + Configure (cell, indexPath, sectionModel); + return cell; + } + + private void Configure (UITableViewCell cell, NSIndexPath indexPath, OrderDetailTableConfiguration.SectionModel sectionModel) + { + switch (sectionModel.Type) { + case OrderDetailTableConfiguration.SectionType.Price: + if (!(cell.TextLabel is null)) { + cell.TextLabel.Text = NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber (Order.MenuItem.Price); + } + break; + case OrderDetailTableConfiguration.SectionType.Quantity: + var quantityCell = cell as QuantityCell; + if (!(quantityCell is null)) { + if (TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.New) { + QuantityLabel = quantityCell.GetQuantityLabel (); + UIStepper stepper = quantityCell.GetStepper (); + if (!(stepper is null)) { + stepper.AddTarget (StepperDidChange, UIControlEvent.ValueChanged); + } + } else { + quantityCell.GetQuantityLabel ().Text = $"{Order.Quantity}"; + quantityCell.GetStepper ().Hidden = true; + } + } + break; + case OrderDetailTableConfiguration.SectionType.Options: + // Maintains a mapping of values to localized values in + // order to help instantiate Order.MenuItemOption later + // when an option is selected in the table view + var option = new MenuItemOption (MenuItemOption.All [indexPath.Row]); + var localizedValue = + Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase ( + option.LocalizedString + ); + OptionMap [localizedValue] = option.Value; + + if (!(cell.TextLabel is null)) { + cell.TextLabel.Text = localizedValue; + } + + if (TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.Historical) { + cell.Accessory = Order.MenuItemOptions.Contains (option) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + } + break; + case OrderDetailTableConfiguration.SectionType.Total: + TotalLabel = cell.TextLabel; + + UpdateTotalLabel (); + break; + case OrderDetailTableConfiguration.SectionType.VoiceShortcut: + if (!(cell.TextLabel is null)) { + cell.TextLabel.TextColor = TableView.TintColor; + var shortcut = VoiceShortcutDataManager.VoiceShortcutForOrder (Order); + if (!(shortcut is null)) { + cell.TextLabel.Text = $"“{shortcut.InvocationPhrase}”"; + } else { + cell.TextLabel.Text = "Add to Siri"; + } + } + break; + default: + return; + } + } + #endregion + + #region table view delegate + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + if (TableConfiguration.Sections [indexPath.Section].Type == OrderDetailTableConfiguration.SectionType.Options && TableConfiguration.OrderType == OrderDetailTableConfiguration.OrderTypeEnum.New) { + var cell = TableView.CellAt (indexPath); + if (cell is null) { return; } + + var cellText = cell.TextLabel?.Text; + if (cellText is null) { return; } + + var optionRawValue = OptionMap [cellText]; + if (optionRawValue is null) { return; } + + var option = new MenuItemOption (optionRawValue); + if (option is null) { return; } + + if (Order.MenuItemOptions.Contains (option)) { + Order.MenuItemOptions.Remove (option); + cell.Accessory = UITableViewCellAccessory.None; + } else { + Order.MenuItemOptions.Add (option); + cell.Accessory = UITableViewCellAccessory.Checkmark; + } + } else if (TableConfiguration.Sections [indexPath.Section].Type == OrderDetailTableConfiguration.SectionType.VoiceShortcut) { + INVoiceShortcut existingShortcut = VoiceShortcutDataManager?.VoiceShortcutForOrder (Order); + if (!(existingShortcut is null)) { + var editVoiceShortcutViewController = new INUIEditVoiceShortcutViewController (existingShortcut); + editVoiceShortcutViewController.Delegate = this; + PresentViewController (editVoiceShortcutViewController, true, null); + } else { + // Since the app isn't yet managing a voice shortcut for + // this order, present the add view controller + INShortcut newShortcut = new INShortcut (Order.Intent); + if (!(newShortcut is null)) { + var addVoiceShortcutVC = new INUIAddVoiceShortcutViewController (newShortcut); + addVoiceShortcutVC.Delegate = this; + PresentViewController (addVoiceShortcutVC, true, null); + } + } + } + } + #endregion + + #region INUIAddVoiceShortcutViewControllerDelegate + public void DidFinish (INUIAddVoiceShortcutViewController controller, INVoiceShortcut voiceShortcut, NSError error) + { + if (!(error is null)) { + Console.WriteLine ($"error adding voice shortcut", error); + return; + } + UpdateVoiceShortcuts (); + } + + public void DidCancel (INUIAddVoiceShortcutViewController controller) + { + DismissViewController (true, null); + } + #endregion + + #region INUIEditVoiceShortcutViewControllerDelegate + public void DidUpdate (INUIEditVoiceShortcutViewController controller, INVoiceShortcut voiceShortcut, NSError error) + { + if (!(error is null)) { + Console.WriteLine ($"error updating voice shortcut", error); + return; + } + UpdateVoiceShortcuts (); + } + + public void DidDelete (INUIEditVoiceShortcutViewController controller, NSUuid deletedVoiceShortcutIdentifier) + { + UpdateVoiceShortcuts (); + } + + public void DidCancel (INUIEditVoiceShortcutViewController controller) + { + DismissViewController (true, null); + } + #endregion + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public OrderDetailViewController (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChef/UI/OrderHistoryTableViewController.cs b/ios12/SoupChef/SoupChef/UI/OrderHistoryTableViewController.cs index 68112fa61..2efef3e36 100644 --- a/ios12/SoupChef/SoupChef/UI/OrderHistoryTableViewController.cs +++ b/ios12/SoupChef/SoupChef/UI/OrderHistoryTableViewController.cs @@ -1,144 +1,131 @@ -/* -See LICENSE folder for this sample’s licensing information. - -Abstract: -This class displays a list of previously placed orders. -*/ - -using Foundation; -using System; -using UIKit; -using SoupKit.Data; -using System.Linq; -using SoupKit.UI; - -namespace SoupChef -{ - public partial class OrderHistoryTableViewController : UITableViewController - { - public static class SegueIdentifiers - { - public const string OrderDetails = "Order Details"; - public const string SoupMenu = "Soup Menu"; - public const string ConfigureMenu = "Configure Menu"; - } - - SoupMenuManager SoupMenuManager = new SoupMenuManager(); - SoupOrderDataManager SoupOrderDataManager = new SoupOrderDataManager(); - VoiceShortcutDataManager VoiceShortcutManager = new VoiceShortcutDataManager(); - NSObject NotificationToken; - - Lazy<NSDateFormatter> DateFormatter => new Lazy<NSDateFormatter>(() => - { - var formatter = new NSDateFormatter() - { - DateStyle = NSDateFormatterStyle.Long, - TimeStyle = NSDateFormatterStyle.Long - }; - return formatter; - }); - - - #region View Controller Life Cycle - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - var weakThis = new WeakReference<OrderHistoryTableViewController>(this); - NotificationToken = NSNotificationCenter.DefaultCenter.AddObserver( - NotificationKeys.DataChanged, - SoupOrderDataManager, - NSOperationQueue.MainQueue, - (notification) => - { - if (weakThis.TryGetTarget(out var orderHistoryViewController)) - { - orderHistoryViewController.TableView.ReloadData(); - } - } - ); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - if (!(NavigationController is null)) - { - NavigationController.ToolbarHidden = true; - } - } - #endregion - - #region Target Action - [Action("unwindToOrderHistoryWithSegue:")] - public void UnwindToOrderHistory(UIStoryboardSegue segue) { } - - [Action("placeNewOrderWithSegue:")] - public void PlaceNewOrder(UIStoryboardSegue segue) - { - var source = segue.SourceViewController as OrderDetailViewController; - if (!(source is null)) - { - SoupOrderDataManager.PlaceOrder(source.Order); - } - } - #endregion - - #region Navigation - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - base.PrepareForSegue(segue, sender); - if (segue.Identifier == SegueIdentifiers.OrderDetails) - { - NSIndexPath selectedIndexPath = TableView.IndexPathsForSelectedRows?.FirstOrDefault(); - if (selectedIndexPath is null) { return; } - - var destination = segue.DestinationViewController as OrderDetailViewController; - if (destination is null) { return; } - - destination.Configure( - new OrderDetailTableConfiguration(OrderDetailTableConfiguration.OrderTypeEnum.Historical), - SoupOrderDataManager.OrderHistory[(nuint)selectedIndexPath.Row], - VoiceShortcutManager - ); - } - else if (segue.Identifier == SegueIdentifiers.ConfigureMenu) - { - var navCon = segue.DestinationViewController as UINavigationController; - var configureMenuTableViewController = navCon?.ViewControllers?.FirstOrDefault() as ConfigureMenuTableViewController; - if (configureMenuTableViewController is null) { return; } - - configureMenuTableViewController.SoupMenuManager = SoupMenuManager; - configureMenuTableViewController.SoupOrderDataManager = SoupOrderDataManager; - } - } - #endregion - - #region UITableViewDataSource - public override nint RowsInSection(UITableView tableView, nint section) - { - return (nint)SoupOrderDataManager.OrderHistory.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = TableView.DequeueReusableCell(SoupOrderDetailCell.CellIdentifier, indexPath) as SoupOrderDetailCell; - if (cell is null ) - { - return new UITableViewCell(); - } - Order order = SoupOrderDataManager.OrderHistory[(nuint)indexPath.Row]; - cell.DetailView.ImageView.Image = UIImage.FromBundle(order.MenuItem.IconImageName); - cell.DetailView.TitleLabel.Text = $"{order.Quantity} {order.MenuItem.LocalizedString}"; - cell.DetailView.SubTitleLabel.Text = DateFormatter.Value.StringFor(order.Date); - return cell; - } - #endregion - - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public OrderHistoryTableViewController(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +/* +See LICENSE folder for this sample’s licensing information. + +Abstract: +This class displays a list of previously placed orders. +*/ + +using Foundation; +using System; +using UIKit; +using SoupKit.Data; +using System.Linq; +using SoupKit.UI; + +namespace SoupChef { + public partial class OrderHistoryTableViewController : UITableViewController { + public static class SegueIdentifiers { + public const string OrderDetails = "Order Details"; + public const string SoupMenu = "Soup Menu"; + public const string ConfigureMenu = "Configure Menu"; + } + + SoupMenuManager SoupMenuManager = new SoupMenuManager (); + SoupOrderDataManager SoupOrderDataManager = new SoupOrderDataManager (); + VoiceShortcutDataManager VoiceShortcutManager = new VoiceShortcutDataManager (); + NSObject NotificationToken; + + Lazy<NSDateFormatter> DateFormatter => new Lazy<NSDateFormatter> (() => { + var formatter = new NSDateFormatter () { + DateStyle = NSDateFormatterStyle.Long, + TimeStyle = NSDateFormatterStyle.Long + }; + return formatter; + }); + + + #region View Controller Life Cycle + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var weakThis = new WeakReference<OrderHistoryTableViewController> (this); + NotificationToken = NSNotificationCenter.DefaultCenter.AddObserver ( + NotificationKeys.DataChanged, + SoupOrderDataManager, + NSOperationQueue.MainQueue, + (notification) => { + if (weakThis.TryGetTarget (out var orderHistoryViewController)) { + orderHistoryViewController.TableView.ReloadData (); + } + } + ); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + if (!(NavigationController is null)) { + NavigationController.ToolbarHidden = true; + } + } + #endregion + + #region Target Action + [Action ("unwindToOrderHistoryWithSegue:")] + public void UnwindToOrderHistory (UIStoryboardSegue segue) { } + + [Action ("placeNewOrderWithSegue:")] + public void PlaceNewOrder (UIStoryboardSegue segue) + { + var source = segue.SourceViewController as OrderDetailViewController; + if (!(source is null)) { + SoupOrderDataManager.PlaceOrder (source.Order); + } + } + #endregion + + #region Navigation + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + base.PrepareForSegue (segue, sender); + if (segue.Identifier == SegueIdentifiers.OrderDetails) { + NSIndexPath selectedIndexPath = TableView.IndexPathsForSelectedRows?.FirstOrDefault (); + if (selectedIndexPath is null) { return; } + + var destination = segue.DestinationViewController as OrderDetailViewController; + if (destination is null) { return; } + + destination.Configure ( + new OrderDetailTableConfiguration (OrderDetailTableConfiguration.OrderTypeEnum.Historical), + SoupOrderDataManager.OrderHistory [(nuint) selectedIndexPath.Row], + VoiceShortcutManager + ); + } else if (segue.Identifier == SegueIdentifiers.ConfigureMenu) { + var navCon = segue.DestinationViewController as UINavigationController; + var configureMenuTableViewController = navCon?.ViewControllers?.FirstOrDefault () as ConfigureMenuTableViewController; + if (configureMenuTableViewController is null) { return; } + + configureMenuTableViewController.SoupMenuManager = SoupMenuManager; + configureMenuTableViewController.SoupOrderDataManager = SoupOrderDataManager; + } + } + #endregion + + #region UITableViewDataSource + public override nint RowsInSection (UITableView tableView, nint section) + { + return (nint) SoupOrderDataManager.OrderHistory.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = TableView.DequeueReusableCell (SoupOrderDetailCell.CellIdentifier, indexPath) as SoupOrderDetailCell; + if (cell is null) { + return new UITableViewCell (); + } + Order order = SoupOrderDataManager.OrderHistory [(nuint) indexPath.Row]; + cell.DetailView.ImageView.Image = UIImage.FromBundle (order.MenuItem.IconImageName); + cell.DetailView.TitleLabel.Text = $"{order.Quantity} {order.MenuItem.LocalizedString}"; + cell.DetailView.SubTitleLabel.Text = DateFormatter.Value.StringFor (order.Date); + return cell; + } + #endregion + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public OrderHistoryTableViewController (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChef/UI/SoupMenuViewController.cs b/ios12/SoupChef/SoupChef/UI/SoupMenuViewController.cs index 7a7060b5c..a71fe4a75 100644 --- a/ios12/SoupChef/SoupChef/UI/SoupMenuViewController.cs +++ b/ios12/SoupChef/SoupChef/UI/SoupMenuViewController.cs @@ -1,94 +1,90 @@ -using Foundation; +using Foundation; using SoupKit.Data; -using System; -using UIKit; -using SoupKit.Support; -using System.Linq; -using SoupKit.UI; - -namespace SoupChef -{ - public partial class SoupMenuViewController : UITableViewController - { - - public MenuItem[] MenuItems { get; set; } = new SoupMenuManager().AvailableRegularItems; - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - UserActivity = NSUserActivityHelper.ViewMenuActivity; - } - - public override void UpdateUserActivityState(NSUserActivity activity) - { - base.UpdateUserActivityState(activity); - - var keys = new NSString[] { - (NSString)(NSUserActivityHelper.ActivityKeys.MenuItems), - (NSString)(NSUserActivityHelper.ActivityKeys.SegueId) - }; - - // Creates an NSArray<NSString> of MenuItem.ItemNameKey values - var menuItemNames = NSArray.FromNSObjects( - MenuItems.Select<MenuItem, NSString>( - (menuItem) => (NSString)(menuItem.ItemNameKey) - ).ToArray<NSString>() - ); - - var objects = new NSObject[] { menuItemNames, (NSString)"Soup Menu" }; - - NSDictionary userInfo = NSDictionary.FromObjectsAndKeys(objects, keys); - - activity.AddUserInfoEntries(userInfo); - - } - - #region Navigation - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "Show New Order Detail Segue") - { - var destination = segue.DestinationViewController as OrderDetailViewController; - if (destination is null) { return; } - - var indexPath = TableView.IndexPathForSelectedRow; - if (indexPath is null) { return; } - - var orderType = new OrderDetailTableConfiguration(OrderDetailTableConfiguration.OrderTypeEnum.New); - var newOrder = new Order(0, MenuItems[indexPath.Row], new NSMutableSet<MenuItemOption>()); - - destination.Configure(orderType, newOrder, null); - } - } - #endregion - - #region UITableViewDataSource - public override nint RowsInSection(UITableView tableView, nint section) - { - return MenuItems.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = TableView.DequeueReusableCell(SoupMenuItemDetailCell.CellIdentifier, indexPath) as SoupMenuItemDetailCell; - if (cell is null) - { - Console.WriteLine("Failed to downcase UITableViewCell as SoupMenuItemDetailCell. Check Main.storyboard."); - return new UITableViewCell(); - } - - var menuItem = MenuItems[indexPath.Row]; - cell.DetailView.ImageView.Image = UIImage.FromBundle(menuItem.IconImageName); - cell.DetailView.TitleLabel.Text = menuItem.LocalizedString; - return cell; - - } - #endregion - - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public SoupMenuViewController(IntPtr handle) : base(handle) { } - #endregion - } -} \ No newline at end of file +using System; +using UIKit; +using SoupKit.Support; +using System.Linq; +using SoupKit.UI; + +namespace SoupChef { + public partial class SoupMenuViewController : UITableViewController { + + public MenuItem [] MenuItems { get; set; } = new SoupMenuManager ().AvailableRegularItems; + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + UserActivity = NSUserActivityHelper.ViewMenuActivity; + } + + public override void UpdateUserActivityState (NSUserActivity activity) + { + base.UpdateUserActivityState (activity); + + var keys = new NSString [] { + (NSString)(NSUserActivityHelper.ActivityKeys.MenuItems), + (NSString)(NSUserActivityHelper.ActivityKeys.SegueId) + }; + + // Creates an NSArray<NSString> of MenuItem.ItemNameKey values + var menuItemNames = NSArray.FromNSObjects ( + MenuItems.Select<MenuItem, NSString> ( + (menuItem) => (NSString) (menuItem.ItemNameKey) + ).ToArray<NSString> () + ); + + var objects = new NSObject [] { menuItemNames, (NSString) "Soup Menu" }; + + NSDictionary userInfo = NSDictionary.FromObjectsAndKeys (objects, keys); + + activity.AddUserInfoEntries (userInfo); + + } + + #region Navigation + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "Show New Order Detail Segue") { + var destination = segue.DestinationViewController as OrderDetailViewController; + if (destination is null) { return; } + + var indexPath = TableView.IndexPathForSelectedRow; + if (indexPath is null) { return; } + + var orderType = new OrderDetailTableConfiguration (OrderDetailTableConfiguration.OrderTypeEnum.New); + var newOrder = new Order (0, MenuItems [indexPath.Row], new NSMutableSet<MenuItemOption> ()); + + destination.Configure (orderType, newOrder, null); + } + } + #endregion + + #region UITableViewDataSource + public override nint RowsInSection (UITableView tableView, nint section) + { + return MenuItems.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = TableView.DequeueReusableCell (SoupMenuItemDetailCell.CellIdentifier, indexPath) as SoupMenuItemDetailCell; + if (cell is null) { + Console.WriteLine ("Failed to downcase UITableViewCell as SoupMenuItemDetailCell. Check Main.storyboard."); + return new UITableViewCell (); + } + + var menuItem = MenuItems [indexPath.Row]; + cell.DetailView.ImageView.Image = UIImage.FromBundle (menuItem.IconImageName); + cell.DetailView.TitleLabel.Text = menuItem.LocalizedString; + return cell; + + } + #endregion + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public SoupMenuViewController (IntPtr handle) : base (handle) { } + #endregion + } +} diff --git a/ios12/SoupChef/SoupChefIntents/IntentHandler.cs b/ios12/SoupChef/SoupChefIntents/IntentHandler.cs index 4e498ae99..5ab1dd525 100644 --- a/ios12/SoupChef/SoupChefIntents/IntentHandler.cs +++ b/ios12/SoupChef/SoupChefIntents/IntentHandler.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; @@ -6,20 +6,17 @@ using SoupChef; using SoupKit; -namespace SoupChefIntents -{ - [Register("IntentHandler")] - public class IntentHandler : INExtension - { - public override NSObject GetHandler(INIntent intent) - { - if (intent is OrderSoupIntent) - { - return new OrderSoupIntentHandler(); - } - throw new Exception("Unhandled intent type: ${intent}"); - } +namespace SoupChefIntents { + [Register ("IntentHandler")] + public class IntentHandler : INExtension { + public override NSObject GetHandler (INIntent intent) + { + if (intent is OrderSoupIntent) { + return new OrderSoupIntentHandler (); + } + throw new Exception ("Unhandled intent type: ${intent}"); + } - protected IntentHandler(IntPtr handle) : base(handle) { } - } + protected IntentHandler (IntPtr handle) : base (handle) { } + } } diff --git a/ios12/SoupChef/SoupChefIntentsUI/ConfirmOrderView.cs b/ios12/SoupChef/SoupChefIntentsUI/ConfirmOrderView.cs index ff5e05971..3019fd0f4 100644 --- a/ios12/SoupChef/SoupChefIntentsUI/ConfirmOrderView.cs +++ b/ios12/SoupChef/SoupChefIntentsUI/ConfirmOrderView.cs @@ -1,18 +1,16 @@ -using Foundation; -using System; -using UIKit; - -namespace SoupChefIntentsUI -{ - public partial class ConfirmOrderView : UIView - { - public UIImageView ImageView => imageView; - public UILabel ItemNameLabel => itemNameLabel; - public UILabel TimeLabel => timeLabel; - public UILabel TotalPriceLabel => totalPriceLabel; - - public ConfirmOrderView (IntPtr handle) : base (handle) - { - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace SoupChefIntentsUI { + public partial class ConfirmOrderView : UIView { + public UIImageView ImageView => imageView; + public UILabel ItemNameLabel => itemNameLabel; + public UILabel TimeLabel => timeLabel; + public UILabel TotalPriceLabel => totalPriceLabel; + + public ConfirmOrderView (IntPtr handle) : base (handle) + { + } + } +} diff --git a/ios12/SoupChef/SoupChefIntentsUI/IntentViewController.cs b/ios12/SoupChef/SoupChefIntentsUI/IntentViewController.cs index 3873846f3..c88254016 100644 --- a/ios12/SoupChef/SoupChefIntentsUI/IntentViewController.cs +++ b/ios12/SoupChef/SoupChefIntentsUI/IntentViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreGraphics; using Foundation; using Intents; @@ -8,140 +8,123 @@ using SoupChef; using CoreFoundation; -namespace SoupChefIntentsUI -{ - public partial class IntentViewController : UIViewController, IINUIHostedViewControlling - { - SoupMenuManager MenuManager { get; } = new SoupMenuManager(); - - [Export("configureViewForParameters:ofInteraction:interactiveBehavior:context:completion:")] - public void ConfigureView( - NSSet<INParameter> parameters, - INInteraction interaction, - INUIInteractiveBehavior interactiveBehavior, - INUIHostedViewContext context, - INUIHostedViewControllingConfigureViewHandler completion) - { - - var intent = interaction.Intent as OrderSoupIntent; - if (intent is null) - { - completion(false, new NSSet<INParameter>(), CGSize.Empty); - } - - var order = Order.FromOrderSoupIntent(intent); - - foreach (var view in View.Subviews) - { - view.RemoveFromSuperview(); - } - - // Different UIs can be displayed depending if the intent is in the - // confirmation phase or the handle phase. - var desiredSize = CGSize.Empty; - - if (interaction.IntentHandlingStatus == INIntentHandlingStatus.Ready) - { - desiredSize = DisplayInvoice(order, intent); - } - else if( interaction.IntentHandlingStatus == INIntentHandlingStatus.Success) - { - var response = interaction.IntentResponse as OrderSoupIntentResponse; - if (!(response is null)) - { - desiredSize = DisplayOrderConfirmation(order, intent, response); - } - } - - completion(true, parameters, desiredSize); - } - - // This method will not be called if ConfigureView is implemented, - // according to: https://developer.apple.com/documentation/sirikit/inuihostedviewcontrolling/1649168-configurewithinteraction - [Export("configureWithInteraction:context:completion:")] - public void Configure(INInteraction interaction, INUIHostedViewContext context, Action<CGSize> completion) - { - throw new NotImplementedException(); - } - - CGSize DisplayInvoice(Order order, OrderSoupIntent intent) - { - invoiceView.ItemNameLabel.Text = order.MenuItem.LocalizedString; - invoiceView.TotalPriceLabel.Text = order.LocalizedCurrencyValue; - invoiceView.UnitPriceLabel.Text = $"{order.Quantity} @ {order.MenuItem.LocalizedCurrencyValue}"; - - var intentImage = intent.GetImage("soup"); - if (!(intentImage is null)) - { - var weakThis = new WeakReference<IntentViewController>(this); - intentImage.FetchImage((image) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (weakThis.TryGetTarget(out var intentViewController)) - { - intentViewController.invoiceView.ImageView.Image = image; - } - }); - }); - } - - var optionText = (!(intent.Options is null)) ? order.LocalizedOptionString : ""; - - invoiceView.OptionsLabel.Text = optionText; - - View.AddSubview(invoiceView); - - var width = this.ExtensionContext?.GetHostedViewMaximumAllowedSize().Width ?? 320; - var frame = new CGRect(0, 0, width, 170); - invoiceView.Frame = frame; - - return frame.Size; - } - - CGSize DisplayOrderConfirmation(Order order, OrderSoupIntent intent, OrderSoupIntentResponse response) - { - confirmationView.ItemNameLabel.Text = order.MenuItem.LocalizedString; - confirmationView.TotalPriceLabel.Text = order.LocalizedCurrencyValue; - confirmationView.ImageView.Layer.CornerRadius = 8; - var waitTime = response.WaitTime; - if (!(waitTime is null)) - { - confirmationView.TimeLabel.Text = $"{waitTime} Minutes"; - } - - var intentImage = intent.GetImage("soup"); - if (!(intentImage is null)) - { - var weakThis = new WeakReference<IntentViewController>(this); - intentImage.FetchImage((image) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (weakThis.TryGetTarget(out var intentViewController)) - { - // NOTE: In the original Swift-based sample, - // the original code sets this image on the - // invoice view, which seems incorrect. - intentViewController.confirmationView.ImageView.Image = image; - } - }); - }); - } - - View.AddSubview(confirmationView); - - var width = this.ExtensionContext?.GetHostedViewMaximumAllowedSize().Width ?? 320; - var frame = new CGRect(0, 0, width, 170); - confirmationView.Frame = frame; - - return frame.Size; - } - - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public IntentViewController(IntPtr handle) : base(handle) { } - #endregion - } +namespace SoupChefIntentsUI { + public partial class IntentViewController : UIViewController, IINUIHostedViewControlling { + SoupMenuManager MenuManager { get; } = new SoupMenuManager (); + + [Export ("configureViewForParameters:ofInteraction:interactiveBehavior:context:completion:")] + public void ConfigureView ( + NSSet<INParameter> parameters, + INInteraction interaction, + INUIInteractiveBehavior interactiveBehavior, + INUIHostedViewContext context, + INUIHostedViewControllingConfigureViewHandler completion) + { + + var intent = interaction.Intent as OrderSoupIntent; + if (intent is null) { + completion (false, new NSSet<INParameter> (), CGSize.Empty); + } + + var order = Order.FromOrderSoupIntent (intent); + + foreach (var view in View.Subviews) { + view.RemoveFromSuperview (); + } + + // Different UIs can be displayed depending if the intent is in the + // confirmation phase or the handle phase. + var desiredSize = CGSize.Empty; + + if (interaction.IntentHandlingStatus == INIntentHandlingStatus.Ready) { + desiredSize = DisplayInvoice (order, intent); + } else if (interaction.IntentHandlingStatus == INIntentHandlingStatus.Success) { + var response = interaction.IntentResponse as OrderSoupIntentResponse; + if (!(response is null)) { + desiredSize = DisplayOrderConfirmation (order, intent, response); + } + } + + completion (true, parameters, desiredSize); + } + + // This method will not be called if ConfigureView is implemented, + // according to: https://developer.apple.com/documentation/sirikit/inuihostedviewcontrolling/1649168-configurewithinteraction + [Export ("configureWithInteraction:context:completion:")] + public void Configure (INInteraction interaction, INUIHostedViewContext context, Action<CGSize> completion) + { + throw new NotImplementedException (); + } + + CGSize DisplayInvoice (Order order, OrderSoupIntent intent) + { + invoiceView.ItemNameLabel.Text = order.MenuItem.LocalizedString; + invoiceView.TotalPriceLabel.Text = order.LocalizedCurrencyValue; + invoiceView.UnitPriceLabel.Text = $"{order.Quantity} @ {order.MenuItem.LocalizedCurrencyValue}"; + + var intentImage = intent.GetImage ("soup"); + if (!(intentImage is null)) { + var weakThis = new WeakReference<IntentViewController> (this); + intentImage.FetchImage ((image) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (weakThis.TryGetTarget (out var intentViewController)) { + intentViewController.invoiceView.ImageView.Image = image; + } + }); + }); + } + + var optionText = (!(intent.Options is null)) ? order.LocalizedOptionString : ""; + + invoiceView.OptionsLabel.Text = optionText; + + View.AddSubview (invoiceView); + + var width = this.ExtensionContext?.GetHostedViewMaximumAllowedSize ().Width ?? 320; + var frame = new CGRect (0, 0, width, 170); + invoiceView.Frame = frame; + + return frame.Size; + } + + CGSize DisplayOrderConfirmation (Order order, OrderSoupIntent intent, OrderSoupIntentResponse response) + { + confirmationView.ItemNameLabel.Text = order.MenuItem.LocalizedString; + confirmationView.TotalPriceLabel.Text = order.LocalizedCurrencyValue; + confirmationView.ImageView.Layer.CornerRadius = 8; + var waitTime = response.WaitTime; + if (!(waitTime is null)) { + confirmationView.TimeLabel.Text = $"{waitTime} Minutes"; + } + + var intentImage = intent.GetImage ("soup"); + if (!(intentImage is null)) { + var weakThis = new WeakReference<IntentViewController> (this); + intentImage.FetchImage ((image) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (weakThis.TryGetTarget (out var intentViewController)) { + // NOTE: In the original Swift-based sample, + // the original code sets this image on the + // invoice view, which seems incorrect. + intentViewController.confirmationView.ImageView.Image = image; + } + }); + }); + } + + View.AddSubview (confirmationView); + + var width = this.ExtensionContext?.GetHostedViewMaximumAllowedSize ().Width ?? 320; + var frame = new CGRect (0, 0, width, 170); + confirmationView.Frame = frame; + + return frame.Size; + } + + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public IntentViewController (IntPtr handle) : base (handle) { } + #endregion + } } diff --git a/ios12/SoupChef/SoupChefIntentsUI/InvoiceView.cs b/ios12/SoupChef/SoupChefIntentsUI/InvoiceView.cs index 52faf8c8b..014a72621 100644 --- a/ios12/SoupChef/SoupChefIntentsUI/InvoiceView.cs +++ b/ios12/SoupChef/SoupChefIntentsUI/InvoiceView.cs @@ -1,19 +1,17 @@ -using Foundation; -using System; -using UIKit; - -namespace SoupChefIntentsUI -{ - public partial class InvoiceView : UIView - { - public UIImageView ImageView => imageView; - public UILabel ItemNameLabel => itemNameLabel; - public UILabel OptionsLabel => optionsLabel; - public UILabel TotalPriceLabel => totalPriceLabel; - public UILabel UnitPriceLabel => unitPriceLabel; - - public InvoiceView (IntPtr handle) : base (handle) - { - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; + +namespace SoupChefIntentsUI { + public partial class InvoiceView : UIView { + public UIImageView ImageView => imageView; + public UILabel ItemNameLabel => itemNameLabel; + public UILabel OptionsLabel => optionsLabel; + public UILabel TotalPriceLabel => totalPriceLabel; + public UILabel UnitPriceLabel => unitPriceLabel; + + public InvoiceView (IntPtr handle) : base (handle) + { + } + } +} diff --git a/ios12/SoupChef/SoupKit/Data/DataManager.cs b/ios12/SoupChef/SoupKit/Data/DataManager.cs index 4e14f1e30..9c713f106 100644 --- a/ios12/SoupChef/SoupKit/Data/DataManager.cs +++ b/ios12/SoupChef/SoupKit/Data/DataManager.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -10,176 +10,157 @@ A data manager that manages data conforming to `Codable` and stores it in `UserD using CoreFoundation; using SoupKit.Support; -namespace SoupKit.Data -{ - public struct UserDefaultsStorageDescriptor - { - public string Key { get; set; } - public UserDefaultsStorageDescriptor(string key) - { - Key = key; - } - } - - public static class NotificationKeys - { - // Clients of `DataManager` that want to know when the data changes can - // listen for this notification. - public const string DataChanged = "DataChangedNotification"; - } - - public class DataManager<ManagedDataType> : NSObject - where ManagedDataType : NSObject, INSCoding - { - // This sample uses App Groups to share a suite of data between the - // main app and the different extensions. - protected NSUserDefaults UserDefaults = NSUserDefaultsHelper.DataSuite; - - // To prevent data races, all access to `UserDefaults` uses this queue. - protected DispatchQueue UserDefaultsAccessQueue = new DispatchQueue("User Defaults Access Queue"); - - // Storage and observation information. - protected UserDefaultsStorageDescriptor StorageDescriptor; - - // A flag to avoid receiving notifications about data this instance just - // wrote to `UserDefaults`. - protected bool IgnoreLocalUserDefaultsChanges = false; - - // The observer object handed back after registering to observe a - // property. - IDisposable UserDefaultsObserver; - - // The data managed by this `DataManager`. - protected ManagedDataType ManagedDataBackingInstance; - - // Access to `managedDataBackingInstance` needs to occur on a dedicated - // queue to avoid data races. - protected DispatchQueue DataAccessQueue = new DispatchQueue("Data Access Queue"); - - // Public access to the managed data for clients of `DataManager` - public ManagedDataType ManagedData - { - get - { - ManagedDataType data = null; - DataAccessQueue.DispatchSync(() => data = ManagedDataBackingInstance); - return data; - } - } - - // See note below about createInitialData and initialData - public DataManager(UserDefaultsStorageDescriptor storageDescriptor, ManagedDataType initialData) - { - StorageDescriptor = storageDescriptor; - LoadData(); - if (ManagedDataBackingInstance is null) - { - ManagedDataBackingInstance = initialData; - WriteData(); - } - ObserveChangesInUserDefaults(); - } - - // createInitialData - // - // The Swift version of this app has a createInitialData method. - // Each child class of the DataManager class overrides this method, and - // then the DataManager base class calls the derived versions to get - // the initial data. C# gives a compiler warning for this ("Virtual - // member call in constructor"). Since in C# the base class constructor - // is run before the child class constructor, having the base clas - // constructor call out to a method on the derived class is calling - // a method on an object that has not yet been fully constructed. - // The C# version of this sample works around this problem by passing - // in the initial data to the constructor. - - void ObserveChangesInUserDefaults() - { - var weakThis = new WeakReference<DataManager<ManagedDataType>>(this); - Action<NSObservedChange> changeHandler = (change) => - { - if (weakThis.TryGetTarget(out var dataManager)) - { - // Ignore any change notifications coming from data this - // instance just saved to `NSUserDefaults`. - if (dataManager is null || dataManager.IgnoreLocalUserDefaultsChanges) - { - return; - } - - // The underlying data changed in `NSUserDefaults`, so - // update this instance with the change and notify clients - // of the change. - dataManager.LoadData(); - dataManager.NotifyClientsDataChanged(); - } - }; - UserDefaultsObserver = UserDefaults.AddObserver( - StorageDescriptor.Key, - NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, - changeHandler - ); - } - - // Notifies clients the data changed by posting an `NSNotification` with - // the key `NotificationKeys.DataChanged` - void NotifyClientsDataChanged() - { - var notification = NSNotification.FromName(NotificationKeys.DataChanged, this); - NSNotificationCenter.DefaultCenter.PostNotification(notification); - } - - protected virtual void FinishUnarchiving(NSObject unarchivedData) - { - throw new NotImplementedException(); - } - - // Loads the data from `NSUserDefaults`. - void LoadData() - { - UserDefaultsAccessQueue.DispatchSync(() => - { - NSData archivedData = UserDefaults.DataForKey(StorageDescriptor.Key); - try - { - // Let the derived classes handle the specifics of - // putting the unarchived data in the correct format. - // This is necessary because the derived classes - // (SoupMenuManager, SoupOrderMenuManager) are using - // generic data formats (NSMutableSet<T> or NSMutableArray<T>) - // and these types cannot be casted directly from the - // deserialized data. - NSObject unarchivedData = NSKeyedUnarchiver.UnarchiveObject(archivedData); - FinishUnarchiving(unarchivedData); - } - catch (Exception e) - { - if (!(e is null)) - { - Console.WriteLine($"Error: {e.Message}"); - } - } - }); - } - - // Writes the data to `NSUserDefaults` - protected void WriteData() - { - UserDefaultsAccessQueue.DispatchAsync(() => - { - try - { - NSData encodedData = NSKeyedArchiver.ArchivedDataWithRootObject(ManagedDataBackingInstance); - IgnoreLocalUserDefaultsChanges = true; - UserDefaults.SetValueForKey(encodedData, (NSString)StorageDescriptor.Key); - IgnoreLocalUserDefaultsChanges = false; - NotifyClientsDataChanged(); - } - catch (Exception e) - { - throw new Exception($"Could not save data. Reason: {e.Message}"); - } - }); - } - } +namespace SoupKit.Data { + public struct UserDefaultsStorageDescriptor { + public string Key { get; set; } + public UserDefaultsStorageDescriptor (string key) + { + Key = key; + } + } + + public static class NotificationKeys { + // Clients of `DataManager` that want to know when the data changes can + // listen for this notification. + public const string DataChanged = "DataChangedNotification"; + } + + public class DataManager<ManagedDataType> : NSObject + where ManagedDataType : NSObject, INSCoding { + // This sample uses App Groups to share a suite of data between the + // main app and the different extensions. + protected NSUserDefaults UserDefaults = NSUserDefaultsHelper.DataSuite; + + // To prevent data races, all access to `UserDefaults` uses this queue. + protected DispatchQueue UserDefaultsAccessQueue = new DispatchQueue ("User Defaults Access Queue"); + + // Storage and observation information. + protected UserDefaultsStorageDescriptor StorageDescriptor; + + // A flag to avoid receiving notifications about data this instance just + // wrote to `UserDefaults`. + protected bool IgnoreLocalUserDefaultsChanges = false; + + // The observer object handed back after registering to observe a + // property. + IDisposable UserDefaultsObserver; + + // The data managed by this `DataManager`. + protected ManagedDataType ManagedDataBackingInstance; + + // Access to `managedDataBackingInstance` needs to occur on a dedicated + // queue to avoid data races. + protected DispatchQueue DataAccessQueue = new DispatchQueue ("Data Access Queue"); + + // Public access to the managed data for clients of `DataManager` + public ManagedDataType ManagedData { + get { + ManagedDataType data = null; + DataAccessQueue.DispatchSync (() => data = ManagedDataBackingInstance); + return data; + } + } + + // See note below about createInitialData and initialData + public DataManager (UserDefaultsStorageDescriptor storageDescriptor, ManagedDataType initialData) + { + StorageDescriptor = storageDescriptor; + LoadData (); + if (ManagedDataBackingInstance is null) { + ManagedDataBackingInstance = initialData; + WriteData (); + } + ObserveChangesInUserDefaults (); + } + + // createInitialData + // + // The Swift version of this app has a createInitialData method. + // Each child class of the DataManager class overrides this method, and + // then the DataManager base class calls the derived versions to get + // the initial data. C# gives a compiler warning for this ("Virtual + // member call in constructor"). Since in C# the base class constructor + // is run before the child class constructor, having the base clas + // constructor call out to a method on the derived class is calling + // a method on an object that has not yet been fully constructed. + // The C# version of this sample works around this problem by passing + // in the initial data to the constructor. + + void ObserveChangesInUserDefaults () + { + var weakThis = new WeakReference<DataManager<ManagedDataType>> (this); + Action<NSObservedChange> changeHandler = (change) => { + if (weakThis.TryGetTarget (out var dataManager)) { + // Ignore any change notifications coming from data this + // instance just saved to `NSUserDefaults`. + if (dataManager is null || dataManager.IgnoreLocalUserDefaultsChanges) { + return; + } + + // The underlying data changed in `NSUserDefaults`, so + // update this instance with the change and notify clients + // of the change. + dataManager.LoadData (); + dataManager.NotifyClientsDataChanged (); + } + }; + UserDefaultsObserver = UserDefaults.AddObserver ( + StorageDescriptor.Key, + NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, + changeHandler + ); + } + + // Notifies clients the data changed by posting an `NSNotification` with + // the key `NotificationKeys.DataChanged` + void NotifyClientsDataChanged () + { + var notification = NSNotification.FromName (NotificationKeys.DataChanged, this); + NSNotificationCenter.DefaultCenter.PostNotification (notification); + } + + protected virtual void FinishUnarchiving (NSObject unarchivedData) + { + throw new NotImplementedException (); + } + + // Loads the data from `NSUserDefaults`. + void LoadData () + { + UserDefaultsAccessQueue.DispatchSync (() => { + NSData archivedData = UserDefaults.DataForKey (StorageDescriptor.Key); + try { + // Let the derived classes handle the specifics of + // putting the unarchived data in the correct format. + // This is necessary because the derived classes + // (SoupMenuManager, SoupOrderMenuManager) are using + // generic data formats (NSMutableSet<T> or NSMutableArray<T>) + // and these types cannot be casted directly from the + // deserialized data. + NSObject unarchivedData = NSKeyedUnarchiver.UnarchiveObject (archivedData); + FinishUnarchiving (unarchivedData); + } catch (Exception e) { + if (!(e is null)) { + Console.WriteLine ($"Error: {e.Message}"); + } + } + }); + } + + // Writes the data to `NSUserDefaults` + protected void WriteData () + { + UserDefaultsAccessQueue.DispatchAsync (() => { + try { + NSData encodedData = NSKeyedArchiver.ArchivedDataWithRootObject (ManagedDataBackingInstance); + IgnoreLocalUserDefaultsChanges = true; + UserDefaults.SetValueForKey (encodedData, (NSString) StorageDescriptor.Key); + IgnoreLocalUserDefaultsChanges = false; + NotifyClientsDataChanged (); + } catch (Exception e) { + throw new Exception ($"Could not save data. Reason: {e.Message}"); + } + }); + } + } } diff --git a/ios12/SoupChef/SoupKit/Data/MenuItem.cs b/ios12/SoupChef/SoupKit/Data/MenuItem.cs index c983e840c..d91c5ef6a 100644 --- a/ios12/SoupChef/SoupKit/Data/MenuItem.cs +++ b/ios12/SoupChef/SoupKit/Data/MenuItem.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -10,103 +10,95 @@ This type encapsulates the attributes of a soup menu item. using SoupKit.Support; using System.Globalization; -namespace SoupKit.Data -{ - public class MenuItem : NSObject, ILocalizable, ILocalizableCurrency, INSCoding - { - public string ItemNameKey { get; set; } - public NSDecimalNumber Price { get; set; } - public string IconImageName { get; set; } - public bool IsAvailable { get; set; } - public bool IsDailySpecial { get; set; } - public MenuItem(string itemNameKey, NSDecimalNumber price, string iconImageName, bool isAvailable, bool isDailySpecial) - { - ItemNameKey = itemNameKey; - Price = price; - IconImageName = iconImageName; - IsAvailable = isAvailable; - IsDailySpecial = isDailySpecial; - } +namespace SoupKit.Data { + public class MenuItem : NSObject, ILocalizable, ILocalizableCurrency, INSCoding { + public string ItemNameKey { get; set; } + public NSDecimalNumber Price { get; set; } + public string IconImageName { get; set; } + public bool IsAvailable { get; set; } + public bool IsDailySpecial { get; set; } + public MenuItem (string itemNameKey, NSDecimalNumber price, string iconImageName, bool isAvailable, bool isDailySpecial) + { + ItemNameKey = itemNameKey; + Price = price; + IconImageName = iconImageName; + IsAvailable = isAvailable; + IsDailySpecial = isDailySpecial; + } - public string LocalizedCurrencyValue - { - get - { - return NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber(Price); - } - } + public string LocalizedCurrencyValue { + get { + return NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber (Price); + } + } - public string LocalizedString - { - get - { - return NSBundleHelper.SoupKitBundle.GetLocalizedString(ItemNameKey, "Menu item title") ?? ""; - } - } + public string LocalizedString { + get { + return NSBundleHelper.SoupKitBundle.GetLocalizedString (ItemNameKey, "Menu item title") ?? ""; + } + } - // In the Swift version of this sample, `MenuItem` is a struct. Since - // it's a class in C#, provide a clone method. - public MenuItem Clone() - { - return new MenuItem(ItemNameKey, Price, IconImageName, IsAvailable, IsDailySpecial); - } + // In the Swift version of this sample, `MenuItem` is a struct. Since + // it's a class in C#, provide a clone method. + public MenuItem Clone () + { + return new MenuItem (ItemNameKey, Price, IconImageName, IsAvailable, IsDailySpecial); + } - // Necessary so this class works as expected in collections. - [Export("isEqual:")] - override public bool IsEqual(NSObject anObject) - { - var other = anObject as MenuItem; + // Necessary so this class works as expected in collections. + [Export ("isEqual:")] + override public bool IsEqual (NSObject anObject) + { + var other = anObject as MenuItem; - if (other is null) - { - return false; - } + if (other is null) { + return false; + } - if (ReferenceEquals(other, this)) - { - return true; - } + if (ReferenceEquals (other, this)) { + return true; + } - bool result = - (ItemNameKey.Equals(other.ItemNameKey) && - Price.IsEqual(other.Price) && - IconImageName.Equals(other.IconImageName) && - IsAvailable == other.IsAvailable && - IsDailySpecial == other.IsDailySpecial); + bool result = + (ItemNameKey.Equals (other.ItemNameKey) && + Price.IsEqual (other.Price) && + IconImageName.Equals (other.IconImageName) && + IsAvailable == other.IsAvailable && + IsDailySpecial == other.IsDailySpecial); - return result; - } + return result; + } - // Necessary so this class works as expected in collections. - public override nuint GetNativeHash() - { - nuint hashValue = (ItemNameKey is null) ? 0 : (nuint)ItemNameKey.GetHashCode(); - hashValue = hashValue ^ (nuint)Price.GetNativeHash(); - hashValue = hashValue ^ (IconImageName is null ? 0 : (nuint)IconImageName.GetHashCode()); - hashValue = hashValue ^ (nuint)IsAvailable.GetHashCode(); - hashValue = hashValue ^ (nuint)IsDailySpecial.GetHashCode(); - return hashValue; - } + // Necessary so this class works as expected in collections. + public override nuint GetNativeHash () + { + nuint hashValue = (ItemNameKey is null) ? 0 : (nuint) ItemNameKey.GetHashCode (); + hashValue = hashValue ^ (nuint) Price.GetNativeHash (); + hashValue = hashValue ^ (IconImageName is null ? 0 : (nuint) IconImageName.GetHashCode ()); + hashValue = hashValue ^ (nuint) IsAvailable.GetHashCode (); + hashValue = hashValue ^ (nuint) IsDailySpecial.GetHashCode (); + return hashValue; + } - #region INSCoding - [Export("initWithCoder:")] - public MenuItem(NSCoder coder) - { - ItemNameKey = (NSString)coder.DecodeObject("ItemNameKey"); - Price = (NSDecimalNumber)coder.DecodeObject("Price"); - IconImageName = (NSString)coder.DecodeObject("IconImageName"); - IsAvailable = (bool)coder.DecodeBool("IsAvailable"); - IsDailySpecial = (bool)coder.DecodeBool("IsDailySpecial"); - } + #region INSCoding + [Export ("initWithCoder:")] + public MenuItem (NSCoder coder) + { + ItemNameKey = (NSString) coder.DecodeObject ("ItemNameKey"); + Price = (NSDecimalNumber) coder.DecodeObject ("Price"); + IconImageName = (NSString) coder.DecodeObject ("IconImageName"); + IsAvailable = (bool) coder.DecodeBool ("IsAvailable"); + IsDailySpecial = (bool) coder.DecodeBool ("IsDailySpecial"); + } - public void EncodeTo(NSCoder encoder) - { - encoder.Encode((NSString)ItemNameKey, "ItemNameKey"); - encoder.Encode(Price, "Price"); - encoder.Encode((NSString)IconImageName, "IconImageName"); - encoder.Encode(IsAvailable, "IsAvailable"); - encoder.Encode(IsDailySpecial, "IsDailySpecial"); - } - #endregion - } + public void EncodeTo (NSCoder encoder) + { + encoder.Encode ((NSString) ItemNameKey, "ItemNameKey"); + encoder.Encode (Price, "Price"); + encoder.Encode ((NSString) IconImageName, "IconImageName"); + encoder.Encode (IsAvailable, "IsAvailable"); + encoder.Encode (IsDailySpecial, "IsDailySpecial"); + } + #endregion + } } diff --git a/ios12/SoupChef/SoupKit/Data/MenuItemOption.cs b/ios12/SoupChef/SoupKit/Data/MenuItemOption.cs index c626ce8bd..72ea09c5d 100644 --- a/ios12/SoupChef/SoupKit/Data/MenuItemOption.cs +++ b/ios12/SoupChef/SoupKit/Data/MenuItemOption.cs @@ -1,76 +1,66 @@ -using System; +using System; using System.Linq; using Foundation; using SoupKit.Support; -namespace SoupKit.Data -{ - public class MenuItemOption : NSObject, ILocalizable, INSCoding - { - public const string Cheese = "CHEESE"; - public const string RedPepper = "RED_PEPPER"; - public const string Croutons = "CROUTONS"; +namespace SoupKit.Data { + public class MenuItemOption : NSObject, ILocalizable, INSCoding { + public const string Cheese = "CHEESE"; + public const string RedPepper = "RED_PEPPER"; + public const string Croutons = "CROUTONS"; - public static string[] All = new string[] { Cheese, RedPepper, Croutons }; + public static string [] All = new string [] { Cheese, RedPepper, Croutons }; - public string LocalizedString - { - get - { - string usageComment = $"UI representation for MenuItemOption value: {Value}"; - return NSBundleHelper.SoupKitBundle.GetLocalizedString(Value, usageComment, null); - } - } + public string LocalizedString { + get { + string usageComment = $"UI representation for MenuItemOption value: {Value}"; + return NSBundleHelper.SoupKitBundle.GetLocalizedString (Value, usageComment, null); + } + } - public MenuItemOption(string value) - { - if (All.Contains(value)) - { - _value = value; - } - else - { - throw new ArgumentException($"Invalid menuItemOption value: {value}"); - } - } + public MenuItemOption (string value) + { + if (All.Contains (value)) { + _value = value; + } else { + throw new ArgumentException ($"Invalid menuItemOption value: {value}"); + } + } - string _value; - public string Value - { - get { return _value; } - } + string _value; + public string Value { + get { return _value; } + } - [Export("isEqual:")] - override public bool IsEqual(NSObject anObject) - { - var other = anObject as MenuItemOption; - if (other is null) - { - return false; - } - if (ReferenceEquals(other, this)) - { - return true; - } - return Value.Equals(other.Value); - } + [Export ("isEqual:")] + override public bool IsEqual (NSObject anObject) + { + var other = anObject as MenuItemOption; + if (other is null) { + return false; + } + if (ReferenceEquals (other, this)) { + return true; + } + return Value.Equals (other.Value); + } - public override nuint GetNativeHash() - { - return !(Value is null) ? (nuint)this.Value?.GetHashCode() : 0; - } + public override nuint GetNativeHash () + { + return !(Value is null) ? (nuint) this.Value?.GetHashCode () : 0; + } - #region INSCoding - [Export("initWithCoder:")] - public MenuItemOption(NSCoder coder) - { - _value = (NSString)coder.DecodeObject("Value"); - } + #region INSCoding + [Export ("initWithCoder:")] + public MenuItemOption (NSCoder coder) + { + _value = (NSString) coder.DecodeObject ("Value"); + } - public void EncodeTo(NSCoder encoder) - { - encoder.Encode((NSString)_value, "Value"); - } - #endregion - } + public void EncodeTo (NSCoder encoder) + { + encoder.Encode ((NSString) _value, "Value"); + } + #endregion + } } diff --git a/ios12/SoupChef/SoupKit/Data/Order.cs b/ios12/SoupChef/SoupKit/Data/Order.cs index b55f456c6..8b40e1c81 100644 --- a/ios12/SoupChef/SoupKit/Data/Order.cs +++ b/ios12/SoupChef/SoupKit/Data/Order.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -13,228 +13,196 @@ This type encapsulates the attributes of a soup order. using Intents; using UIKit; -namespace SoupKit.Data -{ - public class Order : NSObject, ILocalizableCurrency, INSCoding - { - public NSDate Date { get; private set; } - public NSUuid Identifier { get; private set; } - public MenuItem MenuItem { get; private set; } - public int Quantity { get; set; } - public NSMutableSet<MenuItemOption> MenuItemOptions { get; set; } - public NSDecimalNumber Total - { - get - { - return new NSDecimalNumber(Quantity).Multiply(MenuItem.Price); - } - } - - public Order(int quantity, MenuItem menuItem, NSMutableSet<MenuItemOption> menuItemOptions, NSDate date = null, NSUuid identifier = null) - { - Date = date ?? new NSDate(); - Identifier = identifier ?? new NSUuid(); - Quantity = quantity; - MenuItem = menuItem; - MenuItemOptions = menuItemOptions; - } - - // SoupChef considers orders with the same contents (menuItem, quantity, - // menuItemOptions) to be identical. The data and idenfier properties - // are unique to an instance of an order (regardless of contents) and - // are not considered when determining equality. - [Export("isEqual:")] - override public bool IsEqual(NSObject anObject) - { - var other = anObject as Order; - - if (other is null) - { - return false; - } - - if (ReferenceEquals(other, this)) - { - return true; - } - - // MenuItem check - if (MenuItem is null) - { - if (!(other.MenuItem is null)) - { - return false; - } - } - else - { - if (!MenuItem.IsEqual(other.MenuItem)) - { - return false; - } - } - - // Quantity check - if (Quantity != other.Quantity) - { - return false; - } - - // MenuItemOptions check - if (MenuItemOptions is null) - { - if (!(other.MenuItemOptions is null)) - { - return false; - } - } - else - { - if (!MenuItemOptions.IsEqualToSet(other.MenuItemOptions)) - { - return false; - } - } - - return true; - } - - public override nuint GetNativeHash() - { - nuint hashValue = (MenuItem is null) ? 0 : MenuItem.GetNativeHash(); - hashValue = hashValue ^ (nuint)Quantity.GetHashCode(); - hashValue = hashValue ^ (MenuItemOptions is null ? 0 : MenuItemOptions.GetNativeHash()); - return hashValue; - } - - #region LocalizableCurrency (and other localization methods) - public string LocalizedCurrencyValue - { - get - { - return NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber(Total) ?? ""; - } - } - - public string[] LocalizedOptionsArray - { - get - { - var localizedArray = MenuItemOptions - .ToArray<MenuItemOption>() - .Select(arg => arg.LocalizedString) - .OrderBy(arg => arg, StringComparer.CurrentCultureIgnoreCase) - .ToArray<string>(); - return localizedArray; - } - } - - public string LocalizedOptionString - { - get - { - return String.Join(", ", LocalizedOptionsArray); - } - } - #endregion - - #region intent helpers - public OrderSoupIntent Intent - { - get - { - var orderSoupIntent = new OrderSoupIntent(); - orderSoupIntent.Quantity = new NSNumber(Quantity); - orderSoupIntent.Soup = new INObject(MenuItem.ItemNameKey, MenuItem.LocalizedString); - - var image = UIImage.FromBundle(MenuItem.IconImageName); - if (!(image is null)) - { - var data = image.AsPNG(); - orderSoupIntent.SetImage(INImage.FromData(data), "soup"); - } - - orderSoupIntent.Options = MenuItemOptions - .ToArray<MenuItemOption>() - .Select<MenuItemOption, INObject>(arg => new INObject(arg.Value, arg.LocalizedString)) - .ToArray<INObject>(); - - var comment = "Suggested phrase for ordering a specific soup"; - var phrase = NSBundleHelper.SoupKitBundle.GetLocalizedString("ORDER_SOUP_SUGGESTED_PHRASE", comment); - orderSoupIntent.SuggestedInvocationPhrase = String.Format(phrase, MenuItem.LocalizedString); - - return orderSoupIntent; - } - } - - public static Order FromOrderSoupIntent(OrderSoupIntent intent) - { - var menuManager = new SoupMenuManager(); - - var soupID = intent.Soup?.Identifier; - if (soupID is null) - { - return null; - } - - var menuItem = menuManager.FindItem(soupID); - if (menuItem is null) - { - return null; - } - - var quantity = intent.Quantity; - if (menuItem is null) - { - return null; - } - - MenuItemOption[] rawOptions; - if (intent.Options is null) - { - rawOptions = new MenuItemOption[0]; - } - else - { - // For the equivalent code in Apple's Swift sample, compactMap - // is used. This eliminates nil values from the final result. - // Here, LINQ's Where method is used to filter out the null - // values. - rawOptions = intent.Options.Select<INObject, MenuItemOption>((option) => { - var optionID = option.Identifier; - return (optionID is null) ? null : new MenuItemOption(optionID); - }).Where((option) => !(option is null)).ToArray<MenuItemOption>(); - } - - var order = new Order(quantity.Int32Value, menuItem, new NSMutableSet<MenuItemOption>(rawOptions)); - - return order; - } - #endregion - - #region INSCoding - [Export("initWithCoder:")] - public Order(NSCoder coder) - { - Date = (NSDate)coder.DecodeObject("Date"); - Identifier = (NSUuid)coder.DecodeObject("Identifier"); - MenuItem = (MenuItem)coder.DecodeObject("MenuItem"); - Quantity = (int)coder.DecodeInt("Quantity"); - - // Can't decode an NSMutableSet<MenuItemOption> directly. Get an - // NSSet, convert it to NSMutableSet<MenuItemOption> - var set = (NSSet)(coder.DecodeObject("MenuItemOptions")); - MenuItemOptions = new NSMutableSet<MenuItemOption>(set.ToArray<MenuItemOption>()); - } - - public void EncodeTo(NSCoder encoder) - { - encoder.Encode(Date, "Date"); - encoder.Encode(Identifier, "Identifier"); - encoder.Encode(MenuItem, "MenuItem"); - encoder.Encode(Quantity, "Quantity"); - encoder.Encode(MenuItemOptions, "MenuItemOptions"); - } - #endregion - } +namespace SoupKit.Data { + public class Order : NSObject, ILocalizableCurrency, INSCoding { + public NSDate Date { get; private set; } + public NSUuid Identifier { get; private set; } + public MenuItem MenuItem { get; private set; } + public int Quantity { get; set; } + public NSMutableSet<MenuItemOption> MenuItemOptions { get; set; } + public NSDecimalNumber Total { + get { + return new NSDecimalNumber (Quantity).Multiply (MenuItem.Price); + } + } + + public Order (int quantity, MenuItem menuItem, NSMutableSet<MenuItemOption> menuItemOptions, NSDate date = null, NSUuid identifier = null) + { + Date = date ?? new NSDate (); + Identifier = identifier ?? new NSUuid (); + Quantity = quantity; + MenuItem = menuItem; + MenuItemOptions = menuItemOptions; + } + + // SoupChef considers orders with the same contents (menuItem, quantity, + // menuItemOptions) to be identical. The data and idenfier properties + // are unique to an instance of an order (regardless of contents) and + // are not considered when determining equality. + [Export ("isEqual:")] + override public bool IsEqual (NSObject anObject) + { + var other = anObject as Order; + + if (other is null) { + return false; + } + + if (ReferenceEquals (other, this)) { + return true; + } + + // MenuItem check + if (MenuItem is null) { + if (!(other.MenuItem is null)) { + return false; + } + } else { + if (!MenuItem.IsEqual (other.MenuItem)) { + return false; + } + } + + // Quantity check + if (Quantity != other.Quantity) { + return false; + } + + // MenuItemOptions check + if (MenuItemOptions is null) { + if (!(other.MenuItemOptions is null)) { + return false; + } + } else { + if (!MenuItemOptions.IsEqualToSet (other.MenuItemOptions)) { + return false; + } + } + + return true; + } + + public override nuint GetNativeHash () + { + nuint hashValue = (MenuItem is null) ? 0 : MenuItem.GetNativeHash (); + hashValue = hashValue ^ (nuint) Quantity.GetHashCode (); + hashValue = hashValue ^ (MenuItemOptions is null ? 0 : MenuItemOptions.GetNativeHash ()); + return hashValue; + } + + #region LocalizableCurrency (and other localization methods) + public string LocalizedCurrencyValue { + get { + return NSNumberFormatterHelper.CurrencyFormatter.StringFromNumber (Total) ?? ""; + } + } + + public string [] LocalizedOptionsArray { + get { + var localizedArray = MenuItemOptions + .ToArray<MenuItemOption> () + .Select (arg => arg.LocalizedString) + .OrderBy (arg => arg, StringComparer.CurrentCultureIgnoreCase) + .ToArray<string> (); + return localizedArray; + } + } + + public string LocalizedOptionString { + get { + return String.Join (", ", LocalizedOptionsArray); + } + } + #endregion + + #region intent helpers + public OrderSoupIntent Intent { + get { + var orderSoupIntent = new OrderSoupIntent (); + orderSoupIntent.Quantity = new NSNumber (Quantity); + orderSoupIntent.Soup = new INObject (MenuItem.ItemNameKey, MenuItem.LocalizedString); + + var image = UIImage.FromBundle (MenuItem.IconImageName); + if (!(image is null)) { + var data = image.AsPNG (); + orderSoupIntent.SetImage (INImage.FromData (data), "soup"); + } + + orderSoupIntent.Options = MenuItemOptions + .ToArray<MenuItemOption> () + .Select<MenuItemOption, INObject> (arg => new INObject (arg.Value, arg.LocalizedString)) + .ToArray<INObject> (); + + var comment = "Suggested phrase for ordering a specific soup"; + var phrase = NSBundleHelper.SoupKitBundle.GetLocalizedString ("ORDER_SOUP_SUGGESTED_PHRASE", comment); + orderSoupIntent.SuggestedInvocationPhrase = String.Format (phrase, MenuItem.LocalizedString); + + return orderSoupIntent; + } + } + + public static Order FromOrderSoupIntent (OrderSoupIntent intent) + { + var menuManager = new SoupMenuManager (); + + var soupID = intent.Soup?.Identifier; + if (soupID is null) { + return null; + } + + var menuItem = menuManager.FindItem (soupID); + if (menuItem is null) { + return null; + } + + var quantity = intent.Quantity; + if (menuItem is null) { + return null; + } + + MenuItemOption [] rawOptions; + if (intent.Options is null) { + rawOptions = new MenuItemOption [0]; + } else { + // For the equivalent code in Apple's Swift sample, compactMap + // is used. This eliminates nil values from the final result. + // Here, LINQ's Where method is used to filter out the null + // values. + rawOptions = intent.Options.Select<INObject, MenuItemOption> ((option) => { + var optionID = option.Identifier; + return (optionID is null) ? null : new MenuItemOption (optionID); + }).Where ((option) => !(option is null)).ToArray<MenuItemOption> (); + } + + var order = new Order (quantity.Int32Value, menuItem, new NSMutableSet<MenuItemOption> (rawOptions)); + + return order; + } + #endregion + + #region INSCoding + [Export ("initWithCoder:")] + public Order (NSCoder coder) + { + Date = (NSDate) coder.DecodeObject ("Date"); + Identifier = (NSUuid) coder.DecodeObject ("Identifier"); + MenuItem = (MenuItem) coder.DecodeObject ("MenuItem"); + Quantity = (int) coder.DecodeInt ("Quantity"); + + // Can't decode an NSMutableSet<MenuItemOption> directly. Get an + // NSSet, convert it to NSMutableSet<MenuItemOption> + var set = (NSSet) (coder.DecodeObject ("MenuItemOptions")); + MenuItemOptions = new NSMutableSet<MenuItemOption> (set.ToArray<MenuItemOption> ()); + } + + public void EncodeTo (NSCoder encoder) + { + encoder.Encode (Date, "Date"); + encoder.Encode (Identifier, "Identifier"); + encoder.Encode (MenuItem, "MenuItem"); + encoder.Encode (Quantity, "Quantity"); + encoder.Encode (MenuItemOptions, "MenuItemOptions"); + } + #endregion + } } diff --git a/ios12/SoupChef/SoupKit/Data/SoupMenuManager.cs b/ios12/SoupChef/SoupKit/Data/SoupMenuManager.cs index 8c959240a..7bc5cb634 100644 --- a/ios12/SoupChef/SoupKit/Data/SoupMenuManager.cs +++ b/ios12/SoupChef/SoupKit/Data/SoupMenuManager.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -12,209 +12,181 @@ A DataManager subclass that persists the active menu items. using Intents; using UIKit; -namespace SoupKit.Data -{ - public class SoupMenuManager : DataManager<NSMutableSet<MenuItem>> - { - static NSMutableSet<MenuItem> DefaultMenu = new NSMutableSet<MenuItem>( - new MenuItem("CHICKEN_NOODLE_SOUP", new NSDecimalNumber(4.55m), "chicken_noodle_soup", false, true), - new MenuItem("CLAM_CHOWDER", new NSDecimalNumber(3.75m), "new_england_clam_chowder", true, false), - new MenuItem("TOMATO_SOUP", new NSDecimalNumber(2.95m), "tomato_soup", true, false) - ); - - public SoupOrderDataManager OrderManager { get; set; } - - public SoupMenuManager() : base(new UserDefaultsStorageDescriptor(NSUserDefaultsHelper.StorageKeys.SoupMenu), DefaultMenu) { } - - #region Public API for clients of `SoupMenuManager` - public MenuItem[] DailySpecialItems - { - get - { - var specials = new MenuItem[] { }; - var predicate = NSPredicate.FromExpression((evaluatedObject, bindings) => - { - return ((MenuItem)evaluatedObject).IsDailySpecial; - }); - DataAccessQueue.DispatchSync(() => - { - specials = new NSSet<MenuItem>(ManagedDataBackingInstance) - .FilterUsingPredicate(predicate) - .ToArray<MenuItem>(); - }); - return specials; - } - } - - public MenuItem[] AllRegularItems - { - get - { - var regularItems = new MenuItem[] { }; - var predicate = NSPredicate.FromExpression((evaluatedObject, bindings) => - { - return !((MenuItem)evaluatedObject).IsDailySpecial; - }); - DataAccessQueue.DispatchSync(() => - { - regularItems = new NSSet<MenuItem>(ManagedDataBackingInstance) - .FilterUsingPredicate(predicate) - .ToArray<MenuItem>(); - }); - return regularItems; - } - } - - public MenuItem[] AvailableRegularItems - { - get - { - var availableRegularItems = new MenuItem[] { }; - var predicate = NSPredicate.FromExpression((evaluatedObject, bindings) => - { - var menuItem = (MenuItem)evaluatedObject; - return !menuItem.IsDailySpecial && menuItem.IsAvailable; - }); - DataAccessQueue.DispatchSync(() => - { - availableRegularItems = new NSSet<MenuItem>(ManagedDataBackingInstance) - .FilterUsingPredicate(predicate) - .ToArray<MenuItem>(); - }); - return availableRegularItems; - } - } - - public void ReplaceMenuItem(MenuItem previousMenuItem, MenuItem menuItem) - { - DataAccessQueue.DispatchSync(() => - { - ManagedDataBackingInstance.Remove(previousMenuItem); - ManagedDataBackingInstance.Add(menuItem); - }); - - // Access to NSUserDefaults is gated behind a separate access queue. - WriteData(); - - // Inform Siri of changes to the menu. - RemoveDonation(menuItem); - Suggest(menuItem); - } - - public MenuItem FindItem(string identifier) - { - MenuItem[] matchedItems = new MenuItem[] { }; - var predicate = NSPredicate.FromExpression((evaluatedObject, bindings) => - { - return ((MenuItem)evaluatedObject).ItemNameKey == identifier; - }); - matchedItems = new NSSet<MenuItem>(ManagedDataBackingInstance) - .FilterUsingPredicate(predicate) - .ToArray<MenuItem>(); - - return matchedItems.FirstOrDefault(); - } - #endregion - - #region Supporting methods for using the Intents framework. - // Each time an order is placed we instantiate an INInteraction object - // and donate it to the system (see SoupOrderDataManager extension). - // After instantiating the INInteraction, its identifier property is - // set to the same value as the identifier property for the - // corresponding order. Compile a list of all the order identifiers to - // pass to the INInteraction delete method. - void RemoveDonation(MenuItem menuItem) - { - if (!menuItem.IsAvailable) - { - Order[] orderHistory = OrderManager?.OrderHistory.ToArray<Order>(); - if (orderHistory is null) - { - return; - } - - string[] orderIdentifiersToRemove = orderHistory - .Where<Order>((order) => order.MenuItem.ItemNameKey == menuItem.ItemNameKey) - .Select<Order, string>((order) => order.Identifier.ToString()) - .ToArray<string>(); - - INInteraction.DeleteInteractions(orderIdentifiersToRemove, (error) => - { - if (!(error is null)) - { - Console.WriteLine($"Failed to delete interactions with error {error.ToString()}"); - } - else - { - Console.WriteLine("Successfully deleted interactions"); - } - }); - } - } - - // Configures a daily soup special to be made available as a relevant - // shortcut. This item is not available on the regular menu to - // demonstrate how relevant shortcuts are able to suggest tasks the user - // may want to start, but hasn't used in the app before. - void Suggest(MenuItem menuItem) - { - if (menuItem.IsDailySpecial && menuItem.IsAvailable) - { - var order = new Order(1, menuItem, new NSMutableSet<MenuItemOption>()); - var orderIntent = order.Intent; - - var shortcut = new INShortcut(orderIntent); - var suggestedShortcut = new INRelevantShortcut(shortcut); - - var localizedTitle = NSBundleHelper.SoupKitBundle.GetLocalizedString( - "ORDER_LUNCH_TITLE", - "Relevant shortcut title" - ); - var template = new INDefaultCardTemplate(localizedTitle); - template.Subtitle = menuItem.ItemNameKey; - - var image = UIImage.FromBundle(menuItem.IconImageName); - if (!(image is null)) - { - var data = image.AsPNG(); - template.Image = INImage.FromData(data); - } - - suggestedShortcut.WatchTemplate = template; - - // Make a lunch suggestion when arriving to work. - var routineRelevanceProvider = new INDailyRoutineRelevanceProvider( - INDailyRoutineSituation.Work - ); - - // This sample uses a single relevance provider, but using - // multiple relevance providers is supported. - suggestedShortcut.RelevanceProviders = - new INRelevanceProvider[] { routineRelevanceProvider }; - - var suggestedShortcuts = new INRelevantShortcut[] { suggestedShortcut }; - INRelevantShortcutStore.DefaultStore.SetRelevantShortcuts(suggestedShortcuts, (error) => - { - if (!(error is null)) - { - Console.WriteLine($"Providing relevant shortcut failed. \n{error}"); - } - else - { - Console.WriteLine("Providing relevant shortcut succeeded."); - } - }); - } - - } - #endregion - - #region Support methods for unarchiving saved data - override protected void FinishUnarchiving(NSObject unarchivedData) - { - NSSet set = (NSSet)unarchivedData; - ManagedDataBackingInstance = new NSMutableSet<MenuItem>(set.ToArray<MenuItem>()); - } - #endregion - } +namespace SoupKit.Data { + public class SoupMenuManager : DataManager<NSMutableSet<MenuItem>> { + static NSMutableSet<MenuItem> DefaultMenu = new NSMutableSet<MenuItem> ( + new MenuItem ("CHICKEN_NOODLE_SOUP", new NSDecimalNumber (4.55m), "chicken_noodle_soup", false, true), + new MenuItem ("CLAM_CHOWDER", new NSDecimalNumber (3.75m), "new_england_clam_chowder", true, false), + new MenuItem ("TOMATO_SOUP", new NSDecimalNumber (2.95m), "tomato_soup", true, false) + ); + + public SoupOrderDataManager OrderManager { get; set; } + + public SoupMenuManager () : base (new UserDefaultsStorageDescriptor (NSUserDefaultsHelper.StorageKeys.SoupMenu), DefaultMenu) { } + + #region Public API for clients of `SoupMenuManager` + public MenuItem [] DailySpecialItems { + get { + var specials = new MenuItem [] { }; + var predicate = NSPredicate.FromExpression ((evaluatedObject, bindings) => { + return ((MenuItem) evaluatedObject).IsDailySpecial; + }); + DataAccessQueue.DispatchSync (() => { + specials = new NSSet<MenuItem> (ManagedDataBackingInstance) + .FilterUsingPredicate (predicate) + .ToArray<MenuItem> (); + }); + return specials; + } + } + + public MenuItem [] AllRegularItems { + get { + var regularItems = new MenuItem [] { }; + var predicate = NSPredicate.FromExpression ((evaluatedObject, bindings) => { + return !((MenuItem) evaluatedObject).IsDailySpecial; + }); + DataAccessQueue.DispatchSync (() => { + regularItems = new NSSet<MenuItem> (ManagedDataBackingInstance) + .FilterUsingPredicate (predicate) + .ToArray<MenuItem> (); + }); + return regularItems; + } + } + + public MenuItem [] AvailableRegularItems { + get { + var availableRegularItems = new MenuItem [] { }; + var predicate = NSPredicate.FromExpression ((evaluatedObject, bindings) => { + var menuItem = (MenuItem) evaluatedObject; + return !menuItem.IsDailySpecial && menuItem.IsAvailable; + }); + DataAccessQueue.DispatchSync (() => { + availableRegularItems = new NSSet<MenuItem> (ManagedDataBackingInstance) + .FilterUsingPredicate (predicate) + .ToArray<MenuItem> (); + }); + return availableRegularItems; + } + } + + public void ReplaceMenuItem (MenuItem previousMenuItem, MenuItem menuItem) + { + DataAccessQueue.DispatchSync (() => { + ManagedDataBackingInstance.Remove (previousMenuItem); + ManagedDataBackingInstance.Add (menuItem); + }); + + // Access to NSUserDefaults is gated behind a separate access queue. + WriteData (); + + // Inform Siri of changes to the menu. + RemoveDonation (menuItem); + Suggest (menuItem); + } + + public MenuItem FindItem (string identifier) + { + MenuItem [] matchedItems = new MenuItem [] { }; + var predicate = NSPredicate.FromExpression ((evaluatedObject, bindings) => { + return ((MenuItem) evaluatedObject).ItemNameKey == identifier; + }); + matchedItems = new NSSet<MenuItem> (ManagedDataBackingInstance) + .FilterUsingPredicate (predicate) + .ToArray<MenuItem> (); + + return matchedItems.FirstOrDefault (); + } + #endregion + + #region Supporting methods for using the Intents framework. + // Each time an order is placed we instantiate an INInteraction object + // and donate it to the system (see SoupOrderDataManager extension). + // After instantiating the INInteraction, its identifier property is + // set to the same value as the identifier property for the + // corresponding order. Compile a list of all the order identifiers to + // pass to the INInteraction delete method. + void RemoveDonation (MenuItem menuItem) + { + if (!menuItem.IsAvailable) { + Order [] orderHistory = OrderManager?.OrderHistory.ToArray<Order> (); + if (orderHistory is null) { + return; + } + + string [] orderIdentifiersToRemove = orderHistory + .Where<Order> ((order) => order.MenuItem.ItemNameKey == menuItem.ItemNameKey) + .Select<Order, string> ((order) => order.Identifier.ToString ()) + .ToArray<string> (); + + INInteraction.DeleteInteractions (orderIdentifiersToRemove, (error) => { + if (!(error is null)) { + Console.WriteLine ($"Failed to delete interactions with error {error.ToString ()}"); + } else { + Console.WriteLine ("Successfully deleted interactions"); + } + }); + } + } + + // Configures a daily soup special to be made available as a relevant + // shortcut. This item is not available on the regular menu to + // demonstrate how relevant shortcuts are able to suggest tasks the user + // may want to start, but hasn't used in the app before. + void Suggest (MenuItem menuItem) + { + if (menuItem.IsDailySpecial && menuItem.IsAvailable) { + var order = new Order (1, menuItem, new NSMutableSet<MenuItemOption> ()); + var orderIntent = order.Intent; + + var shortcut = new INShortcut (orderIntent); + var suggestedShortcut = new INRelevantShortcut (shortcut); + + var localizedTitle = NSBundleHelper.SoupKitBundle.GetLocalizedString ( + "ORDER_LUNCH_TITLE", + "Relevant shortcut title" + ); + var template = new INDefaultCardTemplate (localizedTitle); + template.Subtitle = menuItem.ItemNameKey; + + var image = UIImage.FromBundle (menuItem.IconImageName); + if (!(image is null)) { + var data = image.AsPNG (); + template.Image = INImage.FromData (data); + } + + suggestedShortcut.WatchTemplate = template; + + // Make a lunch suggestion when arriving to work. + var routineRelevanceProvider = new INDailyRoutineRelevanceProvider ( + INDailyRoutineSituation.Work + ); + + // This sample uses a single relevance provider, but using + // multiple relevance providers is supported. + suggestedShortcut.RelevanceProviders = + new INRelevanceProvider [] { routineRelevanceProvider }; + + var suggestedShortcuts = new INRelevantShortcut [] { suggestedShortcut }; + INRelevantShortcutStore.DefaultStore.SetRelevantShortcuts (suggestedShortcuts, (error) => { + if (!(error is null)) { + Console.WriteLine ($"Providing relevant shortcut failed. \n{error}"); + } else { + Console.WriteLine ("Providing relevant shortcut succeeded."); + } + }); + } + + } + #endregion + + #region Support methods for unarchiving saved data + override protected void FinishUnarchiving (NSObject unarchivedData) + { + NSSet set = (NSSet) unarchivedData; + ManagedDataBackingInstance = new NSMutableSet<MenuItem> (set.ToArray<MenuItem> ()); + } + #endregion + } } diff --git a/ios12/SoupChef/SoupKit/Data/SoupOrderDataManager.cs b/ios12/SoupChef/SoupKit/Data/SoupOrderDataManager.cs index a6d11252b..31e405f93 100644 --- a/ios12/SoupChef/SoupKit/Data/SoupOrderDataManager.cs +++ b/ios12/SoupChef/SoupKit/Data/SoupOrderDataManager.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -11,78 +11,66 @@ A data manager that manages an array of `Order` structs. using System; using System.Linq; -namespace SoupKit.Data -{ - // A concrete `DataManager` for reading and writing data of type `NSMutableArray<Order>`. - public class SoupOrderDataManager : DataManager<NSMutableArray<Order>> - { - public SoupOrderDataManager() : base(new UserDefaultsStorageDescriptor(NSUserDefaultsHelper.StorageKeys.OrderHistory), new NSMutableArray<Order>()) { } +namespace SoupKit.Data { + // A concrete `DataManager` for reading and writing data of type `NSMutableArray<Order>`. + public class SoupOrderDataManager : DataManager<NSMutableArray<Order>> { + public SoupOrderDataManager () : base (new UserDefaultsStorageDescriptor (NSUserDefaultsHelper.StorageKeys.OrderHistory), new NSMutableArray<Order> ()) { } - // Converts an `Order` into `OrderSoupIntent` and donates it as an - // interaction to the system so that this order can be suggested in the - // future or turned into a voice shortcut for quickly placing the same - // order in the future. - void DonateInteraction(Order order) - { - var interaction = new INInteraction(order.Intent, null); - interaction.Identifier = order.Identifier.ToString(); - interaction.DonateInteraction((error) => - { - if (!(error is null)) - { - Console.WriteLine($"Interaction donation failed: {error}"); - } - else - { - Console.WriteLine("Successfully donated interaction."); - } - }); - } + // Converts an `Order` into `OrderSoupIntent` and donates it as an + // interaction to the system so that this order can be suggested in the + // future or turned into a voice shortcut for quickly placing the same + // order in the future. + void DonateInteraction (Order order) + { + var interaction = new INInteraction (order.Intent, null); + interaction.Identifier = order.Identifier.ToString (); + interaction.DonateInteraction ((error) => { + if (!(error is null)) { + Console.WriteLine ($"Interaction donation failed: {error}"); + } else { + Console.WriteLine ("Successfully donated interaction."); + } + }); + } - #region Public API for clients of `SoupOrderDataManager` - // Convenience method to access the data with a property name that makes - // sense in the caller's context. - public NSMutableArray<Order> OrderHistory - { - get - { - return ManagedData as NSMutableArray<Order>; - } - } + #region Public API for clients of `SoupOrderDataManager` + // Convenience method to access the data with a property name that makes + // sense in the caller's context. + public NSMutableArray<Order> OrderHistory { + get { + return ManagedData as NSMutableArray<Order>; + } + } - public void PlaceOrder(Order order) - { - // Access to `ManagedDataBackingInstance` is only valid on - // `DataAccessQueue`. - DataAccessQueue.DispatchSync(() => - { - if (ManagedDataBackingInstance.Count == 0) - { - // Getting an error trying to insert at 0 for an empty - // NSMutableArray<Order> - ManagedDataBackingInstance.Add(order); - } - else - { - ManagedDataBackingInstance.Insert(order, 0); - } - }); + public void PlaceOrder (Order order) + { + // Access to `ManagedDataBackingInstance` is only valid on + // `DataAccessQueue`. + DataAccessQueue.DispatchSync (() => { + if (ManagedDataBackingInstance.Count == 0) { + // Getting an error trying to insert at 0 for an empty + // NSMutableArray<Order> + ManagedDataBackingInstance.Add (order); + } else { + ManagedDataBackingInstance.Insert (order, 0); + } + }); - // Access to UserDefaults is gated behind a separate access queue. - WriteData(); + // Access to UserDefaults is gated behind a separate access queue. + WriteData (); - // Donate an interaction to the system. - DonateInteraction(order); - } - #endregion + // Donate an interaction to the system. + DonateInteraction (order); + } + #endregion - #region Support methods for unarchiving saved data - override protected void FinishUnarchiving(NSObject unarchivedData) - { - var array = (NSArray)unarchivedData; - Order[] orders = NSArray.FromArray<Order>(array); - ManagedDataBackingInstance = new NSMutableArray<Order>(orders); - } - #endregion - } + #region Support methods for unarchiving saved data + override protected void FinishUnarchiving (NSObject unarchivedData) + { + var array = (NSArray) unarchivedData; + Order [] orders = NSArray.FromArray<Order> (array); + ManagedDataBackingInstance = new NSMutableArray<Order> (orders); + } + #endregion + } } diff --git a/ios12/SoupChef/SoupKit/Data/VoiceShortcutDataManager.cs b/ios12/SoupChef/SoupKit/Data/VoiceShortcutDataManager.cs index 6c6864b05..4596b97ab 100644 --- a/ios12/SoupChef/SoupKit/Data/VoiceShortcutDataManager.cs +++ b/ios12/SoupChef/SoupKit/Data/VoiceShortcutDataManager.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -10,49 +10,42 @@ A data manager that surfaces INVoiceShortcuts managed by INVoiceShortcutCenter. using System.Linq; using SoupChef; -namespace SoupKit.Data -{ - public class VoiceShortcutDataManager - { - INVoiceShortcut[] VoiceShortcuts; +namespace SoupKit.Data { + public class VoiceShortcutDataManager { + INVoiceShortcut [] VoiceShortcuts; - public VoiceShortcutDataManager() - { - UpdateVoiceShortcuts(null); - } + public VoiceShortcutDataManager () + { + UpdateVoiceShortcuts (null); + } - public INVoiceShortcut VoiceShortcutForOrder(Order order) - { - var voiceShortcut = VoiceShortcuts.FirstOrDefault((shortcut) => - { - var intent = shortcut.Shortcut.Intent as OrderSoupIntent; - if (intent is null) { return false; } - var orderFromIntent = Order.FromOrderSoupIntent(intent); - if (orderFromIntent is null) { return false; } - return order.IsEqual(orderFromIntent); - }); - return voiceShortcut; - } + public INVoiceShortcut VoiceShortcutForOrder (Order order) + { + var voiceShortcut = VoiceShortcuts.FirstOrDefault ((shortcut) => { + var intent = shortcut.Shortcut.Intent as OrderSoupIntent; + if (intent is null) { return false; } + var orderFromIntent = Order.FromOrderSoupIntent (intent); + if (orderFromIntent is null) { return false; } + return order.IsEqual (orderFromIntent); + }); + return voiceShortcut; + } - public void UpdateVoiceShortcuts(Action completion) - { - INVoiceShortcutCenter.SharedCenter.GetAllVoiceShortcuts((voiceShortcutsFromCenter, error) => - { - if (voiceShortcutsFromCenter is null) - { - if (!(error is null)) - { - Console.WriteLine($"Failed to fetch voice shortcuts with error {error}"); - } - return; - } - VoiceShortcuts = voiceShortcutsFromCenter; - if (!(completion is null)) - { - completion(); - } - }); - } + public void UpdateVoiceShortcuts (Action completion) + { + INVoiceShortcutCenter.SharedCenter.GetAllVoiceShortcuts ((voiceShortcutsFromCenter, error) => { + if (voiceShortcutsFromCenter is null) { + if (!(error is null)) { + Console.WriteLine ($"Failed to fetch voice shortcuts with error {error}"); + } + return; + } + VoiceShortcuts = voiceShortcutsFromCenter; + if (!(completion is null)) { + completion (); + } + }); + } - } + } } diff --git a/ios12/SoupChef/SoupKit/OrderSoupIntentHandler.cs b/ios12/SoupChef/SoupKit/OrderSoupIntentHandler.cs index e30b83d1b..1cd2c1204 100644 --- a/ios12/SoupChef/SoupKit/OrderSoupIntentHandler.cs +++ b/ios12/SoupChef/SoupKit/OrderSoupIntentHandler.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -9,81 +9,73 @@ using SoupChef; using SoupKit.Data; -namespace SoupKit -{ - public class OrderSoupIntentHandler : OrderSoupIntentHandling - { - override public void ConfirmOrderSoup(OrderSoupIntent intent, Action<OrderSoupIntentResponse> completion) - { - // The confirm phase provides an opportunity for you to perform any - // final validation of the intent parameters and to verify that any - // needed services are available. You might confirm that you can - // communicate with your company’s server. - var soupMenuManager = new SoupMenuManager(); +namespace SoupKit { + public class OrderSoupIntentHandler : OrderSoupIntentHandling { + override public void ConfirmOrderSoup (OrderSoupIntent intent, Action<OrderSoupIntentResponse> completion) + { + // The confirm phase provides an opportunity for you to perform any + // final validation of the intent parameters and to verify that any + // needed services are available. You might confirm that you can + // communicate with your company’s server. + var soupMenuManager = new SoupMenuManager (); - var soup = intent.Soup; - if (soup is null) - { - completion(new OrderSoupIntentResponse(OrderSoupIntentResponseCode.Failure, null)); - return; - } + var soup = intent.Soup; + if (soup is null) { + completion (new OrderSoupIntentResponse (OrderSoupIntentResponseCode.Failure, null)); + return; + } - var identifier = soup.Identifier; - if (identifier is null) - { - completion(new OrderSoupIntentResponse(OrderSoupIntentResponseCode.Failure, null)); - return; - } + var identifier = soup.Identifier; + if (identifier is null) { + completion (new OrderSoupIntentResponse (OrderSoupIntentResponseCode.Failure, null)); + return; + } - var menuItem = soupMenuManager.FindItem(identifier); - if (menuItem is null) - { - completion(new OrderSoupIntentResponse(OrderSoupIntentResponseCode.Failure, null)); - return; - } + var menuItem = soupMenuManager.FindItem (identifier); + if (menuItem is null) { + completion (new OrderSoupIntentResponse (OrderSoupIntentResponseCode.Failure, null)); + return; + } - if (!menuItem.IsAvailable) - { - // Here's an example of how to use a custom response for a - // failure case when a particular soup item is unavailable. - completion(OrderSoupIntentResponse.FailureSoupUnavailableIntentResponseWithSoup(soup)); - return; - } + if (!menuItem.IsAvailable) { + // Here's an example of how to use a custom response for a + // failure case when a particular soup item is unavailable. + completion (OrderSoupIntentResponse.FailureSoupUnavailableIntentResponseWithSoup (soup)); + return; + } - // Once the intent is validated, indicate that the intent is ready - // to handle. - completion(new OrderSoupIntentResponse(OrderSoupIntentResponseCode.Ready, null)); - } + // Once the intent is validated, indicate that the intent is ready + // to handle. + completion (new OrderSoupIntentResponse (OrderSoupIntentResponseCode.Ready, null)); + } - public override void HandleOrderSoup(OrderSoupIntent intent, Action<OrderSoupIntentResponse> completion) - { - var soup = intent.Soup; - if (soup is null) - { - completion(new OrderSoupIntentResponse(OrderSoupIntentResponseCode.Failure, null)); - return; - } + public override void HandleOrderSoup (OrderSoupIntent intent, Action<OrderSoupIntentResponse> completion) + { + var soup = intent.Soup; + if (soup is null) { + completion (new OrderSoupIntentResponse (OrderSoupIntentResponseCode.Failure, null)); + return; + } - var order = Order.FromOrderSoupIntent(intent); - if (order is null) - { - completion(new OrderSoupIntentResponse(OrderSoupIntentResponseCode.Failure, null)); - return; - } + var order = Order.FromOrderSoupIntent (intent); + if (order is null) { + completion (new OrderSoupIntentResponse (OrderSoupIntentResponseCode.Failure, null)); + return; + } - // The handle method is also an appropriate place to handle payment - // via Apple Pay. A declined payment is another example of a - // failure case that could take advantage of a custom response. + // The handle method is also an appropriate place to handle payment + // via Apple Pay. A declined payment is another example of a + // failure case that could take advantage of a custom response. - // Place the soup order via the order manager. - var orderManager = new SoupOrderDataManager(); - orderManager.PlaceOrder(order); + // Place the soup order via the order manager. + var orderManager = new SoupOrderDataManager (); + orderManager.PlaceOrder (order); - // For the success case, we want to indicate a wait time to the - // user so that they know when their soup order will be ready. - // This sample uses a hardcoded value, but your implementation could - // use a time interval returned by your server. - completion(OrderSoupIntentResponse.SuccessIntentResponseWithSoup(soup, 10)); - } - } + // For the success case, we want to indicate a wait time to the + // user so that they know when their soup order will be ready. + // This sample uses a hardcoded value, but your implementation could + // use a time interval returned by your server. + completion (OrderSoupIntentResponse.SuccessIntentResponseWithSoup (soup, 10)); + } + } } diff --git a/ios12/SoupChef/SoupKit/Properties/AssemblyInfo.cs b/ios12/SoupChef/SoupKit/Properties/AssemblyInfo.cs index 6b3906ca9..58d0627e8 100644 --- a/ios12/SoupChef/SoupKit/Properties/AssemblyInfo.cs +++ b/ios12/SoupChef/SoupKit/Properties/AssemblyInfo.cs @@ -1,23 +1,23 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. -[assembly: AssemblyTitle("SoupKit")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("")] -[assembly: AssemblyCopyright("")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("SoupKit")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("")] +[assembly: AssemblyCopyright ("")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. diff --git a/ios12/SoupChef/SoupKit/Support/ILocalizable.cs b/ios12/SoupChef/SoupKit/Support/ILocalizable.cs index b350d2115..e6104e7b8 100644 --- a/ios12/SoupChef/SoupKit/Support/ILocalizable.cs +++ b/ios12/SoupChef/SoupKit/Support/ILocalizable.cs @@ -1,14 +1,11 @@ -using System; +using System; -namespace SoupKit.Support -{ - public interface ILocalizable - { - string LocalizedString { get; } - } +namespace SoupKit.Support { + public interface ILocalizable { + string LocalizedString { get; } + } - public interface ILocalizableCurrency - { - string LocalizedCurrencyValue { get; } - } + public interface ILocalizableCurrency { + string LocalizedCurrencyValue { get; } + } } diff --git a/ios12/SoupChef/SoupKit/Support/NSBundleHelper.cs b/ios12/SoupChef/SoupKit/Support/NSBundleHelper.cs index e68146cda..ac6dd42c8 100644 --- a/ios12/SoupChef/SoupKit/Support/NSBundleHelper.cs +++ b/ios12/SoupChef/SoupKit/Support/NSBundleHelper.cs @@ -1,15 +1,13 @@ -using System; +using System; using Foundation; using SoupKit.Data; using ObjCRuntime; -namespace SoupKit.Support -{ - public static class NSBundleHelper - { - public static NSBundle SoupKitBundle { - get { - return NSBundle.MainBundle; - } - } - } +namespace SoupKit.Support { + public static class NSBundleHelper { + public static NSBundle SoupKitBundle { + get { + return NSBundle.MainBundle; + } + } + } } diff --git a/ios12/SoupChef/SoupKit/Support/NSNumberFormatterHelper.cs b/ios12/SoupChef/SoupKit/Support/NSNumberFormatterHelper.cs index 162ca8f2e..3fdf8ee21 100644 --- a/ios12/SoupChef/SoupKit/Support/NSNumberFormatterHelper.cs +++ b/ios12/SoupChef/SoupKit/Support/NSNumberFormatterHelper.cs @@ -1,17 +1,13 @@ -using System; +using System; using Foundation; -namespace SoupKit.Support -{ - public static class NSNumberFormatterHelper - { - public static NSNumberFormatter CurrencyFormatter - { - get - { - var formatter = new NSNumberFormatter(); - formatter.NumberStyle = NSNumberFormatterStyle.Currency; - return formatter; - } - } - } +namespace SoupKit.Support { + public static class NSNumberFormatterHelper { + public static NSNumberFormatter CurrencyFormatter { + get { + var formatter = new NSNumberFormatter (); + formatter.NumberStyle = NSNumberFormatterStyle.Currency; + return formatter; + } + } + } } diff --git a/ios12/SoupChef/SoupKit/Support/NSUserActivityHelper.cs b/ios12/SoupChef/SoupKit/Support/NSUserActivityHelper.cs index 3c81b33ca..231d9df39 100644 --- a/ios12/SoupChef/SoupKit/Support/NSUserActivityHelper.cs +++ b/ios12/SoupChef/SoupKit/Support/NSUserActivityHelper.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; #if __IOS__ @@ -8,49 +8,43 @@ using System.Xml; #endif -namespace SoupKit.Support -{ - public static class NSUserActivityHelper - { - public static class ActivityKeys - { - public const string MenuItems = "menuItems"; - public const string SegueId = "segueID"; - } - - static string SearchableItemContentType = "Soup Menu"; - - public static string ViewMenuActivityType = "com.xamarin.SoupChef.viewMenu"; - - public static NSUserActivity ViewMenuActivity { - get - { - var userActivity = new NSUserActivity(ViewMenuActivityType) - { - Title = NSBundleHelper.SoupKitBundle.GetLocalizedString("ORDER_LUNCH_TITLE", "View menu activity title"), - EligibleForSearch = true, - EligibleForPrediction = true - }; - - var attributes = new CSSearchableItemAttributeSet(NSUserActivityHelper.SearchableItemContentType) - { - ThumbnailData = UIImage.FromBundle("tomato").AsPNG(), - Keywords = ViewMenuSearchableKeywords, - DisplayName = NSBundleHelper.SoupKitBundle.GetLocalizedString("ORDER_LUNCH_TITLE", "View menu activity title"), - ContentDescription = NSBundleHelper.SoupKitBundle.GetLocalizedString("VIEW_MENU_CONTENT_DESCRIPTION", "View menu content description") - }; - userActivity.ContentAttributeSet = attributes; - - var phrase = NSBundleHelper.SoupKitBundle.GetLocalizedString("ORDER_LUNCH_SUGGESTED_PHRASE", "Voice shortcut suggested phrase"); - userActivity.SuggestedInvocationPhrase = phrase; - return userActivity; - } - } - - static string[] ViewMenuSearchableKeywords = new string[] { - NSBundleHelper.SoupKitBundle.GetLocalizedString("ORDER", "Searchable Keyword"), - NSBundleHelper.SoupKitBundle.GetLocalizedString("SOUP", "Searchable Keyword"), - NSBundleHelper.SoupKitBundle.GetLocalizedString("MENU", "Searchable Keyword") - }; - } +namespace SoupKit.Support { + public static class NSUserActivityHelper { + public static class ActivityKeys { + public const string MenuItems = "menuItems"; + public const string SegueId = "segueID"; + } + + static string SearchableItemContentType = "Soup Menu"; + + public static string ViewMenuActivityType = "com.xamarin.SoupChef.viewMenu"; + + public static NSUserActivity ViewMenuActivity { + get { + var userActivity = new NSUserActivity (ViewMenuActivityType) { + Title = NSBundleHelper.SoupKitBundle.GetLocalizedString ("ORDER_LUNCH_TITLE", "View menu activity title"), + EligibleForSearch = true, + EligibleForPrediction = true + }; + + var attributes = new CSSearchableItemAttributeSet (NSUserActivityHelper.SearchableItemContentType) { + ThumbnailData = UIImage.FromBundle ("tomato").AsPNG (), + Keywords = ViewMenuSearchableKeywords, + DisplayName = NSBundleHelper.SoupKitBundle.GetLocalizedString ("ORDER_LUNCH_TITLE", "View menu activity title"), + ContentDescription = NSBundleHelper.SoupKitBundle.GetLocalizedString ("VIEW_MENU_CONTENT_DESCRIPTION", "View menu content description") + }; + userActivity.ContentAttributeSet = attributes; + + var phrase = NSBundleHelper.SoupKitBundle.GetLocalizedString ("ORDER_LUNCH_SUGGESTED_PHRASE", "Voice shortcut suggested phrase"); + userActivity.SuggestedInvocationPhrase = phrase; + return userActivity; + } + } + + static string [] ViewMenuSearchableKeywords = new string [] { + NSBundleHelper.SoupKitBundle.GetLocalizedString("ORDER", "Searchable Keyword"), + NSBundleHelper.SoupKitBundle.GetLocalizedString("SOUP", "Searchable Keyword"), + NSBundleHelper.SoupKitBundle.GetLocalizedString("MENU", "Searchable Keyword") + }; + } } diff --git a/ios12/SoupChef/SoupKit/Support/NSUserDefaultsHelper.cs b/ios12/SoupChef/SoupKit/Support/NSUserDefaultsHelper.cs index a5dbd03b3..ab21224dc 100644 --- a/ios12/SoupChef/SoupKit/Support/NSUserDefaultsHelper.cs +++ b/ios12/SoupChef/SoupKit/Support/NSUserDefaultsHelper.cs @@ -1,28 +1,24 @@ -using System; +using System; using Foundation; using System.Resources; -namespace SoupKit.Support -{ - public static class NSUserDefaultsHelper - { - private const string AppGroup = "group.com.xamarin.SoupChef"; +namespace SoupKit.Support { + public static class NSUserDefaultsHelper { + private const string AppGroup = "group.com.xamarin.SoupChef"; - public static class StorageKeys - { - public const string SoupMenu = "soupMenu"; - public const string OrderHistory = "orderHistory"; - public const string VoiceShortcutHistory = "voiceShortcutHistory"; - } + public static class StorageKeys { + public const string SoupMenu = "soupMenu"; + public const string OrderHistory = "orderHistory"; + public const string VoiceShortcutHistory = "voiceShortcutHistory"; + } - public static NSUserDefaults DataSuite { - get { - var dataSuite = new NSUserDefaults(AppGroup, NSUserDefaultsType.SuiteName); - if( dataSuite is null ) - { - throw new Exception($"Could not load UserDefaults for app group {AppGroup}"); - } - return dataSuite; - } - } - } + public static NSUserDefaults DataSuite { + get { + var dataSuite = new NSUserDefaults (AppGroup, NSUserDefaultsType.SuiteName); + if (dataSuite is null) { + throw new Exception ($"Could not load UserDefaults for app group {AppGroup}"); + } + return dataSuite; + } + } + } } diff --git a/ios12/SoupChef/SoupKit/UI/MenuItemView.cs b/ios12/SoupChef/SoupKit/UI/MenuItemView.cs index b37175afc..e67a69059 100644 --- a/ios12/SoupChef/SoupKit/UI/MenuItemView.cs +++ b/ios12/SoupChef/SoupKit/UI/MenuItemView.cs @@ -1,68 +1,65 @@ -using System; +using System; using UIKit; using CoreGraphics; using Foundation; using StoreKit; using System.Linq; -namespace SoupKit.UI -{ - [Register("MenuItemView")] - public class MenuItemView : UIView - { - public enum SubView - { - ImageView = 777, - TitleLabel = 888, - SubTitleLabel = 999 - } +namespace SoupKit.UI { + [Register ("MenuItemView")] + public class MenuItemView : UIView { + public enum SubView { + ImageView = 777, + TitleLabel = 888, + SubTitleLabel = 999 + } - public UIImageView ImageView { get; set; } = new UIImageView(CGRect.Empty); - public UILabel TitleLabel { get; set; } = new UILabel(CGRect.Empty); - public UILabel SubTitleLabel { get; set; } = new UILabel(CGRect.Empty); + public UIImageView ImageView { get; set; } = new UIImageView (CGRect.Empty); + public UILabel TitleLabel { get; set; } = new UILabel (CGRect.Empty); + public UILabel SubTitleLabel { get; set; } = new UILabel (CGRect.Empty); - [Export("initWithFrame:")] - public MenuItemView(CGRect rect) : base(rect) - { - SetupView(); - } + [Export ("initWithFrame:")] + public MenuItemView (CGRect rect) : base (rect) + { + SetupView (); + } - [Export("initWithCoder:")] - public MenuItemView(NSCoder coder) : base(coder) - { - SetupView(); - } + [Export ("initWithCoder:")] + public MenuItemView (NSCoder coder) : base (coder) + { + SetupView (); + } - public void SetupView() - { - var bundle = NSBundle.FromClass(this.Class); - var nib = UINib.FromName("MenuItemView", bundle); + public void SetupView () + { + var bundle = NSBundle.FromClass (this.Class); + var nib = UINib.FromName ("MenuItemView", bundle); - var stackView = nib.Instantiate(this, null).FirstOrDefault() as UIStackView; - if (stackView is null) { return; } + var stackView = nib.Instantiate (this, null).FirstOrDefault () as UIStackView; + if (stackView is null) { return; } - var imageView = stackView.ViewWithTag((int)SubView.ImageView) as UIImageView; - if (imageView is null) { return; } + var imageView = stackView.ViewWithTag ((int) SubView.ImageView) as UIImageView; + if (imageView is null) { return; } - var titleLabel = stackView.ViewWithTag((int)SubView.TitleLabel) as UILabel; - if (titleLabel is null) { return; } + var titleLabel = stackView.ViewWithTag ((int) SubView.TitleLabel) as UILabel; + if (titleLabel is null) { return; } - var subTitleLabel = stackView.ViewWithTag((int)SubView.SubTitleLabel) as UILabel; - if (subTitleLabel is null) { return; } + var subTitleLabel = stackView.ViewWithTag ((int) SubView.SubTitleLabel) as UILabel; + if (subTitleLabel is null) { return; } - AddSubview(stackView); - ImageView = imageView; - TitleLabel = titleLabel; - SubTitleLabel = subTitleLabel; + AddSubview (stackView); + ImageView = imageView; + TitleLabel = titleLabel; + SubTitleLabel = subTitleLabel; - ImageView.ClipsToBounds = true; - ImageView.Layer.CornerRadius = 8; - } + ImageView.ClipsToBounds = true; + ImageView.Layer.CornerRadius = 8; + } - #region xamarin - // This constructor is used when Xamarin.iOS needs to create a new - // managed object for an already-existing native object. - public MenuItemView(IntPtr handle) : base(handle) { } - #endregion - } + #region xamarin + // This constructor is used when Xamarin.iOS needs to create a new + // managed object for an already-existing native object. + public MenuItemView (IntPtr handle) : base (handle) { } + #endregion + } } diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/AppDelegate.cs b/ios12/VisionObjectTrack/VisionObjectTrack/AppDelegate.cs index 488975d1a..f97f3f86f 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/AppDelegate.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/AppDelegate.cs @@ -1,24 +1,22 @@ - -namespace VisionObjectTrack -{ - using Foundation; - using UIKit; - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations +namespace VisionObjectTrack { + using Foundation; + using UIKit; - public override UIWindow Window { get; set; } + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override UIWindow Window { get; set; } - return true; - } - } -} \ No newline at end of file + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/AssetsViewController.cs b/ios12/VisionObjectTrack/VisionObjectTrack/AssetsViewController.cs index 40d418b81..eb168323e 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/AssetsViewController.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/AssetsViewController.cs @@ -1,221 +1,186 @@ - -namespace VisionObjectTrack -{ - using AVFoundation; - using CoreFoundation; - using CoreGraphics; - using Foundation; - using Photos; - using System; - using UIKit; - - public partial class AssetsViewController : UICollectionViewController - { - private const string ShowTrackingViewSegueIdentifier = "ShowTrackingView"; - - private PHFetchResult assets; - - public AssetsViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - PHPhotoLibrary.RequestAuthorization((status) => - { - if (status == PHAuthorizationStatus.Authorized) - { - DispatchQueue.MainQueue.DispatchAsync(() => this.LoadAssetsFromLibrary()); - } - }); - } - - public override void ViewDidLayoutSubviews() - { - base.ViewDidLayoutSubviews(); - this.RecalculateItemSize(); - } - - public override bool PrefersStatusBarHidden() - { - return true; - } - - private void LoadAssetsFromLibrary() - { - var assetsOptions = new PHFetchOptions(); - // include all source types - assetsOptions.IncludeAssetSourceTypes = PHAssetSourceType.CloudShared | PHAssetSourceType.UserLibrary | PHAssetSourceType.iTunesSynced; - // show most recent first - assetsOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("modificationDate", false) }; - - // fecth videos - this.assets = PHAsset.FetchAssets(PHAssetMediaType.Video, assetsOptions); - - // setup collection view - this.RecalculateItemSize(); - this.CollectionView?.ReloadData(); - } - - private void RecalculateItemSize() - { - if (this.CollectionView != null) - { - if (this.CollectionView.CollectionViewLayout is UICollectionViewFlowLayout layout) - { - var desiredItemCount = this.TraitCollection.HorizontalSizeClass == UIUserInterfaceSizeClass.Compact ? 4 : 6; - var availableSize = this.CollectionView.Bounds.Width; - - var insets = layout.SectionInset; - availableSize -= (insets.Left + insets.Right); - availableSize -= layout.MinimumInteritemSpacing * (desiredItemCount - 1f); - - var itemSize = Math.Floor(availableSize / desiredItemCount); - if (layout.ItemSize.Width != itemSize) - { - layout.ItemSize = new CGSize(itemSize, itemSize); - layout.InvalidateLayout(); - } - } - } - } - - private PHAsset Asset(string identifier) - { - PHAsset foundAsset = null; - this.assets.Enumerate((NSObject element, nuint index, out bool stop) => - { - if (element is PHAsset asset && asset?.LocalIdentifier == identifier) - { - foundAsset = asset; - stop = true; - } - else - { - stop = false; - } - }); - - return foundAsset; - } - - #region Navigation - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == ShowTrackingViewSegueIdentifier) - { - if (sender is AVAsset avAsset) - { - if (segue.DestinationViewController is TrackingViewController trackingController) - { - trackingController.VideoAsset = avAsset; - } - else - { - throw new Exception("Unexpected destination view controller type"); - } - } - else - { - throw new Exception("Unexpected sender type"); - } - } - } - - #endregion - - #region UICollectionViewDataSource - - public override nint NumberOfSections(UICollectionView collectionView) - { - return 1; - } - - public override nint GetItemsCount(UICollectionView collectionView, nint section) - { - return this.assets?.Count ?? 0; - } - - public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath) - { - UICollectionViewCell result = null; - if (this.assets?[indexPath.Item] is PHAsset asset) - { - var genericCell = collectionView.DequeueReusableCell(AssetsCell.Identifier, indexPath); - if (genericCell is AssetsCell cell) - { - cell.RepresentedAssetIdentifier = asset.LocalIdentifier; - var imageManager = new PHImageManager(); - var options = new PHImageRequestOptions - { - NetworkAccessAllowed = true, - ResizeMode = PHImageRequestOptionsResizeMode.Fast, - DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic, - }; - - imageManager.RequestImageForAsset(asset, cell.Bounds.Size, PHImageContentMode.AspectFill, options, (image, _) => - { - if (asset.LocalIdentifier == cell.RepresentedAssetIdentifier) - { - cell.ImageView.Image = image; - } - }); - - result = cell; - } - else - { - result = genericCell as UICollectionViewCell; - } - } - else - { - throw new Exception($"Failed to find asset at index {indexPath.Item}"); - } - - return result; - } - - #endregion - - #region UICollectionViewDelegate - - public override void ItemSelected(UICollectionView collectionView, NSIndexPath indexPath) - { - if (collectionView.CellForItem(indexPath) is AssetsCell cell) - { - var assetId = cell.RepresentedAssetIdentifier; - var asset = this.Asset(assetId); - if (asset == null) - { - throw new Exception($"Failed to find asset with identifier {assetId}"); - } - - var imageManager = PHImageManager.DefaultManager; - var videoOptions = new PHVideoRequestOptions - { - NetworkAccessAllowed = true, - DeliveryMode = PHVideoRequestOptionsDeliveryMode.HighQualityFormat - }; - - imageManager.RequestAvAsset(asset, videoOptions, (avAsset, _, __) => - { - if (avAsset != null) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.PerformSegue(ShowTrackingViewSegueIdentifier, avAsset); - }); - } - }); - } - else - { - throw new Exception($"Failed to find cell as index path {indexPath}"); - } - } - - #endregion - } -} \ No newline at end of file + +namespace VisionObjectTrack { + using AVFoundation; + using CoreFoundation; + using CoreGraphics; + using Foundation; + using Photos; + using System; + using UIKit; + + public partial class AssetsViewController : UICollectionViewController { + private const string ShowTrackingViewSegueIdentifier = "ShowTrackingView"; + + private PHFetchResult assets; + + public AssetsViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + PHPhotoLibrary.RequestAuthorization ((status) => { + if (status == PHAuthorizationStatus.Authorized) { + DispatchQueue.MainQueue.DispatchAsync (() => this.LoadAssetsFromLibrary ()); + } + }); + } + + public override void ViewDidLayoutSubviews () + { + base.ViewDidLayoutSubviews (); + this.RecalculateItemSize (); + } + + public override bool PrefersStatusBarHidden () + { + return true; + } + + private void LoadAssetsFromLibrary () + { + var assetsOptions = new PHFetchOptions (); + // include all source types + assetsOptions.IncludeAssetSourceTypes = PHAssetSourceType.CloudShared | PHAssetSourceType.UserLibrary | PHAssetSourceType.iTunesSynced; + // show most recent first + assetsOptions.SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor ("modificationDate", false) }; + + // fecth videos + this.assets = PHAsset.FetchAssets (PHAssetMediaType.Video, assetsOptions); + + // setup collection view + this.RecalculateItemSize (); + this.CollectionView?.ReloadData (); + } + + private void RecalculateItemSize () + { + if (this.CollectionView != null) { + if (this.CollectionView.CollectionViewLayout is UICollectionViewFlowLayout layout) { + var desiredItemCount = this.TraitCollection.HorizontalSizeClass == UIUserInterfaceSizeClass.Compact ? 4 : 6; + var availableSize = this.CollectionView.Bounds.Width; + + var insets = layout.SectionInset; + availableSize -= (insets.Left + insets.Right); + availableSize -= layout.MinimumInteritemSpacing * (desiredItemCount - 1f); + + var itemSize = Math.Floor (availableSize / desiredItemCount); + if (layout.ItemSize.Width != itemSize) { + layout.ItemSize = new CGSize (itemSize, itemSize); + layout.InvalidateLayout (); + } + } + } + } + + private PHAsset Asset (string identifier) + { + PHAsset foundAsset = null; + this.assets.Enumerate ((NSObject element, nuint index, out bool stop) => { + if (element is PHAsset asset && asset?.LocalIdentifier == identifier) { + foundAsset = asset; + stop = true; + } else { + stop = false; + } + }); + + return foundAsset; + } + + #region Navigation + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == ShowTrackingViewSegueIdentifier) { + if (sender is AVAsset avAsset) { + if (segue.DestinationViewController is TrackingViewController trackingController) { + trackingController.VideoAsset = avAsset; + } else { + throw new Exception ("Unexpected destination view controller type"); + } + } else { + throw new Exception ("Unexpected sender type"); + } + } + } + + #endregion + + #region UICollectionViewDataSource + + public override nint NumberOfSections (UICollectionView collectionView) + { + return 1; + } + + public override nint GetItemsCount (UICollectionView collectionView, nint section) + { + return this.assets?.Count ?? 0; + } + + public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) + { + UICollectionViewCell result = null; + if (this.assets? [indexPath.Item] is PHAsset asset) { + var genericCell = collectionView.DequeueReusableCell (AssetsCell.Identifier, indexPath); + if (genericCell is AssetsCell cell) { + cell.RepresentedAssetIdentifier = asset.LocalIdentifier; + var imageManager = new PHImageManager (); + var options = new PHImageRequestOptions { + NetworkAccessAllowed = true, + ResizeMode = PHImageRequestOptionsResizeMode.Fast, + DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic, + }; + + imageManager.RequestImageForAsset (asset, cell.Bounds.Size, PHImageContentMode.AspectFill, options, (image, _) => { + if (asset.LocalIdentifier == cell.RepresentedAssetIdentifier) { + cell.ImageView.Image = image; + } + }); + + result = cell; + } else { + result = genericCell as UICollectionViewCell; + } + } else { + throw new Exception ($"Failed to find asset at index {indexPath.Item}"); + } + + return result; + } + + #endregion + + #region UICollectionViewDelegate + + public override void ItemSelected (UICollectionView collectionView, NSIndexPath indexPath) + { + if (collectionView.CellForItem (indexPath) is AssetsCell cell) { + var assetId = cell.RepresentedAssetIdentifier; + var asset = this.Asset (assetId); + if (asset == null) { + throw new Exception ($"Failed to find asset with identifier {assetId}"); + } + + var imageManager = PHImageManager.DefaultManager; + var videoOptions = new PHVideoRequestOptions { + NetworkAccessAllowed = true, + DeliveryMode = PHVideoRequestOptionsDeliveryMode.HighQualityFormat + }; + + imageManager.RequestAvAsset (asset, videoOptions, (avAsset, _, __) => { + if (avAsset != null) { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.PerformSegue (ShowTrackingViewSegueIdentifier, avAsset); + }); + } + }); + } else { + throw new Exception ($"Failed to find cell as index path {indexPath}"); + } + } + + #endregion + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/AssetsCell.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/AssetsCell.cs index 327ec87d3..5c24a430d 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/AssetsCell.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/AssetsCell.cs @@ -1,15 +1,13 @@ - -namespace VisionObjectTrack -{ - using System; - using UIKit; - - public partial class AssetsCell : UICollectionViewCell - { - public const string Identifier = "AssetCell"; - - public string RepresentedAssetIdentifier { get; set; } = string.Empty; - - public AssetsCell (IntPtr handle) : base (handle) { } - } -} \ No newline at end of file + +namespace VisionObjectTrack { + using System; + using UIKit; + + public partial class AssetsCell : UICollectionViewCell { + public const string Identifier = "AssetCell"; + + public string RepresentedAssetIdentifier { get; set; } = string.Empty; + + public AssetsCell (IntPtr handle) : base (handle) { } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/CommonTypes.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/CommonTypes.cs index 595119785..b4ce16df4 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/CommonTypes.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/CommonTypes.cs @@ -1,98 +1,93 @@ - -namespace VisionObjectTrack -{ - using System.Collections.Generic; - using CoreGraphics; - using System; - using UIKit; - using Vision; - using VisionObjectTrack.Enums; - public static class TrackedObjectsPalette - { - private static readonly Random Random = new Random(); +namespace VisionObjectTrack { + using System.Collections.Generic; + using CoreGraphics; + using System; + using UIKit; + using Vision; + using VisionObjectTrack.Enums; - private static List<UIColor> Palette = new List<UIColor> - { - UIColor.Green, - UIColor.Cyan, - UIColor.Orange, - UIColor.Brown, - UIColor.DarkGray, - UIColor.Red, - UIColor.Yellow, - UIColor.Magenta, - UIColor.Gray, - UIColor.Purple, - UIColor.Clear, - UIColor.LightGray, - UIColor.Black, - UIColor.Blue - }; + public static class TrackedObjectsPalette { + private static readonly Random Random = new Random (); - public static UIColor Color(int index) - { - return index < Palette.Count ? Palette[index] : RandomColor(); - } + private static List<UIColor> Palette = new List<UIColor> + { + UIColor.Green, + UIColor.Cyan, + UIColor.Orange, + UIColor.Brown, + UIColor.DarkGray, + UIColor.Red, + UIColor.Yellow, + UIColor.Magenta, + UIColor.Gray, + UIColor.Purple, + UIColor.Clear, + UIColor.LightGray, + UIColor.Black, + UIColor.Blue + }; - private static UIColor RandomColor() - { - return UIColor.FromRGBA(RandomComponent(), RandomComponent(), RandomComponent(), 1f); + public static UIColor Color (int index) + { + return index < Palette.Count ? Palette [index] : RandomColor (); + } - float RandomComponent() - { - return Random.Next(256) / 255f; - } - } - } + private static UIColor RandomColor () + { + return UIColor.FromRGBA (RandomComponent (), RandomComponent (), RandomComponent (), 1f); - public class TrackedPolyRect - { - private readonly CGPoint topLeft; - private readonly CGPoint topRight; - private readonly CGPoint bottomLeft; - private readonly CGPoint bottomRight; + float RandomComponent () + { + return Random.Next (256) / 255f; + } + } + } - public TrackedPolyRect(VNDetectedObjectObservation observation, UIColor color, TrackedPolyRectStyle style = TrackedPolyRectStyle.Solid) - : this(observation.BoundingBox, color, style) { } + public class TrackedPolyRect { + private readonly CGPoint topLeft; + private readonly CGPoint topRight; + private readonly CGPoint bottomLeft; + private readonly CGPoint bottomRight; - public TrackedPolyRect(VNRectangleObservation observation, UIColor color, TrackedPolyRectStyle style = TrackedPolyRectStyle.Solid) - { - this.topLeft = observation.TopLeft; - this.topRight = observation.TopRight; - this.bottomLeft = observation.BottomLeft; - this.bottomRight = observation.BottomRight; - this.Color = color; - this.Style = style; - } + public TrackedPolyRect (VNDetectedObjectObservation observation, UIColor color, TrackedPolyRectStyle style = TrackedPolyRectStyle.Solid) + : this (observation.BoundingBox, color, style) { } - public TrackedPolyRect(CGRect cgRect, UIColor color, TrackedPolyRectStyle style = TrackedPolyRectStyle.Solid) - { - this.topLeft = new CGPoint(cgRect.GetMinX(), cgRect.GetMaxY()); - this.topRight = new CGPoint(cgRect.GetMaxX(), cgRect.GetMaxY()); - this.bottomLeft = new CGPoint(cgRect.GetMinX(), cgRect.GetMinY()); - this.bottomRight = new CGPoint(cgRect.GetMaxX(), cgRect.GetMinY()); - this.Color = color; - this.Style = style; - } + public TrackedPolyRect (VNRectangleObservation observation, UIColor color, TrackedPolyRectStyle style = TrackedPolyRectStyle.Solid) + { + this.topLeft = observation.TopLeft; + this.topRight = observation.TopRight; + this.bottomLeft = observation.BottomLeft; + this.bottomRight = observation.BottomRight; + this.Color = color; + this.Style = style; + } - public UIColor Color { get; private set; } + public TrackedPolyRect (CGRect cgRect, UIColor color, TrackedPolyRectStyle style = TrackedPolyRectStyle.Solid) + { + this.topLeft = new CGPoint (cgRect.GetMinX (), cgRect.GetMaxY ()); + this.topRight = new CGPoint (cgRect.GetMaxX (), cgRect.GetMaxY ()); + this.bottomLeft = new CGPoint (cgRect.GetMinX (), cgRect.GetMinY ()); + this.bottomRight = new CGPoint (cgRect.GetMaxX (), cgRect.GetMinY ()); + this.Color = color; + this.Style = style; + } - public TrackedPolyRectStyle Style { get; private set; } + public UIColor Color { get; private set; } - public IList<CGPoint> CornerPoints => new List<CGPoint> { this.topLeft, this.topRight, this.bottomRight, this.bottomLeft }; + public TrackedPolyRectStyle Style { get; private set; } - public CGRect BoundingBox - { - get - { - var topLeftRect = new CGRect(this.topLeft, CGSize.Empty); - var topRightRect = new CGRect(this.topRight, CGSize.Empty); - var bottomLeftRect = new CGRect(this.bottomLeft, CGSize.Empty); - var bottomRightRect = new CGRect(this.bottomRight, CGSize.Empty); + public IList<CGPoint> CornerPoints => new List<CGPoint> { this.topLeft, this.topRight, this.bottomRight, this.bottomLeft }; - return topLeftRect.UnionWith(topRightRect).UnionWith(bottomLeftRect).UnionWith(bottomRightRect); - } - } - } -} \ No newline at end of file + public CGRect BoundingBox { + get { + var topLeftRect = new CGRect (this.topLeft, CGSize.Empty); + var topRightRect = new CGRect (this.topRight, CGSize.Empty); + var bottomLeftRect = new CGRect (this.bottomLeft, CGSize.Empty); + var bottomRightRect = new CGRect (this.bottomRight, CGSize.Empty); + + return topLeftRect.UnionWith (topRightRect).UnionWith (bottomLeftRect).UnionWith (bottomRightRect); + } + } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedObjectType.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedObjectType.cs index 67580f0d5..678ae1721 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedObjectType.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedObjectType.cs @@ -1,9 +1,7 @@ - -namespace VisionObjectTrack.Enums -{ - public enum TrackedObjectType - { - Object, - Rectangle, - } -} \ No newline at end of file + +namespace VisionObjectTrack.Enums { + public enum TrackedObjectType { + Object, + Rectangle, + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedPolyRectStyle.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedPolyRectStyle.cs index c8ff74795..4ea6f696e 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedPolyRectStyle.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/TrackedPolyRectStyle.cs @@ -1,9 +1,7 @@ - -namespace VisionObjectTrack.Enums -{ - public enum TrackedPolyRectStyle - { - Solid, - Dashed, - } -} \ No newline at end of file + +namespace VisionObjectTrack.Enums { + public enum TrackedPolyRectStyle { + Solid, + Dashed, + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/VisionTrackerProcessorErrorType.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/VisionTrackerProcessorErrorType.cs index d3a995d5b..35f346d90 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/VisionTrackerProcessorErrorType.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/Enums/VisionTrackerProcessorErrorType.cs @@ -1,11 +1,9 @@ - -namespace VisionObjectTrack.Enums -{ - public enum VisionTrackerProcessorErrorType - { - ReaderInitializationFailed, - FirstFrameReadFailed, - ObjectTrackingFailed, - RectangleDetectionFailed, - } -} \ No newline at end of file + +namespace VisionObjectTrack.Enums { + public enum VisionTrackerProcessorErrorType { + ReaderInitializationFailed, + FirstFrameReadFailed, + ObjectTrackingFailed, + RectangleDetectionFailed, + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/TrackingImageView.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/TrackingImageView.cs index 4a23d83ac..c627221b0 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/TrackingImageView.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/TrackingImageView.cs @@ -1,199 +1,183 @@ -namespace VisionObjectTrack -{ - using CoreGraphics; - using System; - using System.Collections.Generic; - using UIKit; - using VisionObjectTrack.Enums; - - public partial class TrackingImageView : UIView - { - private CGRect imageAreaRect = CGRect.Empty; - - private readonly nfloat[] dashedLinesLengths = { 4f, 2f }; - - private float dashedPhase = 0f; - - public TrackingImageView(IntPtr handle) : base(handle) { } - - public UIImage Image { get; set; } - - public List<TrackedPolyRect> PolyRects { get; set; } = new List<TrackedPolyRect>(); - - // Rubber-banding setup - - public CGPoint RubberbandingStart { get; set; } = CGPoint.Empty; - - public CGPoint RubberbandingVector { get; set; } = CGPoint.Empty; - - protected CGRect RubberbandingRect - { - get - { - var pt1 = this.RubberbandingStart; - var pt2 = new CGPoint(this.RubberbandingStart.X + this.RubberbandingVector.X, - this.RubberbandingStart.Y + this.RubberbandingVector.Y); - - return new CGRect(Math.Min(pt1.X, pt2.X), - Math.Min(pt1.Y, pt2.Y), - Math.Abs(pt1.X - pt2.X), - Math.Abs(pt1.Y - pt2.Y)); - } - } - - public CGRect RubberbandingRectNormalized - { - get - { - var result = CGRect.Empty; - if (this.imageAreaRect.Size.Width > 0 && this.imageAreaRect.Size.Height > 0) - { - result = this.RubberbandingRect; - - // Make it relative to imageAreaRect - result.X = (result.X - this.imageAreaRect.X) / this.imageAreaRect.Width; - result.Y = (result.Y - this.imageAreaRect.Y) / this.imageAreaRect.Height; - result.Width /= this.imageAreaRect.Width; - result.Height /= this.imageAreaRect.Height; - - // Adjust to Vision.framework input requrement - origin at LLC - result.Y = 1f - result.Y - result.Height; - - } - - return result; - } - } - - public bool IsPointWithinDrawingArea(CGPoint locationInView) - { - return this.imageAreaRect.Contains(locationInView); - } - - public override void LayoutSubviews() - { - base.LayoutSubviews(); - this.SetNeedsDisplay(); - } - - public override void Draw(CGRect rect) - { - var context = UIGraphics.GetCurrentContext(); - - context.SaveState(); - - context.ClearRect(rect); - context.SetFillColor(0f, 0f, 0f, 0f); - context.SetLineWidth(2f); - - // Draw a frame - var newImage = this.ScaleImage(rect.Size); - if (newImage != null) - { - newImage.Draw(this.imageAreaRect); - - // Draw rubberbanding rectangle, if available - if (this.RubberbandingRect != CGRect.Empty) - { - context.SetStrokeColor(UIColor.Blue.CGColor); - - // Switch to dashed lines for rubberbanding selection - context.SetLineDash(this.dashedPhase, this.dashedLinesLengths); - context.StrokeRect(this.RubberbandingRect); - } - - // Draw rects - foreach(var polyRect in this.PolyRects) - { - context.SetStrokeColor(polyRect.Color.CGColor); - switch (polyRect.Style) - { - case TrackedPolyRectStyle.Solid: - context.SetLineDash(this.dashedPhase, new nfloat[] { }); - break; - case TrackedPolyRectStyle.Dashed: - context.SetLineDash(this.dashedPhase, this.dashedLinesLengths); - break; - } - - var cornerPoints = polyRect.CornerPoints; - var previous = this.Scale(cornerPoints[cornerPoints.Count - 1], rect); - foreach(var cornerPoint in cornerPoints) - { - context.MoveTo(previous.X, previous.Y); - var current = this.Scale(cornerPoint, rect); - - context.AddLineToPoint(current.X, current.Y); - previous = current; - } - - context.StrokePath(); - } - - context.RestoreState(); - } - } - - private UIImage ScaleImage(CGSize viewSize) - { - UIImage result = null; - if (this.Image != null && this.Image.Size != CGSize.Empty) - { - this.imageAreaRect = CGRect.Empty; - - // There are two possible cases to fully fit self.image into the the ImageTrackingView area: - // Option 1) image.width = view.width ==> image.height <= view.height - // Option 2) image.height = view.height ==> image.width <= view.width - var imageAspectRatio = this.Image.Size.Width / this.Image.Size.Height; - - // Check if we're in Option 1) case and initialize self.imageAreaRect accordingly - var imageSizeOption1 = new CGSize(viewSize.Width, Math.Floor(viewSize.Width / imageAspectRatio)); - if (imageSizeOption1.Height <= viewSize.Height) - { - var imageX = 0f; - var imageY = Math.Floor((viewSize.Height - imageSizeOption1.Height) / 2f); - this.imageAreaRect = new CGRect(imageX, - imageY, - imageSizeOption1.Width, - imageSizeOption1.Height); - } - - if (this.imageAreaRect == CGRect.Empty) - { - // Check if we're in Option 2) case if Option 1) didn't work out and initialize imageAreaRect accordingly - var imageSizeOption2 = new CGSize(Math.Floor(viewSize.Height * imageAspectRatio), viewSize.Height); - if (imageSizeOption2.Width <= viewSize.Width) - { - var imageX = Math.Floor((viewSize.Width - imageSizeOption2.Width) / 2f); - var imageY = 0f; - this.imageAreaRect = new CGRect(imageX, - imageY, - imageSizeOption2.Width, - imageSizeOption2.Height); - } - } - - // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution). - // Pass 1.0 to force exact pixel size. - UIGraphics.BeginImageContextWithOptions(this.imageAreaRect.Size, false, 0f); - this.Image.Draw(new CGRect(0f, 0f, this.imageAreaRect.Size.Width, this.imageAreaRect.Size.Height)); - - result = UIGraphics.GetImageFromCurrentImageContext(); - UIGraphics.EndImageContext(); - } - - return result; - } - - private CGPoint Scale(CGPoint point, CGRect viewRect) - { - // Adjust bBox from Vision.framework coordinate system (origin at LLC) to imageView coordinate system (origin at ULC) - var pointY = 1f - point.Y; - var scaleFactor = this.imageAreaRect.Size; - - return new CGPoint(point.X * scaleFactor.Width + this.imageAreaRect.X, - pointY * scaleFactor.Height + this.imageAreaRect.Y); - } - } -} \ No newline at end of file +namespace VisionObjectTrack { + using CoreGraphics; + using System; + using System.Collections.Generic; + using UIKit; + using VisionObjectTrack.Enums; + + public partial class TrackingImageView : UIView { + private CGRect imageAreaRect = CGRect.Empty; + + private readonly nfloat [] dashedLinesLengths = { 4f, 2f }; + + private float dashedPhase = 0f; + + public TrackingImageView (IntPtr handle) : base (handle) { } + + public UIImage Image { get; set; } + + public List<TrackedPolyRect> PolyRects { get; set; } = new List<TrackedPolyRect> (); + + // Rubber-banding setup + + public CGPoint RubberbandingStart { get; set; } = CGPoint.Empty; + + public CGPoint RubberbandingVector { get; set; } = CGPoint.Empty; + + protected CGRect RubberbandingRect { + get { + var pt1 = this.RubberbandingStart; + var pt2 = new CGPoint (this.RubberbandingStart.X + this.RubberbandingVector.X, + this.RubberbandingStart.Y + this.RubberbandingVector.Y); + + return new CGRect (Math.Min (pt1.X, pt2.X), + Math.Min (pt1.Y, pt2.Y), + Math.Abs (pt1.X - pt2.X), + Math.Abs (pt1.Y - pt2.Y)); + } + } + + public CGRect RubberbandingRectNormalized { + get { + var result = CGRect.Empty; + if (this.imageAreaRect.Size.Width > 0 && this.imageAreaRect.Size.Height > 0) { + result = this.RubberbandingRect; + + // Make it relative to imageAreaRect + result.X = (result.X - this.imageAreaRect.X) / this.imageAreaRect.Width; + result.Y = (result.Y - this.imageAreaRect.Y) / this.imageAreaRect.Height; + result.Width /= this.imageAreaRect.Width; + result.Height /= this.imageAreaRect.Height; + + // Adjust to Vision.framework input requrement - origin at LLC + result.Y = 1f - result.Y - result.Height; + + } + + return result; + } + } + + public bool IsPointWithinDrawingArea (CGPoint locationInView) + { + return this.imageAreaRect.Contains (locationInView); + } + + public override void LayoutSubviews () + { + base.LayoutSubviews (); + this.SetNeedsDisplay (); + } + + public override void Draw (CGRect rect) + { + var context = UIGraphics.GetCurrentContext (); + + context.SaveState (); + + context.ClearRect (rect); + context.SetFillColor (0f, 0f, 0f, 0f); + context.SetLineWidth (2f); + + // Draw a frame + var newImage = this.ScaleImage (rect.Size); + if (newImage != null) { + newImage.Draw (this.imageAreaRect); + + // Draw rubberbanding rectangle, if available + if (this.RubberbandingRect != CGRect.Empty) { + context.SetStrokeColor (UIColor.Blue.CGColor); + + // Switch to dashed lines for rubberbanding selection + context.SetLineDash (this.dashedPhase, this.dashedLinesLengths); + context.StrokeRect (this.RubberbandingRect); + } + + // Draw rects + foreach (var polyRect in this.PolyRects) { + context.SetStrokeColor (polyRect.Color.CGColor); + switch (polyRect.Style) { + case TrackedPolyRectStyle.Solid: + context.SetLineDash (this.dashedPhase, new nfloat [] { }); + break; + case TrackedPolyRectStyle.Dashed: + context.SetLineDash (this.dashedPhase, this.dashedLinesLengths); + break; + } + + var cornerPoints = polyRect.CornerPoints; + var previous = this.Scale (cornerPoints [cornerPoints.Count - 1], rect); + foreach (var cornerPoint in cornerPoints) { + context.MoveTo (previous.X, previous.Y); + var current = this.Scale (cornerPoint, rect); + + context.AddLineToPoint (current.X, current.Y); + previous = current; + } + + context.StrokePath (); + } + + context.RestoreState (); + } + } + + private UIImage ScaleImage (CGSize viewSize) + { + UIImage result = null; + if (this.Image != null && this.Image.Size != CGSize.Empty) { + this.imageAreaRect = CGRect.Empty; + + // There are two possible cases to fully fit self.image into the the ImageTrackingView area: + // Option 1) image.width = view.width ==> image.height <= view.height + // Option 2) image.height = view.height ==> image.width <= view.width + var imageAspectRatio = this.Image.Size.Width / this.Image.Size.Height; + + // Check if we're in Option 1) case and initialize self.imageAreaRect accordingly + var imageSizeOption1 = new CGSize (viewSize.Width, Math.Floor (viewSize.Width / imageAspectRatio)); + if (imageSizeOption1.Height <= viewSize.Height) { + var imageX = 0f; + var imageY = Math.Floor ((viewSize.Height - imageSizeOption1.Height) / 2f); + this.imageAreaRect = new CGRect (imageX, + imageY, + imageSizeOption1.Width, + imageSizeOption1.Height); + } + + if (this.imageAreaRect == CGRect.Empty) { + // Check if we're in Option 2) case if Option 1) didn't work out and initialize imageAreaRect accordingly + var imageSizeOption2 = new CGSize (Math.Floor (viewSize.Height * imageAspectRatio), viewSize.Height); + if (imageSizeOption2.Width <= viewSize.Width) { + var imageX = Math.Floor ((viewSize.Width - imageSizeOption2.Width) / 2f); + var imageY = 0f; + this.imageAreaRect = new CGRect (imageX, + imageY, + imageSizeOption2.Width, + imageSizeOption2.Height); + } + } + + // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution). + // Pass 1.0 to force exact pixel size. + UIGraphics.BeginImageContextWithOptions (this.imageAreaRect.Size, false, 0f); + this.Image.Draw (new CGRect (0f, 0f, this.imageAreaRect.Size.Width, this.imageAreaRect.Size.Height)); + + result = UIGraphics.GetImageFromCurrentImageContext (); + UIGraphics.EndImageContext (); + } + + return result; + } + + private CGPoint Scale (CGPoint point, CGRect viewRect) + { + // Adjust bBox from Vision.framework coordinate system (origin at LLC) to imageView coordinate system (origin at ULC) + var pointY = 1f - point.Y; + var scaleFactor = this.imageAreaRect.Size; + + return new CGPoint (point.X * scaleFactor.Width + this.imageAreaRect.X, + pointY * scaleFactor.Height + this.imageAreaRect.Y); + } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VideoReader.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VideoReader.cs index c7f7e6cf3..d864d5372 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VideoReader.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VideoReader.cs @@ -1,121 +1,109 @@ - -namespace VisionObjectTrack -{ - using AVFoundation; - using CoreGraphics; - using CoreVideo; - using Foundation; - using ImageIO; - using System; - - /// <summary> - /// Contains the video reader implementation using AVCapture. - /// </summary> - public class VideoReader - { - private const float MillisecondsInSecond = 1000f; - - private AVAsset videoAsset; - private AVAssetTrack videoTrack; - private AVAssetReader assetReader; - private AVAssetReaderTrackOutput videoAssetReaderOutput; - - protected float FrameRateInMilliseconds => this.videoTrack.NominalFrameRate; - - public float FrameRateInSeconds => this.FrameRateInMilliseconds * MillisecondsInSecond; - - public CGAffineTransform AffineTransform => this.videoTrack.PreferredTransform.Invert(); - - public CGImagePropertyOrientation Orientation - { - get - { - var orientation = 1; - var angleInDegrees = Math.Atan2(this.AffineTransform.yx, this.AffineTransform.xx) * 180 / Math.PI; - switch (angleInDegrees) - { - case 0: - orientation = 1; // Recording button is on the right - break; - - case 180: - orientation = 3; // abs(180) degree rotation recording button is on the right - break; - - case -180: - orientation = 3; // abs(180) degree rotation recording button is on the right - break; - - case 90: - orientation = 8; // 90 degree CW rotation recording button is on the top - break; - - case -90: - orientation = 6; // 90 degree CCW rotation recording button is on the bottom - break; - - default: - orientation = 1; - break; - } - - return (CGImagePropertyOrientation)orientation; - } - } - - public static VideoReader Create(AVAsset videoAsset) - { - var result = new VideoReader { videoAsset = videoAsset }; - var array = result.videoAsset.TracksWithMediaType(AVMediaType.Video); - result.videoTrack = array[0]; - - if(!result.RestartReading()) - { - result = null; - } - - return result; - } - - public bool RestartReading() - { - var result = false; - - this.assetReader = AVAssetReader.FromAsset(this.videoAsset, out NSError error); - if (error == null) - { - var settings = new AVVideoSettingsUncompressed { PixelFormatType = CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange }; - this.videoAssetReaderOutput = new AVAssetReaderTrackOutput(this.videoTrack, settings); - if (this.videoAssetReaderOutput != null) - { - this.videoAssetReaderOutput.AlwaysCopiesSampleData = true; - - if (this.assetReader.CanAddOutput(this.videoAssetReaderOutput)) - { - this.assetReader.AddOutput(this.videoAssetReaderOutput); - result = this.assetReader.StartReading(); - } - } - } - else - { - Console.WriteLine($"Failed to create AVAssetReader object: {error}"); - } - - return result; - } - - public CVPixelBuffer NextFrame() - { - CVPixelBuffer result = null; - - var sampleBuffer = this.videoAssetReaderOutput.CopyNextSampleBuffer(); - if(sampleBuffer != null) - { - result = sampleBuffer.GetImageBuffer() as CVPixelBuffer; - } - - return result; - } - } -} \ No newline at end of file + +namespace VisionObjectTrack { + using AVFoundation; + using CoreGraphics; + using CoreVideo; + using Foundation; + using ImageIO; + using System; + + /// <summary> + /// Contains the video reader implementation using AVCapture. + /// </summary> + public class VideoReader { + private const float MillisecondsInSecond = 1000f; + + private AVAsset videoAsset; + private AVAssetTrack videoTrack; + private AVAssetReader assetReader; + private AVAssetReaderTrackOutput videoAssetReaderOutput; + + protected float FrameRateInMilliseconds => this.videoTrack.NominalFrameRate; + + public float FrameRateInSeconds => this.FrameRateInMilliseconds * MillisecondsInSecond; + + public CGAffineTransform AffineTransform => this.videoTrack.PreferredTransform.Invert (); + + public CGImagePropertyOrientation Orientation { + get { + var orientation = 1; + var angleInDegrees = Math.Atan2 (this.AffineTransform.yx, this.AffineTransform.xx) * 180 / Math.PI; + switch (angleInDegrees) { + case 0: + orientation = 1; // Recording button is on the right + break; + + case 180: + orientation = 3; // abs(180) degree rotation recording button is on the right + break; + + case -180: + orientation = 3; // abs(180) degree rotation recording button is on the right + break; + + case 90: + orientation = 8; // 90 degree CW rotation recording button is on the top + break; + + case -90: + orientation = 6; // 90 degree CCW rotation recording button is on the bottom + break; + + default: + orientation = 1; + break; + } + + return (CGImagePropertyOrientation) orientation; + } + } + + public static VideoReader Create (AVAsset videoAsset) + { + var result = new VideoReader { videoAsset = videoAsset }; + var array = result.videoAsset.TracksWithMediaType (AVMediaType.Video); + result.videoTrack = array [0]; + + if (!result.RestartReading ()) { + result = null; + } + + return result; + } + + public bool RestartReading () + { + var result = false; + + this.assetReader = AVAssetReader.FromAsset (this.videoAsset, out NSError error); + if (error == null) { + var settings = new AVVideoSettingsUncompressed { PixelFormatType = CVPixelFormatType.CV420YpCbCr8BiPlanarFullRange }; + this.videoAssetReaderOutput = new AVAssetReaderTrackOutput (this.videoTrack, settings); + if (this.videoAssetReaderOutput != null) { + this.videoAssetReaderOutput.AlwaysCopiesSampleData = true; + + if (this.assetReader.CanAddOutput (this.videoAssetReaderOutput)) { + this.assetReader.AddOutput (this.videoAssetReaderOutput); + result = this.assetReader.StartReading (); + } + } + } else { + Console.WriteLine ($"Failed to create AVAssetReader object: {error}"); + } + + return result; + } + + public CVPixelBuffer NextFrame () + { + CVPixelBuffer result = null; + + var sampleBuffer = this.videoAssetReaderOutput.CopyNextSampleBuffer (); + if (sampleBuffer != null) { + result = sampleBuffer.GetImageBuffer () as CVPixelBuffer; + } + + return result; + } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessor.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessor.cs index 726bf955e..5e75b1780 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessor.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessor.cs @@ -1,248 +1,213 @@ - -namespace VisionObjectTrack -{ - using AVFoundation; - using CoreGraphics; - using CoreVideo; - using Foundation; - using System.Collections.Generic; - using System.Linq; - using Vision; - using VisionObjectTrack.Enums; - - public interface IVisionTrackerProcessorDelegate - { - void DisplayFrame(CVPixelBuffer frame, CGAffineTransform transform, IList<TrackedPolyRect> rects); - void DisplayFrameCounter(int frame); - void DidFinifshTracking(); - } - - /// <summary> - /// Contains the tracker processing logic using Vision. - /// </summary> - public class VisionTrackerProcessor - { - private List<VNRectangleObservation> initialRectObservations = new List<VNRectangleObservation>(); - - private readonly AVAsset videoAsset; - - private bool cancelRequested; - - public VisionTrackerProcessor(AVAsset videoAsset) - { - this.videoAsset = videoAsset; - } - - public IVisionTrackerProcessorDelegate Delegate { get; set; } - - public VNRequestTrackingLevel TrackingLevel { get; set; } = VNRequestTrackingLevel.Accurate; - - public List<TrackedPolyRect> ObjectsToTrack { get; set; } = new List<TrackedPolyRect>(); - - /// <summary> - /// Set Initial Condition - /// </summary> - public void ReadAndDisplayFirstFrame(bool performRectanglesDetection, out NSError error) - { - var videoReader = VideoReader.Create(this.videoAsset); - if (videoReader != null) - { - var firstFrame = videoReader.NextFrame(); - if (firstFrame != null) - { - List<TrackedPolyRect> firstFrameRects = null; - if (performRectanglesDetection) - { - // Vision Rectangle Detection - var imageRequestHandler = new VNImageRequestHandler(firstFrame, videoReader.Orientation, new NSMutableDictionary()); - - var rectangleDetectionRequest = new VNDetectRectanglesRequest(null) - { - MinimumAspectRatio = 0.2f, - MaximumAspectRatio = 1f, - MinimumSize = 0.1f, - MaximumObservations = 10 - }; - - imageRequestHandler.Perform(new VNRequest[] { rectangleDetectionRequest }, out NSError performError); - if (performError != null) - { - error = new VisionTrackerProcessorError(VisionTrackerProcessorErrorType.FirstFrameReadFailed); - return; - } - - var rectObservations = rectangleDetectionRequest.GetResults<VNRectangleObservation>(); - if (rectObservations != null && rectObservations.Any()) - { - this.initialRectObservations = rectObservations.ToList(); - var detectedRects = new List<TrackedPolyRect>(); - for (var index = 0; index < this.initialRectObservations.Count; index++) - { - var rectangleObservation = this.initialRectObservations[index]; - var rectColor = TrackedObjectsPalette.Color(index); - - detectedRects.Add(new TrackedPolyRect(rectangleObservation, rectColor)); - } - - firstFrameRects = detectedRects; - } - } - - error = null; - this.Delegate?.DisplayFrame(firstFrame, videoReader.AffineTransform, firstFrameRects); - } - else - { - error = new VisionTrackerProcessorError(VisionTrackerProcessorErrorType.FirstFrameReadFailed); - } - } - else - { - error = new VisionTrackerProcessorError(VisionTrackerProcessorErrorType.ReaderInitializationFailed); - } - } - - /// <summary> - /// Perform Requests - /// </summary> - public void PerformTracking(TrackedObjectType type, out NSError error) - { - var videoReader = VideoReader.Create(videoAsset); - if (videoReader != null) - { - if (videoReader.NextFrame() != null) - { - this.cancelRequested = false; - - // Create initial observations - var inputObservations = new Dictionary<NSUuid, VNDetectedObjectObservation>(); - var trackedObjects = new Dictionary<NSUuid, TrackedPolyRect>(); - switch (type) - { - case TrackedObjectType.Object: - foreach (var rect in this.ObjectsToTrack) - { - var inputObservation = VNDetectedObjectObservation.FromBoundingBox(rect.BoundingBox); - inputObservations[inputObservation.Uuid] = inputObservation; - trackedObjects[inputObservation.Uuid] = rect; - } - break; - - case TrackedObjectType.Rectangle: - foreach (var rectangleObservation in this.initialRectObservations) - { - inputObservations[rectangleObservation.Uuid] = rectangleObservation; - var rectColor = TrackedObjectsPalette.Color(trackedObjects.Count); - trackedObjects[rectangleObservation.Uuid] = new TrackedPolyRect(rectangleObservation, rectColor); - } - break; - } - - var requestHandler = new VNSequenceRequestHandler(); - var frames = 1; - var trackingFailedForAtLeastOneObject = false; - - CVPixelBuffer frame = null; - while (true) - { - if (this.cancelRequested || (frame = videoReader.NextFrame()) == null) - { - break; - } - - this.Delegate?.DisplayFrameCounter(frames); - frames += 1; - - var rects = new List<TrackedPolyRect>(); - var trackingRequests = new List<VNRequest>(); - foreach (var inputObservation in inputObservations) - { - VNTrackingRequest request = null; - switch (type) - { - case TrackedObjectType.Object: - request = new VNTrackObjectRequest(inputObservation.Value); - break; - - case TrackedObjectType.Rectangle: - if (inputObservation.Value is VNRectangleObservation rectObservation) - { - request = new VNTrackRectangleRequest(rectObservation); - } - else - { - continue; - } - break; - } - - request.TrackingLevel = this.TrackingLevel; - trackingRequests.Add(request); - } - - // Perform array of requests - requestHandler.Perform(trackingRequests.ToArray(), frame, videoReader.Orientation, out NSError performError); - trackingFailedForAtLeastOneObject = performError != null; - - foreach (var processedRequest in trackingRequests) - { - var results = processedRequest.GetResults<VNObservation>(); - if (results == null || !results.Any()) - { - continue; - } - - if (results.FirstOrDefault() is VNDetectedObjectObservation observation) - { - // Assume threshold = 0.5f - var rectStyle = observation.Confidence > 0.5f ? TrackedPolyRectStyle.Solid : TrackedPolyRectStyle.Dashed; - var knownRect = trackedObjects[observation.Uuid]; - - switch (type) - { - case TrackedObjectType.Object: - rects.Add(new TrackedPolyRect(observation, knownRect.Color, rectStyle)); - break; - - case TrackedObjectType.Rectangle: - if (observation is VNRectangleObservation rectObservation) - { - rects.Add(new TrackedPolyRect(rectObservation, knownRect.Color, rectStyle)); - } - break; - } - - // Initialize inputObservation for the next iteration - inputObservations[observation.Uuid] = observation; - } - } - - // Draw results - this.Delegate?.DisplayFrame(frame, videoReader.AffineTransform, rects); - - var miliseconds = videoReader.FrameRateInSeconds / 1000; - System.Threading.Thread.Sleep((int)miliseconds); - } - - this.Delegate?.DidFinifshTracking(); - - error = trackingFailedForAtLeastOneObject ? new VisionTrackerProcessorError(VisionTrackerProcessorErrorType.FirstFrameReadFailed) - : null; - } - else - { - error = new VisionTrackerProcessorError(VisionTrackerProcessorErrorType.FirstFrameReadFailed); - } - } - else - { - error = new VisionTrackerProcessorError(VisionTrackerProcessorErrorType.ReaderInitializationFailed); - } - } - - public void CancelTracking() - { - this.cancelRequested = true; - } - } -} \ No newline at end of file + +namespace VisionObjectTrack { + using AVFoundation; + using CoreGraphics; + using CoreVideo; + using Foundation; + using System.Collections.Generic; + using System.Linq; + using Vision; + using VisionObjectTrack.Enums; + + public interface IVisionTrackerProcessorDelegate { + void DisplayFrame (CVPixelBuffer frame, CGAffineTransform transform, IList<TrackedPolyRect> rects); + void DisplayFrameCounter (int frame); + void DidFinifshTracking (); + } + + /// <summary> + /// Contains the tracker processing logic using Vision. + /// </summary> + public class VisionTrackerProcessor { + private List<VNRectangleObservation> initialRectObservations = new List<VNRectangleObservation> (); + + private readonly AVAsset videoAsset; + + private bool cancelRequested; + + public VisionTrackerProcessor (AVAsset videoAsset) + { + this.videoAsset = videoAsset; + } + + public IVisionTrackerProcessorDelegate Delegate { get; set; } + + public VNRequestTrackingLevel TrackingLevel { get; set; } = VNRequestTrackingLevel.Accurate; + + public List<TrackedPolyRect> ObjectsToTrack { get; set; } = new List<TrackedPolyRect> (); + + /// <summary> + /// Set Initial Condition + /// </summary> + public void ReadAndDisplayFirstFrame (bool performRectanglesDetection, out NSError error) + { + var videoReader = VideoReader.Create (this.videoAsset); + if (videoReader != null) { + var firstFrame = videoReader.NextFrame (); + if (firstFrame != null) { + List<TrackedPolyRect> firstFrameRects = null; + if (performRectanglesDetection) { + // Vision Rectangle Detection + var imageRequestHandler = new VNImageRequestHandler (firstFrame, videoReader.Orientation, new NSMutableDictionary ()); + + var rectangleDetectionRequest = new VNDetectRectanglesRequest (null) { + MinimumAspectRatio = 0.2f, + MaximumAspectRatio = 1f, + MinimumSize = 0.1f, + MaximumObservations = 10 + }; + + imageRequestHandler.Perform (new VNRequest [] { rectangleDetectionRequest }, out NSError performError); + if (performError != null) { + error = new VisionTrackerProcessorError (VisionTrackerProcessorErrorType.FirstFrameReadFailed); + return; + } + + var rectObservations = rectangleDetectionRequest.GetResults<VNRectangleObservation> (); + if (rectObservations != null && rectObservations.Any ()) { + this.initialRectObservations = rectObservations.ToList (); + var detectedRects = new List<TrackedPolyRect> (); + for (var index = 0; index < this.initialRectObservations.Count; index++) { + var rectangleObservation = this.initialRectObservations [index]; + var rectColor = TrackedObjectsPalette.Color (index); + + detectedRects.Add (new TrackedPolyRect (rectangleObservation, rectColor)); + } + + firstFrameRects = detectedRects; + } + } + + error = null; + this.Delegate?.DisplayFrame (firstFrame, videoReader.AffineTransform, firstFrameRects); + } else { + error = new VisionTrackerProcessorError (VisionTrackerProcessorErrorType.FirstFrameReadFailed); + } + } else { + error = new VisionTrackerProcessorError (VisionTrackerProcessorErrorType.ReaderInitializationFailed); + } + } + + /// <summary> + /// Perform Requests + /// </summary> + public void PerformTracking (TrackedObjectType type, out NSError error) + { + var videoReader = VideoReader.Create (videoAsset); + if (videoReader != null) { + if (videoReader.NextFrame () != null) { + this.cancelRequested = false; + + // Create initial observations + var inputObservations = new Dictionary<NSUuid, VNDetectedObjectObservation> (); + var trackedObjects = new Dictionary<NSUuid, TrackedPolyRect> (); + switch (type) { + case TrackedObjectType.Object: + foreach (var rect in this.ObjectsToTrack) { + var inputObservation = VNDetectedObjectObservation.FromBoundingBox (rect.BoundingBox); + inputObservations [inputObservation.Uuid] = inputObservation; + trackedObjects [inputObservation.Uuid] = rect; + } + break; + + case TrackedObjectType.Rectangle: + foreach (var rectangleObservation in this.initialRectObservations) { + inputObservations [rectangleObservation.Uuid] = rectangleObservation; + var rectColor = TrackedObjectsPalette.Color (trackedObjects.Count); + trackedObjects [rectangleObservation.Uuid] = new TrackedPolyRect (rectangleObservation, rectColor); + } + break; + } + + var requestHandler = new VNSequenceRequestHandler (); + var frames = 1; + var trackingFailedForAtLeastOneObject = false; + + CVPixelBuffer frame = null; + while (true) { + if (this.cancelRequested || (frame = videoReader.NextFrame ()) == null) { + break; + } + + this.Delegate?.DisplayFrameCounter (frames); + frames += 1; + + var rects = new List<TrackedPolyRect> (); + var trackingRequests = new List<VNRequest> (); + foreach (var inputObservation in inputObservations) { + VNTrackingRequest request = null; + switch (type) { + case TrackedObjectType.Object: + request = new VNTrackObjectRequest (inputObservation.Value); + break; + + case TrackedObjectType.Rectangle: + if (inputObservation.Value is VNRectangleObservation rectObservation) { + request = new VNTrackRectangleRequest (rectObservation); + } else { + continue; + } + break; + } + + request.TrackingLevel = this.TrackingLevel; + trackingRequests.Add (request); + } + + // Perform array of requests + requestHandler.Perform (trackingRequests.ToArray (), frame, videoReader.Orientation, out NSError performError); + trackingFailedForAtLeastOneObject = performError != null; + + foreach (var processedRequest in trackingRequests) { + var results = processedRequest.GetResults<VNObservation> (); + if (results == null || !results.Any ()) { + continue; + } + + if (results.FirstOrDefault () is VNDetectedObjectObservation observation) { + // Assume threshold = 0.5f + var rectStyle = observation.Confidence > 0.5f ? TrackedPolyRectStyle.Solid : TrackedPolyRectStyle.Dashed; + var knownRect = trackedObjects [observation.Uuid]; + + switch (type) { + case TrackedObjectType.Object: + rects.Add (new TrackedPolyRect (observation, knownRect.Color, rectStyle)); + break; + + case TrackedObjectType.Rectangle: + if (observation is VNRectangleObservation rectObservation) { + rects.Add (new TrackedPolyRect (rectObservation, knownRect.Color, rectStyle)); + } + break; + } + + // Initialize inputObservation for the next iteration + inputObservations [observation.Uuid] = observation; + } + } + + // Draw results + this.Delegate?.DisplayFrame (frame, videoReader.AffineTransform, rects); + + var miliseconds = videoReader.FrameRateInSeconds / 1000; + System.Threading.Thread.Sleep ((int) miliseconds); + } + + this.Delegate?.DidFinifshTracking (); + + error = trackingFailedForAtLeastOneObject ? new VisionTrackerProcessorError (VisionTrackerProcessorErrorType.FirstFrameReadFailed) + : null; + } else { + error = new VisionTrackerProcessorError (VisionTrackerProcessorErrorType.FirstFrameReadFailed); + } + } else { + error = new VisionTrackerProcessorError (VisionTrackerProcessorErrorType.ReaderInitializationFailed); + } + } + + public void CancelTracking () + { + this.cancelRequested = true; + } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessorError.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessorError.cs index ad8ad5215..a4a89eb0a 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessorError.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Helpers/VisionTrackerProcessorError.cs @@ -1,16 +1,14 @@ - -namespace VisionObjectTrack -{ - using Foundation; - using VisionObjectTrack.Enums; - public class VisionTrackerProcessorError : NSError - { - public VisionTrackerProcessorError(VisionTrackerProcessorErrorType type) - { - this.Type = type; - } +namespace VisionObjectTrack { + using Foundation; + using VisionObjectTrack.Enums; - public VisionTrackerProcessorErrorType Type { get; private set; } - } -} \ No newline at end of file + public class VisionTrackerProcessorError : NSError { + public VisionTrackerProcessorError (VisionTrackerProcessorErrorType type) + { + this.Type = type; + } + + public VisionTrackerProcessorErrorType Type { get; private set; } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/Main.cs b/ios12/VisionObjectTrack/VisionObjectTrack/Main.cs index 63c257ff8..492e0e868 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/Main.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/Main.cs @@ -1,16 +1,14 @@ - -namespace VisionObjectTrack -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace VisionObjectTrack { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/VisionObjectTrack/VisionObjectTrack/TrackingViewController.cs b/ios12/VisionObjectTrack/VisionObjectTrack/TrackingViewController.cs index 229c8bb1d..cdebc70f6 100644 --- a/ios12/VisionObjectTrack/VisionObjectTrack/TrackingViewController.cs +++ b/ios12/VisionObjectTrack/VisionObjectTrack/TrackingViewController.cs @@ -1,346 +1,318 @@ -namespace VisionObjectTrack -{ - using AVFoundation; - using CoreFoundation; - using CoreGraphics; - using CoreImage; - using CoreVideo; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - using Vision; - using VisionObjectTrack.Enums; - - public partial class TrackingViewController : UIViewController, IVisionTrackerProcessorDelegate, IUIGestureRecognizerDelegate - { - private AVAsset videoAsset; - - private VisionTrackerProcessor visionProcessor; - - private DispatchQueue workQueue = new DispatchQueue("com.apple.VisionTracker");//, qos: .userInitiated) - - private TrackedObjectType trackedObjectType = TrackedObjectType.Object; - - private List<TrackedPolyRect> objectsToTrack = new List<TrackedPolyRect>(); - - private State state = State.Stopped; - - public TrackingViewController(IntPtr handle) : base(handle) { } - - public AVAsset VideoAsset - { - get - { - return this.videoAsset; - } - - set - { - this.videoAsset = value; - this.visionProcessor = new VisionTrackerProcessor(this.videoAsset) { Delegate = this }; - } - } - - public State State - { - get - { - return this.state; - } - - set - { - this.state = value; - this.HandleStateChange(); - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - var backplateLayer = this.frameCounterLabelBackplate.Layer; - backplateLayer.CornerRadius = backplateLayer.Bounds.Height / 2f; - - this.frameCounterLabelBackplate.Hidden = true; - this.frameCounterLabel.Font = UIFont.MonospacedDigitSystemFontOfSize(16, UIFontWeight.Light); - this.handleModeSelection(this.modeSelector); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - this.workQueue.DispatchAsync(() => this.DisplayFirstVideoFrame()); - } - - public override void ViewWillDisappear(bool animated) - { - this.visionProcessor.CancelTracking(); - base.ViewWillDisappear(animated); - } - - public override bool PrefersStatusBarHidden() - { - return true; - } - - private void DisplayFirstVideoFrame() - { - var isTrackingRects = this.trackedObjectType == TrackedObjectType.Rectangle; - this.visionProcessor.ReadAndDisplayFirstFrame(isTrackingRects, out NSError error); - if (error != null) - { - this.HandleError(error); - } - } - - private void StartTracking() - { - this.visionProcessor.PerformTracking(this.trackedObjectType, out NSError error); - if (error != null) - { - this.HandleError(error); - } - } - - private void HandleError(NSError error) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - string title = null; - string message = null; - - if (error is VisionTrackerProcessorError processorError) - { - title = "Vision Processor Error"; - switch (processorError.Type) - { - case VisionTrackerProcessorErrorType.FirstFrameReadFailed: - message = "Cannot read the first frame from selected video."; - break; - - case VisionTrackerProcessorErrorType.ObjectTrackingFailed: - message = "Tracking of one or more objects failed."; - break; - - case VisionTrackerProcessorErrorType.ReaderInitializationFailed: - message = "Cannot create a Video Reader for selected video."; - break; - - case VisionTrackerProcessorErrorType.RectangleDetectionFailed: - message = "Rectagle Detector failed to detect rectangles on the first frame of selected video."; - break; - } - } - else - { - title = "Error"; - message = error.LocalizedDescription; - } - - var alert = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Cancel, null)); - this.PresentViewController(alert, true, null); - }); - } - - private void HandleStateChange() - { - UIBarButtonItem newBarButton = null; - bool navBarHidden = false; - bool frameCounterHidden = false; - - switch (this.state) - { - case State.Stopped: - navBarHidden = false; - frameCounterHidden = true; - - // reveal settings view - this.trackingViewTopConstraint.Constant = 0; - this.entitySelector.Enabled = true; - newBarButton = new UIBarButtonItem(UIBarButtonSystemItem.Play, (s, e) => this.handleStartStopButton(null)); - break; - - case State.Tracking: - navBarHidden = true; - frameCounterHidden = false; - - // cover settings view - this.trackingViewTopConstraint.Constant = -settingsView.Frame.Height; - this.entitySelector.Enabled = false; - newBarButton = new UIBarButtonItem(UIBarButtonSystemItem.Stop, (s, e) => this.handleStartStopButton(null)); - break; - } - - this.NavigationController?.SetNavigationBarHidden(navBarHidden, true); - UIView.Animate(0.5d, () => - { - this.View.LayoutIfNeeded(); - this.NavigationItem.RightBarButtonItem = newBarButton; - this.frameCounterLabelBackplate.Hidden = frameCounterHidden; - }); - } - - partial void handleEntitySelection(UISegmentedControl sender) - { - switch (sender.SelectedSegment) - { - case 0: - this.trackedObjectType = TrackedObjectType.Object; - this.NavigationItem.Prompt = "Drag to select objects"; - this.clearRectsButton.Enabled = true; - break; - - case 1: - this.trackedObjectType = TrackedObjectType.Rectangle; - this.NavigationItem.Prompt = "Rectangles are detected automatically"; - this.clearRectsButton.Enabled = false; - break; - } - - this.workQueue.DispatchAsync(() => this.DisplayFirstVideoFrame()); - } - - partial void handleModeSelection(UISegmentedControl sender) - { - switch (sender.SelectedSegment) - { - case 0: - this.visionProcessor.TrackingLevel = VNRequestTrackingLevel.Fast; - break; - - case 1: - this.visionProcessor.TrackingLevel = VNRequestTrackingLevel.Accurate; - break; - } - } - - partial void handleClearRectsButton(UIButton sender) - { - this.objectsToTrack.Clear(); - this.workQueue.DispatchAsync(() => this.DisplayFirstVideoFrame()); - } - - partial void handleStartStopButton(UIBarButtonItem sender) - { - switch (this.state) - { - case State.Tracking: - // stop tracking - this.visionProcessor.CancelTracking(); - this.State = State.Stopped; - this.workQueue.DispatchAsync(() => this.DisplayFirstVideoFrame()); - break; - - case State.Stopped: - // initialize processor and start tracking - this.State = State.Tracking; - this.visionProcessor.ObjectsToTrack = this.objectsToTrack; - this.workQueue.DispatchAsync(() => this.StartTracking()); - break; - } - } - - [Export("gestureRecognizer:shouldReceiveTouch:")] - public bool ShouldReceiveTouch(UIGestureRecognizer recognizer, UITouch touch) - { - var locationInView = touch.LocationInView(this.trackingView); - return this.trackingView.IsPointWithinDrawingArea(locationInView) && this.trackedObjectType == TrackedObjectType.Object; - } - - partial void handlePan(UIPanGestureRecognizer gestureRecognizer) - { - switch (gestureRecognizer.State) - { - case UIGestureRecognizerState.Began: - // Initiate object selection - var locationInView = gestureRecognizer.LocationInView(this.trackingView); - if (this.trackingView.IsPointWithinDrawingArea(locationInView)) - { - this.trackingView.RubberbandingStart = locationInView; // start new rubberbanding - } - break; - - case UIGestureRecognizerState.Changed: - // Process resizing of the object's bounding box - var translationPoint = gestureRecognizer.TranslationInView(this.trackingView); - var translation = CGAffineTransform.MakeTranslation(translationPoint.X, translationPoint.Y); - var endPoint = translation.TransformPoint(this.trackingView.RubberbandingStart); - - if (this.trackingView.IsPointWithinDrawingArea(endPoint)) - { - this.trackingView.RubberbandingVector = translationPoint; - this.trackingView.SetNeedsDisplay(); - } - break; - - case UIGestureRecognizerState.Ended: - // Finish resizing of the object's boundong box - var selectedBBox = this.trackingView.RubberbandingRectNormalized; - if (selectedBBox.Width > 0 && selectedBBox.Height > 0) - { - var rectColor = TrackedObjectsPalette.Color(this.objectsToTrack.Count); - this.objectsToTrack.Add(new TrackedPolyRect(selectedBBox, rectColor)); - - this.DisplayFrame(null, CGAffineTransform.MakeIdentity(), this.objectsToTrack); - } - break; - } - } - - partial void handleTap(UITapGestureRecognizer gestureRecognizer) - { - // toggle navigation bar visibility if tracking is in progress - if (this.state == State.Tracking && gestureRecognizer.State == UIGestureRecognizerState.Ended) - { - this.NavigationController?.SetNavigationBarHidden(!this.NavigationController.NavigationBarHidden, true); - } - } - - #region IVisionTrackerProcessorDelegate - - public void DisplayFrame(CVPixelBuffer frame, CGAffineTransform transform, IList<TrackedPolyRect> rects) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (frame != null) - { - var ciImage = new CIImage(frame).ImageByApplyingTransform(transform); - var uiImage = new UIImage(ciImage); - this.trackingView.Image = uiImage; - } - - this.trackingView.PolyRects = rects?.ToList() ?? (this.trackedObjectType == TrackedObjectType.Object ? this.objectsToTrack - : new List<TrackedPolyRect>()); - this.trackingView.RubberbandingStart = CGPoint.Empty; - this.trackingView.RubberbandingVector = CGPoint.Empty; - - this.trackingView.SetNeedsDisplay(); - }); - } - - public void DisplayFrameCounter(int frame) - { - DispatchQueue.MainQueue.DispatchAsync(() => this.frameCounterLabel.Text = $"Frame: {frame}"); - } - - public void DidFinifshTracking() - { - this.workQueue.DispatchAsync(() => this.DisplayFirstVideoFrame()); - DispatchQueue.MainQueue.DispatchAsync(() => this.State = State.Stopped); - } - - #endregion - } - - public enum State - { - Tracking, - Stopped, - } -} \ No newline at end of file +namespace VisionObjectTrack { + using AVFoundation; + using CoreFoundation; + using CoreGraphics; + using CoreImage; + using CoreVideo; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + using Vision; + using VisionObjectTrack.Enums; + + public partial class TrackingViewController : UIViewController, IVisionTrackerProcessorDelegate, IUIGestureRecognizerDelegate { + private AVAsset videoAsset; + + private VisionTrackerProcessor visionProcessor; + + private DispatchQueue workQueue = new DispatchQueue ("com.apple.VisionTracker");//, qos: .userInitiated) + + private TrackedObjectType trackedObjectType = TrackedObjectType.Object; + + private List<TrackedPolyRect> objectsToTrack = new List<TrackedPolyRect> (); + + private State state = State.Stopped; + + public TrackingViewController (IntPtr handle) : base (handle) { } + + public AVAsset VideoAsset { + get { + return this.videoAsset; + } + + set { + this.videoAsset = value; + this.visionProcessor = new VisionTrackerProcessor (this.videoAsset) { Delegate = this }; + } + } + + public State State { + get { + return this.state; + } + + set { + this.state = value; + this.HandleStateChange (); + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + var backplateLayer = this.frameCounterLabelBackplate.Layer; + backplateLayer.CornerRadius = backplateLayer.Bounds.Height / 2f; + + this.frameCounterLabelBackplate.Hidden = true; + this.frameCounterLabel.Font = UIFont.MonospacedDigitSystemFontOfSize (16, UIFontWeight.Light); + this.handleModeSelection (this.modeSelector); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + this.workQueue.DispatchAsync (() => this.DisplayFirstVideoFrame ()); + } + + public override void ViewWillDisappear (bool animated) + { + this.visionProcessor.CancelTracking (); + base.ViewWillDisappear (animated); + } + + public override bool PrefersStatusBarHidden () + { + return true; + } + + private void DisplayFirstVideoFrame () + { + var isTrackingRects = this.trackedObjectType == TrackedObjectType.Rectangle; + this.visionProcessor.ReadAndDisplayFirstFrame (isTrackingRects, out NSError error); + if (error != null) { + this.HandleError (error); + } + } + + private void StartTracking () + { + this.visionProcessor.PerformTracking (this.trackedObjectType, out NSError error); + if (error != null) { + this.HandleError (error); + } + } + + private void HandleError (NSError error) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + string title = null; + string message = null; + + if (error is VisionTrackerProcessorError processorError) { + title = "Vision Processor Error"; + switch (processorError.Type) { + case VisionTrackerProcessorErrorType.FirstFrameReadFailed: + message = "Cannot read the first frame from selected video."; + break; + + case VisionTrackerProcessorErrorType.ObjectTrackingFailed: + message = "Tracking of one or more objects failed."; + break; + + case VisionTrackerProcessorErrorType.ReaderInitializationFailed: + message = "Cannot create a Video Reader for selected video."; + break; + + case VisionTrackerProcessorErrorType.RectangleDetectionFailed: + message = "Rectagle Detector failed to detect rectangles on the first frame of selected video."; + break; + } + } else { + title = "Error"; + message = error.LocalizedDescription; + } + + var alert = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Cancel, null)); + this.PresentViewController (alert, true, null); + }); + } + + private void HandleStateChange () + { + UIBarButtonItem newBarButton = null; + bool navBarHidden = false; + bool frameCounterHidden = false; + + switch (this.state) { + case State.Stopped: + navBarHidden = false; + frameCounterHidden = true; + + // reveal settings view + this.trackingViewTopConstraint.Constant = 0; + this.entitySelector.Enabled = true; + newBarButton = new UIBarButtonItem (UIBarButtonSystemItem.Play, (s, e) => this.handleStartStopButton (null)); + break; + + case State.Tracking: + navBarHidden = true; + frameCounterHidden = false; + + // cover settings view + this.trackingViewTopConstraint.Constant = -settingsView.Frame.Height; + this.entitySelector.Enabled = false; + newBarButton = new UIBarButtonItem (UIBarButtonSystemItem.Stop, (s, e) => this.handleStartStopButton (null)); + break; + } + + this.NavigationController?.SetNavigationBarHidden (navBarHidden, true); + UIView.Animate (0.5d, () => { + this.View.LayoutIfNeeded (); + this.NavigationItem.RightBarButtonItem = newBarButton; + this.frameCounterLabelBackplate.Hidden = frameCounterHidden; + }); + } + + partial void handleEntitySelection (UISegmentedControl sender) + { + switch (sender.SelectedSegment) { + case 0: + this.trackedObjectType = TrackedObjectType.Object; + this.NavigationItem.Prompt = "Drag to select objects"; + this.clearRectsButton.Enabled = true; + break; + + case 1: + this.trackedObjectType = TrackedObjectType.Rectangle; + this.NavigationItem.Prompt = "Rectangles are detected automatically"; + this.clearRectsButton.Enabled = false; + break; + } + + this.workQueue.DispatchAsync (() => this.DisplayFirstVideoFrame ()); + } + + partial void handleModeSelection (UISegmentedControl sender) + { + switch (sender.SelectedSegment) { + case 0: + this.visionProcessor.TrackingLevel = VNRequestTrackingLevel.Fast; + break; + + case 1: + this.visionProcessor.TrackingLevel = VNRequestTrackingLevel.Accurate; + break; + } + } + + partial void handleClearRectsButton (UIButton sender) + { + this.objectsToTrack.Clear (); + this.workQueue.DispatchAsync (() => this.DisplayFirstVideoFrame ()); + } + + partial void handleStartStopButton (UIBarButtonItem sender) + { + switch (this.state) { + case State.Tracking: + // stop tracking + this.visionProcessor.CancelTracking (); + this.State = State.Stopped; + this.workQueue.DispatchAsync (() => this.DisplayFirstVideoFrame ()); + break; + + case State.Stopped: + // initialize processor and start tracking + this.State = State.Tracking; + this.visionProcessor.ObjectsToTrack = this.objectsToTrack; + this.workQueue.DispatchAsync (() => this.StartTracking ()); + break; + } + } + + [Export ("gestureRecognizer:shouldReceiveTouch:")] + public bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch) + { + var locationInView = touch.LocationInView (this.trackingView); + return this.trackingView.IsPointWithinDrawingArea (locationInView) && this.trackedObjectType == TrackedObjectType.Object; + } + + partial void handlePan (UIPanGestureRecognizer gestureRecognizer) + { + switch (gestureRecognizer.State) { + case UIGestureRecognizerState.Began: + // Initiate object selection + var locationInView = gestureRecognizer.LocationInView (this.trackingView); + if (this.trackingView.IsPointWithinDrawingArea (locationInView)) { + this.trackingView.RubberbandingStart = locationInView; // start new rubberbanding + } + break; + + case UIGestureRecognizerState.Changed: + // Process resizing of the object's bounding box + var translationPoint = gestureRecognizer.TranslationInView (this.trackingView); + var translation = CGAffineTransform.MakeTranslation (translationPoint.X, translationPoint.Y); + var endPoint = translation.TransformPoint (this.trackingView.RubberbandingStart); + + if (this.trackingView.IsPointWithinDrawingArea (endPoint)) { + this.trackingView.RubberbandingVector = translationPoint; + this.trackingView.SetNeedsDisplay (); + } + break; + + case UIGestureRecognizerState.Ended: + // Finish resizing of the object's boundong box + var selectedBBox = this.trackingView.RubberbandingRectNormalized; + if (selectedBBox.Width > 0 && selectedBBox.Height > 0) { + var rectColor = TrackedObjectsPalette.Color (this.objectsToTrack.Count); + this.objectsToTrack.Add (new TrackedPolyRect (selectedBBox, rectColor)); + + this.DisplayFrame (null, CGAffineTransform.MakeIdentity (), this.objectsToTrack); + } + break; + } + } + + partial void handleTap (UITapGestureRecognizer gestureRecognizer) + { + // toggle navigation bar visibility if tracking is in progress + if (this.state == State.Tracking && gestureRecognizer.State == UIGestureRecognizerState.Ended) { + this.NavigationController?.SetNavigationBarHidden (!this.NavigationController.NavigationBarHidden, true); + } + } + + #region IVisionTrackerProcessorDelegate + + public void DisplayFrame (CVPixelBuffer frame, CGAffineTransform transform, IList<TrackedPolyRect> rects) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (frame != null) { + var ciImage = new CIImage (frame).ImageByApplyingTransform (transform); + var uiImage = new UIImage (ciImage); + this.trackingView.Image = uiImage; + } + + this.trackingView.PolyRects = rects?.ToList () ?? (this.trackedObjectType == TrackedObjectType.Object ? this.objectsToTrack + : new List<TrackedPolyRect> ()); + this.trackingView.RubberbandingStart = CGPoint.Empty; + this.trackingView.RubberbandingVector = CGPoint.Empty; + + this.trackingView.SetNeedsDisplay (); + }); + } + + public void DisplayFrameCounter (int frame) + { + DispatchQueue.MainQueue.DispatchAsync (() => this.frameCounterLabel.Text = $"Frame: {frame}"); + } + + public void DidFinifshTracking () + { + this.workQueue.DispatchAsync (() => this.DisplayFirstVideoFrame ()); + DispatchQueue.MainQueue.DispatchAsync (() => this.State = State.Stopped); + } + + #endregion + } + + public enum State { + Tracking, + Stopped, + } +} diff --git a/ios12/XamarinNL/AppDelegate.cs b/ios12/XamarinNL/AppDelegate.cs index fb0ca704a..a89cbc300 100644 --- a/ios12/XamarinNL/AppDelegate.cs +++ b/ios12/XamarinNL/AppDelegate.cs @@ -1,59 +1,56 @@ -using Foundation; +using Foundation; using UIKit; -namespace XamarinNL -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - // class-level declarations - - public override UIWindow Window - { - get; - set; - } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method - - return true; - } - - public override void OnResignActivation(UIApplication application) - { - // Invoked when the application is about to move from active to inactive state. - // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) - // or when the user quits the application and it begins the transition to the background state. - // Games should use this method to pause the game. - } - - public override void DidEnterBackground(UIApplication application) - { - // Use this method to release shared resources, save user data, invalidate timers and store the application state. - // If your application supports background exection this method is called instead of WillTerminate when the user quits. - } - - public override void WillEnterForeground(UIApplication application) - { - // Called as part of the transiton from background to active state. - // Here you can undo many of the changes made on entering the background. - } - - public override void OnActivated(UIApplication application) - { - // Restart any tasks that were paused (or not yet started) while the application was inactive. - // If the application was previously in the background, optionally refresh the user interface. - } - - public override void WillTerminate(UIApplication application) - { - // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. - } - } +namespace XamarinNL { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + // class-level declarations + + public override UIWindow Window { + get; + set; + } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method + + return true; + } + + public override void OnResignActivation (UIApplication application) + { + // Invoked when the application is about to move from active to inactive state. + // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) + // or when the user quits the application and it begins the transition to the background state. + // Games should use this method to pause the game. + } + + public override void DidEnterBackground (UIApplication application) + { + // Use this method to release shared resources, save user data, invalidate timers and store the application state. + // If your application supports background exection this method is called instead of WillTerminate when the user quits. + } + + public override void WillEnterForeground (UIApplication application) + { + // Called as part of the transiton from background to active state. + // Here you can undo many of the changes made on entering the background. + } + + public override void OnActivated (UIApplication application) + { + // Restart any tasks that were paused (or not yet started) while the application was inactive. + // If the application was previously in the background, optionally refresh the user interface. + } + + public override void WillTerminate (UIApplication application) + { + // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. + } + } } diff --git a/ios12/XamarinNL/LanguageProbabilityTableViewController.cs b/ios12/XamarinNL/LanguageProbabilityTableViewController.cs index 661e598a7..e8cc10fdf 100644 --- a/ios12/XamarinNL/LanguageProbabilityTableViewController.cs +++ b/ios12/XamarinNL/LanguageProbabilityTableViewController.cs @@ -1,53 +1,49 @@ -using Foundation; -using System; -using UIKit; -using System.Linq; -using NaturalLanguage; - -namespace XamarinNL -{ - public partial class LanguageProbabilityTableViewController : UITableViewController - { - const string LanguageProbabilityCell = "LanguageProbabilityCell"; - - NSString[] sortedLanguages; - - NSDictionary<NSString, NSNumber> probabilities; - public NSDictionary<NSString, NSNumber> Probabilities - { - set - { - probabilities = value; - sortedLanguages = value.Keys.OrderByDescending(lang => value[lang].DoubleValue).ToArray<NSString>(); - } - } - - public LanguageProbabilityTableViewController(IntPtr handle) : base(handle) { } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return sortedLanguages.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = TableView.DequeueReusableCell(LanguageProbabilityCell); - NSString languageAbbreviation = sortedLanguages[indexPath.Row]; - NLLanguage language = NLLanguageExtensions.GetValue(languageAbbreviation); - cell.TextLabel.Text = language.ToString(); - cell.DetailTextLabel.Text = probabilities[languageAbbreviation].ToString(); - return cell; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - TableView.ReloadData(); - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; +using System.Linq; +using NaturalLanguage; + +namespace XamarinNL { + public partial class LanguageProbabilityTableViewController : UITableViewController { + const string LanguageProbabilityCell = "LanguageProbabilityCell"; + + NSString [] sortedLanguages; + + NSDictionary<NSString, NSNumber> probabilities; + public NSDictionary<NSString, NSNumber> Probabilities { + set { + probabilities = value; + sortedLanguages = value.Keys.OrderByDescending (lang => value [lang].DoubleValue).ToArray<NSString> (); + } + } + + public LanguageProbabilityTableViewController (IntPtr handle) : base (handle) { } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return sortedLanguages.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = TableView.DequeueReusableCell (LanguageProbabilityCell); + NSString languageAbbreviation = sortedLanguages [indexPath.Row]; + NLLanguage language = NLLanguageExtensions.GetValue (languageAbbreviation); + cell.TextLabel.Text = language.ToString (); + cell.DetailTextLabel.Text = probabilities [languageAbbreviation].ToString (); + return cell; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + TableView.ReloadData (); + } + } +} diff --git a/ios12/XamarinNL/LanguageRecognizerViewController.cs b/ios12/XamarinNL/LanguageRecognizerViewController.cs index deea65385..3db5d3aad 100644 --- a/ios12/XamarinNL/LanguageRecognizerViewController.cs +++ b/ios12/XamarinNL/LanguageRecognizerViewController.cs @@ -1,61 +1,56 @@ -using Foundation; -using System; -using UIKit; -using NaturalLanguage; - -namespace XamarinNL -{ - public partial class LanguageRecognizerViewController : UIViewController, IUITextFieldDelegate - { - const string ShowLanguageProbabilitiesSegue = "ShowLanguageProbabilitiesSegue"; - - NSDictionary<NSString, NSNumber> probabilities; - - public LanguageRecognizerViewController(IntPtr handle) : base(handle) { } - - partial void HandleLanguageProbabilitiesButtonTap(UIButton sender) - { - UserInput.ResignFirstResponder(); - if (!String.IsNullOrWhiteSpace(UserInput.Text)) - { - var recognizer = new NLLanguageRecognizer(); - recognizer.Process(UserInput.Text); - probabilities = recognizer.GetNativeLanguageHypotheses(10); - PerformSegue(ShowLanguageProbabilitiesSegue, this); - } - } - - partial void HandleDetermineLanguageButtonTap(UIButton sender) - { - UserInput.ResignFirstResponder(); - if (!String.IsNullOrWhiteSpace(UserInput.Text)) - { - NLLanguage lang = NLLanguageRecognizer.GetDominantLanguage(UserInput.Text); - DominantLanguageLabel.Text = lang.ToString(); - } - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - base.PrepareForSegue(segue, sender); - var destination = segue.DestinationViewController as LanguageProbabilityTableViewController; - if (destination != null) - { - destination.Probabilities = probabilities; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - UserInput.Delegate = this; - } - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - UserInput.ResignFirstResponder(); - return true; - } - } -} \ No newline at end of file +using Foundation; +using System; +using UIKit; +using NaturalLanguage; + +namespace XamarinNL { + public partial class LanguageRecognizerViewController : UIViewController, IUITextFieldDelegate { + const string ShowLanguageProbabilitiesSegue = "ShowLanguageProbabilitiesSegue"; + + NSDictionary<NSString, NSNumber> probabilities; + + public LanguageRecognizerViewController (IntPtr handle) : base (handle) { } + + partial void HandleLanguageProbabilitiesButtonTap (UIButton sender) + { + UserInput.ResignFirstResponder (); + if (!String.IsNullOrWhiteSpace (UserInput.Text)) { + var recognizer = new NLLanguageRecognizer (); + recognizer.Process (UserInput.Text); + probabilities = recognizer.GetNativeLanguageHypotheses (10); + PerformSegue (ShowLanguageProbabilitiesSegue, this); + } + } + + partial void HandleDetermineLanguageButtonTap (UIButton sender) + { + UserInput.ResignFirstResponder (); + if (!String.IsNullOrWhiteSpace (UserInput.Text)) { + NLLanguage lang = NLLanguageRecognizer.GetDominantLanguage (UserInput.Text); + DominantLanguageLabel.Text = lang.ToString (); + } + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + base.PrepareForSegue (segue, sender); + var destination = segue.DestinationViewController as LanguageProbabilityTableViewController; + if (destination != null) { + destination.Probabilities = probabilities; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + UserInput.Delegate = this; + } + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + UserInput.ResignFirstResponder (); + return true; + } + } +} diff --git a/ios12/XamarinNL/LanguageTaggerTableViewController.cs b/ios12/XamarinNL/LanguageTaggerTableViewController.cs index 0ef94cfaa..0ec2ee440 100644 --- a/ios12/XamarinNL/LanguageTaggerTableViewController.cs +++ b/ios12/XamarinNL/LanguageTaggerTableViewController.cs @@ -1,48 +1,46 @@ -using Foundation; +using Foundation; using NaturalLanguage; -using System; -using UIKit; - -namespace XamarinNL -{ - public partial class LanguageTaggerTableViewController : UITableViewController - { - const string EntityCell = "EntityCell"; - - public NSValue[] TokenRanges { get; set; } - public NSString[] Tags { get; set; } - public string Text { get; set; } - - public LanguageTaggerTableViewController(IntPtr handle) : base(handle) { } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return Tags.Length; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = TableView.DequeueReusableCell(EntityCell); - - var range = TokenRanges[indexPath.Row].RangeValue; - var token = Text.Substring((int)range.Location, (int)range.Length); - var tag = Tags[indexPath.Row]; - - cell.TextLabel.Text = token; - cell.DetailTextLabel.Text = tag; - - return cell; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - TableView.ReloadData(); - } - } -} \ No newline at end of file +using System; +using UIKit; + +namespace XamarinNL { + public partial class LanguageTaggerTableViewController : UITableViewController { + const string EntityCell = "EntityCell"; + + public NSValue [] TokenRanges { get; set; } + public NSString [] Tags { get; set; } + public string Text { get; set; } + + public LanguageTaggerTableViewController (IntPtr handle) : base (handle) { } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return Tags.Length; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = TableView.DequeueReusableCell (EntityCell); + + var range = TokenRanges [indexPath.Row].RangeValue; + var token = Text.Substring ((int) range.Location, (int) range.Length); + var tag = Tags [indexPath.Row]; + + cell.TextLabel.Text = token; + cell.DetailTextLabel.Text = tag; + + return cell; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + TableView.ReloadData (); + } + } +} diff --git a/ios12/XamarinNL/LanguageTaggerViewController.cs b/ios12/XamarinNL/LanguageTaggerViewController.cs index 09c7804b8..cdadf8719 100644 --- a/ios12/XamarinNL/LanguageTaggerViewController.cs +++ b/ios12/XamarinNL/LanguageTaggerViewController.cs @@ -1,70 +1,66 @@ -using Foundation; +using Foundation; using NaturalLanguage; -using System; -using UIKit; - -namespace XamarinNL -{ - public partial class LanguageTaggerViewController : UIViewController, IUITextFieldDelegate - { - const string ShowEntitiesSegue = "ShowEntitiesSegue"; +using System; +using UIKit; - NSString[] tags; - NSValue[] tokenRanges; - string detailViewTitle; +namespace XamarinNL { + public partial class LanguageTaggerViewController : UIViewController, IUITextFieldDelegate { + const string ShowEntitiesSegue = "ShowEntitiesSegue"; - public LanguageTaggerViewController(IntPtr handle) : base(handle) { } + NSString [] tags; + NSValue [] tokenRanges; + string detailViewTitle; - partial void HandlePartsOfSpeechButtonTap(UIButton sender) - { - ShowTags(NLTagScheme.LexicalClass); - } + public LanguageTaggerViewController (IntPtr handle) : base (handle) { } - partial void HandleNamedEntitiesButtonTap(UIButton sender) - { - ShowTags(NLTagScheme.NameType); - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - base.PrepareForSegue(segue, sender); - var destination = segue.DestinationViewController as LanguageTaggerTableViewController; - if (destination != null) - { - destination.Text = UserInput.Text; - destination.Tags = tags; - destination.TokenRanges = tokenRanges; - destination.Title = detailViewTitle; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - UserInput.Delegate = this; - } - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - UserInput.ResignFirstResponder(); - return true; - } + partial void HandlePartsOfSpeechButtonTap (UIButton sender) + { + ShowTags (NLTagScheme.LexicalClass); + } - void ShowTags(NLTagScheme tagScheme) - { - if (!String.IsNullOrWhiteSpace(UserInput.Text)) - { - var tagger = new NLTagger(new NLTagScheme[] { tagScheme }); - var range = new NSRange(0, UserInput.Text.Length); - tagger.String = UserInput.Text; - - tags = tagger.GetTags(range, NLTokenUnit.Word, tagScheme, NLTaggerOptions.OmitWhitespace, out NSValue[] ranges); - tokenRanges = ranges; - detailViewTitle = tagScheme == NLTagScheme.NameType ? "Named Entities" : "Parts of Speech"; - - PerformSegue(ShowEntitiesSegue, this); - } - } - } -} \ No newline at end of file + partial void HandleNamedEntitiesButtonTap (UIButton sender) + { + ShowTags (NLTagScheme.NameType); + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + base.PrepareForSegue (segue, sender); + var destination = segue.DestinationViewController as LanguageTaggerTableViewController; + if (destination != null) { + destination.Text = UserInput.Text; + destination.Tags = tags; + destination.TokenRanges = tokenRanges; + destination.Title = detailViewTitle; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + UserInput.Delegate = this; + } + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + UserInput.ResignFirstResponder (); + return true; + } + + void ShowTags (NLTagScheme tagScheme) + { + if (!String.IsNullOrWhiteSpace (UserInput.Text)) { + var tagger = new NLTagger (new NLTagScheme [] { tagScheme }); + var range = new NSRange (0, UserInput.Text.Length); + tagger.String = UserInput.Text; + + tags = tagger.GetTags (range, NLTokenUnit.Word, tagScheme, NLTaggerOptions.OmitWhitespace, out NSValue [] ranges); + tokenRanges = ranges; + detailViewTitle = tagScheme == NLTagScheme.NameType ? "Named Entities" : "Parts of Speech"; + + PerformSegue (ShowEntitiesSegue, this); + } + } + } +} diff --git a/ios12/XamarinNL/LanguageTokenizerTableViewController.cs b/ios12/XamarinNL/LanguageTokenizerTableViewController.cs index 15a401d3c..0d454c241 100644 --- a/ios12/XamarinNL/LanguageTokenizerTableViewController.cs +++ b/ios12/XamarinNL/LanguageTokenizerTableViewController.cs @@ -4,39 +4,37 @@ using System.Linq; using NaturalLanguage; -namespace XamarinNL -{ - public partial class LanguageTokenizerTableViewController : UITableViewController - { - const string TokenCell = "TokenCell"; +namespace XamarinNL { + public partial class LanguageTokenizerTableViewController : UITableViewController { + const string TokenCell = "TokenCell"; - public NSValue[] Tokens { get; set; } - public string Text { get; set; } + public NSValue [] Tokens { get; set; } + public string Text { get; set; } - public LanguageTokenizerTableViewController(IntPtr handle) : base(handle) { } + public LanguageTokenizerTableViewController (IntPtr handle) : base (handle) { } - public override nint RowsInSection(UITableView tableView, nint section) - { - return Tokens.Length; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return Tokens.Length; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = TableView.DequeueReusableCell(TokenCell); - NSRange range = Tokens[indexPath.Row].RangeValue; - cell.TextLabel.Text = Text.Substring((int)range.Location, (int)range.Length); - return cell; - } + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = TableView.DequeueReusableCell (TokenCell); + NSRange range = Tokens [indexPath.Row].RangeValue; + cell.TextLabel.Text = Text.Substring ((int) range.Location, (int) range.Length); + return cell; + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + } - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - TableView.ReloadData(); - } - } -} \ No newline at end of file + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + TableView.ReloadData (); + } + } +} diff --git a/ios12/XamarinNL/LanguageTokenizerViewController.cs b/ios12/XamarinNL/LanguageTokenizerViewController.cs index e026ced1f..0a2ed28dc 100644 --- a/ios12/XamarinNL/LanguageTokenizerViewController.cs +++ b/ios12/XamarinNL/LanguageTokenizerViewController.cs @@ -3,60 +3,56 @@ using UIKit; using NaturalLanguage; -namespace XamarinNL -{ - public partial class LanguageTokenizerViewController : UIViewController, IUITextFieldDelegate - { - const string ShowTokensSegue = "ShowTokensSegue"; - - NSValue[] tokens; - - public LanguageTokenizerViewController(IntPtr handle) : base(handle) { } - - partial void HandleFindSentencesTap(UIButton sender) - { - ShowTokens(NLTokenUnit.Sentence); - } - - partial void HandleFindWordsButtonTap(UIButton sender) - { - ShowTokens(NLTokenUnit.Word); - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - base.PrepareForSegue(segue, sender); - var destination = segue.DestinationViewController as LanguageTokenizerTableViewController; - if (destination != null) - { - destination.Tokens = tokens; - destination.Text = UserInput.Text; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - UserInput.Delegate = this; - } - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - UserInput.ResignFirstResponder(); - return true; - } - - void ShowTokens(NLTokenUnit unit) - { - if (!String.IsNullOrWhiteSpace(UserInput.Text)) - { - var tokenizer = new NLTokenizer(unit); - tokenizer.String = UserInput.Text; - var range = new NSRange(0, UserInput.Text.Length); - tokens = tokenizer.GetTokens(range); - PerformSegue(ShowTokensSegue, this); - } - } - } -} \ No newline at end of file +namespace XamarinNL { + public partial class LanguageTokenizerViewController : UIViewController, IUITextFieldDelegate { + const string ShowTokensSegue = "ShowTokensSegue"; + + NSValue [] tokens; + + public LanguageTokenizerViewController (IntPtr handle) : base (handle) { } + + partial void HandleFindSentencesTap (UIButton sender) + { + ShowTokens (NLTokenUnit.Sentence); + } + + partial void HandleFindWordsButtonTap (UIButton sender) + { + ShowTokens (NLTokenUnit.Word); + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + base.PrepareForSegue (segue, sender); + var destination = segue.DestinationViewController as LanguageTokenizerTableViewController; + if (destination != null) { + destination.Tokens = tokens; + destination.Text = UserInput.Text; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + UserInput.Delegate = this; + } + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + UserInput.ResignFirstResponder (); + return true; + } + + void ShowTokens (NLTokenUnit unit) + { + if (!String.IsNullOrWhiteSpace (UserInput.Text)) { + var tokenizer = new NLTokenizer (unit); + tokenizer.String = UserInput.Text; + var range = new NSRange (0, UserInput.Text.Length); + tokens = tokenizer.GetTokens (range); + PerformSegue (ShowTokensSegue, this); + } + } + } +} diff --git a/ios12/XamarinNL/Main.cs b/ios12/XamarinNL/Main.cs index c2475943c..8612b5d48 100644 --- a/ios12/XamarinNL/Main.cs +++ b/ios12/XamarinNL/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace XamarinNL -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } +namespace XamarinNL { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } } diff --git a/ios12/XamarinShot/XamarinShot/AppDelegate.cs b/ios12/XamarinShot/XamarinShot/AppDelegate.cs index 732c18482..a5ef458b5 100644 --- a/ios12/XamarinShot/XamarinShot/AppDelegate.cs +++ b/ios12/XamarinShot/XamarinShot/AppDelegate.cs @@ -1,28 +1,26 @@ - -namespace XamarinShot -{ - using Foundation; - using System.Linq; - using XamarinShot.Utils; - using UIKit; - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace XamarinShot { + using Foundation; + using System.Linq; + using XamarinShot.Utils; + using UIKit; - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - var dictionary = NSDictionary.FromObjectsAndKeys(UserDefaults.ApplicationDefaults.Values.Select(value => value).ToArray(), - UserDefaults.ApplicationDefaults.Keys.Select(key => new NSString(key)).ToArray()); - NSUserDefaults.StandardUserDefaults.RegisterDefaults(dictionary); + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - return true; - } + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + var dictionary = NSDictionary.FromObjectsAndKeys (UserDefaults.ApplicationDefaults.Values.Select (value => value).ToArray (), + UserDefaults.ApplicationDefaults.Keys.Select (key => new NSString (key)).ToArray ()); + NSUserDefaults.StandardUserDefaults.RegisterDefaults (dictionary); - public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options) - { - return false; - } - } -} \ No newline at end of file + return true; + } + + public override bool OpenUrl (UIApplication app, NSUrl url, NSDictionary options) + { + return false; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/DeveloperSettingsTableViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/DeveloperSettingsTableViewController.cs index f58390af8..93a2e19ff 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/DeveloperSettingsTableViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/DeveloperSettingsTableViewController.cs @@ -1,365 +1,342 @@ - -namespace XamarinShot -{ - using Foundation; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using UIKit; - - /// <summary> - /// View controller for development & debugging settings. - /// </summary> - public partial class DeveloperSettingsTableViewController : UITableViewController, IUITextFieldDelegate - { - private readonly ProximityManager proximityManager = ProximityManager.Shared; - - private List<UISwitch> switches; - - public DeveloperSettingsTableViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // set default delegates - - this.TableView.Delegate = this; - this.TableView.DataSource = this; - this.trailWidthTextField.Delegate = this; - this.trailLengthTextField.Delegate = this; - - // initialize - - NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.DidBecomeActiveNotification, this.DidApplicationBecomeActive); - this.antialiasingMode.On = UserDefaults.AntialiasingMode; - this.useEncryptionSwitch.On = UserDefaults.UseEncryption; - - // if user turns of location permissions in settings after enabling them, we should turn off gameRoomMode - if (!this.proximityManager.IsAuthorized) - { - UserDefaults.GameRoomMode = false; - } - - this.gameRoomModeSwitch.On = UserDefaults.GameRoomMode; - this.useAutofocusSwitch.On = UserDefaults.AutoFocus; - this.allowGameBoardAutoSizeSwitch.On = UserDefaults.AllowGameBoardAutoSize; - - // level - this.showResetLevelSwitch.On = UserDefaults.ShowResetLever; - this.showFlags.On = UserDefaults.ShowFlags; - this.showClouds.On = UserDefaults.ShowClouds; - this.showRopeSimulation.On = UserDefaults.ShowRopeSimulation; - - // happens here so the switches have been loaded from the storyboard - this.switches = new List<UISwitch> - { - this.showARDebugSwitch, this.showRenderStatsSwitch, - this.showTrackingStateSwitch, this.showWireframe, this.showLOD, - this.showPhysicsDebugSwitch, this.showSettingsSwitch, this.showARRelocalizationHelp, - this.showNetworkDebugSwitch, this.showThermalStateSwitch - }; - - this.ConfigureUISwitches(); - this.ConfigureBoardLocationCells(); - this.ConfigureProjectileTrail(); - } - - private void DidApplicationBecomeActive(NSNotification notification) - { - // check for permission changes after becoming active again - if (!this.proximityManager.IsAuthorized) - { - UserDefaults.GameRoomMode = false; - } - - this.gameRoomModeSwitch.On = UserDefaults.GameRoomMode; - } - - private void ConfigureUISwitches() - { - this.disableInGameUISwitch.On = UserDefaults.DisableInGameUI; - this.showARDebugSwitch.On = UserDefaults.ShowARDebug; - this.showRenderStatsSwitch.On = UserDefaults.ShowSceneViewStats; - this.showTrackingStateSwitch.On = UserDefaults.ShowTrackingState; - this.showWireframe.On = UserDefaults.ShowWireframe; - this.showLOD.On = UserDefaults.ShowLOD; - this.showPhysicsDebugSwitch.On = UserDefaults.ShowPhysicsDebug; - this.showSettingsSwitch.On = UserDefaults.ShowSettingsInGame; - this.showARRelocalizationHelp.On = UserDefaults.ShowARRelocalizationHelp; - this.showNetworkDebugSwitch.On = UserDefaults.ShowNetworkDebug; - this.showProjectileTrailSwitch.On = UserDefaults.ShowProjectileTrail; - this.synchronizeMusicWithWallClockSwitch.On = UserDefaults.SynchronizeMusicWithWallClock; - this.showThermalStateSwitch.On = UserDefaults.ShowThermalState; - - foreach (var @switch in this.switches) - { - @switch.Enabled = !UserDefaults.DisableInGameUI; - } - } - - private void ConfigureBoardLocationCells() - { - var boardLocationMode = UserDefaults.BoardLocatingMode; - this.worldMapCell.Accessory = boardLocationMode == BoardLocatingMode.WorldMap ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; - this.manualCell.Accessory = boardLocationMode == BoardLocatingMode.Manual ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; - } - - private void ConfigureProjectileTrail() - { - this.useCustomTrailSwitch.On = UserDefaults.UseCustomTrail; - this.taperTrailSwitch.On = UserDefaults.TrailShouldNarrow; - - if (UserDefaults.UseCustomTrail) - { - var width = UserDefaults.TrailWidth ?? TrailBallProjectile.DefaultTrailWidth; - this.trailWidthTextField.Text = width.ToString(); - this.trailWidthTextField.Enabled = true; - this.trailLengthTextField.Text = $"{UserDefaults.TrailLength ?? TrailBallProjectile.DefaultTrailLength}"; - this.trailLengthTextField.Enabled = true; - } - else - { - var defaultText = NSBundle.MainBundle.GetLocalizedString("Default"); // when no custom selected - this.trailWidthTextField.Text = defaultText; - this.trailWidthTextField.Enabled = false; - this.trailLengthTextField.Text = defaultText; - this.trailLengthTextField.Enabled = false; - } - } - - partial void showARDebugChanged(UISwitch sender) - { - UserDefaults.ShowARDebug = sender.On; - } - - partial void showRenderStatsChanged(UISwitch sender) - { - UserDefaults.ShowSceneViewStats = sender.On; - } - - partial void showTrackingStateChanged(UISwitch sender) - { - UserDefaults.ShowTrackingState = sender.On; - } - - partial void showPhysicsChanged(UISwitch sender) - { - UserDefaults.ShowPhysicsDebug = sender.On; - } - - partial void showNetworkDebugChanged(UISwitch sender) - { - UserDefaults.ShowNetworkDebug = sender.On; - } - - partial void showWireframeChanged(UISwitch sender) - { - UserDefaults.ShowWireframe = sender.On; - } - - partial void antialiasingModeChanged(UISwitch sender) - { - UserDefaults.AntialiasingMode = sender.On; - } - - partial void enableGameRoomModeChanged(UISwitch sender) - { - UserDefaults.GameRoomMode = sender.On; - if (!this.proximityManager.IsAuthorized && sender.On) - { - // if trying to enable beacons without location permissions, display alert - var alertController = UIAlertController.Create(NSBundle.MainBundle.GetLocalizedString("Insufficient Location Permissions For Beacons"), // "User didn't enable location services" - NSBundle.MainBundle.GetLocalizedString("Please go to Settings and enable location services for XamarinShot to look for nearby beacons"), // "Steps the user can take to activate beacon" - UIAlertControllerStyle.Alert); - alertController.AddAction(UIAlertAction.Create(NSBundle.MainBundle.GetLocalizedString("Dismiss"), - UIAlertActionStyle.Default, - null)); - this.PresentViewController(alertController, true, null); - UserDefaults.GameRoomMode = false; - this.gameRoomModeSwitch.SetState(false, true); - } - } - - partial void useEncryptionChanged(UISwitch sender) - { - UserDefaults.UseEncryption = sender.On; - } - - partial void showSettingsChanged(UISwitch sender) - { - UserDefaults.ShowSettingsInGame = sender.On; - } - - partial void showARRelocalizationHelpChanged(UISwitch sender) - { - UserDefaults.ShowARRelocalizationHelp = sender.On; - } - - partial void showResetSwitch(UISwitch sender) - { - UserDefaults.ShowResetLever = sender.On; - } - - partial void showCloudsChanged(UISwitch sender) - { - UserDefaults.ShowClouds = sender.On; - } - - partial void showFlagsChanged(UISwitch sender) - { - UserDefaults.ShowFlags = sender.On; - } - - partial void showRopeSimulationChanged(UISwitch sender) - { - UserDefaults.ShowRopeSimulation = sender.On; - } - - partial void showLODChanged(UISwitch sender) - { - UserDefaults.ShowLOD = sender.On; - } - - partial void useAutofocus(UISwitch sender) - { - UserDefaults.AutoFocus = sender.On; - } - - partial void disableInGameUIChanged(UISwitch sender) - { - UserDefaults.DisableInGameUI = sender.On; - if (sender.On) - { - // also turn off everything else - UserDefaults.ShowARDebug = false; - UserDefaults.ShowPhysicsDebug = false; - UserDefaults.ShowARDebug = false; - UserDefaults.ShowWireframe = false; - UserDefaults.ShowSceneViewStats = false; - UserDefaults.ShowTrackingState = false; - UserDefaults.ShowSettingsInGame = false; - UserDefaults.ShowARRelocalizationHelp = false; - UserDefaults.ShowNetworkDebug = false; - UserDefaults.ShowLOD = false; - } - - this.ConfigureUISwitches(); - } - - partial void synchronizeMusicWithWallClockChanged(UISwitch sender) - { - UserDefaults.SynchronizeMusicWithWallClock = sender.On; - } - - #region projectile trail - - partial void allowGameBoardAutoSizeChanged(UISwitch sender) - { - UserDefaults.AllowGameBoardAutoSize = sender.On; - } - - partial void showProjectileTrailChanged(UISwitch sender) - { - UserDefaults.ShowProjectileTrail = sender.On; - } - - partial void useCustomTrailChanged(UISwitch sender) - { - UserDefaults.UseCustomTrail = sender.On; - this.ConfigureProjectileTrail(); - } - - partial void taperTrailChanged(UISwitch sender) - { - UserDefaults.TrailShouldNarrow = sender.On; - this.ConfigureProjectileTrail(); - } - - partial void showThermalStateChanged(UISwitch sender) - { - UserDefaults.ShowThermalState = sender.On; - } - - #endregion - - #region table delegate - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - this.TableView.DeselectRow(indexPath, true); - var cell = this.TableView.CellAt(indexPath); - if (cell != null) - { - if (cell == this.worldMapCell) - { - UserDefaults.BoardLocatingMode = BoardLocatingMode.WorldMap; - } - else if (cell == this.manualCell) - { - UserDefaults.BoardLocatingMode = BoardLocatingMode.Manual; - } - - this.ConfigureBoardLocationCells(); - } - } - - #endregion - - #region IUITextFieldDelegate - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - textField.ResignFirstResponder(); - return true; - } - - [Export("textFieldDidEndEditing:reason:")] - public void EditingEnded(UITextField textField, UITextFieldDidEndEditingReason reason) - { - if (textField == this.trailWidthTextField) - { - this.TrailWidthDidEndEditing(reason); - } - else if (textField == this.trailLengthTextField) - { - this.TrailLengthDidEndEditing(reason); - } - } - - private void TrailWidthDidEndEditing(UITextFieldDidEndEditingReason reason) - { - if(!string.IsNullOrEmpty(this.trailWidthTextField.Text) && - float.TryParse(this.trailWidthTextField.Text, out float newValue)) - { - UserDefaults.TrailWidth = newValue; // value stored in unit ball size (1.0 as trail width equal to ball size) - } - else - { - UserDefaults.TrailWidth = null; - } - - this.ConfigureProjectileTrail(); - } - - private void TrailLengthDidEndEditing(UITextFieldDidEndEditingReason reason) - { - if (!string.IsNullOrEmpty(this.trailLengthTextField.Text) && - int.TryParse(this.trailLengthTextField.Text, out int newValue)) - { - UserDefaults.TrailLength = newValue; - } - else - { - UserDefaults.TrailLength = null; - } - - this.ConfigureProjectileTrail(); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot { + using Foundation; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using UIKit; + + /// <summary> + /// View controller for development & debugging settings. + /// </summary> + public partial class DeveloperSettingsTableViewController : UITableViewController, IUITextFieldDelegate { + private readonly ProximityManager proximityManager = ProximityManager.Shared; + + private List<UISwitch> switches; + + public DeveloperSettingsTableViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // set default delegates + + this.TableView.Delegate = this; + this.TableView.DataSource = this; + this.trailWidthTextField.Delegate = this; + this.trailLengthTextField.Delegate = this; + + // initialize + + NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.DidBecomeActiveNotification, this.DidApplicationBecomeActive); + this.antialiasingMode.On = UserDefaults.AntialiasingMode; + this.useEncryptionSwitch.On = UserDefaults.UseEncryption; + + // if user turns of location permissions in settings after enabling them, we should turn off gameRoomMode + if (!this.proximityManager.IsAuthorized) { + UserDefaults.GameRoomMode = false; + } + + this.gameRoomModeSwitch.On = UserDefaults.GameRoomMode; + this.useAutofocusSwitch.On = UserDefaults.AutoFocus; + this.allowGameBoardAutoSizeSwitch.On = UserDefaults.AllowGameBoardAutoSize; + + // level + this.showResetLevelSwitch.On = UserDefaults.ShowResetLever; + this.showFlags.On = UserDefaults.ShowFlags; + this.showClouds.On = UserDefaults.ShowClouds; + this.showRopeSimulation.On = UserDefaults.ShowRopeSimulation; + + // happens here so the switches have been loaded from the storyboard + this.switches = new List<UISwitch> + { + this.showARDebugSwitch, this.showRenderStatsSwitch, + this.showTrackingStateSwitch, this.showWireframe, this.showLOD, + this.showPhysicsDebugSwitch, this.showSettingsSwitch, this.showARRelocalizationHelp, + this.showNetworkDebugSwitch, this.showThermalStateSwitch + }; + + this.ConfigureUISwitches (); + this.ConfigureBoardLocationCells (); + this.ConfigureProjectileTrail (); + } + + private void DidApplicationBecomeActive (NSNotification notification) + { + // check for permission changes after becoming active again + if (!this.proximityManager.IsAuthorized) { + UserDefaults.GameRoomMode = false; + } + + this.gameRoomModeSwitch.On = UserDefaults.GameRoomMode; + } + + private void ConfigureUISwitches () + { + this.disableInGameUISwitch.On = UserDefaults.DisableInGameUI; + this.showARDebugSwitch.On = UserDefaults.ShowARDebug; + this.showRenderStatsSwitch.On = UserDefaults.ShowSceneViewStats; + this.showTrackingStateSwitch.On = UserDefaults.ShowTrackingState; + this.showWireframe.On = UserDefaults.ShowWireframe; + this.showLOD.On = UserDefaults.ShowLOD; + this.showPhysicsDebugSwitch.On = UserDefaults.ShowPhysicsDebug; + this.showSettingsSwitch.On = UserDefaults.ShowSettingsInGame; + this.showARRelocalizationHelp.On = UserDefaults.ShowARRelocalizationHelp; + this.showNetworkDebugSwitch.On = UserDefaults.ShowNetworkDebug; + this.showProjectileTrailSwitch.On = UserDefaults.ShowProjectileTrail; + this.synchronizeMusicWithWallClockSwitch.On = UserDefaults.SynchronizeMusicWithWallClock; + this.showThermalStateSwitch.On = UserDefaults.ShowThermalState; + + foreach (var @switch in this.switches) { + @switch.Enabled = !UserDefaults.DisableInGameUI; + } + } + + private void ConfigureBoardLocationCells () + { + var boardLocationMode = UserDefaults.BoardLocatingMode; + this.worldMapCell.Accessory = boardLocationMode == BoardLocatingMode.WorldMap ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + this.manualCell.Accessory = boardLocationMode == BoardLocatingMode.Manual ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + } + + private void ConfigureProjectileTrail () + { + this.useCustomTrailSwitch.On = UserDefaults.UseCustomTrail; + this.taperTrailSwitch.On = UserDefaults.TrailShouldNarrow; + + if (UserDefaults.UseCustomTrail) { + var width = UserDefaults.TrailWidth ?? TrailBallProjectile.DefaultTrailWidth; + this.trailWidthTextField.Text = width.ToString (); + this.trailWidthTextField.Enabled = true; + this.trailLengthTextField.Text = $"{UserDefaults.TrailLength ?? TrailBallProjectile.DefaultTrailLength}"; + this.trailLengthTextField.Enabled = true; + } else { + var defaultText = NSBundle.MainBundle.GetLocalizedString ("Default"); // when no custom selected + this.trailWidthTextField.Text = defaultText; + this.trailWidthTextField.Enabled = false; + this.trailLengthTextField.Text = defaultText; + this.trailLengthTextField.Enabled = false; + } + } + + partial void showARDebugChanged (UISwitch sender) + { + UserDefaults.ShowARDebug = sender.On; + } + + partial void showRenderStatsChanged (UISwitch sender) + { + UserDefaults.ShowSceneViewStats = sender.On; + } + + partial void showTrackingStateChanged (UISwitch sender) + { + UserDefaults.ShowTrackingState = sender.On; + } + + partial void showPhysicsChanged (UISwitch sender) + { + UserDefaults.ShowPhysicsDebug = sender.On; + } + + partial void showNetworkDebugChanged (UISwitch sender) + { + UserDefaults.ShowNetworkDebug = sender.On; + } + + partial void showWireframeChanged (UISwitch sender) + { + UserDefaults.ShowWireframe = sender.On; + } + + partial void antialiasingModeChanged (UISwitch sender) + { + UserDefaults.AntialiasingMode = sender.On; + } + + partial void enableGameRoomModeChanged (UISwitch sender) + { + UserDefaults.GameRoomMode = sender.On; + if (!this.proximityManager.IsAuthorized && sender.On) { + // if trying to enable beacons without location permissions, display alert + var alertController = UIAlertController.Create (NSBundle.MainBundle.GetLocalizedString ("Insufficient Location Permissions For Beacons"), // "User didn't enable location services" + NSBundle.MainBundle.GetLocalizedString ("Please go to Settings and enable location services for XamarinShot to look for nearby beacons"), // "Steps the user can take to activate beacon" + UIAlertControllerStyle.Alert); + alertController.AddAction (UIAlertAction.Create (NSBundle.MainBundle.GetLocalizedString ("Dismiss"), + UIAlertActionStyle.Default, + null)); + this.PresentViewController (alertController, true, null); + UserDefaults.GameRoomMode = false; + this.gameRoomModeSwitch.SetState (false, true); + } + } + + partial void useEncryptionChanged (UISwitch sender) + { + UserDefaults.UseEncryption = sender.On; + } + + partial void showSettingsChanged (UISwitch sender) + { + UserDefaults.ShowSettingsInGame = sender.On; + } + + partial void showARRelocalizationHelpChanged (UISwitch sender) + { + UserDefaults.ShowARRelocalizationHelp = sender.On; + } + + partial void showResetSwitch (UISwitch sender) + { + UserDefaults.ShowResetLever = sender.On; + } + + partial void showCloudsChanged (UISwitch sender) + { + UserDefaults.ShowClouds = sender.On; + } + + partial void showFlagsChanged (UISwitch sender) + { + UserDefaults.ShowFlags = sender.On; + } + + partial void showRopeSimulationChanged (UISwitch sender) + { + UserDefaults.ShowRopeSimulation = sender.On; + } + + partial void showLODChanged (UISwitch sender) + { + UserDefaults.ShowLOD = sender.On; + } + + partial void useAutofocus (UISwitch sender) + { + UserDefaults.AutoFocus = sender.On; + } + + partial void disableInGameUIChanged (UISwitch sender) + { + UserDefaults.DisableInGameUI = sender.On; + if (sender.On) { + // also turn off everything else + UserDefaults.ShowARDebug = false; + UserDefaults.ShowPhysicsDebug = false; + UserDefaults.ShowARDebug = false; + UserDefaults.ShowWireframe = false; + UserDefaults.ShowSceneViewStats = false; + UserDefaults.ShowTrackingState = false; + UserDefaults.ShowSettingsInGame = false; + UserDefaults.ShowARRelocalizationHelp = false; + UserDefaults.ShowNetworkDebug = false; + UserDefaults.ShowLOD = false; + } + + this.ConfigureUISwitches (); + } + + partial void synchronizeMusicWithWallClockChanged (UISwitch sender) + { + UserDefaults.SynchronizeMusicWithWallClock = sender.On; + } + + #region projectile trail + + partial void allowGameBoardAutoSizeChanged (UISwitch sender) + { + UserDefaults.AllowGameBoardAutoSize = sender.On; + } + + partial void showProjectileTrailChanged (UISwitch sender) + { + UserDefaults.ShowProjectileTrail = sender.On; + } + + partial void useCustomTrailChanged (UISwitch sender) + { + UserDefaults.UseCustomTrail = sender.On; + this.ConfigureProjectileTrail (); + } + + partial void taperTrailChanged (UISwitch sender) + { + UserDefaults.TrailShouldNarrow = sender.On; + this.ConfigureProjectileTrail (); + } + + partial void showThermalStateChanged (UISwitch sender) + { + UserDefaults.ShowThermalState = sender.On; + } + + #endregion + + #region table delegate + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + this.TableView.DeselectRow (indexPath, true); + var cell = this.TableView.CellAt (indexPath); + if (cell != null) { + if (cell == this.worldMapCell) { + UserDefaults.BoardLocatingMode = BoardLocatingMode.WorldMap; + } else if (cell == this.manualCell) { + UserDefaults.BoardLocatingMode = BoardLocatingMode.Manual; + } + + this.ConfigureBoardLocationCells (); + } + } + + #endregion + + #region IUITextFieldDelegate + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + textField.ResignFirstResponder (); + return true; + } + + [Export ("textFieldDidEndEditing:reason:")] + public void EditingEnded (UITextField textField, UITextFieldDidEndEditingReason reason) + { + if (textField == this.trailWidthTextField) { + this.TrailWidthDidEndEditing (reason); + } else if (textField == this.trailLengthTextField) { + this.TrailLengthDidEndEditing (reason); + } + } + + private void TrailWidthDidEndEditing (UITextFieldDidEndEditingReason reason) + { + if (!string.IsNullOrEmpty (this.trailWidthTextField.Text) && + float.TryParse (this.trailWidthTextField.Text, out float newValue)) { + UserDefaults.TrailWidth = newValue; // value stored in unit ball size (1.0 as trail width equal to ball size) + } else { + UserDefaults.TrailWidth = null; + } + + this.ConfigureProjectileTrail (); + } + + private void TrailLengthDidEndEditing (UITextFieldDidEndEditingReason reason) + { + if (!string.IsNullOrEmpty (this.trailLengthTextField.Text) && + int.TryParse (this.trailLengthTextField.Text, out int newValue)) { + UserDefaults.TrailLength = newValue; + } else { + UserDefaults.TrailLength = null; + } + + this.ConfigureProjectileTrail (); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/GameStartViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/GameStartViewController.cs index a9fccc942..b38e8e06e 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/GameStartViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/GameStartViewController.cs @@ -1,161 +1,152 @@ - -namespace XamarinShot -{ - using Foundation; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using UIKit; - - public interface IGameStartViewControllerDelegate - { - void OnSoloGamePressed(UIViewController controller, UIButton button); - void OnGameSelected(UIViewController controller, NetworkSession game); - void OnGameStarted(UIViewController controller, NetworkSession game); - void OnSettingsSelected(UIViewController controller); - } - - /// <summary> - /// View controller for in-game 2D overlay UI. - /// </summary> - public partial class GameStartViewController : UIViewController, IProximityManagerDelegate - { - private readonly Player myself = UserDefaults.Myself; - - private readonly ProximityManager proximityManager = ProximityManager.Shared; - - private GameBrowser gameBrowser; - - private ButtonBeep backButtonBeep; - - private ButtonBeep buttonBeep; - - public GameStartViewController(IntPtr handle) : base(handle) { } - - public IGameStartViewControllerDelegate Delegate { get; set; } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.proximityManager.Delegate = this; - this.hostButton.ClipsToBounds = true; - this.hostButton.Layer.CornerRadius = 30f; - - this.joinButton.ClipsToBounds = true; - this.joinButton.Layer.CornerRadius = 30f; - - this.buttonBeep = ButtonBeep.Create("button_forward.wav", 0.5f); - this.backButtonBeep = ButtonBeep.Create("button_backward.wav", 0.5f); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - if (UserDefaults.GameRoomMode) - { - //os_log(.debug, "Will start beacon ranging") - this.proximityManager.Start(); - } - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (!string.IsNullOrEmpty(segue.Identifier) && - Enum.TryParse<GameSegue>(segue.Identifier, true, out var segueType)) - { - switch (segueType) - { - case GameSegue.EmbeddedGameBrowser: - if (segue.DestinationViewController is NetworkGameBrowserViewController browser) - { - this.gameBrowser = new GameBrowser(this.myself); - browser.Browser = this.gameBrowser; - browser.ProximityManager = this.proximityManager; - } - - break; - } - } - } - - public void JoinGame(NetworkSession session) - { - this.Delegate?.OnGameSelected(this, session); - this.SetupOverlayVC(); - } - - partial void startSoloGamePressed(UIButton sender) - { - this.Delegate?.OnSoloGamePressed(this, sender); - } - - partial void startGamePressed(UIButton sender) - { - this.buttonBeep.Play(); - this.StartGame(this.myself); - } - - partial void settingsPressed(UIButton sender) - { - this.Delegate?.OnSettingsSelected(this); - } - - partial void joinButtonPressed(UIButton sender) - { - this.buttonBeep.Play(); - this.ShowViews(false); - } - - partial void backButtonPressed(UIButton sender) - { - this.backButtonBeep.Play(); - this.SetupOverlayVC(); - } - - private void SetupOverlayVC() - { - this.ShowViews(true); - } - - private void ShowViews(bool forSetup) - { - UIView.Transition(this.View, 1d, UIViewAnimationOptions.TransitionCrossDissolve, () => - { - this.blurView.Hidden = forSetup; - this.browserContainerView.Hidden = forSetup; - this.backButton.Hidden = forSetup; - this.nearbyGamesLabel.Hidden = forSetup; - - this.joinButton.Hidden = !forSetup; - this.hostButton.Hidden = !forSetup; - }, null); - } - - private void StartGame(Player player) - { - GameTableLocation location = null; - if (UserDefaults.GameRoomMode) - { - location = this.proximityManager.ClosestLocation; - } - - var gameSession = new NetworkSession(player, true, location, this.myself); - this.Delegate?.OnGameStarted(this, gameSession); - this.SetupOverlayVC(); - } - - #region IProximityManagerDelegate - - public void LocationChanged(ProximityManager manager, GameTableLocation location) - { - this.gameBrowser?.Refresh(); - } - - public void AuthorizationChanged(ProximityManager manager, bool authorization) { } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot { + using Foundation; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using UIKit; + + public interface IGameStartViewControllerDelegate { + void OnSoloGamePressed (UIViewController controller, UIButton button); + void OnGameSelected (UIViewController controller, NetworkSession game); + void OnGameStarted (UIViewController controller, NetworkSession game); + void OnSettingsSelected (UIViewController controller); + } + + /// <summary> + /// View controller for in-game 2D overlay UI. + /// </summary> + public partial class GameStartViewController : UIViewController, IProximityManagerDelegate { + private readonly Player myself = UserDefaults.Myself; + + private readonly ProximityManager proximityManager = ProximityManager.Shared; + + private GameBrowser gameBrowser; + + private ButtonBeep backButtonBeep; + + private ButtonBeep buttonBeep; + + public GameStartViewController (IntPtr handle) : base (handle) { } + + public IGameStartViewControllerDelegate Delegate { get; set; } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.proximityManager.Delegate = this; + this.hostButton.ClipsToBounds = true; + this.hostButton.Layer.CornerRadius = 30f; + + this.joinButton.ClipsToBounds = true; + this.joinButton.Layer.CornerRadius = 30f; + + this.buttonBeep = ButtonBeep.Create ("button_forward.wav", 0.5f); + this.backButtonBeep = ButtonBeep.Create ("button_backward.wav", 0.5f); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + if (UserDefaults.GameRoomMode) { + //os_log(.debug, "Will start beacon ranging") + this.proximityManager.Start (); + } + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (!string.IsNullOrEmpty (segue.Identifier) && + Enum.TryParse<GameSegue> (segue.Identifier, true, out var segueType)) { + switch (segueType) { + case GameSegue.EmbeddedGameBrowser: + if (segue.DestinationViewController is NetworkGameBrowserViewController browser) { + this.gameBrowser = new GameBrowser (this.myself); + browser.Browser = this.gameBrowser; + browser.ProximityManager = this.proximityManager; + } + + break; + } + } + } + + public void JoinGame (NetworkSession session) + { + this.Delegate?.OnGameSelected (this, session); + this.SetupOverlayVC (); + } + + partial void startSoloGamePressed (UIButton sender) + { + this.Delegate?.OnSoloGamePressed (this, sender); + } + + partial void startGamePressed (UIButton sender) + { + this.buttonBeep.Play (); + this.StartGame (this.myself); + } + + partial void settingsPressed (UIButton sender) + { + this.Delegate?.OnSettingsSelected (this); + } + + partial void joinButtonPressed (UIButton sender) + { + this.buttonBeep.Play (); + this.ShowViews (false); + } + + partial void backButtonPressed (UIButton sender) + { + this.backButtonBeep.Play (); + this.SetupOverlayVC (); + } + + private void SetupOverlayVC () + { + this.ShowViews (true); + } + + private void ShowViews (bool forSetup) + { + UIView.Transition (this.View, 1d, UIViewAnimationOptions.TransitionCrossDissolve, () => { + this.blurView.Hidden = forSetup; + this.browserContainerView.Hidden = forSetup; + this.backButton.Hidden = forSetup; + this.nearbyGamesLabel.Hidden = forSetup; + + this.joinButton.Hidden = !forSetup; + this.hostButton.Hidden = !forSetup; + }, null); + } + + private void StartGame (Player player) + { + GameTableLocation location = null; + if (UserDefaults.GameRoomMode) { + location = this.proximityManager.ClosestLocation; + } + + var gameSession = new NetworkSession (player, true, location, this.myself); + this.Delegate?.OnGameStarted (this, gameSession); + this.SetupOverlayVC (); + } + + #region IProximityManagerDelegate + + public void LocationChanged (ProximityManager manager, GameTableLocation location) + { + this.gameBrowser?.Refresh (); + } + + public void AuthorizationChanged (ProximityManager manager, bool authorization) { } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+ARSCNViewDelegate.cs b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+ARSCNViewDelegate.cs index 64972c657..9a4f6f6b8 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+ARSCNViewDelegate.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+ARSCNViewDelegate.cs @@ -1,126 +1,115 @@ - -namespace XamarinShot -{ - using ARKit; - using CoreFoundation; - using Foundation; - using SceneKit; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using System.Linq; - - /// <summary> - /// ARSCNViewDelegate methods for the Game Scene View Controller. - /// </summary> - partial class GameViewController : IARSCNViewDelegate - { - [Export("renderer:nodeForAnchor:")] - public SCNNode GetNode(SceneKit.ISCNSceneRenderer renderer, ARKit.ARAnchor anchor) - { - SCNNode result = null; - if (anchor == this.gameBoard.Anchor) - { - // If board anchor was added, setup the level. - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (this.sessionState == SessionState.LocalizingToBoard) - { - this.SessionState = SessionState.SetupLevel; - } - }); - - // We already created a node for the board anchor - result = this.gameBoard; - } - - return result; - } - - [Export("renderer:didUpdateNode:forAnchor:")] - public void DidUpdateNode(ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) - { - if (anchor is BoardAnchor boardAnchor) - { - // Update the game board's scale from the board anchor - // The transform will have already been updated - without the scale - var width = (float)boardAnchor.Size.Width; - node.Scale = new SCNVector3(width, width, width); - } - } - - [Export("session:cameraDidChangeTrackingState:")] - public void CameraDidChangeTrackingState(ARSession session, ARCamera camera) - { - //os_log(.info, "camera tracking state changed to %s", "\(camera.trackingState)") - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.trackingStateLabel.Text = camera.TrackingState.ToString(); - }); - - switch (camera.TrackingState) - { - case ARTrackingState.Normal: - // Resume game if previously interrupted - if (this.isSessionInterrupted) - { - this.IsSessionInterrupted = false; - } - - // Fade in the board if previously hidden - if (this.gameBoard.Hidden) - { - this.gameBoard.Opacity = 1f; - this.gameBoard.Hidden = false; - } - - // Fade in the level if previously hidden - if (this.renderRoot.Opacity == 0f) - { - this.renderRoot.Opacity = 1f; - } - break; - - case ARTrackingState.Limited: - // Hide the game board and level if tracking is limited - this.gameBoard.Hidden = true; - this.renderRoot.Opacity = 0f; - break; - } - } - - [Export("session:didFailWithError:")] - public void DidFail(ARSession session, NSError error) - { - // Get localized strings from error - string[] messages = - { - error.LocalizedDescription, - error.LocalizedFailureReason, - error.LocalizedRecoverySuggestion - }; - - // Use `compactMap(_:)` to remove optional error messages. - var errorMessage = string.Join("\n", messages.Where(message => !string.IsNullOrEmpty(message))); - - // Present the error message to the user - this.ShowAlert("Session Error", errorMessage); - } - - [Export("sessionWasInterrupted:")] - public void WasInterrupted(ARSession session) - { - // Inform the user that the session has been interrupted - this.IsSessionInterrupted = true; - - // Hide game board and level - this.gameBoard.Hidden = true; - this.renderRoot.Opacity = 0f; - } - - [Export("sessionShouldAttemptRelocalization:")] - public bool ShouldAttemptRelocalization(ARSession session) - { - return true; - } - } -} \ No newline at end of file + +namespace XamarinShot { + using ARKit; + using CoreFoundation; + using Foundation; + using SceneKit; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using System.Linq; + + /// <summary> + /// ARSCNViewDelegate methods for the Game Scene View Controller. + /// </summary> + partial class GameViewController : IARSCNViewDelegate { + [Export ("renderer:nodeForAnchor:")] + public SCNNode GetNode (SceneKit.ISCNSceneRenderer renderer, ARKit.ARAnchor anchor) + { + SCNNode result = null; + if (anchor == this.gameBoard.Anchor) { + // If board anchor was added, setup the level. + DispatchQueue.MainQueue.DispatchAsync (() => { + if (this.sessionState == SessionState.LocalizingToBoard) { + this.SessionState = SessionState.SetupLevel; + } + }); + + // We already created a node for the board anchor + result = this.gameBoard; + } + + return result; + } + + [Export ("renderer:didUpdateNode:forAnchor:")] + public void DidUpdateNode (ISCNSceneRenderer renderer, SCNNode node, ARAnchor anchor) + { + if (anchor is BoardAnchor boardAnchor) { + // Update the game board's scale from the board anchor + // The transform will have already been updated - without the scale + var width = (float) boardAnchor.Size.Width; + node.Scale = new SCNVector3 (width, width, width); + } + } + + [Export ("session:cameraDidChangeTrackingState:")] + public void CameraDidChangeTrackingState (ARSession session, ARCamera camera) + { + //os_log(.info, "camera tracking state changed to %s", "\(camera.trackingState)") + DispatchQueue.MainQueue.DispatchAsync (() => { + this.trackingStateLabel.Text = camera.TrackingState.ToString (); + }); + + switch (camera.TrackingState) { + case ARTrackingState.Normal: + // Resume game if previously interrupted + if (this.isSessionInterrupted) { + this.IsSessionInterrupted = false; + } + + // Fade in the board if previously hidden + if (this.gameBoard.Hidden) { + this.gameBoard.Opacity = 1f; + this.gameBoard.Hidden = false; + } + + // Fade in the level if previously hidden + if (this.renderRoot.Opacity == 0f) { + this.renderRoot.Opacity = 1f; + } + break; + + case ARTrackingState.Limited: + // Hide the game board and level if tracking is limited + this.gameBoard.Hidden = true; + this.renderRoot.Opacity = 0f; + break; + } + } + + [Export ("session:didFailWithError:")] + public void DidFail (ARSession session, NSError error) + { + // Get localized strings from error + string [] messages = + { + error.LocalizedDescription, + error.LocalizedFailureReason, + error.LocalizedRecoverySuggestion + }; + + // Use `compactMap(_:)` to remove optional error messages. + var errorMessage = string.Join ("\n", messages.Where (message => !string.IsNullOrEmpty (message))); + + // Present the error message to the user + this.ShowAlert ("Session Error", errorMessage); + } + + [Export ("sessionWasInterrupted:")] + public void WasInterrupted (ARSession session) + { + // Inform the user that the session has been interrupted + this.IsSessionInterrupted = true; + + // Hide game board and level + this.gameBoard.Hidden = true; + this.renderRoot.Opacity = 0f; + } + + [Export ("sessionShouldAttemptRelocalization:")] + public bool ShouldAttemptRelocalization (ARSession session) + { + return true; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Gestures.cs b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Gestures.cs index 27f553743..a0b8e982f 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Gestures.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Gestures.cs @@ -1,173 +1,144 @@ - -namespace XamarinShot -{ - using ARKit; - using Foundation; - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Models.GestureRecognizers; - using System; - using System.Linq; - using UIKit; - - /// <summary> - /// Gesture interaction methods for the Game Scene View Controller. - /// </summary> - partial class GameViewController : IUIGestureRecognizerDelegate - { - partial void handleTap(UITapGestureRecognizer gesture) - { - if (gesture.State == UIGestureRecognizerState.Ended) - { - var location = gesture.LocationInView(this.sceneView); - - switch (this.sessionState) - { - case SessionState.PlacingBoard: - case SessionState.AdjustingBoard: - if (!this.gameBoard.IsBorderHidden) - { - this.SessionState = SessionState.SetupLevel; - } - break; - - case SessionState.GameInProgress: - this.gameManager?.HandleTouch(TouchType.Tapped); - break; - } - } - } - - partial void handlePinch(ThresholdPinchGestureRecognizer gesture) - { - if (this.CanAdjustBoard) - { - this.SessionState = SessionState.AdjustingBoard; - - switch (gesture.State) - { - case UIGestureRecognizerState.Changed: - if (gesture.IsThresholdExceeded) - { - this.gameBoard.UpdateScale((float)gesture.Scale); - gesture.Scale = 1f; - } - break; - } - } - } - - partial void handleRotation(ThresholdRotationGestureRecognizer gesture) - { - if (this.CanAdjustBoard) - { - this.SessionState = SessionState.AdjustingBoard; - - switch (gesture.State) - { - case UIGestureRecognizerState.Changed: - if (gesture.IsThresholdExceeded) - { - var newY = this.gameBoard.EulerAngles.Y; - if (this.gameBoard.EulerAngles.X > Math.PI / 2d) - { - newY += (float)gesture.Rotation; - } - else - { - newY -= (float)gesture.Rotation; - } - - this.gameBoard.EulerAngles = new SCNVector3(this.gameBoard.EulerAngles.X, newY, this.gameBoard.EulerAngles.Z); - gesture.Rotation = 0f; - } - break; - } - } - } - - - partial void handlePan(ThresholdPanGestureRecognizer gesture) - { - if (this.CanAdjustBoard) - { - this.SessionState = SessionState.AdjustingBoard; - - var location = gesture.LocationInView(this.sceneView); - var results = this.sceneView.HitTest(location, ARHitTestResultType.ExistingPlane); - var nearestPlane = results.FirstOrDefault(); - if (nearestPlane != null) - { - switch (gesture.State) - { - case UIGestureRecognizerState.Began: - this.panOffset = nearestPlane.WorldTransform.Column3.Xyz - this.gameBoard.WorldPosition; - break; - case UIGestureRecognizerState.Changed: - this.gameBoard.WorldPosition = nearestPlane.WorldTransform.Column3.Xyz - this.panOffset; - break; - } - } - } - } - - private void HandleLongPress(UILongPressGestureRecognizer gesture) - { - if (this.CanAdjustBoard) - { - this.SessionState = SessionState.AdjustingBoard; - this.gameBoard.UseDefaultScale(); - } - } - - public override void TouchesBegan(NSSet touches, UIEvent evt) - { - this.Touch(TouchType.Began); - } - - public override void TouchesEnded(NSSet touches, UIEvent evt) - { - this.Touch(TouchType.Ended); - } - - public override void TouchesCancelled(NSSet touches, UIEvent evt) - { - this.Touch(TouchType.Ended); - } - - private void Touch(TouchType type) - { - this.gameManager?.HandleTouch(type); - } - - private bool GestureRecognizer(UIGestureRecognizer first, UIGestureRecognizer second) - { - if (first is UIRotationGestureRecognizer && second is UIPinchGestureRecognizer) - { - return true; - } - else if (first is UIRotationGestureRecognizer && second is UIPanGestureRecognizer) - { - return true; - } - else if (first is UIPinchGestureRecognizer && second is UIRotationGestureRecognizer) - { - return true; - } - else if (first is UIPinchGestureRecognizer && second is UIPanGestureRecognizer) - { - return true; - } - else if (first is UIPanGestureRecognizer && second is UIPinchGestureRecognizer) - { - return true; - } - else if (first is UIPanGestureRecognizer && second is UIRotationGestureRecognizer) - { - return true; - } - - return false; - } - } -} \ No newline at end of file + +namespace XamarinShot { + using ARKit; + using Foundation; + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Models.GestureRecognizers; + using System; + using System.Linq; + using UIKit; + + /// <summary> + /// Gesture interaction methods for the Game Scene View Controller. + /// </summary> + partial class GameViewController : IUIGestureRecognizerDelegate { + partial void handleTap (UITapGestureRecognizer gesture) + { + if (gesture.State == UIGestureRecognizerState.Ended) { + var location = gesture.LocationInView (this.sceneView); + + switch (this.sessionState) { + case SessionState.PlacingBoard: + case SessionState.AdjustingBoard: + if (!this.gameBoard.IsBorderHidden) { + this.SessionState = SessionState.SetupLevel; + } + break; + + case SessionState.GameInProgress: + this.gameManager?.HandleTouch (TouchType.Tapped); + break; + } + } + } + + partial void handlePinch (ThresholdPinchGestureRecognizer gesture) + { + if (this.CanAdjustBoard) { + this.SessionState = SessionState.AdjustingBoard; + + switch (gesture.State) { + case UIGestureRecognizerState.Changed: + if (gesture.IsThresholdExceeded) { + this.gameBoard.UpdateScale ((float) gesture.Scale); + gesture.Scale = 1f; + } + break; + } + } + } + + partial void handleRotation (ThresholdRotationGestureRecognizer gesture) + { + if (this.CanAdjustBoard) { + this.SessionState = SessionState.AdjustingBoard; + + switch (gesture.State) { + case UIGestureRecognizerState.Changed: + if (gesture.IsThresholdExceeded) { + var newY = this.gameBoard.EulerAngles.Y; + if (this.gameBoard.EulerAngles.X > Math.PI / 2d) { + newY += (float) gesture.Rotation; + } else { + newY -= (float) gesture.Rotation; + } + + this.gameBoard.EulerAngles = new SCNVector3 (this.gameBoard.EulerAngles.X, newY, this.gameBoard.EulerAngles.Z); + gesture.Rotation = 0f; + } + break; + } + } + } + + + partial void handlePan (ThresholdPanGestureRecognizer gesture) + { + if (this.CanAdjustBoard) { + this.SessionState = SessionState.AdjustingBoard; + + var location = gesture.LocationInView (this.sceneView); + var results = this.sceneView.HitTest (location, ARHitTestResultType.ExistingPlane); + var nearestPlane = results.FirstOrDefault (); + if (nearestPlane != null) { + switch (gesture.State) { + case UIGestureRecognizerState.Began: + this.panOffset = nearestPlane.WorldTransform.Column3.Xyz - this.gameBoard.WorldPosition; + break; + case UIGestureRecognizerState.Changed: + this.gameBoard.WorldPosition = nearestPlane.WorldTransform.Column3.Xyz - this.panOffset; + break; + } + } + } + } + + private void HandleLongPress (UILongPressGestureRecognizer gesture) + { + if (this.CanAdjustBoard) { + this.SessionState = SessionState.AdjustingBoard; + this.gameBoard.UseDefaultScale (); + } + } + + public override void TouchesBegan (NSSet touches, UIEvent evt) + { + this.Touch (TouchType.Began); + } + + public override void TouchesEnded (NSSet touches, UIEvent evt) + { + this.Touch (TouchType.Ended); + } + + public override void TouchesCancelled (NSSet touches, UIEvent evt) + { + this.Touch (TouchType.Ended); + } + + private void Touch (TouchType type) + { + this.gameManager?.HandleTouch (type); + } + + private bool GestureRecognizer (UIGestureRecognizer first, UIGestureRecognizer second) + { + if (first is UIRotationGestureRecognizer && second is UIPinchGestureRecognizer) { + return true; + } else if (first is UIRotationGestureRecognizer && second is UIPanGestureRecognizer) { + return true; + } else if (first is UIPinchGestureRecognizer && second is UIRotationGestureRecognizer) { + return true; + } else if (first is UIPinchGestureRecognizer && second is UIPanGestureRecognizer) { + return true; + } else if (first is UIPanGestureRecognizer && second is UIPinchGestureRecognizer) { + return true; + } else if (first is UIPanGestureRecognizer && second is UIRotationGestureRecognizer) { + return true; + } + + return false; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Maps.cs b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Maps.cs index 7e5be7efe..f6b0f22f3 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Maps.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController+Maps.cs @@ -1,410 +1,350 @@ - -namespace XamarinShot -{ - using ARKit; - using CoreFoundation; - using Foundation; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using System.Linq; - using UIKit; - - /// <summary> - /// Maps saving and loading methods for the Game Scene View Controller. - /// </summary> - partial class GameViewController : IUIDocumentPickerDelegate, IWorldMapSelectorDelegate - { - #region Relocalization Help - - private void ConfigureRelocalizationHelp() - { - if (UserDefaults.ShowARRelocalizationHelp) - { - switch (this.sessionState) - { - case SessionState.LookingForSurface: - case SessionState.PlacingBoard: - case SessionState.AdjustingBoard: - this.ShowRelocalizationHelp(false); - break; - - case SessionState.LocalizingToBoard: - var anchor = this.targetWorldMap?.KeyPositionAnchors()?.FirstOrDefault(); - if (anchor != null) - { - this.ShowRelocalizationHelp(true); - this.SetKeyPositionThumbnail(anchor.Image); - } - break; - - default: - this.HideRelocalizationHelp(); - break; - } - } - else - { - this.HideRelocalizationHelp(); - } - } - - private void ShowRelocalizationHelp(bool isClient) - { - if (!isClient) - { - this.saveAsKeyPositionButton.Hidden = false; - } - else - { - this.keyPositionThumbnail.Hidden = false; - this.nextKeyPositionThumbnailButton.Hidden = false; - this.previousKeyPositionThumbnailButton.Hidden = false; - } - } - - private void HideRelocalizationHelp() - { - this.keyPositionThumbnail.Hidden = true; - this.saveAsKeyPositionButton.Hidden = true; - this.nextKeyPositionThumbnailButton.Hidden = true; - this.previousKeyPositionThumbnailButton.Hidden = true; - } - - private void SetKeyPositionThumbnail(UIImage image) - { - this.keyPositionThumbnail.Image = image; - } - - partial void saveAsKeyPositionPressed(UIButton sender) - { - // Save the current position as an ARAnchor and store it in the worldmap for later use when re-localizing to guide users - UIImage image = null; - OpenTK.NMatrix4? pose = null; - var mappingStatus = ARWorldMappingStatus.NotAvailable; - - if (this.sceneView.Session.CurrentFrame != null) - { - image = this.sceneView.CreateScreenshot(UIDevice.CurrentDevice.Orientation); - pose = this.sceneView.Session.CurrentFrame.Camera.Transform; - mappingStatus = this.sceneView.Session.CurrentFrame.WorldMappingStatus; - } - - // Add key position anchor to the scene - if (pose.HasValue && image != null) - { - var newKeyPosition = new KeyPositionAnchor(image, pose.Value, mappingStatus); - this.sceneView.Session.AddAnchor(newKeyPosition); - } - } - - partial void showNextKeyPositionThumbnail(UIButton sender) - { - if (this.keyPositionThumbnail.Image != null) - { - // Get the key position anchors from the current world map - var keyPositionAnchors = this.targetWorldMap?.KeyPositionAnchors(); - if (keyPositionAnchors != null) - { - // Get the current key position anchor displayed - var currentKeyPositionAnchor = keyPositionAnchors.FirstOrDefault(anchor => anchor.Image == this.keyPositionThumbnail.Image); - if (currentKeyPositionAnchor != null) - { - var currentIndex = keyPositionAnchors.IndexOf(currentKeyPositionAnchor); - if (currentIndex != -1) - { - var nextIndex = (currentIndex + 1) % keyPositionAnchors.Count; - this.SetKeyPositionThumbnail(keyPositionAnchors[nextIndex].Image); - } - } - } - } - } - - partial void showPreviousKeyPositionThumbnail(UIButton sender) - { - var image = this.keyPositionThumbnail.Image; - if (image != null) - { - // Get the key position anchors from the current world map - var keyPositionAnchors = this.targetWorldMap?.KeyPositionAnchors(); - if (keyPositionAnchors != null) - { - // Get the current key position anchor displayed - var currentKeyPositionAnchor = keyPositionAnchors.FirstOrDefault(anchor => anchor.Image == image); - if (currentKeyPositionAnchor != null) - { - var currentIndex = keyPositionAnchors.IndexOf(currentKeyPositionAnchor); - if (currentIndex != -1) - { - var nextIndex = currentIndex; - if (currentIndex == 0 && keyPositionAnchors.Count > 1) - { - nextIndex = keyPositionAnchors.Count - 1; - } - else if (currentIndex - 1 >= 0) - { - nextIndex = currentIndex - 1; - } - else - { - nextIndex = 0; - } - - this.SetKeyPositionThumbnail(keyPositionAnchors[nextIndex].Image); - } - } - } - } - } - - #endregion - - #region Saving and Loading Maps - - private void ConfigureMappingUI() - { - var showMappingState = this.sessionState != SessionState.GameInProgress && - this.sessionState != SessionState.Setup && - this.sessionState != SessionState.LocalizingToBoard && - UserDefaults.ShowARDebug; - //TODO: - this.mappingStateLabel.Hidden = !showMappingState; - //this.saveButton.Hidden = this.sessionState == SessionState.setup; - //this.loadButton.Hidden = this.sessionState == SessionState.setup; - } - - private void UpdateMappingStatus(ARWorldMappingStatus mappingStatus) - { - // Check the mapping status of the worldmap to be able to save the worldmap when in a good state - switch (mappingStatus) - { - case ARWorldMappingStatus.NotAvailable: - this.mappingStateLabel.Text = "Mapping state: Not Available"; - this.mappingStateLabel.TextColor = UIColor.Red; - this.saveAsKeyPositionButton.Enabled = false; - //this.saveButton.Enabled = false; - break; - - case ARWorldMappingStatus.Limited: - this.mappingStateLabel.Text = "Mapping state: Limited"; - this.mappingStateLabel.TextColor = UIColor.Red; - this.saveAsKeyPositionButton.Enabled = false; - //this.saveButton.Enabled = false; - break; - - case ARWorldMappingStatus.Extending: - this.mappingStateLabel.Text = "Mapping state: Extending"; - this.mappingStateLabel.TextColor = UIColor.Red; - this.saveAsKeyPositionButton.Enabled = false; - //this.saveButton.Enabled = false; - break; - - case ARWorldMappingStatus.Mapped: - this.mappingStateLabel.Text = "Mapping state: Mapped"; - this.mappingStateLabel.TextColor = UIColor.Green; - this.saveAsKeyPositionButton.Enabled = true; - //this.saveButton.Enabled = true; - break; - } - } - - private void GetCurrentWorldMapData(Action<NSData, NSError> closure) - { - //os_log(.info, "in getCurrentWordMapData") - // When loading a map, send the loaded map and not the current extended map - if (this.targetWorldMap != null) - { - //os_log(.info, "using existing worldmap, not asking session for a new one.") - this.CompressMap(this.targetWorldMap, closure); - } - else - { - //os_log(.info, "asking ARSession for the world map") - this.sceneView.Session.GetCurrentWorldMap((map, error) => - { - //os_log(.info, "ARSession getCurrentWorldMap returned") - if (error != null) - { - //os_log(.error, "didn't work! %s", "\(error)") - closure(null, error); - } - - if (map != null) - { - //os_log(.info, "got a worldmap, compressing it") - this.CompressMap(map, closure); - } - }); - } - } - - [Action("savePressed:")] - private void SavePressed(UIButton sender) - { - this.activityIndicator.StartAnimating(); - this.GetCurrentWorldMapData((data, error) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.activityIndicator.StopAnimating(); - if (error != null) - { - var title = error.LocalizedDescription; - var message = error.LocalizedFailureReason; - this.ShowAlert(title, message); - return; - } - - if (data != null) - { - this.ShowSaveDialog(data); - } - }); - }); - } - - [Action("loadPressed:")] - private void LoadPressed(UIButton sender) - { - var picker = new UIDocumentPickerViewController(new string[] { "com.apple.xamarin-shot.worldmap" }, UIDocumentPickerMode.Open) - { - AllowsMultipleSelection = false, - Delegate = this, - }; - this.PresentViewController(picker, true, null); - } - - private void ShowSaveDialog(NSData data) - { - var dialog = UIAlertController.Create("Save World Map", null, UIAlertControllerStyle.Alert); - dialog.AddTextField(null); - var saveAction = UIAlertAction.Create("Save", UIAlertActionStyle.Default, (action) => - { - var fileName = dialog.TextFields?.FirstOrDefault()?.Text; - if (!string.IsNullOrEmpty(fileName)) - { - DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Background).DispatchAsync(() => - { - var docs = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out NSError error); - if (error == null) - { - var maps = docs.Append("maps", true); - NSFileManager.DefaultManager.CreateDirectory(maps, true, null, out NSError creationError); - var targetURL = maps.Append(fileName, false).AppendPathExtension("xamarinshotmap"); - data.Save(targetURL, NSDataWritingOptions.Atomic, out NSError saveingError); - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.ShowAlert("Saved"); - }); - } - else - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.ShowAlert(error.LocalizedDescription, null); - }); - } - }); - } - }); - - var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null); - - dialog.AddAction(saveAction); - dialog.AddAction(cancelAction); - - this.PresentViewController(dialog, true, null); - } - - /// <summary> - /// Get the archived data from a URL Path - /// </summary> - private void FetchArchivedWorldMap(NSUrl url, Action<NSData, NSError> closure) - { - DispatchQueue.DefaultGlobalQueue.DispatchAsync(() => - { - try - { - _ = url.StartAccessingSecurityScopedResource(); - var data = NSData.FromUrl(url); - closure(data, null); - } - catch - { - // TODO: - //DispatchQueue.MainQueue.DispatchAsync(() => - //{ - // this.ShowAlert(error.LocalizedDescription); - //}); - - //closure(null, error); - } - finally - { - url.StopAccessingSecurityScopedResource(); - } - }); - } - - private void CompressMap(ARWorldMap map, Action<NSData, NSError> closure) - { - DispatchQueue.DefaultGlobalQueue.DispatchAsync(() => - { - var data = NSKeyedArchiver.ArchivedDataWithRootObject(map, true, out NSError error); - if (error == null) - { - closure(data, null); - } - else - { - // archiving failed - closure(null, error); - } - }); - } - - #endregion - - #region UIDocumentPickerDelegate - - [Export("documentPicker:didPickDocumentsAtURLs:")] - public void DidPickDocument(UIDocumentPickerViewController controller, NSUrl[] urls) - { - var selected = urls.FirstOrDefault(); - if (selected != null) - { - this.FetchArchivedWorldMap(selected, (data, error) => - { - if (error == null && data != null) - { - this.LoadWorldMap(data); - } - }); - } - } - - public void DidPickDocument(UIDocumentPickerViewController controller, NSUrl url) - { - this.DidPickDocument(controller, new NSUrl[] { url }); - } - - #endregion - - #region IWorldMapSelectorDelegate - - public void WorldMapSelector(WorldMapSelectorViewController worldMapSelector, Uri selectedMap) - { - this.FetchArchivedWorldMap(selectedMap, (data, error) => - { - if (error == null && data != null) - { - this.LoadWorldMap(data); - } - }); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot { + using ARKit; + using CoreFoundation; + using Foundation; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using System.Linq; + using UIKit; + + /// <summary> + /// Maps saving and loading methods for the Game Scene View Controller. + /// </summary> + partial class GameViewController : IUIDocumentPickerDelegate, IWorldMapSelectorDelegate { + #region Relocalization Help + + private void ConfigureRelocalizationHelp () + { + if (UserDefaults.ShowARRelocalizationHelp) { + switch (this.sessionState) { + case SessionState.LookingForSurface: + case SessionState.PlacingBoard: + case SessionState.AdjustingBoard: + this.ShowRelocalizationHelp (false); + break; + + case SessionState.LocalizingToBoard: + var anchor = this.targetWorldMap?.KeyPositionAnchors ()?.FirstOrDefault (); + if (anchor != null) { + this.ShowRelocalizationHelp (true); + this.SetKeyPositionThumbnail (anchor.Image); + } + break; + + default: + this.HideRelocalizationHelp (); + break; + } + } else { + this.HideRelocalizationHelp (); + } + } + + private void ShowRelocalizationHelp (bool isClient) + { + if (!isClient) { + this.saveAsKeyPositionButton.Hidden = false; + } else { + this.keyPositionThumbnail.Hidden = false; + this.nextKeyPositionThumbnailButton.Hidden = false; + this.previousKeyPositionThumbnailButton.Hidden = false; + } + } + + private void HideRelocalizationHelp () + { + this.keyPositionThumbnail.Hidden = true; + this.saveAsKeyPositionButton.Hidden = true; + this.nextKeyPositionThumbnailButton.Hidden = true; + this.previousKeyPositionThumbnailButton.Hidden = true; + } + + private void SetKeyPositionThumbnail (UIImage image) + { + this.keyPositionThumbnail.Image = image; + } + + partial void saveAsKeyPositionPressed (UIButton sender) + { + // Save the current position as an ARAnchor and store it in the worldmap for later use when re-localizing to guide users + UIImage image = null; + OpenTK.NMatrix4? pose = null; + var mappingStatus = ARWorldMappingStatus.NotAvailable; + + if (this.sceneView.Session.CurrentFrame != null) { + image = this.sceneView.CreateScreenshot (UIDevice.CurrentDevice.Orientation); + pose = this.sceneView.Session.CurrentFrame.Camera.Transform; + mappingStatus = this.sceneView.Session.CurrentFrame.WorldMappingStatus; + } + + // Add key position anchor to the scene + if (pose.HasValue && image != null) { + var newKeyPosition = new KeyPositionAnchor (image, pose.Value, mappingStatus); + this.sceneView.Session.AddAnchor (newKeyPosition); + } + } + + partial void showNextKeyPositionThumbnail (UIButton sender) + { + if (this.keyPositionThumbnail.Image != null) { + // Get the key position anchors from the current world map + var keyPositionAnchors = this.targetWorldMap?.KeyPositionAnchors (); + if (keyPositionAnchors != null) { + // Get the current key position anchor displayed + var currentKeyPositionAnchor = keyPositionAnchors.FirstOrDefault (anchor => anchor.Image == this.keyPositionThumbnail.Image); + if (currentKeyPositionAnchor != null) { + var currentIndex = keyPositionAnchors.IndexOf (currentKeyPositionAnchor); + if (currentIndex != -1) { + var nextIndex = (currentIndex + 1) % keyPositionAnchors.Count; + this.SetKeyPositionThumbnail (keyPositionAnchors [nextIndex].Image); + } + } + } + } + } + + partial void showPreviousKeyPositionThumbnail (UIButton sender) + { + var image = this.keyPositionThumbnail.Image; + if (image != null) { + // Get the key position anchors from the current world map + var keyPositionAnchors = this.targetWorldMap?.KeyPositionAnchors (); + if (keyPositionAnchors != null) { + // Get the current key position anchor displayed + var currentKeyPositionAnchor = keyPositionAnchors.FirstOrDefault (anchor => anchor.Image == image); + if (currentKeyPositionAnchor != null) { + var currentIndex = keyPositionAnchors.IndexOf (currentKeyPositionAnchor); + if (currentIndex != -1) { + var nextIndex = currentIndex; + if (currentIndex == 0 && keyPositionAnchors.Count > 1) { + nextIndex = keyPositionAnchors.Count - 1; + } else if (currentIndex - 1 >= 0) { + nextIndex = currentIndex - 1; + } else { + nextIndex = 0; + } + + this.SetKeyPositionThumbnail (keyPositionAnchors [nextIndex].Image); + } + } + } + } + } + + #endregion + + #region Saving and Loading Maps + + private void ConfigureMappingUI () + { + var showMappingState = this.sessionState != SessionState.GameInProgress && + this.sessionState != SessionState.Setup && + this.sessionState != SessionState.LocalizingToBoard && + UserDefaults.ShowARDebug; + //TODO: + this.mappingStateLabel.Hidden = !showMappingState; + //this.saveButton.Hidden = this.sessionState == SessionState.setup; + //this.loadButton.Hidden = this.sessionState == SessionState.setup; + } + + private void UpdateMappingStatus (ARWorldMappingStatus mappingStatus) + { + // Check the mapping status of the worldmap to be able to save the worldmap when in a good state + switch (mappingStatus) { + case ARWorldMappingStatus.NotAvailable: + this.mappingStateLabel.Text = "Mapping state: Not Available"; + this.mappingStateLabel.TextColor = UIColor.Red; + this.saveAsKeyPositionButton.Enabled = false; + //this.saveButton.Enabled = false; + break; + + case ARWorldMappingStatus.Limited: + this.mappingStateLabel.Text = "Mapping state: Limited"; + this.mappingStateLabel.TextColor = UIColor.Red; + this.saveAsKeyPositionButton.Enabled = false; + //this.saveButton.Enabled = false; + break; + + case ARWorldMappingStatus.Extending: + this.mappingStateLabel.Text = "Mapping state: Extending"; + this.mappingStateLabel.TextColor = UIColor.Red; + this.saveAsKeyPositionButton.Enabled = false; + //this.saveButton.Enabled = false; + break; + + case ARWorldMappingStatus.Mapped: + this.mappingStateLabel.Text = "Mapping state: Mapped"; + this.mappingStateLabel.TextColor = UIColor.Green; + this.saveAsKeyPositionButton.Enabled = true; + //this.saveButton.Enabled = true; + break; + } + } + + private void GetCurrentWorldMapData (Action<NSData, NSError> closure) + { + //os_log(.info, "in getCurrentWordMapData") + // When loading a map, send the loaded map and not the current extended map + if (this.targetWorldMap != null) { + //os_log(.info, "using existing worldmap, not asking session for a new one.") + this.CompressMap (this.targetWorldMap, closure); + } else { + //os_log(.info, "asking ARSession for the world map") + this.sceneView.Session.GetCurrentWorldMap ((map, error) => { + //os_log(.info, "ARSession getCurrentWorldMap returned") + if (error != null) { + //os_log(.error, "didn't work! %s", "\(error)") + closure (null, error); + } + + if (map != null) { + //os_log(.info, "got a worldmap, compressing it") + this.CompressMap (map, closure); + } + }); + } + } + + [Action ("savePressed:")] + private void SavePressed (UIButton sender) + { + this.activityIndicator.StartAnimating (); + this.GetCurrentWorldMapData ((data, error) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.activityIndicator.StopAnimating (); + if (error != null) { + var title = error.LocalizedDescription; + var message = error.LocalizedFailureReason; + this.ShowAlert (title, message); + return; + } + + if (data != null) { + this.ShowSaveDialog (data); + } + }); + }); + } + + [Action ("loadPressed:")] + private void LoadPressed (UIButton sender) + { + var picker = new UIDocumentPickerViewController (new string [] { "com.apple.xamarin-shot.worldmap" }, UIDocumentPickerMode.Open) { + AllowsMultipleSelection = false, + Delegate = this, + }; + this.PresentViewController (picker, true, null); + } + + private void ShowSaveDialog (NSData data) + { + var dialog = UIAlertController.Create ("Save World Map", null, UIAlertControllerStyle.Alert); + dialog.AddTextField (null); + var saveAction = UIAlertAction.Create ("Save", UIAlertActionStyle.Default, (action) => { + var fileName = dialog.TextFields?.FirstOrDefault ()?.Text; + if (!string.IsNullOrEmpty (fileName)) { + DispatchQueue.GetGlobalQueue (DispatchQueuePriority.Background).DispatchAsync (() => { + var docs = NSFileManager.DefaultManager.GetUrl (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out NSError error); + if (error == null) { + var maps = docs.Append ("maps", true); + NSFileManager.DefaultManager.CreateDirectory (maps, true, null, out NSError creationError); + var targetURL = maps.Append (fileName, false).AppendPathExtension ("xamarinshotmap"); + data.Save (targetURL, NSDataWritingOptions.Atomic, out NSError saveingError); + DispatchQueue.MainQueue.DispatchAsync (() => { + this.ShowAlert ("Saved"); + }); + } else { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.ShowAlert (error.LocalizedDescription, null); + }); + } + }); + } + }); + + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null); + + dialog.AddAction (saveAction); + dialog.AddAction (cancelAction); + + this.PresentViewController (dialog, true, null); + } + + /// <summary> + /// Get the archived data from a URL Path + /// </summary> + private void FetchArchivedWorldMap (NSUrl url, Action<NSData, NSError> closure) + { + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + try { + _ = url.StartAccessingSecurityScopedResource (); + var data = NSData.FromUrl (url); + closure (data, null); + } catch { + // TODO: + //DispatchQueue.MainQueue.DispatchAsync(() => + //{ + // this.ShowAlert(error.LocalizedDescription); + //}); + + //closure(null, error); + } finally { + url.StopAccessingSecurityScopedResource (); + } + }); + } + + private void CompressMap (ARWorldMap map, Action<NSData, NSError> closure) + { + DispatchQueue.DefaultGlobalQueue.DispatchAsync (() => { + var data = NSKeyedArchiver.ArchivedDataWithRootObject (map, true, out NSError error); + if (error == null) { + closure (data, null); + } else { + // archiving failed + closure (null, error); + } + }); + } + + #endregion + + #region UIDocumentPickerDelegate + + [Export ("documentPicker:didPickDocumentsAtURLs:")] + public void DidPickDocument (UIDocumentPickerViewController controller, NSUrl [] urls) + { + var selected = urls.FirstOrDefault (); + if (selected != null) { + this.FetchArchivedWorldMap (selected, (data, error) => { + if (error == null && data != null) { + this.LoadWorldMap (data); + } + }); + } + } + + public void DidPickDocument (UIDocumentPickerViewController controller, NSUrl url) + { + this.DidPickDocument (controller, new NSUrl [] { url }); + } + + #endregion + + #region IWorldMapSelectorDelegate + + public void WorldMapSelector (WorldMapSelectorViewController worldMapSelector, Uri selectedMap) + { + this.FetchArchivedWorldMap (selectedMap, (data, error) => { + if (error == null && data != null) { + this.LoadWorldMap (data); + } + }); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController.cs index ec07f7133..5ca971ddb 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/GameViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/GameViewController.cs @@ -1,1070 +1,922 @@ - -namespace XamarinShot -{ - using ARKit; - using CoreFoundation; - using CoreGraphics; - using Foundation; - using SceneKit; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - /// <summary> - /// Main view controller for the AR game. - /// </summary> - public partial class GameViewController : UIViewController, - ISCNSceneRendererDelegate, - IARSessionDelegate, - IGameManagerDelegate, - IGameStartViewControllerDelegate - { - private readonly SCNNode audioListenerNode = new SCNNode(); - - private GameManager gameManager; - - private SessionState sessionState = SessionState.Setup; - - private bool isSessionInterrupted; - - // used when state is localizingToWorldMap or localizingToSavedMap - private ARWorldMap targetWorldMap; - - private GameBoard gameBoard = new GameBoard(); - - // Root node of the level - private SCNNode renderRoot = new SCNNode(); - - private SCNVector3 panOffset = SCNVector3.Zero; - - private ButtonBeep buttonBeep; - private ButtonBeep backButtonBeep; - - // Music player - private readonly MusicCoordinator musicCoordinator = new MusicCoordinator(); - - private GameLevel selectedLevel; - - // Proximity manager for beacons - private readonly ProximityManager proximityManager = ProximityManager.Shared; - - protected GameViewController(IntPtr handle) : base(handle) { } - - public bool CanAdjustBoard => this.sessionState == SessionState.PlacingBoard || this.sessionState == SessionState.AdjustingBoard; - - public bool AttemptingBoardPlacement => this.sessionState == SessionState.LookingForSurface || this.sessionState == SessionState.PlacingBoard; - - private int teamACatapultCount = 0; - public int TeamACatapultCount - { - get => this.teamACatapultCount; - set - { - if (this.teamACatapultCount != value) - { - this.teamACatapultCount = value; - - // The "highlighted" state actually means that the catapult has been disabled. - for (var index = 0; index < this.teamACatapultImages.Length; index++) - { - var shouldAppear = index < this.teamACatapultCount; - this.teamACatapultImages[index].Highlighted = !shouldAppear; - } - } - } - } - - private int teamBCatapultCount = 0; - public int TeamBCatapultCount - { - get => this.teamBCatapultCount; - set - { - if (this.teamBCatapultCount != value) - { - this.teamBCatapultCount = value; - - // The "highlighted" state actually means that the catapult has been disabled. - for (var index = 0; index < this.teamBCatapultImages.Length; index++) - { - var shouldAppear = index < this.teamBCatapultCount; - this.teamBCatapultImages[index].Highlighted = !shouldAppear; - } - } - } - } - - public GameManager GameManager - { - get - { - return this.gameManager; - } - - set - { - this.gameManager = value; - if (this.gameManager != null) - { - if (this.gameManager.IsNetworked && !this.gameManager.IsServer) - { - this.SessionState = SessionState.WaitingForBoard; - } - else - { - this.SessionState = SessionState.LookingForSurface; - } - - this.gameManager.Delegate = this; - this.gameManager.MainScreenBounds = UIScreen.MainScreen.Bounds; - } - else - { - this.SessionState = SessionState.Setup; - } - } - } - - public SessionState SessionState - { - get - { - return this.sessionState; - } - - set - { - if (this.sessionState != value) - { - this.sessionState = value; - this.ConfigureView(); - this.ConfigureARSession(); - } - } - } - - public bool IsSessionInterrupted - { - get - { - return this.isSessionInterrupted; - } - - set - { - this.isSessionInterrupted = value; - if (this.isSessionInterrupted && !UserDefaults.DisableInGameUI) - { - this.instructionLabel.Hidden = false; - this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString("Point the camera towards the table."); - } - else - { - var localizedInstruction = sessionState.LocalizedInstruction(); - if (!string.IsNullOrEmpty(localizedInstruction)) - { - this.instructionLabel.Hidden = false; - this.instructionLabel.Text = localizedInstruction; - } - else - { - this.instructionLabel.Hidden = true; - } - } - } - } - - public GameLevel SelectedLevel - { - get - { - return this.selectedLevel; - } - - set - { - this.selectedLevel = value; - if (this.selectedLevel != null) - { - this.gameBoard.PreferredSize = this.selectedLevel.TargetSize; - } - } - } - - public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation) - { - base.DidRotate(fromInterfaceOrientation); - this.gameManager.MainScreenBounds = UIScreen.MainScreen.Bounds; - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Set the view's delegate - this.sceneView.Delegate = this; - - // Explicitly set the listener position to be in an SCNNode that we control - // because the scaling of the scaling difference between the render coordinate - // space and the simulation coordinate space. This node isn't added to the node - // hierarchy of the scene, so it isn't affected by changes to the scene scale. - // On each frame update, however, its position is explicitly set to a transformed - // value that is consistent with the game objects in the scene. - this.sceneView.AudioListener = this.audioListenerNode; - - this.sceneView.Scene.RootNode.AddChildNode(this.gameBoard); - - this.SessionState = SessionState.Setup; - this.sceneView.Session.Delegate = this; - - this.instructionLabel.ClipsToBounds = true; - this.instructionLabel.Layer.CornerRadius = 8f; - - if (UserDefaults.AllowGameBoardAutoSize) - { - this.sceneView.AddGestureRecognizer(new UILongPressGestureRecognizer(this.HandleLongPress)); - } - - this.notificationLabel.ClipsToBounds = true; - this.notificationLabel.Layer.CornerRadius = 8f; - - this.buttonBeep = ButtonBeep.Create("button_forward.wav", 0.5f); - this.backButtonBeep = ButtonBeep.Create("button_backward.wav", 0.5f); - - this.renderRoot.Name = "_renderRoot"; - this.sceneView.Scene.RootNode.AddChildNode(this.renderRoot); - - NSNotificationCenter.DefaultCenter.AddObserver(NSProcessInfo.ThermalStateDidChangeNotification, (obj) => this.UpdateThermalStateIndicator()); - - // this preloads the assets used by the level - materials and texture and compiles shaders - this.PreloadLevel(); - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - this.ConfigureARSession(); - this.ConfigureView(); - } - - private void UpdateThermalStateIndicator() - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - // Show thermal state label if default enabled and state is critical - this.thermalStateLabel.Hidden = !(UserDefaults.ShowThermalState && NSProcessInfo.ProcessInfo.ThermalState == NSProcessInfoThermalState.Critical); - }); - } - - #region Configuration - - private void ConfigureView() - { - var debugOptions = SCNDebugOptions.None; - - // fix the scaling of the physics debug view to match the world - if (UserDefaults.ShowPhysicsDebug) - { - debugOptions |= SCNDebugOptions.ShowPhysicsShapes; - } - - // show where ARKit is detecting feature points - if (UserDefaults.ShowARDebug) - { - debugOptions |= ARSCNDebugOptions.ShowFeaturePoints; - } - - // see high poly-count and LOD transitions - wireframe overlay - if (UserDefaults.ShowWireframe) - { - debugOptions |= SCNDebugOptions.ShowWireframe; - } - - this.sceneView.DebugOptions = debugOptions; - - // perf stats - this.sceneView.ShowsStatistics = UserDefaults.ShowSceneViewStats; - - this.trackingStateLabel.Hidden = !UserDefaults.ShowTrackingState; - - // smooth the edges by rendering at higher resolution - // defaults to none on iOS, use on faster GPUs - // 0, 2, 4 on iOS, 8, 16x on macOS - this.sceneView.AntialiasingMode = UserDefaults.AntialiasingMode ? SCNAntialiasingMode.Multisampling4X : SCNAntialiasingMode.None; - - var localizedInstruction = this.sessionState.LocalizedInstruction(); - if(!string.IsNullOrEmpty(localizedInstruction)) - { - this.instructionLabel.Hidden = false; - this.instructionLabel.Text = localizedInstruction; - } - else - { - this.instructionLabel.Hidden = true; - } - - if (this.sessionState == SessionState.WaitingForBoard) - { - this.activityIndicator.StartAnimating(); - } - else - { - this.activityIndicator.StopAnimating(); - } - - if (!UserDefaults.ShowSettingsInGame) - { - this.settingsButton.Hidden = true; - } - - if (UserDefaults.DisableInGameUI) - { - this.exitGameButton.SetImage(null, UIControlState.Normal); - } - else - { - this.exitGameButton.SetImage(UIImage.FromBundle("close"), UIControlState.Normal); - } - - this.exitGameButton.Hidden = this.sessionState == SessionState.Setup; - - this.ConfigureMappingUI(); - this.ConfigureRelocalizationHelp(); - this.UpdateThermalStateIndicator(); - } - - private void ConfigureARSession() - { - var configuration = new ARWorldTrackingConfiguration { AutoFocusEnabled = UserDefaults.AutoFocus }; - var options = ARSessionRunOptions.None; - - switch (this.sessionState) - { - case SessionState.Setup: - // in setup - // AR session paused - this.sceneView.Session.Pause(); - return; - - case SessionState.LookingForSurface: - case SessionState.WaitingForBoard: - // both server and client, go ahead and start tracking the world - configuration.PlaneDetection = ARPlaneDetection.Horizontal; - options = ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors; - - // Only reset session if not already running - if (this.sceneView.Playing) - { - return; - } - break; - - case SessionState.PlacingBoard: - case SessionState.AdjustingBoard: - // we've found at least one surface, but should keep looking. - // so no change to the running session - return; - - case SessionState.LocalizingToBoard: - if (this.targetWorldMap != null) // should have had a world map - { - configuration.InitialWorldMap = this.targetWorldMap; - configuration.PlaneDetection = ARPlaneDetection.Horizontal; - options = ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors; - this.gameBoard.Anchor = this.targetWorldMap.BoardAnchor(); - if (this.gameBoard.Anchor != null) - { - this.gameBoard.Transform = this.gameBoard.Anchor.Transform.ToSCNMatrix4(); - var width = (float)this.gameBoard.Anchor.Size.Width; - this.gameBoard.Scale = new SCNVector3(width, width, width); - } - - this.gameBoard.HideBorder(0); - } - break; - - case SessionState.SetupLevel: - // more init - return; - case SessionState.GameInProgress: - // The game is in progress, no change to the running session - return; - } - - // Turning light estimation off to test PBR on SceneKit file - configuration.LightEstimationEnabled = false; - - // configured AR session - this.sceneView.Session.Run(configuration, options); - } - - #endregion - - #region UI Buttons - - partial void exitGamePressed(UIButton sender) - { - var stayAction = UIAlertAction.Create(NSBundle.MainBundle.GetLocalizedString("Stay"), UIAlertActionStyle.Default, null); - var leaveAction = UIAlertAction.Create(NSBundle.MainBundle.GetLocalizedString("Leave"), UIAlertActionStyle.Cancel, (action) => - { - this.ExitGame(); - // start looking for beacons again - this.proximityManager.Start(); - }); - - var actions = new UIAlertAction[] { stayAction, leaveAction }; - var localizedTitle = NSBundle.MainBundle.GetLocalizedString("Are you sure you want to leave the game?"); - - string localizedMessage = null; - if (this.gameManager != null && this.gameManager.IsServer) - { - localizedMessage = NSBundle.MainBundle.GetLocalizedString("You’re the host, so if you leave now the other players will have to leave too."); - } - - this.ShowAlert(localizedTitle, localizedMessage, actions); - } - - private void ExitGame() - { - this.backButtonBeep.Play(); - if (this.gameManager != null) - { - this.gameManager.Delegate = null; - this.gameManager.ReleaseLevel(); - this.gameManager.Dispose(); - this.GameManager = null; - } - - this.ShowOverlay(); - - // Cleanup the current loaded map - if (this.targetWorldMap != null) - { - this.targetWorldMap.Dispose(); - this.targetWorldMap = null; - } - - foreach (var item in this.teamACatapultImages) - { - item.Hidden = true; - item.Highlighted = false; - } - - foreach (var item in this.teamBCatapultImages) - { - item.Hidden = true; - item.Highlighted = false; - } - - this.notificationLabel.Hidden = true; - UserDefaults.HasOnboarded = false; - - // Reset game board - this.gameBoard.Reset(); - if(this.gameBoard.Anchor != null) - { - this.sceneView.Session.RemoveAnchor(this.gameBoard.Anchor); - this.gameBoard.Anchor = null; - } - } - - private void ShowAlert(string title, string message = null, IList<UIAlertAction> actions = null) - { - var alertController = UIAlertController.Create(title, message, UIAlertControllerStyle.Alert); - if (actions != null) - { - foreach (var action in actions) - { - alertController.AddAction(action); - } - } - else - { - alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); - } - - this.PresentViewController(alertController, true, null); - } - - #endregion - - #region Board management - - protected CGPoint ScreenCenter - { - get - { - var bounds = this.sceneView.Bounds; - return new CGPoint(bounds.GetMidX(), bounds.GetMidY()); - } - } - - private void UpdateGameBoard(ARFrame frame) - { - if (this.sessionState == SessionState.SetupLevel) - { - // this will advance the session state - this.SetupLevel(); - } - // Only automatically update board when looking for surface or placing board - else if (this.AttemptingBoardPlacement) - { - // Make sure this is only run on the render thread - if (this.gameBoard.ParentNode == null) - { - this.sceneView.Scene.RootNode.AddChildNode(this.gameBoard); - } - - // Perform hit testing only when ARKit tracking is in a good state. - if (frame.Camera.TrackingState == ARTrackingState.Normal) - { - var result = this.sceneView.HitTest(this.ScreenCenter, ARHitTestResultType.EstimatedHorizontalPlane | ARHitTestResultType.ExistingPlaneUsingExtent).FirstOrDefault(); - if (result != null) - { - using (result) - { - // Ignore results that are too close to the camera when initially placing - if (result.Distance > 0.5f || this.sessionState == SessionState.PlacingBoard) - { - this.SessionState = SessionState.PlacingBoard; - this.gameBoard.Update(result, frame.Camera); - } - } - } - else - { - this.SessionState = SessionState.LookingForSurface; - if (!this.gameBoard.IsBorderHidden) - { - this.gameBoard.HideBorder(); - } - } - } - } - } - - private void Process(BoardSetupAction boardAction, Player peer) - { - switch (boardAction.Type) - { - case BoardSetupAction.BoardSetupActionType.BoardLocation: - switch (boardAction.BoardLocation.Type) - { - case GameBoardLocation.GameBoardLocationType.WorldMapData: - // Received WorldMap data - this.LoadWorldMap(boardAction.BoardLocation.WorldMapData); - break; - case GameBoardLocation.GameBoardLocationType.Manual: - // Received a manual board placement - this.SessionState = SessionState.LookingForSurface; - break; - } - break; - - case BoardSetupAction.BoardSetupActionType.RequestBoardLocation: - this.SendWorldTo(peer); - break; - } - } - - /// <summary> - /// Load the World Map from archived data - /// </summary> - private void LoadWorldMap(NSData archivedData) - { - if (NSKeyedUnarchiver.GetUnarchivedObject(typeof(ARWorldMap), archivedData, out NSError error) is ARWorldMap worldMap) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.targetWorldMap = worldMap; - this.SessionState = SessionState.LocalizingToBoard; - }); - } - else if (error != null) - { - // The WorldMap received couldn't be decompressed - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.ShowAlert("An error occured while loading the WorldMap (Failed to decompress)"); - this.SessionState = SessionState.Setup; - }); - } - else - { - // The WorldMap received couldn't be read - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.ShowAlert("An error occured while loading the WorldMap (Failed to read)"); - this.SessionState = SessionState.Setup; - }); - } - } - - private void PreloadLevel() - { - // Preloading assets started - - var main = DispatchQueue.MainQueue; - var background = DispatchQueue.DefaultGlobalQueue; - background.DispatchAsync(() => - { - foreach (var level in GameLevel.AllLevels) - { - // this is just a dummy scene to preload data - // this is not added to the sceneView - var scene = new SCNScene(); - // this may result in two callers loading the scene - level.Load(); - if (level.ActiveLevel != null) - { - this.SetLevelLighting(level.ActiveLevel); - scene.RootNode.AddChildNode(level.ActiveLevel); - scene.Paused = true; - - // This doesn't actually add the scene to the ARSCNView, it just sets up a background task - // the preloading is done on a background thread, and the completion handler called - - // prepare must be called from main thread - main.DispatchSync(() => - { - // preparing a scene compiles shaders - this.sceneView.Prepare(new NSObject[] { scene }, (success) => - { - Console.WriteLine(success ? "Preloading assets succeeded" : "Preloading assets failed"); - }); - }); - } - } - }); - } - - private void SetLevelLighting(SCNNode node) - { - var light = node.FindChildNode("LightNode", true)?.Light; - if (light != null) - { - light.ShadowRadius = 3; - light.ShadowSampleCount = 8; - } - } - - private void SetupLevel() - { - if(this.gameManager == null) - { - throw new Exception("gameManager not initialized"); - } - - if (this.gameBoard.Anchor == null) - { - var boardTransform = this.gameBoard.Transform.Normalize(); - boardTransform.Transpose(); - - var boardSize = new CGSize((float)this.gameBoard.Scale.X, (float)(this.gameBoard.Scale.X * this.gameBoard.AspectRatio)); - this.gameBoard.Anchor = new BoardAnchor(boardTransform, boardSize); - this.sceneView.Session.AddAnchor(this.gameBoard.Anchor); - } - - this.gameBoard.HideBorder(); - this.SessionState = SessionState.GameInProgress; - - GameTime.SetLevelStartTime(); - this.gameManager.Start(); - this.gameManager.AddLevel(this.renderRoot, this.gameBoard); - this.gameManager.RestWorld(); - - if (!UserDefaults.DisableInGameUI) - { - this.teamACatapultImages.ForEach((item) => item.Hidden = false); - this.teamBCatapultImages.ForEach((item) => item.Hidden = false); - } - - // stop ranging for beacons after placing board - if (UserDefaults.GameRoomMode) - { - this.proximityManager.Stop(); - if (this.proximityManager.ClosestLocation != null) - { - this.gameManager.UpdateSessionLocation(this.proximityManager.ClosestLocation); - } - } - } - - private void SendWorldTo(Player peer) - { - if (this.gameManager != null && this.gameManager.IsServer) - { - switch (UserDefaults.BoardLocatingMode) - { - case BoardLocatingMode.WorldMap: - // generating worldmap - this.GetCurrentWorldMapData((data, error) => - { - if (error == null && data != null) - { - // got a compressed map - var location = new GameBoardLocation { WorldMapData = data, Type = GameBoardLocation.GameBoardLocationType.WorldMapData }; - DispatchQueue.MainQueue.DispatchAsync(() => - { - // sending worldmap - this.gameManager.Send(new BoardSetupAction { BoardLocation = location, Type = BoardSetupAction.BoardSetupActionType.BoardLocation }, peer); - }); - } - else if (error != null) - { - Console.WriteLine($"Didn't work! {error?.LocalizedDescription ?? string.Empty}"); - } - }); - break; - - case BoardLocatingMode.Manual: - this.gameManager.Send(new BoardSetupAction { BoardLocation = new GameBoardLocation { Type = GameBoardLocation.GameBoardLocationType.Manual } }, peer); - break; - } - } - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (!string.IsNullOrEmpty(segue.Identifier) && - Enum.TryParse<GameSegue>(segue.Identifier, true, out GameSegue segueType)) - { - switch (segueType) - { - case GameSegue.EmbeddedOverlay: - if (segue.DestinationViewController is GameStartViewController gameStartViewController) - { - gameStartViewController.Delegate = this; - this.musicCoordinator.PlayMusic("music_menu", 0f); - } - break; - - case GameSegue.WorldMapSelector: - if (segue.DestinationViewController is WorldMapSelectorViewController worldMapSelectorViewController) - { - worldMapSelectorViewController.Delegate = this; - } - break; - } - } - } - - private void ShowOverlay() - { - UIView.Transition(this.View, 1d, UIViewAnimationOptions.TransitionCrossDissolve, () => - { - this.overlayView.Hidden = false; - this.inSceneButtons.ForEach((button) => button.Hidden = true); - - this.settingsButton.Hidden = true; - this.instructionLabel.Hidden = true; - }, () => - { - this.overlayView.UserInteractionEnabled = true; - UIApplication.SharedApplication.IdleTimerDisabled = false; - }); - - this.musicCoordinator.PlayMusic("music_menu", 0.5f); - } - - private void HideOverlay() - { - UIView.Transition(this.View, 1d, UIViewAnimationOptions.TransitionCrossDissolve, () => - { - this.overlayView.Hidden = true; - this.inSceneButtons.ForEach((button) => button.Hidden = false); - - this.instructionLabel.Hidden = false; - this.settingsButton.Hidden = !UserDefaults.ShowSettingsInGame; - }, () => - { - this.overlayView.UserInteractionEnabled = false; - UIApplication.SharedApplication.IdleTimerDisabled = true; - }); - - this.musicCoordinator.StopMusic("music_menu", 3f); - } - - #endregion - - #region ISCNSceneRendererDelegate - - // This is the ordering of delegate calls - // https://developer.apple.com/documentation/scenekit/scnscenerendererdelegate - - [Export("renderer:updateAtTime:")] - public void Update(ISCNSceneRenderer renderer, double timeInSeconds) - { - if (this.gameManager != null && this.gameManager.IsInitialized) - { - GameTime.UpdateAtTime(timeInSeconds); - - if (this.sceneView.PointOfView != null && this.selectedLevel != null && this.selectedLevel.Placed) - { - // make a copy of the camera data that other threads can access - // ARKit has updated the transform right before this - this.gameManager.CopySimulationCamera(); - - // these can use the pointOfView since the render thread scales/unscales the camera around rendering - var pointOfViewTransform = this.sceneView.PointOfView.Transform; - pointOfViewTransform.Transpose(); - var cameraTransform = this.gameManager.RenderSpaceTransformToSimulationSpace(pointOfViewTransform); - var cameraInfo = new CameraInfo(cameraTransform); - - this.gameManager.UpdateCamera(cameraInfo); - - var canGrabCatapult = this.gameManager.CanGrabACatapult(cameraInfo.Ray); - var isGrabbingCatapult = this.gameManager.IsCurrentPlayerGrabbingACatapult(); - - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (this.sessionState == SessionState.GameInProgress) - { - if (!UserDefaults.HasOnboarded && !UserDefaults.DisableInGameUI) - { - if (isGrabbingCatapult) - { - this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString("Release to shoot."); - } - else if (canGrabCatapult) - { - this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString("Tap anywhere and hold to pull back."); - } - else - { - this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString("Move closer to a slingshot."); - } - } - else - { - if (!this.instructionLabel.Hidden && !this.isSessionInterrupted) - { - this.instructionLabel.Hidden = true; - } - } - } - }); - } - - this.gameManager.Update(GameTime.DeltaTime); - } - } - - [Export("renderer:didApplyConstraintsAtTime:")] - public void DidApplyConstraints(ISCNSceneRenderer renderer, double atTime) - { - if (this.gameManager != null && this.gameManager.IsInitialized) - { - // scale up/down the camera to render space - this.gameManager.ScaleCameraToRender(); - - // render space from here until scaleCameraToSimulation() is called - if (this.sceneView.PointOfView != null) - { - this.audioListenerNode.WorldTransform = this.sceneView.PointOfView.WorldTransform; - } - - // The only functionality currently controlled here is the trail on the projectile. - // Therefore this part is used to turn on/off show projectile trail - if (UserDefaults.ShowProjectileTrail) - { - this.gameManager?.OnDidApplyConstraints(renderer); - } - } - } - - [Export("renderer:didRenderScene:atTime:")] - public void DidRenderScene(ISCNSceneRenderer renderer, SCNScene scene, double timeInSeconds) - { - // update visibility properties in renderloop because we have to scale the physics world down to render properly - if (this.gameManager != null && this.gameManager.IsInitialized) - { - // this visibility test is in scaled space, using renderer frustum culling - if (this.sceneView.PointOfView != null) - { - this.gameManager?.UpdateCatapultVisibility(renderer, this.sceneView.PointOfView); - } - - // return the pointOfView back from scaled space - this.gameManager?.ScaleCameraToSimulation(); - } - } - - #endregion - - #region ARSessionDelegate - - [Export("session:didUpdateFrame:")] - public void DidUpdateFrame(ARSession session, ARFrame frame) - { - // Update game board placement in physical world - if (this.gameManager != null) - { - // this is main thread calling into init code - this.UpdateGameBoard(frame); - } - - // Update mapping status for saving maps - this.UpdateMappingStatus(frame.WorldMappingStatus); - - // dispose after updating - frame.Dispose(); - } - - #endregion - - #region IGameManagerDelegate - - public void OnReceived(GameManager manager, BoardSetupAction boardAction, Player player) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.Process(boardAction, player); - }); - } - - public void OnJoiningHost(GameManager manager, Player host) - { - // host joined the game - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (this.sessionState == SessionState.WaitingForBoard) - { - manager.Send(new BoardSetupAction { Type = BoardSetupAction.BoardSetupActionType.RequestBoardLocation }); - } - - if (!UserDefaults.DisableInGameUI) - { - this.notificationLabel.Text = "You joined the game!"; - this.notificationLabel.FadeInFadeOut(1d); - } - }); - } - - public void OnJoiningPlayer(GameManager manager, Player player) - { - // non-host player joined the game - if (!UserDefaults.DisableInGameUI) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.notificationLabel.Text = $"{player.Username} joined the game."; - this.notificationLabel.FadeInFadeOut(1d); - }); - - // If the gameplay music is already running, start it on the newly - // connected client. - if (this.musicCoordinator.CurrentMusicPlayer?.Name == "music_gameplay") - { - var musicTime = this.musicCoordinator.CurrentMusicTime(); - //os_log(.debug, "music play position = %f", musicTime) - if (musicTime >= 0) - { - manager.StartGameMusic(player); - } - } - } - } - - public void OnLeavingHost(GameManager manager, Player host) - { - // host left the game - if (!UserDefaults.DisableInGameUI) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - // the game can no longer continue - this.notificationLabel.Text = "The host left the game. Please join another game or start your own!"; - this.notificationLabel.Hidden = false; - }); - } - } - - public void OnLeavingPlayer(GameManager manager, Player player) - { - // non-host player left the game - if (!UserDefaults.DisableInGameUI) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.notificationLabel.Text = $"{player.Username} left the game."; - this.notificationLabel.FadeInFadeOut(1d); - }); - } - } - - public void OnDidStartGame(GameManager manager) { } - - public void OnManagerDidWinGame(GameManager manager) - { - this.musicCoordinator.PlayMusic("music_win"); - } - - public void OnHasNetworkDelay(GameManager manager, bool hasNetworkDelay) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (UserDefaults.ShowNetworkDebug) - { - this.networkDelayText.Hidden = !hasNetworkDelay; - } - }); - } - - public void OnGameStateUpdated(GameManager manager, GameState gameState) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (this.SessionState == SessionState.GameInProgress) - { - this.TeamACatapultCount = gameState.TeamACatapults; - this.TeamBCatapultCount = gameState.TeamBCatapults; - } - }); - } - - #endregion - - #region IGameStartViewControllerDelegate - - private void CreateGameManager(NetworkSession session) - { - var level = UserDefaults.SelectedLevel; - this.SelectedLevel = level; - this.GameManager = new GameManager(this.sceneView, - level, - session, - this.sceneView.AudioEnvironmentNode, - this.musicCoordinator); - } - - public void OnSoloGamePressed(UIViewController viewController, UIButton button) - { - this.HideOverlay(); - this.CreateGameManager(null); - } - - public void OnGameSelected(UIViewController viewController, NetworkSession game) - { - this.HideOverlay(); - this.CreateGameManager(game); - } - - public void OnGameStarted(UIViewController viewController, NetworkSession game) - { - this.HideOverlay(); - this.CreateGameManager(game); - } - - public void OnSettingsSelected(UIViewController viewController) - { - this.PerformSegue(GameSegue.ShowSettings.ToString(), this); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot { + using ARKit; + using CoreFoundation; + using CoreGraphics; + using Foundation; + using SceneKit; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + /// <summary> + /// Main view controller for the AR game. + /// </summary> + public partial class GameViewController : UIViewController, + ISCNSceneRendererDelegate, + IARSessionDelegate, + IGameManagerDelegate, + IGameStartViewControllerDelegate { + private readonly SCNNode audioListenerNode = new SCNNode (); + + private GameManager gameManager; + + private SessionState sessionState = SessionState.Setup; + + private bool isSessionInterrupted; + + // used when state is localizingToWorldMap or localizingToSavedMap + private ARWorldMap targetWorldMap; + + private GameBoard gameBoard = new GameBoard (); + + // Root node of the level + private SCNNode renderRoot = new SCNNode (); + + private SCNVector3 panOffset = SCNVector3.Zero; + + private ButtonBeep buttonBeep; + private ButtonBeep backButtonBeep; + + // Music player + private readonly MusicCoordinator musicCoordinator = new MusicCoordinator (); + + private GameLevel selectedLevel; + + // Proximity manager for beacons + private readonly ProximityManager proximityManager = ProximityManager.Shared; + + protected GameViewController (IntPtr handle) : base (handle) { } + + public bool CanAdjustBoard => this.sessionState == SessionState.PlacingBoard || this.sessionState == SessionState.AdjustingBoard; + + public bool AttemptingBoardPlacement => this.sessionState == SessionState.LookingForSurface || this.sessionState == SessionState.PlacingBoard; + + private int teamACatapultCount = 0; + public int TeamACatapultCount { + get => this.teamACatapultCount; + set { + if (this.teamACatapultCount != value) { + this.teamACatapultCount = value; + + // The "highlighted" state actually means that the catapult has been disabled. + for (var index = 0; index < this.teamACatapultImages.Length; index++) { + var shouldAppear = index < this.teamACatapultCount; + this.teamACatapultImages [index].Highlighted = !shouldAppear; + } + } + } + } + + private int teamBCatapultCount = 0; + public int TeamBCatapultCount { + get => this.teamBCatapultCount; + set { + if (this.teamBCatapultCount != value) { + this.teamBCatapultCount = value; + + // The "highlighted" state actually means that the catapult has been disabled. + for (var index = 0; index < this.teamBCatapultImages.Length; index++) { + var shouldAppear = index < this.teamBCatapultCount; + this.teamBCatapultImages [index].Highlighted = !shouldAppear; + } + } + } + } + + public GameManager GameManager { + get { + return this.gameManager; + } + + set { + this.gameManager = value; + if (this.gameManager != null) { + if (this.gameManager.IsNetworked && !this.gameManager.IsServer) { + this.SessionState = SessionState.WaitingForBoard; + } else { + this.SessionState = SessionState.LookingForSurface; + } + + this.gameManager.Delegate = this; + this.gameManager.MainScreenBounds = UIScreen.MainScreen.Bounds; + } else { + this.SessionState = SessionState.Setup; + } + } + } + + public SessionState SessionState { + get { + return this.sessionState; + } + + set { + if (this.sessionState != value) { + this.sessionState = value; + this.ConfigureView (); + this.ConfigureARSession (); + } + } + } + + public bool IsSessionInterrupted { + get { + return this.isSessionInterrupted; + } + + set { + this.isSessionInterrupted = value; + if (this.isSessionInterrupted && !UserDefaults.DisableInGameUI) { + this.instructionLabel.Hidden = false; + this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString ("Point the camera towards the table."); + } else { + var localizedInstruction = sessionState.LocalizedInstruction (); + if (!string.IsNullOrEmpty (localizedInstruction)) { + this.instructionLabel.Hidden = false; + this.instructionLabel.Text = localizedInstruction; + } else { + this.instructionLabel.Hidden = true; + } + } + } + } + + public GameLevel SelectedLevel { + get { + return this.selectedLevel; + } + + set { + this.selectedLevel = value; + if (this.selectedLevel != null) { + this.gameBoard.PreferredSize = this.selectedLevel.TargetSize; + } + } + } + + public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) + { + base.DidRotate (fromInterfaceOrientation); + this.gameManager.MainScreenBounds = UIScreen.MainScreen.Bounds; + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Set the view's delegate + this.sceneView.Delegate = this; + + // Explicitly set the listener position to be in an SCNNode that we control + // because the scaling of the scaling difference between the render coordinate + // space and the simulation coordinate space. This node isn't added to the node + // hierarchy of the scene, so it isn't affected by changes to the scene scale. + // On each frame update, however, its position is explicitly set to a transformed + // value that is consistent with the game objects in the scene. + this.sceneView.AudioListener = this.audioListenerNode; + + this.sceneView.Scene.RootNode.AddChildNode (this.gameBoard); + + this.SessionState = SessionState.Setup; + this.sceneView.Session.Delegate = this; + + this.instructionLabel.ClipsToBounds = true; + this.instructionLabel.Layer.CornerRadius = 8f; + + if (UserDefaults.AllowGameBoardAutoSize) { + this.sceneView.AddGestureRecognizer (new UILongPressGestureRecognizer (this.HandleLongPress)); + } + + this.notificationLabel.ClipsToBounds = true; + this.notificationLabel.Layer.CornerRadius = 8f; + + this.buttonBeep = ButtonBeep.Create ("button_forward.wav", 0.5f); + this.backButtonBeep = ButtonBeep.Create ("button_backward.wav", 0.5f); + + this.renderRoot.Name = "_renderRoot"; + this.sceneView.Scene.RootNode.AddChildNode (this.renderRoot); + + NSNotificationCenter.DefaultCenter.AddObserver (NSProcessInfo.ThermalStateDidChangeNotification, (obj) => this.UpdateThermalStateIndicator ()); + + // this preloads the assets used by the level - materials and texture and compiles shaders + this.PreloadLevel (); + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + this.ConfigureARSession (); + this.ConfigureView (); + } + + private void UpdateThermalStateIndicator () + { + DispatchQueue.MainQueue.DispatchAsync (() => { + // Show thermal state label if default enabled and state is critical + this.thermalStateLabel.Hidden = !(UserDefaults.ShowThermalState && NSProcessInfo.ProcessInfo.ThermalState == NSProcessInfoThermalState.Critical); + }); + } + + #region Configuration + + private void ConfigureView () + { + var debugOptions = SCNDebugOptions.None; + + // fix the scaling of the physics debug view to match the world + if (UserDefaults.ShowPhysicsDebug) { + debugOptions |= SCNDebugOptions.ShowPhysicsShapes; + } + + // show where ARKit is detecting feature points + if (UserDefaults.ShowARDebug) { + debugOptions |= ARSCNDebugOptions.ShowFeaturePoints; + } + + // see high poly-count and LOD transitions - wireframe overlay + if (UserDefaults.ShowWireframe) { + debugOptions |= SCNDebugOptions.ShowWireframe; + } + + this.sceneView.DebugOptions = debugOptions; + + // perf stats + this.sceneView.ShowsStatistics = UserDefaults.ShowSceneViewStats; + + this.trackingStateLabel.Hidden = !UserDefaults.ShowTrackingState; + + // smooth the edges by rendering at higher resolution + // defaults to none on iOS, use on faster GPUs + // 0, 2, 4 on iOS, 8, 16x on macOS + this.sceneView.AntialiasingMode = UserDefaults.AntialiasingMode ? SCNAntialiasingMode.Multisampling4X : SCNAntialiasingMode.None; + + var localizedInstruction = this.sessionState.LocalizedInstruction (); + if (!string.IsNullOrEmpty (localizedInstruction)) { + this.instructionLabel.Hidden = false; + this.instructionLabel.Text = localizedInstruction; + } else { + this.instructionLabel.Hidden = true; + } + + if (this.sessionState == SessionState.WaitingForBoard) { + this.activityIndicator.StartAnimating (); + } else { + this.activityIndicator.StopAnimating (); + } + + if (!UserDefaults.ShowSettingsInGame) { + this.settingsButton.Hidden = true; + } + + if (UserDefaults.DisableInGameUI) { + this.exitGameButton.SetImage (null, UIControlState.Normal); + } else { + this.exitGameButton.SetImage (UIImage.FromBundle ("close"), UIControlState.Normal); + } + + this.exitGameButton.Hidden = this.sessionState == SessionState.Setup; + + this.ConfigureMappingUI (); + this.ConfigureRelocalizationHelp (); + this.UpdateThermalStateIndicator (); + } + + private void ConfigureARSession () + { + var configuration = new ARWorldTrackingConfiguration { AutoFocusEnabled = UserDefaults.AutoFocus }; + var options = ARSessionRunOptions.None; + + switch (this.sessionState) { + case SessionState.Setup: + // in setup + // AR session paused + this.sceneView.Session.Pause (); + return; + + case SessionState.LookingForSurface: + case SessionState.WaitingForBoard: + // both server and client, go ahead and start tracking the world + configuration.PlaneDetection = ARPlaneDetection.Horizontal; + options = ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors; + + // Only reset session if not already running + if (this.sceneView.Playing) { + return; + } + break; + + case SessionState.PlacingBoard: + case SessionState.AdjustingBoard: + // we've found at least one surface, but should keep looking. + // so no change to the running session + return; + + case SessionState.LocalizingToBoard: + if (this.targetWorldMap != null) // should have had a world map + { + configuration.InitialWorldMap = this.targetWorldMap; + configuration.PlaneDetection = ARPlaneDetection.Horizontal; + options = ARSessionRunOptions.ResetTracking | ARSessionRunOptions.RemoveExistingAnchors; + this.gameBoard.Anchor = this.targetWorldMap.BoardAnchor (); + if (this.gameBoard.Anchor != null) { + this.gameBoard.Transform = this.gameBoard.Anchor.Transform.ToSCNMatrix4 (); + var width = (float) this.gameBoard.Anchor.Size.Width; + this.gameBoard.Scale = new SCNVector3 (width, width, width); + } + + this.gameBoard.HideBorder (0); + } + break; + + case SessionState.SetupLevel: + // more init + return; + case SessionState.GameInProgress: + // The game is in progress, no change to the running session + return; + } + + // Turning light estimation off to test PBR on SceneKit file + configuration.LightEstimationEnabled = false; + + // configured AR session + this.sceneView.Session.Run (configuration, options); + } + + #endregion + + #region UI Buttons + + partial void exitGamePressed (UIButton sender) + { + var stayAction = UIAlertAction.Create (NSBundle.MainBundle.GetLocalizedString ("Stay"), UIAlertActionStyle.Default, null); + var leaveAction = UIAlertAction.Create (NSBundle.MainBundle.GetLocalizedString ("Leave"), UIAlertActionStyle.Cancel, (action) => { + this.ExitGame (); + // start looking for beacons again + this.proximityManager.Start (); + }); + + var actions = new UIAlertAction [] { stayAction, leaveAction }; + var localizedTitle = NSBundle.MainBundle.GetLocalizedString ("Are you sure you want to leave the game?"); + + string localizedMessage = null; + if (this.gameManager != null && this.gameManager.IsServer) { + localizedMessage = NSBundle.MainBundle.GetLocalizedString ("You’re the host, so if you leave now the other players will have to leave too."); + } + + this.ShowAlert (localizedTitle, localizedMessage, actions); + } + + private void ExitGame () + { + this.backButtonBeep.Play (); + if (this.gameManager != null) { + this.gameManager.Delegate = null; + this.gameManager.ReleaseLevel (); + this.gameManager.Dispose (); + this.GameManager = null; + } + + this.ShowOverlay (); + + // Cleanup the current loaded map + if (this.targetWorldMap != null) { + this.targetWorldMap.Dispose (); + this.targetWorldMap = null; + } + + foreach (var item in this.teamACatapultImages) { + item.Hidden = true; + item.Highlighted = false; + } + + foreach (var item in this.teamBCatapultImages) { + item.Hidden = true; + item.Highlighted = false; + } + + this.notificationLabel.Hidden = true; + UserDefaults.HasOnboarded = false; + + // Reset game board + this.gameBoard.Reset (); + if (this.gameBoard.Anchor != null) { + this.sceneView.Session.RemoveAnchor (this.gameBoard.Anchor); + this.gameBoard.Anchor = null; + } + } + + private void ShowAlert (string title, string message = null, IList<UIAlertAction> actions = null) + { + var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); + if (actions != null) { + foreach (var action in actions) { + alertController.AddAction (action); + } + } else { + alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, null)); + } + + this.PresentViewController (alertController, true, null); + } + + #endregion + + #region Board management + + protected CGPoint ScreenCenter { + get { + var bounds = this.sceneView.Bounds; + return new CGPoint (bounds.GetMidX (), bounds.GetMidY ()); + } + } + + private void UpdateGameBoard (ARFrame frame) + { + if (this.sessionState == SessionState.SetupLevel) { + // this will advance the session state + this.SetupLevel (); + } + // Only automatically update board when looking for surface or placing board + else if (this.AttemptingBoardPlacement) { + // Make sure this is only run on the render thread + if (this.gameBoard.ParentNode == null) { + this.sceneView.Scene.RootNode.AddChildNode (this.gameBoard); + } + + // Perform hit testing only when ARKit tracking is in a good state. + if (frame.Camera.TrackingState == ARTrackingState.Normal) { + var result = this.sceneView.HitTest (this.ScreenCenter, ARHitTestResultType.EstimatedHorizontalPlane | ARHitTestResultType.ExistingPlaneUsingExtent).FirstOrDefault (); + if (result != null) { + using (result) { + // Ignore results that are too close to the camera when initially placing + if (result.Distance > 0.5f || this.sessionState == SessionState.PlacingBoard) { + this.SessionState = SessionState.PlacingBoard; + this.gameBoard.Update (result, frame.Camera); + } + } + } else { + this.SessionState = SessionState.LookingForSurface; + if (!this.gameBoard.IsBorderHidden) { + this.gameBoard.HideBorder (); + } + } + } + } + } + + private void Process (BoardSetupAction boardAction, Player peer) + { + switch (boardAction.Type) { + case BoardSetupAction.BoardSetupActionType.BoardLocation: + switch (boardAction.BoardLocation.Type) { + case GameBoardLocation.GameBoardLocationType.WorldMapData: + // Received WorldMap data + this.LoadWorldMap (boardAction.BoardLocation.WorldMapData); + break; + case GameBoardLocation.GameBoardLocationType.Manual: + // Received a manual board placement + this.SessionState = SessionState.LookingForSurface; + break; + } + break; + + case BoardSetupAction.BoardSetupActionType.RequestBoardLocation: + this.SendWorldTo (peer); + break; + } + } + + /// <summary> + /// Load the World Map from archived data + /// </summary> + private void LoadWorldMap (NSData archivedData) + { + if (NSKeyedUnarchiver.GetUnarchivedObject (typeof (ARWorldMap), archivedData, out NSError error) is ARWorldMap worldMap) { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.targetWorldMap = worldMap; + this.SessionState = SessionState.LocalizingToBoard; + }); + } else if (error != null) { + // The WorldMap received couldn't be decompressed + DispatchQueue.MainQueue.DispatchAsync (() => { + this.ShowAlert ("An error occured while loading the WorldMap (Failed to decompress)"); + this.SessionState = SessionState.Setup; + }); + } else { + // The WorldMap received couldn't be read + DispatchQueue.MainQueue.DispatchAsync (() => { + this.ShowAlert ("An error occured while loading the WorldMap (Failed to read)"); + this.SessionState = SessionState.Setup; + }); + } + } + + private void PreloadLevel () + { + // Preloading assets started + + var main = DispatchQueue.MainQueue; + var background = DispatchQueue.DefaultGlobalQueue; + background.DispatchAsync (() => { + foreach (var level in GameLevel.AllLevels) { + // this is just a dummy scene to preload data + // this is not added to the sceneView + var scene = new SCNScene (); + // this may result in two callers loading the scene + level.Load (); + if (level.ActiveLevel != null) { + this.SetLevelLighting (level.ActiveLevel); + scene.RootNode.AddChildNode (level.ActiveLevel); + scene.Paused = true; + + // This doesn't actually add the scene to the ARSCNView, it just sets up a background task + // the preloading is done on a background thread, and the completion handler called + + // prepare must be called from main thread + main.DispatchSync (() => { + // preparing a scene compiles shaders + this.sceneView.Prepare (new NSObject [] { scene }, (success) => { + Console.WriteLine (success ? "Preloading assets succeeded" : "Preloading assets failed"); + }); + }); + } + } + }); + } + + private void SetLevelLighting (SCNNode node) + { + var light = node.FindChildNode ("LightNode", true)?.Light; + if (light != null) { + light.ShadowRadius = 3; + light.ShadowSampleCount = 8; + } + } + + private void SetupLevel () + { + if (this.gameManager == null) { + throw new Exception ("gameManager not initialized"); + } + + if (this.gameBoard.Anchor == null) { + var boardTransform = this.gameBoard.Transform.Normalize (); + boardTransform.Transpose (); + + var boardSize = new CGSize ((float) this.gameBoard.Scale.X, (float) (this.gameBoard.Scale.X * this.gameBoard.AspectRatio)); + this.gameBoard.Anchor = new BoardAnchor (boardTransform, boardSize); + this.sceneView.Session.AddAnchor (this.gameBoard.Anchor); + } + + this.gameBoard.HideBorder (); + this.SessionState = SessionState.GameInProgress; + + GameTime.SetLevelStartTime (); + this.gameManager.Start (); + this.gameManager.AddLevel (this.renderRoot, this.gameBoard); + this.gameManager.RestWorld (); + + if (!UserDefaults.DisableInGameUI) { + this.teamACatapultImages.ForEach ((item) => item.Hidden = false); + this.teamBCatapultImages.ForEach ((item) => item.Hidden = false); + } + + // stop ranging for beacons after placing board + if (UserDefaults.GameRoomMode) { + this.proximityManager.Stop (); + if (this.proximityManager.ClosestLocation != null) { + this.gameManager.UpdateSessionLocation (this.proximityManager.ClosestLocation); + } + } + } + + private void SendWorldTo (Player peer) + { + if (this.gameManager != null && this.gameManager.IsServer) { + switch (UserDefaults.BoardLocatingMode) { + case BoardLocatingMode.WorldMap: + // generating worldmap + this.GetCurrentWorldMapData ((data, error) => { + if (error == null && data != null) { + // got a compressed map + var location = new GameBoardLocation { WorldMapData = data, Type = GameBoardLocation.GameBoardLocationType.WorldMapData }; + DispatchQueue.MainQueue.DispatchAsync (() => { + // sending worldmap + this.gameManager.Send (new BoardSetupAction { BoardLocation = location, Type = BoardSetupAction.BoardSetupActionType.BoardLocation }, peer); + }); + } else if (error != null) { + Console.WriteLine ($"Didn't work! {error?.LocalizedDescription ?? string.Empty}"); + } + }); + break; + + case BoardLocatingMode.Manual: + this.gameManager.Send (new BoardSetupAction { BoardLocation = new GameBoardLocation { Type = GameBoardLocation.GameBoardLocationType.Manual } }, peer); + break; + } + } + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (!string.IsNullOrEmpty (segue.Identifier) && + Enum.TryParse<GameSegue> (segue.Identifier, true, out GameSegue segueType)) { + switch (segueType) { + case GameSegue.EmbeddedOverlay: + if (segue.DestinationViewController is GameStartViewController gameStartViewController) { + gameStartViewController.Delegate = this; + this.musicCoordinator.PlayMusic ("music_menu", 0f); + } + break; + + case GameSegue.WorldMapSelector: + if (segue.DestinationViewController is WorldMapSelectorViewController worldMapSelectorViewController) { + worldMapSelectorViewController.Delegate = this; + } + break; + } + } + } + + private void ShowOverlay () + { + UIView.Transition (this.View, 1d, UIViewAnimationOptions.TransitionCrossDissolve, () => { + this.overlayView.Hidden = false; + this.inSceneButtons.ForEach ((button) => button.Hidden = true); + + this.settingsButton.Hidden = true; + this.instructionLabel.Hidden = true; + }, () => { + this.overlayView.UserInteractionEnabled = true; + UIApplication.SharedApplication.IdleTimerDisabled = false; + }); + + this.musicCoordinator.PlayMusic ("music_menu", 0.5f); + } + + private void HideOverlay () + { + UIView.Transition (this.View, 1d, UIViewAnimationOptions.TransitionCrossDissolve, () => { + this.overlayView.Hidden = true; + this.inSceneButtons.ForEach ((button) => button.Hidden = false); + + this.instructionLabel.Hidden = false; + this.settingsButton.Hidden = !UserDefaults.ShowSettingsInGame; + }, () => { + this.overlayView.UserInteractionEnabled = false; + UIApplication.SharedApplication.IdleTimerDisabled = true; + }); + + this.musicCoordinator.StopMusic ("music_menu", 3f); + } + + #endregion + + #region ISCNSceneRendererDelegate + + // This is the ordering of delegate calls + // https://developer.apple.com/documentation/scenekit/scnscenerendererdelegate + + [Export ("renderer:updateAtTime:")] + public void Update (ISCNSceneRenderer renderer, double timeInSeconds) + { + if (this.gameManager != null && this.gameManager.IsInitialized) { + GameTime.UpdateAtTime (timeInSeconds); + + if (this.sceneView.PointOfView != null && this.selectedLevel != null && this.selectedLevel.Placed) { + // make a copy of the camera data that other threads can access + // ARKit has updated the transform right before this + this.gameManager.CopySimulationCamera (); + + // these can use the pointOfView since the render thread scales/unscales the camera around rendering + var pointOfViewTransform = this.sceneView.PointOfView.Transform; + pointOfViewTransform.Transpose (); + var cameraTransform = this.gameManager.RenderSpaceTransformToSimulationSpace (pointOfViewTransform); + var cameraInfo = new CameraInfo (cameraTransform); + + this.gameManager.UpdateCamera (cameraInfo); + + var canGrabCatapult = this.gameManager.CanGrabACatapult (cameraInfo.Ray); + var isGrabbingCatapult = this.gameManager.IsCurrentPlayerGrabbingACatapult (); + + DispatchQueue.MainQueue.DispatchAsync (() => { + if (this.sessionState == SessionState.GameInProgress) { + if (!UserDefaults.HasOnboarded && !UserDefaults.DisableInGameUI) { + if (isGrabbingCatapult) { + this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString ("Release to shoot."); + } else if (canGrabCatapult) { + this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString ("Tap anywhere and hold to pull back."); + } else { + this.instructionLabel.Text = NSBundle.MainBundle.GetLocalizedString ("Move closer to a slingshot."); + } + } else { + if (!this.instructionLabel.Hidden && !this.isSessionInterrupted) { + this.instructionLabel.Hidden = true; + } + } + } + }); + } + + this.gameManager.Update (GameTime.DeltaTime); + } + } + + [Export ("renderer:didApplyConstraintsAtTime:")] + public void DidApplyConstraints (ISCNSceneRenderer renderer, double atTime) + { + if (this.gameManager != null && this.gameManager.IsInitialized) { + // scale up/down the camera to render space + this.gameManager.ScaleCameraToRender (); + + // render space from here until scaleCameraToSimulation() is called + if (this.sceneView.PointOfView != null) { + this.audioListenerNode.WorldTransform = this.sceneView.PointOfView.WorldTransform; + } + + // The only functionality currently controlled here is the trail on the projectile. + // Therefore this part is used to turn on/off show projectile trail + if (UserDefaults.ShowProjectileTrail) { + this.gameManager?.OnDidApplyConstraints (renderer); + } + } + } + + [Export ("renderer:didRenderScene:atTime:")] + public void DidRenderScene (ISCNSceneRenderer renderer, SCNScene scene, double timeInSeconds) + { + // update visibility properties in renderloop because we have to scale the physics world down to render properly + if (this.gameManager != null && this.gameManager.IsInitialized) { + // this visibility test is in scaled space, using renderer frustum culling + if (this.sceneView.PointOfView != null) { + this.gameManager?.UpdateCatapultVisibility (renderer, this.sceneView.PointOfView); + } + + // return the pointOfView back from scaled space + this.gameManager?.ScaleCameraToSimulation (); + } + } + + #endregion + + #region ARSessionDelegate + + [Export ("session:didUpdateFrame:")] + public void DidUpdateFrame (ARSession session, ARFrame frame) + { + // Update game board placement in physical world + if (this.gameManager != null) { + // this is main thread calling into init code + this.UpdateGameBoard (frame); + } + + // Update mapping status for saving maps + this.UpdateMappingStatus (frame.WorldMappingStatus); + + // dispose after updating + frame.Dispose (); + } + + #endregion + + #region IGameManagerDelegate + + public void OnReceived (GameManager manager, BoardSetupAction boardAction, Player player) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.Process (boardAction, player); + }); + } + + public void OnJoiningHost (GameManager manager, Player host) + { + // host joined the game + DispatchQueue.MainQueue.DispatchAsync (() => { + if (this.sessionState == SessionState.WaitingForBoard) { + manager.Send (new BoardSetupAction { Type = BoardSetupAction.BoardSetupActionType.RequestBoardLocation }); + } + + if (!UserDefaults.DisableInGameUI) { + this.notificationLabel.Text = "You joined the game!"; + this.notificationLabel.FadeInFadeOut (1d); + } + }); + } + + public void OnJoiningPlayer (GameManager manager, Player player) + { + // non-host player joined the game + if (!UserDefaults.DisableInGameUI) { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.notificationLabel.Text = $"{player.Username} joined the game."; + this.notificationLabel.FadeInFadeOut (1d); + }); + + // If the gameplay music is already running, start it on the newly + // connected client. + if (this.musicCoordinator.CurrentMusicPlayer?.Name == "music_gameplay") { + var musicTime = this.musicCoordinator.CurrentMusicTime (); + //os_log(.debug, "music play position = %f", musicTime) + if (musicTime >= 0) { + manager.StartGameMusic (player); + } + } + } + } + + public void OnLeavingHost (GameManager manager, Player host) + { + // host left the game + if (!UserDefaults.DisableInGameUI) { + DispatchQueue.MainQueue.DispatchAsync (() => { + // the game can no longer continue + this.notificationLabel.Text = "The host left the game. Please join another game or start your own!"; + this.notificationLabel.Hidden = false; + }); + } + } + + public void OnLeavingPlayer (GameManager manager, Player player) + { + // non-host player left the game + if (!UserDefaults.DisableInGameUI) { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.notificationLabel.Text = $"{player.Username} left the game."; + this.notificationLabel.FadeInFadeOut (1d); + }); + } + } + + public void OnDidStartGame (GameManager manager) { } + + public void OnManagerDidWinGame (GameManager manager) + { + this.musicCoordinator.PlayMusic ("music_win"); + } + + public void OnHasNetworkDelay (GameManager manager, bool hasNetworkDelay) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (UserDefaults.ShowNetworkDebug) { + this.networkDelayText.Hidden = !hasNetworkDelay; + } + }); + } + + public void OnGameStateUpdated (GameManager manager, GameState gameState) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (this.SessionState == SessionState.GameInProgress) { + this.TeamACatapultCount = gameState.TeamACatapults; + this.TeamBCatapultCount = gameState.TeamBCatapults; + } + }); + } + + #endregion + + #region IGameStartViewControllerDelegate + + private void CreateGameManager (NetworkSession session) + { + var level = UserDefaults.SelectedLevel; + this.SelectedLevel = level; + this.GameManager = new GameManager (this.sceneView, + level, + session, + this.sceneView.AudioEnvironmentNode, + this.musicCoordinator); + } + + public void OnSoloGamePressed (UIViewController viewController, UIButton button) + { + this.HideOverlay (); + this.CreateGameManager (null); + } + + public void OnGameSelected (UIViewController viewController, NetworkSession game) + { + this.HideOverlay (); + this.CreateGameManager (game); + } + + public void OnGameStarted (UIViewController viewController, NetworkSession game) + { + this.HideOverlay (); + this.CreateGameManager (game); + } + + public void OnSettingsSelected (UIViewController viewController) + { + this.PerformSegue (GameSegue.ShowSettings.ToString (), this); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/LevelSelectorViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/LevelSelectorViewController.cs index 9696277c6..5155806df 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/LevelSelectorViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/LevelSelectorViewController.cs @@ -1,74 +1,67 @@ - -namespace XamarinShot -{ - using Foundation; - using XamarinShot.Models; - using XamarinShot.Utils; - using System; - using UIKit; - - public interface ILevelSelectorViewControllerDelegate - { - void OnLevelSelected(LevelSelectorViewController controller, GameLevel level); - } - - /// <summary> - /// View controller for choosing levels. - /// </summary> - public partial class LevelSelectorViewController : UITableViewController - { - public LevelSelectorViewController(IntPtr handle) : base(handle) { } - - public ILevelSelectorViewControllerDelegate Delegate { get; set; } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.TableView.Delegate = this; - this.TableView.DataSource = this; - } - #region UITableViewDataSource - - public override nint RowsInSection(UITableView tableView, nint section) - { - return GameLevel.AllLevels.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var level = GameLevel.Level(indexPath.Row); - if (level == null) - { - throw new Exception($"Level {indexPath.Row} not found"); - } - - var cell = this.TableView.DequeueReusableCell("LevelCell", indexPath); - cell.TextLabel.Text = level.Name; - - return cell; - } +namespace XamarinShot { + using Foundation; + using XamarinShot.Models; + using XamarinShot.Utils; + using System; + using UIKit; - #endregion + public interface ILevelSelectorViewControllerDelegate { + void OnLevelSelected (LevelSelectorViewController controller, GameLevel level); + } - #region UITableViewDelegate - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - var level = GameLevel.Level(indexPath.Row); - if (level != null) - { - UserDefaults.SelectedLevel = level; - this.Delegate?.OnLevelSelected(this, level); + /// <summary> + /// View controller for choosing levels. + /// </summary> + public partial class LevelSelectorViewController : UITableViewController { + public LevelSelectorViewController (IntPtr handle) : base (handle) { } - this.NavigationController.PopViewController(true); - } - else - { - throw new Exception($"Level {indexPath.Row} not found"); - } - } + public ILevelSelectorViewControllerDelegate Delegate { get; set; } - #endregion - } -} \ No newline at end of file + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.TableView.Delegate = this; + this.TableView.DataSource = this; + } + + #region UITableViewDataSource + + public override nint RowsInSection (UITableView tableView, nint section) + { + return GameLevel.AllLevels.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var level = GameLevel.Level (indexPath.Row); + if (level == null) { + throw new Exception ($"Level {indexPath.Row} not found"); + } + + var cell = this.TableView.DequeueReusableCell ("LevelCell", indexPath); + cell.TextLabel.Text = level.Name; + + return cell; + } + + #endregion + + #region UITableViewDelegate + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + var level = GameLevel.Level (indexPath.Row); + if (level != null) { + UserDefaults.SelectedLevel = level; + this.Delegate?.OnLevelSelected (this, level); + + this.NavigationController.PopViewController (true); + } else { + throw new Exception ($"Level {indexPath.Row} not found"); + } + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/NetworkGameBrowserViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/NetworkGameBrowserViewController.cs index 413664015..fc67e74f6 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/NetworkGameBrowserViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/NetworkGameBrowserViewController.cs @@ -1,145 +1,131 @@ - -namespace XamarinShot -{ - using Foundation; - using XamarinShot.Models; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - /// <summary> - /// View controller for finding network games. - /// </summary> - public partial class NetworkGameBrowserViewController : UIViewController, - IUITableViewDelegate, - IUITableViewDataSource, - IGameBrowserDelegate - { - private List<NetworkGame> games = new List<NetworkGame>(); - - private GameBrowser browser; - - public NetworkGameBrowserViewController(IntPtr handle) : base(handle) { } - - // must be set by parent - public ProximityManager ProximityManager { get; set; } - - /// <summary> - /// Must be set by parent - /// </summary> - /// <value>The browser.</value> - public GameBrowser Browser - { - get - { - return this.browser; - } - - set - { - if (this.browser != null) - { - this.browser.Stop(); - } - - this.browser = value; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.tableView.DataSource = this; - this.tableView.Delegate = this; - this.tableView.Layer.CornerRadius = 10; - this.tableView.ClipsToBounds = true; - this.StartBrowser(); - } - - private void StartBrowser() - { - if (this.browser != null) - { - this.browser.Delegate = this; - this.browser.Start(); - - this.tableView.ReloadData(); - } - } - - private void JoinGame(NetworkGame game) - { - var session = this.browser?.Join(game); - if (session != null) - { - if (this.ParentViewController is GameStartViewController parent) - { - parent.JoinGame(session); - } - else - { - throw new ArgumentException("Unexpected parent", nameof(this.ParentViewController)); - } - } - } - - #region IGameBrowserDelegate - - public void SawGames(GameBrowser browser, IList<NetworkGame> games) - { - // os_log(.info, "saw %d games!", games.count) - var location = this.ProximityManager?.ClosestLocation; - if (location != null && UserDefaults.GameRoomMode) - { - this.games = games.Where(game => game.Location == location).ToList(); - } - else - { - this.games = games.ToList(); - } - - this.tableView.ReloadData(); - } - - #endregion - - #region UITableViewDataSource - - public nint RowsInSection(UITableView tableView, nint section) - { - return this.games.Count; - } - - [Export("numberOfSectionsInTableView:")] - public nint NumberOfSections(UITableView tableView) - { - return 1; - } - - public UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var game = this.games[indexPath.Row]; - - var cell = tableView.DequeueReusableCell("GameCell", indexPath); - cell.TextLabel.Text = game.Name; - return cell; - } - - #endregion - - #region IUITableViewDelegate - - [Export("tableView:didSelectRowAtIndexPath:")] - public void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - this.tableView.DeselectRow(indexPath, true); - var otherPlayer = this.games[indexPath.Row]; - this.JoinGame(otherPlayer); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot { + using Foundation; + using XamarinShot.Models; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + /// <summary> + /// View controller for finding network games. + /// </summary> + public partial class NetworkGameBrowserViewController : UIViewController, + IUITableViewDelegate, + IUITableViewDataSource, + IGameBrowserDelegate { + private List<NetworkGame> games = new List<NetworkGame> (); + + private GameBrowser browser; + + public NetworkGameBrowserViewController (IntPtr handle) : base (handle) { } + + // must be set by parent + public ProximityManager ProximityManager { get; set; } + + /// <summary> + /// Must be set by parent + /// </summary> + /// <value>The browser.</value> + public GameBrowser Browser { + get { + return this.browser; + } + + set { + if (this.browser != null) { + this.browser.Stop (); + } + + this.browser = value; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.tableView.DataSource = this; + this.tableView.Delegate = this; + this.tableView.Layer.CornerRadius = 10; + this.tableView.ClipsToBounds = true; + this.StartBrowser (); + } + + private void StartBrowser () + { + if (this.browser != null) { + this.browser.Delegate = this; + this.browser.Start (); + + this.tableView.ReloadData (); + } + } + + private void JoinGame (NetworkGame game) + { + var session = this.browser?.Join (game); + if (session != null) { + if (this.ParentViewController is GameStartViewController parent) { + parent.JoinGame (session); + } else { + throw new ArgumentException ("Unexpected parent", nameof (this.ParentViewController)); + } + } + } + + #region IGameBrowserDelegate + + public void SawGames (GameBrowser browser, IList<NetworkGame> games) + { + // os_log(.info, "saw %d games!", games.count) + var location = this.ProximityManager?.ClosestLocation; + if (location != null && UserDefaults.GameRoomMode) { + this.games = games.Where (game => game.Location == location).ToList (); + } else { + this.games = games.ToList (); + } + + this.tableView.ReloadData (); + } + + #endregion + + #region UITableViewDataSource + + public nint RowsInSection (UITableView tableView, nint section) + { + return this.games.Count; + } + + [Export ("numberOfSectionsInTableView:")] + public nint NumberOfSections (UITableView tableView) + { + return 1; + } + + public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var game = this.games [indexPath.Row]; + + var cell = tableView.DequeueReusableCell ("GameCell", indexPath); + cell.TextLabel.Text = game.Name; + return cell; + } + + #endregion + + #region IUITableViewDelegate + + [Export ("tableView:didSelectRowAtIndexPath:")] + public void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + this.tableView.DeselectRow (indexPath, true); + var otherPlayer = this.games [indexPath.Row]; + this.JoinGame (otherPlayer); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/UserSettingsTableViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/UserSettingsTableViewController.cs index bfb302b9e..0fba6ad53 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/UserSettingsTableViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/UserSettingsTableViewController.cs @@ -1,122 +1,114 @@ - -namespace XamarinShot -{ - using Foundation; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using UIKit; - - /// <summary> - /// View controller for user settings. - /// </summary> - public partial class UserSettingsTableViewController : UITableViewController, - IUITextFieldDelegate, - ILevelSelectorViewControllerDelegate - { - private ButtonBeep effectsLevelReleased; - - public UserSettingsTableViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.playerNameTextField.Delegate = this; - - this.UpdateSelectedLevel(); - - this.playerNameTextField.Text = UserDefaults.Myself.Username; - this.spectatorSwitch.On = UserDefaults.Spectator; - this.musicVolume.Value = UserDefaults.MusicVolume; - this.effectsVolume.Value = UserDefaults.EffectsVolume; - this.effectsLevelReleased = ButtonBeep.Create("catapult_highlight_on_02.wav", UserDefaults.EffectsVolume); - this.appVersionLabel.Text = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleShortVersionString") + - $" ({NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion")})"; - } - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - var segueIdentifier = segue.Identifier; - if (!string.IsNullOrEmpty(segueIdentifier) && - Enum.TryParse<GameSegue>(segueIdentifier, true, out GameSegue segueType)) - { - switch (segueType) - { - case GameSegue.LevelSelector: - if (segue.DestinationViewController is LevelSelectorViewController levelSelector) - { - levelSelector.Delegate = this; - } - - break; - } - } - } - - partial void spectatorChanged(UISwitch sender) - { - UserDefaults.Spectator = sender.On; - } - - partial void musicVolumeChanged(UISlider sender) - { - UserDefaults.MusicVolume = sender.Value; - } - - partial void effectVolumeChanged(UISlider sender) - { - UserDefaults.EffectsVolume = sender.Value; - } - - partial void effectVolumeReleased(UISlider sender) - { - this.effectsLevelReleased.Play(); - } - - partial void doneTapped(UIBarButtonItem sender) - { - this.DismissViewController(true, null); - } - - private void UpdateSelectedLevel() - { - var selectedLevel = UserDefaults.SelectedLevel; - this.selectedLevelLabel.Text = selectedLevel.Name; - } - - #region IUITextFieldDelegate - - [Export("textFieldShouldReturn:")] - public bool ShouldReturn(UITextField textField) - { - textField.ResignFirstResponder(); - return true; - } - - [Export("textFieldDidEndEditing:reason:")] - public void EditingEnded(UITextField textField, UITextFieldDidEndEditingReason reason) - { - if (reason == UITextFieldDidEndEditingReason.Committed && - !string.IsNullOrEmpty(this.playerNameTextField.Text)) - { - UserDefaults.Myself = new Player(this.playerNameTextField.Text); - } - else - { - this.playerNameTextField.Text = UserDefaults.Myself.Username; - } - } - - #endregion - - #region ILevelSelectorViewControllerDelegate - - public void OnLevelSelected(LevelSelectorViewController levelSelectorViewController, GameLevel level) - { - this.UpdateSelectedLevel(); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot { + using Foundation; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using UIKit; + + /// <summary> + /// View controller for user settings. + /// </summary> + public partial class UserSettingsTableViewController : UITableViewController, + IUITextFieldDelegate, + ILevelSelectorViewControllerDelegate { + private ButtonBeep effectsLevelReleased; + + public UserSettingsTableViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.playerNameTextField.Delegate = this; + + this.UpdateSelectedLevel (); + + this.playerNameTextField.Text = UserDefaults.Myself.Username; + this.spectatorSwitch.On = UserDefaults.Spectator; + this.musicVolume.Value = UserDefaults.MusicVolume; + this.effectsVolume.Value = UserDefaults.EffectsVolume; + this.effectsLevelReleased = ButtonBeep.Create ("catapult_highlight_on_02.wav", UserDefaults.EffectsVolume); + this.appVersionLabel.Text = NSBundle.MainBundle.ObjectForInfoDictionary ("CFBundleShortVersionString") + + $" ({NSBundle.MainBundle.ObjectForInfoDictionary ("CFBundleVersion")})"; + } + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + var segueIdentifier = segue.Identifier; + if (!string.IsNullOrEmpty (segueIdentifier) && + Enum.TryParse<GameSegue> (segueIdentifier, true, out GameSegue segueType)) { + switch (segueType) { + case GameSegue.LevelSelector: + if (segue.DestinationViewController is LevelSelectorViewController levelSelector) { + levelSelector.Delegate = this; + } + + break; + } + } + } + + partial void spectatorChanged (UISwitch sender) + { + UserDefaults.Spectator = sender.On; + } + + partial void musicVolumeChanged (UISlider sender) + { + UserDefaults.MusicVolume = sender.Value; + } + + partial void effectVolumeChanged (UISlider sender) + { + UserDefaults.EffectsVolume = sender.Value; + } + + partial void effectVolumeReleased (UISlider sender) + { + this.effectsLevelReleased.Play (); + } + + partial void doneTapped (UIBarButtonItem sender) + { + this.DismissViewController (true, null); + } + + private void UpdateSelectedLevel () + { + var selectedLevel = UserDefaults.SelectedLevel; + this.selectedLevelLabel.Text = selectedLevel.Name; + } + + #region IUITextFieldDelegate + + [Export ("textFieldShouldReturn:")] + public bool ShouldReturn (UITextField textField) + { + textField.ResignFirstResponder (); + return true; + } + + [Export ("textFieldDidEndEditing:reason:")] + public void EditingEnded (UITextField textField, UITextFieldDidEndEditingReason reason) + { + if (reason == UITextFieldDidEndEditingReason.Committed && + !string.IsNullOrEmpty (this.playerNameTextField.Text)) { + UserDefaults.Myself = new Player (this.playerNameTextField.Text); + } else { + this.playerNameTextField.Text = UserDefaults.Myself.Username; + } + } + + #endregion + + #region ILevelSelectorViewControllerDelegate + + public void OnLevelSelected (LevelSelectorViewController levelSelectorViewController, GameLevel level) + { + this.UpdateSelectedLevel (); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Controllers/WorldMapSelectorViewController.cs b/ios12/XamarinShot/XamarinShot/Controllers/WorldMapSelectorViewController.cs index db91d19ce..c84048d3e 100644 --- a/ios12/XamarinShot/XamarinShot/Controllers/WorldMapSelectorViewController.cs +++ b/ios12/XamarinShot/XamarinShot/Controllers/WorldMapSelectorViewController.cs @@ -1,68 +1,64 @@ - -namespace XamarinShot -{ - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - public interface IWorldMapSelectorDelegate - { - void WorldMapSelector(WorldMapSelectorViewController worldMapSelector, Uri selectedMap); - } +namespace XamarinShot { + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; - /// <summary> - /// Allows the user to load a pre-saved map of the physical world for ARKit. The app then uses this to place the board in real space. - /// </summary> - public partial class WorldMapSelectorViewController : UITableViewController - { - private List<NSUrl> maps = new List<NSUrl>(); + public interface IWorldMapSelectorDelegate { + void WorldMapSelector (WorldMapSelectorViewController worldMapSelector, Uri selectedMap); + } - public WorldMapSelectorViewController(IntPtr handle) : base(handle) { } + /// <summary> + /// Allows the user to load a pre-saved map of the physical world for ARKit. The app then uses this to place the board in real space. + /// </summary> + public partial class WorldMapSelectorViewController : UITableViewController { + private List<NSUrl> maps = new List<NSUrl> (); - public IWorldMapSelectorDelegate Delegate { get; set; } + public WorldMapSelectorViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public IWorldMapSelectorDelegate Delegate { get; set; } - var docs = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out NSError error); - if (error != null) - { - Console.WriteLine($"error loading world maps directory: {error.LocalizedDescription ?? string.Empty}"); - this.DismissViewController(true, null); - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); - var mapsDirectory = docs.Append("maps", isDirectory: true); - var localMaps = NSFileManager.DefaultManager.GetDirectoryContent(mapsDirectory, null, default(NSDirectoryEnumerationOptions), out NSError _); - this.maps = localMaps.Select(map => map.AbsoluteUrl).ToList(); - } + var docs = NSFileManager.DefaultManager.GetUrl (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, null, true, out NSError error); + if (error != null) { + Console.WriteLine ($"error loading world maps directory: {error.LocalizedDescription ?? string.Empty}"); + this.DismissViewController (true, null); + } - #region IUITableViewDelegate + var mapsDirectory = docs.Append ("maps", isDirectory: true); + var localMaps = NSFileManager.DefaultManager.GetDirectoryContent (mapsDirectory, null, default (NSDirectoryEnumerationOptions), out NSError _); + this.maps = localMaps.Select (map => map.AbsoluteUrl).ToList (); + } - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - this.Delegate?.WorldMapSelector(this, this.maps[indexPath.Row]); - this.DismissViewController(true, null); - } + #region IUITableViewDelegate - #endregion + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + this.Delegate?.WorldMapSelector (this, this.maps [indexPath.Row]); + this.DismissViewController (true, null); + } - #region IUITableViewDataSource + #endregion - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.maps.Count; - } + #region IUITableViewDataSource - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("MapCell", indexPath); - cell.TextLabel.Text = this.maps[indexPath.Row].RemovePathExtension().LastPathComponent; - return cell; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.maps.Count; + } - #endregion - } -} \ No newline at end of file + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("MapCell", indexPath); + cell.TextLabel.Text = this.maps [indexPath.Row].RemovePathExtension ().LastPathComponent; + return cell; + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Enums/BoardLocatingMode.cs b/ios12/XamarinShot/XamarinShot/Core/Enums/BoardLocatingMode.cs index b9fc37aa1..7cc2378f4 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Enums/BoardLocatingMode.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Enums/BoardLocatingMode.cs @@ -1,11 +1,9 @@ - -namespace XamarinShot.Models.Enums -{ - public enum BoardLocatingMode - { - WorldMap = 0, // default - // slot 1 previously used; leave empty so that on update, - // worldMap is used insead. - Manual = 2, - } -} \ No newline at end of file + +namespace XamarinShot.Models.Enums { + public enum BoardLocatingMode { + WorldMap = 0, // default + // slot 1 previously used; leave empty so that on update, + // worldMap is used insead. + Manual = 2, + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Enums/CollisionMask.cs b/ios12/XamarinShot/XamarinShot/Core/Enums/CollisionMask.cs index a363d283a..640882a16 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Enums/CollisionMask.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Enums/CollisionMask.cs @@ -1,15 +1,13 @@ - -namespace XamarinShot.Models.Enums -{ - [System.Flags] - public enum CollisionMask - { - RigidBody = 1, - GlitterObject = 2, - Ball = 4, - Phantom = 32, // for detecting collisions with trigger volumes - TriggerVolume = 64, // trigger behavior without affecting physics - CatapultTeamA = 128, - CatapultTeamB = 256 - } -} \ No newline at end of file + +namespace XamarinShot.Models.Enums { + [System.Flags] + public enum CollisionMask { + RigidBody = 1, + GlitterObject = 2, + Ball = 4, + Phantom = 32, // for detecting collisions with trigger volumes + TriggerVolume = 64, // trigger behavior without affecting physics + CatapultTeamA = 128, + CatapultTeamB = 256 + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Enums/GameSegue.cs b/ios12/XamarinShot/XamarinShot/Core/Enums/GameSegue.cs index 1b47b0356..d468d4df5 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Enums/GameSegue.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Enums/GameSegue.cs @@ -1,12 +1,10 @@ - -namespace XamarinShot.Models.Enums -{ - public enum GameSegue - { - EmbeddedGameBrowser, - EmbeddedOverlay, - ShowSettings, - LevelSelector, - WorldMapSelector, - } -} \ No newline at end of file + +namespace XamarinShot.Models.Enums { + public enum GameSegue { + EmbeddedGameBrowser, + EmbeddedOverlay, + ShowSettings, + LevelSelector, + WorldMapSelector, + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Enums/ProjectileType.cs b/ios12/XamarinShot/XamarinShot/Core/Enums/ProjectileType.cs index a7487d666..ec06b76a1 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Enums/ProjectileType.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Enums/ProjectileType.cs @@ -1,10 +1,8 @@ - -namespace XamarinShot.Models.Enums -{ - public enum ProjectileType - { - None = 0, - Cannonball, - Chicken, - } -} \ No newline at end of file + +namespace XamarinShot.Models.Enums { + public enum ProjectileType { + None = 0, + Cannonball, + Chicken, + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Enums/SessionState.cs b/ios12/XamarinShot/XamarinShot/Core/Enums/SessionState.cs index b06809b26..12127c961 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Enums/SessionState.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Enums/SessionState.cs @@ -1,59 +1,53 @@ - -namespace XamarinShot.Models.Enums -{ - using Foundation; - using XamarinShot.Utils; - public enum SessionState - { - Setup, - LookingForSurface, - AdjustingBoard, - PlacingBoard, - WaitingForBoard, - LocalizingToBoard, - SetupLevel, - GameInProgress, - } +namespace XamarinShot.Models.Enums { + using Foundation; + using XamarinShot.Utils; - public static class SessionStateExtensions - { - public static string LocalizedInstruction(this SessionState self) - { - string result = null; - if (!UserDefaults.DisableInGameUI) - { - switch (self) - { - case SessionState.LookingForSurface: - result = NSBundle.MainBundle.GetLocalizedString("Find a flat surface to place the game."); - break; - case SessionState.PlacingBoard: - result = NSBundle.MainBundle.GetLocalizedString("Scale, rotate or move the board."); - break; - case SessionState.AdjustingBoard: - result = NSBundle.MainBundle.GetLocalizedString("Make adjustments and tap to continue."); - break; - case SessionState.GameInProgress: - if (!UserDefaults.HasOnboarded && !UserDefaults.Spectator) - { - result = NSBundle.MainBundle.GetLocalizedString("Move closer to a slingshot."); - } - break; - case SessionState.WaitingForBoard: - result = NSBundle.MainBundle.GetLocalizedString("Synchronizing world map…"); - break; - case SessionState.LocalizingToBoard: - result = NSBundle.MainBundle.GetLocalizedString("Point the camera towards the table."); - break; - case SessionState.SetupLevel: - case SessionState.Setup: - result = null; - break; - } - } + public enum SessionState { + Setup, + LookingForSurface, + AdjustingBoard, + PlacingBoard, + WaitingForBoard, + LocalizingToBoard, + SetupLevel, + GameInProgress, + } - return result; - } - } -} \ No newline at end of file + public static class SessionStateExtensions { + public static string LocalizedInstruction (this SessionState self) + { + string result = null; + if (!UserDefaults.DisableInGameUI) { + switch (self) { + case SessionState.LookingForSurface: + result = NSBundle.MainBundle.GetLocalizedString ("Find a flat surface to place the game."); + break; + case SessionState.PlacingBoard: + result = NSBundle.MainBundle.GetLocalizedString ("Scale, rotate or move the board."); + break; + case SessionState.AdjustingBoard: + result = NSBundle.MainBundle.GetLocalizedString ("Make adjustments and tap to continue."); + break; + case SessionState.GameInProgress: + if (!UserDefaults.HasOnboarded && !UserDefaults.Spectator) { + result = NSBundle.MainBundle.GetLocalizedString ("Move closer to a slingshot."); + } + break; + case SessionState.WaitingForBoard: + result = NSBundle.MainBundle.GetLocalizedString ("Synchronizing world map…"); + break; + case SessionState.LocalizingToBoard: + result = NSBundle.MainBundle.GetLocalizedString ("Point the camera towards the table."); + break; + case SessionState.SetupLevel: + case SessionState.Setup: + result = null; + break; + } + } + + return result; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Enums/TouchType.cs b/ios12/XamarinShot/XamarinShot/Core/Enums/TouchType.cs index d770f82a0..09de5a522 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Enums/TouchType.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Enums/TouchType.cs @@ -1,10 +1,8 @@ - -namespace XamarinShot.Models.Enums -{ - public enum TouchType - { - Tapped, - Began, - Ended, - } -} \ No newline at end of file + +namespace XamarinShot.Models.Enums { + public enum TouchType { + Tapped, + Began, + Ended, + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/AnimWaypointComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/AnimWaypointComponent.cs index 7af7aa351..da89e2bc1 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/AnimWaypointComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/AnimWaypointComponent.cs @@ -1,237 +1,213 @@ - -namespace XamarinShot.Models.GameplayState -{ - using Foundation; - using GameplayKit; - using SceneKit; - using System; - using System.Collections.Generic; - using System.Linq; - using XamarinShot.Utils; - - public class AnimWaypointComponent : GKComponent - { - private const string WaypointPrefix = "_waypoint"; - - private readonly List<Waypoint> wayPoints = new List<Waypoint>(); - - private readonly double speed = 1d; - - private double currentTime = 0d; - - private int currentFrame = 0; - - private SCNNode node; - - public AnimWaypointComponent(SCNNode node, Dictionary<string, object> properties) : base() - { - this.node = node; - - if (properties.TryGetValue("speed", out object speed)) - { - this.speed = (double)speed; - } - - // find all waypoints - this.InitWaypoints(this.node); - this.CalculateTangents(); - - // does this animation support random start times? - if (properties.TryGetValue("random", out object random)) - { - if (random is bool isRandom && isRandom && this.wayPoints.Any()) - { - var last = this.wayPoints.Last(); - this.currentTime = new Random().NextDouble() * last.Time; - } - } - - // do we want to start at a particular percentage along curve? - if (properties.TryGetValue("phase", out object objectPhase)) - { - if (objectPhase is double phase && this.wayPoints.Any()) - { - var desiredPhase = DigitExtensions.Clamp(phase, 0d, 1d); - var last = this.wayPoints.Last(); - this.currentTime = desiredPhase * last.Time; - } - - } - - // do we want to start at a specific point in time? - if (properties.TryGetValue("offset", out object objectOffset)) - { - if (objectOffset is double offset && this.wayPoints.Any()) - { - var last = this.wayPoints.Last(); - this.currentTime = offset * last.Time; - } - - } - } - - public AnimWaypointComponent(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public bool HasWaypoints => this.wayPoints.Count > 1; - - private void CalcCurrentFrameIndex() - { - var last = this.wayPoints.LastOrDefault(); - if (last != null) - { - // loop if we are past endpoint - while (this.currentTime > last.Time && last.Time > 0) - { - this.currentTime -= last.Time; - } - - // update frame when past time value - for (int i = 0; i < this.wayPoints.Count; i++) - { - if (this.currentTime > this.wayPoints[i].Time) - { - this.currentFrame = i; - } - else - { - break; - } - } - } - } - - private void InitWaypoints(SCNNode node) - { - // find start of animation group system - var systemRoot = node.ParentWithPrefix("_system"); - if (systemRoot != null) - { - // find all of the waypoints - this.IterateForWaypoints(systemRoot); - - // close the loop - var first = this.wayPoints.FirstOrDefault(); - if (first != null) - { - var waypoint = new Waypoint(first.Pos, - SCNVector3.Zero, - first.Rot, - (double)this.wayPoints.Count / this.speed); - this.wayPoints.Add(waypoint); - } - } - } - - /// <summary> - /// Find all way points - /// </summary> - private void IterateForWaypoints(SCNNode node) - { - if (!string.IsNullOrEmpty(node.Name) && node.Name.StartsWith(WaypointPrefix, StringComparison.Ordinal)) - { - var waypoint = new Waypoint(node.WorldPosition, - SCNVector3.Zero, - node.WorldOrientation, - (double)this.wayPoints.Count / this.speed); - this.wayPoints.Add(waypoint); - } - - foreach (var child in node.ChildNodes) - { - if (!string.IsNullOrEmpty(node.Name) && !node.Name.StartsWith("_system", StringComparison.Ordinal)) - { - // ignore child nodes part of another system - this.IterateForWaypoints(child); - } - } - } - - /// <summary> - /// generate a spline if given 2 positions and 2 tangents - /// </summary> - /// <returns>The curve.</returns> - private float HermiteCurve(float pos1, float pos2, float tangent1, float tangent2, float time) - { - var tSqr = time * time; - var tCube = tSqr * time; - var h1 = 2f * tCube - 3f * tSqr + 1f; - var h2 = -2f * tCube + 3f * tSqr; - var h3 = tCube - 2f * tSqr + time; - var h4 = tCube - tSqr; - var spline = h1 * pos1 + h2 * pos2 + h3 * tangent1 + h4 * tangent2; - - return spline; - } - - /// <summary> - /// Generate approximate spline tangents for every point - /// </summary> - private void CalculateTangents() - { - for (int i = 0; i < this.wayPoints.Count; i++) - { - // TODO: check - var next = (i + 1) % this.wayPoints.Count; - var prev = (i + this.wayPoints.Count - 1) % this.wayPoints.Count; - this.wayPoints[i].Tangent = (this.wayPoints[next].Pos - this.wayPoints[prev].Pos) / 3; - } - } - - #region IUpdatableComponent - - public override void Update(double deltaTimeInSeconds) - { - this.currentTime += deltaTimeInSeconds; - this.CalcCurrentFrameIndex(); - - var alpha = (float)((this.currentTime - this.wayPoints[currentFrame].Time) / - (this.wayPoints[currentFrame + 1].Time - this.wayPoints[currentFrame].Time)); - alpha = DigitExtensions.Clamp(alpha, 0f, 1f); - - var curPos = this.wayPoints[currentFrame].Pos; - var curTan = this.wayPoints[currentFrame].Tangent; - var curRot = this.wayPoints[currentFrame].Rot; - var nextPos = this.wayPoints[currentFrame + 1].Pos; - var nextTan = this.wayPoints[currentFrame + 1].Tangent; - var nextRot = this.wayPoints[currentFrame + 1].Rot; - - - var newPosX = this.HermiteCurve(curPos.X, nextPos.X, curTan.X, nextTan.X, alpha); - var newPosY = this.HermiteCurve(curPos.Y, nextPos.Y, curTan.Y, nextTan.Y, alpha); - var newPosZ = this.HermiteCurve(curPos.Z, nextPos.Z, curTan.Z, nextTan.Z, alpha); - var newQuat = SCNQuaternion.Slerp(curRot, nextRot, alpha); - node.WorldPosition = new SCNVector3(newPosX, newPosY, newPosZ); - node.WorldOrientation = newQuat; - - // update child rigid bodies to percolate into physics - if (this.Entity is GameObject entity) - { - if (entity.PhysicsNode?.PhysicsBody != null) - { - entity.PhysicsNode.PhysicsBody.ResetTransform(); - } - } - } - - #endregion - - class Waypoint - { - public Waypoint(SCNVector3 pos, SCNVector3 tangent, SCNQuaternion rot, double time) - { - this.Pos = pos; - this.Tangent = tangent; - this.Rot = rot; - this.Time = time; - } - - public SCNVector3 Pos { get; set; } - - public SCNVector3 Tangent { get; set; } - - public SCNQuaternion Rot { get; set; } - - public double Time { get; set; } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using Foundation; + using GameplayKit; + using SceneKit; + using System; + using System.Collections.Generic; + using System.Linq; + using XamarinShot.Utils; + + public class AnimWaypointComponent : GKComponent { + private const string WaypointPrefix = "_waypoint"; + + private readonly List<Waypoint> wayPoints = new List<Waypoint> (); + + private readonly double speed = 1d; + + private double currentTime = 0d; + + private int currentFrame = 0; + + private SCNNode node; + + public AnimWaypointComponent (SCNNode node, Dictionary<string, object> properties) : base () + { + this.node = node; + + if (properties.TryGetValue ("speed", out object speed)) { + this.speed = (double) speed; + } + + // find all waypoints + this.InitWaypoints (this.node); + this.CalculateTangents (); + + // does this animation support random start times? + if (properties.TryGetValue ("random", out object random)) { + if (random is bool isRandom && isRandom && this.wayPoints.Any ()) { + var last = this.wayPoints.Last (); + this.currentTime = new Random ().NextDouble () * last.Time; + } + } + + // do we want to start at a particular percentage along curve? + if (properties.TryGetValue ("phase", out object objectPhase)) { + if (objectPhase is double phase && this.wayPoints.Any ()) { + var desiredPhase = DigitExtensions.Clamp (phase, 0d, 1d); + var last = this.wayPoints.Last (); + this.currentTime = desiredPhase * last.Time; + } + + } + + // do we want to start at a specific point in time? + if (properties.TryGetValue ("offset", out object objectOffset)) { + if (objectOffset is double offset && this.wayPoints.Any ()) { + var last = this.wayPoints.Last (); + this.currentTime = offset * last.Time; + } + + } + } + + public AnimWaypointComponent (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public bool HasWaypoints => this.wayPoints.Count > 1; + + private void CalcCurrentFrameIndex () + { + var last = this.wayPoints.LastOrDefault (); + if (last != null) { + // loop if we are past endpoint + while (this.currentTime > last.Time && last.Time > 0) { + this.currentTime -= last.Time; + } + + // update frame when past time value + for (int i = 0; i < this.wayPoints.Count; i++) { + if (this.currentTime > this.wayPoints [i].Time) { + this.currentFrame = i; + } else { + break; + } + } + } + } + + private void InitWaypoints (SCNNode node) + { + // find start of animation group system + var systemRoot = node.ParentWithPrefix ("_system"); + if (systemRoot != null) { + // find all of the waypoints + this.IterateForWaypoints (systemRoot); + + // close the loop + var first = this.wayPoints.FirstOrDefault (); + if (first != null) { + var waypoint = new Waypoint (first.Pos, + SCNVector3.Zero, + first.Rot, + (double) this.wayPoints.Count / this.speed); + this.wayPoints.Add (waypoint); + } + } + } + + /// <summary> + /// Find all way points + /// </summary> + private void IterateForWaypoints (SCNNode node) + { + if (!string.IsNullOrEmpty (node.Name) && node.Name.StartsWith (WaypointPrefix, StringComparison.Ordinal)) { + var waypoint = new Waypoint (node.WorldPosition, + SCNVector3.Zero, + node.WorldOrientation, + (double) this.wayPoints.Count / this.speed); + this.wayPoints.Add (waypoint); + } + + foreach (var child in node.ChildNodes) { + if (!string.IsNullOrEmpty (node.Name) && !node.Name.StartsWith ("_system", StringComparison.Ordinal)) { + // ignore child nodes part of another system + this.IterateForWaypoints (child); + } + } + } + + /// <summary> + /// generate a spline if given 2 positions and 2 tangents + /// </summary> + /// <returns>The curve.</returns> + private float HermiteCurve (float pos1, float pos2, float tangent1, float tangent2, float time) + { + var tSqr = time * time; + var tCube = tSqr * time; + var h1 = 2f * tCube - 3f * tSqr + 1f; + var h2 = -2f * tCube + 3f * tSqr; + var h3 = tCube - 2f * tSqr + time; + var h4 = tCube - tSqr; + var spline = h1 * pos1 + h2 * pos2 + h3 * tangent1 + h4 * tangent2; + + return spline; + } + + /// <summary> + /// Generate approximate spline tangents for every point + /// </summary> + private void CalculateTangents () + { + for (int i = 0; i < this.wayPoints.Count; i++) { + // TODO: check + var next = (i + 1) % this.wayPoints.Count; + var prev = (i + this.wayPoints.Count - 1) % this.wayPoints.Count; + this.wayPoints [i].Tangent = (this.wayPoints [next].Pos - this.wayPoints [prev].Pos) / 3; + } + } + + #region IUpdatableComponent + + public override void Update (double deltaTimeInSeconds) + { + this.currentTime += deltaTimeInSeconds; + this.CalcCurrentFrameIndex (); + + var alpha = (float) ((this.currentTime - this.wayPoints [currentFrame].Time) / + (this.wayPoints [currentFrame + 1].Time - this.wayPoints [currentFrame].Time)); + alpha = DigitExtensions.Clamp (alpha, 0f, 1f); + + var curPos = this.wayPoints [currentFrame].Pos; + var curTan = this.wayPoints [currentFrame].Tangent; + var curRot = this.wayPoints [currentFrame].Rot; + var nextPos = this.wayPoints [currentFrame + 1].Pos; + var nextTan = this.wayPoints [currentFrame + 1].Tangent; + var nextRot = this.wayPoints [currentFrame + 1].Rot; + + + var newPosX = this.HermiteCurve (curPos.X, nextPos.X, curTan.X, nextTan.X, alpha); + var newPosY = this.HermiteCurve (curPos.Y, nextPos.Y, curTan.Y, nextTan.Y, alpha); + var newPosZ = this.HermiteCurve (curPos.Z, nextPos.Z, curTan.Z, nextTan.Z, alpha); + var newQuat = SCNQuaternion.Slerp (curRot, nextRot, alpha); + node.WorldPosition = new SCNVector3 (newPosX, newPosY, newPosZ); + node.WorldOrientation = newQuat; + + // update child rigid bodies to percolate into physics + if (this.Entity is GameObject entity) { + if (entity.PhysicsNode?.PhysicsBody != null) { + entity.PhysicsNode.PhysicsBody.ResetTransform (); + } + } + } + + #endregion + + class Waypoint { + public Waypoint (SCNVector3 pos, SCNVector3 tangent, SCNQuaternion rot, double time) + { + this.Pos = pos; + this.Tangent = tangent; + this.Rot = rot; + this.Time = time; + } + + public SCNVector3 Pos { get; set; } + + public SCNVector3 Tangent { get; set; } + + public SCNQuaternion Rot { get; set; } + + public double Time { get; set; } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ConstrainHierarchyComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ConstrainHierarchyComponent.cs index ab3415d88..27ea3f494 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ConstrainHierarchyComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ConstrainHierarchyComponent.cs @@ -1,147 +1,132 @@ - -namespace XamarinShot.Models.GameplayState -{ - using Foundation; - using GameplayKit; - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - - // goes through hierarchy of node, starting at parent, and checks for constraint_ball nodes - // which it tries to attach to constraint_socket_nodes with the same suffix. - public class ConstrainHierarchyComponent : GKComponent, IPhysicsBehaviorComponent - { - public const string HingeName = "constraint_hinge"; - public const string JointName = "constraint_ball"; - public const string SocketName = "constraint_attach"; - - private const float SearchDist = 0.5f; - - private readonly List<SCNPhysicsBehavior> joints = new List<SCNPhysicsBehavior>(); - - public ConstrainHierarchyComponent() : base() { } - - public ConstrainHierarchyComponent(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public IList<SCNPhysicsBehavior> Behaviors => this.joints; - - /// <summary> - /// go through hierarchy, find all socket nodes + their corresponding join locations - /// </summary> - public void InitBehavior(SCNNode levelRoot, SCNPhysicsWorld world) - { - if (this.Entity is GameObject entity) - { - var root = entity.ObjectRootNode; - var systemRoot = root.ParentWithPrefix("_system"); - if (systemRoot != null) - { - // search for ball constraint with name constraint_ball_ - var ballArray = root.FindAllJoints(ConstrainHierarchyComponent.JointName); - foreach (var ballSocket in ballArray) - { - if (entity.PhysicsNode?.PhysicsBody != null) - { - entity.PhysicsNode.PhysicsBody.ResetTransform(); - var socketOffset = ballSocket.ConvertPositionToNode(SCNVector3.Zero, systemRoot); - - // find in root first - var (closestNode, _) = this.FindAttachNodeNearPoint(systemRoot, systemRoot, socketOffset, SearchDist); - - var attachPhysics = closestNode?.NearestParentGameObject()?.PhysicsNode; - var attachBody = attachPhysics?.PhysicsBody; - if(attachBody != null) - { - attachBody.ResetTransform(); - this.CreateBallJoint(entity.PhysicsNode.PhysicsBody, - ballSocket.ConvertPositionToNode(SCNVector3.Zero, entity.PhysicsNode), - attachBody, - closestNode.ConvertPositionToNode(SCNVector3.Zero, attachPhysics)); - } - } - } - - var hingeArray = root.FindAllJoints(ConstrainHierarchyComponent.HingeName); - foreach (var hingeJoint in hingeArray) - { - if (entity.PhysicsNode?.PhysicsBody != null) - { - entity.PhysicsNode.PhysicsBody.ResetTransform(); - var hingeOffset = hingeJoint.ConvertPositionToNode(SCNVector3.Zero, systemRoot); - - // find in root first - var (closestNode, _) = this.FindAttachNodeNearPoint(systemRoot, systemRoot, hingeOffset, SearchDist); - - var attachPhysics = closestNode?.NearestParentGameObject()?.PhysicsNode; - var attachBody = attachPhysics?.PhysicsBody; - if (attachBody != null) - { - attachBody.ResetTransform(); - this.CreateHingeJoint(entity.PhysicsNode.PhysicsBody, - hingeJoint.ConvertVectorToNode(SCNVector3.UnitY, entity.PhysicsNode), - hingeJoint.ConvertPositionToNode(SCNVector3.Zero, entity.PhysicsNode), - attachBody, - hingeJoint.ConvertVectorToNode(SCNVector3.UnitY, attachPhysics), - closestNode.ConvertPositionToNode(SCNVector3.Zero, attachPhysics)); - } - } - } - - foreach(var joint in this.joints) - { - world.AddBehavior(joint); - } - } - } - } - - private void CreateBallJoint(SCNPhysicsBody source, SCNVector3 sourceOffset, SCNPhysicsBody dest, SCNVector3 destOffset) - { - var joint = SCNPhysicsBallSocketJoint.Create(source, sourceOffset, dest, destOffset); - this.joints.Add(joint); - } - - private void CreateHingeJoint(SCNPhysicsBody source, - SCNVector3 sourceAxis, - SCNVector3 sourceAnchor, - SCNPhysicsBody dest, - SCNVector3 destAxis, - SCNVector3 destAnchor) - { - var joint = SCNPhysicsHingeJoint.Create(source, sourceAxis, sourceAnchor, dest, destAxis, destAnchor); - this.joints.Add(joint); - } - - private (SCNNode, float) FindAttachNodeNearPoint(SCNNode system, SCNNode node, SCNVector3 point, float tolerance) - { - var currentTolerance = tolerance; - SCNNode currentClosestNode = null; - - // if this object has a socket node near ball node, then use it - if (!string.IsNullOrEmpty(node.Name) && - node.Name.StartsWith((ConstrainHierarchyComponent.SocketName), StringComparison.Ordinal)) - { - var attachOffset = node.ConvertPositionToNode(SCNVector3.Zero, system); - var distance = (point - attachOffset).Length; - if (distance < currentTolerance) - { - currentTolerance = distance; - currentClosestNode = node; - } - } - - foreach (var child in node.ChildNodes) - { - var (socketNode, distance) = FindAttachNodeNearPoint(system, child, point, currentTolerance); - if (socketNode != null) - { - currentTolerance = distance; - currentClosestNode = socketNode; - } - } - - return (currentClosestNode, currentTolerance); - } - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using Foundation; + using GameplayKit; + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + + // goes through hierarchy of node, starting at parent, and checks for constraint_ball nodes + // which it tries to attach to constraint_socket_nodes with the same suffix. + public class ConstrainHierarchyComponent : GKComponent, IPhysicsBehaviorComponent { + public const string HingeName = "constraint_hinge"; + public const string JointName = "constraint_ball"; + public const string SocketName = "constraint_attach"; + + private const float SearchDist = 0.5f; + + private readonly List<SCNPhysicsBehavior> joints = new List<SCNPhysicsBehavior> (); + + public ConstrainHierarchyComponent () : base () { } + + public ConstrainHierarchyComponent (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public IList<SCNPhysicsBehavior> Behaviors => this.joints; + + /// <summary> + /// go through hierarchy, find all socket nodes + their corresponding join locations + /// </summary> + public void InitBehavior (SCNNode levelRoot, SCNPhysicsWorld world) + { + if (this.Entity is GameObject entity) { + var root = entity.ObjectRootNode; + var systemRoot = root.ParentWithPrefix ("_system"); + if (systemRoot != null) { + // search for ball constraint with name constraint_ball_ + var ballArray = root.FindAllJoints (ConstrainHierarchyComponent.JointName); + foreach (var ballSocket in ballArray) { + if (entity.PhysicsNode?.PhysicsBody != null) { + entity.PhysicsNode.PhysicsBody.ResetTransform (); + var socketOffset = ballSocket.ConvertPositionToNode (SCNVector3.Zero, systemRoot); + + // find in root first + var (closestNode, _) = this.FindAttachNodeNearPoint (systemRoot, systemRoot, socketOffset, SearchDist); + + var attachPhysics = closestNode?.NearestParentGameObject ()?.PhysicsNode; + var attachBody = attachPhysics?.PhysicsBody; + if (attachBody != null) { + attachBody.ResetTransform (); + this.CreateBallJoint (entity.PhysicsNode.PhysicsBody, + ballSocket.ConvertPositionToNode (SCNVector3.Zero, entity.PhysicsNode), + attachBody, + closestNode.ConvertPositionToNode (SCNVector3.Zero, attachPhysics)); + } + } + } + + var hingeArray = root.FindAllJoints (ConstrainHierarchyComponent.HingeName); + foreach (var hingeJoint in hingeArray) { + if (entity.PhysicsNode?.PhysicsBody != null) { + entity.PhysicsNode.PhysicsBody.ResetTransform (); + var hingeOffset = hingeJoint.ConvertPositionToNode (SCNVector3.Zero, systemRoot); + + // find in root first + var (closestNode, _) = this.FindAttachNodeNearPoint (systemRoot, systemRoot, hingeOffset, SearchDist); + + var attachPhysics = closestNode?.NearestParentGameObject ()?.PhysicsNode; + var attachBody = attachPhysics?.PhysicsBody; + if (attachBody != null) { + attachBody.ResetTransform (); + this.CreateHingeJoint (entity.PhysicsNode.PhysicsBody, + hingeJoint.ConvertVectorToNode (SCNVector3.UnitY, entity.PhysicsNode), + hingeJoint.ConvertPositionToNode (SCNVector3.Zero, entity.PhysicsNode), + attachBody, + hingeJoint.ConvertVectorToNode (SCNVector3.UnitY, attachPhysics), + closestNode.ConvertPositionToNode (SCNVector3.Zero, attachPhysics)); + } + } + } + + foreach (var joint in this.joints) { + world.AddBehavior (joint); + } + } + } + } + + private void CreateBallJoint (SCNPhysicsBody source, SCNVector3 sourceOffset, SCNPhysicsBody dest, SCNVector3 destOffset) + { + var joint = SCNPhysicsBallSocketJoint.Create (source, sourceOffset, dest, destOffset); + this.joints.Add (joint); + } + + private void CreateHingeJoint (SCNPhysicsBody source, + SCNVector3 sourceAxis, + SCNVector3 sourceAnchor, + SCNPhysicsBody dest, + SCNVector3 destAxis, + SCNVector3 destAnchor) + { + var joint = SCNPhysicsHingeJoint.Create (source, sourceAxis, sourceAnchor, dest, destAxis, destAnchor); + this.joints.Add (joint); + } + + private (SCNNode, float) FindAttachNodeNearPoint (SCNNode system, SCNNode node, SCNVector3 point, float tolerance) + { + var currentTolerance = tolerance; + SCNNode currentClosestNode = null; + + // if this object has a socket node near ball node, then use it + if (!string.IsNullOrEmpty (node.Name) && + node.Name.StartsWith ((ConstrainHierarchyComponent.SocketName), StringComparison.Ordinal)) { + var attachOffset = node.ConvertPositionToNode (SCNVector3.Zero, system); + var distance = (point - attachOffset).Length; + if (distance < currentTolerance) { + currentTolerance = distance; + currentClosestNode = node; + } + } + + foreach (var child in node.ChildNodes) { + var (socketNode, distance) = FindAttachNodeNearPoint (system, child, point, currentTolerance); + if (socketNode != null) { + currentTolerance = distance; + currentClosestNode = socketNode; + } + } + + return (currentClosestNode, currentTolerance); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameAudioComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameAudioComponent.cs index 0afc57bad..a3897d237 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameAudioComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameAudioComponent.cs @@ -1,159 +1,136 @@ - -namespace XamarinShot.Models.GameplayState -{ - using System; - using System.Collections.Generic; - using System.Linq; - using Foundation; - using GameplayKit; - using SceneKit; - - public interface IGameAudioComponentDelegate - { - void CollisionEventOccurred(GameAudioComponent component, CollisionEvent collisionEvent); - } - - public class GameAudioComponent : GKComponent, ICollisionHandlerComponent, ITouchableComponent - { - private const double CollisionCooldown = 0.5d; - - private readonly SCNNode node; - - private readonly bool hasCollisionSounds; - - private readonly CollisionAudioSampler.Config configuration; - - private SFXCoordinator sfxCoordinator; - - private CollisionAudioSampler audioSampler; - - private DateTime lastCollisionTime = DateTime.MinValue; - - public GameAudioComponent(SCNNode node, Dictionary<string, object> properties) : base() - { - this.node = node; - this.configuration = CollisionAudioSampler.Config.Create(properties); - - if (properties.TryGetValue("collision", out object collision) && collision is bool) - { - this.hasCollisionSounds = (bool)collision; - } - } - - public GameAudioComponent(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public IGameAudioComponentDelegate Delegate { get; set; } - - public SFXCoordinator SfxCoordinator - { - get - { - return this.sfxCoordinator; - } - - set - { - this.sfxCoordinator = value; - if (this.sfxCoordinator != null && this.hasCollisionSounds && this.configuration != null) - { - this.audioSampler = new CollisionAudioSampler(this.node, this.configuration, this.sfxCoordinator); - } - } - } - - /// <summary> - /// this is what is called if custom collision response is active - /// </summary> - public void DidCollision(GameManager manager, SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) - { - // we don't play sound if this is a triggerVolume - if (!string.IsNullOrEmpty(node.Name) && node.Name.StartsWith("CollisionTrigger", StringComparison.Ordinal)) - { - return; - } - - if (!string.IsNullOrEmpty(otherNode.Name) && otherNode.Name.StartsWith("CollisionTrigger", StringComparison.Ordinal)) - { - return; - } - - var names = new string[] { node.Name, otherNode.Name }; - var withBall = names.Contains("ball"); - var withTable = names.Contains("OcclusionBox"); - - if (node.Name == "OcclusionBox") - { - // don't play any sounds on the table. - return; - } - - var effectiveImpulse = impulse; - if (withTable) - { - // the table does not move, so the calculated impulse is zero (sometimes?). - // Ensure that the ball has an impulse value, so if it happens to be zero, - // fake one based on its velocity - if (impulse == 0f && withBall) - { - if (node.PhysicsBody != null) - { - var v = node.PhysicsBody.Velocity; - var factor = 1.5f; - var velocity = new SCNVector3(v.X, v.Y, v.Z).Length; - effectiveImpulse = factor * velocity; - } - else - { - effectiveImpulse = 0; - } - } - } - - this.PrepareCollisionSound(effectiveImpulse, withBall, withTable); - } - - /// <summary> - /// when this object collides with something else. (runs only on the server) - /// </summary> - public void PrepareCollisionSound(float impulse, bool withBall, bool withTable) - { - if (this.audioSampler != null) - { - var now = DateTime.UtcNow; - CollisionEvent collisionEvent = null; - - if (withBall) - { - // always play a collision sound with the ball - collisionEvent = this.audioSampler.CreateCollisionEvent(impulse, true, withTable); - this.lastCollisionTime = DateTime.UtcNow; - } - else - { - // check cooldown-time. - if (this.lastCollisionTime == DateTime.MinValue || (now - this.lastCollisionTime).TotalSeconds > CollisionCooldown) - { - this.lastCollisionTime = now; - collisionEvent = this.audioSampler.CreateCollisionEvent(impulse, false, withTable); - } - } - - if (collisionEvent != null) - { - this.Delegate?.CollisionEventOccurred(this, collisionEvent); - } - } - } - - /// <summary> - /// Play the collision event on the sampler. (Server and client) - /// </summary> - public void PlayCollisionSound(CollisionEvent collisionEvent) - { - if (this.audioSampler != null) - { - this.audioSampler.Play(collisionEvent); - } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using System; + using System.Collections.Generic; + using System.Linq; + using Foundation; + using GameplayKit; + using SceneKit; + + public interface IGameAudioComponentDelegate { + void CollisionEventOccurred (GameAudioComponent component, CollisionEvent collisionEvent); + } + + public class GameAudioComponent : GKComponent, ICollisionHandlerComponent, ITouchableComponent { + private const double CollisionCooldown = 0.5d; + + private readonly SCNNode node; + + private readonly bool hasCollisionSounds; + + private readonly CollisionAudioSampler.Config configuration; + + private SFXCoordinator sfxCoordinator; + + private CollisionAudioSampler audioSampler; + + private DateTime lastCollisionTime = DateTime.MinValue; + + public GameAudioComponent (SCNNode node, Dictionary<string, object> properties) : base () + { + this.node = node; + this.configuration = CollisionAudioSampler.Config.Create (properties); + + if (properties.TryGetValue ("collision", out object collision) && collision is bool) { + this.hasCollisionSounds = (bool) collision; + } + } + + public GameAudioComponent (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public IGameAudioComponentDelegate Delegate { get; set; } + + public SFXCoordinator SfxCoordinator { + get { + return this.sfxCoordinator; + } + + set { + this.sfxCoordinator = value; + if (this.sfxCoordinator != null && this.hasCollisionSounds && this.configuration != null) { + this.audioSampler = new CollisionAudioSampler (this.node, this.configuration, this.sfxCoordinator); + } + } + } + + /// <summary> + /// this is what is called if custom collision response is active + /// </summary> + public void DidCollision (GameManager manager, SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) + { + // we don't play sound if this is a triggerVolume + if (!string.IsNullOrEmpty (node.Name) && node.Name.StartsWith ("CollisionTrigger", StringComparison.Ordinal)) { + return; + } + + if (!string.IsNullOrEmpty (otherNode.Name) && otherNode.Name.StartsWith ("CollisionTrigger", StringComparison.Ordinal)) { + return; + } + + var names = new string [] { node.Name, otherNode.Name }; + var withBall = names.Contains ("ball"); + var withTable = names.Contains ("OcclusionBox"); + + if (node.Name == "OcclusionBox") { + // don't play any sounds on the table. + return; + } + + var effectiveImpulse = impulse; + if (withTable) { + // the table does not move, so the calculated impulse is zero (sometimes?). + // Ensure that the ball has an impulse value, so if it happens to be zero, + // fake one based on its velocity + if (impulse == 0f && withBall) { + if (node.PhysicsBody != null) { + var v = node.PhysicsBody.Velocity; + var factor = 1.5f; + var velocity = new SCNVector3 (v.X, v.Y, v.Z).Length; + effectiveImpulse = factor * velocity; + } else { + effectiveImpulse = 0; + } + } + } + + this.PrepareCollisionSound (effectiveImpulse, withBall, withTable); + } + + /// <summary> + /// when this object collides with something else. (runs only on the server) + /// </summary> + public void PrepareCollisionSound (float impulse, bool withBall, bool withTable) + { + if (this.audioSampler != null) { + var now = DateTime.UtcNow; + CollisionEvent collisionEvent = null; + + if (withBall) { + // always play a collision sound with the ball + collisionEvent = this.audioSampler.CreateCollisionEvent (impulse, true, withTable); + this.lastCollisionTime = DateTime.UtcNow; + } else { + // check cooldown-time. + if (this.lastCollisionTime == DateTime.MinValue || (now - this.lastCollisionTime).TotalSeconds > CollisionCooldown) { + this.lastCollisionTime = now; + collisionEvent = this.audioSampler.CreateCollisionEvent (impulse, false, withTable); + } + } + + if (collisionEvent != null) { + this.Delegate?.CollisionEventOccurred (this, collisionEvent); + } + } + } + + /// <summary> + /// Play the collision event on the sampler. (Server and client) + /// </summary> + public void PlayCollisionSound (CollisionEvent collisionEvent) + { + if (this.audioSampler != null) { + this.audioSampler.Play (collisionEvent); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameObjectComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameObjectComponent.cs index e6a6e5b95..c15cd9c9c 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameObjectComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GameObjectComponent.cs @@ -1,42 +1,38 @@ - -namespace XamarinShot.Models.GameplayState -{ - using SceneKit; - using System.Collections.Generic; - - /// <summary> - /// Components that imply the object can be touched - /// </summary> - public interface ITouchableComponent { } - - /// <summary> - /// Components that indicate the object should exhibit highlight behavior based on camera distance + orientation - /// </summary> - public interface IHighlightableComponent - { - bool IsHighlighted { get; } - - bool ShouldHighlight(Ray camera); - - void DoHighlight(bool show, SFXCoordinator sfxCoordinator); - } - - /// <summary> - /// Components that allow require special handling during collisions - /// </summary> - public interface ICollisionHandlerComponent - { - // node is the node associated with this CollisionHandlerComponent. - void DidCollision(GameManager manager, SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse); - } - - /// <summary> - /// Components that require setup for scenekit's SCNPhysicsBehavior to work - /// </summary> - public interface IPhysicsBehaviorComponent - { - IList<SCNPhysicsBehavior> Behaviors { get; } - - void InitBehavior(SCNNode levelRoot, SCNPhysicsWorld world); - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using SceneKit; + using System.Collections.Generic; + + /// <summary> + /// Components that imply the object can be touched + /// </summary> + public interface ITouchableComponent { } + + /// <summary> + /// Components that indicate the object should exhibit highlight behavior based on camera distance + orientation + /// </summary> + public interface IHighlightableComponent { + bool IsHighlighted { get; } + + bool ShouldHighlight (Ray camera); + + void DoHighlight (bool show, SFXCoordinator sfxCoordinator); + } + + /// <summary> + /// Components that allow require special handling during collisions + /// </summary> + public interface ICollisionHandlerComponent { + // node is the node associated with this CollisionHandlerComponent. + void DidCollision (GameManager manager, SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse); + } + + /// <summary> + /// Components that require setup for scenekit's SCNPhysicsBehavior to work + /// </summary> + public interface IPhysicsBehaviorComponent { + IList<SCNPhysicsBehavior> Behaviors { get; } + + void InitBehavior (SCNNode levelRoot, SCNPhysicsWorld world); + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GamePhysicsSmoothComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GamePhysicsSmoothComponent.cs index 6ecb16dea..285d4896f 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GamePhysicsSmoothComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/GamePhysicsSmoothComponent.cs @@ -1,100 +1,91 @@ - -namespace XamarinShot.Models.GameplayState -{ - using Foundation; - using GameplayKit; - using SceneKit; - using XamarinShot.Utils; - using System; - - public class GamePhysicsSmoothComponent : GKComponent - { - private const float MaxCorrection = 0.5f; - private const float MaxRotation = 0.3f; - - private readonly SCNNode physicsNode; - private SCNNode geometryNode; - private SCNVector3 parentOffPos; - private SCNQuaternion parentOffRot; - private SCNVector3 sourceOffPos = SCNVector3.Zero; - private SCNQuaternion sourceOffRot = new SCNQuaternion(); - - public GamePhysicsSmoothComponent(SCNNode physicsNode, SCNNode geometryNode) : base() - { - this.physicsNode = physicsNode; - this.geometryNode = geometryNode; - - // get initial offset - this.parentOffPos = this.geometryNode.Position; - this.parentOffRot = this.geometryNode.Orientation; - } - - public GamePhysicsSmoothComponent(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - // we can make this call when the physics changes to smooth it - // make sure its called BEFORE the physics value is changed in the rigid body - // it works by separating the actual geometry slightly from the physics to correct for the visual pop when position is changed - private void CorrectPhysics(SCNNode node, SCNVector3 pos, SCNQuaternion rot) - { - // find old value - var oldTransform = this.geometryNode.WorldTransform; - - // change position of object - node.Position = pos; - node.Orientation = rot; - - this.physicsNode.PhysicsBody.ResetTransform(); - - // restore offset - if (node != this.geometryNode) - { - this.geometryNode.WorldTransform = oldTransform; - this.sourceOffPos = this.geometryNode.Position; - this.sourceOffRot = geometryNode.Orientation; - } - else - { - this.sourceOffPos = parentOffPos; - this.sourceOffRot = parentOffRot; - } - - // cap the maximum deltas we allow in rotation and position space - this.UpdateSmooth(1d / 60d); - } - - /// <summary> - /// Inch geometry back to original offset from rigid body - /// </summary> - private void UpdateSmooth(double deltaTime) - { - // allow some motion up to a maximum offset - var posDelta = this.parentOffPos - this.sourceOffPos; - if (posDelta.Length > MaxCorrection) - { - posDelta = MaxCorrection * SCNVector3.Normalize(posDelta); - } - - // lerp pos - var newPos = this.sourceOffPos + posDelta; - this.geometryNode.Position = newPos; - - // cap the max rotation that can show through - var quatDelta = this.parentOffRot.Divide(this.sourceOffRot); - quatDelta.ToAxisAngle(out SCNVector3 _, out float angle); - - if (angle > MaxRotation) - { - this.geometryNode.Orientation = SCNQuaternion.Slerp(this.sourceOffRot, this.parentOffRot, MaxRotation / angle); - } - else - { - this.geometryNode.Orientation = this.parentOffRot; - } - } - - public override void Update(double deltaTimeInSeconds) - { - this.UpdateSmooth(deltaTimeInSeconds); - } - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using Foundation; + using GameplayKit; + using SceneKit; + using XamarinShot.Utils; + using System; + + public class GamePhysicsSmoothComponent : GKComponent { + private const float MaxCorrection = 0.5f; + private const float MaxRotation = 0.3f; + + private readonly SCNNode physicsNode; + private SCNNode geometryNode; + private SCNVector3 parentOffPos; + private SCNQuaternion parentOffRot; + private SCNVector3 sourceOffPos = SCNVector3.Zero; + private SCNQuaternion sourceOffRot = new SCNQuaternion (); + + public GamePhysicsSmoothComponent (SCNNode physicsNode, SCNNode geometryNode) : base () + { + this.physicsNode = physicsNode; + this.geometryNode = geometryNode; + + // get initial offset + this.parentOffPos = this.geometryNode.Position; + this.parentOffRot = this.geometryNode.Orientation; + } + + public GamePhysicsSmoothComponent (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + // we can make this call when the physics changes to smooth it + // make sure its called BEFORE the physics value is changed in the rigid body + // it works by separating the actual geometry slightly from the physics to correct for the visual pop when position is changed + private void CorrectPhysics (SCNNode node, SCNVector3 pos, SCNQuaternion rot) + { + // find old value + var oldTransform = this.geometryNode.WorldTransform; + + // change position of object + node.Position = pos; + node.Orientation = rot; + + this.physicsNode.PhysicsBody.ResetTransform (); + + // restore offset + if (node != this.geometryNode) { + this.geometryNode.WorldTransform = oldTransform; + this.sourceOffPos = this.geometryNode.Position; + this.sourceOffRot = geometryNode.Orientation; + } else { + this.sourceOffPos = parentOffPos; + this.sourceOffRot = parentOffRot; + } + + // cap the maximum deltas we allow in rotation and position space + this.UpdateSmooth (1d / 60d); + } + + /// <summary> + /// Inch geometry back to original offset from rigid body + /// </summary> + private void UpdateSmooth (double deltaTime) + { + // allow some motion up to a maximum offset + var posDelta = this.parentOffPos - this.sourceOffPos; + if (posDelta.Length > MaxCorrection) { + posDelta = MaxCorrection * SCNVector3.Normalize (posDelta); + } + + // lerp pos + var newPos = this.sourceOffPos + posDelta; + this.geometryNode.Position = newPos; + + // cap the max rotation that can show through + var quatDelta = this.parentOffRot.Divide (this.sourceOffRot); + quatDelta.ToAxisAngle (out SCNVector3 _, out float angle); + + if (angle > MaxRotation) { + this.geometryNode.Orientation = SCNQuaternion.Slerp (this.sourceOffRot, this.parentOffRot, MaxRotation / angle); + } else { + this.geometryNode.Orientation = this.parentOffRot; + } + } + + public override void Update (double deltaTimeInSeconds) + { + this.UpdateSmooth (deltaTimeInSeconds); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/RemoveWhenFallenComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/RemoveWhenFallenComponent.cs index 58e3bdcb9..4df840b2c 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/RemoveWhenFallenComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/RemoveWhenFallenComponent.cs @@ -1,36 +1,31 @@ - -namespace XamarinShot.Models.GameplayState -{ - using GameplayKit; - using SceneKit; - /// <summary> - /// Removes nodes from the scene when they fall out of bounds. - /// </summary> - public class RemoveWhenFallenComponent : GKComponent - { - private readonly SCNVector3 MinBounds = new SCNVector3(-80f, -10f, -80f); // -10.0 represents 1.0 meter high table - private readonly SCNVector3 MaxBounds = new SCNVector3(80f, 1000f, 80f); +namespace XamarinShot.Models.GameplayState { + using GameplayKit; + using SceneKit; - public override void Update(double deltaTimeInSeconds) - { - if (GameTime.FrameCount % 6 != 0) - { - if (this.Entity is GameObject gameObject && gameObject?.PhysicsNode != null) - { - // check past min/max bounds - // the border was chosen experimentally to see what feels good - var position = gameObject.PhysicsNode.PresentationNode.WorldPosition; + /// <summary> + /// Removes nodes from the scene when they fall out of bounds. + /// </summary> + public class RemoveWhenFallenComponent : GKComponent { + private readonly SCNVector3 MinBounds = new SCNVector3 (-80f, -10f, -80f); // -10.0 represents 1.0 meter high table + private readonly SCNVector3 MaxBounds = new SCNVector3 (80f, 1000f, 80f); - // this is only checking position, but bounds could be offset or bigger - var shouldRemove = SCNVector3.ComponentMin(position, MinBounds) != MinBounds || - SCNVector3.ComponentMax(position, MaxBounds) != MaxBounds; - if (shouldRemove) - { - gameObject.Disable(); - } - } - } - } - } -} \ No newline at end of file + public override void Update (double deltaTimeInSeconds) + { + if (GameTime.FrameCount % 6 != 0) { + if (this.Entity is GameObject gameObject && gameObject?.PhysicsNode != null) { + // check past min/max bounds + // the border was chosen experimentally to see what feels good + var position = gameObject.PhysicsNode.PresentationNode.WorldPosition; + + // this is only checking position, but bounds could be offset or bigger + var shouldRemove = SCNVector3.ComponentMin (position, MinBounds) != MinBounds || + SCNVector3.ComponentMax (position, MaxBounds) != MaxBounds; + if (shouldRemove) { + gameObject.Disable (); + } + } + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ResetSwitchComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ResetSwitchComponent.cs index 10d22a0b9..5083b4404 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ResetSwitchComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/ResetSwitchComponent.cs @@ -1,125 +1,111 @@ - -namespace XamarinShot.Models.GameplayState -{ - using Foundation; - using GameplayKit; - using SceneKit; - using System; - - public class ResetSwitchComponent : GKComponent, IHighlightableComponent - { - private const float LeverHighlightDistance = 2.5f; - - private readonly SCNVector3 leverHoldScale = new SCNVector3(1.2f, 1.2f, 1.2f); - private SCNNode highlightObj; - private SCNNode mirrorObj; - private SCNNode leverObj; - - public ResetSwitchComponent(GameObject entity, SCNNode lever) : base() - { - this.Base = entity.ObjectRootNode; - this.leverObj = lever; - - // find outline node to mirror highlighting - var highlightNode = entity.ObjectRootNode.FindChildNode("Highlight", true); - var mirrorOutline = highlightNode.FindChildNode("resetSwitch_leverOutline", true); - if (highlightNode != null && mirrorOutline != null) - { - this.highlightObj = highlightNode; - this.mirrorObj = mirrorOutline; - } - } - - public ResetSwitchComponent(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public SCNNode Base { get; } - - /// <summary> - /// set the angle of the lever here - /// </summary> - public float Angle - { - get - { - return this.leverObj.EulerAngles.X; - } - - set - { - this.leverObj.EulerAngles = new SCNVector3(value, - this.leverObj.EulerAngles.Y, - this.leverObj.EulerAngles.Z); - - - // apply to outline component - if (this.mirrorObj != null) - { - this.mirrorObj.EulerAngles = new SCNVector3(value, - this.leverObj.EulerAngles.Y, - this.leverObj.EulerAngles.Z); - } - } - } - - public bool IsHighlighted => this.highlightObj != null && !this.highlightObj.Hidden; - - /// <summary> - /// Convenience function to return which side of center the lever is on, so we can flip the - /// </summary> - public SCNVector3 PullOffset(SCNVector3 cameraOffset) - { - return this.Base.ConvertVectorFromNode(cameraOffset, null); - } - - #region IHighlightableComponent - - public bool ShouldHighlight(Ray camera) - { - var cameraToButtonDistance = (this.leverObj.WorldPosition - camera.Position).Length; - return cameraToButtonDistance <= LeverHighlightDistance; - } - - /// <summary> - /// Enable/disable the highlight on this object - /// </summary> - public void DoHighlight(bool show, SFXCoordinator sfxCoordinator) - { - // turn off - if (!show) - { - this.leverObj.Scale = SCNVector3.One; - - if (this.highlightObj != null) - { - this.highlightObj.Hidden = true; - } - - if (this.mirrorObj != null) - { - this.mirrorObj.Scale = SCNVector3.One; - } - - sfxCoordinator?.PlayLeverHighlight(false); - } - else - { - // turn on - this.leverObj.Scale = this.leverHoldScale; - - if (this.highlightObj != null) - { - this.highlightObj.Hidden = false; - } - - if (this.mirrorObj != null) - { - this.mirrorObj.Scale = this.leverHoldScale; - } - - sfxCoordinator?.PlayLeverHighlight(highlighted: true); - } - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using Foundation; + using GameplayKit; + using SceneKit; + using System; + + public class ResetSwitchComponent : GKComponent, IHighlightableComponent { + private const float LeverHighlightDistance = 2.5f; + + private readonly SCNVector3 leverHoldScale = new SCNVector3 (1.2f, 1.2f, 1.2f); + private SCNNode highlightObj; + private SCNNode mirrorObj; + private SCNNode leverObj; + + public ResetSwitchComponent (GameObject entity, SCNNode lever) : base () + { + this.Base = entity.ObjectRootNode; + this.leverObj = lever; + + // find outline node to mirror highlighting + var highlightNode = entity.ObjectRootNode.FindChildNode ("Highlight", true); + var mirrorOutline = highlightNode.FindChildNode ("resetSwitch_leverOutline", true); + if (highlightNode != null && mirrorOutline != null) { + this.highlightObj = highlightNode; + this.mirrorObj = mirrorOutline; + } + } + + public ResetSwitchComponent (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public SCNNode Base { get; } + + /// <summary> + /// set the angle of the lever here + /// </summary> + public float Angle { + get { + return this.leverObj.EulerAngles.X; + } + + set { + this.leverObj.EulerAngles = new SCNVector3 (value, + this.leverObj.EulerAngles.Y, + this.leverObj.EulerAngles.Z); + + + // apply to outline component + if (this.mirrorObj != null) { + this.mirrorObj.EulerAngles = new SCNVector3 (value, + this.leverObj.EulerAngles.Y, + this.leverObj.EulerAngles.Z); + } + } + } + + public bool IsHighlighted => this.highlightObj != null && !this.highlightObj.Hidden; + + /// <summary> + /// Convenience function to return which side of center the lever is on, so we can flip the + /// </summary> + public SCNVector3 PullOffset (SCNVector3 cameraOffset) + { + return this.Base.ConvertVectorFromNode (cameraOffset, null); + } + + #region IHighlightableComponent + + public bool ShouldHighlight (Ray camera) + { + var cameraToButtonDistance = (this.leverObj.WorldPosition - camera.Position).Length; + return cameraToButtonDistance <= LeverHighlightDistance; + } + + /// <summary> + /// Enable/disable the highlight on this object + /// </summary> + public void DoHighlight (bool show, SFXCoordinator sfxCoordinator) + { + // turn off + if (!show) { + this.leverObj.Scale = SCNVector3.One; + + if (this.highlightObj != null) { + this.highlightObj.Hidden = true; + } + + if (this.mirrorObj != null) { + this.mirrorObj.Scale = SCNVector3.One; + } + + sfxCoordinator?.PlayLeverHighlight (false); + } else { + // turn on + this.leverObj.Scale = this.leverHoldScale; + + if (this.highlightObj != null) { + this.highlightObj.Hidden = false; + } + + if (this.mirrorObj != null) { + this.mirrorObj.Scale = this.leverHoldScale; + } + + sfxCoordinator?.PlayLeverHighlight (highlighted: true); + } + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/SlingshotComponent.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/SlingshotComponent.cs index 49029fcdf..28b33c415 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/SlingshotComponent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Components/SlingshotComponent.cs @@ -1,57 +1,53 @@ - -namespace XamarinShot.Models.GameplayState -{ - using Foundation; - using GameplayKit; - using SceneKit; - using System; - - public class SlingshotComponent : GKComponent - { - private readonly SCNVector3 restPosition; - private readonly SCNNode catapult; - - private SCNVector3 currentPosition; - private SCNVector3 velocity; - private bool physicsMode; - - public SlingshotComponent(SCNNode catapult) : base() - { - this.catapult = catapult; - this.restPosition = catapult.Position; - this.currentPosition = this.restPosition; - this.physicsMode = false; // Started off and gets turned on only if needed - this.velocity = SCNVector3.Zero; - } - - public SlingshotComponent(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public void SetGrabMode(bool state) - { - this.physicsMode = !state; // physics mode is off when grab mode is on - if (this.physicsMode) - { - this.currentPosition = catapult.Position; - } - } - - public override void Update(double deltaTimeInSeconds) - { - if (this.physicsMode) - { - // add force in direction to rest point - var offset = this.restPosition - this.currentPosition; - var force = offset * 1000f - this.velocity * 10f; - - this.velocity += force * (float)deltaTimeInSeconds; - this.currentPosition += this.velocity * (float)deltaTimeInSeconds; - this.catapult.Position = this.currentPosition; - - // bring back to 0 - this.catapult.EulerAngles = new SCNVector3(this.catapult.EulerAngles.X * 0.9f, - this.catapult.EulerAngles.Y, - this.catapult.EulerAngles.Z); - } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models.GameplayState { + using Foundation; + using GameplayKit; + using SceneKit; + using System; + + public class SlingshotComponent : GKComponent { + private readonly SCNVector3 restPosition; + private readonly SCNNode catapult; + + private SCNVector3 currentPosition; + private SCNVector3 velocity; + private bool physicsMode; + + public SlingshotComponent (SCNNode catapult) : base () + { + this.catapult = catapult; + this.restPosition = catapult.Position; + this.currentPosition = this.restPosition; + this.physicsMode = false; // Started off and gets turned on only if needed + this.velocity = SCNVector3.Zero; + } + + public SlingshotComponent (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public void SetGrabMode (bool state) + { + this.physicsMode = !state; // physics mode is off when grab mode is on + if (this.physicsMode) { + this.currentPosition = catapult.Position; + } + } + + public override void Update (double deltaTimeInSeconds) + { + if (this.physicsMode) { + // add force in direction to rest point + var offset = this.restPosition - this.currentPosition; + var force = offset * 1000f - this.velocity * 10f; + + this.velocity += force * (float) deltaTimeInSeconds; + this.currentPosition += this.velocity * (float) deltaTimeInSeconds; + this.catapult.Position = this.currentPosition; + + // bring back to 0 + this.catapult.EulerAngles = new SCNVector3 (this.catapult.EulerAngles.X * 0.9f, + this.catapult.EulerAngles.Y, + this.catapult.EulerAngles.Z); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Flag.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Flag.cs index 547af0ea8..c4398cda4 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Flag.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/Flag.cs @@ -1,500 +1,460 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using Metal; - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - - public class SimulationData - { - public SimulationData(SCNVector3 wind) - { - this.Wind = wind; - } - - public SCNVector3 Wind { get; private set; } - } - - public class ClothData : IDisposable - { - public ClothData(SCNNode clothNode, ClothSimMetalNode meshData) - { - this.ClothNode = clothNode; - this.MeshData = meshData; - } - - ~ClothData() - { - this.Dispose(false); - } - - public SCNNode ClothNode { get; private set; } - - public ClothSimMetalNode MeshData { get; private set; } - - #region IDisposable - - private bool disposed; - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - if(this.ClothNode != null) - { - this.ClothNode.Dispose(); - this.ClothNode = null; - } - - if (this.MeshData != null) - { - this.MeshData.Dispose(); - this.MeshData = null; - } - } - - this.disposed = true; - } - } - - #endregion - } - - public class ClothSimMetalNode : IDisposable - { - public ClothSimMetalNode(IMTLDevice device, uint width, uint height) - { - var vector3Size = System.Runtime.InteropServices.Marshal.SizeOf<OpenTK.NVector3>(); - - var vertices = new List<SCNVector3>(); - var normals = new List<SCNVector3>(); - var uvs = new List<OpenTK.Vector2>(); - var indices = new List<byte>(); - - for (var y = 0; y < height; y++) - { - for (var x = 0; x < width; x++) - { - var p = new SCNVector3(x, 0, y); - vertices.Add(p); - normals.Add(SCNVector3.UnitY); - uvs.Add(new OpenTK.Vector2(p.X / width, p.Z / height)); - } - } - - for (var y = 0; y < (height - 1); y++) - { - for (var x = 0; x < (width - 1); x++) - { - // make 2 triangles from the 4 vertices of a quad - var i0 = (byte)(y * width + x); - var i1 = (byte)(i0 + 1); - var i2 = (byte)(i0 + width); - var i3 = (byte)(i2 + 1); - - // triangle 1 - indices.Add(i0); - indices.Add(i2); - indices.Add(i3); - - // triangle 2 - indices.Add(i0); - indices.Add(i3); - indices.Add(i1); - } - } - - var vertexBuffer1 = device.CreateBuffer(vertices.ToArray(), MTLResourceOptions.CpuCacheModeWriteCombined); - var vertexBuffer2 = device.CreateBuffer((nuint)(vertices.Count * vector3Size), - MTLResourceOptions.CpuCacheModeWriteCombined); - - var vertexSource = SCNGeometrySource.FromMetalBuffer(vertexBuffer1, - MTLVertexFormat.Float3, - SCNGeometrySourceSemantics.Vertex, - vertices.Count, - 0, - vector3Size); - - - var normalBuffer = device.CreateBuffer(normals.ToArray(), MTLResourceOptions.CpuCacheModeWriteCombined); - var normalWorkBuffer = device.CreateBuffer((nuint)(normals.Count * vector3Size), - MTLResourceOptions.CpuCacheModeWriteCombined); - - var normalSource = SCNGeometrySource.FromMetalBuffer(normalBuffer, - MTLVertexFormat.Float3, - SCNGeometrySourceSemantics.Normal, - normals.Count, - 0, - vector3Size); - - - var uvBuffer = device.CreateBuffer(uvs.ToArray(), MTLResourceOptions.CpuCacheModeWriteCombined); - - var uvSource = SCNGeometrySource.FromMetalBuffer(uvBuffer, - MTLVertexFormat.Float2, - SCNGeometrySourceSemantics.Texcoord, - uvs.Count, - 0, - OpenTK.Vector2.SizeInBytes); - - var data = NSData.FromArray(indices.ToArray()); - var indexElement = SCNGeometryElement.FromData(data, SCNGeometryPrimitiveType.Triangles, 1178, 4); - var geometry = SCNGeometry.Create(new SCNGeometrySource[] { vertexSource, normalSource, uvSource }, - new SCNGeometryElement[] { indexElement }); - - // velocity buffers - var velocityBuffer1 = device.CreateBuffer((nuint)(vertices.Count * vector3Size), - MTLResourceOptions.CpuCacheModeWriteCombined); - - var velocityBuffer2 = device.CreateBuffer((nuint)(vertices.Count * vector3Size), - MTLResourceOptions.CpuCacheModeWriteCombined); - - this.Geometry = geometry; - this.VertexCount = vertices.Count; - this.Vb1 = vertexBuffer1; - this.Vb2 = vertexBuffer2; - this.NormalBuffer = normalBuffer; - this.NormalWorkBuffer = normalWorkBuffer; - this.VelocityBuffers = new List<IMTLBuffer> { velocityBuffer1, velocityBuffer2 }; - } - - ~ClothSimMetalNode() - { - this.Dispose(false); - } - - public SCNGeometry Geometry { get; private set; } - - public IMTLBuffer Vb1 { get; private set; } - - public IMTLBuffer Vb2 { get; private set; } - - public IMTLBuffer NormalBuffer { get; private set; } - - public IMTLBuffer NormalWorkBuffer { get; private set; } - - public int VertexCount { get; private set; } - - public List<IMTLBuffer> VelocityBuffers { get; } = new List<IMTLBuffer>(); - - public int CurrentBufferIndex { get; set; } - - #region IDisposable - - private bool disposed; - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - if (this.Geometry != null) - { - this.Geometry.Dispose(); - this.Geometry = null; - } - - if (this.Vb1 != null) - { - this.Vb1.Dispose(); - this.Vb1 = null; - } - - if (this.Vb2 != null) - { - this.Vb2.Dispose(); - this.Vb2 = null; - } - - if (this.NormalBuffer != null) - { - this.NormalBuffer.Dispose(); - this.NormalBuffer = null; - } - - if (this.NormalWorkBuffer != null) - { - this.NormalWorkBuffer.Dispose(); - this.NormalWorkBuffer = null; - } - - foreach (var item in this.VelocityBuffers) - { - item.Dispose(); - } - - this.VelocityBuffers.Clear(); - } - - this.disposed = true; - } - } - - #endregion - } - - /// <summary> - /// Encapsulate the 'Metal stuff' within a single class to handle setup and execution of the compute shaders. - /// </summary> - public class MetalClothSimulator : IDisposable - { - private const uint Width = 32; - private const uint Height = 20; - - private readonly List<ClothData> clothData = new List<ClothData>(); - - private readonly IMTLDevice device; - - private IMTLCommandQueue commandQueue; - private IMTLLibrary defaultLibrary; - private IMTLFunction functionClothSim; - private IMTLFunction functionNormalUpdate; - private IMTLFunction functionNormalSmooth; - private IMTLComputePipelineState pipelineStateClothSim; - private IMTLComputePipelineState pipelineStateNormalUpdate; - private IMTLComputePipelineState pipelineStateNormalSmooth; - - public MetalClothSimulator(IMTLDevice device) - { - this.device = device; - this.commandQueue = this.device.CreateCommandQueue(); - - this.defaultLibrary = this.device.CreateDefaultLibrary(); - this.functionClothSim = this.defaultLibrary.CreateFunction("updateVertex"); - this.functionNormalUpdate = this.defaultLibrary.CreateFunction("updateNormal"); - this.functionNormalSmooth = this.defaultLibrary.CreateFunction("smoothNormal"); - - this.pipelineStateClothSim = this.device.CreateComputePipelineState(this.functionClothSim, out NSError pipelineStateClothSimError); - this.pipelineStateNormalUpdate = this.device.CreateComputePipelineState(this.functionNormalUpdate, out NSError pipelineStateNormalUpdateError); - this.pipelineStateNormalSmooth = this.device.CreateComputePipelineState(this.functionNormalSmooth, out NSError pipelineStateNormalSmoothError); - - if (pipelineStateClothSimError != null || - pipelineStateNormalUpdateError != null || - pipelineStateNormalSmoothError != null) - { - throw new Exception("error"); - } - } - - ~MetalClothSimulator() - { - Dispose(false); - } - - public void CreateFlagSimulationFromNode(SCNNode node) - { - var meshData = new ClothSimMetalNode(this.device, Width, Height); - var clothNode = SCNNode.FromGeometry(meshData.Geometry); - - var flag = node.FindChildNode("flagStaticWave", true); - if (flag != null) - { - var boundingBoxMax = SCNVector3.Zero; - var boundingBoxMin = SCNVector3.Zero; - flag.GetBoundingBox(ref boundingBoxMin, ref boundingBoxMax); - var existingFlagBV = boundingBoxMax - boundingBoxMin; - - var rescaleToMatchSizeMatrix = SCNMatrix4.Scale(existingFlagBV.X / (float)Width); - - var rotation = SCNQuaternion.FromAxisAngle(SCNVector3.UnitX, (float)Math.PI / 2f); - var localTransform = rescaleToMatchSizeMatrix * SCNMatrix4.Rotate(rotation.ToQuaternion()); - - localTransform.Transpose(); - var currentTransform = SCNMatrix4.Transpose(flag.Transform); - var newTransform = currentTransform * localTransform; - - clothNode.Transform = SCNMatrix4.Transpose(newTransform);// flag.Transform * localTransform; - if (clothNode.Geometry != null) - { - clothNode.Geometry.FirstMaterial = flag.Geometry?.FirstMaterial; - if (clothNode.Geometry.FirstMaterial != null) - { - clothNode.Geometry.FirstMaterial.DoubleSided = true; - } - } - - flag.ParentNode.ReplaceChildNode(flag, clothNode); - clothNode.Geometry.SetupPaintColorMask("flag_flagA"); - clothNode.SetPaintColors(); - clothNode.FixNormalMaps(); - - this.clothData.Add(new ClothData(clothNode, meshData)); - } - } - - public void Update(SCNNode node) - { - foreach (var cloth in this.clothData) - { - var wind = new SCNVector3(1.8f, 0f, 0f); - - // The multiplier is to rescale ball to flag model space. - // The correct value should be passed in. - var simData = new SimulationData(wind); - this.Deform(cloth.MeshData, simData); - } - } - - public void Deform(ClothSimMetalNode mesh, SimulationData simData) - { - var w = this.pipelineStateClothSim.ThreadExecutionWidth; - var threadsPerThreadgroup = new MTLSize((nint)w, 1, 1); - - var threadgroupsPerGrid = new MTLSize((mesh.VertexCount + (int)w - 1) / (int)w, 1, 1); - - var clothSimCommandBuffer = this.commandQueue.CommandBuffer(); - var clothSimCommandEncoder = clothSimCommandBuffer?.ComputeCommandEncoder; - if (clothSimCommandEncoder != null) - { - clothSimCommandEncoder.SetComputePipelineState(pipelineStateClothSim); - - clothSimCommandEncoder.SetBuffer(mesh.Vb1, 0, 0); - clothSimCommandEncoder.SetBuffer(mesh.Vb2, 0, 1); - clothSimCommandEncoder.SetBuffer(mesh.VelocityBuffers[mesh.CurrentBufferIndex], 0, 2); - - mesh.CurrentBufferIndex = (mesh.CurrentBufferIndex + 1) % 2; - clothSimCommandEncoder.SetBuffer(mesh.VelocityBuffers[mesh.CurrentBufferIndex], 0, 3); - - //var pointer = System.Runtime.InteropServices.Marshal.GetComInterfaceForObject(simData, typeof(SimulationData)); - //clothSimCommandEncoder?.SetBytes(pointer, (nuint)System.Runtime.InteropServices.Marshal.SizeOf<SimulationData>(), 4); - - clothSimCommandEncoder.DispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup); - - clothSimCommandEncoder.EndEncoding(); - } - - clothSimCommandBuffer?.Commit(); - - // - - var normalComputeCommandBuffer = this.commandQueue.CommandBuffer(); - var normalComputeCommandEncoder = normalComputeCommandBuffer?.ComputeCommandEncoder; - if (normalComputeCommandEncoder != null) - { - normalComputeCommandEncoder.SetComputePipelineState(pipelineStateNormalUpdate); - normalComputeCommandEncoder.SetBuffer(mesh.Vb2, 0, 0); - normalComputeCommandEncoder.SetBuffer(mesh.Vb1, 0, 1); - normalComputeCommandEncoder.SetBuffer(mesh.NormalWorkBuffer, 0, 2); - normalComputeCommandEncoder.DispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup); - - normalComputeCommandEncoder.EndEncoding(); - } - - normalComputeCommandBuffer?.Commit(); - - // - - var normalSmoothComputeCommandBuffer = this.commandQueue.CommandBuffer(); - var normalSmoothComputeCommandEncoder = normalSmoothComputeCommandBuffer?.ComputeCommandEncoder; - if (normalSmoothComputeCommandEncoder != null) - { - normalSmoothComputeCommandEncoder.SetComputePipelineState(pipelineStateNormalSmooth); - normalSmoothComputeCommandEncoder.SetBuffer(mesh.NormalWorkBuffer, 0, 0); - normalSmoothComputeCommandEncoder.SetBuffer(mesh.NormalBuffer, 0, 1); - normalSmoothComputeCommandEncoder.DispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup); - - normalSmoothComputeCommandEncoder.EndEncoding(); - } - - normalSmoothComputeCommandBuffer?.Commit(); - } - - #region IDisposable - - private bool disposed; - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (!this.disposed) - { - if (disposing) - { - if (this.commandQueue != null) - { - this.commandQueue.Dispose(); - this.commandQueue = null; - } - - if (this.defaultLibrary != null) - { - this.defaultLibrary.Dispose(); - this.defaultLibrary = null; - } - - if (this.functionClothSim != null) - { - this.functionClothSim.Dispose(); - this.functionClothSim = null; - } - - if (this.functionNormalUpdate != null) - { - this.functionNormalUpdate.Dispose(); - this.functionNormalUpdate = null; - } - - if (this.functionNormalSmooth != null) - { - this.functionNormalSmooth.Dispose(); - this.functionNormalSmooth = null; - } - - if (this.pipelineStateClothSim != null) - { - this.pipelineStateClothSim.Dispose(); - this.pipelineStateClothSim = null; - } - - if (this.pipelineStateNormalUpdate != null) - { - this.pipelineStateNormalUpdate.Dispose(); - this.pipelineStateNormalUpdate = null; - } - - if (this.pipelineStateNormalSmooth != null) - { - this.pipelineStateNormalSmooth.Dispose(); - this.pipelineStateNormalSmooth = null; - } - - foreach (var item in this.clothData) - { - item.ClothNode.RemoveFromParentNode(); - item.Dispose(); - } - - this.clothData.Clear(); - } - - this.disposed = true; - } - } - - #endregion - - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using Metal; + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + + public class SimulationData { + public SimulationData (SCNVector3 wind) + { + this.Wind = wind; + } + + public SCNVector3 Wind { get; private set; } + } + + public class ClothData : IDisposable { + public ClothData (SCNNode clothNode, ClothSimMetalNode meshData) + { + this.ClothNode = clothNode; + this.MeshData = meshData; + } + + ~ClothData () + { + this.Dispose (false); + } + + public SCNNode ClothNode { get; private set; } + + public ClothSimMetalNode MeshData { get; private set; } + + #region IDisposable + + private bool disposed; + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + protected virtual void Dispose (bool disposing) + { + if (!this.disposed) { + if (disposing) { + if (this.ClothNode != null) { + this.ClothNode.Dispose (); + this.ClothNode = null; + } + + if (this.MeshData != null) { + this.MeshData.Dispose (); + this.MeshData = null; + } + } + + this.disposed = true; + } + } + + #endregion + } + + public class ClothSimMetalNode : IDisposable { + public ClothSimMetalNode (IMTLDevice device, uint width, uint height) + { + var vector3Size = System.Runtime.InteropServices.Marshal.SizeOf<OpenTK.NVector3> (); + + var vertices = new List<SCNVector3> (); + var normals = new List<SCNVector3> (); + var uvs = new List<OpenTK.Vector2> (); + var indices = new List<byte> (); + + for (var y = 0; y < height; y++) { + for (var x = 0; x < width; x++) { + var p = new SCNVector3 (x, 0, y); + vertices.Add (p); + normals.Add (SCNVector3.UnitY); + uvs.Add (new OpenTK.Vector2 (p.X / width, p.Z / height)); + } + } + + for (var y = 0; y < (height - 1); y++) { + for (var x = 0; x < (width - 1); x++) { + // make 2 triangles from the 4 vertices of a quad + var i0 = (byte) (y * width + x); + var i1 = (byte) (i0 + 1); + var i2 = (byte) (i0 + width); + var i3 = (byte) (i2 + 1); + + // triangle 1 + indices.Add (i0); + indices.Add (i2); + indices.Add (i3); + + // triangle 2 + indices.Add (i0); + indices.Add (i3); + indices.Add (i1); + } + } + + var vertexBuffer1 = device.CreateBuffer (vertices.ToArray (), MTLResourceOptions.CpuCacheModeWriteCombined); + var vertexBuffer2 = device.CreateBuffer ((nuint) (vertices.Count * vector3Size), + MTLResourceOptions.CpuCacheModeWriteCombined); + + var vertexSource = SCNGeometrySource.FromMetalBuffer (vertexBuffer1, + MTLVertexFormat.Float3, + SCNGeometrySourceSemantics.Vertex, + vertices.Count, + 0, + vector3Size); + + + var normalBuffer = device.CreateBuffer (normals.ToArray (), MTLResourceOptions.CpuCacheModeWriteCombined); + var normalWorkBuffer = device.CreateBuffer ((nuint) (normals.Count * vector3Size), + MTLResourceOptions.CpuCacheModeWriteCombined); + + var normalSource = SCNGeometrySource.FromMetalBuffer (normalBuffer, + MTLVertexFormat.Float3, + SCNGeometrySourceSemantics.Normal, + normals.Count, + 0, + vector3Size); + + + var uvBuffer = device.CreateBuffer (uvs.ToArray (), MTLResourceOptions.CpuCacheModeWriteCombined); + + var uvSource = SCNGeometrySource.FromMetalBuffer (uvBuffer, + MTLVertexFormat.Float2, + SCNGeometrySourceSemantics.Texcoord, + uvs.Count, + 0, + OpenTK.Vector2.SizeInBytes); + + var data = NSData.FromArray (indices.ToArray ()); + var indexElement = SCNGeometryElement.FromData (data, SCNGeometryPrimitiveType.Triangles, 1178, 4); + var geometry = SCNGeometry.Create (new SCNGeometrySource [] { vertexSource, normalSource, uvSource }, + new SCNGeometryElement [] { indexElement }); + + // velocity buffers + var velocityBuffer1 = device.CreateBuffer ((nuint) (vertices.Count * vector3Size), + MTLResourceOptions.CpuCacheModeWriteCombined); + + var velocityBuffer2 = device.CreateBuffer ((nuint) (vertices.Count * vector3Size), + MTLResourceOptions.CpuCacheModeWriteCombined); + + this.Geometry = geometry; + this.VertexCount = vertices.Count; + this.Vb1 = vertexBuffer1; + this.Vb2 = vertexBuffer2; + this.NormalBuffer = normalBuffer; + this.NormalWorkBuffer = normalWorkBuffer; + this.VelocityBuffers = new List<IMTLBuffer> { velocityBuffer1, velocityBuffer2 }; + } + + ~ClothSimMetalNode () + { + this.Dispose (false); + } + + public SCNGeometry Geometry { get; private set; } + + public IMTLBuffer Vb1 { get; private set; } + + public IMTLBuffer Vb2 { get; private set; } + + public IMTLBuffer NormalBuffer { get; private set; } + + public IMTLBuffer NormalWorkBuffer { get; private set; } + + public int VertexCount { get; private set; } + + public List<IMTLBuffer> VelocityBuffers { get; } = new List<IMTLBuffer> (); + + public int CurrentBufferIndex { get; set; } + + #region IDisposable + + private bool disposed; + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + protected virtual void Dispose (bool disposing) + { + if (!this.disposed) { + if (disposing) { + if (this.Geometry != null) { + this.Geometry.Dispose (); + this.Geometry = null; + } + + if (this.Vb1 != null) { + this.Vb1.Dispose (); + this.Vb1 = null; + } + + if (this.Vb2 != null) { + this.Vb2.Dispose (); + this.Vb2 = null; + } + + if (this.NormalBuffer != null) { + this.NormalBuffer.Dispose (); + this.NormalBuffer = null; + } + + if (this.NormalWorkBuffer != null) { + this.NormalWorkBuffer.Dispose (); + this.NormalWorkBuffer = null; + } + + foreach (var item in this.VelocityBuffers) { + item.Dispose (); + } + + this.VelocityBuffers.Clear (); + } + + this.disposed = true; + } + } + + #endregion + } + + /// <summary> + /// Encapsulate the 'Metal stuff' within a single class to handle setup and execution of the compute shaders. + /// </summary> + public class MetalClothSimulator : IDisposable { + private const uint Width = 32; + private const uint Height = 20; + + private readonly List<ClothData> clothData = new List<ClothData> (); + + private readonly IMTLDevice device; + + private IMTLCommandQueue commandQueue; + private IMTLLibrary defaultLibrary; + private IMTLFunction functionClothSim; + private IMTLFunction functionNormalUpdate; + private IMTLFunction functionNormalSmooth; + private IMTLComputePipelineState pipelineStateClothSim; + private IMTLComputePipelineState pipelineStateNormalUpdate; + private IMTLComputePipelineState pipelineStateNormalSmooth; + + public MetalClothSimulator (IMTLDevice device) + { + this.device = device; + this.commandQueue = this.device.CreateCommandQueue (); + + this.defaultLibrary = this.device.CreateDefaultLibrary (); + this.functionClothSim = this.defaultLibrary.CreateFunction ("updateVertex"); + this.functionNormalUpdate = this.defaultLibrary.CreateFunction ("updateNormal"); + this.functionNormalSmooth = this.defaultLibrary.CreateFunction ("smoothNormal"); + + this.pipelineStateClothSim = this.device.CreateComputePipelineState (this.functionClothSim, out NSError pipelineStateClothSimError); + this.pipelineStateNormalUpdate = this.device.CreateComputePipelineState (this.functionNormalUpdate, out NSError pipelineStateNormalUpdateError); + this.pipelineStateNormalSmooth = this.device.CreateComputePipelineState (this.functionNormalSmooth, out NSError pipelineStateNormalSmoothError); + + if (pipelineStateClothSimError != null || + pipelineStateNormalUpdateError != null || + pipelineStateNormalSmoothError != null) { + throw new Exception ("error"); + } + } + + ~MetalClothSimulator () + { + Dispose (false); + } + + public void CreateFlagSimulationFromNode (SCNNode node) + { + var meshData = new ClothSimMetalNode (this.device, Width, Height); + var clothNode = SCNNode.FromGeometry (meshData.Geometry); + + var flag = node.FindChildNode ("flagStaticWave", true); + if (flag != null) { + var boundingBoxMax = SCNVector3.Zero; + var boundingBoxMin = SCNVector3.Zero; + flag.GetBoundingBox (ref boundingBoxMin, ref boundingBoxMax); + var existingFlagBV = boundingBoxMax - boundingBoxMin; + + var rescaleToMatchSizeMatrix = SCNMatrix4.Scale (existingFlagBV.X / (float) Width); + + var rotation = SCNQuaternion.FromAxisAngle (SCNVector3.UnitX, (float) Math.PI / 2f); + var localTransform = rescaleToMatchSizeMatrix * SCNMatrix4.Rotate (rotation.ToQuaternion ()); + + localTransform.Transpose (); + var currentTransform = SCNMatrix4.Transpose (flag.Transform); + var newTransform = currentTransform * localTransform; + + clothNode.Transform = SCNMatrix4.Transpose (newTransform);// flag.Transform * localTransform; + if (clothNode.Geometry != null) { + clothNode.Geometry.FirstMaterial = flag.Geometry?.FirstMaterial; + if (clothNode.Geometry.FirstMaterial != null) { + clothNode.Geometry.FirstMaterial.DoubleSided = true; + } + } + + flag.ParentNode.ReplaceChildNode (flag, clothNode); + clothNode.Geometry.SetupPaintColorMask ("flag_flagA"); + clothNode.SetPaintColors (); + clothNode.FixNormalMaps (); + + this.clothData.Add (new ClothData (clothNode, meshData)); + } + } + + public void Update (SCNNode node) + { + foreach (var cloth in this.clothData) { + var wind = new SCNVector3 (1.8f, 0f, 0f); + + // The multiplier is to rescale ball to flag model space. + // The correct value should be passed in. + var simData = new SimulationData (wind); + this.Deform (cloth.MeshData, simData); + } + } + + public void Deform (ClothSimMetalNode mesh, SimulationData simData) + { + var w = this.pipelineStateClothSim.ThreadExecutionWidth; + var threadsPerThreadgroup = new MTLSize ((nint) w, 1, 1); + + var threadgroupsPerGrid = new MTLSize ((mesh.VertexCount + (int) w - 1) / (int) w, 1, 1); + + var clothSimCommandBuffer = this.commandQueue.CommandBuffer (); + var clothSimCommandEncoder = clothSimCommandBuffer?.ComputeCommandEncoder; + if (clothSimCommandEncoder != null) { + clothSimCommandEncoder.SetComputePipelineState (pipelineStateClothSim); + + clothSimCommandEncoder.SetBuffer (mesh.Vb1, 0, 0); + clothSimCommandEncoder.SetBuffer (mesh.Vb2, 0, 1); + clothSimCommandEncoder.SetBuffer (mesh.VelocityBuffers [mesh.CurrentBufferIndex], 0, 2); + + mesh.CurrentBufferIndex = (mesh.CurrentBufferIndex + 1) % 2; + clothSimCommandEncoder.SetBuffer (mesh.VelocityBuffers [mesh.CurrentBufferIndex], 0, 3); + + //var pointer = System.Runtime.InteropServices.Marshal.GetComInterfaceForObject(simData, typeof(SimulationData)); + //clothSimCommandEncoder?.SetBytes(pointer, (nuint)System.Runtime.InteropServices.Marshal.SizeOf<SimulationData>(), 4); + + clothSimCommandEncoder.DispatchThreadgroups (threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup); + + clothSimCommandEncoder.EndEncoding (); + } + + clothSimCommandBuffer?.Commit (); + + // + + var normalComputeCommandBuffer = this.commandQueue.CommandBuffer (); + var normalComputeCommandEncoder = normalComputeCommandBuffer?.ComputeCommandEncoder; + if (normalComputeCommandEncoder != null) { + normalComputeCommandEncoder.SetComputePipelineState (pipelineStateNormalUpdate); + normalComputeCommandEncoder.SetBuffer (mesh.Vb2, 0, 0); + normalComputeCommandEncoder.SetBuffer (mesh.Vb1, 0, 1); + normalComputeCommandEncoder.SetBuffer (mesh.NormalWorkBuffer, 0, 2); + normalComputeCommandEncoder.DispatchThreadgroups (threadgroupsPerGrid, threadsPerThreadgroup); + + normalComputeCommandEncoder.EndEncoding (); + } + + normalComputeCommandBuffer?.Commit (); + + // + + var normalSmoothComputeCommandBuffer = this.commandQueue.CommandBuffer (); + var normalSmoothComputeCommandEncoder = normalSmoothComputeCommandBuffer?.ComputeCommandEncoder; + if (normalSmoothComputeCommandEncoder != null) { + normalSmoothComputeCommandEncoder.SetComputePipelineState (pipelineStateNormalSmooth); + normalSmoothComputeCommandEncoder.SetBuffer (mesh.NormalWorkBuffer, 0, 0); + normalSmoothComputeCommandEncoder.SetBuffer (mesh.NormalBuffer, 0, 1); + normalSmoothComputeCommandEncoder.DispatchThreadgroups (threadgroupsPerGrid, threadsPerThreadgroup); + + normalSmoothComputeCommandEncoder.EndEncoding (); + } + + normalSmoothComputeCommandBuffer?.Commit (); + } + + #region IDisposable + + private bool disposed; + + public void Dispose () + { + Dispose (true); + GC.SuppressFinalize (this); + } + + protected virtual void Dispose (bool disposing) + { + if (!this.disposed) { + if (disposing) { + if (this.commandQueue != null) { + this.commandQueue.Dispose (); + this.commandQueue = null; + } + + if (this.defaultLibrary != null) { + this.defaultLibrary.Dispose (); + this.defaultLibrary = null; + } + + if (this.functionClothSim != null) { + this.functionClothSim.Dispose (); + this.functionClothSim = null; + } + + if (this.functionNormalUpdate != null) { + this.functionNormalUpdate.Dispose (); + this.functionNormalUpdate = null; + } + + if (this.functionNormalSmooth != null) { + this.functionNormalSmooth.Dispose (); + this.functionNormalSmooth = null; + } + + if (this.pipelineStateClothSim != null) { + this.pipelineStateClothSim.Dispose (); + this.pipelineStateClothSim = null; + } + + if (this.pipelineStateNormalUpdate != null) { + this.pipelineStateNormalUpdate.Dispose (); + this.pipelineStateNormalUpdate = null; + } + + if (this.pipelineStateNormalSmooth != null) { + this.pipelineStateNormalSmooth.Dispose (); + this.pipelineStateNormalSmooth = null; + } + + foreach (var item in this.clothData) { + item.ClothNode.RemoveFromParentNode (); + item.Dispose (); + } + + this.clothData.Clear (); + } + + this.disposed = true; + } + } + + #endregion + + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameCamera.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameCamera.cs index c1228b04a..63f1517f7 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameCamera.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameCamera.cs @@ -1,70 +1,62 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Utils; - using System; - public class GameCamera - { - private readonly GameCameraProps properties = new GameCameraProps(); - - private readonly SCNNode node; - - public GameCamera(SCNNode node) - { - this.node = node; - } - - public void UpdateProperties() - { - var gameObject = this.node.GetGameObject(); - if (gameObject != null) - { - // use the props data, or else use the defaults in the struct above - var hdr = gameObject.PropBool("hdr"); - if (hdr) - { - properties.Hdr = hdr; - } - - var motionBlur = gameObject.PropDouble("motionBlur"); - if (motionBlur.HasValue) - { - properties.MotionBlur = motionBlur.Value; - } - - var ambientOcclusion = gameObject.PropDouble("ambientOcclusion"); - if (ambientOcclusion.HasValue) - { - properties.AmbientOcclusion = ambientOcclusion.Value; - } - } - } - - public void TransferProperties() - { - if (this.node.Camera != null) - { - // Wide-gamut rendering is enabled by default on supported devices; - // to opt out, set the SCNDisableWideGamut key in your app's Info.plist file. - this.node.Camera.WantsHdr = this.properties.Hdr; - - // Ambient occlusion doesn't work with defaults - this.node.Camera.ScreenSpaceAmbientOcclusionIntensity = (nfloat)this.properties.AmbientOcclusion; - - // Motion blur is not supported when wide-gamut color rendering is enabled. - this.node.Camera.MotionBlurIntensity = (nfloat)this.properties.MotionBlur; - } - } - - class GameCameraProps - { - public bool Hdr { get; set; } - - public double AmbientOcclusion { get; set; } = 0d; - - public double MotionBlur { get; set; } = 0d; - } - } -} \ No newline at end of file +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Utils; + using System; + + public class GameCamera { + private readonly GameCameraProps properties = new GameCameraProps (); + + private readonly SCNNode node; + + public GameCamera (SCNNode node) + { + this.node = node; + } + + public void UpdateProperties () + { + var gameObject = this.node.GetGameObject (); + if (gameObject != null) { + // use the props data, or else use the defaults in the struct above + var hdr = gameObject.PropBool ("hdr"); + if (hdr) { + properties.Hdr = hdr; + } + + var motionBlur = gameObject.PropDouble ("motionBlur"); + if (motionBlur.HasValue) { + properties.MotionBlur = motionBlur.Value; + } + + var ambientOcclusion = gameObject.PropDouble ("ambientOcclusion"); + if (ambientOcclusion.HasValue) { + properties.AmbientOcclusion = ambientOcclusion.Value; + } + } + } + + public void TransferProperties () + { + if (this.node.Camera != null) { + // Wide-gamut rendering is enabled by default on supported devices; + // to opt out, set the SCNDisableWideGamut key in your app's Info.plist file. + this.node.Camera.WantsHdr = this.properties.Hdr; + + // Ambient occlusion doesn't work with defaults + this.node.Camera.ScreenSpaceAmbientOcclusionIntensity = (nfloat) this.properties.AmbientOcclusion; + + // Motion blur is not supported when wide-gamut color rendering is enabled. + this.node.Camera.MotionBlurIntensity = (nfloat) this.properties.MotionBlur; + } + } + + class GameCameraProps { + public bool Hdr { get; set; } + + public double AmbientOcclusion { get; set; } = 0d; + + public double MotionBlur { get; set; } = 0d; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameLight.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameLight.cs index 09ff8eec1..82e1650ee 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameLight.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameLight.cs @@ -1,110 +1,102 @@ - -namespace XamarinShot.Models -{ - using CoreGraphics; - using SceneKit; - using XamarinShot.Utils; - using System; - - public class GameLight - { - private readonly GameLightProperties properties = new GameLightProperties(); - - private readonly SCNNode node; - - public GameLight(SCNNode node) - { - this.node = node; - } - - public void UpdateProperties() - { - var gameObject = this.node.GetGameObject(); - if (gameObject != null) - { - // use the props data, or else use the defaults in the struct above - var shadowMapSize = gameObject.PropFloat2("shadowMapSize"); - if(shadowMapSize.HasValue) - { - this.properties.ShadowMapSize = shadowMapSize.Value; - } - - var angles = gameObject.PropFloat3("angles"); - if (angles.HasValue) - { - var toRadians = (float)Math.PI / 180f; - properties.Angles = angles.Value * toRadians; - } - - var shadowMode = gameObject.PropInt("shadowMode"); - if (shadowMode.HasValue) - { - this.properties.ShadowMode = shadowMode.Value; - } - } - } - - public void TransferProperties() - { - // are euler's set at refeference (ShadowLight) or internal node (LightNode) - var lightNode = this.node.FindChildNode("LightNode", true); - var light = lightNode.Light; - - // As shadow map size is reduced get a softer shadow but more acne - // and bias results in shadow offset. Mostly thin geometry like the boxes - // and the shadow plane have acne. Turn off z-writes on the shadow plane. - - switch (this.properties.ShadowMode) - { - case 0: - // activate special filtering mode with 16 sample fixed pattern - // this slows down the rendering by 2x - light.ShadowRadius = 0f; - light.ShadowSampleCount = 16; - break; - - case 1: - light.ShadowRadius = 3f; // 2.5 - light.ShadowSampleCount = 8; - break; - - case 2: - // as resolution decreases more acne, use bias and cutoff in shadowPlane shaderModifier - light.ShadowRadius = 1f; - light.ShadowSampleCount = 1; - break; - default: - break; - } - - // when true, this reduces acne, but is causing shadow to separate - // not seeing much acne, so turn it off for now - light.ForcesBackFaceCasters = false; - - light.ShadowMapSize = new CGSize(this.properties.ShadowMapSize.X, - this.properties.ShadowMapSize.Y); - - // Can turn on cascades with auto-adjust disabled here, but not in editor. - // Based on shadowDistance where next cascade starts. These are the defaults. - // light.shadowCascadeCount = 2 - // light.shadowCascadeSplittingFactor = 0.15 - - // this is a square volume that is mapped to the shadowMapSize - // may need to adjust this based on the angle of the light and table size - // setting angles won't work until we isolate angles in the level file to a single node - // lightNode.parent.angles = prop.angles - light.OrthographicScale = 15f; - light.ZNear = 1f; - light.ZFar = 30f; - } - - private class GameLightProperties - { - public OpenTK.Vector2 ShadowMapSize { get; set; } = new OpenTK.Vector2(2048f, 4096f); - - public SCNVector3 Angles { get; set; } = new SCNVector3(-90f, 0f, 0f); - - public int ShadowMode { get; set; } = 0; - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using CoreGraphics; + using SceneKit; + using XamarinShot.Utils; + using System; + + public class GameLight { + private readonly GameLightProperties properties = new GameLightProperties (); + + private readonly SCNNode node; + + public GameLight (SCNNode node) + { + this.node = node; + } + + public void UpdateProperties () + { + var gameObject = this.node.GetGameObject (); + if (gameObject != null) { + // use the props data, or else use the defaults in the struct above + var shadowMapSize = gameObject.PropFloat2 ("shadowMapSize"); + if (shadowMapSize.HasValue) { + this.properties.ShadowMapSize = shadowMapSize.Value; + } + + var angles = gameObject.PropFloat3 ("angles"); + if (angles.HasValue) { + var toRadians = (float) Math.PI / 180f; + properties.Angles = angles.Value * toRadians; + } + + var shadowMode = gameObject.PropInt ("shadowMode"); + if (shadowMode.HasValue) { + this.properties.ShadowMode = shadowMode.Value; + } + } + } + + public void TransferProperties () + { + // are euler's set at refeference (ShadowLight) or internal node (LightNode) + var lightNode = this.node.FindChildNode ("LightNode", true); + var light = lightNode.Light; + + // As shadow map size is reduced get a softer shadow but more acne + // and bias results in shadow offset. Mostly thin geometry like the boxes + // and the shadow plane have acne. Turn off z-writes on the shadow plane. + + switch (this.properties.ShadowMode) { + case 0: + // activate special filtering mode with 16 sample fixed pattern + // this slows down the rendering by 2x + light.ShadowRadius = 0f; + light.ShadowSampleCount = 16; + break; + + case 1: + light.ShadowRadius = 3f; // 2.5 + light.ShadowSampleCount = 8; + break; + + case 2: + // as resolution decreases more acne, use bias and cutoff in shadowPlane shaderModifier + light.ShadowRadius = 1f; + light.ShadowSampleCount = 1; + break; + default: + break; + } + + // when true, this reduces acne, but is causing shadow to separate + // not seeing much acne, so turn it off for now + light.ForcesBackFaceCasters = false; + + light.ShadowMapSize = new CGSize (this.properties.ShadowMapSize.X, + this.properties.ShadowMapSize.Y); + + // Can turn on cascades with auto-adjust disabled here, but not in editor. + // Based on shadowDistance where next cascade starts. These are the defaults. + // light.shadowCascadeCount = 2 + // light.shadowCascadeSplittingFactor = 0.15 + + // this is a square volume that is mapped to the shadowMapSize + // may need to adjust this based on the angle of the light and table size + // setting angles won't work until we isolate angles in the level file to a single node + // lightNode.parent.angles = prop.angles + light.OrthographicScale = 15f; + light.ZNear = 1f; + light.ZFar = 30f; + } + + private class GameLightProperties { + public OpenTK.Vector2 ShadowMapSize { get; set; } = new OpenTK.Vector2 (2048f, 4096f); + + public SCNVector3 Angles { get; set; } = new SCNVector3 (-90f, 0f, 0f); + + public int ShadowMode { get; set; } = 0; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameManager.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameManager.cs index 90f9f098a..670215f02 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameManager.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameManager.cs @@ -1,1500 +1,1359 @@ - -namespace XamarinShot.Models -{ - using AVFoundation; - using Foundation; - using SceneKit; - using System; - using System.Collections.Generic; - using System.Linq; - using XamarinShot.Models.Enums; - using XamarinShot.Models.GameplayState; - using XamarinShot.Utils; - - public class GameState - { - public int TeamACatapults { get; set; } = 0; - - public int TeamBCatapults { get; set; } = 0; - - public void Add(Catapult catapult) - { - switch (catapult.Team) - { - case Team.TeamA: - this.TeamACatapults += 1; - break; - case Team.TeamB: - this.TeamBCatapults += 1; - break; - } - } - } - - public interface IGameManagerDelegate - { - void OnReceived(GameManager manager, BoardSetupAction received, Player from); - void OnJoiningPlayer(GameManager manager, Player player); - void OnLeavingPlayer(GameManager manager, Player player); - void OnJoiningHost(GameManager manager, Player host); - void OnLeavingHost(GameManager manager, Player host); - void OnDidStartGame(GameManager manager); - void OnManagerDidWinGame(GameManager manager); - void OnHasNetworkDelay(GameManager manager, bool hasNetworkDelay); - void OnGameStateUpdated(GameManager manager, GameState gameState); - } - - public class GameManager : SCNPhysicsContactDelegate, - INetworkSessionDelegate, - ICatapultDelegate, - IInteractionDelegate, - IProjectileDelegate, - IPhysicsSyncSceneDataDelegate, - IGameObjectPoolDelegate, - IGameAudioComponentDelegate - { - // interactions with the scene must be on the main thread - private readonly SCNScene scene; - private GameLevel level; - private SCNNode levelNode; - - // use this to access the simulation scaled camera - private readonly SCNNode pointOfViewSimulation; - - // these come from ARSCNView currentlys - private readonly SCNNode pointOfView; // can be in sim or render space - - private GameBoard gameBoard; - private GameObject tableBoxObject; - - // should be the inverse of the level's world transform - private SCNMatrix4 renderToSimulationTransform = SCNMatrix4.Identity; - - private readonly IList<GameObject> gameObjects = new List<GameObject>(); // keep track of all of our entities here - private GameCamera gameCamera; - private GameLight gameLight; - - private readonly NetworkSession session; - private readonly SFXCoordinator sfxCoordinator; - private readonly MusicCoordinator musicCoordinator; - private readonly bool useWallClock; - - private readonly NSLock catapultsLock = new NSLock(); - - private readonly List<GameCommand> gameCommands = new List<GameCommand>(); - private readonly NSLock commandsLock = new NSLock(); - - private readonly List<TouchEvent> touchEvents = new List<TouchEvent>(); - private readonly NSLock touchEventsLock = new NSLock(); - - private Dictionary<string, List<GameObject>> categories = new Dictionary<string, List<GameObject>>(); // this object can be used to group like items if their gamedefs include a category - - // Refernces to Metal do not compile for the Simulator - // TODO: - //#if !targetEnvironment(simulator) - //private MetalClothSimulator flagSimulation; - //#endif - - // Physics - private readonly PhysicsSyncSceneData physicsSyncData = new PhysicsSyncSceneData(); - private readonly GameObjectPool gameObjectPool = new GameObjectPool(); - private readonly InteractionManager interactionManager = new InteractionManager(); - private readonly GameObjectManager gameObjectManager = new GameObjectManager(); - - public GameManager(SCNView sceneView, - GameLevel level, - NetworkSession session, - AVAudioEnvironmentNode audioEnvironment, - MusicCoordinator musicCoordinator) : base() - { - - // make our own scene instead of using the incoming one - this.scene = sceneView.Scene; - this.PhysicsWorld = this.scene.PhysicsWorld; - this.PhysicsWorld.Gravity = new SCNVector3(0f, -10f, 0f); - - //if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR) - //{ - //this.flagSimulation = new MetalClothSimulator(sceneView.Device); - //} - - // this is a node, that isn't attached to the ARSCNView - this.pointOfView = sceneView.PointOfView; - this.pointOfViewSimulation = this.pointOfView.Clone(); - - this.level = level; - - this.session = session; - this.musicCoordinator = musicCoordinator; - this.sfxCoordinator = new SFXCoordinator(audioEnvironment); - this.useWallClock = UserDefaults.SynchronizeMusicWithWallClock; - - // init entity system - this.GameDefinitions = GameObject.LoadGameDefs("art.scnassets/data/entities_def"); - - // load the level if it wasn't already pre-loaded - this.level.Load(); - - // start with a copy of the level, never change the originals, since we use original to reset - this.levelNode = this.level.ActiveLevel; - - this.IsNetworked = this.session != null; - this.IsServer = this.session?.IsServer ?? true; // Solo game act like a server - - if (this.session != null) - { - this.session.Delegate = this; - } - - this.PhysicsWorld.ContactDelegate = this; // get notified of collisions - } - - ~GameManager() - { - this.Unload(); - this.Dispose(false); - } - - public IGameManagerDelegate Delegate { get; set; } - - public Player CurrentPlayer { get; private set; } = UserDefaults.Myself; - - public List<Catapult> Catapults { get; private set; } = new List<Catapult>(); - - public SCNPhysicsWorld PhysicsWorld { get; private set; } - - public bool IsNetworked { get; private set; } - - public bool IsServer { get; private set; } - - /// <summary> - /// Don't execute any code from SCNView renderer until this is true - /// </summary> - public bool IsInitialized { get; private set; } - - public SCNMatrix4 RenderToSimulationTransform - { - get - { - return this.renderToSimulationTransform; - } - - set - { - this.renderToSimulationTransform = value; - this.sfxCoordinator.RenderToSimulationTransform = this.renderToSimulationTransform; - } - } - - public void Send(BoardSetupAction boardAction) - { - this.session?.Send(new GAction { BoardSetup = boardAction }); - } - - public void Send(BoardSetupAction boardAction, Player player) - { - this.session?.Send(new GAction { BoardSetup = boardAction }, player); - } - - public void Send(GameActionType gameAction) - { - this.session?.Send(new GAction { GameAction = gameAction }); - } - - #region processing touches - - private CameraInfo lastCameraInfo = new CameraInfo(SCNMatrix4.Identity); - - public void HandleTouch(TouchType type) - { - if (!UserDefaults.Spectator) - { - this.touchEventsLock.Lock(); - this.touchEvents.Add(new TouchEvent(type, this.lastCameraInfo.Ray)); - this.touchEventsLock.Unlock(); - } - } - - public void UpdateCamera(CameraInfo cameraInfo) - { - if (this.gameCamera == null) - { - // need the real render camera in order to set rendering state - var camera = this.pointOfView; - camera.Name = "GameCamera"; - this.gameCamera = new GameCamera(camera); - _ = this.InitGameObject(camera); - - this.gameCamera.UpdateProperties(); - } - - // transfer props to the current camera - this.gameCamera.TransferProperties(); - - this.interactionManager.UpdateAll(cameraInfo); - this.lastCameraInfo = cameraInfo; - } - - #endregion - - #region inbound from network - - private void Process(GameCommand command) - { - if (command.Action.GameAction != null) - { - if (command.Player != null) - { - this.interactionManager.Handle(command.Action.GameAction, command.Player); - } - } - else if (command.Action.BoardSetup != null) - { - if (command.Player != null) - { - this.Delegate?.OnReceived(this, command.Action.BoardSetup, command.Player); - } - } - else if (command.Action.Physics != null) - { - this.physicsSyncData.Receive(command.Action.Physics); - } - else if (command.Action.StartGameMusic != null) - { - // Start music at the correct place. - if (command.Player != null) - { - this.HandleStartGameMusic(command.Action.StartGameMusic, command.Player); - } - } - } - - #endregion - - #region update - - /// <summary> - /// Called from rendering loop once per frame - /// </summary> - public void Update(double timeDelta) - { - this.ProcessCommandQueue(); - this.ProcessTouches(); - this.SyncPhysics(); - - // TODO: - //#if !targetEnvironment(simulator) - //this.flagSimulation.Update(this.levelNode); - //#endif - - this.gameObjectManager.Update(timeDelta); - - var entities = new List<GameObject>(this.gameObjects); - entities.ForEach((entity) => entity.Update(timeDelta)); - } - - private const int MaxCatapults = 6; - - public CoreGraphics.CGRect MainScreenBounds { get; set; } - - /// <summary> - /// Keep track of which catapults we can see as candidates for grabbing/highlighting - /// </summary> - public void UpdateCatapultVisibility(ISCNSceneRenderer renderer, SCNNode camera) - { - this.catapultsLock.Lock(); - if (this.Catapults.Any() && this.Catapults.Count == MaxCatapults) - { - // track which are visible - foreach (var catapult in this.Catapults) - { - // projectile part should be available, otherwise this is not highlightable - var visGeo = catapult.Projectile?.FindNodeWithGeometry(); - if (visGeo == null) - { - catapult.IsVisible = false; - continue; - } - - // use bigger geo when already highlighted to avoid highlight from flipping back and fourth - if (catapult.IsHighlighted && catapult.HighlightObject != null) - { - visGeo = catapult.HighlightObject; - } - - // this is done in scaled space - var isVisible = renderer.IsNodeInsideFrustum(visGeo.FindNodeWithGeometry(), camera); - catapult.IsVisible = isVisible; - - catapult.ProjectedPosition = new SCNVector3(renderer.ProjectPoint(catapult.Base.WorldPosition)); - catapult.ProjectedPosition = new SCNVector3(catapult.ProjectedPosition.X / (float)this.MainScreenBounds.Width, - catapult.ProjectedPosition.Y / (float)this.MainScreenBounds.Height, - catapult.ProjectedPosition.Z); - } - } - - this.catapultsLock.Unlock(); - } - - private void ProcessCommandQueue() - { - // retrieving the command should happen with the lock held, but executing - // it should be outside the lock. - // inner function lets us take advantage of the defer keyword - // for lock management. - - var command = nextCommand(); - while (command != null) - { - this.Process(command); - command = nextCommand(); - } - - GameCommand nextCommand() - { - GameCommand result = null; - this.commandsLock.Lock(); - if (this.gameCommands.Any()) - { - result = this.gameCommands.First(); - this.gameCommands.RemoveAt(0); - } - - this.commandsLock.Unlock(); - return result; - } - } - - private void ProcessTouches() - { - var touch = nextTouch(); - while (touch != null) - { - this.Process(touch); - touch = nextTouch(); - } - - TouchEvent nextTouch() - { - TouchEvent result = null; - - this.touchEventsLock.Lock(); - if (this.touchEvents.Any()) - { - result = this.touchEvents.First(); - this.touchEvents.RemoveAt(0); - } - - this.touchEventsLock.Unlock(); - - return result; - } - } - - private void Process(TouchEvent touch) - { - this.interactionManager.HandleTouch(touch.Type, touch.Camera); - } - - public void QueueAction(GameActionType gameAction) - { - this.commandsLock.Lock(); - this.gameCommands.Add(new GameCommand(this.CurrentPlayer, new GAction { GameAction = gameAction })); - this.commandsLock.Unlock(); - } - - private void SyncPhysics() - { - if (this.IsNetworked && this.physicsSyncData.IsInitialized) - { - if (this.IsServer) - { - if (this.session.IsAnyActivePeers) - { - var physicsData = this.physicsSyncData.GenerateData(); - this.session.Send(new GAction { Physics = physicsData }); - } - } - else - { - this.physicsSyncData.UpdateFromReceivedData(); - } - } - } - - public void PlayWinSound() - { - this.Delegate?.OnManagerDidWinGame(this); - } - - public void StartGameMusic(IInteraction interaction) - { - this.StartGameMusicEverywhere(); - } - - public void StartGameMusic(Player player) - { - // Begin by handling an empty message. Our timestamp will be added and - // sent in ping/pong to estimate latency. - this.HandleStartGameMusic(new StartGameMusicTime(false, new List<double>()), player); - } - - /// <summary> - /// Status for SceneViewController to query and display UI interaction - /// </summary> - public bool CanGrabACatapult(Ray cameraRay) - { - if (this.interactionManager.Interaction(typeof(CatapultInteraction)) is CatapultInteraction catapultInteraction) - { - return catapultInteraction.CanGrabAnyCatapult(cameraRay); - } - else - { - return false; - } - } - - private void DisplayWin() - { - if (this.interactionManager.Interaction(typeof(VictoryInteraction)) is VictoryInteraction victory) - { - victory.ActivateVictory(); - } - else - { - throw new Exception("No Victory Effect"); - } - } - - public bool IsCurrentPlayerGrabbingACatapult() - { - var grabInteraction = this.interactionManager.Interaction(typeof(GrabInteraction)) as GrabInteraction; - return grabInteraction?.GrabbedGrabbable is Catapult; - } - - /// <summary> - /// Configures the node from the level to be placed on the provided board. - /// </summary> - public void AddLevel(SCNNode node, GameBoard gameBoard) - { - this.gameBoard = gameBoard; - - this.level.PlaceLevel(node, this.scene, this.gameBoard.Scale.X); - - // Initialize table box object - this.CreateTableTopOcclusionBox(); - - this.UpdateRenderTransform(); - - if (this.level?.ActiveLevel != null) - { - this.FixLevelsOfDetail(this.level.ActiveLevel); - } - } - - public void FixLevelsOfDetail(SCNNode node) - { - // set screenSpacePercent to 0 for high-poly lod always, - // or to much greater than 1 for low-poly lod always - var screenSpacePercent = 0.15f; - var screenSpaceRadius = SCNNodeExtensions.ComputeScreenSpaceRadius(screenSpacePercent); - - // The lod system doesn't account for camera being scaled - // so do it ourselves. Here we remove the scale. - screenSpaceRadius /= level.LodScale; - - var showLOD = UserDefaults.ShowLOD; - node.FixLevelsOfDetail(screenSpaceRadius, showLOD); - } - - // call this if the level moves from AR changes or user moving/scaling it - private void UpdateRenderTransform() - { - if (this.gameBoard != null) - { - // Scale level to normalized scale (1 unit wide) for rendering - var levelNodeTransform = SimdExtensions.CreateFromScale(this.level.NormalizedScale); - - var worldTransform = this.gameBoard.WorldTransform; - worldTransform.Transpose(); - this.RenderToSimulationTransform = SCNMatrix4.Invert(levelNodeTransform) * SCNMatrix4.Invert(worldTransform); - } - } - - /// <summary> - /// Initializes all the objects and interactions for the game, and prepares to process user input. - /// </summary> - public void Start() - { - // Now we initialize all the game objects and interactions for the game. - - // reset the index that we assign to GameObjects. - // test to make sure no GameObjects are built prior - // also be careful that the server increments the counter for new nodes - GameObject.ResetIndexCounter(); - this.categories = new Dictionary<string, List<GameObject>>(); - - this.InitializeGameObjectPool(); - - this.InitializeLevel(); - this.InitBehaviors(); - - // Initialize interactions that add objects to the level - this.InitializeInteractions(); - - this.physicsSyncData.Delegate = this; - - // Start advertising game - if (this.session != null && this.session.IsServer) - { - this.session.StartAdvertising(); - } - - this.Delegate?.OnDidStartGame(this); - - this.StartGameMusicEverywhere(); - - this.IsInitialized = true; - } - - public void ReleaseLevel() - { - // remove all audio players added to AVAudioEngine. - this.sfxCoordinator.RemoveAllAudioSamplers(); - this.level.Reset(); - } - - private void InitBehaviors() - { - // after everything is setup, add the behaviors if any - foreach (var gameObject in this.gameObjects) - { - // update constraints - foreach (var component in gameObject.Components.Where(component => component is IPhysicsBehaviorComponent)) - { - (component as IPhysicsBehaviorComponent).InitBehavior(this.levelNode, this.PhysicsWorld); - } - } - } - - #endregion - - #region Table Occlusion - - /// <summary> - /// Create an opaque object representing the table used to occlude falling objects - /// </summary> - private void CreateTableTopOcclusionBox() - { - var tableBoxNode = this.scene.RootNode.FindChildNode("OcclusionBox", true); - if(tableBoxNode == null) - { - throw new Exception("Table node not found"); - } - - // make a table object so we can attach audio component to it - this.tableBoxObject = this.InitGameObject(tableBoxNode); - } - - #endregion - - #region Initialize Game Functions - - private string TeamName(SCNNode node) - { - string result = null; - if (!string.IsNullOrEmpty(node.Name)) - { - // set to A or B, don't set blocks to teamAA, AB, AC - if (node.Name == "_teamA" || node.Name == "_teamB") - { - result = node.Name; - } - } - - return result; - } - - /// <summary> - /// Walk all the nodes looking for actual objects. - /// </summary> - private void EnumerateHierarchy(SCNNode node, string teamName = null) - { - // If the node has no name or a name does not contain - // a type identifier, we look at its children. - string identifier = null; - if (!string.IsNullOrEmpty(node.Name) && !string.IsNullOrEmpty(identifier = node.GetTypeIdentifier())) - { - this.Configure(node, node.Name, identifier, teamName); - } - else - { - var newTeamName = this.TeamName(node) ?? teamName; - foreach (var child in node.ChildNodes) - { - this.EnumerateHierarchy(child, newTeamName); - } - } - } - - private void Configure(SCNNode node, string name, string type, string team) - { - // For nodes with types, we create at most one gameObject, configured - // based on the node type. - - switch (type) - { - case "catapult": - // replaces the placeholder node with a working catapult - var catapultNode = Catapult.ReplaceCatapultPlaceholder(node); - - // Create Catapult GameObject - var identifier = this.Catapults.Count; - var catapult = new Catapult(catapultNode, this.sfxCoordinator, identifier, this.GameDefinitions); - this.gameObjects.Add(catapult); - this.SetupAudioComponent(catapult); - - catapultNode.Name = name; - - catapult.Delegate = this; - this.Catapults.Add(catapult); - - catapult.UpdateProperties(); - catapult.AddComponent(new RemoveWhenFallenComponent()); - this.GameState.Add(catapult); - - this.physicsSyncData.AddObject(catapult); - break; - - case "ShadowPlane": - case "OcclusionBox": - // don't add a game object, but don't visit it either - return; - - case "ShadowLight": - if (this.gameLight == null) - { - node.Name = "GameLight"; - var light = this.InitGameObject(node); - this.gameObjects.Add(light); - - this.gameLight = new GameLight(node); - this.gameLight.UpdateProperties(); - } - - this.gameLight?.TransferProperties(); - return; - - default: - // This handles all other objects, including blocks, reset switches, etc. - // All special functionality is defined in entities_def.json file - - // can't removing these throw off the object index - // if not all clients remove these - switch (type) - { - case "cloud": - if (!UserDefaults.ShowClouds) - { - node.RemoveFromParentNode(); - return; - } - break; - - case "flag": - if (!UserDefaults.ShowFlags) - { - node.RemoveFromParentNode(); - return; - } - else - { - //#if !targetEnvironment(simulator) - //this.flagSimulation.CreateFlagSimulationFromNode(node); - //#endif - } - break; - - case "resetSwitch": - if (!UserDefaults.ShowResetLever) - { - node.RemoveFromParentNode(); - return; - } - break; - } - break; - } - - var gameObject = this.InitGameObject(node); - - // hardcoded overrides for physics happens here - if (!gameObject.UsePredefinedPhysics) - { - // Constrain the angularVelocity until first ball fires. - // This is done to stabilize the level. - if (gameObject.PhysicsNode?.PhysicsBody != null) - { - gameObject.PhysicsNode.PhysicsBody.AngularVelocityFactor = SCNVector3.Zero; - } - - if (gameObject.PhysicsNode?.PhysicsBody != null) - { - gameObject.PhysicsNode.PhysicsBody.AngularDamping = 0.03f; - gameObject.PhysicsNode.PhysicsBody.Damping = 0.03f; - gameObject.PhysicsNode.PhysicsBody.Mass = 3; - gameObject.PhysicsNode.PhysicsBody.LinearRestingThreshold = 1f; - gameObject.PhysicsNode.PhysicsBody.AngularRestingThreshold = 1f; - - var collisionBitMask = (CollisionMask)(int)gameObject.PhysicsNode.PhysicsBody.CollisionBitMask; - gameObject.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint)(int)(collisionBitMask | CollisionMask.Ball); - - if (gameObject.Density > 0) - { - gameObject.PhysicsNode.CalculateMassFromDensity(name, gameObject.Density); - } - - gameObject.PhysicsNode.PhysicsBody.ResetTransform(); - if (gameObject.PhysicsNode.PhysicsBody.AllowsResting) - { - gameObject.PhysicsNode.PhysicsBody.SetResting(true); - } - } - - // add to network synchronization code - if (gameObject.PhysicsNode != null) - { - this.physicsSyncData.AddObject(gameObject); - - if (gameObject.IsBlockObject) - { - this.gameObjectManager.AddBlockObject(gameObject); - } - - gameObject.AddComponent(new RemoveWhenFallenComponent()); - } - - if (gameObject.Categorize) - { - if (!this.categories.ContainsKey(gameObject.Category)) - { - this.categories[gameObject.Category] = new List<GameObject>(); - } - - this.categories[gameObject.Category].Add(gameObject); - } - } - } - - /// <summary> - /// Set the world at rest - /// </summary> - public void RestWorld() - { - var objects = new List<GameObject>(this.gameObjects); - foreach(var gameObject in objects) - { - if(gameObject.PhysicsNode?.PhysicsBody != null && - gameObject != this.tableBoxObject && - gameObject.PhysicsNode.PhysicsBody.AllowsResting) - { - gameObject.PhysicsNode.PhysicsBody.SetResting(true); - } - } - } - - private void PostUpdateHierarchy(SCNNode node) - { - if (node.ValueForKey(new NSString("nameRestore")) is NSString nameRestore) - { - node.Name = nameRestore.ToString(); - } - - foreach (var child in node.ChildNodes) - { - this.PostUpdateHierarchy(child); - } - } - - private void InitializeGameObjectPool() - { - this.gameObjectPool.ProjectileDelegate = this; - this.gameObjectPool.CreatePoolObjects(this); - - // GameObjectPool has a fixed number of items which we need to add to physicsSyncData and gameObjectManager - foreach (var projectile in this.gameObjectPool.ProjectilePool) - { - this.physicsSyncData.AddProjectile(projectile); - this.gameObjectManager.AddProjectile(projectile); - this.SetupAudioComponent(projectile); - } - } - - private void SetupAudioComponent(GameObject @object) - { - if (@object.GetComponent(typeof(GameAudioComponent)) is GameAudioComponent audioComponent) - { - this.sfxCoordinator.SetupGameAudioComponent(audioComponent); - audioComponent.Delegate = this; - } - } - - private void InitializeLevel() - { - // enumerateHierarchy is recursive and may find catapults at any level - // putting the lock outside ensures that the win condition won't be evaluated - // on an incomplete set of catapults. - this.catapultsLock.Lock(); - - this.EnumerateHierarchy(this.levelNode); - - // do post init functions here - this.PostUpdateHierarchy(this.levelNode); - - this.catapultsLock.Unlock(); - } - - private void InitializeInteractions() - { - // Grab Interaction - var grabInteraction = new GrabInteraction(this); - this.interactionManager.AddInteraction(grabInteraction); - - // Highlight Interaction - var highlightInteraction = new HighlightInteraction(this); - highlightInteraction.GrabInteraction = grabInteraction; - highlightInteraction.SfxCoordinator = this.sfxCoordinator; - this.interactionManager.AddInteraction(highlightInteraction); - - // Catapult Interaction - var catapultInteraction = new CatapultInteraction(this); - catapultInteraction.GrabInteraction = grabInteraction; - this.interactionManager.AddInteraction(catapultInteraction); - - // Fill Catapult Interaction with catapults - if (!this.Catapults.Any()) - { - throw new Exception("Catapult not initialized"); - } - - foreach (var catapult in this.Catapults) - { - catapultInteraction.AddCatapult(catapult); - } - - // Catapult Disable Interaction - this.interactionManager.AddInteraction(new CatapultDisableInteraction(this)); - - // Vortex - var vortex = new VortexInteraction(this); - vortex.VortexActivationDelegate = catapultInteraction; - vortex.SfxCoordinator = this.sfxCoordinator; - vortex.MusicCoordinator = this.musicCoordinator; - this.interactionManager.AddInteraction(vortex); - - // Lever - var lever = new LeverInteraction(this); - var switches = new List<GameObject>(); - if (this.categories.TryGetValue("reset", out List<GameObject> processedSwitches)) - { - switches = processedSwitches; - } - - lever.Setup(switches, vortex); - lever.SfxCoordinator = this.sfxCoordinator; - this.interactionManager.AddInteraction(lever); - - // Victory - this.interactionManager.AddInteraction(new VictoryInteraction(this)); - } - - #endregion - - #region Physics scaling - - public void CopySimulationCamera() - { - // copy the POV camera to minimize the need to lock, this is right after ARKit updates it in - // the render thread, and before we scale the actual POV camera for rendering - this.pointOfViewSimulation.WorldTransform = this.pointOfView.WorldTransform; - } - - public void ScaleCameraToRender() - { - var worldTransform = this.pointOfView.WorldTransform; - worldTransform.Transpose(); - var newWorldTransform = this.renderToSimulationTransform * worldTransform; - newWorldTransform.Transpose(); - this.pointOfView.WorldTransform = newWorldTransform; - } - - public void ScaleCameraToSimulation() - { - this.pointOfView.WorldTransform = this.pointOfViewSimulation.WorldTransform; - } - - public SCNMatrix4 RenderSpaceTransformToSimulationSpace(SCNMatrix4 transform) - { - return this.renderToSimulationTransform * transform; - } - - private GameObject InitGameObject(SCNNode node) - { - var gameObject = GameObject.Create<GameObject>(node, this.GameDefinitions); - - this.gameObjects.Add(gameObject); - this.SetupAudioComponent(gameObject); - - return gameObject; - } - - /// <summary> - /// After collision we care about is detected, we check for any collision related components and process them - /// </summary> - private void DidCollision(SCNNode nodeA, SCNNode nodeB, SCNVector3 pos, float impulse) - { - // let any collision handling components on nodeA respond to the collision with nodeB - - var entity = nodeA.NearestParentGameObject(); - if (entity != null) - { - foreach (var component in entity.Components.Where(component => component is ICollisionHandlerComponent)) - { - (component as ICollisionHandlerComponent).DidCollision(this, nodeA, nodeB, pos, impulse); - } - } - - // let any collision handling components in nodeB respond to the collision with nodeA - entity = nodeB.NearestParentGameObject(); - if (entity != null) - { - foreach (var component in entity.Components.Where(component => component is ICollisionHandlerComponent)) - { - (component as ICollisionHandlerComponent).DidCollision(this, nodeA, nodeB, pos, impulse); - } - } - - this.interactionManager.DidCollision(nodeA, nodeB, pos, impulse); - } - - public void DidBeginContact(SCNNode nodeA, SCNNode nodeB, SCNVector3 pos, float impulse) - { - this.interactionManager.DidCollision(nodeA, nodeB, pos, impulse); - } - - public void OnDidApplyConstraints(ISCNSceneRenderer renderer) - { - this.gameObjectManager.OnDidApplyConstraints(renderer); - } - - /// <summary> - /// Start the game music on the server device and all connected devices - /// </summary> - private void StartGameMusicEverywhere() - { - if (this.IsServer) - { - // Start music locally: - var timeData = this.StartGameMusicNow(); - this.HandleStartGameMusic(timeData, this.CurrentPlayer); - - // Start the game music on all connected clients: - this.session?.Send(new GAction { StartGameMusic = timeData }); - } - } - - private StartGameMusicTime StartGameMusicNow() - { - var cal = new NSCalendar(NSCalendarType.Gregorian); - var dc = cal.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, new NSDate()); - var reference = cal.DateFromComponents(dc); // chose a reference date of the start of today. - var now = new NSDate().SecondsSinceReferenceDate - reference.SecondsSinceReferenceDate;; - if (this.useWallClock) - { - return new StartGameMusicTime(true, new List<double> { now }); - } - else - { - return new StartGameMusicTime(true, new List<double> { 0d }); - } - } - - private void HandleStartGameMusic(StartGameMusicTime timeData, Player player) - { - if (this.useWallClock) - { - this.HandleStartGameMusicWithWallClock(timeData, player); - } - else - { - this.HandleStartGameMusicWithLatencyEstimate(timeData, player); - } - } - - private void HandleStartGameMusicWithWallClock(StartGameMusicTime timeData, Player player) - { - if (this.session == null) - { - throw new Exception("Need a game session"); - } - - // This synchronization method uses the wall clock of the two devices. It - // relies on them both having a very accurate clock, which really may not be - // the case. - // - // Choose a time reference closer to the present so that milliseconds since - // this reference can be expressed in UInt32. - - var cal = new NSCalendar(NSCalendarType.Gregorian); - var dc = cal.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, new NSDate()); - var reference = cal.DateFromComponents(dc); // chose a reference date of the start of today. - var now = new NSDate().SecondsSinceReferenceDate - reference.SecondsSinceReferenceDate; - - if (timeData.StartNow) - { - if (timeData.Timestamps.Count == 1) - { - var startWallTime = timeData.Timestamps[0]; - var position = now - startWallTime; - this.musicCoordinator.PlayMusic("music_gameplay", position); - } - else - { - throw new Exception("expected to have serverTimestamps.count == 1"); - } - } - else - { - if (this.IsServer) - { - var position = this.musicCoordinator.CurrentMusicTime(); - var newData = new StartGameMusicTime(true, new List<double> { now - position }); - this.session.Send(new GAction { StartGameMusic = newData }, player); - } - } - } - - private void HandleStartGameMusicWithLatencyEstimate(StartGameMusicTime timeData, Player player) - { - if (this.session == null) - { - throw new Exception("Need a game session"); - } - - // This synchronization method uses an echoed message (like ping) to calculate - // the time taken to send a message to the other device and back and make an - // estimate of latency based on the average of a few of these round trips. - - var cal = new NSCalendar(NSCalendarType.Gregorian); - var dc = cal.Components(NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, new NSDate()); - var reference = cal.DateFromComponents(dc); // chose a reference date of the start of today. - var now = new NSDate().SecondsSinceReferenceDate - reference.SecondsSinceReferenceDate; - - if (timeData.StartNow) - { - if (timeData.Timestamps.Count == 1) - { - var position = timeData.Timestamps[0]; - this.musicCoordinator.PlayMusic("music_gameplay", position); - } - else - { - throw new Exception("expected to have serverTimestamps.count == 1"); - } - } - else - { - if (this.IsServer) - { - var numberOfRoundTripsToEstimateLatency = 4; // must be less than 16 to fit in data structure. - // A round trip has a start and an end time, so we want one more than this in the array. - if (timeData.Timestamps.Count < numberOfRoundTripsToEstimateLatency + 1) - { - var timestamps = timeData.Timestamps; - timestamps.Add(now); - var newData = new StartGameMusicTime(false, timestamps); - this.session.Send(new GAction { StartGameMusic = newData }, player); - } - else - { - // Estimate the latency as the time taken for a few messages to go across and back - // divided by the number of ping/pongs and assuming the halfway point. - var count = timeData.Timestamps.Count; - var latencyEstimate = 0.5f * (timeData.Timestamps[count - 1] - timeData.Timestamps[0]) / (count - 1f); - var position = this.musicCoordinator.CurrentMusicTime(); - var newData = new StartGameMusicTime(true, new List<double> { position + latencyEstimate }); - this.session.Send(new GAction { StartGameMusic = newData }, player); - } - } - else - { - // echo the same message back to the server - this.session.Send(new GAction { StartGameMusic = timeData }, player); - } - } - } - - public void UpdateSessionLocation(GameTableLocation location) - { - this.session?.UpdateLocation(location); - } - - #endregion - - #region IGameSessionDelegate - - public void NetworkSessionReceived(NetworkSession session, GameCommand command) - { - this.commandsLock.Lock(); - - // Check if the action received is used to setup the board - // If so, process it and don't wait for the next update cycle to unqueue the event - // The GameManager is paused at that time of joining a game - if (command.Action.BoardSetup != null) - { - this.Process(command); - } - else - { - this.gameCommands.Add(command); - } - - this.commandsLock.Unlock(); - } - - public void NetworkSessionJoining(NetworkSession session, Player player) - { - if (player.Equals(this.session.Host)) - { - this.Delegate?.OnJoiningHost(this, player); - } - else - { - this.Delegate?.OnJoiningPlayer(this, player); - } - } - - public void NetworkSessionLeaving(NetworkSession session, Player player) - { - if (player == this.session.Host) - { - this.Delegate?.OnLeavingHost(this, player); - } - else - { - this.Delegate?.OnLeavingPlayer(this, player); - } - } - - #endregion - - #region ICatapultDelegate - - public GameState GameState { get; private set; } = new GameState(); - - public void DidBreak(Catapult catapult, bool justKnockedout, bool vortex) - { - if (justKnockedout) - { - this.sfxCoordinator.PlayCatapultBreak(catapult, vortex); - } - - this.gameObjectManager.AddBlockObject(catapult); - - this.GameState.TeamACatapults = this.Catapults.Count(c => c.Team == Team.TeamA && !c.Disabled); - this.GameState.TeamBCatapults = this.Catapults.Count(c => c.Team == Team.TeamB && !c.Disabled); - - // Sending new gameState - this.Delegate?.OnGameStateUpdated(this, this.GameState); - } - - public void DidBeginGrab(Catapult catapult) - { - // start haptics and sounds too for each catapult - this.sfxCoordinator.PlayGrabBall(catapult); - } - - public void DidMove(Catapult catapult, float stretchDistance, float stretchRate) - { - // sounds - balloon squeak - // haptics - vibrate with more energy depending on pull - var playHaptic = this.IsCurrentPlayerGrabbingACatapult(); - this.sfxCoordinator.PlayStretch(catapult, stretchDistance, stretchRate, playHaptic); - } - - public void DidLaunch(Catapult catapult, GameVelocity velocity) - { - // sounds - twang of bow or rubber band - // haptics - big launch vibrate - this.sfxCoordinator.StopStretch(catapult); - var playHaptic = this.IsCurrentPlayerGrabbingACatapult(); - this.sfxCoordinator.PlayLaunch(catapult, velocity, playHaptic); - if (!UserDefaults.HasOnboarded && playHaptic) - { - UserDefaults.HasOnboarded = true; - } - } - - #endregion - - #region IInteractionDelegate - - public IProjectileDelegate ProjectileDelegate => this; - - public List<GameObject> AllBlockObjects => this.gameObjectManager.BlockObjects; - - public void RemoveTableBoxNodeFromLevel() - { - this.tableBoxObject?.ObjectRootNode?.RemoveFromParentNode(); - var shadowPlane = this.levelNode.FindChildNode("ShadowPlane", true); - if (shadowPlane != null) - { - shadowPlane.RunAction(SCNAction.FadeOut(0.5)); - } - } - - public void RemoveAllPhysicsBehaviors() - { - this.PhysicsWorld.RemoveAllBehaviors(); - } - - public void AddInteraction(IInteraction interaction) - { - this.interactionManager.AddInteraction(interaction); - } - - public void AddNodeToLevel(SCNNode node) - { - this.levelNode.AddChildNode(node); - } - - public Projectile SpawnProjectile() - { - var projectile = this.gameObjectPool.SpawnProjectile(); - this.physicsSyncData.ReplaceProjectile(projectile); - this.gameObjectManager.ReplaceProjectile(projectile); - // It would be better to use a preallocated audio sampler here if - // loading a new one takes too long. But it appears ok for now... - this.SetupAudioComponent(projectile); - - return projectile; - } - - public Projectile CreateProjectile() - { - return this.gameObjectPool.CreateProjectile(ProjectileType.Cannonball, null); - } - - public int GameObjectPoolCount() - { - return this.gameObjectPool.InitialPoolCount; - } - - public void DispatchActionToServer(GameActionType gameAction) - { - if (this.IsServer) - { - this.QueueAction(gameAction); - } - else - { - this.Send(gameAction); // send to host - } - } - - public void DispatchActionToAll(GameActionType gameAction) - { - this.QueueAction(gameAction); - this.Send(gameAction); - } - - public void ServerDispatchActionToAll(GameActionType gameAction) - { - if (this.IsServer) - { - this.Send(gameAction); - } - } - - public void DispatchToPlayer(GameActionType gameAction, Player player) - { - if (this.CurrentPlayer == player) - { - this.QueueAction(gameAction); - } - else - { - this.session?.Send(new GAction { GameAction = gameAction }, player); - } - } - - #endregion - - #region IProjectileDelegate - - public void DespawnProjectile(Projectile projectile) - { - this.gameObjectPool.DespawnProjectile(projectile); - } - - public void AddParticles(SCNNode particlesNode, SCNVector3 worldPosition) - { - levelNode.AddChildNode(particlesNode); - particlesNode.WorldPosition = worldPosition; - } - - #endregion - - #region PhysicsSyncSceneDataDelegate - - public void HasNetworkDelayStatusChanged(bool hasNetworkDelay) - { - this.Delegate?.OnHasNetworkDelay(this, hasNetworkDelay); - } - - public Projectile SpawnProjectile(int objectIndex) - { - var projectile = this.gameObjectPool.SpawnProjectile(objectIndex); - projectile.Delegate = this; - - this.levelNode.AddChildNode(projectile.ObjectRootNode); - this.gameObjectManager.ReplaceProjectile(projectile); - - return projectile; - } - - public void PlayPhysicsSound(int objectIndex, CollisionEvent soundEvent) - { - // Find the correct GameObject and play the collision sound - foreach (var gameObject in this.gameObjects.Where(gameObject => gameObject.Index == objectIndex)) - { - if (gameObject.GetComponent(typeof(GameAudioComponent)) is GameAudioComponent audioComponent) - { - audioComponent.PlayCollisionSound(soundEvent); - } - - break; - } - } - - #endregion - - #region IGameObjectPoolDelegate - - public Dictionary<string, object> GameDefinitions { get; } = new Dictionary<string, object>(); - - public void OnSpawnedProjectile() - { - // Release all physics contraints - foreach (var block in this.gameObjectManager.BlockObjects) - { - if (block.PhysicsNode?.PhysicsBody != null) - { - block.PhysicsNode.PhysicsBody.AngularVelocityFactor = SCNVector3.One; - } - } - } - - #endregion - - #region IGameAudioComponentDelegate - - public void CollisionEventOccurred(GameAudioComponent component, CollisionEvent collisionEvent) - { - // For the server device, play the sound locally immediately. - if (this.IsServer) - { - component.PlayCollisionSound(collisionEvent); - - // Add to the network sync - if (component.Entity is GameObject gameObject) - { - this.physicsSyncData.AddSound(gameObject.Index, collisionEvent); - } - else - { - throw new Exception("Component is not attached to GameObject"); - } - } - } - - #endregion - - #region SCNPhysicsContactDelegate - - public override void DidEndContact(SCNPhysicsWorld world, SCNPhysicsContact contact) - { - if (contact != null) - { - this.DidCollision(contact.NodeA, contact.NodeB, new SCNVector3(contact.ContactPoint), (float)contact.CollisionImpulse); - } - } - - public override void DidBeginContact(SCNPhysicsWorld world, SCNPhysicsContact contact) - { - if (contact != null) - { - this.DidBeginContact(contact.NodeA, contact.NodeB, new SCNVector3(contact.ContactPoint), (float)contact.CollisionImpulse); - } - } - - #endregion - - #region Destroy - - public void Unload() - { - this.session.Delegate = null; - this.PhysicsWorld.ContactDelegate = null; - this.levelNode.RemoveFromParentNode(); - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - if(disposing) - { - this.Unload(); - this.gameObjects.Clear(); - this.tableBoxObject = null; - - this.session.Delegate = null; - this.session.Dispose(); - this.pointOfViewSimulation.Dispose(); - - this.commandsLock.Dispose(); - this.catapultsLock.Dispose(); - this.touchEventsLock.Dispose(); - - this.physicsSyncData.Delegate = null; - this.gameObjectPool.ProjectileDelegate = null; - this.gameObjectPool.Delegate = null; - this.gameObjectPool.Dispose(); - - //if(this.flagSimulation != null) - //{ - // this.flagSimulation.Dispose(); - // this.flagSimulation = null; - //} - } - } - - #endregion - - /// <summary> - /// Actions coming from the main thread/UI layer - /// </summary> - class TouchEvent - { - public TouchEvent(TouchType type, Ray camera) - { - this.Type = type; - this.Camera = camera; - } - - public TouchType Type { get; set; } - - public Ray Camera { get; set; } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using AVFoundation; + using Foundation; + using SceneKit; + using System; + using System.Collections.Generic; + using System.Linq; + using XamarinShot.Models.Enums; + using XamarinShot.Models.GameplayState; + using XamarinShot.Utils; + + public class GameState { + public int TeamACatapults { get; set; } = 0; + + public int TeamBCatapults { get; set; } = 0; + + public void Add (Catapult catapult) + { + switch (catapult.Team) { + case Team.TeamA: + this.TeamACatapults += 1; + break; + case Team.TeamB: + this.TeamBCatapults += 1; + break; + } + } + } + + public interface IGameManagerDelegate { + void OnReceived (GameManager manager, BoardSetupAction received, Player from); + void OnJoiningPlayer (GameManager manager, Player player); + void OnLeavingPlayer (GameManager manager, Player player); + void OnJoiningHost (GameManager manager, Player host); + void OnLeavingHost (GameManager manager, Player host); + void OnDidStartGame (GameManager manager); + void OnManagerDidWinGame (GameManager manager); + void OnHasNetworkDelay (GameManager manager, bool hasNetworkDelay); + void OnGameStateUpdated (GameManager manager, GameState gameState); + } + + public class GameManager : SCNPhysicsContactDelegate, + INetworkSessionDelegate, + ICatapultDelegate, + IInteractionDelegate, + IProjectileDelegate, + IPhysicsSyncSceneDataDelegate, + IGameObjectPoolDelegate, + IGameAudioComponentDelegate { + // interactions with the scene must be on the main thread + private readonly SCNScene scene; + private GameLevel level; + private SCNNode levelNode; + + // use this to access the simulation scaled camera + private readonly SCNNode pointOfViewSimulation; + + // these come from ARSCNView currentlys + private readonly SCNNode pointOfView; // can be in sim or render space + + private GameBoard gameBoard; + private GameObject tableBoxObject; + + // should be the inverse of the level's world transform + private SCNMatrix4 renderToSimulationTransform = SCNMatrix4.Identity; + + private readonly IList<GameObject> gameObjects = new List<GameObject> (); // keep track of all of our entities here + private GameCamera gameCamera; + private GameLight gameLight; + + private readonly NetworkSession session; + private readonly SFXCoordinator sfxCoordinator; + private readonly MusicCoordinator musicCoordinator; + private readonly bool useWallClock; + + private readonly NSLock catapultsLock = new NSLock (); + + private readonly List<GameCommand> gameCommands = new List<GameCommand> (); + private readonly NSLock commandsLock = new NSLock (); + + private readonly List<TouchEvent> touchEvents = new List<TouchEvent> (); + private readonly NSLock touchEventsLock = new NSLock (); + + private Dictionary<string, List<GameObject>> categories = new Dictionary<string, List<GameObject>> (); // this object can be used to group like items if their gamedefs include a category + + // Refernces to Metal do not compile for the Simulator + // TODO: + //#if !targetEnvironment(simulator) + //private MetalClothSimulator flagSimulation; + //#endif + + // Physics + private readonly PhysicsSyncSceneData physicsSyncData = new PhysicsSyncSceneData (); + private readonly GameObjectPool gameObjectPool = new GameObjectPool (); + private readonly InteractionManager interactionManager = new InteractionManager (); + private readonly GameObjectManager gameObjectManager = new GameObjectManager (); + + public GameManager (SCNView sceneView, + GameLevel level, + NetworkSession session, + AVAudioEnvironmentNode audioEnvironment, + MusicCoordinator musicCoordinator) : base () + { + + // make our own scene instead of using the incoming one + this.scene = sceneView.Scene; + this.PhysicsWorld = this.scene.PhysicsWorld; + this.PhysicsWorld.Gravity = new SCNVector3 (0f, -10f, 0f); + + //if (ObjCRuntime.Runtime.Arch == ObjCRuntime.Arch.SIMULATOR) + //{ + //this.flagSimulation = new MetalClothSimulator(sceneView.Device); + //} + + // this is a node, that isn't attached to the ARSCNView + this.pointOfView = sceneView.PointOfView; + this.pointOfViewSimulation = this.pointOfView.Clone (); + + this.level = level; + + this.session = session; + this.musicCoordinator = musicCoordinator; + this.sfxCoordinator = new SFXCoordinator (audioEnvironment); + this.useWallClock = UserDefaults.SynchronizeMusicWithWallClock; + + // init entity system + this.GameDefinitions = GameObject.LoadGameDefs ("art.scnassets/data/entities_def"); + + // load the level if it wasn't already pre-loaded + this.level.Load (); + + // start with a copy of the level, never change the originals, since we use original to reset + this.levelNode = this.level.ActiveLevel; + + this.IsNetworked = this.session != null; + this.IsServer = this.session?.IsServer ?? true; // Solo game act like a server + + if (this.session != null) { + this.session.Delegate = this; + } + + this.PhysicsWorld.ContactDelegate = this; // get notified of collisions + } + + ~GameManager () + { + this.Unload (); + this.Dispose (false); + } + + public IGameManagerDelegate Delegate { get; set; } + + public Player CurrentPlayer { get; private set; } = UserDefaults.Myself; + + public List<Catapult> Catapults { get; private set; } = new List<Catapult> (); + + public SCNPhysicsWorld PhysicsWorld { get; private set; } + + public bool IsNetworked { get; private set; } + + public bool IsServer { get; private set; } + + /// <summary> + /// Don't execute any code from SCNView renderer until this is true + /// </summary> + public bool IsInitialized { get; private set; } + + public SCNMatrix4 RenderToSimulationTransform { + get { + return this.renderToSimulationTransform; + } + + set { + this.renderToSimulationTransform = value; + this.sfxCoordinator.RenderToSimulationTransform = this.renderToSimulationTransform; + } + } + + public void Send (BoardSetupAction boardAction) + { + this.session?.Send (new GAction { BoardSetup = boardAction }); + } + + public void Send (BoardSetupAction boardAction, Player player) + { + this.session?.Send (new GAction { BoardSetup = boardAction }, player); + } + + public void Send (GameActionType gameAction) + { + this.session?.Send (new GAction { GameAction = gameAction }); + } + + #region processing touches + + private CameraInfo lastCameraInfo = new CameraInfo (SCNMatrix4.Identity); + + public void HandleTouch (TouchType type) + { + if (!UserDefaults.Spectator) { + this.touchEventsLock.Lock (); + this.touchEvents.Add (new TouchEvent (type, this.lastCameraInfo.Ray)); + this.touchEventsLock.Unlock (); + } + } + + public void UpdateCamera (CameraInfo cameraInfo) + { + if (this.gameCamera == null) { + // need the real render camera in order to set rendering state + var camera = this.pointOfView; + camera.Name = "GameCamera"; + this.gameCamera = new GameCamera (camera); + _ = this.InitGameObject (camera); + + this.gameCamera.UpdateProperties (); + } + + // transfer props to the current camera + this.gameCamera.TransferProperties (); + + this.interactionManager.UpdateAll (cameraInfo); + this.lastCameraInfo = cameraInfo; + } + + #endregion + + #region inbound from network + + private void Process (GameCommand command) + { + if (command.Action.GameAction != null) { + if (command.Player != null) { + this.interactionManager.Handle (command.Action.GameAction, command.Player); + } + } else if (command.Action.BoardSetup != null) { + if (command.Player != null) { + this.Delegate?.OnReceived (this, command.Action.BoardSetup, command.Player); + } + } else if (command.Action.Physics != null) { + this.physicsSyncData.Receive (command.Action.Physics); + } else if (command.Action.StartGameMusic != null) { + // Start music at the correct place. + if (command.Player != null) { + this.HandleStartGameMusic (command.Action.StartGameMusic, command.Player); + } + } + } + + #endregion + + #region update + + /// <summary> + /// Called from rendering loop once per frame + /// </summary> + public void Update (double timeDelta) + { + this.ProcessCommandQueue (); + this.ProcessTouches (); + this.SyncPhysics (); + + // TODO: + //#if !targetEnvironment(simulator) + //this.flagSimulation.Update(this.levelNode); + //#endif + + this.gameObjectManager.Update (timeDelta); + + var entities = new List<GameObject> (this.gameObjects); + entities.ForEach ((entity) => entity.Update (timeDelta)); + } + + private const int MaxCatapults = 6; + + public CoreGraphics.CGRect MainScreenBounds { get; set; } + + /// <summary> + /// Keep track of which catapults we can see as candidates for grabbing/highlighting + /// </summary> + public void UpdateCatapultVisibility (ISCNSceneRenderer renderer, SCNNode camera) + { + this.catapultsLock.Lock (); + if (this.Catapults.Any () && this.Catapults.Count == MaxCatapults) { + // track which are visible + foreach (var catapult in this.Catapults) { + // projectile part should be available, otherwise this is not highlightable + var visGeo = catapult.Projectile?.FindNodeWithGeometry (); + if (visGeo == null) { + catapult.IsVisible = false; + continue; + } + + // use bigger geo when already highlighted to avoid highlight from flipping back and fourth + if (catapult.IsHighlighted && catapult.HighlightObject != null) { + visGeo = catapult.HighlightObject; + } + + // this is done in scaled space + var isVisible = renderer.IsNodeInsideFrustum (visGeo.FindNodeWithGeometry (), camera); + catapult.IsVisible = isVisible; + + catapult.ProjectedPosition = new SCNVector3 (renderer.ProjectPoint (catapult.Base.WorldPosition)); + catapult.ProjectedPosition = new SCNVector3 (catapult.ProjectedPosition.X / (float) this.MainScreenBounds.Width, + catapult.ProjectedPosition.Y / (float) this.MainScreenBounds.Height, + catapult.ProjectedPosition.Z); + } + } + + this.catapultsLock.Unlock (); + } + + private void ProcessCommandQueue () + { + // retrieving the command should happen with the lock held, but executing + // it should be outside the lock. + // inner function lets us take advantage of the defer keyword + // for lock management. + + var command = nextCommand (); + while (command != null) { + this.Process (command); + command = nextCommand (); + } + + GameCommand nextCommand () + { + GameCommand result = null; + this.commandsLock.Lock (); + if (this.gameCommands.Any ()) { + result = this.gameCommands.First (); + this.gameCommands.RemoveAt (0); + } + + this.commandsLock.Unlock (); + return result; + } + } + + private void ProcessTouches () + { + var touch = nextTouch (); + while (touch != null) { + this.Process (touch); + touch = nextTouch (); + } + + TouchEvent nextTouch () + { + TouchEvent result = null; + + this.touchEventsLock.Lock (); + if (this.touchEvents.Any ()) { + result = this.touchEvents.First (); + this.touchEvents.RemoveAt (0); + } + + this.touchEventsLock.Unlock (); + + return result; + } + } + + private void Process (TouchEvent touch) + { + this.interactionManager.HandleTouch (touch.Type, touch.Camera); + } + + public void QueueAction (GameActionType gameAction) + { + this.commandsLock.Lock (); + this.gameCommands.Add (new GameCommand (this.CurrentPlayer, new GAction { GameAction = gameAction })); + this.commandsLock.Unlock (); + } + + private void SyncPhysics () + { + if (this.IsNetworked && this.physicsSyncData.IsInitialized) { + if (this.IsServer) { + if (this.session.IsAnyActivePeers) { + var physicsData = this.physicsSyncData.GenerateData (); + this.session.Send (new GAction { Physics = physicsData }); + } + } else { + this.physicsSyncData.UpdateFromReceivedData (); + } + } + } + + public void PlayWinSound () + { + this.Delegate?.OnManagerDidWinGame (this); + } + + public void StartGameMusic (IInteraction interaction) + { + this.StartGameMusicEverywhere (); + } + + public void StartGameMusic (Player player) + { + // Begin by handling an empty message. Our timestamp will be added and + // sent in ping/pong to estimate latency. + this.HandleStartGameMusic (new StartGameMusicTime (false, new List<double> ()), player); + } + + /// <summary> + /// Status for SceneViewController to query and display UI interaction + /// </summary> + public bool CanGrabACatapult (Ray cameraRay) + { + if (this.interactionManager.Interaction (typeof (CatapultInteraction)) is CatapultInteraction catapultInteraction) { + return catapultInteraction.CanGrabAnyCatapult (cameraRay); + } else { + return false; + } + } + + private void DisplayWin () + { + if (this.interactionManager.Interaction (typeof (VictoryInteraction)) is VictoryInteraction victory) { + victory.ActivateVictory (); + } else { + throw new Exception ("No Victory Effect"); + } + } + + public bool IsCurrentPlayerGrabbingACatapult () + { + var grabInteraction = this.interactionManager.Interaction (typeof (GrabInteraction)) as GrabInteraction; + return grabInteraction?.GrabbedGrabbable is Catapult; + } + + /// <summary> + /// Configures the node from the level to be placed on the provided board. + /// </summary> + public void AddLevel (SCNNode node, GameBoard gameBoard) + { + this.gameBoard = gameBoard; + + this.level.PlaceLevel (node, this.scene, this.gameBoard.Scale.X); + + // Initialize table box object + this.CreateTableTopOcclusionBox (); + + this.UpdateRenderTransform (); + + if (this.level?.ActiveLevel != null) { + this.FixLevelsOfDetail (this.level.ActiveLevel); + } + } + + public void FixLevelsOfDetail (SCNNode node) + { + // set screenSpacePercent to 0 for high-poly lod always, + // or to much greater than 1 for low-poly lod always + var screenSpacePercent = 0.15f; + var screenSpaceRadius = SCNNodeExtensions.ComputeScreenSpaceRadius (screenSpacePercent); + + // The lod system doesn't account for camera being scaled + // so do it ourselves. Here we remove the scale. + screenSpaceRadius /= level.LodScale; + + var showLOD = UserDefaults.ShowLOD; + node.FixLevelsOfDetail (screenSpaceRadius, showLOD); + } + + // call this if the level moves from AR changes or user moving/scaling it + private void UpdateRenderTransform () + { + if (this.gameBoard != null) { + // Scale level to normalized scale (1 unit wide) for rendering + var levelNodeTransform = SimdExtensions.CreateFromScale (this.level.NormalizedScale); + + var worldTransform = this.gameBoard.WorldTransform; + worldTransform.Transpose (); + this.RenderToSimulationTransform = SCNMatrix4.Invert (levelNodeTransform) * SCNMatrix4.Invert (worldTransform); + } + } + + /// <summary> + /// Initializes all the objects and interactions for the game, and prepares to process user input. + /// </summary> + public void Start () + { + // Now we initialize all the game objects and interactions for the game. + + // reset the index that we assign to GameObjects. + // test to make sure no GameObjects are built prior + // also be careful that the server increments the counter for new nodes + GameObject.ResetIndexCounter (); + this.categories = new Dictionary<string, List<GameObject>> (); + + this.InitializeGameObjectPool (); + + this.InitializeLevel (); + this.InitBehaviors (); + + // Initialize interactions that add objects to the level + this.InitializeInteractions (); + + this.physicsSyncData.Delegate = this; + + // Start advertising game + if (this.session != null && this.session.IsServer) { + this.session.StartAdvertising (); + } + + this.Delegate?.OnDidStartGame (this); + + this.StartGameMusicEverywhere (); + + this.IsInitialized = true; + } + + public void ReleaseLevel () + { + // remove all audio players added to AVAudioEngine. + this.sfxCoordinator.RemoveAllAudioSamplers (); + this.level.Reset (); + } + + private void InitBehaviors () + { + // after everything is setup, add the behaviors if any + foreach (var gameObject in this.gameObjects) { + // update constraints + foreach (var component in gameObject.Components.Where (component => component is IPhysicsBehaviorComponent)) { + (component as IPhysicsBehaviorComponent).InitBehavior (this.levelNode, this.PhysicsWorld); + } + } + } + + #endregion + + #region Table Occlusion + + /// <summary> + /// Create an opaque object representing the table used to occlude falling objects + /// </summary> + private void CreateTableTopOcclusionBox () + { + var tableBoxNode = this.scene.RootNode.FindChildNode ("OcclusionBox", true); + if (tableBoxNode == null) { + throw new Exception ("Table node not found"); + } + + // make a table object so we can attach audio component to it + this.tableBoxObject = this.InitGameObject (tableBoxNode); + } + + #endregion + + #region Initialize Game Functions + + private string TeamName (SCNNode node) + { + string result = null; + if (!string.IsNullOrEmpty (node.Name)) { + // set to A or B, don't set blocks to teamAA, AB, AC + if (node.Name == "_teamA" || node.Name == "_teamB") { + result = node.Name; + } + } + + return result; + } + + /// <summary> + /// Walk all the nodes looking for actual objects. + /// </summary> + private void EnumerateHierarchy (SCNNode node, string teamName = null) + { + // If the node has no name or a name does not contain + // a type identifier, we look at its children. + string identifier = null; + if (!string.IsNullOrEmpty (node.Name) && !string.IsNullOrEmpty (identifier = node.GetTypeIdentifier ())) { + this.Configure (node, node.Name, identifier, teamName); + } else { + var newTeamName = this.TeamName (node) ?? teamName; + foreach (var child in node.ChildNodes) { + this.EnumerateHierarchy (child, newTeamName); + } + } + } + + private void Configure (SCNNode node, string name, string type, string team) + { + // For nodes with types, we create at most one gameObject, configured + // based on the node type. + + switch (type) { + case "catapult": + // replaces the placeholder node with a working catapult + var catapultNode = Catapult.ReplaceCatapultPlaceholder (node); + + // Create Catapult GameObject + var identifier = this.Catapults.Count; + var catapult = new Catapult (catapultNode, this.sfxCoordinator, identifier, this.GameDefinitions); + this.gameObjects.Add (catapult); + this.SetupAudioComponent (catapult); + + catapultNode.Name = name; + + catapult.Delegate = this; + this.Catapults.Add (catapult); + + catapult.UpdateProperties (); + catapult.AddComponent (new RemoveWhenFallenComponent ()); + this.GameState.Add (catapult); + + this.physicsSyncData.AddObject (catapult); + break; + + case "ShadowPlane": + case "OcclusionBox": + // don't add a game object, but don't visit it either + return; + + case "ShadowLight": + if (this.gameLight == null) { + node.Name = "GameLight"; + var light = this.InitGameObject (node); + this.gameObjects.Add (light); + + this.gameLight = new GameLight (node); + this.gameLight.UpdateProperties (); + } + + this.gameLight?.TransferProperties (); + return; + + default: + // This handles all other objects, including blocks, reset switches, etc. + // All special functionality is defined in entities_def.json file + + // can't removing these throw off the object index + // if not all clients remove these + switch (type) { + case "cloud": + if (!UserDefaults.ShowClouds) { + node.RemoveFromParentNode (); + return; + } + break; + + case "flag": + if (!UserDefaults.ShowFlags) { + node.RemoveFromParentNode (); + return; + } else { + //#if !targetEnvironment(simulator) + //this.flagSimulation.CreateFlagSimulationFromNode(node); + //#endif + } + break; + + case "resetSwitch": + if (!UserDefaults.ShowResetLever) { + node.RemoveFromParentNode (); + return; + } + break; + } + break; + } + + var gameObject = this.InitGameObject (node); + + // hardcoded overrides for physics happens here + if (!gameObject.UsePredefinedPhysics) { + // Constrain the angularVelocity until first ball fires. + // This is done to stabilize the level. + if (gameObject.PhysicsNode?.PhysicsBody != null) { + gameObject.PhysicsNode.PhysicsBody.AngularVelocityFactor = SCNVector3.Zero; + } + + if (gameObject.PhysicsNode?.PhysicsBody != null) { + gameObject.PhysicsNode.PhysicsBody.AngularDamping = 0.03f; + gameObject.PhysicsNode.PhysicsBody.Damping = 0.03f; + gameObject.PhysicsNode.PhysicsBody.Mass = 3; + gameObject.PhysicsNode.PhysicsBody.LinearRestingThreshold = 1f; + gameObject.PhysicsNode.PhysicsBody.AngularRestingThreshold = 1f; + + var collisionBitMask = (CollisionMask) (int) gameObject.PhysicsNode.PhysicsBody.CollisionBitMask; + gameObject.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint) (int) (collisionBitMask | CollisionMask.Ball); + + if (gameObject.Density > 0) { + gameObject.PhysicsNode.CalculateMassFromDensity (name, gameObject.Density); + } + + gameObject.PhysicsNode.PhysicsBody.ResetTransform (); + if (gameObject.PhysicsNode.PhysicsBody.AllowsResting) { + gameObject.PhysicsNode.PhysicsBody.SetResting (true); + } + } + + // add to network synchronization code + if (gameObject.PhysicsNode != null) { + this.physicsSyncData.AddObject (gameObject); + + if (gameObject.IsBlockObject) { + this.gameObjectManager.AddBlockObject (gameObject); + } + + gameObject.AddComponent (new RemoveWhenFallenComponent ()); + } + + if (gameObject.Categorize) { + if (!this.categories.ContainsKey (gameObject.Category)) { + this.categories [gameObject.Category] = new List<GameObject> (); + } + + this.categories [gameObject.Category].Add (gameObject); + } + } + } + + /// <summary> + /// Set the world at rest + /// </summary> + public void RestWorld () + { + var objects = new List<GameObject> (this.gameObjects); + foreach (var gameObject in objects) { + if (gameObject.PhysicsNode?.PhysicsBody != null && + gameObject != this.tableBoxObject && + gameObject.PhysicsNode.PhysicsBody.AllowsResting) { + gameObject.PhysicsNode.PhysicsBody.SetResting (true); + } + } + } + + private void PostUpdateHierarchy (SCNNode node) + { + if (node.ValueForKey (new NSString ("nameRestore")) is NSString nameRestore) { + node.Name = nameRestore.ToString (); + } + + foreach (var child in node.ChildNodes) { + this.PostUpdateHierarchy (child); + } + } + + private void InitializeGameObjectPool () + { + this.gameObjectPool.ProjectileDelegate = this; + this.gameObjectPool.CreatePoolObjects (this); + + // GameObjectPool has a fixed number of items which we need to add to physicsSyncData and gameObjectManager + foreach (var projectile in this.gameObjectPool.ProjectilePool) { + this.physicsSyncData.AddProjectile (projectile); + this.gameObjectManager.AddProjectile (projectile); + this.SetupAudioComponent (projectile); + } + } + + private void SetupAudioComponent (GameObject @object) + { + if (@object.GetComponent (typeof (GameAudioComponent)) is GameAudioComponent audioComponent) { + this.sfxCoordinator.SetupGameAudioComponent (audioComponent); + audioComponent.Delegate = this; + } + } + + private void InitializeLevel () + { + // enumerateHierarchy is recursive and may find catapults at any level + // putting the lock outside ensures that the win condition won't be evaluated + // on an incomplete set of catapults. + this.catapultsLock.Lock (); + + this.EnumerateHierarchy (this.levelNode); + + // do post init functions here + this.PostUpdateHierarchy (this.levelNode); + + this.catapultsLock.Unlock (); + } + + private void InitializeInteractions () + { + // Grab Interaction + var grabInteraction = new GrabInteraction (this); + this.interactionManager.AddInteraction (grabInteraction); + + // Highlight Interaction + var highlightInteraction = new HighlightInteraction (this); + highlightInteraction.GrabInteraction = grabInteraction; + highlightInteraction.SfxCoordinator = this.sfxCoordinator; + this.interactionManager.AddInteraction (highlightInteraction); + + // Catapult Interaction + var catapultInteraction = new CatapultInteraction (this); + catapultInteraction.GrabInteraction = grabInteraction; + this.interactionManager.AddInteraction (catapultInteraction); + + // Fill Catapult Interaction with catapults + if (!this.Catapults.Any ()) { + throw new Exception ("Catapult not initialized"); + } + + foreach (var catapult in this.Catapults) { + catapultInteraction.AddCatapult (catapult); + } + + // Catapult Disable Interaction + this.interactionManager.AddInteraction (new CatapultDisableInteraction (this)); + + // Vortex + var vortex = new VortexInteraction (this); + vortex.VortexActivationDelegate = catapultInteraction; + vortex.SfxCoordinator = this.sfxCoordinator; + vortex.MusicCoordinator = this.musicCoordinator; + this.interactionManager.AddInteraction (vortex); + + // Lever + var lever = new LeverInteraction (this); + var switches = new List<GameObject> (); + if (this.categories.TryGetValue ("reset", out List<GameObject> processedSwitches)) { + switches = processedSwitches; + } + + lever.Setup (switches, vortex); + lever.SfxCoordinator = this.sfxCoordinator; + this.interactionManager.AddInteraction (lever); + + // Victory + this.interactionManager.AddInteraction (new VictoryInteraction (this)); + } + + #endregion + + #region Physics scaling + + public void CopySimulationCamera () + { + // copy the POV camera to minimize the need to lock, this is right after ARKit updates it in + // the render thread, and before we scale the actual POV camera for rendering + this.pointOfViewSimulation.WorldTransform = this.pointOfView.WorldTransform; + } + + public void ScaleCameraToRender () + { + var worldTransform = this.pointOfView.WorldTransform; + worldTransform.Transpose (); + var newWorldTransform = this.renderToSimulationTransform * worldTransform; + newWorldTransform.Transpose (); + this.pointOfView.WorldTransform = newWorldTransform; + } + + public void ScaleCameraToSimulation () + { + this.pointOfView.WorldTransform = this.pointOfViewSimulation.WorldTransform; + } + + public SCNMatrix4 RenderSpaceTransformToSimulationSpace (SCNMatrix4 transform) + { + return this.renderToSimulationTransform * transform; + } + + private GameObject InitGameObject (SCNNode node) + { + var gameObject = GameObject.Create<GameObject> (node, this.GameDefinitions); + + this.gameObjects.Add (gameObject); + this.SetupAudioComponent (gameObject); + + return gameObject; + } + + /// <summary> + /// After collision we care about is detected, we check for any collision related components and process them + /// </summary> + private void DidCollision (SCNNode nodeA, SCNNode nodeB, SCNVector3 pos, float impulse) + { + // let any collision handling components on nodeA respond to the collision with nodeB + + var entity = nodeA.NearestParentGameObject (); + if (entity != null) { + foreach (var component in entity.Components.Where (component => component is ICollisionHandlerComponent)) { + (component as ICollisionHandlerComponent).DidCollision (this, nodeA, nodeB, pos, impulse); + } + } + + // let any collision handling components in nodeB respond to the collision with nodeA + entity = nodeB.NearestParentGameObject (); + if (entity != null) { + foreach (var component in entity.Components.Where (component => component is ICollisionHandlerComponent)) { + (component as ICollisionHandlerComponent).DidCollision (this, nodeA, nodeB, pos, impulse); + } + } + + this.interactionManager.DidCollision (nodeA, nodeB, pos, impulse); + } + + public void DidBeginContact (SCNNode nodeA, SCNNode nodeB, SCNVector3 pos, float impulse) + { + this.interactionManager.DidCollision (nodeA, nodeB, pos, impulse); + } + + public void OnDidApplyConstraints (ISCNSceneRenderer renderer) + { + this.gameObjectManager.OnDidApplyConstraints (renderer); + } + + /// <summary> + /// Start the game music on the server device and all connected devices + /// </summary> + private void StartGameMusicEverywhere () + { + if (this.IsServer) { + // Start music locally: + var timeData = this.StartGameMusicNow (); + this.HandleStartGameMusic (timeData, this.CurrentPlayer); + + // Start the game music on all connected clients: + this.session?.Send (new GAction { StartGameMusic = timeData }); + } + } + + private StartGameMusicTime StartGameMusicNow () + { + var cal = new NSCalendar (NSCalendarType.Gregorian); + var dc = cal.Components (NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, new NSDate ()); + var reference = cal.DateFromComponents (dc); // chose a reference date of the start of today. + var now = new NSDate ().SecondsSinceReferenceDate - reference.SecondsSinceReferenceDate; ; + if (this.useWallClock) { + return new StartGameMusicTime (true, new List<double> { now }); + } else { + return new StartGameMusicTime (true, new List<double> { 0d }); + } + } + + private void HandleStartGameMusic (StartGameMusicTime timeData, Player player) + { + if (this.useWallClock) { + this.HandleStartGameMusicWithWallClock (timeData, player); + } else { + this.HandleStartGameMusicWithLatencyEstimate (timeData, player); + } + } + + private void HandleStartGameMusicWithWallClock (StartGameMusicTime timeData, Player player) + { + if (this.session == null) { + throw new Exception ("Need a game session"); + } + + // This synchronization method uses the wall clock of the two devices. It + // relies on them both having a very accurate clock, which really may not be + // the case. + // + // Choose a time reference closer to the present so that milliseconds since + // this reference can be expressed in UInt32. + + var cal = new NSCalendar (NSCalendarType.Gregorian); + var dc = cal.Components (NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, new NSDate ()); + var reference = cal.DateFromComponents (dc); // chose a reference date of the start of today. + var now = new NSDate ().SecondsSinceReferenceDate - reference.SecondsSinceReferenceDate; + + if (timeData.StartNow) { + if (timeData.Timestamps.Count == 1) { + var startWallTime = timeData.Timestamps [0]; + var position = now - startWallTime; + this.musicCoordinator.PlayMusic ("music_gameplay", position); + } else { + throw new Exception ("expected to have serverTimestamps.count == 1"); + } + } else { + if (this.IsServer) { + var position = this.musicCoordinator.CurrentMusicTime (); + var newData = new StartGameMusicTime (true, new List<double> { now - position }); + this.session.Send (new GAction { StartGameMusic = newData }, player); + } + } + } + + private void HandleStartGameMusicWithLatencyEstimate (StartGameMusicTime timeData, Player player) + { + if (this.session == null) { + throw new Exception ("Need a game session"); + } + + // This synchronization method uses an echoed message (like ping) to calculate + // the time taken to send a message to the other device and back and make an + // estimate of latency based on the average of a few of these round trips. + + var cal = new NSCalendar (NSCalendarType.Gregorian); + var dc = cal.Components (NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, new NSDate ()); + var reference = cal.DateFromComponents (dc); // chose a reference date of the start of today. + var now = new NSDate ().SecondsSinceReferenceDate - reference.SecondsSinceReferenceDate; + + if (timeData.StartNow) { + if (timeData.Timestamps.Count == 1) { + var position = timeData.Timestamps [0]; + this.musicCoordinator.PlayMusic ("music_gameplay", position); + } else { + throw new Exception ("expected to have serverTimestamps.count == 1"); + } + } else { + if (this.IsServer) { + var numberOfRoundTripsToEstimateLatency = 4; // must be less than 16 to fit in data structure. + // A round trip has a start and an end time, so we want one more than this in the array. + if (timeData.Timestamps.Count < numberOfRoundTripsToEstimateLatency + 1) { + var timestamps = timeData.Timestamps; + timestamps.Add (now); + var newData = new StartGameMusicTime (false, timestamps); + this.session.Send (new GAction { StartGameMusic = newData }, player); + } else { + // Estimate the latency as the time taken for a few messages to go across and back + // divided by the number of ping/pongs and assuming the halfway point. + var count = timeData.Timestamps.Count; + var latencyEstimate = 0.5f * (timeData.Timestamps [count - 1] - timeData.Timestamps [0]) / (count - 1f); + var position = this.musicCoordinator.CurrentMusicTime (); + var newData = new StartGameMusicTime (true, new List<double> { position + latencyEstimate }); + this.session.Send (new GAction { StartGameMusic = newData }, player); + } + } else { + // echo the same message back to the server + this.session.Send (new GAction { StartGameMusic = timeData }, player); + } + } + } + + public void UpdateSessionLocation (GameTableLocation location) + { + this.session?.UpdateLocation (location); + } + + #endregion + + #region IGameSessionDelegate + + public void NetworkSessionReceived (NetworkSession session, GameCommand command) + { + this.commandsLock.Lock (); + + // Check if the action received is used to setup the board + // If so, process it and don't wait for the next update cycle to unqueue the event + // The GameManager is paused at that time of joining a game + if (command.Action.BoardSetup != null) { + this.Process (command); + } else { + this.gameCommands.Add (command); + } + + this.commandsLock.Unlock (); + } + + public void NetworkSessionJoining (NetworkSession session, Player player) + { + if (player.Equals (this.session.Host)) { + this.Delegate?.OnJoiningHost (this, player); + } else { + this.Delegate?.OnJoiningPlayer (this, player); + } + } + + public void NetworkSessionLeaving (NetworkSession session, Player player) + { + if (player == this.session.Host) { + this.Delegate?.OnLeavingHost (this, player); + } else { + this.Delegate?.OnLeavingPlayer (this, player); + } + } + + #endregion + + #region ICatapultDelegate + + public GameState GameState { get; private set; } = new GameState (); + + public void DidBreak (Catapult catapult, bool justKnockedout, bool vortex) + { + if (justKnockedout) { + this.sfxCoordinator.PlayCatapultBreak (catapult, vortex); + } + + this.gameObjectManager.AddBlockObject (catapult); + + this.GameState.TeamACatapults = this.Catapults.Count (c => c.Team == Team.TeamA && !c.Disabled); + this.GameState.TeamBCatapults = this.Catapults.Count (c => c.Team == Team.TeamB && !c.Disabled); + + // Sending new gameState + this.Delegate?.OnGameStateUpdated (this, this.GameState); + } + + public void DidBeginGrab (Catapult catapult) + { + // start haptics and sounds too for each catapult + this.sfxCoordinator.PlayGrabBall (catapult); + } + + public void DidMove (Catapult catapult, float stretchDistance, float stretchRate) + { + // sounds - balloon squeak + // haptics - vibrate with more energy depending on pull + var playHaptic = this.IsCurrentPlayerGrabbingACatapult (); + this.sfxCoordinator.PlayStretch (catapult, stretchDistance, stretchRate, playHaptic); + } + + public void DidLaunch (Catapult catapult, GameVelocity velocity) + { + // sounds - twang of bow or rubber band + // haptics - big launch vibrate + this.sfxCoordinator.StopStretch (catapult); + var playHaptic = this.IsCurrentPlayerGrabbingACatapult (); + this.sfxCoordinator.PlayLaunch (catapult, velocity, playHaptic); + if (!UserDefaults.HasOnboarded && playHaptic) { + UserDefaults.HasOnboarded = true; + } + } + + #endregion + + #region IInteractionDelegate + + public IProjectileDelegate ProjectileDelegate => this; + + public List<GameObject> AllBlockObjects => this.gameObjectManager.BlockObjects; + + public void RemoveTableBoxNodeFromLevel () + { + this.tableBoxObject?.ObjectRootNode?.RemoveFromParentNode (); + var shadowPlane = this.levelNode.FindChildNode ("ShadowPlane", true); + if (shadowPlane != null) { + shadowPlane.RunAction (SCNAction.FadeOut (0.5)); + } + } + + public void RemoveAllPhysicsBehaviors () + { + this.PhysicsWorld.RemoveAllBehaviors (); + } + + public void AddInteraction (IInteraction interaction) + { + this.interactionManager.AddInteraction (interaction); + } + + public void AddNodeToLevel (SCNNode node) + { + this.levelNode.AddChildNode (node); + } + + public Projectile SpawnProjectile () + { + var projectile = this.gameObjectPool.SpawnProjectile (); + this.physicsSyncData.ReplaceProjectile (projectile); + this.gameObjectManager.ReplaceProjectile (projectile); + // It would be better to use a preallocated audio sampler here if + // loading a new one takes too long. But it appears ok for now... + this.SetupAudioComponent (projectile); + + return projectile; + } + + public Projectile CreateProjectile () + { + return this.gameObjectPool.CreateProjectile (ProjectileType.Cannonball, null); + } + + public int GameObjectPoolCount () + { + return this.gameObjectPool.InitialPoolCount; + } + + public void DispatchActionToServer (GameActionType gameAction) + { + if (this.IsServer) { + this.QueueAction (gameAction); + } else { + this.Send (gameAction); // send to host + } + } + + public void DispatchActionToAll (GameActionType gameAction) + { + this.QueueAction (gameAction); + this.Send (gameAction); + } + + public void ServerDispatchActionToAll (GameActionType gameAction) + { + if (this.IsServer) { + this.Send (gameAction); + } + } + + public void DispatchToPlayer (GameActionType gameAction, Player player) + { + if (this.CurrentPlayer == player) { + this.QueueAction (gameAction); + } else { + this.session?.Send (new GAction { GameAction = gameAction }, player); + } + } + + #endregion + + #region IProjectileDelegate + + public void DespawnProjectile (Projectile projectile) + { + this.gameObjectPool.DespawnProjectile (projectile); + } + + public void AddParticles (SCNNode particlesNode, SCNVector3 worldPosition) + { + levelNode.AddChildNode (particlesNode); + particlesNode.WorldPosition = worldPosition; + } + + #endregion + + #region PhysicsSyncSceneDataDelegate + + public void HasNetworkDelayStatusChanged (bool hasNetworkDelay) + { + this.Delegate?.OnHasNetworkDelay (this, hasNetworkDelay); + } + + public Projectile SpawnProjectile (int objectIndex) + { + var projectile = this.gameObjectPool.SpawnProjectile (objectIndex); + projectile.Delegate = this; + + this.levelNode.AddChildNode (projectile.ObjectRootNode); + this.gameObjectManager.ReplaceProjectile (projectile); + + return projectile; + } + + public void PlayPhysicsSound (int objectIndex, CollisionEvent soundEvent) + { + // Find the correct GameObject and play the collision sound + foreach (var gameObject in this.gameObjects.Where (gameObject => gameObject.Index == objectIndex)) { + if (gameObject.GetComponent (typeof (GameAudioComponent)) is GameAudioComponent audioComponent) { + audioComponent.PlayCollisionSound (soundEvent); + } + + break; + } + } + + #endregion + + #region IGameObjectPoolDelegate + + public Dictionary<string, object> GameDefinitions { get; } = new Dictionary<string, object> (); + + public void OnSpawnedProjectile () + { + // Release all physics contraints + foreach (var block in this.gameObjectManager.BlockObjects) { + if (block.PhysicsNode?.PhysicsBody != null) { + block.PhysicsNode.PhysicsBody.AngularVelocityFactor = SCNVector3.One; + } + } + } + + #endregion + + #region IGameAudioComponentDelegate + + public void CollisionEventOccurred (GameAudioComponent component, CollisionEvent collisionEvent) + { + // For the server device, play the sound locally immediately. + if (this.IsServer) { + component.PlayCollisionSound (collisionEvent); + + // Add to the network sync + if (component.Entity is GameObject gameObject) { + this.physicsSyncData.AddSound (gameObject.Index, collisionEvent); + } else { + throw new Exception ("Component is not attached to GameObject"); + } + } + } + + #endregion + + #region SCNPhysicsContactDelegate + + public override void DidEndContact (SCNPhysicsWorld world, SCNPhysicsContact contact) + { + if (contact != null) { + this.DidCollision (contact.NodeA, contact.NodeB, new SCNVector3 (contact.ContactPoint), (float) contact.CollisionImpulse); + } + } + + public override void DidBeginContact (SCNPhysicsWorld world, SCNPhysicsContact contact) + { + if (contact != null) { + this.DidBeginContact (contact.NodeA, contact.NodeB, new SCNVector3 (contact.ContactPoint), (float) contact.CollisionImpulse); + } + } + + #endregion + + #region Destroy + + public void Unload () + { + this.session.Delegate = null; + this.PhysicsWorld.ContactDelegate = null; + this.levelNode.RemoveFromParentNode (); + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + if (disposing) { + this.Unload (); + this.gameObjects.Clear (); + this.tableBoxObject = null; + + this.session.Delegate = null; + this.session.Dispose (); + this.pointOfViewSimulation.Dispose (); + + this.commandsLock.Dispose (); + this.catapultsLock.Dispose (); + this.touchEventsLock.Dispose (); + + this.physicsSyncData.Delegate = null; + this.gameObjectPool.ProjectileDelegate = null; + this.gameObjectPool.Delegate = null; + this.gameObjectPool.Dispose (); + + //if(this.flagSimulation != null) + //{ + // this.flagSimulation.Dispose(); + // this.flagSimulation = null; + //} + } + } + + #endregion + + /// <summary> + /// Actions coming from the main thread/UI layer + /// </summary> + class TouchEvent { + public TouchEvent (TouchType type, Ray camera) + { + this.Type = type; + this.Camera = camera; + } + + public TouchType Type { get; set; } + + public Ray Camera { get; set; } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObject.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObject.cs index e3955f1ff..00170484c 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObject.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObject.cs @@ -1,555 +1,496 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using GameplayKit; - using SceneKit; - using XamarinShot.Models.GameplayState; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - public class GameObject : GKEntity - { - private static int IndexCounter = 0; +namespace XamarinShot.Models { + using Foundation; + using GameplayKit; + using SceneKit; + using XamarinShot.Models.GameplayState; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; - private Dictionary<string, object> properties = new Dictionary<string, object>(); + public class GameObject : GKEntity { + private static int IndexCounter = 0; - /// <summary> - /// call this before loading a level, all nodes loaded will share an index since nodes always load in the same order. - /// </summary> - public static void ResetIndexCounter() - { - IndexCounter = 0; - } + private Dictionary<string, object> properties = new Dictionary<string, object> (); - /// <summary> - /// Init with index that can be used to replace an old node - /// </summary> - public GameObject(SCNNode node, int? index, Dictionary<string, object> gamedefs, bool alive, bool server) : base() - { - this.ObjectRootNode = node; - this.IsAlive = alive; + /// <summary> + /// call this before loading a level, all nodes loaded will share an index since nodes always load in the same order. + /// </summary> + public static void ResetIndexCounter () + { + IndexCounter = 0; + } - if (index.HasValue) - { - this.Index = index.Value; - } - else - { - this.Index = GameObject.IndexCounter; - GameObject.IndexCounter += 1; - } - - this.GeometryNode = node.FindNodeWithGeometry(); - this.PhysicsNode = node.FindNodeWithPhysicsBody(); - - // set the gameObject onto the node - node.SetGameObject(this); - this.IsServer = server; - - if (!string.IsNullOrEmpty(node.Name)) - { - this.InitGameComponents(gamedefs, node.Name); - } - } - - public GameObject() : base() { } - - public GameObject(NSCoder coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public bool Categorize { get; set; } - - public string Category { get; set; } = string.Empty; - - public bool UsePredefinedPhysics { get; set; } - - public bool IsBlockObject { get; set; } = true; - - public float Density { get; set; } = 0f; - - public bool IsAlive { get; set; } - - public bool IsServer { get; set; } - - public int Index { get; private set; } = 0; - - public SCNNode GeometryNode { get; private set; } - - public SCNNode ObjectRootNode { get; private set; } - - public SCNNode PhysicsNode { get; set; } - - public static T Create<T>(SCNNode node, int? index, Dictionary<string, object> gamedefs, bool alive, bool server) where T : GameObject, new() - { - return Activator.CreateInstance(typeof(T), node, index, gamedefs, alive, server) as T; - } - - public static T Create<T>(SCNNode node) where T : GameObject, new() { return GameObject.Create<T>(node, new Dictionary<string, object>()); } - - public static T Create<T>(SCNNode node, Dictionary<string, object> gamedefs) where T : GameObject, new() { return GameObject.Create<T>(node, null, gamedefs, false, false); } - - #region helper for common root-level property tuning parameters - - public double? PropDouble(string name) - { - double? result = null; - if (this.properties.TryGet(name, out object value) && double.TryParse(value.ToString(), out double parsed)) - { - result = parsed; - } - - return result; - } - - protected string PropString(string name) - { - return this.properties[name].ToString(); - } - - public bool PropBool(string name) - { - var result = default(bool); - if (this.properties.TryGet(name, out object value) && bool.TryParse(value.ToString(), out bool parsed)) - { - result = parsed; - } - - return result; - } - - public int? PropInt(string name) - { - int? result = null; - if (this.properties.TryGet(name, out object value) && int.TryParse(value.ToString(), out int parsed)) - { - result = parsed; - } - - return result; - } - - public OpenTK.Vector2? PropFloat2(string name) - { - var valueString = this.PropString(name); - if (!string.IsNullOrEmpty(valueString)) - { - var strings = valueString.Split(' '); - if (strings.Length >= 2) - { - if (float.TryParse(strings[0], out float x) && - float.TryParse(strings[1], out float y)) - { - return new OpenTK.Vector2(x, y); - } - } - } - - return null; - } - - public SCNVector3? PropFloat3(string name) - { - var valueString = this.PropString(name); - if (!string.IsNullOrEmpty(valueString)) - { - var strings = valueString.Split(' '); - if (strings.Length >= 3) - { - if (float.TryParse(strings[0], out float x) && - float.TryParse(strings[1], out float y) && - float.TryParse(strings[2], out float z)) - { - return new SCNVector3(x, y, z); - } - } - } - - return null; - } - - #endregion - - private void InitGameComponents(Dictionary<string, object> gamedefs, string def) - { - if (gamedefs.TryGetValue("entityDefs", out object objectValue) && objectValue is Dictionary<string, object> entityDefs) - { - // always remove trailing integers from def name just in case class name is just a clone of something - var digits = NSCharacterSet.DecimalDigits; - - var defPrefix = def; - foreach (var uni in def.Reverse()) - { - if (digits.Contains(uni)) - { - defPrefix.Remove(defPrefix.Length - 1, 1); - } - else - { - break; - } - } - - var baseDefinitions = new Dictionary<string, object>(); - - // set up basedef, just in case nothing was found - if (entityDefs["base"] is Dictionary<string, object> baseDictionary) - { - baseDefinitions = baseDictionary; - this.Category = "base"; - } - - // if we have a physics body, use that as the base def - if (this.GeometryNode != null && this.PhysicsNode != null) - { - baseDictionary = entityDefs["basePhysics"] as Dictionary<string, object>; - if (baseDictionary != null) - { - baseDefinitions = baseDictionary; - this.Category = "basePhysics"; - } - } - - // check up to the first underscore - var type = ObjectRootNode.GetTypeIdentifier(); - if (!string.IsNullOrEmpty(type) && - entityDefs.TryGetValue(type, out object typeValue) && - typeValue is Dictionary<string, object> typeDictionary) - { - baseDictionary = typeDictionary; - baseDefinitions = baseDictionary; - this.Category = type; - } - - // check the name without the last number - if (entityDefs.TryGetValue(defPrefix, out object defPrefixValue) && - defPrefixValue is Dictionary<string, object> defPrefixDictionary) - { - baseDictionary = defPrefixDictionary; - baseDefinitions = baseDictionary; - this.Category = defPrefix; - } - - // now check for the actual name - if (entityDefs.TryGetValue(def, out object defValue) && - defValue is Dictionary<string, object> defDictionary) - { - baseDictionary = defDictionary; - baseDefinitions = baseDictionary; - this.Category = def; - } - - properties = baseDefinitions; - foreach (var (key, value) in baseDefinitions) - { - switch (key) - { - case "smoothPhysics": - this.SetupSmoothPhysics(value); - break; - - case "audio": - this.SetupAudio(value, this.ObjectRootNode); - break; - - case "properties": - this.SetupProperties(value); - break; - - case "slingshot": - this.SetupSlingshot(value); - break; - - case "resetSwitch": - this.SetupResetSwitch(value); - break; - - case "category": - this.SetupCategory(value); - break; - - case "animWaypoints": - this.SetupWaypoints(value); - break; - - case "constrainPhysics": - this.SetupConstrainPhysics(value); - break; - - case "blockObject": - this.UpdateBlockObject(value); - break; - - case "predefinedPhysics": - this.UpdatePredefinedPhysics(value); - break; - - case "density": - this.UpdateDensity(value); - break; - - default: - //os_log(.info, "Unknown component %s", key) - continue; - } - } - } - } - - /// <summary> - /// help correct for hitches if needed - /// </summary> - private void SetupSmoothPhysics(object value) - { - if (value is bool doSmooth && doSmooth && this.GeometryNode != null && this.PhysicsNode != null) - { - var physicsComponent = new GamePhysicsSmoothComponent(this.PhysicsNode, this.GeometryNode); - this.AddComponent(physicsComponent); - } - } - - /// <summary> - /// initialize audio features for collisions, etc - /// </summary> - private void SetupAudio(object value, SCNNode node) - { - if (value is Dictionary<string, object> properties) - { - this.AddComponent(new GameAudioComponent(node, properties)); - } - } - - /// <summary> - /// generic properties on this object - /// </summary> - private void SetupProperties(object value) - { - if (value is Dictionary<string, object> properties) - { - this.properties = properties; - } - } - - /// <summary> - /// component to update the slingshot on this object, if it has one - /// </summary> - private void SetupSlingshot(object value) - { - if (value is bool doSmooth && doSmooth) - { - var catapultPull = this.ObjectRootNode.FindChildNode("pull", true); - if (catapultPull != null) - { - this.AddComponent(new SlingshotComponent(catapultPull)); - } - } - } - - /// <summary> - /// special features when the object is a reset switch - /// </summary> - private void SetupResetSwitch(object value) - { - if (value is bool resetSwitch && resetSwitch) - { - var leverObj = this.ObjectRootNode.FindChildNode("resetSwitch_lever", true); - if (leverObj != null) - { - this.AddComponent(new ResetSwitchComponent(this, leverObj)); - } - } - } - - /// <summary> - /// categories let you group like objects together under a similar container - /// </summary> - private void SetupCategory(object value) - { - if (value is Dictionary<string, object> properties && - properties.TryGetValue("enabled", out object enabled) && - (bool)enabled) - { - if (properties.TryGetValue("header", out object header) - && !string.IsNullOrEmpty(header.ToString())) - { - this.Categorize = true; - this.Category = header.ToString(); - } - } - } - - private void SetupWaypoints(object value) - { - if (value is Dictionary<string, object> properties) - { - var animComponent = new AnimWaypointComponent(this.ObjectRootNode, properties); - if (animComponent.HasWaypoints) - { - this.AddComponent(animComponent); - } - } - } - - private void SetupConstrainPhysics(object value) - { - if (value is bool doConstrain && doConstrain && this.ObjectRootNode.HasConstraints()) - { - this.AddComponent(new ConstrainHierarchyComponent()); - } - } - - private void UpdateBlockObject(object value) - { - if (value is bool doBlockObject) - { - this.IsBlockObject = doBlockObject; - } - } - - private void UpdatePredefinedPhysics(object value) - { - if (value is bool predefinedPhysics) - { - this.UsePredefinedPhysics = predefinedPhysics; - } - } - - private void UpdateDensity(object value) - { - if (float.TryParse(value?.ToString(), out float density)) - { - this.Density = density; - } - } - - /// <summary> - /// Load the entity definitions from the specified file - /// </summary> - public static Dictionary<string, object> LoadGameDefs(string file) - { - var gameDefs = new Dictionary<string, object>(); - var url = NSBundle.MainBundle.GetUrlForResource(file, "json"); - if (url != null) - { - // read data - var json = NSString.FromData(NSData.FromUrl(url), NSStringEncoding.UTF8).ToString(); - - // strip comments out of the file with a regex - var commentRemovalRegex = "//.*\\n\\s*|/\\*.*?\\n?.*?\\*/\\n?\\s*"; - json = System.Text.RegularExpressions.Regex.Replace(json, commentRemovalRegex, string.Empty); - - // parse - gameDefs = json.Parse<Dictionary<string, object>>(); - } - - // correct for inheritance - if (gameDefs.TryGet("entityDefs", out Dictionary<string, object> defs)) - { - var newDefs = new Dictionary<string, object>(); - - // if a def has an inheritance key, apply the inheritance - foreach (var (key, _) in defs) - { - if (defs.TryGet(key, out Dictionary<string, object> def)) - { - var updated = UpdateDefInheritance(defs, def); - newDefs[key] = UpdateDictionary(updated); - } - } - - gameDefs["entityDefs"] = newDefs; - - return gameDefs; - - Dictionary<string, object> UpdateDictionary(Dictionary<string, object> dictionary) - { - var result = new Dictionary<string, object>(); - - foreach (var (key, value) in dictionary) - { - result[key] = dictionary.TryGet(key, out Dictionary<string, object> parsedValue) ? UpdateDictionary(parsedValue) : value; - } - - return result; - } - } - else - { - return new Dictionary<string, object>(); - } - } - - /// <summary> - /// Search for inheritance if available, and copy those properties over, then overwrite - /// </summary> - public static Dictionary<string, object> UpdateDefInheritance(Dictionary<string, object> defs, Dictionary<string, object> def) - { - var result = def; - - if (def.TryGet("inherit", out string inheritProp) && - !string.IsNullOrEmpty(inheritProp) && - defs.TryGet(inheritProp, out Dictionary<string, object> inheritDef)) - { - result = UpdateDefInheritance(defs, inheritDef); - - // copy new keys over top - foreach (var (key, value) in def) - { - if (key != "inherit") - { - result[key] = value; - } - } - } - - return result; - } - - #region Runtime methods - - public void Disable() - { - this.IsAlive = false; - this.PhysicsNode?.RemoveAllParticleSystems(); - this.ObjectRootNode.RemoveFromParentNode(); - this.RemoveComponent(typeof(RemoveWhenFallenComponent)); - } - - public void Apply(PhysicsNodeData nodeData, bool isHalfway) - { - if (this.PhysicsNode != null) - { - // if we're not alive, avoid applying physics updates. - // this will allow objects on clients to get culled properly - if (this.IsAlive) - { - if (isHalfway) - { - this.PhysicsNode.WorldPosition = (nodeData.Position + this.PhysicsNode.WorldPosition) * 0.5f; - this.PhysicsNode.Orientation = SCNQuaternion.Slerp(this.PhysicsNode.Orientation, nodeData.Orientation, 0.5f); - } - else - { - this.PhysicsNode.WorldPosition = nodeData.Position; - this.PhysicsNode.Orientation = nodeData.Orientation; - } - - if (this.PhysicsNode.PhysicsBody != null) - { - this.PhysicsNode.PhysicsBody.ResetTransform(); - this.PhysicsNode.PhysicsBody.Velocity = nodeData.Velocity; - this.PhysicsNode.PhysicsBody.AngularVelocity = nodeData.AngularVelocity; - } - } - } - } - - public virtual PhysicsNodeData GeneratePhysicsData() - { - return new PhysicsNodeData(this.PhysicsNode, this.IsAlive); - } - - #endregion - } -} \ No newline at end of file + /// <summary> + /// Init with index that can be used to replace an old node + /// </summary> + public GameObject (SCNNode node, int? index, Dictionary<string, object> gamedefs, bool alive, bool server) : base () + { + this.ObjectRootNode = node; + this.IsAlive = alive; + + if (index.HasValue) { + this.Index = index.Value; + } else { + this.Index = GameObject.IndexCounter; + GameObject.IndexCounter += 1; + } + + this.GeometryNode = node.FindNodeWithGeometry (); + this.PhysicsNode = node.FindNodeWithPhysicsBody (); + + // set the gameObject onto the node + node.SetGameObject (this); + this.IsServer = server; + + if (!string.IsNullOrEmpty (node.Name)) { + this.InitGameComponents (gamedefs, node.Name); + } + } + + public GameObject () : base () { } + + public GameObject (NSCoder coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public bool Categorize { get; set; } + + public string Category { get; set; } = string.Empty; + + public bool UsePredefinedPhysics { get; set; } + + public bool IsBlockObject { get; set; } = true; + + public float Density { get; set; } = 0f; + + public bool IsAlive { get; set; } + + public bool IsServer { get; set; } + + public int Index { get; private set; } = 0; + + public SCNNode GeometryNode { get; private set; } + + public SCNNode ObjectRootNode { get; private set; } + + public SCNNode PhysicsNode { get; set; } + + public static T Create<T> (SCNNode node, int? index, Dictionary<string, object> gamedefs, bool alive, bool server) where T : GameObject, new() + { + return Activator.CreateInstance (typeof (T), node, index, gamedefs, alive, server) as T; + } + + public static T Create<T> (SCNNode node) where T : GameObject, new() { return GameObject.Create<T> (node, new Dictionary<string, object> ()); } + + public static T Create<T> (SCNNode node, Dictionary<string, object> gamedefs) where T : GameObject, new() { return GameObject.Create<T> (node, null, gamedefs, false, false); } + + #region helper for common root-level property tuning parameters + + public double? PropDouble (string name) + { + double? result = null; + if (this.properties.TryGet (name, out object value) && double.TryParse (value.ToString (), out double parsed)) { + result = parsed; + } + + return result; + } + + protected string PropString (string name) + { + return this.properties [name].ToString (); + } + + public bool PropBool (string name) + { + var result = default (bool); + if (this.properties.TryGet (name, out object value) && bool.TryParse (value.ToString (), out bool parsed)) { + result = parsed; + } + + return result; + } + + public int? PropInt (string name) + { + int? result = null; + if (this.properties.TryGet (name, out object value) && int.TryParse (value.ToString (), out int parsed)) { + result = parsed; + } + + return result; + } + + public OpenTK.Vector2? PropFloat2 (string name) + { + var valueString = this.PropString (name); + if (!string.IsNullOrEmpty (valueString)) { + var strings = valueString.Split (' '); + if (strings.Length >= 2) { + if (float.TryParse (strings [0], out float x) && + float.TryParse (strings [1], out float y)) { + return new OpenTK.Vector2 (x, y); + } + } + } + + return null; + } + + public SCNVector3? PropFloat3 (string name) + { + var valueString = this.PropString (name); + if (!string.IsNullOrEmpty (valueString)) { + var strings = valueString.Split (' '); + if (strings.Length >= 3) { + if (float.TryParse (strings [0], out float x) && + float.TryParse (strings [1], out float y) && + float.TryParse (strings [2], out float z)) { + return new SCNVector3 (x, y, z); + } + } + } + + return null; + } + + #endregion + + private void InitGameComponents (Dictionary<string, object> gamedefs, string def) + { + if (gamedefs.TryGetValue ("entityDefs", out object objectValue) && objectValue is Dictionary<string, object> entityDefs) { + // always remove trailing integers from def name just in case class name is just a clone of something + var digits = NSCharacterSet.DecimalDigits; + + var defPrefix = def; + foreach (var uni in def.Reverse ()) { + if (digits.Contains (uni)) { + defPrefix.Remove (defPrefix.Length - 1, 1); + } else { + break; + } + } + + var baseDefinitions = new Dictionary<string, object> (); + + // set up basedef, just in case nothing was found + if (entityDefs ["base"] is Dictionary<string, object> baseDictionary) { + baseDefinitions = baseDictionary; + this.Category = "base"; + } + + // if we have a physics body, use that as the base def + if (this.GeometryNode != null && this.PhysicsNode != null) { + baseDictionary = entityDefs ["basePhysics"] as Dictionary<string, object>; + if (baseDictionary != null) { + baseDefinitions = baseDictionary; + this.Category = "basePhysics"; + } + } + + // check up to the first underscore + var type = ObjectRootNode.GetTypeIdentifier (); + if (!string.IsNullOrEmpty (type) && + entityDefs.TryGetValue (type, out object typeValue) && + typeValue is Dictionary<string, object> typeDictionary) { + baseDictionary = typeDictionary; + baseDefinitions = baseDictionary; + this.Category = type; + } + + // check the name without the last number + if (entityDefs.TryGetValue (defPrefix, out object defPrefixValue) && + defPrefixValue is Dictionary<string, object> defPrefixDictionary) { + baseDictionary = defPrefixDictionary; + baseDefinitions = baseDictionary; + this.Category = defPrefix; + } + + // now check for the actual name + if (entityDefs.TryGetValue (def, out object defValue) && + defValue is Dictionary<string, object> defDictionary) { + baseDictionary = defDictionary; + baseDefinitions = baseDictionary; + this.Category = def; + } + + properties = baseDefinitions; + foreach (var (key, value) in baseDefinitions) { + switch (key) { + case "smoothPhysics": + this.SetupSmoothPhysics (value); + break; + + case "audio": + this.SetupAudio (value, this.ObjectRootNode); + break; + + case "properties": + this.SetupProperties (value); + break; + + case "slingshot": + this.SetupSlingshot (value); + break; + + case "resetSwitch": + this.SetupResetSwitch (value); + break; + + case "category": + this.SetupCategory (value); + break; + + case "animWaypoints": + this.SetupWaypoints (value); + break; + + case "constrainPhysics": + this.SetupConstrainPhysics (value); + break; + + case "blockObject": + this.UpdateBlockObject (value); + break; + + case "predefinedPhysics": + this.UpdatePredefinedPhysics (value); + break; + + case "density": + this.UpdateDensity (value); + break; + + default: + //os_log(.info, "Unknown component %s", key) + continue; + } + } + } + } + + /// <summary> + /// help correct for hitches if needed + /// </summary> + private void SetupSmoothPhysics (object value) + { + if (value is bool doSmooth && doSmooth && this.GeometryNode != null && this.PhysicsNode != null) { + var physicsComponent = new GamePhysicsSmoothComponent (this.PhysicsNode, this.GeometryNode); + this.AddComponent (physicsComponent); + } + } + + /// <summary> + /// initialize audio features for collisions, etc + /// </summary> + private void SetupAudio (object value, SCNNode node) + { + if (value is Dictionary<string, object> properties) { + this.AddComponent (new GameAudioComponent (node, properties)); + } + } + + /// <summary> + /// generic properties on this object + /// </summary> + private void SetupProperties (object value) + { + if (value is Dictionary<string, object> properties) { + this.properties = properties; + } + } + + /// <summary> + /// component to update the slingshot on this object, if it has one + /// </summary> + private void SetupSlingshot (object value) + { + if (value is bool doSmooth && doSmooth) { + var catapultPull = this.ObjectRootNode.FindChildNode ("pull", true); + if (catapultPull != null) { + this.AddComponent (new SlingshotComponent (catapultPull)); + } + } + } + + /// <summary> + /// special features when the object is a reset switch + /// </summary> + private void SetupResetSwitch (object value) + { + if (value is bool resetSwitch && resetSwitch) { + var leverObj = this.ObjectRootNode.FindChildNode ("resetSwitch_lever", true); + if (leverObj != null) { + this.AddComponent (new ResetSwitchComponent (this, leverObj)); + } + } + } + + /// <summary> + /// categories let you group like objects together under a similar container + /// </summary> + private void SetupCategory (object value) + { + if (value is Dictionary<string, object> properties && + properties.TryGetValue ("enabled", out object enabled) && + (bool) enabled) { + if (properties.TryGetValue ("header", out object header) + && !string.IsNullOrEmpty (header.ToString ())) { + this.Categorize = true; + this.Category = header.ToString (); + } + } + } + + private void SetupWaypoints (object value) + { + if (value is Dictionary<string, object> properties) { + var animComponent = new AnimWaypointComponent (this.ObjectRootNode, properties); + if (animComponent.HasWaypoints) { + this.AddComponent (animComponent); + } + } + } + + private void SetupConstrainPhysics (object value) + { + if (value is bool doConstrain && doConstrain && this.ObjectRootNode.HasConstraints ()) { + this.AddComponent (new ConstrainHierarchyComponent ()); + } + } + + private void UpdateBlockObject (object value) + { + if (value is bool doBlockObject) { + this.IsBlockObject = doBlockObject; + } + } + + private void UpdatePredefinedPhysics (object value) + { + if (value is bool predefinedPhysics) { + this.UsePredefinedPhysics = predefinedPhysics; + } + } + + private void UpdateDensity (object value) + { + if (float.TryParse (value?.ToString (), out float density)) { + this.Density = density; + } + } + + /// <summary> + /// Load the entity definitions from the specified file + /// </summary> + public static Dictionary<string, object> LoadGameDefs (string file) + { + var gameDefs = new Dictionary<string, object> (); + var url = NSBundle.MainBundle.GetUrlForResource (file, "json"); + if (url != null) { + // read data + var json = NSString.FromData (NSData.FromUrl (url), NSStringEncoding.UTF8).ToString (); + + // strip comments out of the file with a regex + var commentRemovalRegex = "//.*\\n\\s*|/\\*.*?\\n?.*?\\*/\\n?\\s*"; + json = System.Text.RegularExpressions.Regex.Replace (json, commentRemovalRegex, string.Empty); + + // parse + gameDefs = json.Parse<Dictionary<string, object>> (); + } + + // correct for inheritance + if (gameDefs.TryGet ("entityDefs", out Dictionary<string, object> defs)) { + var newDefs = new Dictionary<string, object> (); + + // if a def has an inheritance key, apply the inheritance + foreach (var (key, _) in defs) { + if (defs.TryGet (key, out Dictionary<string, object> def)) { + var updated = UpdateDefInheritance (defs, def); + newDefs [key] = UpdateDictionary (updated); + } + } + + gameDefs ["entityDefs"] = newDefs; + + return gameDefs; + + Dictionary<string, object> UpdateDictionary (Dictionary<string, object> dictionary) + { + var result = new Dictionary<string, object> (); + + foreach (var (key, value) in dictionary) { + result [key] = dictionary.TryGet (key, out Dictionary<string, object> parsedValue) ? UpdateDictionary (parsedValue) : value; + } + + return result; + } + } else { + return new Dictionary<string, object> (); + } + } + + /// <summary> + /// Search for inheritance if available, and copy those properties over, then overwrite + /// </summary> + public static Dictionary<string, object> UpdateDefInheritance (Dictionary<string, object> defs, Dictionary<string, object> def) + { + var result = def; + + if (def.TryGet ("inherit", out string inheritProp) && + !string.IsNullOrEmpty (inheritProp) && + defs.TryGet (inheritProp, out Dictionary<string, object> inheritDef)) { + result = UpdateDefInheritance (defs, inheritDef); + + // copy new keys over top + foreach (var (key, value) in def) { + if (key != "inherit") { + result [key] = value; + } + } + } + + return result; + } + + #region Runtime methods + + public void Disable () + { + this.IsAlive = false; + this.PhysicsNode?.RemoveAllParticleSystems (); + this.ObjectRootNode.RemoveFromParentNode (); + this.RemoveComponent (typeof (RemoveWhenFallenComponent)); + } + + public void Apply (PhysicsNodeData nodeData, bool isHalfway) + { + if (this.PhysicsNode != null) { + // if we're not alive, avoid applying physics updates. + // this will allow objects on clients to get culled properly + if (this.IsAlive) { + if (isHalfway) { + this.PhysicsNode.WorldPosition = (nodeData.Position + this.PhysicsNode.WorldPosition) * 0.5f; + this.PhysicsNode.Orientation = SCNQuaternion.Slerp (this.PhysicsNode.Orientation, nodeData.Orientation, 0.5f); + } else { + this.PhysicsNode.WorldPosition = nodeData.Position; + this.PhysicsNode.Orientation = nodeData.Orientation; + } + + if (this.PhysicsNode.PhysicsBody != null) { + this.PhysicsNode.PhysicsBody.ResetTransform (); + this.PhysicsNode.PhysicsBody.Velocity = nodeData.Velocity; + this.PhysicsNode.PhysicsBody.AngularVelocity = nodeData.AngularVelocity; + } + } + } + } + + public virtual PhysicsNodeData GeneratePhysicsData () + { + return new PhysicsNodeData (this.PhysicsNode, this.IsAlive); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObjectManager.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObjectManager.cs index b1e4c18e3..ee6f3d3c7 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObjectManager.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameObjectManager.cs @@ -1,98 +1,89 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using SceneKit; - using System; - using System.Collections.Generic; - using System.Linq; - - public class GameObjectManager - { - private readonly NSLock @lock = new NSLock(); - - #region Block Management - - public List<GameObject> BlockObjects { get; private set; } = new List<GameObject>(); - - public void AddBlockObject(GameObject block) - { - if (!this.BlockObjects.Contains(block)) - { - this.BlockObjects.Add(block); - } - } - - #endregion - - #region Projectile Management - - private readonly List<Projectile> projectiles = new List<Projectile>(); - - public void AddProjectile(Projectile projectile) - { - this.@lock.Lock(); - this.projectiles.Add(projectile); - this.@lock.Unlock(); - } - - public void ReplaceProjectile(Projectile projectile) - { - this.@lock.Lock(); - - var oldProjectile = this.projectiles.FirstOrDefault(tile => tile.Index == projectile.Index); - if (oldProjectile != null) - { - this.projectiles[this.projectiles.IndexOf(oldProjectile)] = projectile; - } - else - { - throw new Exception($"Cannot find the projectile to replace {projectile.Index}"); - } - - this.@lock.Unlock(); - } - - public void DidBeginContactAll(SCNPhysicsContact contact) - { - this.@lock.Lock(); - - foreach (var projectile in this.projectiles) - { - projectile.DidBeginContact(contact); - } - - this.@lock.Unlock(); - } - - #endregion - - #region Shared Management - - public void Update(double deltaTime) - { - this.@lock.Lock(); - - foreach (var projectile in this.projectiles) - { - projectile.Update(deltaTime); - } - - this.@lock.Unlock(); - } - - public void OnDidApplyConstraints(ISCNSceneRenderer renderer) - { - this.@lock.Lock(); - - foreach (var projectile in this.projectiles) - { - projectile.OnDidApplyConstraints(renderer); - } - - this.@lock.Unlock(); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using SceneKit; + using System; + using System.Collections.Generic; + using System.Linq; + + public class GameObjectManager { + private readonly NSLock @lock = new NSLock (); + + #region Block Management + + public List<GameObject> BlockObjects { get; private set; } = new List<GameObject> (); + + public void AddBlockObject (GameObject block) + { + if (!this.BlockObjects.Contains (block)) { + this.BlockObjects.Add (block); + } + } + + #endregion + + #region Projectile Management + + private readonly List<Projectile> projectiles = new List<Projectile> (); + + public void AddProjectile (Projectile projectile) + { + this.@lock.Lock (); + this.projectiles.Add (projectile); + this.@lock.Unlock (); + } + + public void ReplaceProjectile (Projectile projectile) + { + this.@lock.Lock (); + + var oldProjectile = this.projectiles.FirstOrDefault (tile => tile.Index == projectile.Index); + if (oldProjectile != null) { + this.projectiles [this.projectiles.IndexOf (oldProjectile)] = projectile; + } else { + throw new Exception ($"Cannot find the projectile to replace {projectile.Index}"); + } + + this.@lock.Unlock (); + } + + public void DidBeginContactAll (SCNPhysicsContact contact) + { + this.@lock.Lock (); + + foreach (var projectile in this.projectiles) { + projectile.DidBeginContact (contact); + } + + this.@lock.Unlock (); + } + + #endregion + + #region Shared Management + + public void Update (double deltaTime) + { + this.@lock.Lock (); + + foreach (var projectile in this.projectiles) { + projectile.Update (deltaTime); + } + + this.@lock.Unlock (); + } + + public void OnDidApplyConstraints (ISCNSceneRenderer renderer) + { + this.@lock.Lock (); + + foreach (var projectile in this.projectiles) { + projectile.OnDidApplyConstraints (renderer); + } + + this.@lock.Unlock (); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameTime.cs b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameTime.cs index 202e1aea4..ced886bbf 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameTime.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gameplay State/GameTime.cs @@ -1,46 +1,43 @@ - -namespace XamarinShot.Models -{ - public static class GameTime - { - //! The start time of the app. - // Note: Uninitialized time/startTime are set to -1.0 so it can be checked in a lazy initialization - private static double StartTime = -1d; - - private static double LevelStartTime = -1d; - - //! The time given by the renderer's updateAtTime - public static double Time { get; private set; } = -1d; - - //! The time since the app started - public static double TimeSinceStart { get; private set; } = 0d; - - //! The time changed since last frame - public static double DeltaTime { get; private set; } = 0d; - - //! The frame count since the app started - public static int FrameCount { get; private set; } = 0; - - public static double TimeSinceLevelStart => GameTime.Time - LevelStartTime; - - public static void SetLevelStartTime() - { - LevelStartTime = GameTime.Time; - } - - public static void UpdateAtTime(double time) - { - if (StartTime == -1d) - { - StartTime = time; - Time = time; - return; - } - - DeltaTime = time - Time; - TimeSinceStart = time - StartTime; - Time = time; - FrameCount += 1; - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + public static class GameTime { + //! The start time of the app. + // Note: Uninitialized time/startTime are set to -1.0 so it can be checked in a lazy initialization + private static double StartTime = -1d; + + private static double LevelStartTime = -1d; + + //! The time given by the renderer's updateAtTime + public static double Time { get; private set; } = -1d; + + //! The time since the app started + public static double TimeSinceStart { get; private set; } = 0d; + + //! The time changed since last frame + public static double DeltaTime { get; private set; } = 0d; + + //! The frame count since the app started + public static int FrameCount { get; private set; } = 0; + + public static double TimeSinceLevelStart => GameTime.Time - LevelStartTime; + + public static void SetLevelStartTime () + { + LevelStartTime = GameTime.Time; + } + + public static void UpdateAtTime (double time) + { + if (StartTime == -1d) { + StartTime = time; + Time = time; + return; + } + + DeltaTime = time - Time; + TimeSinceStart = time - StartTime; + Time = time; + FrameCount += 1; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPanGestureRecognizer.cs b/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPanGestureRecognizer.cs index bb72ad0ce..cd19dee37 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPanGestureRecognizer.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPanGestureRecognizer.cs @@ -1,93 +1,85 @@ - -namespace XamarinShot.Models.GestureRecognizers -{ - using CoreGraphics; - using Foundation; - using XamarinShot.Utils; - using System; - using UIKit; - /// <summary> - /// A custom pan gesture reconizer that fires only when a threshold is passed. - /// </summary> - [Register("ThresholdPanGestureRecognizer")] - public class ThresholdPanGestureRecognizer : UIPanGestureRecognizer - { - /// The threshold in screen pixels after which this gesture is detected. - private static float Threshold = 30f; - - /// The initial touch location when this gesture started. - private CGPoint initialLocation = CGPoint.Empty; +namespace XamarinShot.Models.GestureRecognizers { + using CoreGraphics; + using Foundation; + using XamarinShot.Utils; + using System; + using UIKit; - public ThresholdPanGestureRecognizer(IntPtr handle) : base(handle) { } + /// <summary> + /// A custom pan gesture reconizer that fires only when a threshold is passed. + /// </summary> + [Register ("ThresholdPanGestureRecognizer")] + public class ThresholdPanGestureRecognizer : UIPanGestureRecognizer { + /// The threshold in screen pixels after which this gesture is detected. + private static float Threshold = 30f; - /// <summary> - /// Indicates whether the currently active gesture has exceeeded the threshold. - /// </summary> - public bool IsThresholdExceeded { get; private set; } + /// The initial touch location when this gesture started. + private CGPoint initialLocation = CGPoint.Empty; - /// <summary> - /// Observe when the gesture's `state` changes to reset the threshold. - /// </summary> - public override UIGestureRecognizerState State - { - get - { - return base.State; - } + public ThresholdPanGestureRecognizer (IntPtr handle) : base (handle) { } - set - { - base.State = value; - switch (base.State) - { - case UIGestureRecognizerState.Possible: - case UIGestureRecognizerState.Began: - case UIGestureRecognizerState.Changed: - break; - default: - // Reset variables. - this.IsThresholdExceeded = false; - this.initialLocation = CGPoint.Empty; - break; - } - } - } + /// <summary> + /// Indicates whether the currently active gesture has exceeeded the threshold. + /// </summary> + public bool IsThresholdExceeded { get; private set; } - public override void TouchesBegan(NSSet touches, UIEvent evt) - { - base.TouchesBegan(touches, evt); - this.initialLocation = this.LocationInView(this.View); - } + /// <summary> + /// Observe when the gesture's `state` changes to reset the threshold. + /// </summary> + public override UIGestureRecognizerState State { + get { + return base.State; + } - public override void TouchesMoved(NSSet touches, UIEvent evt) - { - base.TouchesMoved(touches, evt); + set { + base.State = value; + switch (base.State) { + case UIGestureRecognizerState.Possible: + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + break; + default: + // Reset variables. + this.IsThresholdExceeded = false; + this.initialLocation = CGPoint.Empty; + break; + } + } + } - var translationMagnitude = this.TranslationInView(this.View).Length(); + public override void TouchesBegan (NSSet touches, UIEvent evt) + { + base.TouchesBegan (touches, evt); + this.initialLocation = this.LocationInView (this.View); + } - if (!this.IsThresholdExceeded && translationMagnitude > ThresholdPanGestureRecognizer.Threshold) - { - this.IsThresholdExceeded = true; + public override void TouchesMoved (NSSet touches, UIEvent evt) + { + base.TouchesMoved (touches, evt); - // Set the overall translation to zero as the gesture should now begin. - this.SetTranslation(CGPoint.Empty, this.View); - } - } + var translationMagnitude = this.TranslationInView (this.View).Length (); - public override CGPoint LocationInView(UIView view) - { - switch(this.State) - { - case UIGestureRecognizerState.Began: - case UIGestureRecognizerState.Changed: - var correctedLocation = new CGPoint(this.initialLocation.X + this.TranslationInView(view).X, - this.initialLocation.Y + this.TranslationInView(view).Y); - return correctedLocation; - - default: - return base.LocationInView(view); - } - } - } -} \ No newline at end of file + if (!this.IsThresholdExceeded && translationMagnitude > ThresholdPanGestureRecognizer.Threshold) { + this.IsThresholdExceeded = true; + + // Set the overall translation to zero as the gesture should now begin. + this.SetTranslation (CGPoint.Empty, this.View); + } + } + + public override CGPoint LocationInView (UIView view) + { + switch (this.State) { + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + var correctedLocation = new CGPoint (this.initialLocation.X + this.TranslationInView (view).X, + this.initialLocation.Y + this.TranslationInView (view).Y); + return correctedLocation; + + default: + return base.LocationInView (view); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPinchGestureRecognizer.cs b/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPinchGestureRecognizer.cs index 371e4b0d2..68e87ade4 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPinchGestureRecognizer.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdPinchGestureRecognizer.cs @@ -1,106 +1,92 @@ - -namespace XamarinShot.Models.GestureRecognizers -{ - using CoreGraphics; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - /// <summary> - /// A custom pinch gesture reconizer that fires only when a threshold is passed. - /// </summary> - [Register("ThresholdPinchGestureRecognizer")] - public class ThresholdPinchGestureRecognizer : UIPinchGestureRecognizer - { - /// The threshold in screen pixels after which this gesture is detected. - private static float Threshold = 40f; +namespace XamarinShot.Models.GestureRecognizers { + using CoreGraphics; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; - /// The initial touch location when this gesture started. - private float initialTouchDistance = 0f; + /// <summary> + /// A custom pinch gesture reconizer that fires only when a threshold is passed. + /// </summary> + [Register ("ThresholdPinchGestureRecognizer")] + public class ThresholdPinchGestureRecognizer : UIPinchGestureRecognizer { + /// The threshold in screen pixels after which this gesture is detected. + private static float Threshold = 40f; - public ThresholdPinchGestureRecognizer(IntPtr handle) : base(handle) { } + /// The initial touch location when this gesture started. + private float initialTouchDistance = 0f; - /// <summary> - /// Indicates whether the currently active gesture has exceeeded the threshold. - /// </summary> - public bool IsThresholdExceeded { get; private set; } + public ThresholdPinchGestureRecognizer (IntPtr handle) : base (handle) { } - /// <summary> - /// Observe when the gesture's `state` changes to reset the threshold. - /// </summary> - public override UIGestureRecognizerState State - { - get - { - return base.State; - } + /// <summary> + /// Indicates whether the currently active gesture has exceeeded the threshold. + /// </summary> + public bool IsThresholdExceeded { get; private set; } - set - { - base.State = value; - switch (base.State) - { - case UIGestureRecognizerState.Began: - case UIGestureRecognizerState.Changed: - break; - default: - // Reset threshold check. - this.IsThresholdExceeded = false; - break; - } - } - } + /// <summary> + /// Observe when the gesture's `state` changes to reset the threshold. + /// </summary> + public override UIGestureRecognizerState State { + get { + return base.State; + } - public override void TouchesMoved(NSSet touches, UIEvent evt) - { - if (touches.Count == 2) - { - base.TouchesMoved(touches, evt); + set { + base.State = value; + switch (base.State) { + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + break; + default: + // Reset threshold check. + this.IsThresholdExceeded = false; + break; + } + } + } - switch (this.State) - { - case UIGestureRecognizerState.Began: - this.initialTouchDistance = this.TouchDistance(touches.Cast<UITouch>().ToList()); - break; + public override void TouchesMoved (NSSet touches, UIEvent evt) + { + if (touches.Count == 2) { + base.TouchesMoved (touches, evt); - case UIGestureRecognizerState.Changed: - var touchDistance = this.TouchDistance(touches.Cast<UITouch>().ToList()); - if (Math.Abs(touchDistance - this.initialTouchDistance) > ThresholdPinchGestureRecognizer.Threshold) - { - this.IsThresholdExceeded = true; - } - break; + switch (this.State) { + case UIGestureRecognizerState.Began: + this.initialTouchDistance = this.TouchDistance (touches.Cast<UITouch> ().ToList ()); + break; - default: - break; - } + case UIGestureRecognizerState.Changed: + var touchDistance = this.TouchDistance (touches.Cast<UITouch> ().ToList ()); + if (Math.Abs (touchDistance - this.initialTouchDistance) > ThresholdPinchGestureRecognizer.Threshold) { + this.IsThresholdExceeded = true; + } + break; - if (!this.IsThresholdExceeded) - { - this.Scale = 1f; - } - } - } + default: + break; + } - private float TouchDistance(IList<UITouch> touches) - { - if (touches.Count == 2) - { - var points = new List<CGPoint>(); - foreach(var touch in touches) - { - points.Add(touch.LocationInView(this.View)); - } + if (!this.IsThresholdExceeded) { + this.Scale = 1f; + } + } + } - var distance = Math.Sqrt((points[0].X - points[1].X) * (points[0].X - points[1].X) + (points[0].Y - points[1].Y) * (points[0].Y - points[1].Y)); - return (float)distance; - } - else - { - return 0f; - } - } - } -} \ No newline at end of file + private float TouchDistance (IList<UITouch> touches) + { + if (touches.Count == 2) { + var points = new List<CGPoint> (); + foreach (var touch in touches) { + points.Add (touch.LocationInView (this.View)); + } + + var distance = Math.Sqrt ((points [0].X - points [1].X) * (points [0].X - points [1].X) + (points [0].Y - points [1].Y) * (points [0].Y - points [1].Y)); + return (float) distance; + } else { + return 0f; + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdRotationGestureRecognizer.cs b/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdRotationGestureRecognizer.cs index ec6b552d6..74dc6f4ee 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdRotationGestureRecognizer.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Gesture Recognizers/ThresholdRotationGestureRecognizer.cs @@ -1,73 +1,65 @@ - -namespace XamarinShot.Models.GestureRecognizers -{ - using Foundation; - using System; - using UIKit; - /// <summary> - /// A custom rotation gesture reconizer that fires only when a threshold is passed. - /// </summary> - [Register("ThresholdRotationGestureRecognizer")] - public class ThresholdRotationGestureRecognizer : UIRotationGestureRecognizer - { - /// The threshold in screen pixels after which this gesture is detected. - private static float Threshold = (float)Math.PI / 18f; // (10°) +namespace XamarinShot.Models.GestureRecognizers { + using Foundation; + using System; + using UIKit; - private nfloat previousRotation = 0f; + /// <summary> + /// A custom rotation gesture reconizer that fires only when a threshold is passed. + /// </summary> + [Register ("ThresholdRotationGestureRecognizer")] + public class ThresholdRotationGestureRecognizer : UIRotationGestureRecognizer { + /// The threshold in screen pixels after which this gesture is detected. + private static float Threshold = (float) Math.PI / 18f; // (10°) - private nfloat rotationDelta = 0f; + private nfloat previousRotation = 0f; - public ThresholdRotationGestureRecognizer(IntPtr handle) : base(handle) { } + private nfloat rotationDelta = 0f; - /// <summary> - /// Indicates whether the currently active gesture has exceeeded the threshold. - /// </summary> - public bool IsThresholdExceeded { get; private set; } + public ThresholdRotationGestureRecognizer (IntPtr handle) : base (handle) { } - /// <summary> - /// Observe when the gesture's `state` changes to reset the threshold. - /// </summary> - public override UIGestureRecognizerState State - { - get - { - return base.State; - } + /// <summary> + /// Indicates whether the currently active gesture has exceeeded the threshold. + /// </summary> + public bool IsThresholdExceeded { get; private set; } - set - { - base.State = value; - switch (base.State) - { - case UIGestureRecognizerState.Began: - case UIGestureRecognizerState.Changed: - break; - default: - // Reset threshold check. - this.IsThresholdExceeded = false; - this.previousRotation = 0f; - this.rotationDelta = 0f; - break; - } - } - } + /// <summary> + /// Observe when the gesture's `state` changes to reset the threshold. + /// </summary> + public override UIGestureRecognizerState State { + get { + return base.State; + } - public override void TouchesMoved(NSSet touches, UIEvent evt) - { - base.TouchesMoved(touches, evt); + set { + base.State = value; + switch (base.State) { + case UIGestureRecognizerState.Began: + case UIGestureRecognizerState.Changed: + break; + default: + // Reset threshold check. + this.IsThresholdExceeded = false; + this.previousRotation = 0f; + this.rotationDelta = 0f; + break; + } + } + } - if (this.IsThresholdExceeded) - { - this.rotationDelta = this.Rotation - this.previousRotation; - this.previousRotation = this.Rotation; - } + public override void TouchesMoved (NSSet touches, UIEvent evt) + { + base.TouchesMoved (touches, evt); - if (!this.IsThresholdExceeded && Math.Abs(this.Rotation) > ThresholdRotationGestureRecognizer.Threshold) - { - this.IsThresholdExceeded = true; - this.previousRotation = this.Rotation; - } - } - } -} \ No newline at end of file + if (this.IsThresholdExceeded) { + this.rotationDelta = this.Rotation - this.previousRotation; + this.previousRotation = this.Rotation; + } + + if (!this.IsThresholdExceeded && Math.Abs (this.Rotation) > ThresholdRotationGestureRecognizer.Threshold) { + this.IsThresholdExceeded = true; + this.previousRotation = this.Rotation; + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultDisableInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultDisableInteraction.cs index ae87a864c..1c4a504fb 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultDisableInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultDisableInteraction.cs @@ -1,82 +1,69 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using System; - using System.Linq; - public class CatapultDisableInteraction : IInteraction - { - private const double CatapultUnstableTimeUntilDisable = 3d; +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using System; + using System.Linq; - public CatapultDisableInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; + public class CatapultDisableInteraction : IInteraction { + private const double CatapultUnstableTimeUntilDisable = 3d; - // Client should try to request the initial catapult disable state from server - if (!this.Delegate.IsServer) - { - this.Delegate.DispatchActionToServer(new GameActionType { Type = GameActionType.GActionType.KnockoutSync }); - } - } + public CatapultDisableInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; - public IInteractionDelegate Delegate { get; private set; } + // Client should try to request the initial catapult disable state from server + if (!this.Delegate.IsServer) { + this.Delegate.DispatchActionToServer (new GameActionType { Type = GameActionType.GActionType.KnockoutSync }); + } + } - public void Update(CameraInfo cameraInfo) - { - if(this.Delegate == null) - { - throw new Exception("No Delegate"); - } + public IInteractionDelegate Delegate { get; private set; } - foreach(var catapult in this.Delegate.Catapults) - { - // Check and disable knocked catapults - if (!catapult.Disabled && catapult.CatapultKnockedTime > CatapultUnstableTimeUntilDisable) - { - var knockoutInfo = new HitCatapult(catapult.CatapultId, true, false); - this.Delegate.DispatchActionToAll(new GameActionType { CatapultKnockOut = knockoutInfo, Type = GameActionType.GActionType.HitCatapult }); - } - } - } + public void Update (CameraInfo cameraInfo) + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } - #region Game Action Handling + foreach (var catapult in this.Delegate.Catapults) { + // Check and disable knocked catapults + if (!catapult.Disabled && catapult.CatapultKnockedTime > CatapultUnstableTimeUntilDisable) { + var knockoutInfo = new HitCatapult (catapult.CatapultId, true, false); + this.Delegate.DispatchActionToAll (new GameActionType { CatapultKnockOut = knockoutInfo, Type = GameActionType.GActionType.HitCatapult }); + } + } + } - public void Handle(GameActionType gameAction, Player player) - { - if (this.Delegate == null) - { - throw new Exception("No Delegate"); - } + #region Game Action Handling - if(gameAction.Type == GameActionType.GActionType.HitCatapult) - { - var catapult = this.Delegate.Catapults.FirstOrDefault(item => item.CatapultId == gameAction.CatapultKnockOut.CatapultId); - if(catapult != null) - { - if (!catapult.Disabled) - { - catapult.ProcessKnockOut(gameAction.CatapultKnockOut); - catapult.IsGrabbed = false; - } - } - } - else if (gameAction.Type == GameActionType.GActionType.KnockoutSync && this.Delegate.IsServer) - { - // Server will dispatch catapult knockout messages to all clients to make sure knockout states are in sync - foreach (var catapult in this.Delegate.Catapults.Where(catapult => catapult.Disabled)) - { - var knockoutInfo = new HitCatapult(catapult.CatapultId, false, false); - this.Delegate.DispatchActionToAll(new GameActionType { CatapultKnockOut = knockoutInfo, Type = GameActionType.GActionType.HitCatapult }); - } - } - } + public void Handle (GameActionType gameAction, Player player) + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } - public void HandleTouch(TouchType type, Ray camera) { } + if (gameAction.Type == GameActionType.GActionType.HitCatapult) { + var catapult = this.Delegate.Catapults.FirstOrDefault (item => item.CatapultId == gameAction.CatapultKnockOut.CatapultId); + if (catapult != null) { + if (!catapult.Disabled) { + catapult.ProcessKnockOut (gameAction.CatapultKnockOut); + catapult.IsGrabbed = false; + } + } + } else if (gameAction.Type == GameActionType.GActionType.KnockoutSync && this.Delegate.IsServer) { + // Server will dispatch catapult knockout messages to all clients to make sure knockout states are in sync + foreach (var catapult in this.Delegate.Catapults.Where (catapult => catapult.Disabled)) { + var knockoutInfo = new HitCatapult (catapult.CatapultId, false, false); + this.Delegate.DispatchActionToAll (new GameActionType { CatapultKnockOut = knockoutInfo, Type = GameActionType.GActionType.HitCatapult }); + } + } + } - #endregion + public void HandleTouch (TouchType type, Ray camera) { } - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) { } - } -} \ No newline at end of file + #endregion + + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) { } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultInteraction.cs index b0980007b..de082339c 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/CatapultInteraction.cs @@ -1,368 +1,322 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Models.Interactions; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - - /// <summary> - /// Abstract: - /// User interaction for the slingshot. - /// </summary> - public class CatapultInteraction : IInteraction, IGrabInteractionDelegate, IVortexActivationDelegate - { - private readonly Dictionary<int, Catapult> catapults = new Dictionary<int, Catapult>(); - - // this is a ball that doesn't have physics - private readonly SCNNode dummyBall; - - private GrabInteraction grabInteraction; - - public CatapultInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; - this.dummyBall = SCNNodeExtensions.LoadSCNAsset("projectiles_ball_8k"); - - // stri the geometry out of a low-lod model, assume it doesn't have an lod - if (this.dummyBall.Geometry != null) - { - var lod = SCNNodeExtensions.LoadSCNAsset("projectiles_ball"); - if (lod.Geometry != null) - { - lod.Geometry.Materials = this.dummyBall.Geometry.Materials; - - // this radius will be replaced by fixLevelsOfDetail - // when the level is placed - this.dummyBall.Geometry.LevelsOfDetail = new SCNLevelOfDetail[] { SCNLevelOfDetail.CreateWithScreenSpaceRadius(lod.Geometry, 100f) }; - } - } - } - - public IInteractionDelegate Delegate { get; private set; } - - public GrabInteraction GrabInteraction - { - get - { - return this.grabInteraction; - } - - set - { - this.grabInteraction = value; - // Add hook up to grabInteraction delegate automatically - if (this.grabInteraction != null) - { - this.grabInteraction.GrabDelegate = this; - } - } - } - - public void AddCatapult(Catapult catapult) - { - if (this.grabInteraction == null) - { - throw new Exception("GrabInteraction not set"); - } - - this.grabInteraction.AddGrabbable(catapult); - this.catapults[catapult.CatapultId] = catapult; - this.SetProjectileOnCatapult(catapult, ProjectileType.Cannonball); - } - - private void SetProjectileOnCatapult(Catapult catapult, ProjectileType projectileType) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - var projectile = TrailBallProjectile.Create(this.dummyBall.Clone()); - projectile.IsAlive = true; - projectile.Team = catapult.Team; - - if (projectile.PhysicsNode == null) - { - throw new Exception("Projectile has no physicsNode"); - } - - projectile.PhysicsNode.PhysicsBody = null; - this.Delegate.AddNodeToLevel(projectile.PhysicsNode); - - catapult.SetProjectileType(projectileType, projectile.ObjectRootNode); - } - - public bool CanGrabAnyCatapult(Ray cameraRay) - { - return this.catapults.Any(keyValuePair => keyValuePair.Value.CanGrab(cameraRay)); - } - - #region Interactions - - public void Update(CameraInfo cameraInfo) - { - foreach (var catapult in this.catapults.Values) - { - catapult.Update(); - } - } - - #endregion - - #region Game Action Handling - - public void Handle(GameActionType gameAction, Player player) - { - if (gameAction.Type == GameActionType.GActionType.CatapultRelease) - { - if (this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - this.HandleCatapultReleaseAction(gameAction.CatapultRelease, player, this.Delegate); - } - } - - private void ReleaseCatapultGrab(int catapultId) - { - if (!this.catapults.TryGetValue(catapultId, out Catapult catapult)) - { - throw new Exception($"No catapult {catapultId}"); - } - - if (this.grabInteraction == null) - { - throw new Exception("GrabInteraction not set"); - } - - catapult.IsGrabbed = false; - - // Empty grabbedCatapult if this catapult was grabbed by player - if (this.grabInteraction.GrabbedGrabbable is Catapult grabbedCatapult && grabbedCatapult.CatapultId == catapultId) - { - this.grabInteraction.GrabbedGrabbable = null; - } - } - - private void HandleCatapultReleaseAction(SlingData data, Player player, IInteractionDelegate @delegate) - { - if (this.catapults.TryGetValue(data.CatapultId, out Catapult catapult)) - { - catapult.OnLaunch(GameVelocity.Zero); - this.ReleaseCatapultGrab(data.CatapultId); - } - } - - #endregion - - #region Grab Interaction Delegate - - public bool ShouldForceRelease(IGrabbable grabbable) - { - if (grabbable is Catapult catapult) - { - return catapult.IsPulledTooFar || this.IsCatapultFloating(catapult); - } - else - { - throw new Exception("Grabbable is not catapult"); - } - } - - private bool IsCatapultFloating(Catapult catapult) - { - if (this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - if (catapult.Base.PhysicsBody != null) - { - var contacts = this.Delegate.PhysicsWorld.ContactTest(catapult.Base.PhysicsBody, (SCNPhysicsTest)null); - return !contacts.Any(); - } - else - { - return false; - } - } - - public void OnGrabStart(IGrabbable grabbable, CameraInfo cameraInfo, Player player) - { - if (grabbable is Catapult catapult) - { - catapult.OnGrabStart(); - } - } - - public void OnServerRelease(IGrabbable grabbable, CameraInfo cameraInfo, Player player) - { - if (this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - if (grabbable is Catapult catapult) - { - // Launch the ball - var velocity = catapult.TryGetLaunchVelocity(cameraInfo); - if (velocity != null) - { - catapult.OnLaunch(velocity); - this.SlingBall(catapult, velocity); - catapult.ReleaseSlingGrab(); - - this.ReleaseCatapultGrab(catapult.CatapultId); - - var slingData = new SlingData(catapult.CatapultId, catapult.ProjectileType, velocity); - - // succeed in launching catapult, notify all clients of the update - this.Delegate.ServerDispatchActionToAll(new GameActionType { CatapultRelease = slingData, Type = GameActionType.GActionType.CatapultRelease }); - } - } - } - - public void OnServerGrab(IGrabbable grabbable, CameraInfo cameraInfo, Player player) - { - if (grabbable is Catapult catapult) - { - catapult.ServerGrab(cameraInfo.Ray); - } - } - - public void OnUpdateGrabStatus(IGrabbable grabbable, CameraInfo cameraInfo) - { - if (grabbable is Catapult catapult) - { - catapult.BallVisible = BallVisible.Visible; - catapult.OnGrab(cameraInfo); - } - } - - #endregion - - #region Collision - - private const float MinImpuseToReleaseCatapult = 1.5f; - - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) - { - var gameObject = node.NearestParentGameObject(); - if (gameObject != null && gameObject is Catapult catapult) - { - var otherGameObject = otherNode.NearestParentGameObject(); - if (otherGameObject != null) - { - // Projectile case - if (otherGameObject is Projectile projectile) - { - var catapultNode = catapult.Base; - if (catapultNode.PhysicsBody == null) - { - throw new Exception("Catapult has no physicsBody"); - } - - // Do not let projectile from the same team kill the catapult - if (catapult.Team == projectile.Team) - { - catapultNode.PhysicsBody.Velocity = SCNVector3.Zero; - catapultNode.PhysicsBody.AngularVelocity = SCNVector4.UnitY; - } - } - - // Server tries to release the catapult if it got impulse from block or projectile - if (impulse > MinImpuseToReleaseCatapult) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - if (this.Delegate.IsServer) - { - // Any game objects (blocks or projectiles) case - var data = new GrabInfo(catapult.CatapultId, catapult.LastCameraInfo); - this.Delegate.DispatchActionToServer(new GameActionType { TryRelease = data, Type = GameActionType.GActionType.TryRelease }); - } - } - } - } - } - - #endregion - - #region Sling Ball - - public void SlingBall(Catapult catapult, GameVelocity velocity) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - var newProjectile = this.Delegate.SpawnProjectile(); - newProjectile.Team = catapult.Team; - - this.Delegate.AddNodeToLevel(newProjectile.ObjectRootNode); - - // The lifeTime of projectile needed to sustain the pool is defined by: - // (Catapult Count) * (1 + (lifeTime) / (cooldownTime)) = (Pool Count) - var poolCount = this.Delegate.GameObjectPoolCount(); - var lifeTime = (double)(poolCount / this.catapults.Count - 1) * catapult.CoolDownTime; - - newProjectile.Launch(velocity, lifeTime, this.Delegate.ProjectileDelegate); - - // assign the catapult source to this ball - if (newProjectile.PhysicsNode?.PhysicsBody != null) - { - newProjectile.PhysicsNode.SetValueForKey(NSObject.FromObject(catapult.CatapultId), new NSString("Source")); - newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask = (int)(CollisionMask.RigidBody | CollisionMask.GlitterObject); - if (catapult.Team == Team.TeamA) - { - var collisionMask = (CollisionMask)(int)(newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask); - newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint)(int)(collisionMask | CollisionMask.CatapultTeamB); - - var categoryBitMask = (CollisionMask)(int)(newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask); - newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask = (nuint)(int)(categoryBitMask | CollisionMask.CatapultTeamA); - } - else - { - var collisionMask = (CollisionMask)(int)(newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask); - newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint)(int)(collisionMask | CollisionMask.CatapultTeamA); - - var categoryBitMask = (CollisionMask)(int)(newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask); - newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask = (nuint)(int)(categoryBitMask | CollisionMask.CatapultTeamB); - } - } - } - - public void HandleTouch(TouchType type, Ray camera) { } - - #endregion - - #region IVortexActivationDelegate - - public void VortexDidActivate(VortexInteraction vortex) - { - // Kill all catapults when vortex activates - if(this.Delegate == null) - { - throw new Exception("No delegate"); - } - - foreach(var catapult in this.catapults.Values) - { - var data = new HitCatapult(catapult.CatapultId, false, true); - this.Delegate.DispatchActionToAll(new GameActionType { CatapultKnockOut = data, Type = GameActionType.GActionType.HitCatapult }); - } - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Models.Interactions; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + /// <summary> + /// Abstract: + /// User interaction for the slingshot. + /// </summary> + public class CatapultInteraction : IInteraction, IGrabInteractionDelegate, IVortexActivationDelegate { + private readonly Dictionary<int, Catapult> catapults = new Dictionary<int, Catapult> (); + + // this is a ball that doesn't have physics + private readonly SCNNode dummyBall; + + private GrabInteraction grabInteraction; + + public CatapultInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; + this.dummyBall = SCNNodeExtensions.LoadSCNAsset ("projectiles_ball_8k"); + + // stri the geometry out of a low-lod model, assume it doesn't have an lod + if (this.dummyBall.Geometry != null) { + var lod = SCNNodeExtensions.LoadSCNAsset ("projectiles_ball"); + if (lod.Geometry != null) { + lod.Geometry.Materials = this.dummyBall.Geometry.Materials; + + // this radius will be replaced by fixLevelsOfDetail + // when the level is placed + this.dummyBall.Geometry.LevelsOfDetail = new SCNLevelOfDetail [] { SCNLevelOfDetail.CreateWithScreenSpaceRadius (lod.Geometry, 100f) }; + } + } + } + + public IInteractionDelegate Delegate { get; private set; } + + public GrabInteraction GrabInteraction { + get { + return this.grabInteraction; + } + + set { + this.grabInteraction = value; + // Add hook up to grabInteraction delegate automatically + if (this.grabInteraction != null) { + this.grabInteraction.GrabDelegate = this; + } + } + } + + public void AddCatapult (Catapult catapult) + { + if (this.grabInteraction == null) { + throw new Exception ("GrabInteraction not set"); + } + + this.grabInteraction.AddGrabbable (catapult); + this.catapults [catapult.CatapultId] = catapult; + this.SetProjectileOnCatapult (catapult, ProjectileType.Cannonball); + } + + private void SetProjectileOnCatapult (Catapult catapult, ProjectileType projectileType) + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + var projectile = TrailBallProjectile.Create (this.dummyBall.Clone ()); + projectile.IsAlive = true; + projectile.Team = catapult.Team; + + if (projectile.PhysicsNode == null) { + throw new Exception ("Projectile has no physicsNode"); + } + + projectile.PhysicsNode.PhysicsBody = null; + this.Delegate.AddNodeToLevel (projectile.PhysicsNode); + + catapult.SetProjectileType (projectileType, projectile.ObjectRootNode); + } + + public bool CanGrabAnyCatapult (Ray cameraRay) + { + return this.catapults.Any (keyValuePair => keyValuePair.Value.CanGrab (cameraRay)); + } + + #region Interactions + + public void Update (CameraInfo cameraInfo) + { + foreach (var catapult in this.catapults.Values) { + catapult.Update (); + } + } + + #endregion + + #region Game Action Handling + + public void Handle (GameActionType gameAction, Player player) + { + if (gameAction.Type == GameActionType.GActionType.CatapultRelease) { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + this.HandleCatapultReleaseAction (gameAction.CatapultRelease, player, this.Delegate); + } + } + + private void ReleaseCatapultGrab (int catapultId) + { + if (!this.catapults.TryGetValue (catapultId, out Catapult catapult)) { + throw new Exception ($"No catapult {catapultId}"); + } + + if (this.grabInteraction == null) { + throw new Exception ("GrabInteraction not set"); + } + + catapult.IsGrabbed = false; + + // Empty grabbedCatapult if this catapult was grabbed by player + if (this.grabInteraction.GrabbedGrabbable is Catapult grabbedCatapult && grabbedCatapult.CatapultId == catapultId) { + this.grabInteraction.GrabbedGrabbable = null; + } + } + + private void HandleCatapultReleaseAction (SlingData data, Player player, IInteractionDelegate @delegate) + { + if (this.catapults.TryGetValue (data.CatapultId, out Catapult catapult)) { + catapult.OnLaunch (GameVelocity.Zero); + this.ReleaseCatapultGrab (data.CatapultId); + } + } + + #endregion + + #region Grab Interaction Delegate + + public bool ShouldForceRelease (IGrabbable grabbable) + { + if (grabbable is Catapult catapult) { + return catapult.IsPulledTooFar || this.IsCatapultFloating (catapult); + } else { + throw new Exception ("Grabbable is not catapult"); + } + } + + private bool IsCatapultFloating (Catapult catapult) + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + if (catapult.Base.PhysicsBody != null) { + var contacts = this.Delegate.PhysicsWorld.ContactTest (catapult.Base.PhysicsBody, (SCNPhysicsTest) null); + return !contacts.Any (); + } else { + return false; + } + } + + public void OnGrabStart (IGrabbable grabbable, CameraInfo cameraInfo, Player player) + { + if (grabbable is Catapult catapult) { + catapult.OnGrabStart (); + } + } + + public void OnServerRelease (IGrabbable grabbable, CameraInfo cameraInfo, Player player) + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + if (grabbable is Catapult catapult) { + // Launch the ball + var velocity = catapult.TryGetLaunchVelocity (cameraInfo); + if (velocity != null) { + catapult.OnLaunch (velocity); + this.SlingBall (catapult, velocity); + catapult.ReleaseSlingGrab (); + + this.ReleaseCatapultGrab (catapult.CatapultId); + + var slingData = new SlingData (catapult.CatapultId, catapult.ProjectileType, velocity); + + // succeed in launching catapult, notify all clients of the update + this.Delegate.ServerDispatchActionToAll (new GameActionType { CatapultRelease = slingData, Type = GameActionType.GActionType.CatapultRelease }); + } + } + } + + public void OnServerGrab (IGrabbable grabbable, CameraInfo cameraInfo, Player player) + { + if (grabbable is Catapult catapult) { + catapult.ServerGrab (cameraInfo.Ray); + } + } + + public void OnUpdateGrabStatus (IGrabbable grabbable, CameraInfo cameraInfo) + { + if (grabbable is Catapult catapult) { + catapult.BallVisible = BallVisible.Visible; + catapult.OnGrab (cameraInfo); + } + } + + #endregion + + #region Collision + + private const float MinImpuseToReleaseCatapult = 1.5f; + + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse) + { + var gameObject = node.NearestParentGameObject (); + if (gameObject != null && gameObject is Catapult catapult) { + var otherGameObject = otherNode.NearestParentGameObject (); + if (otherGameObject != null) { + // Projectile case + if (otherGameObject is Projectile projectile) { + var catapultNode = catapult.Base; + if (catapultNode.PhysicsBody == null) { + throw new Exception ("Catapult has no physicsBody"); + } + + // Do not let projectile from the same team kill the catapult + if (catapult.Team == projectile.Team) { + catapultNode.PhysicsBody.Velocity = SCNVector3.Zero; + catapultNode.PhysicsBody.AngularVelocity = SCNVector4.UnitY; + } + } + + // Server tries to release the catapult if it got impulse from block or projectile + if (impulse > MinImpuseToReleaseCatapult) { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + if (this.Delegate.IsServer) { + // Any game objects (blocks or projectiles) case + var data = new GrabInfo (catapult.CatapultId, catapult.LastCameraInfo); + this.Delegate.DispatchActionToServer (new GameActionType { TryRelease = data, Type = GameActionType.GActionType.TryRelease }); + } + } + } + } + } + + #endregion + + #region Sling Ball + + public void SlingBall (Catapult catapult, GameVelocity velocity) + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + var newProjectile = this.Delegate.SpawnProjectile (); + newProjectile.Team = catapult.Team; + + this.Delegate.AddNodeToLevel (newProjectile.ObjectRootNode); + + // The lifeTime of projectile needed to sustain the pool is defined by: + // (Catapult Count) * (1 + (lifeTime) / (cooldownTime)) = (Pool Count) + var poolCount = this.Delegate.GameObjectPoolCount (); + var lifeTime = (double) (poolCount / this.catapults.Count - 1) * catapult.CoolDownTime; + + newProjectile.Launch (velocity, lifeTime, this.Delegate.ProjectileDelegate); + + // assign the catapult source to this ball + if (newProjectile.PhysicsNode?.PhysicsBody != null) { + newProjectile.PhysicsNode.SetValueForKey (NSObject.FromObject (catapult.CatapultId), new NSString ("Source")); + newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask = (int) (CollisionMask.RigidBody | CollisionMask.GlitterObject); + if (catapult.Team == Team.TeamA) { + var collisionMask = (CollisionMask) (int) (newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask); + newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint) (int) (collisionMask | CollisionMask.CatapultTeamB); + + var categoryBitMask = (CollisionMask) (int) (newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask); + newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask = (nuint) (int) (categoryBitMask | CollisionMask.CatapultTeamA); + } else { + var collisionMask = (CollisionMask) (int) (newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask); + newProjectile.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint) (int) (collisionMask | CollisionMask.CatapultTeamA); + + var categoryBitMask = (CollisionMask) (int) (newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask); + newProjectile.PhysicsNode.PhysicsBody.CategoryBitMask = (nuint) (int) (categoryBitMask | CollisionMask.CatapultTeamB); + } + } + } + + public void HandleTouch (TouchType type, Ray camera) { } + + #endregion + + #region IVortexActivationDelegate + + public void VortexDidActivate (VortexInteraction vortex) + { + // Kill all catapults when vortex activates + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + foreach (var catapult in this.catapults.Values) { + var data = new HitCatapult (catapult.CatapultId, false, true); + this.Delegate.DispatchActionToAll (new GameActionType { CatapultKnockOut = data, Type = GameActionType.GActionType.HitCatapult }); + } + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/GameObjectPool.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/GameObjectPool.cs index f5e9f396d..a547fbc1d 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/GameObjectPool.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/GameObjectPool.cs @@ -1,152 +1,140 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Models.GameplayState; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - - public interface IGameObjectPoolDelegate - { - Dictionary<string, object> GameDefinitions { get; } - - void OnSpawnedProjectile(); - } - - // Pool that makes it possible for clients to join the game after a ball has been shot - // In this case, the pool helps manage fixed projectile slots used for physics sync. - // The pool do not actually reuse the object (that functionality could be added if necessary). - public class GameObjectPool : IDisposable - { - private readonly SCNNode cannonball; - - private readonly SCNNode chicken; - - public GameObjectPool() - { - this.cannonball = SCNNodeExtensions.LoadSCNAsset("projectiles_ball"); - this.chicken = SCNNodeExtensions.LoadSCNAsset("projectiles_chicken"); - - this.InitialPoolCount = 30; - } - - public IGameObjectPoolDelegate Delegate { get; set; } - - public IProjectileDelegate ProjectileDelegate { get; set; } - - public List<Projectile> ProjectilePool { get; } = new List<Projectile>(); - - public int InitialPoolCount { get; private set; } = 0; - - public Projectile SpawnProjectile() - { - var count = 0; - foreach(var projectile in this.ProjectilePool.Where(projectile => !projectile.IsAlive)) - { - count += 1; - } - - foreach (var projectile in this.ProjectilePool.Where(projectile => !projectile.IsAlive)) - { - return this.SpawnProjectile(projectile.Index); - } - - throw new Exception("No more free projectile in the pool"); - } - - /// <summary> - /// Spawn projectile with specific object index - /// </summary> - public Projectile SpawnProjectile(int objectIndex) - { - if(this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - this.Delegate.OnSpawnedProjectile(); - - var projectile = this.ProjectilePool.FirstOrDefault(tile => tile.Index == objectIndex); - if(projectile != null) - { - var newProjectile = this.CreateProjectile(ProjectileType.Cannonball, projectile.Index); - newProjectile.IsAlive = true; - this.ProjectilePool[this.ProjectilePool.IndexOf(projectile)] = newProjectile; - newProjectile.Delegate = this.ProjectileDelegate; - newProjectile.OnSpawn(); - return newProjectile; - } - - throw new Exception($"Could not find projectile with index: {objectIndex}"); - } - - public void DespawnProjectile(Projectile projectile) - { - projectile.Disable(); - } - - public void CreatePoolObjects(IGameObjectPoolDelegate @delegate) - { - this.Delegate = @delegate; - for (var i = 0; i < this.InitialPoolCount; i++) - { - var newProjectile = this.CreateProjectile(ProjectileType.Cannonball, null); - this.ProjectilePool.Add(newProjectile); - } - } - - public Projectile CreateProjectile(ProjectileType projectileType, int? index) - { - if (this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - Projectile projectile = null; - switch (projectileType) - { - case ProjectileType.Cannonball: - projectile = TrailBallProjectile.Create(this.cannonball, index, this.Delegate.GameDefinitions); - break; - // Add other projectile types here as needed - case ProjectileType.Chicken: - projectile = ChickenProjectile.Create(this.chicken, index, this.Delegate.GameDefinitions); - break; - default: - throw new Exception("Trying to get .none projectile"); - } - - projectile.AddComponent(new RemoveWhenFallenComponent()); - return projectile; - } - - #region IDisposable - - private bool isDisposed; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!this.isDisposed) - { - if (disposing) - { - this.chicken.Dispose(); - this.cannonball.Dispose(); - } - - this.isDisposed = true; - } - } - - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(true); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Models.GameplayState; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + public interface IGameObjectPoolDelegate { + Dictionary<string, object> GameDefinitions { get; } + + void OnSpawnedProjectile (); + } + + // Pool that makes it possible for clients to join the game after a ball has been shot + // In this case, the pool helps manage fixed projectile slots used for physics sync. + // The pool do not actually reuse the object (that functionality could be added if necessary). + public class GameObjectPool : IDisposable { + private readonly SCNNode cannonball; + + private readonly SCNNode chicken; + + public GameObjectPool () + { + this.cannonball = SCNNodeExtensions.LoadSCNAsset ("projectiles_ball"); + this.chicken = SCNNodeExtensions.LoadSCNAsset ("projectiles_chicken"); + + this.InitialPoolCount = 30; + } + + public IGameObjectPoolDelegate Delegate { get; set; } + + public IProjectileDelegate ProjectileDelegate { get; set; } + + public List<Projectile> ProjectilePool { get; } = new List<Projectile> (); + + public int InitialPoolCount { get; private set; } = 0; + + public Projectile SpawnProjectile () + { + var count = 0; + foreach (var projectile in this.ProjectilePool.Where (projectile => !projectile.IsAlive)) { + count += 1; + } + + foreach (var projectile in this.ProjectilePool.Where (projectile => !projectile.IsAlive)) { + return this.SpawnProjectile (projectile.Index); + } + + throw new Exception ("No more free projectile in the pool"); + } + + /// <summary> + /// Spawn projectile with specific object index + /// </summary> + public Projectile SpawnProjectile (int objectIndex) + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + this.Delegate.OnSpawnedProjectile (); + + var projectile = this.ProjectilePool.FirstOrDefault (tile => tile.Index == objectIndex); + if (projectile != null) { + var newProjectile = this.CreateProjectile (ProjectileType.Cannonball, projectile.Index); + newProjectile.IsAlive = true; + this.ProjectilePool [this.ProjectilePool.IndexOf (projectile)] = newProjectile; + newProjectile.Delegate = this.ProjectileDelegate; + newProjectile.OnSpawn (); + return newProjectile; + } + + throw new Exception ($"Could not find projectile with index: {objectIndex}"); + } + + public void DespawnProjectile (Projectile projectile) + { + projectile.Disable (); + } + + public void CreatePoolObjects (IGameObjectPoolDelegate @delegate) + { + this.Delegate = @delegate; + for (var i = 0; i < this.InitialPoolCount; i++) { + var newProjectile = this.CreateProjectile (ProjectileType.Cannonball, null); + this.ProjectilePool.Add (newProjectile); + } + } + + public Projectile CreateProjectile (ProjectileType projectileType, int? index) + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + Projectile projectile = null; + switch (projectileType) { + case ProjectileType.Cannonball: + projectile = TrailBallProjectile.Create (this.cannonball, index, this.Delegate.GameDefinitions); + break; + // Add other projectile types here as needed + case ProjectileType.Chicken: + projectile = ChickenProjectile.Create (this.chicken, index, this.Delegate.GameDefinitions); + break; + default: + throw new Exception ("Trying to get .none projectile"); + } + + projectile.AddComponent (new RemoveWhenFallenComponent ()); + return projectile; + } + + #region IDisposable + + private bool isDisposed; // To detect redundant calls + + protected virtual void Dispose (bool disposing) + { + if (!this.isDisposed) { + if (disposing) { + this.chicken.Dispose (); + this.cannonball.Dispose (); + } + + this.isDisposed = true; + } + } + + public void Dispose () + { + this.Dispose (true); + GC.SuppressFinalize (true); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/GrabInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/GrabInteraction.cs index 534398721..0a01642d0 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/GrabInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/GrabInteraction.cs @@ -1,318 +1,286 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Models.Interactions; - using System; - using System.Collections.Generic; - - public interface IGrabInteractionDelegate - { - bool ShouldForceRelease(IGrabbable grabbable); - void OnServerGrab(IGrabbable grabbable, CameraInfo cameraInfo, Player player); - void OnGrabStart(IGrabbable grabbable, CameraInfo cameraInfo, Player player); - void OnServerRelease(IGrabbable grabbable, CameraInfo cameraInfo, Player player); - void OnUpdateGrabStatus(IGrabbable grabbable, CameraInfo cameraInfo); - } - - public class GrabInteraction : IInteraction - { - private bool isTouching; - - // Index used to assign to new object - private int currentIndex = 0; - - public GrabInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; - } - - public IInteractionDelegate Delegate { get; private set; } - - public IGrabInteractionDelegate GrabDelegate { get; set; } - - public IGrabbable GrabbedGrabbable { get; set; } - - public Dictionary<int, IGrabbable> Grabbables { get; private set; } = new Dictionary<int, IGrabbable>(); - - /// <summary> - /// Should be added only from the classes using GrabInteraction to prevent duplicates - /// </summary> - public void AddGrabbable(IGrabbable grabbable) - { - grabbable.GrabbableId = this.currentIndex; - this.Grabbables[this.currentIndex] = grabbable; - this.currentIndex += 1; - } - - public void HandleTouch(TouchType type, Ray camera) - { - if (type == TouchType.Began) - { - if (this.GrabbableToGrab(camera) != null) - { - this.isTouching = true; - } - } - else if (type == TouchType.Ended) - { - this.isTouching = false; - } - } - - public void Update(CameraInfo cameraInfo) - { - if(this.Delegate == null || this.GrabDelegate == null) - { - throw new Exception("No Delegate"); - } - - // Dispatch grab action to server so that server can test if grab succeed. - // If grab succeed, server would update the grabbable's player for all clients - // Note: - // This check is done in update to counter the case of network lag - // if touch down and up is very quick, the shouldTryRelease might not trigger right at touch up, - // because information on grabbed grabbableID might not arrived yet - if (this.isTouching && this.GrabbedGrabbable == null) - { - if (GameTime.FrameCount % 3 == 0) // Only send messages at 20 fps to save bandwidth - { - // Send grab message to server if player can grab something - var grabbable = this.GrabbableToGrab(cameraInfo.Ray); - if (grabbable != null) - { - var grab = new GrabInfo(grabbable.GrabbableId, cameraInfo); - this.Delegate.DispatchActionToServer(new GameActionType { TryGrab = grab, Type = GameActionType.GActionType.TryGrab }); - return; - } - } - } - - if (this.GrabbedGrabbable != null) - { - if (!this.Delegate.IsServer) - { - // Client move the sling locally, ignore server's physics data to prevent lag - this.GrabbedGrabbable.Move(cameraInfo); - } - - // If touch is up or the sling is pulled too far, release the ball - if (!this.isTouching || this.GrabDelegate.ShouldForceRelease(this.GrabbedGrabbable)) - { - if (GameTime.FrameCount % 3 == 0)// Only send messages at 20 fps to save bandwidth - { - var grab = new GrabInfo(this.GrabbedGrabbable.GrabbableId, cameraInfo); - this.Delegate.DispatchActionToServer(new GameActionType { TryRelease = grab, Type = GameActionType.GActionType.TryRelease }); - return; - } - } - - // Dispatch slingMove to server. - var data = new GrabInfo(this.GrabbedGrabbable.GrabbableId, cameraInfo); - this.Delegate.DispatchActionToServer(new GameActionType { GrabMove = data, Type = GameActionType.GActionType.GrabMove }); - } - } - - private IGrabbable NearestVisibleGrabbable(Ray cameraRay) - { - // Find closest visible grabbable - IGrabbable closestGrabbable = null; - var closestDist = 0f; - foreach(var grabbable in this.Grabbables.Values) - { - if (grabbable.IsVisible) - { - var distance = grabbable.DistanceFrom(cameraRay.Position); - if (closestGrabbable == null || distance < closestDist) - { - closestGrabbable = grabbable; - closestDist = distance; - } - } - } - - return closestGrabbable; - } - - public IGrabbable GrabbableToGrab(Ray cameraRay) - { - IGrabbable result = null; - - var grabbable = this.NearestVisibleGrabbable(cameraRay); - if(grabbable != null) - { - if(grabbable.CanGrab(cameraRay)) - { - result = grabbable; - } - } - - return result; - } - - #region Interactions - - public void Handle(GameActionType gameAction, Player player) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - switch (gameAction.Type) - { - // Try Grab - case GameActionType.GActionType.TryGrab: - this.HandleTryGrabAction(gameAction.TryGrab, player, this.Delegate); - break; - - // Inform specific player of grab, when it succeeds - case GameActionType.GActionType.GrabStart: - this.HandleGrabStartAction(gameAction.GrabStart, player, this.Delegate); - break; - - // Sling Move - case GameActionType.GActionType.GrabMove: - this.HandleGrabMove(gameAction.GrabMove, player, this.Delegate); - break; - - // Try Release - case GameActionType.GActionType.TryRelease: - this.HandleTryReleaseAction(gameAction.TryRelease, player, this.Delegate); - break; - - // Inform specific player of release - case GameActionType.GActionType.ReleaseEnd: - this.HandleReleaseEndAction(gameAction.ReleaseEnd, player, this.Delegate); - break; - - // Update Grabbable Status - case GameActionType.GActionType.GrabbableStatus: - this.HandleGrabbableStatus(gameAction.GrabbableStatus); - break; - } - } - - #endregion - - #region Handle Actions - - private void HandleTryGrabAction(GrabInfo data, Player player, IInteractionDelegate @delegate) - { - if(this.GrabDelegate == null) - { - throw new Exception("GrabDelegate not set"); - } - - // since we can't send a message only to the server, make sure we're the server - // when processing. - if (@delegate.IsServer) - { - // Check if player already owned a grabbable - // This is to filter tryGrab messages a player might send because it has not received grab message yet - foreach(var value in this.Grabbables.Values) - { - if (value.Player != null && value.Player == player) - { - return; - } - } - - var grabbable = this.GrabbableById(data.GrabbableId); - this.GrabDelegate.OnServerGrab(grabbable, data.CameraInfo, player); - grabbable.Player = player; - - // Inform player that the grabbable was grabbed - var newData = new GrabInfo(grabbable.GrabbableId, data.CameraInfo); - @delegate.DispatchToPlayer(new GameActionType { GrabStart = newData, Type = GameActionType.GActionType.GrabStart }, player); - - // Update grabbable in the server and clients with a new status - // Note: status update only sends the information on whether - this.HandleGrabbableStatus(newData); - @delegate.ServerDispatchActionToAll(new GameActionType { GrabbableStatus = newData, Type = GameActionType.GActionType.GrabbableStatus }); - } - } - - private void HandleGrabStartAction(GrabInfo data, Player player, IInteractionDelegate @delegate) - { - if(this.GrabDelegate == null) - { - throw new Exception("GrabDelegate not set"); - } - - var grabbable = this.GrabbableById(data.GrabbableId); - this.GrabbedGrabbable = grabbable; - this.GrabDelegate.OnGrabStart(grabbable, data.CameraInfo, player); - } - - private void HandleTryReleaseAction(GrabInfo data, Player player, IInteractionDelegate @delegate) - { - if(this.GrabDelegate == null) - { - throw new Exception("GrabDelegate not set"); - } - - if (this.Delegate.IsServer) - { - // Launch if player already grabbed a grabbable - var grabbable = this.GrabbableById(data.GrabbableId); - if (grabbable.IsGrabbed) - { - this.GrabDelegate.OnServerRelease(grabbable, data.CameraInfo, player); - - // Inform player that the grabbable was grabbed - var newData = new GrabInfo(grabbable.GrabbableId, data.CameraInfo); - @delegate.DispatchToPlayer(new GameActionType { ReleaseEnd = newData, Type = GameActionType.GActionType.ReleaseEnd }, player); - } - } - } - - private void HandleReleaseEndAction(GrabInfo data, Player player, IInteractionDelegate @delegate) - { - this.isTouching = false; - } - - private void HandleGrabMove(GrabInfo data, Player player, IInteractionDelegate @delegate) - { - if (this.Grabbables.TryGetValue(data.GrabbableId, out IGrabbable grabbable)) - { - grabbable.Move(data.CameraInfo); - } - } - - private void HandleGrabbableStatus(GrabInfo status) - { - if(this.GrabDelegate == null) - { - throw new Exception("GrabDelegate not set"); - } - - if(!this.Grabbables.TryGetValue(status.GrabbableId, out IGrabbable grabbable)) - { - throw new Exception($"No Grabbable {status.GrabbableId}"); - } - - grabbable.IsGrabbed = true; - this.GrabDelegate.OnUpdateGrabStatus(grabbable, status.CameraInfo); - } - - #endregion - - #region Helper - - private IGrabbable GrabbableById(int grabbableId) - { - if(!this.Grabbables.TryGetValue(grabbableId, out IGrabbable grabbable)) - { - throw new Exception("Grabbable not found"); - } - - return grabbable; - } - - #endregion - - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Models.Interactions; + using System; + using System.Collections.Generic; + + public interface IGrabInteractionDelegate { + bool ShouldForceRelease (IGrabbable grabbable); + void OnServerGrab (IGrabbable grabbable, CameraInfo cameraInfo, Player player); + void OnGrabStart (IGrabbable grabbable, CameraInfo cameraInfo, Player player); + void OnServerRelease (IGrabbable grabbable, CameraInfo cameraInfo, Player player); + void OnUpdateGrabStatus (IGrabbable grabbable, CameraInfo cameraInfo); + } + + public class GrabInteraction : IInteraction { + private bool isTouching; + + // Index used to assign to new object + private int currentIndex = 0; + + public GrabInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; + } + + public IInteractionDelegate Delegate { get; private set; } + + public IGrabInteractionDelegate GrabDelegate { get; set; } + + public IGrabbable GrabbedGrabbable { get; set; } + + public Dictionary<int, IGrabbable> Grabbables { get; private set; } = new Dictionary<int, IGrabbable> (); + + /// <summary> + /// Should be added only from the classes using GrabInteraction to prevent duplicates + /// </summary> + public void AddGrabbable (IGrabbable grabbable) + { + grabbable.GrabbableId = this.currentIndex; + this.Grabbables [this.currentIndex] = grabbable; + this.currentIndex += 1; + } + + public void HandleTouch (TouchType type, Ray camera) + { + if (type == TouchType.Began) { + if (this.GrabbableToGrab (camera) != null) { + this.isTouching = true; + } + } else if (type == TouchType.Ended) { + this.isTouching = false; + } + } + + public void Update (CameraInfo cameraInfo) + { + if (this.Delegate == null || this.GrabDelegate == null) { + throw new Exception ("No Delegate"); + } + + // Dispatch grab action to server so that server can test if grab succeed. + // If grab succeed, server would update the grabbable's player for all clients + // Note: + // This check is done in update to counter the case of network lag + // if touch down and up is very quick, the shouldTryRelease might not trigger right at touch up, + // because information on grabbed grabbableID might not arrived yet + if (this.isTouching && this.GrabbedGrabbable == null) { + if (GameTime.FrameCount % 3 == 0) // Only send messages at 20 fps to save bandwidth + { + // Send grab message to server if player can grab something + var grabbable = this.GrabbableToGrab (cameraInfo.Ray); + if (grabbable != null) { + var grab = new GrabInfo (grabbable.GrabbableId, cameraInfo); + this.Delegate.DispatchActionToServer (new GameActionType { TryGrab = grab, Type = GameActionType.GActionType.TryGrab }); + return; + } + } + } + + if (this.GrabbedGrabbable != null) { + if (!this.Delegate.IsServer) { + // Client move the sling locally, ignore server's physics data to prevent lag + this.GrabbedGrabbable.Move (cameraInfo); + } + + // If touch is up or the sling is pulled too far, release the ball + if (!this.isTouching || this.GrabDelegate.ShouldForceRelease (this.GrabbedGrabbable)) { + if (GameTime.FrameCount % 3 == 0)// Only send messages at 20 fps to save bandwidth + { + var grab = new GrabInfo (this.GrabbedGrabbable.GrabbableId, cameraInfo); + this.Delegate.DispatchActionToServer (new GameActionType { TryRelease = grab, Type = GameActionType.GActionType.TryRelease }); + return; + } + } + + // Dispatch slingMove to server. + var data = new GrabInfo (this.GrabbedGrabbable.GrabbableId, cameraInfo); + this.Delegate.DispatchActionToServer (new GameActionType { GrabMove = data, Type = GameActionType.GActionType.GrabMove }); + } + } + + private IGrabbable NearestVisibleGrabbable (Ray cameraRay) + { + // Find closest visible grabbable + IGrabbable closestGrabbable = null; + var closestDist = 0f; + foreach (var grabbable in this.Grabbables.Values) { + if (grabbable.IsVisible) { + var distance = grabbable.DistanceFrom (cameraRay.Position); + if (closestGrabbable == null || distance < closestDist) { + closestGrabbable = grabbable; + closestDist = distance; + } + } + } + + return closestGrabbable; + } + + public IGrabbable GrabbableToGrab (Ray cameraRay) + { + IGrabbable result = null; + + var grabbable = this.NearestVisibleGrabbable (cameraRay); + if (grabbable != null) { + if (grabbable.CanGrab (cameraRay)) { + result = grabbable; + } + } + + return result; + } + + #region Interactions + + public void Handle (GameActionType gameAction, Player player) + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + switch (gameAction.Type) { + // Try Grab + case GameActionType.GActionType.TryGrab: + this.HandleTryGrabAction (gameAction.TryGrab, player, this.Delegate); + break; + + // Inform specific player of grab, when it succeeds + case GameActionType.GActionType.GrabStart: + this.HandleGrabStartAction (gameAction.GrabStart, player, this.Delegate); + break; + + // Sling Move + case GameActionType.GActionType.GrabMove: + this.HandleGrabMove (gameAction.GrabMove, player, this.Delegate); + break; + + // Try Release + case GameActionType.GActionType.TryRelease: + this.HandleTryReleaseAction (gameAction.TryRelease, player, this.Delegate); + break; + + // Inform specific player of release + case GameActionType.GActionType.ReleaseEnd: + this.HandleReleaseEndAction (gameAction.ReleaseEnd, player, this.Delegate); + break; + + // Update Grabbable Status + case GameActionType.GActionType.GrabbableStatus: + this.HandleGrabbableStatus (gameAction.GrabbableStatus); + break; + } + } + + #endregion + + #region Handle Actions + + private void HandleTryGrabAction (GrabInfo data, Player player, IInteractionDelegate @delegate) + { + if (this.GrabDelegate == null) { + throw new Exception ("GrabDelegate not set"); + } + + // since we can't send a message only to the server, make sure we're the server + // when processing. + if (@delegate.IsServer) { + // Check if player already owned a grabbable + // This is to filter tryGrab messages a player might send because it has not received grab message yet + foreach (var value in this.Grabbables.Values) { + if (value.Player != null && value.Player == player) { + return; + } + } + + var grabbable = this.GrabbableById (data.GrabbableId); + this.GrabDelegate.OnServerGrab (grabbable, data.CameraInfo, player); + grabbable.Player = player; + + // Inform player that the grabbable was grabbed + var newData = new GrabInfo (grabbable.GrabbableId, data.CameraInfo); + @delegate.DispatchToPlayer (new GameActionType { GrabStart = newData, Type = GameActionType.GActionType.GrabStart }, player); + + // Update grabbable in the server and clients with a new status + // Note: status update only sends the information on whether + this.HandleGrabbableStatus (newData); + @delegate.ServerDispatchActionToAll (new GameActionType { GrabbableStatus = newData, Type = GameActionType.GActionType.GrabbableStatus }); + } + } + + private void HandleGrabStartAction (GrabInfo data, Player player, IInteractionDelegate @delegate) + { + if (this.GrabDelegate == null) { + throw new Exception ("GrabDelegate not set"); + } + + var grabbable = this.GrabbableById (data.GrabbableId); + this.GrabbedGrabbable = grabbable; + this.GrabDelegate.OnGrabStart (grabbable, data.CameraInfo, player); + } + + private void HandleTryReleaseAction (GrabInfo data, Player player, IInteractionDelegate @delegate) + { + if (this.GrabDelegate == null) { + throw new Exception ("GrabDelegate not set"); + } + + if (this.Delegate.IsServer) { + // Launch if player already grabbed a grabbable + var grabbable = this.GrabbableById (data.GrabbableId); + if (grabbable.IsGrabbed) { + this.GrabDelegate.OnServerRelease (grabbable, data.CameraInfo, player); + + // Inform player that the grabbable was grabbed + var newData = new GrabInfo (grabbable.GrabbableId, data.CameraInfo); + @delegate.DispatchToPlayer (new GameActionType { ReleaseEnd = newData, Type = GameActionType.GActionType.ReleaseEnd }, player); + } + } + } + + private void HandleReleaseEndAction (GrabInfo data, Player player, IInteractionDelegate @delegate) + { + this.isTouching = false; + } + + private void HandleGrabMove (GrabInfo data, Player player, IInteractionDelegate @delegate) + { + if (this.Grabbables.TryGetValue (data.GrabbableId, out IGrabbable grabbable)) { + grabbable.Move (data.CameraInfo); + } + } + + private void HandleGrabbableStatus (GrabInfo status) + { + if (this.GrabDelegate == null) { + throw new Exception ("GrabDelegate not set"); + } + + if (!this.Grabbables.TryGetValue (status.GrabbableId, out IGrabbable grabbable)) { + throw new Exception ($"No Grabbable {status.GrabbableId}"); + } + + grabbable.IsGrabbed = true; + this.GrabDelegate.OnUpdateGrabStatus (grabbable, status.CameraInfo); + } + + #endregion + + #region Helper + + private IGrabbable GrabbableById (int grabbableId) + { + if (!this.Grabbables.TryGetValue (grabbableId, out IGrabbable grabbable)) { + throw new Exception ("Grabbable not found"); + } + + return grabbable; + } + + #endregion + + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/HighlightInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/HighlightInteraction.cs index 7e84556d5..4d4a619b9 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/HighlightInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/HighlightInteraction.cs @@ -1,75 +1,64 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using System.Linq; - public class HighlightInteraction : IInteraction - { - public HighlightInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; - } +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using System.Linq; - public IInteractionDelegate Delegate { get; private set; } + public class HighlightInteraction : IInteraction { + public HighlightInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; + } - public GrabInteraction GrabInteraction { get; set; } + public IInteractionDelegate Delegate { get; private set; } - public SFXCoordinator SfxCoordinator { get; set; } + public GrabInteraction GrabInteraction { get; set; } - public void Update(CameraInfo cameraInfo) - { - if(!UserDefaults.Spectator) - { - if(this.GrabInteraction == null) - { - throw new Exception("GrabInteraction not set"); - } + public SFXCoordinator SfxCoordinator { get; set; } - // Get the current nearest grabbable - var nearestGrabbable = this.GrabInteraction.GrabbableToGrab(cameraInfo.Ray); - var grabbables = this.GrabInteraction.Grabbables.Values; + public void Update (CameraInfo cameraInfo) + { + if (!UserDefaults.Spectator) { + if (this.GrabInteraction == null) { + throw new Exception ("GrabInteraction not set"); + } - // If player already grab something, we should turn off all highlight silently - if (this.GrabInteraction.GrabbedGrabbable != null) - { - foreach(var grabbable in grabbables.Where(item => item.IsHighlighted)) - { - grabbable.DoHighlight(false, null); - } + // Get the current nearest grabbable + var nearestGrabbable = this.GrabInteraction.GrabbableToGrab (cameraInfo.Ray); + var grabbables = this.GrabInteraction.Grabbables.Values; - return; - } + // If player already grab something, we should turn off all highlight silently + if (this.GrabInteraction.GrabbedGrabbable != null) { + foreach (var grabbable in grabbables.Where (item => item.IsHighlighted)) { + grabbable.DoHighlight (false, null); + } - // Turn on/off highlight with sound - foreach(var grabbable in grabbables) - { - var isNearestGrabbable = false; - if (nearestGrabbable != null && - grabbable.GrabbableId == nearestGrabbable.GrabbableId) - { - isNearestGrabbable = true; - } + return; + } - if (isNearestGrabbable && !grabbable.IsHighlighted) - { - grabbable.DoHighlight(true, this.SfxCoordinator); - } - else if (!isNearestGrabbable && grabbable.IsHighlighted) - { - grabbable.DoHighlight(false, this.SfxCoordinator); - } - } - } - } + // Turn on/off highlight with sound + foreach (var grabbable in grabbables) { + var isNearestGrabbable = false; + if (nearestGrabbable != null && + grabbable.GrabbableId == nearestGrabbable.GrabbableId) { + isNearestGrabbable = true; + } - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } + if (isNearestGrabbable && !grabbable.IsHighlighted) { + grabbable.DoHighlight (true, this.SfxCoordinator); + } else if (!isNearestGrabbable && grabbable.IsHighlighted) { + grabbable.DoHighlight (false, this.SfxCoordinator); + } + } + } + } - public void Handle(GameActionType gameAction, Player player) { } + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } - public void HandleTouch(TouchType type, Ray camera) { } - } -} \ No newline at end of file + public void Handle (GameActionType gameAction, Player player) { } + + public void HandleTouch (TouchType type, Ray camera) { } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/IGrabbable.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/IGrabbable.cs index 9006a93b2..ad4eef302 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/IGrabbable.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/IGrabbable.cs @@ -1,21 +1,19 @@ - -namespace XamarinShot.Models.Interactions -{ - using SceneKit; - public interface IGrabbable - { - int GrabbableId { get; set; } - Player Player { get; set; } - bool IsGrabbed { get; set; } +namespace XamarinShot.Models.Interactions { + using SceneKit; - bool IsVisible { get; set; } - bool IsHighlighted { get; } - void DoHighlight(bool show, SFXCoordinator sfxCoordinator); + public interface IGrabbable { + int GrabbableId { get; set; } + Player Player { get; set; } + bool IsGrabbed { get; set; } - bool CanGrab(Ray cameraRay); - float DistanceFrom(SCNVector3 worldPos); + bool IsVisible { get; set; } + bool IsHighlighted { get; } + void DoHighlight (bool show, SFXCoordinator sfxCoordinator); - void Move(CameraInfo cameraInfo); - } -} \ No newline at end of file + bool CanGrab (Ray cameraRay); + float DistanceFrom (SCNVector3 worldPos); + + void Move (CameraInfo cameraInfo); + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/IInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/IInteraction.cs index 4322e3aec..645a838fa 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/IInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/IInteraction.cs @@ -1,76 +1,72 @@ - -namespace XamarinShot.Models -{ - using System.Collections.Generic; - using SceneKit; - using XamarinShot.Models.Enums; - - public class GameRayCastHitInfo - { - public GameRayCastHitInfo(SCNVector3 position, SCNVector3 direction, IList<SCNHitTestResult> hits) - { - this.Position = position; - this.Direction = direction; - this.Hits = hits; - } - - public SCNVector3 Position { get; set; } - - public SCNVector3 Direction { get; set; } - - public IList<SCNHitTestResult> Hits { get; set; } - - public Ray Ray() - { - return new Ray(this.Position, this.Direction); - } - } - - public interface IInteractionDelegate - { - Player CurrentPlayer { get; } - SCNPhysicsWorld PhysicsWorld { get; } - IProjectileDelegate ProjectileDelegate { get; } - bool IsServer { get; } - List<GameObject> AllBlockObjects { get; } - List<Catapult> Catapults { get; } - - void RemoveTableBoxNodeFromLevel(); - - void AddNodeToLevel(SCNNode node); - Projectile SpawnProjectile(); - Projectile CreateProjectile(); // Create projectile without putting it into a pool, useful for using it to show when catapult gets pulled - int GameObjectPoolCount(); - void RemoveAllPhysicsBehaviors(); - - void AddInteraction(IInteraction interaction); - - void DispatchActionToServer(GameActionType gameAction); - void DispatchActionToAll(GameActionType gameAction); // including self - void ServerDispatchActionToAll(GameActionType gameAction); - void DispatchToPlayer(GameActionType gameAction, Player player); - - void PlayWinSound(); - void StartGameMusic(IInteraction interaction); - } - - public interface IInteraction - { - void Update(CameraInfo cameraInfo); - - /// <summary> - /// Handle Inputs - /// </summary> - void HandleTouch(TouchType type, Ray camera); - - /// <summary> - /// Handle Action - /// </summary> - void Handle(GameActionType gameAction, Player player); - - /// <summary> - /// Handle Collision - /// </summary> - void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse); - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using System.Collections.Generic; + using SceneKit; + using XamarinShot.Models.Enums; + + public class GameRayCastHitInfo { + public GameRayCastHitInfo (SCNVector3 position, SCNVector3 direction, IList<SCNHitTestResult> hits) + { + this.Position = position; + this.Direction = direction; + this.Hits = hits; + } + + public SCNVector3 Position { get; set; } + + public SCNVector3 Direction { get; set; } + + public IList<SCNHitTestResult> Hits { get; set; } + + public Ray Ray () + { + return new Ray (this.Position, this.Direction); + } + } + + public interface IInteractionDelegate { + Player CurrentPlayer { get; } + SCNPhysicsWorld PhysicsWorld { get; } + IProjectileDelegate ProjectileDelegate { get; } + bool IsServer { get; } + List<GameObject> AllBlockObjects { get; } + List<Catapult> Catapults { get; } + + void RemoveTableBoxNodeFromLevel (); + + void AddNodeToLevel (SCNNode node); + Projectile SpawnProjectile (); + Projectile CreateProjectile (); // Create projectile without putting it into a pool, useful for using it to show when catapult gets pulled + int GameObjectPoolCount (); + void RemoveAllPhysicsBehaviors (); + + void AddInteraction (IInteraction interaction); + + void DispatchActionToServer (GameActionType gameAction); + void DispatchActionToAll (GameActionType gameAction); // including self + void ServerDispatchActionToAll (GameActionType gameAction); + void DispatchToPlayer (GameActionType gameAction, Player player); + + void PlayWinSound (); + void StartGameMusic (IInteraction interaction); + } + + public interface IInteraction { + void Update (CameraInfo cameraInfo); + + /// <summary> + /// Handle Inputs + /// </summary> + void HandleTouch (TouchType type, Ray camera); + + /// <summary> + /// Handle Action + /// </summary> + void Handle (GameActionType gameAction, Player player); + + /// <summary> + /// Handle Collision + /// </summary> + void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 pos, float impulse); + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/InteractionManager.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/InteractionManager.cs index 9327e32ef..f623be932 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/InteractionManager.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/InteractionManager.cs @@ -1,79 +1,72 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using System; - using System.Collections.Generic; - /// <summary> - /// Abstract: - /// Manages user interactions. - /// </summary> - public class InteractionManager - { - private readonly Dictionary<int, IInteraction> interactions = new Dictionary<int, IInteraction>(); +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using System; + using System.Collections.Generic; - public void AddInteraction(IInteraction interaction) - { - var classIdentifier = interaction.GetType().GetHashCode(); - this.interactions[classIdentifier] = interaction; - } + /// <summary> + /// Abstract: + /// Manages user interactions. + /// </summary> + public class InteractionManager { + private readonly Dictionary<int, IInteraction> interactions = new Dictionary<int, IInteraction> (); - public IInteraction Interaction(Type interactionClass) - { - IInteraction result = null; + public void AddInteraction (IInteraction interaction) + { + var classIdentifier = interaction.GetType ().GetHashCode (); + this.interactions [classIdentifier] = interaction; + } - var classIdentifier = interactionClass.GetHashCode(); - if (this.interactions.TryGetValue(classIdentifier, out IInteraction interaction)) - { - result = interaction; - } + public IInteraction Interaction (Type interactionClass) + { + IInteraction result = null; - return result; - } + var classIdentifier = interactionClass.GetHashCode (); + if (this.interactions.TryGetValue (classIdentifier, out IInteraction interaction)) { + result = interaction; + } - public void RemoveAllInteractions() - { - this.interactions.Clear(); - } + return result; + } - public void UpdateAll(CameraInfo cameraInfo) - { - foreach (var interaction in this.interactions.Values) - { - interaction.Update(cameraInfo); - } - } + public void RemoveAllInteractions () + { + this.interactions.Clear (); + } - public void Handle(GameActionType gameAction, Player player) - { - foreach (var interaction in this.interactions.Values) - { - interaction.Handle(gameAction, player); - } - } + public void UpdateAll (CameraInfo cameraInfo) + { + foreach (var interaction in this.interactions.Values) { + interaction.Update (cameraInfo); + } + } - #region Touch Event Routing + public void Handle (GameActionType gameAction, Player player) + { + foreach (var interaction in this.interactions.Values) { + interaction.Handle (gameAction, player); + } + } - public void HandleTouch(TouchType type, Ray camera) - { - foreach (var interaction in this.interactions.Values) - { - interaction.HandleTouch(type, camera); - } - } + #region Touch Event Routing - public void DidCollision(SCNNode nodeA, SCNNode nodeB, SCNVector3 position, float impulse) - { - foreach (var interaction in this.interactions.Values) - { - // nodeA and nodeB take turn to be the main node - interaction.DidCollision(nodeA, nodeB, position, impulse); - interaction.DidCollision(nodeB, nodeA, position, impulse); - } - } + public void HandleTouch (TouchType type, Ray camera) + { + foreach (var interaction in this.interactions.Values) { + interaction.HandleTouch (type, camera); + } + } - #endregion - } -} \ No newline at end of file + public void DidCollision (SCNNode nodeA, SCNNode nodeB, SCNVector3 position, float impulse) + { + foreach (var interaction in this.interactions.Values) { + // nodeA and nodeB take turn to be the main node + interaction.DidCollision (nodeA, nodeB, position, impulse); + interaction.DidCollision (nodeB, nodeA, position, impulse); + } + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/LeverInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/LeverInteraction.cs index ceb2b9e68..61a1fcf66 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/LeverInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/LeverInteraction.cs @@ -1,173 +1,142 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Models.GameplayState; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - - public interface ILeverInteractionDelegate - { - bool IsActivated { get; } - void Activate(); - } - - public class LeverInteraction : IInteraction - { - private const float LeverHighlightDistance = 2.5f; - private const float LeverPullZtoLeverEulerRotation = 1f; - private const float LeverSpringBackSpeed = 2f; - private const float LeverMaxEulerX = (float)Math.PI / 6f; - - private readonly List<ResetSwitchComponent> resetSwitches = new List<ResetSwitchComponent>(); - - private SCNVector3 startLeverHoldCameraPosition = SCNVector3.Zero; - private ResetSwitchComponent activeSwitch; - private ResetSwitchComponent highlightedSwitch; - private float startLeverEulerX; - - public LeverInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; - } - - public IInteractionDelegate Delegate { get; private set; } - - public ILeverInteractionDelegate InteractionToActivate { get; private set; } - - public SFXCoordinator SfxCoordinator { get; set; } - - public void Setup(List<GameObject> resetSwitches, ILeverInteractionDelegate interactionToActivate) - { - foreach(var @object in resetSwitches) - { - if (@object.GetComponent(typeof(ResetSwitchComponent)) is ResetSwitchComponent resetComponent) - { - this.resetSwitches.Add(resetComponent); - } - } - - this.InteractionToActivate = interactionToActivate; - } - - public void HandleTouch(TouchType type, Ray camera) - { - if (type == TouchType.Began) - { - if (this.highlightedSwitch != null) - { - this.startLeverHoldCameraPosition = camera.Position; - this.startLeverEulerX = this.highlightedSwitch.Angle; - this.activeSwitch = this.highlightedSwitch; - } - } - else if (type == TouchType.Ended) - { - this.activeSwitch = null; - } - } - - public void Handle(GameActionType gameAction, Player player) - { - // Move the lever to received position unless this player is already holding a lever - if (gameAction.Type == GameActionType.GActionType.LeverMove) - { - if(this.resetSwitches.Count > gameAction.LeverMove.LeverId) - { - if (this.activeSwitch != this.resetSwitches[gameAction.LeverMove.LeverId]) - { - this.resetSwitches[gameAction.LeverMove.LeverId].Angle = gameAction.LeverMove.EulerAngleX; - } - } - else - { - throw new Exception("resetSwitches does not match across network"); - } - } - } - - public void Update(CameraInfo cameraInfo) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - // Do not move the lever after it has been activated - if(!(this.InteractionToActivate?.IsActivated ?? false)) - { - if (this.activeSwitch != null) - { - // Lever Pulling - var cameraOffset = this.activeSwitch.PullOffset(cameraInfo.Ray.Position - this.startLeverHoldCameraPosition); - var cameraMovedZ = cameraOffset.Z; - - var targetEulerX = this.startLeverEulerX + LeverPullZtoLeverEulerRotation * cameraMovedZ; - targetEulerX = DigitExtensions.Clamp(-LeverMaxEulerX, targetEulerX, LeverMaxEulerX); - this.activeSwitch.Angle = targetEulerX; - - if (targetEulerX <= -LeverMaxEulerX) - { - // Interaction activation once the switch lever is turned all the way - this.InteractionToActivate?.Activate(); - - // Fade out the switches - var waitAction = SCNAction.Wait(3f); - var fadeAction = SCNAction.FadeOut(3d); - - foreach(var resetSwitch in this.resetSwitches) - { - resetSwitch.Base.RunAction(SCNAction.Sequence(new SCNAction[] { waitAction, fadeAction })); - } - return; - } - else - { - // Inform peers of the movement - var leverId = this.resetSwitches.IndexOf(this.activeSwitch); - if(leverId == -1) - { - throw new Exception("No lever in array"); - } - - this.Delegate.DispatchActionToServer(new GameActionType { LeverMove = new LeverMove(leverId, targetEulerX), Type = GameActionType.GActionType.LeverMove }); - } - } - else - { - // Lever spring back - foreach(var lever in this.resetSwitches.Where(lever => lever.Angle < LeverMaxEulerX)) - { - lever.Angle = Math.Min(LeverMaxEulerX, lever.Angle + LeverSpringBackSpeed * (float)GameTime.DeltaTime); - } - } - - // Highlight lever when nearby, otherwise check if we should hide the highlight - if (this.highlightedSwitch != null) - { - if (!this.highlightedSwitch.ShouldHighlight(cameraInfo.Ray)) - { - this.highlightedSwitch.DoHighlight(false, this.SfxCoordinator); - this.highlightedSwitch = null; - } - } - else - { - foreach(var resetSwitch in this.resetSwitches ) - { - if (resetSwitch.ShouldHighlight(cameraInfo.Ray)) - { - resetSwitch.DoHighlight(true, this.SfxCoordinator); - this.highlightedSwitch = resetSwitch; - } - } - } - } - } - - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Models.GameplayState; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + public interface ILeverInteractionDelegate { + bool IsActivated { get; } + void Activate (); + } + + public class LeverInteraction : IInteraction { + private const float LeverHighlightDistance = 2.5f; + private const float LeverPullZtoLeverEulerRotation = 1f; + private const float LeverSpringBackSpeed = 2f; + private const float LeverMaxEulerX = (float) Math.PI / 6f; + + private readonly List<ResetSwitchComponent> resetSwitches = new List<ResetSwitchComponent> (); + + private SCNVector3 startLeverHoldCameraPosition = SCNVector3.Zero; + private ResetSwitchComponent activeSwitch; + private ResetSwitchComponent highlightedSwitch; + private float startLeverEulerX; + + public LeverInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; + } + + public IInteractionDelegate Delegate { get; private set; } + + public ILeverInteractionDelegate InteractionToActivate { get; private set; } + + public SFXCoordinator SfxCoordinator { get; set; } + + public void Setup (List<GameObject> resetSwitches, ILeverInteractionDelegate interactionToActivate) + { + foreach (var @object in resetSwitches) { + if (@object.GetComponent (typeof (ResetSwitchComponent)) is ResetSwitchComponent resetComponent) { + this.resetSwitches.Add (resetComponent); + } + } + + this.InteractionToActivate = interactionToActivate; + } + + public void HandleTouch (TouchType type, Ray camera) + { + if (type == TouchType.Began) { + if (this.highlightedSwitch != null) { + this.startLeverHoldCameraPosition = camera.Position; + this.startLeverEulerX = this.highlightedSwitch.Angle; + this.activeSwitch = this.highlightedSwitch; + } + } else if (type == TouchType.Ended) { + this.activeSwitch = null; + } + } + + public void Handle (GameActionType gameAction, Player player) + { + // Move the lever to received position unless this player is already holding a lever + if (gameAction.Type == GameActionType.GActionType.LeverMove) { + if (this.resetSwitches.Count > gameAction.LeverMove.LeverId) { + if (this.activeSwitch != this.resetSwitches [gameAction.LeverMove.LeverId]) { + this.resetSwitches [gameAction.LeverMove.LeverId].Angle = gameAction.LeverMove.EulerAngleX; + } + } else { + throw new Exception ("resetSwitches does not match across network"); + } + } + } + + public void Update (CameraInfo cameraInfo) + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + // Do not move the lever after it has been activated + if (!(this.InteractionToActivate?.IsActivated ?? false)) { + if (this.activeSwitch != null) { + // Lever Pulling + var cameraOffset = this.activeSwitch.PullOffset (cameraInfo.Ray.Position - this.startLeverHoldCameraPosition); + var cameraMovedZ = cameraOffset.Z; + + var targetEulerX = this.startLeverEulerX + LeverPullZtoLeverEulerRotation * cameraMovedZ; + targetEulerX = DigitExtensions.Clamp (-LeverMaxEulerX, targetEulerX, LeverMaxEulerX); + this.activeSwitch.Angle = targetEulerX; + + if (targetEulerX <= -LeverMaxEulerX) { + // Interaction activation once the switch lever is turned all the way + this.InteractionToActivate?.Activate (); + + // Fade out the switches + var waitAction = SCNAction.Wait (3f); + var fadeAction = SCNAction.FadeOut (3d); + + foreach (var resetSwitch in this.resetSwitches) { + resetSwitch.Base.RunAction (SCNAction.Sequence (new SCNAction [] { waitAction, fadeAction })); + } + return; + } else { + // Inform peers of the movement + var leverId = this.resetSwitches.IndexOf (this.activeSwitch); + if (leverId == -1) { + throw new Exception ("No lever in array"); + } + + this.Delegate.DispatchActionToServer (new GameActionType { LeverMove = new LeverMove (leverId, targetEulerX), Type = GameActionType.GActionType.LeverMove }); + } + } else { + // Lever spring back + foreach (var lever in this.resetSwitches.Where (lever => lever.Angle < LeverMaxEulerX)) { + lever.Angle = Math.Min (LeverMaxEulerX, lever.Angle + LeverSpringBackSpeed * (float) GameTime.DeltaTime); + } + } + + // Highlight lever when nearby, otherwise check if we should hide the highlight + if (this.highlightedSwitch != null) { + if (!this.highlightedSwitch.ShouldHighlight (cameraInfo.Ray)) { + this.highlightedSwitch.DoHighlight (false, this.SfxCoordinator); + this.highlightedSwitch = null; + } + } else { + foreach (var resetSwitch in this.resetSwitches) { + if (resetSwitch.ShouldHighlight (cameraInfo.Ray)) { + resetSwitch.DoHighlight (true, this.SfxCoordinator); + this.highlightedSwitch = resetSwitch; + } + } + } + } + } + + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/Projectile.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/Projectile.cs index 5f0e4d7ed..e43109449 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/Projectile.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/Projectile.cs @@ -1,178 +1,158 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - - public interface IProjectileDelegate - { - bool IsServer { get; } - void AddParticles(SCNNode particlesNode, SCNVector3 worldPosition); - void DespawnProjectile(Projectile projectile); - void AddNodeToLevel(SCNNode node); - } - - public class Projectile : GameObject - { - // Projectile life time should be set so that projectiles will not be depleted from the pool - private const double FadeTimeToLifeTimeRatio = 0.1d; - - private Team team = Team.None; - - private double startTime; - - private bool isLaunched; - - private double lifeTime; - - public Projectile() { } - - public Projectile(SCNNode node, int? index, Dictionary<string, object> gamedefs, bool isAlive, bool isServer) : base(node, index, gamedefs, false, false) { } - - public Projectile(NSCoder coder) => throw new Exception("init(coder:) has not been implemented"); - - public double Age => this.isLaunched ? (GameTime.Time - this.startTime) : 0d; - - protected double FadeStartTime => this.lifeTime * (1d - FadeTimeToLifeTimeRatio); - - public IProjectileDelegate Delegate { get; set; } - - public SCNPhysicsBody PhysicsBody { get; set; } - - public Team Team - { - get - { - return this.team; - } - - set - { - this.team = value; - - // we assume the geometry and lod are unique to geometry and lod here - if (this.GeometryNode?.Geometry?.FirstMaterial?.Diffuse != null) - { - this.GeometryNode.Geometry.FirstMaterial.Diffuse.Contents = team.GetColor(); - } - - var levelsOfDetail = this.GeometryNode?.Geometry?.LevelsOfDetail; - if (levelsOfDetail != null) - { - foreach(var lod in levelsOfDetail) - { - if (lod.Geometry?.FirstMaterial?.Diffuse.Contents != null) - { - lod.Geometry.FirstMaterial.Diffuse.Contents = team.GetColor(); - } - } - } - } - } - public static T Create<T>(SCNNode prototypeNode, int? index, Dictionary<string, object> gamedefs) where T : Projectile, new() - { - var node = prototypeNode.Clone(); - // geometry and materials are reference types, so here we - // do a deep copy. that way, each projectile gets its own color. - node.CopyGeometryAndMaterials(); - - var physicsNode = node.FindNodeWithPhysicsBody(); - if(physicsNode?.PhysicsBody == null) - { - throw new Exception("Projectile node has no physics"); - } - - physicsNode.PhysicsBody.ContactTestBitMask = (int)(CollisionMask.RigidBody | CollisionMask.GlitterObject | CollisionMask.TriggerVolume); - physicsNode.PhysicsBody.CategoryBitMask = (int)CollisionMask.Ball; - - var result = GameObject.Create<T>(node, index, gamedefs, false, false); - result.PhysicsNode = physicsNode; - result.PhysicsBody = physicsNode.PhysicsBody; - - return result; - } - - public static T Create<T>(SCNNode prototypeNode) where T : Projectile, new() { return Projectile.Create<T>(prototypeNode, null, new Dictionary<string, object>()); } - - public virtual void Launch(GameVelocity velocity, double lifeTime, IProjectileDelegate @delegate) - { - this.startTime = GameTime.Time; - this.isLaunched = true; - this.lifeTime = lifeTime; - this.Delegate = @delegate; - - if (this.PhysicsNode != null && this.PhysicsBody != null) - { - this.PhysicsBody.VelocityFactor = SCNVector3.One; - this.PhysicsBody.AngularVelocityFactor = SCNVector3.One; - this.PhysicsBody.Velocity = velocity.Vector; - this.PhysicsNode.Name = "ball"; - this.PhysicsNode.WorldPosition = velocity.Origin; - this.PhysicsBody.ResetTransform(); - } - else - { - throw new System.Exception("Projectile not setup"); - } - } - - public virtual void OnDidApplyConstraints(ISCNSceneRenderer renderer) { } - - public void DidBeginContact(SCNPhysicsContact contact) { } - - public virtual void OnSpawn() { } - - public override void Update(double deltaTimeInSeconds) - { - base.Update(deltaTimeInSeconds); - - // Projectile should fade and disappear after a while - if (this.Age > this.lifeTime) - { - this.ObjectRootNode.Opacity = 1f; - this.Despawn(); - } - else if (this.Age > this.FadeStartTime) - { - this.ObjectRootNode.Opacity = (float)(1f - (this.Age - this.FadeStartTime) / (this.lifeTime - this.FadeStartTime)); - } - } - - public virtual void Despawn() - { - if(this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - this.Delegate.DespawnProjectile(this); - } - - public override PhysicsNodeData GeneratePhysicsData() - { - var data = base.GeneratePhysicsData(); - if (data != null) - { - data.Team = team; - } - - return data; - } - } - - /// <summary> - /// Chicken example of how we make a new projectile type - /// </summary> - public class ChickenProjectile : Projectile - { - public ChickenProjectile() { } - - public static ChickenProjectile Create(SCNNode prototypeNode) { return Projectile.Create<ChickenProjectile>(prototypeNode); } - - public static ChickenProjectile Create(SCNNode prototypeNode, int? index, Dictionary<string, object> gamedefs) { return Projectile.Create<ChickenProjectile>(prototypeNode, index, gamedefs); } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + + public interface IProjectileDelegate { + bool IsServer { get; } + void AddParticles (SCNNode particlesNode, SCNVector3 worldPosition); + void DespawnProjectile (Projectile projectile); + void AddNodeToLevel (SCNNode node); + } + + public class Projectile : GameObject { + // Projectile life time should be set so that projectiles will not be depleted from the pool + private const double FadeTimeToLifeTimeRatio = 0.1d; + + private Team team = Team.None; + + private double startTime; + + private bool isLaunched; + + private double lifeTime; + + public Projectile () { } + + public Projectile (SCNNode node, int? index, Dictionary<string, object> gamedefs, bool isAlive, bool isServer) : base (node, index, gamedefs, false, false) { } + + public Projectile (NSCoder coder) => throw new Exception ("init(coder:) has not been implemented"); + + public double Age => this.isLaunched ? (GameTime.Time - this.startTime) : 0d; + + protected double FadeStartTime => this.lifeTime * (1d - FadeTimeToLifeTimeRatio); + + public IProjectileDelegate Delegate { get; set; } + + public SCNPhysicsBody PhysicsBody { get; set; } + + public Team Team { + get { + return this.team; + } + + set { + this.team = value; + + // we assume the geometry and lod are unique to geometry and lod here + if (this.GeometryNode?.Geometry?.FirstMaterial?.Diffuse != null) { + this.GeometryNode.Geometry.FirstMaterial.Diffuse.Contents = team.GetColor (); + } + + var levelsOfDetail = this.GeometryNode?.Geometry?.LevelsOfDetail; + if (levelsOfDetail != null) { + foreach (var lod in levelsOfDetail) { + if (lod.Geometry?.FirstMaterial?.Diffuse.Contents != null) { + lod.Geometry.FirstMaterial.Diffuse.Contents = team.GetColor (); + } + } + } + } + } + public static T Create<T> (SCNNode prototypeNode, int? index, Dictionary<string, object> gamedefs) where T : Projectile, new() + { + var node = prototypeNode.Clone (); + // geometry and materials are reference types, so here we + // do a deep copy. that way, each projectile gets its own color. + node.CopyGeometryAndMaterials (); + + var physicsNode = node.FindNodeWithPhysicsBody (); + if (physicsNode?.PhysicsBody == null) { + throw new Exception ("Projectile node has no physics"); + } + + physicsNode.PhysicsBody.ContactTestBitMask = (int) (CollisionMask.RigidBody | CollisionMask.GlitterObject | CollisionMask.TriggerVolume); + physicsNode.PhysicsBody.CategoryBitMask = (int) CollisionMask.Ball; + + var result = GameObject.Create<T> (node, index, gamedefs, false, false); + result.PhysicsNode = physicsNode; + result.PhysicsBody = physicsNode.PhysicsBody; + + return result; + } + + public static T Create<T> (SCNNode prototypeNode) where T : Projectile, new() { return Projectile.Create<T> (prototypeNode, null, new Dictionary<string, object> ()); } + + public virtual void Launch (GameVelocity velocity, double lifeTime, IProjectileDelegate @delegate) + { + this.startTime = GameTime.Time; + this.isLaunched = true; + this.lifeTime = lifeTime; + this.Delegate = @delegate; + + if (this.PhysicsNode != null && this.PhysicsBody != null) { + this.PhysicsBody.VelocityFactor = SCNVector3.One; + this.PhysicsBody.AngularVelocityFactor = SCNVector3.One; + this.PhysicsBody.Velocity = velocity.Vector; + this.PhysicsNode.Name = "ball"; + this.PhysicsNode.WorldPosition = velocity.Origin; + this.PhysicsBody.ResetTransform (); + } else { + throw new System.Exception ("Projectile not setup"); + } + } + + public virtual void OnDidApplyConstraints (ISCNSceneRenderer renderer) { } + + public void DidBeginContact (SCNPhysicsContact contact) { } + + public virtual void OnSpawn () { } + + public override void Update (double deltaTimeInSeconds) + { + base.Update (deltaTimeInSeconds); + + // Projectile should fade and disappear after a while + if (this.Age > this.lifeTime) { + this.ObjectRootNode.Opacity = 1f; + this.Despawn (); + } else if (this.Age > this.FadeStartTime) { + this.ObjectRootNode.Opacity = (float) (1f - (this.Age - this.FadeStartTime) / (this.lifeTime - this.FadeStartTime)); + } + } + + public virtual void Despawn () + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + this.Delegate.DespawnProjectile (this); + } + + public override PhysicsNodeData GeneratePhysicsData () + { + var data = base.GeneratePhysicsData (); + if (data != null) { + data.Team = team; + } + + return data; + } + } + + /// <summary> + /// Chicken example of how we make a new projectile type + /// </summary> + public class ChickenProjectile : Projectile { + public ChickenProjectile () { } + + public static ChickenProjectile Create (SCNNode prototypeNode) { return Projectile.Create<ChickenProjectile> (prototypeNode); } + + public static ChickenProjectile Create (SCNNode prototypeNode, int? index, Dictionary<string, object> gamedefs) { return Projectile.Create<ChickenProjectile> (prototypeNode, index, gamedefs); } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/TrailBallProjectile.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/TrailBallProjectile.cs index 13e60d866..27331a71a 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/TrailBallProjectile.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/TrailBallProjectile.cs @@ -1,197 +1,180 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - public class TrailBallProjectile : Projectile - { - public const float DefaultTrailWidth = 0.5f; // Default trail with with ball size as the unit (1.0 represents same width as the ball) - - public const int DefaultTrailLength = 108; - - private const float Epsilon = 1.19209290E-07f; // upper limit on float rounding error - - // default values the result of a vast user study. - private const float BallSize = 0.275f; - - private readonly List<SCNVector3> worldPositions = new List<SCNVector3>(); - - private readonly List<SCNVector3> tempWorldPositions = new List<SCNVector3>(); - - private readonly List<SCNVector4> colors = new List<SCNVector4>(); - - private readonly SCNNode trailNode = new SCNNode(); - - - public TrailBallProjectile() { } - - public TrailBallProjectile(SCNNode node, int? index, Dictionary<string, object> gamedefs, bool isAlive, bool isServer) : base(node, index, gamedefs, isAlive, isServer) { } - - - public float TrailHalfWidth => (UserDefaults.TrailWidth ?? TrailBallProjectile.DefaultTrailWidth) * BallSize * 0.5f; - - public int MaxTrailPositions => UserDefaults.TrailLength ?? TrailBallProjectile.DefaultTrailLength; - - public bool TrailShouldNarrow => UserDefaults.TrailShouldNarrow; - - public static TrailBallProjectile Create(SCNNode prototypeNode, int? index, Dictionary<string, object> gamedefs) { return Projectile.Create<TrailBallProjectile>(prototypeNode, index, gamedefs); } - - public static TrailBallProjectile Create(SCNNode prototypeNode) { return Projectile.Create<TrailBallProjectile>(prototypeNode); } - - public override void Launch(GameVelocity velocity, double lifeTime, IProjectileDelegate @delegate) - { - base.Launch(velocity, lifeTime, @delegate); - this.AddTrail(); - } - - public override void OnSpawn() - { - base.OnSpawn(); - this.AddTrail(); - } - - public override void Despawn() - { - base.Despawn(); - this.RemoveTrail(); - } - - private void AddTrail() - { - if (this.PhysicsNode != null) - { - this.trailNode.CastsShadow = false; - if (this.PhysicsNode.PhysicsBody != null) - { - this.PhysicsNode.PhysicsBody.AngularDamping = 1f; - } - - if (this.Delegate != null) - { - this.Delegate.AddNodeToLevel(this.trailNode); - } - } - } - - private void RemoveTrail() - { - this.trailNode.RemoveFromParentNode(); - } - - public override void OnDidApplyConstraints(ISCNSceneRenderer renderer) - { - var frameSkips = 3; - if ((GameTime.FrameCount + this.Index) % frameSkips == 0) - { - if (this.PhysicsNode != null) - { - if (this.worldPositions.Count > (this.MaxTrailPositions / frameSkips)) - { - this.RemoveVerticesPair(); - } - - var position = this.PhysicsNode.PresentationNode.WorldPosition; - - SCNVector3 trailDir; - if (this.worldPositions.Any()) - { - var previousPosition = this.worldPositions.LastOrDefault(); - trailDir = position - previousPosition; - - var lengthSquared = trailDir.LengthSquared; - if (lengthSquared < Epsilon) - { - this.RemoveVerticesPair(); - this.UpdateColors(); - var tempPositions = this.tempWorldPositions.Select(tempPosition => this.trailNode.PresentationNode.ConvertPositionFromNode(tempPosition, null)).ToList(); - this.trailNode.PresentationNode.Geometry = this.CreateTrailMesh(tempPositions, this.colors); - return; - } - - trailDir = SCNVector3.Normalize(trailDir); - } - else - { - trailDir = this.ObjectRootNode.WorldFront; - } - - var right = SCNVector3.Cross(SCNVector3.UnitY, trailDir); - right = SCNVector3.Normalize(right); - var scale = 1f; //Float(i - 1) / worldPositions.count - var halfWidth = this.TrailHalfWidth; - if (this.TrailShouldNarrow) - { - halfWidth *= scale; - } - - var u = position + right * halfWidth; - var v = position - right * halfWidth; - - this.worldPositions.Add(position); - this.tempWorldPositions.Add(u); - this.tempWorldPositions.Add(v); - - this.colors.Add(SCNVector4.Zero); - this.colors.Add(SCNVector4.Zero); - - this.UpdateColors(); - var localPositions = this.tempWorldPositions.Select(tempPosition => this.trailNode.PresentationNode.ConvertPositionFromNode(tempPosition, null)).ToList(); - this.trailNode.PresentationNode.Geometry = this.CreateTrailMesh(localPositions, this.colors); - } - } - } - - private void RemoveVerticesPair() - { - this.worldPositions.RemoveAt(0); - this.tempWorldPositions.RemoveRange(0, 2); - this.colors.RemoveRange(0, 2); - } - - private void UpdateColors() - { - var baseColor = SimdExtensions.CreateVector4(this.Team.GetColor()); - for (var i = 0; i < this.colors.Count; i++) - { - var scale = (float)i / (float)this.colors.Count; - this.colors[i] = baseColor * scale; - } - } - - private SCNGeometry CreateTrailMesh(List<SCNVector3> positions, List<SCNVector4> colors) - { - SCNGeometry result = null; - if (positions.Count >= 4) - { - var array = new byte[positions.Count]; - for (byte i = 0; i < positions.Count; i++) - { - array[i] = i; - } - - var positionSource = SCNGeometrySource.FromVertices(positions.ToArray()); - var colorSource = SCNGeometrySourceExtensions.Create(colors); - var element = SCNGeometryElement.FromData(NSData.FromArray(array), SCNGeometryPrimitiveType.TriangleStrip, positions.Count - 2, 2); - result = SCNGeometry.Create(new SCNGeometrySource[] { positionSource, colorSource }, new SCNGeometryElement[] { element }); - - var material = result.FirstMaterial; - if (material == null) - { - throw new Exception("created geometry without material"); - } - - material.DoubleSided = true; - material.LightingModelName = SCNLightingModel.Constant; - material.BlendMode = SCNBlendMode.Add; - material.WritesToDepthBuffer = false; - } - - return result; - } - } -} \ No newline at end of file +namespace XamarinShot.Models { + using Foundation; + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + public class TrailBallProjectile : Projectile { + public const float DefaultTrailWidth = 0.5f; // Default trail with with ball size as the unit (1.0 represents same width as the ball) + + public const int DefaultTrailLength = 108; + + private const float Epsilon = 1.19209290E-07f; // upper limit on float rounding error + + // default values the result of a vast user study. + private const float BallSize = 0.275f; + + private readonly List<SCNVector3> worldPositions = new List<SCNVector3> (); + + private readonly List<SCNVector3> tempWorldPositions = new List<SCNVector3> (); + + private readonly List<SCNVector4> colors = new List<SCNVector4> (); + + private readonly SCNNode trailNode = new SCNNode (); + + + public TrailBallProjectile () { } + + public TrailBallProjectile (SCNNode node, int? index, Dictionary<string, object> gamedefs, bool isAlive, bool isServer) : base (node, index, gamedefs, isAlive, isServer) { } + + + public float TrailHalfWidth => (UserDefaults.TrailWidth ?? TrailBallProjectile.DefaultTrailWidth) * BallSize * 0.5f; + + public int MaxTrailPositions => UserDefaults.TrailLength ?? TrailBallProjectile.DefaultTrailLength; + + public bool TrailShouldNarrow => UserDefaults.TrailShouldNarrow; + + public static TrailBallProjectile Create (SCNNode prototypeNode, int? index, Dictionary<string, object> gamedefs) { return Projectile.Create<TrailBallProjectile> (prototypeNode, index, gamedefs); } + + public static TrailBallProjectile Create (SCNNode prototypeNode) { return Projectile.Create<TrailBallProjectile> (prototypeNode); } + + public override void Launch (GameVelocity velocity, double lifeTime, IProjectileDelegate @delegate) + { + base.Launch (velocity, lifeTime, @delegate); + this.AddTrail (); + } + + public override void OnSpawn () + { + base.OnSpawn (); + this.AddTrail (); + } + + public override void Despawn () + { + base.Despawn (); + this.RemoveTrail (); + } + + private void AddTrail () + { + if (this.PhysicsNode != null) { + this.trailNode.CastsShadow = false; + if (this.PhysicsNode.PhysicsBody != null) { + this.PhysicsNode.PhysicsBody.AngularDamping = 1f; + } + + if (this.Delegate != null) { + this.Delegate.AddNodeToLevel (this.trailNode); + } + } + } + + private void RemoveTrail () + { + this.trailNode.RemoveFromParentNode (); + } + + public override void OnDidApplyConstraints (ISCNSceneRenderer renderer) + { + var frameSkips = 3; + if ((GameTime.FrameCount + this.Index) % frameSkips == 0) { + if (this.PhysicsNode != null) { + if (this.worldPositions.Count > (this.MaxTrailPositions / frameSkips)) { + this.RemoveVerticesPair (); + } + + var position = this.PhysicsNode.PresentationNode.WorldPosition; + + SCNVector3 trailDir; + if (this.worldPositions.Any ()) { + var previousPosition = this.worldPositions.LastOrDefault (); + trailDir = position - previousPosition; + + var lengthSquared = trailDir.LengthSquared; + if (lengthSquared < Epsilon) { + this.RemoveVerticesPair (); + this.UpdateColors (); + var tempPositions = this.tempWorldPositions.Select (tempPosition => this.trailNode.PresentationNode.ConvertPositionFromNode (tempPosition, null)).ToList (); + this.trailNode.PresentationNode.Geometry = this.CreateTrailMesh (tempPositions, this.colors); + return; + } + + trailDir = SCNVector3.Normalize (trailDir); + } else { + trailDir = this.ObjectRootNode.WorldFront; + } + + var right = SCNVector3.Cross (SCNVector3.UnitY, trailDir); + right = SCNVector3.Normalize (right); + var scale = 1f; //Float(i - 1) / worldPositions.count + var halfWidth = this.TrailHalfWidth; + if (this.TrailShouldNarrow) { + halfWidth *= scale; + } + + var u = position + right * halfWidth; + var v = position - right * halfWidth; + + this.worldPositions.Add (position); + this.tempWorldPositions.Add (u); + this.tempWorldPositions.Add (v); + + this.colors.Add (SCNVector4.Zero); + this.colors.Add (SCNVector4.Zero); + + this.UpdateColors (); + var localPositions = this.tempWorldPositions.Select (tempPosition => this.trailNode.PresentationNode.ConvertPositionFromNode (tempPosition, null)).ToList (); + this.trailNode.PresentationNode.Geometry = this.CreateTrailMesh (localPositions, this.colors); + } + } + } + + private void RemoveVerticesPair () + { + this.worldPositions.RemoveAt (0); + this.tempWorldPositions.RemoveRange (0, 2); + this.colors.RemoveRange (0, 2); + } + + private void UpdateColors () + { + var baseColor = SimdExtensions.CreateVector4 (this.Team.GetColor ()); + for (var i = 0; i < this.colors.Count; i++) { + var scale = (float) i / (float) this.colors.Count; + this.colors [i] = baseColor * scale; + } + } + + private SCNGeometry CreateTrailMesh (List<SCNVector3> positions, List<SCNVector4> colors) + { + SCNGeometry result = null; + if (positions.Count >= 4) { + var array = new byte [positions.Count]; + for (byte i = 0; i < positions.Count; i++) { + array [i] = i; + } + + var positionSource = SCNGeometrySource.FromVertices (positions.ToArray ()); + var colorSource = SCNGeometrySourceExtensions.Create (colors); + var element = SCNGeometryElement.FromData (NSData.FromArray (array), SCNGeometryPrimitiveType.TriangleStrip, positions.Count - 2, 2); + result = SCNGeometry.Create (new SCNGeometrySource [] { positionSource, colorSource }, new SCNGeometryElement [] { element }); + + var material = result.FirstMaterial; + if (material == null) { + throw new Exception ("created geometry without material"); + } + + material.DoubleSided = true; + material.LightingModelName = SCNLightingModel.Constant; + material.BlendMode = SCNBlendMode.Add; + material.WritesToDepthBuffer = false; + } + + return result; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/VictoryInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/VictoryInteraction.cs index 6bbfc2948..0e2f37fd9 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/VictoryInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/VictoryInteraction.cs @@ -1,141 +1,120 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - using System.Linq; - - public class VictoryInteraction : IInteraction - { - private const double TimeUntilPhysicsReleased = 10d; - - private const double FadeTime = 0.5d; - - private readonly NSLock @lock = new NSLock(); // need thread protection because main thread is the one that called didWin() - - private readonly SCNNode victoryNode; - - private Team teamWon = Team.None; - - private double activationStartTime; - - public VictoryInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; - this.victoryNode = SCNNodeExtensions.LoadSCNAsset("victory"); - } - - public IInteractionDelegate Delegate { get; private set; } - - public bool DisplayedVictory { get; private set; } - - public bool GameDone { get; private set; } - - public void ActivateVictory() - { - if (!this.DisplayedVictory) - { - this.@lock.Lock(); - - if(this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - this.Delegate.AddNodeToLevel(this.victoryNode); - this.victoryNode.WorldPosition = new SCNVector3(0f, 15f, 0f); - - var eulerAnglesY = teamWon == Team.TeamA ? (float)Math.PI : 0f; // Rotate Victory to face in the right direction - this.victoryNode.EulerAngles = new SCNVector3(this.victoryNode.EulerAngles.X, eulerAnglesY, this.victoryNode.EulerAngles.Z); - foreach(var child in this.victoryNode.ChildNodes) - { - child.PhysicsBody?.ResetTransform(); - } - - this.DisplayedVictory = true; - this.activationStartTime = GameTime.Time; - - // Set color to that of winning team - this.victoryNode.SetPaintColors(this.teamWon); - - this.Delegate.PlayWinSound(); - - this.@lock.Unlock(); - } - } - - public void Update(CameraInfo cameraInfo) - { - if (this.DisplayedVictory) - { - // Enlarge victory text before falling down - this.victoryNode.Opacity = (float)(DigitExtensions.Clamp((GameTime.Time - this.activationStartTime) / FadeTime, 0d, 1d)); - - if (GameTime.Time - this.activationStartTime > TimeUntilPhysicsReleased) - { - foreach(var child in this.victoryNode.ChildNodes) - { - if (child.PhysicsBody != null) - { - child.PhysicsBody.VelocityFactor = SCNVector3.One; - child.PhysicsBody.AngularVelocityFactor = SCNVector3.One; - } - } - } - } - else - { - // Update win condition - if (this.DidWin() && this.teamWon != Team.None) - { - this.ActivateVictory(); - } - } - } - - public void HandleTouch(TouchType type, Ray camera) { } - - private bool DidWin() - { - if(this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - var catapults = this.Delegate.Catapults; - - var teamToCatapultCount = new int[] { 0, 0, 0 }; - foreach(var catapult in catapults.Where(catapult => !catapult.Disabled)) - { - teamToCatapultCount[(int)catapult.Team] += 1; - } - - var gameDone = true; - if (teamToCatapultCount[1] == 0 && teamToCatapultCount[2] == 0) - { - this.teamWon = Team.None; - } - else if (teamToCatapultCount[1] == 0) - { - this.teamWon = Team.TeamB; - } - else if (teamToCatapultCount[2] == 0) - { - this.teamWon = Team.TeamA; - } - else - { - gameDone = false; - } - - return gameDone; - } - - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } - - public void Handle(GameActionType gameAction, Player player) { } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + using System.Linq; + + public class VictoryInteraction : IInteraction { + private const double TimeUntilPhysicsReleased = 10d; + + private const double FadeTime = 0.5d; + + private readonly NSLock @lock = new NSLock (); // need thread protection because main thread is the one that called didWin() + + private readonly SCNNode victoryNode; + + private Team teamWon = Team.None; + + private double activationStartTime; + + public VictoryInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; + this.victoryNode = SCNNodeExtensions.LoadSCNAsset ("victory"); + } + + public IInteractionDelegate Delegate { get; private set; } + + public bool DisplayedVictory { get; private set; } + + public bool GameDone { get; private set; } + + public void ActivateVictory () + { + if (!this.DisplayedVictory) { + this.@lock.Lock (); + + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + this.Delegate.AddNodeToLevel (this.victoryNode); + this.victoryNode.WorldPosition = new SCNVector3 (0f, 15f, 0f); + + var eulerAnglesY = teamWon == Team.TeamA ? (float) Math.PI : 0f; // Rotate Victory to face in the right direction + this.victoryNode.EulerAngles = new SCNVector3 (this.victoryNode.EulerAngles.X, eulerAnglesY, this.victoryNode.EulerAngles.Z); + foreach (var child in this.victoryNode.ChildNodes) { + child.PhysicsBody?.ResetTransform (); + } + + this.DisplayedVictory = true; + this.activationStartTime = GameTime.Time; + + // Set color to that of winning team + this.victoryNode.SetPaintColors (this.teamWon); + + this.Delegate.PlayWinSound (); + + this.@lock.Unlock (); + } + } + + public void Update (CameraInfo cameraInfo) + { + if (this.DisplayedVictory) { + // Enlarge victory text before falling down + this.victoryNode.Opacity = (float) (DigitExtensions.Clamp ((GameTime.Time - this.activationStartTime) / FadeTime, 0d, 1d)); + + if (GameTime.Time - this.activationStartTime > TimeUntilPhysicsReleased) { + foreach (var child in this.victoryNode.ChildNodes) { + if (child.PhysicsBody != null) { + child.PhysicsBody.VelocityFactor = SCNVector3.One; + child.PhysicsBody.AngularVelocityFactor = SCNVector3.One; + } + } + } + } else { + // Update win condition + if (this.DidWin () && this.teamWon != Team.None) { + this.ActivateVictory (); + } + } + } + + public void HandleTouch (TouchType type, Ray camera) { } + + private bool DidWin () + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + var catapults = this.Delegate.Catapults; + + var teamToCatapultCount = new int [] { 0, 0, 0 }; + foreach (var catapult in catapults.Where (catapult => !catapult.Disabled)) { + teamToCatapultCount [(int) catapult.Team] += 1; + } + + var gameDone = true; + if (teamToCatapultCount [1] == 0 && teamToCatapultCount [2] == 0) { + this.teamWon = Team.None; + } else if (teamToCatapultCount [1] == 0) { + this.teamWon = Team.TeamB; + } else if (teamToCatapultCount [2] == 0) { + this.teamWon = Team.TeamA; + } else { + gameDone = false; + } + + return gameDone; + } + + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } + + public void Handle (GameActionType gameAction, Player player) { } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Interactions/VortexInteraction.cs b/ios12/XamarinShot/XamarinShot/Core/Interactions/VortexInteraction.cs index 2c42d7eb1..7d4a3f205 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Interactions/VortexInteraction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Interactions/VortexInteraction.cs @@ -1,450 +1,413 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System; - - public interface IVortexActivationDelegate - { - void VortexDidActivate(VortexInteraction vortex); - } - - public class VortexInteraction : IInteraction, ILeverInteractionDelegate - { - private const double VortexAnimationDuration = 11.5d; - private const double LiftStageStartTime = 1d; - private const double LiftStageEndTime = 3d; - - private double startInitialFloatTime; - private double startVortexTime; - - private State state = State.None; - - // Chasm - private SCNVector3 chasmFinalScale = new SCNVector3(0.96f, 1f, 0.96f); - private readonly SCNNode chasmPhysics; - private SCNNode chasmExpandObject; - - // Vortex Cylinder's shape represents vortex shape, and is used to animate vortex - private SCNNode vortexCylinder; - - public VortexInteraction(IInteractionDelegate @delegate) - { - this.Delegate = @delegate; - - // Chasm Occluder Box: that will take over the table occluder once table occluder is removed for Vortex Interaction - var vortex = SCNNodeExtensions.LoadSCNAsset("chasm_animation"); - - // Chasm - this.chasmPhysics = vortex.FindChildNode("chasm", true); - if(this.chasmPhysics == null) - { - throw new Exception("Vortex has no chasm"); - } - - foreach(var child in this.chasmPhysics.ChildNodes) - { - if (!String.IsNullOrEmpty(child.Name) && child.Name.StartsWith("occluder", StringComparison.Ordinal)) - { - child.SetNodeToOccluder(); - } - } - - this.chasmPhysics.WorldPosition = new SCNVector3(0f, -0.1f, 0f); // avoid z-fight with ShadowPlane - this.chasmPhysics.Scale = this.chasmFinalScale; - this.chasmPhysics.StopAllAnimations(); - } - - /// <summary> - /// Stage time - /// </summary> - protected double TimeSinceInitialFloatStart => GameTime.Time - this.startInitialFloatTime; - - protected double TimeSinceVortexStart => GameTime.Time - this.startVortexTime; - - public bool IsActivated => this.state != State.None; - - public IInteractionDelegate Delegate { get; private set; } - - public IVortexActivationDelegate VortexActivationDelegate { get; set; } - - public SFXCoordinator SfxCoordinator { get; set; } - - public MusicCoordinator MusicCoordinator { get; set; } - - public void Activate() - { - if(this.Delegate == null) - { - throw new Exception("No delegate"); - } - - this.Delegate.DispatchActionToServer(new GameActionType { Type = GameActionType.GActionType.OneHitKOAnimate }); - } - - public void Handle(GameActionType gameAction, Player player) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - if (gameAction.Type == GameActionType.GActionType.OneHitKOAnimate && this.state == State.None) - { - this.state = State.InitialWait; - this.startInitialFloatTime = GameTime.Time; - - this.Delegate.RemoveTableBoxNodeFromLevel(); - this.Delegate.RemoveAllPhysicsBehaviors(); - - // Kill all catapults - this.VortexActivationDelegate?.VortexDidActivate(this); - this.SetBlocksToNoGravity(); - - this.Delegate.ServerDispatchActionToAll(new GameActionType { Type = GameActionType.GActionType.OneHitKOAnimate }); - - if (this.SfxCoordinator != null) - { - this.SfxCoordinator.PlayAudioFile("vortex_04", 0.5f, false); - } - - if (this.MusicCoordinator != null) - { - this.MusicCoordinator.StopCurrentMusic(2d); - } - } - } - - public void Update(CameraInfo cameraInfo) - { - this.UpdateVortexState(); - } - - private void UpdateVortexState() - { - switch (this.state) - { - case State.None: - break; - - case State.InitialWait: - if (this.TimeSinceInitialFloatStart > LiftStageStartTime) - { - this.PrepareForVortexAnimationStart(); - this.state = State.AnimateLift; - } - break; - - case State.AnimateLift: - if (this.TimeSinceInitialFloatStart > LiftStageEndTime) - { - this.PrepareForVortexAnimationEnded(); - this.state = State.AnimateVortex; - } - break; - - case State.AnimateVortex: - if (this.TimeSinceVortexStart < VortexAnimationDuration) - { - this.AnimateVortex(); - } - else - { - this.OnVortexAnimationEnded(); - this.state = State.None; - } - break; - } - } - - #region Animate Vortex - - // Stable vortex (values found through experimentation) - private const float RadialSpringConstant = 100f; - private const float TangentVelocitySpringContant = 40f; - private const float MaxVelocity = 3f; - - private const float MaxRandomVortexTorque = 0f; - private const double MaxRandomVortexForce = 0.2d; - - private SCNVector3 lastFront = new SCNVector3(0f, 0f, -1f); - private float lastVortexCenterY = 0f; - private float lastVortexHeight = 0f; - private float lastOuterRadius = 0f; - - public void AnimateVortex() - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - if (this.vortexCylinder == null) - { - throw new Exception("Vortex animation cylinder not set"); - } - - // Vortex shape from animation - var vortexShape = this.vortexCylinder.PresentationNode.Scale; - var vortexHeightDelta = vortexShape.Y - this.lastVortexHeight; - this.lastVortexHeight = vortexShape.Y; - - var vortexCenterY = this.vortexCylinder.PresentationNode.WorldPosition.Y; - var vortexCenterYDelta = vortexCenterY - this.lastVortexCenterY; - this.lastVortexCenterY = vortexCenterY; - - // Deform shape over time - var maxOuterRadius = vortexShape.X; - var maxInnerRadius = maxOuterRadius * 0.2f; // 20 % from experiment - var maxOuterRadiusDelta = maxOuterRadius - this.lastOuterRadius; - this.lastOuterRadius = maxOuterRadius; - - // Orbital velocity - var currentFront = this.vortexCylinder.PresentationNode.WorldFront; - var orbitalMoveDelta = (currentFront - this.lastFront).Length * maxInnerRadius; - this.lastFront = currentFront; - - var orbitalVelocityFactor = 5f; - var orbitalVelocity = (orbitalMoveDelta / (float)GameTime.DeltaTime) * orbitalVelocityFactor; - - var topBound = vortexCenterY + vortexShape.Y * 0.5f; - var bottomBound = vortexCenterY - vortexShape.Y * 0.5f; - - var blockObjects = this.Delegate.AllBlockObjects; - var up = SCNVector3.UnitY; - foreach (var block in blockObjects) - { - if (block.PhysicsNode?.PhysicsBody != null) - { - var position = block.PhysicsNode.PresentationNode.WorldPosition; - var positionWithoutY = new SCNVector3(position.X, 0f, position.Z); - var distanceFromCenter = positionWithoutY.Length; - var directionToCenter = -SCNVector3.Normalize(positionWithoutY); - - // Adjust radius into curve - // Equation representing a half radius chord of circle equation - var normalizedY = DigitExtensions.Clamp(position.Y / topBound, 0f, 1f); - var radiusFactor = (float)Math.Sqrt(4f - 3f * normalizedY * normalizedY) - 1f; - radiusFactor = radiusFactor * 0.8f + 0.2f; - var innerRadius = maxInnerRadius * radiusFactor; - var outerRadius = maxOuterRadius * radiusFactor; - - // Cap velocity - var maxVelocity = 30f; - if (block.PhysicsNode.PhysicsBody.Velocity.Length > maxVelocity) - { - block.PhysicsNode.PhysicsBody.Velocity = SCNVector3.Normalize(block.PhysicsNode.PhysicsBody.Velocity) * maxVelocity; - } - - var force = SCNVector3.Zero; - - // Stage specific manipulation - var vortexDirection = SCNVector3.Cross(directionToCenter, up); - var speedInVortexDirection = SCNVector3.Dot(block.PhysicsNode.PhysicsBody.Velocity, vortexDirection); - - // Stable vortex pull - var pullForceMagnitude = (speedInVortexDirection * speedInVortexDirection) * (float)(block.PhysicsNode.PhysicsBody.Mass) / distanceFromCenter; - force += pullForceMagnitude * directionToCenter; - - // Pull into outer radius - var radialInwardForceMagnitude = RadialSpringConstant * (float)Math.Max(0d, distanceFromCenter - outerRadius); - force += radialInwardForceMagnitude * directionToCenter; - - // Pull away from inner radius - var radialOutwardForceMagnitude = RadialSpringConstant * (float)Math.Max(0d, innerRadius - distanceFromCenter); - force += -radialOutwardForceMagnitude * directionToCenter; - - // Vortex velocity adjustment - if (distanceFromCenter > innerRadius) - { - var tangentForceMagnitude = TangentVelocitySpringContant * (speedInVortexDirection - orbitalVelocity); - force += -tangentForceMagnitude * vortexDirection * (0.5f + (float)(random.NextDouble() * 1d)); - } - - // Random forces/torque - force += force.Length * (float)((random.NextDouble() * 2d - 1d) * MaxRandomVortexForce) * up; - this.ApplyRandomTorque(block.PhysicsNode.PhysicsBody, MaxRandomVortexTorque); - - // Top bound pull down - var topBoundForceMagnitude = RadialSpringConstant * (float)Math.Max(0d, position.Y - topBound); - force += topBoundForceMagnitude * -up; - - // Bottom bound pull up - var bottomBoundForceMagnitude = RadialSpringConstant * (float)Math.Max(0d, bottomBound - position.Y); - force += bottomBoundForceMagnitude * up; - - block.PhysicsNode.PhysicsBody.ApplyForce(force, false); - - // Scale the vortex - // The higher position in the bound, more it should move upward to scale the vortex - var normalizedPositionInBoundY = DigitExtensions.Clamp((position.Y - bottomBound) / vortexShape.Y, 0f, 1f); - var heightMoveFactor = Math.Abs(normalizedPositionInBoundY - 0.5f); - var newPositionY = position.Y + vortexCenterYDelta + vortexHeightDelta * heightMoveFactor; - - var positionXZ = new SCNVector3(position.X, 0f, position.Z); - var radialMoveFactor = DigitExtensions.Clamp(distanceFromCenter / outerRadius, 0f, 1f); - var newPositionXZ = positionXZ + maxOuterRadiusDelta * radialMoveFactor * -directionToCenter; - - block.PhysicsNode.WorldPosition = new SCNVector3(newPositionXZ.X, newPositionY, newPositionXZ.Z); - block.PhysicsNode.WorldOrientation = block.PhysicsNode.PresentationNode.WorldOrientation; - block.PhysicsNode.PhysicsBody.ResetTransform(); - } - } - } - - public void HandleTouch(TouchType type, Ray camera) { } - - #endregion - - #region Prepare for Vortex - - private const float MaxInitialImpulse = 3f; - private const float MaxInitialTorque = 1f; // Found through experimentation - - private void SetBlocksToNoGravity() - { - this.EnumerateThroughBlocks((physicsBody) => - { - physicsBody.AffectedByGravity = false; - }); - } - - private Random random = new Random(); - - private void PrepareForVortexAnimationStart() - { - this.EnumerateThroughBlocks((physicsBody) => - { - physicsBody.AffectedByGravity = false; - var initialImpulse = MaxInitialImpulse * (float)(random.NextDouble() * 0.7d + 0.3d); - physicsBody.ApplyForce(new SCNVector3(0f, initialImpulse, 0f), true); - - this.ApplyRandomTorque(physicsBody, MaxInitialTorque); - - physicsBody.Damping = 0.4f; - }); - } - - private void PrepareForVortexAnimationEnded() - { - if(this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - this.EnumerateThroughBlocks((physicsBody) => - { - physicsBody.Damping = 0.1f; - }); - - // Chasm Expand Object (used for animation) - var vortex = SCNNodeExtensions.LoadSCNAsset("chasm_animation"); - this.vortexCylinder = vortex.FindChildNode("Cylinder", true); - if(this.vortexCylinder == null) - { - throw new Exception("Vortex has no cone"); - } - - this.Delegate.AddNodeToLevel(this.vortexCylinder); - this.vortexCylinder.StopAllAnimations(); - this.vortexCylinder.PlayAllAnimations(); - this.vortexCylinder.Hidden = true; // Vortex Cylinder is only used for deriving the vortex shape animation - - // Chasm Expand Object (used for animation) - this.chasmExpandObject = vortex.FindChildNode("chasm", true); - if(this.chasmExpandObject == null) - { - throw new Exception("Vortex has no chasm"); - } - - foreach(var child in this.chasmExpandObject.ChildNodes) - { - if (!string.IsNullOrEmpty(child.Name) && child.Name.StartsWith("occluder", StringComparison.Ordinal)) - { - child.SetNodeToOccluder(); - } - } - - this.Delegate.AddNodeToLevel(this.chasmExpandObject); - this.chasmExpandObject.StopAllAnimations(); - this.chasmExpandObject.PlayAllAnimations(); - - var vortexShape = this.vortexCylinder.PresentationNode.Scale; - this.lastOuterRadius = vortexShape.X; - this.lastVortexCenterY = this.vortexCylinder.PresentationNode.WorldPosition.Y; - this.lastVortexHeight = vortexShape.Y; - this.lastFront = this.vortexCylinder.PresentationNode.WorldFront; - - this.startVortexTime = GameTime.Time; - } - - private void OnVortexAnimationEnded() - { - // Remove or hide everything - this.vortexCylinder?.StopAllAnimations(); - this.vortexCylinder?.RemoveFromParentNode(); - this.chasmExpandObject?.RemoveFromParentNode(); - - if(this.Delegate == null) - { - throw new Exception("No delegate"); - } - - var blockObjects = this.Delegate.AllBlockObjects; - foreach(var block in blockObjects) - { - block.ObjectRootNode.Hidden = true; - } - } - - private void EnumerateThroughBlocks(Action<SCNPhysicsBody> physicsFunction) - { - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - var blockObjects = this.Delegate.AllBlockObjects; - foreach(var block in blockObjects) - { - if (block.PhysicsNode?.PhysicsBody != null) - { - physicsFunction(block.PhysicsNode.PhysicsBody); - } - } - } - - #endregion - - #region Helper Function - - private void ApplyRandomTorque(SCNPhysicsBody physicsBody, float maxTorque) - { - var randomAxis = new SCNVector3((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()); - randomAxis = SCNVector3.Normalize(randomAxis); - - var randomTorque = new SCNVector4(randomAxis, (float)(random.NextDouble() * 2d - 1d) * maxTorque); - physicsBody.ApplyTorque(randomTorque, true); - } - - private float StageProgress(double startTime, double endTime) - { - var progress = (float)((this.TimeSinceInitialFloatStart - startTime) / (endTime - startTime)); - return DigitExtensions.Clamp(progress, 0f, 1f); - } - - #endregion - - public void DidCollision(SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } - - enum State - { - None, - InitialWait, - AnimateLift, - AnimateVortex - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System; + + public interface IVortexActivationDelegate { + void VortexDidActivate (VortexInteraction vortex); + } + + public class VortexInteraction : IInteraction, ILeverInteractionDelegate { + private const double VortexAnimationDuration = 11.5d; + private const double LiftStageStartTime = 1d; + private const double LiftStageEndTime = 3d; + + private double startInitialFloatTime; + private double startVortexTime; + + private State state = State.None; + + // Chasm + private SCNVector3 chasmFinalScale = new SCNVector3 (0.96f, 1f, 0.96f); + private readonly SCNNode chasmPhysics; + private SCNNode chasmExpandObject; + + // Vortex Cylinder's shape represents vortex shape, and is used to animate vortex + private SCNNode vortexCylinder; + + public VortexInteraction (IInteractionDelegate @delegate) + { + this.Delegate = @delegate; + + // Chasm Occluder Box: that will take over the table occluder once table occluder is removed for Vortex Interaction + var vortex = SCNNodeExtensions.LoadSCNAsset ("chasm_animation"); + + // Chasm + this.chasmPhysics = vortex.FindChildNode ("chasm", true); + if (this.chasmPhysics == null) { + throw new Exception ("Vortex has no chasm"); + } + + foreach (var child in this.chasmPhysics.ChildNodes) { + if (!String.IsNullOrEmpty (child.Name) && child.Name.StartsWith ("occluder", StringComparison.Ordinal)) { + child.SetNodeToOccluder (); + } + } + + this.chasmPhysics.WorldPosition = new SCNVector3 (0f, -0.1f, 0f); // avoid z-fight with ShadowPlane + this.chasmPhysics.Scale = this.chasmFinalScale; + this.chasmPhysics.StopAllAnimations (); + } + + /// <summary> + /// Stage time + /// </summary> + protected double TimeSinceInitialFloatStart => GameTime.Time - this.startInitialFloatTime; + + protected double TimeSinceVortexStart => GameTime.Time - this.startVortexTime; + + public bool IsActivated => this.state != State.None; + + public IInteractionDelegate Delegate { get; private set; } + + public IVortexActivationDelegate VortexActivationDelegate { get; set; } + + public SFXCoordinator SfxCoordinator { get; set; } + + public MusicCoordinator MusicCoordinator { get; set; } + + public void Activate () + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + this.Delegate.DispatchActionToServer (new GameActionType { Type = GameActionType.GActionType.OneHitKOAnimate }); + } + + public void Handle (GameActionType gameAction, Player player) + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + if (gameAction.Type == GameActionType.GActionType.OneHitKOAnimate && this.state == State.None) { + this.state = State.InitialWait; + this.startInitialFloatTime = GameTime.Time; + + this.Delegate.RemoveTableBoxNodeFromLevel (); + this.Delegate.RemoveAllPhysicsBehaviors (); + + // Kill all catapults + this.VortexActivationDelegate?.VortexDidActivate (this); + this.SetBlocksToNoGravity (); + + this.Delegate.ServerDispatchActionToAll (new GameActionType { Type = GameActionType.GActionType.OneHitKOAnimate }); + + if (this.SfxCoordinator != null) { + this.SfxCoordinator.PlayAudioFile ("vortex_04", 0.5f, false); + } + + if (this.MusicCoordinator != null) { + this.MusicCoordinator.StopCurrentMusic (2d); + } + } + } + + public void Update (CameraInfo cameraInfo) + { + this.UpdateVortexState (); + } + + private void UpdateVortexState () + { + switch (this.state) { + case State.None: + break; + + case State.InitialWait: + if (this.TimeSinceInitialFloatStart > LiftStageStartTime) { + this.PrepareForVortexAnimationStart (); + this.state = State.AnimateLift; + } + break; + + case State.AnimateLift: + if (this.TimeSinceInitialFloatStart > LiftStageEndTime) { + this.PrepareForVortexAnimationEnded (); + this.state = State.AnimateVortex; + } + break; + + case State.AnimateVortex: + if (this.TimeSinceVortexStart < VortexAnimationDuration) { + this.AnimateVortex (); + } else { + this.OnVortexAnimationEnded (); + this.state = State.None; + } + break; + } + } + + #region Animate Vortex + + // Stable vortex (values found through experimentation) + private const float RadialSpringConstant = 100f; + private const float TangentVelocitySpringContant = 40f; + private const float MaxVelocity = 3f; + + private const float MaxRandomVortexTorque = 0f; + private const double MaxRandomVortexForce = 0.2d; + + private SCNVector3 lastFront = new SCNVector3 (0f, 0f, -1f); + private float lastVortexCenterY = 0f; + private float lastVortexHeight = 0f; + private float lastOuterRadius = 0f; + + public void AnimateVortex () + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + if (this.vortexCylinder == null) { + throw new Exception ("Vortex animation cylinder not set"); + } + + // Vortex shape from animation + var vortexShape = this.vortexCylinder.PresentationNode.Scale; + var vortexHeightDelta = vortexShape.Y - this.lastVortexHeight; + this.lastVortexHeight = vortexShape.Y; + + var vortexCenterY = this.vortexCylinder.PresentationNode.WorldPosition.Y; + var vortexCenterYDelta = vortexCenterY - this.lastVortexCenterY; + this.lastVortexCenterY = vortexCenterY; + + // Deform shape over time + var maxOuterRadius = vortexShape.X; + var maxInnerRadius = maxOuterRadius * 0.2f; // 20 % from experiment + var maxOuterRadiusDelta = maxOuterRadius - this.lastOuterRadius; + this.lastOuterRadius = maxOuterRadius; + + // Orbital velocity + var currentFront = this.vortexCylinder.PresentationNode.WorldFront; + var orbitalMoveDelta = (currentFront - this.lastFront).Length * maxInnerRadius; + this.lastFront = currentFront; + + var orbitalVelocityFactor = 5f; + var orbitalVelocity = (orbitalMoveDelta / (float) GameTime.DeltaTime) * orbitalVelocityFactor; + + var topBound = vortexCenterY + vortexShape.Y * 0.5f; + var bottomBound = vortexCenterY - vortexShape.Y * 0.5f; + + var blockObjects = this.Delegate.AllBlockObjects; + var up = SCNVector3.UnitY; + foreach (var block in blockObjects) { + if (block.PhysicsNode?.PhysicsBody != null) { + var position = block.PhysicsNode.PresentationNode.WorldPosition; + var positionWithoutY = new SCNVector3 (position.X, 0f, position.Z); + var distanceFromCenter = positionWithoutY.Length; + var directionToCenter = -SCNVector3.Normalize (positionWithoutY); + + // Adjust radius into curve + // Equation representing a half radius chord of circle equation + var normalizedY = DigitExtensions.Clamp (position.Y / topBound, 0f, 1f); + var radiusFactor = (float) Math.Sqrt (4f - 3f * normalizedY * normalizedY) - 1f; + radiusFactor = radiusFactor * 0.8f + 0.2f; + var innerRadius = maxInnerRadius * radiusFactor; + var outerRadius = maxOuterRadius * radiusFactor; + + // Cap velocity + var maxVelocity = 30f; + if (block.PhysicsNode.PhysicsBody.Velocity.Length > maxVelocity) { + block.PhysicsNode.PhysicsBody.Velocity = SCNVector3.Normalize (block.PhysicsNode.PhysicsBody.Velocity) * maxVelocity; + } + + var force = SCNVector3.Zero; + + // Stage specific manipulation + var vortexDirection = SCNVector3.Cross (directionToCenter, up); + var speedInVortexDirection = SCNVector3.Dot (block.PhysicsNode.PhysicsBody.Velocity, vortexDirection); + + // Stable vortex pull + var pullForceMagnitude = (speedInVortexDirection * speedInVortexDirection) * (float) (block.PhysicsNode.PhysicsBody.Mass) / distanceFromCenter; + force += pullForceMagnitude * directionToCenter; + + // Pull into outer radius + var radialInwardForceMagnitude = RadialSpringConstant * (float) Math.Max (0d, distanceFromCenter - outerRadius); + force += radialInwardForceMagnitude * directionToCenter; + + // Pull away from inner radius + var radialOutwardForceMagnitude = RadialSpringConstant * (float) Math.Max (0d, innerRadius - distanceFromCenter); + force += -radialOutwardForceMagnitude * directionToCenter; + + // Vortex velocity adjustment + if (distanceFromCenter > innerRadius) { + var tangentForceMagnitude = TangentVelocitySpringContant * (speedInVortexDirection - orbitalVelocity); + force += -tangentForceMagnitude * vortexDirection * (0.5f + (float) (random.NextDouble () * 1d)); + } + + // Random forces/torque + force += force.Length * (float) ((random.NextDouble () * 2d - 1d) * MaxRandomVortexForce) * up; + this.ApplyRandomTorque (block.PhysicsNode.PhysicsBody, MaxRandomVortexTorque); + + // Top bound pull down + var topBoundForceMagnitude = RadialSpringConstant * (float) Math.Max (0d, position.Y - topBound); + force += topBoundForceMagnitude * -up; + + // Bottom bound pull up + var bottomBoundForceMagnitude = RadialSpringConstant * (float) Math.Max (0d, bottomBound - position.Y); + force += bottomBoundForceMagnitude * up; + + block.PhysicsNode.PhysicsBody.ApplyForce (force, false); + + // Scale the vortex + // The higher position in the bound, more it should move upward to scale the vortex + var normalizedPositionInBoundY = DigitExtensions.Clamp ((position.Y - bottomBound) / vortexShape.Y, 0f, 1f); + var heightMoveFactor = Math.Abs (normalizedPositionInBoundY - 0.5f); + var newPositionY = position.Y + vortexCenterYDelta + vortexHeightDelta * heightMoveFactor; + + var positionXZ = new SCNVector3 (position.X, 0f, position.Z); + var radialMoveFactor = DigitExtensions.Clamp (distanceFromCenter / outerRadius, 0f, 1f); + var newPositionXZ = positionXZ + maxOuterRadiusDelta * radialMoveFactor * -directionToCenter; + + block.PhysicsNode.WorldPosition = new SCNVector3 (newPositionXZ.X, newPositionY, newPositionXZ.Z); + block.PhysicsNode.WorldOrientation = block.PhysicsNode.PresentationNode.WorldOrientation; + block.PhysicsNode.PhysicsBody.ResetTransform (); + } + } + } + + public void HandleTouch (TouchType type, Ray camera) { } + + #endregion + + #region Prepare for Vortex + + private const float MaxInitialImpulse = 3f; + private const float MaxInitialTorque = 1f; // Found through experimentation + + private void SetBlocksToNoGravity () + { + this.EnumerateThroughBlocks ((physicsBody) => { + physicsBody.AffectedByGravity = false; + }); + } + + private Random random = new Random (); + + private void PrepareForVortexAnimationStart () + { + this.EnumerateThroughBlocks ((physicsBody) => { + physicsBody.AffectedByGravity = false; + var initialImpulse = MaxInitialImpulse * (float) (random.NextDouble () * 0.7d + 0.3d); + physicsBody.ApplyForce (new SCNVector3 (0f, initialImpulse, 0f), true); + + this.ApplyRandomTorque (physicsBody, MaxInitialTorque); + + physicsBody.Damping = 0.4f; + }); + } + + private void PrepareForVortexAnimationEnded () + { + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + this.EnumerateThroughBlocks ((physicsBody) => { + physicsBody.Damping = 0.1f; + }); + + // Chasm Expand Object (used for animation) + var vortex = SCNNodeExtensions.LoadSCNAsset ("chasm_animation"); + this.vortexCylinder = vortex.FindChildNode ("Cylinder", true); + if (this.vortexCylinder == null) { + throw new Exception ("Vortex has no cone"); + } + + this.Delegate.AddNodeToLevel (this.vortexCylinder); + this.vortexCylinder.StopAllAnimations (); + this.vortexCylinder.PlayAllAnimations (); + this.vortexCylinder.Hidden = true; // Vortex Cylinder is only used for deriving the vortex shape animation + + // Chasm Expand Object (used for animation) + this.chasmExpandObject = vortex.FindChildNode ("chasm", true); + if (this.chasmExpandObject == null) { + throw new Exception ("Vortex has no chasm"); + } + + foreach (var child in this.chasmExpandObject.ChildNodes) { + if (!string.IsNullOrEmpty (child.Name) && child.Name.StartsWith ("occluder", StringComparison.Ordinal)) { + child.SetNodeToOccluder (); + } + } + + this.Delegate.AddNodeToLevel (this.chasmExpandObject); + this.chasmExpandObject.StopAllAnimations (); + this.chasmExpandObject.PlayAllAnimations (); + + var vortexShape = this.vortexCylinder.PresentationNode.Scale; + this.lastOuterRadius = vortexShape.X; + this.lastVortexCenterY = this.vortexCylinder.PresentationNode.WorldPosition.Y; + this.lastVortexHeight = vortexShape.Y; + this.lastFront = this.vortexCylinder.PresentationNode.WorldFront; + + this.startVortexTime = GameTime.Time; + } + + private void OnVortexAnimationEnded () + { + // Remove or hide everything + this.vortexCylinder?.StopAllAnimations (); + this.vortexCylinder?.RemoveFromParentNode (); + this.chasmExpandObject?.RemoveFromParentNode (); + + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + var blockObjects = this.Delegate.AllBlockObjects; + foreach (var block in blockObjects) { + block.ObjectRootNode.Hidden = true; + } + } + + private void EnumerateThroughBlocks (Action<SCNPhysicsBody> physicsFunction) + { + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + var blockObjects = this.Delegate.AllBlockObjects; + foreach (var block in blockObjects) { + if (block.PhysicsNode?.PhysicsBody != null) { + physicsFunction (block.PhysicsNode.PhysicsBody); + } + } + } + + #endregion + + #region Helper Function + + private void ApplyRandomTorque (SCNPhysicsBody physicsBody, float maxTorque) + { + var randomAxis = new SCNVector3 ((float) random.NextDouble (), (float) random.NextDouble (), (float) random.NextDouble ()); + randomAxis = SCNVector3.Normalize (randomAxis); + + var randomTorque = new SCNVector4 (randomAxis, (float) (random.NextDouble () * 2d - 1d) * maxTorque); + physicsBody.ApplyTorque (randomTorque, true); + } + + private float StageProgress (double startTime, double endTime) + { + var progress = (float) ((this.TimeSinceInitialFloatStart - startTime) / (endTime - startTime)); + return DigitExtensions.Clamp (progress, 0f, 1f); + } + + #endregion + + public void DidCollision (SCNNode node, SCNNode otherNode, SCNVector3 position, float impulse) { } + + enum State { + None, + InitialWait, + AnimateLift, + AnimateVortex + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/BoolFormatting.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/BoolFormatting.cs index ed93d123b..e52ef5db5 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/BoolFormatting.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/BoolFormatting.cs @@ -1,21 +1,19 @@ - -namespace XamarinShot.Models.Formattings -{ - using System; - using Newtonsoft.Json; - public class BoolFormatting : JsonConverter<bool> - { - public override bool CanRead => true; +namespace XamarinShot.Models.Formattings { + using System; + using Newtonsoft.Json; - public override bool ReadJson(JsonReader reader, Type objectType, bool existingValue, bool hasExistingValue, JsonSerializer serializer) - { - return reader.ReadAsBoolean() ?? false; - } + public class BoolFormatting : JsonConverter<bool> { + public override bool CanRead => true; - public override void WriteJson(JsonWriter writer, bool value, JsonSerializer serializer) - { - writer.WriteValue(value ? 1 : 0); - } - } -} \ No newline at end of file + public override bool ReadJson (JsonReader reader, Type objectType, bool existingValue, bool hasExistingValue, JsonSerializer serializer) + { + return reader.ReadAsBoolean () ?? false; + } + + public override void WriteJson (JsonWriter writer, bool value, JsonSerializer serializer) + { + writer.WriteValue (value ? 1 : 0); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/PhysicsNodeDataFormatting.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/PhysicsNodeDataFormatting.cs index 8d8dbbb4d..8450dea31 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/PhysicsNodeDataFormatting.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/PhysicsNodeDataFormatting.cs @@ -1,63 +1,56 @@ - -namespace XamarinShot.Models.Formattings -{ - using System; - using Newtonsoft.Json; - using Newtonsoft.Json.Linq; - using SceneKit; - - public class PhysicsNodeDataFormatting : JsonConverter<PhysicsNodeData> - { - public override bool CanRead => true; - - public override PhysicsNodeData ReadJson(JsonReader reader, Type objectType, PhysicsNodeData existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var result = default(PhysicsNodeData); - if (reader.TokenType != JsonToken.Null) - { - result = new PhysicsNodeData(); - - var jsonObject = JObject.Load(reader); - result.IsAlive = jsonObject[(nameof(result.IsAlive))].Value<bool>(); - if(result.IsAlive) - { - result.IsMoving = jsonObject[nameof(result.IsAlive)].Value<bool>(); - result.Team = (Team)jsonObject[nameof(result.Team)].Value<int>(); - - result.Position = jsonObject[nameof(result.Position)].ToObject<SCNVector3>(serializer); - result.Orientation = jsonObject[(nameof(result.Orientation))].ToObject<SCNQuaternion>(serializer); - - if (result.IsMoving) - { - result.Velocity = jsonObject[nameof(result.Velocity)]?.ToObject<SCNVector3>(serializer) ?? SCNVector3.Zero; - result.AngularVelocity = jsonObject[nameof(result.AngularVelocity)]?.ToObject<SCNVector4>(serializer) ?? SCNVector4.Zero; - } - } - } - - return result; - } - - public override void WriteJson(JsonWriter writer, PhysicsNodeData value, JsonSerializer serializer) - { - var jsonObject = new JObject(); - jsonObject.Add(nameof(value.IsAlive), JToken.FromObject(value.IsAlive, serializer)); - - if (value.IsAlive) - { - jsonObject.Add(nameof(value.IsMoving), JToken.FromObject(value.IsMoving, serializer)); - jsonObject.Add(nameof(value.Team), JToken.FromObject(value.Team, serializer)); - jsonObject.Add(nameof(value.Position), JToken.FromObject(value.Position, serializer)); - jsonObject.Add(nameof(value.Orientation), JToken.FromObject(value.Orientation, serializer)); - - if (value.IsMoving) - { - jsonObject.Add(nameof(value.Velocity), JToken.FromObject(value.Velocity, serializer)); - jsonObject.Add(nameof(value.AngularVelocity), JToken.FromObject(value.AngularVelocity, serializer)); - } - } - - jsonObject.WriteTo(writer); - } - } + +namespace XamarinShot.Models.Formattings { + using System; + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + using SceneKit; + + public class PhysicsNodeDataFormatting : JsonConverter<PhysicsNodeData> { + public override bool CanRead => true; + + public override PhysicsNodeData ReadJson (JsonReader reader, Type objectType, PhysicsNodeData existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var result = default (PhysicsNodeData); + if (reader.TokenType != JsonToken.Null) { + result = new PhysicsNodeData (); + + var jsonObject = JObject.Load (reader); + result.IsAlive = jsonObject [(nameof (result.IsAlive))].Value<bool> (); + if (result.IsAlive) { + result.IsMoving = jsonObject [nameof (result.IsAlive)].Value<bool> (); + result.Team = (Team) jsonObject [nameof (result.Team)].Value<int> (); + + result.Position = jsonObject [nameof (result.Position)].ToObject<SCNVector3> (serializer); + result.Orientation = jsonObject [(nameof (result.Orientation))].ToObject<SCNQuaternion> (serializer); + + if (result.IsMoving) { + result.Velocity = jsonObject [nameof (result.Velocity)]?.ToObject<SCNVector3> (serializer) ?? SCNVector3.Zero; + result.AngularVelocity = jsonObject [nameof (result.AngularVelocity)]?.ToObject<SCNVector4> (serializer) ?? SCNVector4.Zero; + } + } + } + + return result; + } + + public override void WriteJson (JsonWriter writer, PhysicsNodeData value, JsonSerializer serializer) + { + var jsonObject = new JObject (); + jsonObject.Add (nameof (value.IsAlive), JToken.FromObject (value.IsAlive, serializer)); + + if (value.IsAlive) { + jsonObject.Add (nameof (value.IsMoving), JToken.FromObject (value.IsMoving, serializer)); + jsonObject.Add (nameof (value.Team), JToken.FromObject (value.Team, serializer)); + jsonObject.Add (nameof (value.Position), JToken.FromObject (value.Position, serializer)); + jsonObject.Add (nameof (value.Orientation), JToken.FromObject (value.Orientation, serializer)); + + if (value.IsMoving) { + jsonObject.Add (nameof (value.Velocity), JToken.FromObject (value.Velocity, serializer)); + jsonObject.Add (nameof (value.AngularVelocity), JToken.FromObject (value.AngularVelocity, serializer)); + } + } + + jsonObject.WriteTo (writer); + } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNMatrix4Formatting.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNMatrix4Formatting.cs index b2bc8a413..1ad7fa2eb 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNMatrix4Formatting.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNMatrix4Formatting.cs @@ -1,27 +1,25 @@ - -namespace XamarinShot.Models.Formattings -{ - using System; - using Newtonsoft.Json; - using SceneKit; - public class SCNMatrix4Formatting : JsonConverter<SCNMatrix4> - { - public override bool CanRead => false; +namespace XamarinShot.Models.Formattings { + using System; + using Newtonsoft.Json; + using SceneKit; - public override SCNMatrix4 ReadJson(JsonReader reader, Type objectType, SCNMatrix4 existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public class SCNMatrix4Formatting : JsonConverter<SCNMatrix4> { + public override bool CanRead => false; - public override void WriteJson(JsonWriter writer, SCNMatrix4 value, JsonSerializer serializer) - { - var @object = new Newtonsoft.Json.Linq.JObject - { - { "Row0", Newtonsoft.Json.Linq.JToken.FromObject(value.Row0, serializer) }, - { "Row1", Newtonsoft.Json.Linq.JToken.FromObject(value.Row1, serializer) }, - { "Row2", Newtonsoft.Json.Linq.JToken.FromObject(value.Row2, serializer) }, - { "Row3", Newtonsoft.Json.Linq.JToken.FromObject(value.Row3, serializer) }, - }; + public override SCNMatrix4 ReadJson (JsonReader reader, Type objectType, SCNMatrix4 existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException (); - @object.WriteTo(writer); - } - } + public override void WriteJson (JsonWriter writer, SCNMatrix4 value, JsonSerializer serializer) + { + var @object = new Newtonsoft.Json.Linq.JObject + { + { "Row0", Newtonsoft.Json.Linq.JToken.FromObject(value.Row0, serializer) }, + { "Row1", Newtonsoft.Json.Linq.JToken.FromObject(value.Row1, serializer) }, + { "Row2", Newtonsoft.Json.Linq.JToken.FromObject(value.Row2, serializer) }, + { "Row3", Newtonsoft.Json.Linq.JToken.FromObject(value.Row3, serializer) }, + }; + + @object.WriteTo (writer); + } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNQuaternionFormatting.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNQuaternionFormatting.cs index a57a09157..3a7889537 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNQuaternionFormatting.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNQuaternionFormatting.cs @@ -1,27 +1,25 @@ - -namespace XamarinShot.Models.Formattings -{ - using System; - using Newtonsoft.Json; - using SceneKit; - public class SCNQuaternionFormatting : JsonConverter<SCNQuaternion> - { - public override bool CanRead => false; +namespace XamarinShot.Models.Formattings { + using System; + using Newtonsoft.Json; + using SceneKit; - public override SCNQuaternion ReadJson(JsonReader reader, Type objectType, SCNQuaternion existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public class SCNQuaternionFormatting : JsonConverter<SCNQuaternion> { + public override bool CanRead => false; - public override void WriteJson(JsonWriter writer, SCNQuaternion value, JsonSerializer serializer) - { - var @object = new Newtonsoft.Json.Linq.JObject - { - { "X", Newtonsoft.Json.Linq.JToken.FromObject(value.X) }, - { "Y", Newtonsoft.Json.Linq.JToken.FromObject(value.Y) }, - { "Z", Newtonsoft.Json.Linq.JToken.FromObject(value.Z) }, - { "W", Newtonsoft.Json.Linq.JToken.FromObject(value.W) } - }; + public override SCNQuaternion ReadJson (JsonReader reader, Type objectType, SCNQuaternion existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException (); - @object.WriteTo(writer); - } - } + public override void WriteJson (JsonWriter writer, SCNQuaternion value, JsonSerializer serializer) + { + var @object = new Newtonsoft.Json.Linq.JObject + { + { "X", Newtonsoft.Json.Linq.JToken.FromObject(value.X) }, + { "Y", Newtonsoft.Json.Linq.JToken.FromObject(value.Y) }, + { "Z", Newtonsoft.Json.Linq.JToken.FromObject(value.Z) }, + { "W", Newtonsoft.Json.Linq.JToken.FromObject(value.W) } + }; + + @object.WriteTo (writer); + } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector3Formatting.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector3Formatting.cs index 60c61feb8..b455b9ddf 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector3Formatting.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector3Formatting.cs @@ -1,26 +1,24 @@ - -namespace XamarinShot.Models.Formattings -{ - using System; - using Newtonsoft.Json; - using SceneKit; - public class SCNVector3Formatting : JsonConverter<SCNVector3> - { - public override bool CanRead => false; +namespace XamarinShot.Models.Formattings { + using System; + using Newtonsoft.Json; + using SceneKit; - public override SCNVector3 ReadJson(JsonReader reader, Type objectType, SCNVector3 existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public class SCNVector3Formatting : JsonConverter<SCNVector3> { + public override bool CanRead => false; - public override void WriteJson(JsonWriter writer, SCNVector3 value, JsonSerializer serializer) - { - var @object = new Newtonsoft.Json.Linq.JObject - { - { "X", Newtonsoft.Json.Linq.JToken.FromObject(value.X) }, - { "Y", Newtonsoft.Json.Linq.JToken.FromObject(value.Y) }, - { "Z", Newtonsoft.Json.Linq.JToken.FromObject(value.Z) } - }; + public override SCNVector3 ReadJson (JsonReader reader, Type objectType, SCNVector3 existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException (); - @object.WriteTo(writer); - } - } + public override void WriteJson (JsonWriter writer, SCNVector3 value, JsonSerializer serializer) + { + var @object = new Newtonsoft.Json.Linq.JObject + { + { "X", Newtonsoft.Json.Linq.JToken.FromObject(value.X) }, + { "Y", Newtonsoft.Json.Linq.JToken.FromObject(value.Y) }, + { "Z", Newtonsoft.Json.Linq.JToken.FromObject(value.Z) } + }; + + @object.WriteTo (writer); + } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector4Formatting.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector4Formatting.cs index b18f714fa..34be1cf32 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector4Formatting.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Formattings/SCNVector4Formatting.cs @@ -1,27 +1,25 @@ - -namespace XamarinShot.Models.Formattings -{ - using System; - using Newtonsoft.Json; - using SceneKit; - public class SCNVector4Formatting : JsonConverter<SCNVector4> - { - public override bool CanRead => false; +namespace XamarinShot.Models.Formattings { + using System; + using Newtonsoft.Json; + using SceneKit; - public override SCNVector4 ReadJson(JsonReader reader, Type objectType, SCNVector4 existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public class SCNVector4Formatting : JsonConverter<SCNVector4> { + public override bool CanRead => false; - public override void WriteJson(JsonWriter writer, SCNVector4 value, JsonSerializer serializer) - { - var @object = new Newtonsoft.Json.Linq.JObject - { - { "X", Newtonsoft.Json.Linq.JToken.FromObject(value.X) }, - { "Y", Newtonsoft.Json.Linq.JToken.FromObject(value.Y) }, - { "Z", Newtonsoft.Json.Linq.JToken.FromObject(value.Z) }, - { "W", Newtonsoft.Json.Linq.JToken.FromObject(value.W) }, - }; + public override SCNVector4 ReadJson (JsonReader reader, Type objectType, SCNVector4 existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException (); - @object.WriteTo(writer); - } - } + public override void WriteJson (JsonWriter writer, SCNVector4 value, JsonSerializer serializer) + { + var @object = new Newtonsoft.Json.Linq.JObject + { + { "X", Newtonsoft.Json.Linq.JToken.FromObject(value.X) }, + { "Y", Newtonsoft.Json.Linq.JToken.FromObject(value.Y) }, + { "Z", Newtonsoft.Json.Linq.JToken.FromObject(value.Z) }, + { "W", Newtonsoft.Json.Linq.JToken.FromObject(value.W) }, + }; + + @object.WriteTo (writer); + } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GAction.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GAction.cs index 99091b510..ac71d40aa 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GAction.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GAction.cs @@ -1,150 +1,131 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using System; - using System.Runtime.Serialization; - - public class GAction - { - public BoardSetupAction BoardSetup { get; set; } - - public GameActionType GameAction { get; set; } - - public PhysicsSyncData Physics { get; set; } - - public StartGameMusicTime StartGameMusic { get; set; } - - [Newtonsoft.Json.JsonIgnore] - public string Description - { - get - { - if (this.GameAction != null) - { - switch (this.GameAction.Type) - { - case GameActionType.GActionType.GrabStart: - return "grabStart"; - case GameActionType.GActionType.CatapultRelease: - return "catapultRelease"; - case GameActionType.GActionType.TryGrab: - return "tryGrab"; - case GameActionType.GActionType.GrabMove: - return "grabMove"; - case GameActionType.GActionType.GrabbableStatus: - return "grabbableStatus"; - case GameActionType.GActionType.HitCatapult: - return "catapultKnockOut"; - case GameActionType.GActionType.OneHitKOAnimate: - return "oneHitKOPrepareAnimation"; - case GameActionType.GActionType.TryRelease: - return "tryRelease"; - case GameActionType.GActionType.LeverMove: - return "levelMove"; - case GameActionType.GActionType.ReleaseEnd: - return "releaseEnd"; - case GameActionType.GActionType.KnockoutSync: - return "requestKnockoutSync"; - } - } - else if (this.BoardSetup != null) - { - switch (this.BoardSetup.Type) - { - case BoardSetupAction.BoardSetupActionType.RequestBoardLocation: - return "requestBoardLocation"; - case BoardSetupAction.BoardSetupActionType.BoardLocation: - return "boardLocation"; - } - } - else if (this.Physics != null) - { - return "physics"; - } - else if (this.StartGameMusic != null) - { - return "startGameMusic"; - } - - throw new NotImplementedException(); - } - } - } - - public class GameActionType - { - public GrabInfo TryGrab { get; set; } - public GrabInfo GrabStart { get; set; } - public GrabInfo GrabMove { get; set; } - public GrabInfo TryRelease { get; set; } - public GrabInfo ReleaseEnd { get; set; } - - public SlingData CatapultRelease { get; set; } - public GrabInfo GrabbableStatus { get; set; } - - public HitCatapult CatapultKnockOut { get; set; } - public LeverMove LeverMove { get; set; } - - public GActionType Type { get; set; } - - public enum GActionType - { - OneHitKOAnimate, - - TryGrab, - GrabStart, - GrabMove, - TryRelease, - ReleaseEnd, - - CatapultRelease, - GrabbableStatus, - KnockoutSync, - HitCatapult, - LeverMove, - } - } - - public class BoardSetupAction - { - public GameBoardLocation BoardLocation { get; set; } - - public BoardSetupActionType Type { get; set; } - - public enum BoardSetupActionType - { - RequestBoardLocation, - BoardLocation - } - } - - public class GameBoardLocation - { - [Newtonsoft.Json.JsonIgnore] - public NSData WorldMapData { get; set; } - - public byte[] WorldMapBytes { get; set; } - - public GameBoardLocationType Type { get; set; } - - [OnSerializing] - internal void OnSerializingMethod(StreamingContext context) - { - this.WorldMapBytes = this.WorldMapData.ToArray(); - } - - [OnDeserialized] - internal void OnDeserializedMethod(StreamingContext context) - { - this.WorldMapData = NSData.FromArray(this.WorldMapBytes); - this.WorldMapBytes = null; - } - - public enum GameBoardLocationType - { - WorldMapData, - Manual, - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using System; + using System.Runtime.Serialization; + + public class GAction { + public BoardSetupAction BoardSetup { get; set; } + + public GameActionType GameAction { get; set; } + + public PhysicsSyncData Physics { get; set; } + + public StartGameMusicTime StartGameMusic { get; set; } + + [Newtonsoft.Json.JsonIgnore] + public string Description { + get { + if (this.GameAction != null) { + switch (this.GameAction.Type) { + case GameActionType.GActionType.GrabStart: + return "grabStart"; + case GameActionType.GActionType.CatapultRelease: + return "catapultRelease"; + case GameActionType.GActionType.TryGrab: + return "tryGrab"; + case GameActionType.GActionType.GrabMove: + return "grabMove"; + case GameActionType.GActionType.GrabbableStatus: + return "grabbableStatus"; + case GameActionType.GActionType.HitCatapult: + return "catapultKnockOut"; + case GameActionType.GActionType.OneHitKOAnimate: + return "oneHitKOPrepareAnimation"; + case GameActionType.GActionType.TryRelease: + return "tryRelease"; + case GameActionType.GActionType.LeverMove: + return "levelMove"; + case GameActionType.GActionType.ReleaseEnd: + return "releaseEnd"; + case GameActionType.GActionType.KnockoutSync: + return "requestKnockoutSync"; + } + } else if (this.BoardSetup != null) { + switch (this.BoardSetup.Type) { + case BoardSetupAction.BoardSetupActionType.RequestBoardLocation: + return "requestBoardLocation"; + case BoardSetupAction.BoardSetupActionType.BoardLocation: + return "boardLocation"; + } + } else if (this.Physics != null) { + return "physics"; + } else if (this.StartGameMusic != null) { + return "startGameMusic"; + } + + throw new NotImplementedException (); + } + } + } + + public class GameActionType { + public GrabInfo TryGrab { get; set; } + public GrabInfo GrabStart { get; set; } + public GrabInfo GrabMove { get; set; } + public GrabInfo TryRelease { get; set; } + public GrabInfo ReleaseEnd { get; set; } + + public SlingData CatapultRelease { get; set; } + public GrabInfo GrabbableStatus { get; set; } + + public HitCatapult CatapultKnockOut { get; set; } + public LeverMove LeverMove { get; set; } + + public GActionType Type { get; set; } + + public enum GActionType { + OneHitKOAnimate, + + TryGrab, + GrabStart, + GrabMove, + TryRelease, + ReleaseEnd, + + CatapultRelease, + GrabbableStatus, + KnockoutSync, + HitCatapult, + LeverMove, + } + } + + public class BoardSetupAction { + public GameBoardLocation BoardLocation { get; set; } + + public BoardSetupActionType Type { get; set; } + + public enum BoardSetupActionType { + RequestBoardLocation, + BoardLocation + } + } + + public class GameBoardLocation { + [Newtonsoft.Json.JsonIgnore] + public NSData WorldMapData { get; set; } + + public byte [] WorldMapBytes { get; set; } + + public GameBoardLocationType Type { get; set; } + + [OnSerializing] + internal void OnSerializingMethod (StreamingContext context) + { + this.WorldMapBytes = this.WorldMapData.ToArray (); + } + + [OnDeserialized] + internal void OnDeserializedMethod (StreamingContext context) + { + this.WorldMapData = NSData.FromArray (this.WorldMapBytes); + this.WorldMapBytes = null; + } + + public enum GameBoardLocationType { + WorldMapData, + Manual, + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoard.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoard.cs index c1a48dddc..5d66049be 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoard.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoard.cs @@ -1,517 +1,478 @@ -/* +/* Abstract: Manages placement of the game board in real space before starting a game. */ -namespace XamarinShot.Models -{ - using ARKit; - using CoreAnimation; - using CoreGraphics; - using Foundation; - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - /// GameBoard represents the physical surface which the game is played upon. - /// In this node's child coordinate space, coordinates are normalized to the - /// board's width. So if the user wants to see the game appear in worldspace 1.5 meters - /// wide, the scale portion of this node's transform will be 1.5 in all dimensions. - public class GameBoard : SCNNode - { - /// The minimum size of the board in meters - private const float MinimumScale = 0.3f; - - /// The maximum size of the board in meters - private const float MaximumScale = 11.0f; // 15x27m @ 10, 1.5m x 2.7m @ 1 - - /// Duration of the open/close animation - private const double AnimationDuration = 0.7d; - - /// The level's preferred size. - /// This is used both to set the aspect ratio and to determine - /// the default size. - private CGSize preferredSize = new CGSize(1.5f, 2.7f); - - /// Indicates whether the segments of the border are disconnected. - private bool isBorderOpen; - - /// Indicates if the game board is currently being animated. - private bool isAnimating; - - /// The game board's most recent positions. - private List<SCNVector3> recentPositions = new List<SCNVector3>(); - - /// The game board's most recent rotation angles. - private List<float> recentRotationAngles = new List<float>(); - - /// Previously visited plane anchors. - private readonly List<ARAnchor> anchorsOfVisitedPlanes = new List<ARAnchor>(); - - /// The node used to visualize the game border. - private readonly SCNNode borderNode = new SCNNode(); - - /// List of the segments in the border. - private readonly List<BorderSegment> borderSegments= new List<BorderSegment>(); - - public GameBoard() : base() - { - // Set initial game board scale - this.Scale = new SCNVector3(GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale); - - // Create all border segments - foreach (Corner corner in Enum.GetValues(typeof(Corner))) - { - foreach (Alignment alignment in Enum.GetValues(typeof(Alignment))) - { - var borderSize = new CGSize(1f, this.AspectRatio); - var borderSegment = new BorderSegment(corner, alignment, borderSize); - - this.borderSegments.Add(borderSegment); - this.borderNode.AddChildNode(borderSegment); - } - } - - // Create fill plane - this.borderNode.AddChildNode(this.FillPlane); - - // Orient border to XZ plane and set aspect ratio - this.borderNode.EulerAngles = new SCNVector3((float)Math.PI / 2f, this.borderNode.EulerAngles.Y, this.borderNode.EulerAngles.Z); - this.borderNode.Hidden = true; - - this.AddChildNode(this.borderNode); - } - - public GameBoard(NSCoder coder) => throw new NotImplementedException("It has not been implemented"); - - /// <summary> - /// The color of the border - /// </summary> - public static UIColor BorderColor { get; } = UIColor.White; - - /// <summary> - /// The BoardAnchor in the scene - /// </summary> - public BoardAnchor Anchor { get; set; } - - /// <summary> - /// Indicates whether the border is currently hidden - /// </summary> - public bool IsBorderHidden => this.borderNode.Hidden || this.borderNode.GetAction("hide") != null; - - /// <summary> - /// The aspect ratio of the level. - /// </summary> - public float AspectRatio => (float)(this.preferredSize.Height / this.preferredSize.Width); - - /// <summary> - /// The level's preferred size. - /// This is used both to set the aspect ratio and to determine - /// the default size. - /// </summary> - public CGSize PreferredSize - { - get - { - return this.preferredSize; - } - - set - { - this.preferredSize = value; - this.UpdateBorderAspectRatio(); - } - } - - #region Appearance - - /// <summary> - /// Hides the border. - /// </summary> - public void HideBorder(double duration = 0.5d) - { - if (this.borderNode.GetAction("hide") == null) - { - this.borderNode.RemoveAction("unhide"); - this.borderNode.RunAction(SCNAction.FadeOut(duration), "hide", () => - { - this.borderNode.Hidden = true; - }); - } - } - - /// <summary> - /// Unhides the border. - /// </summary> - public void UnhideBorder() - { - if (this.borderNode.GetAction("unhide") == null) - { - this.borderNode.RemoveAction("hide"); - this.borderNode.RunAction(SCNAction.FadeIn(0.5), "unhide"); - this.borderNode.Hidden = false; - } - } - - /// <summary> - /// Updates the game board with the latest hit test result and camera. - /// </summary> - public void Update(ARHitTestResult hitTestResult, ARCamera camera) - { - if (this.IsBorderHidden) - { - this.UnhideBorder(); - } - - if (hitTestResult.Anchor is ARPlaneAnchor planeAnchor) - { - this.PerformCloseAnimation(!this.anchorsOfVisitedPlanes.Contains(planeAnchor)); - this.anchorsOfVisitedPlanes.Add(planeAnchor); - } - else - { - this.PerformOpenAnimation(); - } - - this.UpdateTransform(hitTestResult, camera); - } - - public void Reset() - { - this.borderNode.RemoveAllActions(); - this.borderNode.Hidden = true; - this.recentPositions.Clear(); - this.recentRotationAngles.Clear(); - this.Hidden = false; - } - - /// <summary> - /// Incrementally scales the board by the given amount - /// </summary> - public void UpdateScale(float factor) - { - // assumes we always scale the same in all 3 dimensions - var currentScale = this.Scale.X; - var newScale = DigitExtensions.Clamp(currentScale * factor, GameBoard.MinimumScale, GameBoard.MaximumScale); - this.Scale = new SCNVector3(newScale, newScale, newScale); - } - - public void UseDefaultScale() - { - var scale = (float)this.preferredSize.Width; - this.Scale = new SCNVector3(scale, scale, scale); - } - - #endregion - - #region Helper Methods - - /// <summary> - /// Update the transform of the game board with the latest hit test result and camera - /// </summary> - private void UpdateTransform(ARHitTestResult hitTestResult, ARCamera camera) - { - var position = hitTestResult.WorldTransform.GetTranslation(); - - // Average using several most recent positions. - this.recentPositions.Add(position); - this.recentPositions = new List<SCNVector3>(this.recentPositions.TakeLast(10)); - - // Move to average of recent positions to avoid jitter. - var average = this.recentPositions.Reduce(new SCNVector3(0f, 0f, 0f)) / (float)this.recentPositions.Count; - this.Position = average; - - // Orient bounds to plane if possible - if (hitTestResult.Anchor is ARPlaneAnchor planeAnchor) - { - this.OrientToPlane(planeAnchor, camera); - this.ScaleToPlane(planeAnchor); - } - else - { - // Fall back to camera orientation - this.OrientToCamera(camera); - this.Scale = new SCNVector3(GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale); - } - - // Remove any animation duration if present - SCNTransaction.AnimationDuration = 0; - } - - private void OrientToCamera(ARCamera camera) - { - this.Rotate(camera.EulerAngles.Y); - } - - private void OrientToPlane(ARPlaneAnchor planeAnchor, ARCamera camera) - { - // Get board rotation about y - this.Orientation = SimdExtensions.CreateQuaternion(planeAnchor.Transform.ToSCNMatrix4()); - var boardAngle = this.EulerAngles.Y; - - // If plane is longer than deep, rotate 90 degrees - if (planeAnchor.Extent.X > planeAnchor.Extent.Z) - { - boardAngle += (float)Math.PI / 2f; - } - - // Normalize angle to closest 180 degrees to camera angle - boardAngle = boardAngle.NormalizedAngle(camera.EulerAngles.Y, (float)Math.PI); - - this.Rotate(boardAngle); - } - - private void Rotate(float angle) - { - // Avoid interpolating between angle flips of 180 degrees - var previouAngle = this.recentRotationAngles.Sum() / (float)this.recentRotationAngles.Count; - if (Math.Abs(angle - previouAngle) > Math.PI / 2) - { - this.recentRotationAngles = this.recentRotationAngles.Select(value => value.NormalizedAngle(angle, (float)Math.PI)).ToList(); - } - - // Average using several most recent rotation angles. - this.recentRotationAngles.Add(angle); - this.recentRotationAngles = new List<float>(this.recentRotationAngles.TakeLast(20)); - - // Move to average of recent positions to avoid jitter. - var averageAngle = this.recentRotationAngles.Sum() / (float)this.recentRotationAngles.Count; - this.Rotation = new SCNVector4(0f, 1f, 0f, averageAngle); - } - - private void ScaleToPlane(ARPlaneAnchor planeAnchor) - { - // Determine if extent should be flipped (plane is 90 degrees rotated) - var planeXAxis = planeAnchor.Transform.Column0.Xyz; - var axisFlipped = Math.Abs(SCNVector3.Dot(planeXAxis, this.WorldRight)) < 0.5f; - - // Flip dimensions if necessary - var planeExtent = planeAnchor.Extent; - if (axisFlipped) - { - planeExtent = new OpenTK.NVector3(planeExtent.Z, 0f, planeExtent.X); - } - - // Scale board to the max extent that fits in the plane - var width = Math.Min(planeExtent.X, GameBoard.MaximumScale); - var depth = Math.Min(planeExtent.Z, width * this.AspectRatio); - width = depth / this.AspectRatio; - this.Scale = new SCNVector3(width, width, width); - - // Adjust position of board within plane's bounds - var planeLocalExtent = new SCNVector3(width, 0f, depth); - if (axisFlipped) - { - planeLocalExtent = new SCNVector3(planeLocalExtent.Z, 0f, planeLocalExtent.X); - } - - this.AdjustPosition(planeAnchor, planeLocalExtent); - } - - private void AdjustPosition(ARPlaneAnchor planeAnchor, SCNVector3 extent) - { - var positionAdjusted = false; - var planeAnchorTransform = planeAnchor.Transform.ToSCNMatrix4(); - var worldToPlane = SCNMatrix4.Invert(planeAnchorTransform); - - // Get current position in the local plane coordinate space - var planeLocalPosition = worldToPlane.Multiply(this.Transform.Column3); - - // Compute bounds min and max - var boardMin = planeLocalPosition.Xyz - extent / 2f; - var boardMax = planeLocalPosition.Xyz + extent / 2f; - - var planeAnchorCenter = planeAnchor.Center.ToSCNVector3(); - var planeAnchorExtent = planeAnchor.Extent.ToSCNVector3(); - var planeMin = planeAnchorCenter - planeAnchorExtent / 2f; - var planeMax = planeAnchorCenter + planeAnchorExtent / 2f; - - // Adjust position for x within plane bounds - if (boardMin.X < planeMin.X) - { - planeLocalPosition.X += planeMin.X - boardMin.X; - positionAdjusted = true; - } - else if (boardMax.X > planeMax.X) - { - planeLocalPosition.X -= boardMax.X - planeMax.X; - positionAdjusted = true; - } - - // Adjust position for z within plane bounds - if (boardMin.Z < planeMin.Z) - { - planeLocalPosition.Z += planeMin.Z - boardMin.Z; - positionAdjusted = true; - } - else if (boardMax.Z > planeMax.Z) - { - planeLocalPosition.Z -= boardMax.Z - planeMax.Z; - positionAdjusted = true; - } - - if (positionAdjusted) - { - this.Position = (planeAnchorTransform.Multiply(planeLocalPosition)).Xyz; - } - } - - private void UpdateBorderAspectRatio() - { - var borderSize = new CGSize(1f, this.AspectRatio); - foreach (var segment in this.borderSegments) - { - segment.BorderSize = borderSize; - } - - if (this.FillPlane.Geometry is SCNPlane plane) - { - var length = 1 - 2 * BorderSegment.Thickness; - plane.Height = length * this.AspectRatio; - - var textureScale = SimdExtensions.CreateFromScale(new SCNVector3(40f, 40f * this.AspectRatio, 1f)); - if (plane.FirstMaterial != null) - { - plane.FirstMaterial.Diffuse.ContentsTransform = textureScale; - plane.FirstMaterial.Emission.ContentsTransform = textureScale; - } - } - - this.isBorderOpen = false; - } - - #endregion - - #region Animations - - private void PerformOpenAnimation() - { - if (!this.isBorderOpen && !this.isAnimating) - { - this.isBorderOpen = true; - this.isAnimating = true; - - // Open animation - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = GameBoard.AnimationDuration / 4f; - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); - - this.borderNode.Opacity = 1f; - foreach (var segment in this.borderSegments) - { - segment.Open(); - } - - this.Scale = new SCNVector3(GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale); - - // completion is run on main-thread - SCNTransaction.SetCompletionBlock(() => - { - SCNTransaction.Begin(); - this.borderNode.RunAction(this.PulseAction(), "pulse"); - this.isAnimating = false; - SCNTransaction.Commit(); - }); - - - SCNTransaction.Commit(); - } - } - - private void PerformCloseAnimation(bool flash = false) - { - if (this.isBorderOpen && !this.isAnimating) - { - this.isBorderOpen = false; - this.isAnimating = true; - - this.borderNode.RemoveAction("pulse"); - this.borderNode.Opacity = 1f; - - // Close animation - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = GameBoard.AnimationDuration / 2f; - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); - - this.borderNode.Opacity = 0.99f; - SCNTransaction.SetCompletionBlock(() => - { - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = GameBoard.AnimationDuration / 2f; - SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut); - - foreach (var segment in this.borderSegments) - { - segment.Close(); - } - - SCNTransaction.SetCompletionBlock(() => - { - this.isAnimating = false; - }); - - SCNTransaction.Commit(); - }); - - SCNTransaction.Commit(); - - if (flash) - { - var waitAction = SCNAction.Wait(GameBoard.AnimationDuration * 0.75f); - var fadeInAction = SCNAction.FadeOpacityTo(0.6f, GameBoard.AnimationDuration * 0.125f); - var fadeOutAction = SCNAction.FadeOpacityTo(0f, GameBoard.AnimationDuration * 0.125f); - this.FillPlane.RunAction(SCNAction.Sequence(new SCNAction[] { waitAction, fadeOutAction, fadeInAction })); - } - } - } - - #endregion - - #region Convenience Methods - - protected SCNNode FillPlane => this.GetFillPlane(); - - private SCNNode GetFillPlane() - { - var length = 1f - 2f * BorderSegment.Thickness; - var plane = SCNPlane.Create(length, length * this.AspectRatio); - var node = SCNNode.FromGeometry(plane); - node.Name = "fillPlane"; - node.Opacity = 0.6f; - - var material = plane.FirstMaterial; - material.Diffuse.Contents = UIImage.FromBundle("art.scnassets/textures/grid.png"); - - var textureScale = SimdExtensions.CreateFromScale(new SCNVector3(40f, 40f * this.AspectRatio, 1f)); - material.Diffuse.ContentsTransform = textureScale; - material.Emission.Contents = UIImage.FromBundle("art.scnassets/textures/grid.png"); - material.Emission.ContentsTransform = textureScale; - material.Diffuse.WrapS = SCNWrapMode.Repeat; - material.Diffuse.WrapT = SCNWrapMode.Repeat; - material.DoubleSided = true; - material.Ambient.Contents = UIColor.Black; - material.LightingModelName = SCNLightingModel.Constant; - - return node; - } - - #endregion - - #region Animations and Actions - - private SCNAction PulseAction() - { - var pulseOutAction = SCNAction.FadeOpacityTo(0.4f, 0.5f); - var pulseInAction = SCNAction.FadeOpacityTo(1f, 0.5f); - pulseOutAction.TimingMode = SCNActionTimingMode.EaseInEaseOut; - pulseInAction.TimingMode = SCNActionTimingMode.EaseInEaseOut; - - return SCNAction.RepeatActionForever(SCNAction.Sequence(new SCNAction[] { pulseOutAction, pulseInAction })); - } - - #endregion - } -} \ No newline at end of file +namespace XamarinShot.Models { + using ARKit; + using CoreAnimation; + using CoreGraphics; + using Foundation; + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + /// GameBoard represents the physical surface which the game is played upon. + /// In this node's child coordinate space, coordinates are normalized to the + /// board's width. So if the user wants to see the game appear in worldspace 1.5 meters + /// wide, the scale portion of this node's transform will be 1.5 in all dimensions. + public class GameBoard : SCNNode { + /// The minimum size of the board in meters + private const float MinimumScale = 0.3f; + + /// The maximum size of the board in meters + private const float MaximumScale = 11.0f; // 15x27m @ 10, 1.5m x 2.7m @ 1 + + /// Duration of the open/close animation + private const double AnimationDuration = 0.7d; + + /// The level's preferred size. + /// This is used both to set the aspect ratio and to determine + /// the default size. + private CGSize preferredSize = new CGSize (1.5f, 2.7f); + + /// Indicates whether the segments of the border are disconnected. + private bool isBorderOpen; + + /// Indicates if the game board is currently being animated. + private bool isAnimating; + + /// The game board's most recent positions. + private List<SCNVector3> recentPositions = new List<SCNVector3> (); + + /// The game board's most recent rotation angles. + private List<float> recentRotationAngles = new List<float> (); + + /// Previously visited plane anchors. + private readonly List<ARAnchor> anchorsOfVisitedPlanes = new List<ARAnchor> (); + + /// The node used to visualize the game border. + private readonly SCNNode borderNode = new SCNNode (); + + /// List of the segments in the border. + private readonly List<BorderSegment> borderSegments = new List<BorderSegment> (); + + public GameBoard () : base () + { + // Set initial game board scale + this.Scale = new SCNVector3 (GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale); + + // Create all border segments + foreach (Corner corner in Enum.GetValues (typeof (Corner))) { + foreach (Alignment alignment in Enum.GetValues (typeof (Alignment))) { + var borderSize = new CGSize (1f, this.AspectRatio); + var borderSegment = new BorderSegment (corner, alignment, borderSize); + + this.borderSegments.Add (borderSegment); + this.borderNode.AddChildNode (borderSegment); + } + } + + // Create fill plane + this.borderNode.AddChildNode (this.FillPlane); + + // Orient border to XZ plane and set aspect ratio + this.borderNode.EulerAngles = new SCNVector3 ((float) Math.PI / 2f, this.borderNode.EulerAngles.Y, this.borderNode.EulerAngles.Z); + this.borderNode.Hidden = true; + + this.AddChildNode (this.borderNode); + } + + public GameBoard (NSCoder coder) => throw new NotImplementedException ("It has not been implemented"); + + /// <summary> + /// The color of the border + /// </summary> + public static UIColor BorderColor { get; } = UIColor.White; + + /// <summary> + /// The BoardAnchor in the scene + /// </summary> + public BoardAnchor Anchor { get; set; } + + /// <summary> + /// Indicates whether the border is currently hidden + /// </summary> + public bool IsBorderHidden => this.borderNode.Hidden || this.borderNode.GetAction ("hide") != null; + + /// <summary> + /// The aspect ratio of the level. + /// </summary> + public float AspectRatio => (float) (this.preferredSize.Height / this.preferredSize.Width); + + /// <summary> + /// The level's preferred size. + /// This is used both to set the aspect ratio and to determine + /// the default size. + /// </summary> + public CGSize PreferredSize { + get { + return this.preferredSize; + } + + set { + this.preferredSize = value; + this.UpdateBorderAspectRatio (); + } + } + + #region Appearance + + /// <summary> + /// Hides the border. + /// </summary> + public void HideBorder (double duration = 0.5d) + { + if (this.borderNode.GetAction ("hide") == null) { + this.borderNode.RemoveAction ("unhide"); + this.borderNode.RunAction (SCNAction.FadeOut (duration), "hide", () => { + this.borderNode.Hidden = true; + }); + } + } + + /// <summary> + /// Unhides the border. + /// </summary> + public void UnhideBorder () + { + if (this.borderNode.GetAction ("unhide") == null) { + this.borderNode.RemoveAction ("hide"); + this.borderNode.RunAction (SCNAction.FadeIn (0.5), "unhide"); + this.borderNode.Hidden = false; + } + } + + /// <summary> + /// Updates the game board with the latest hit test result and camera. + /// </summary> + public void Update (ARHitTestResult hitTestResult, ARCamera camera) + { + if (this.IsBorderHidden) { + this.UnhideBorder (); + } + + if (hitTestResult.Anchor is ARPlaneAnchor planeAnchor) { + this.PerformCloseAnimation (!this.anchorsOfVisitedPlanes.Contains (planeAnchor)); + this.anchorsOfVisitedPlanes.Add (planeAnchor); + } else { + this.PerformOpenAnimation (); + } + + this.UpdateTransform (hitTestResult, camera); + } + + public void Reset () + { + this.borderNode.RemoveAllActions (); + this.borderNode.Hidden = true; + this.recentPositions.Clear (); + this.recentRotationAngles.Clear (); + this.Hidden = false; + } + + /// <summary> + /// Incrementally scales the board by the given amount + /// </summary> + public void UpdateScale (float factor) + { + // assumes we always scale the same in all 3 dimensions + var currentScale = this.Scale.X; + var newScale = DigitExtensions.Clamp (currentScale * factor, GameBoard.MinimumScale, GameBoard.MaximumScale); + this.Scale = new SCNVector3 (newScale, newScale, newScale); + } + + public void UseDefaultScale () + { + var scale = (float) this.preferredSize.Width; + this.Scale = new SCNVector3 (scale, scale, scale); + } + + #endregion + + #region Helper Methods + + /// <summary> + /// Update the transform of the game board with the latest hit test result and camera + /// </summary> + private void UpdateTransform (ARHitTestResult hitTestResult, ARCamera camera) + { + var position = hitTestResult.WorldTransform.GetTranslation (); + + // Average using several most recent positions. + this.recentPositions.Add (position); + this.recentPositions = new List<SCNVector3> (this.recentPositions.TakeLast (10)); + + // Move to average of recent positions to avoid jitter. + var average = this.recentPositions.Reduce (new SCNVector3 (0f, 0f, 0f)) / (float) this.recentPositions.Count; + this.Position = average; + + // Orient bounds to plane if possible + if (hitTestResult.Anchor is ARPlaneAnchor planeAnchor) { + this.OrientToPlane (planeAnchor, camera); + this.ScaleToPlane (planeAnchor); + } else { + // Fall back to camera orientation + this.OrientToCamera (camera); + this.Scale = new SCNVector3 (GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale); + } + + // Remove any animation duration if present + SCNTransaction.AnimationDuration = 0; + } + + private void OrientToCamera (ARCamera camera) + { + this.Rotate (camera.EulerAngles.Y); + } + + private void OrientToPlane (ARPlaneAnchor planeAnchor, ARCamera camera) + { + // Get board rotation about y + this.Orientation = SimdExtensions.CreateQuaternion (planeAnchor.Transform.ToSCNMatrix4 ()); + var boardAngle = this.EulerAngles.Y; + + // If plane is longer than deep, rotate 90 degrees + if (planeAnchor.Extent.X > planeAnchor.Extent.Z) { + boardAngle += (float) Math.PI / 2f; + } + + // Normalize angle to closest 180 degrees to camera angle + boardAngle = boardAngle.NormalizedAngle (camera.EulerAngles.Y, (float) Math.PI); + + this.Rotate (boardAngle); + } + + private void Rotate (float angle) + { + // Avoid interpolating between angle flips of 180 degrees + var previouAngle = this.recentRotationAngles.Sum () / (float) this.recentRotationAngles.Count; + if (Math.Abs (angle - previouAngle) > Math.PI / 2) { + this.recentRotationAngles = this.recentRotationAngles.Select (value => value.NormalizedAngle (angle, (float) Math.PI)).ToList (); + } + + // Average using several most recent rotation angles. + this.recentRotationAngles.Add (angle); + this.recentRotationAngles = new List<float> (this.recentRotationAngles.TakeLast (20)); + + // Move to average of recent positions to avoid jitter. + var averageAngle = this.recentRotationAngles.Sum () / (float) this.recentRotationAngles.Count; + this.Rotation = new SCNVector4 (0f, 1f, 0f, averageAngle); + } + + private void ScaleToPlane (ARPlaneAnchor planeAnchor) + { + // Determine if extent should be flipped (plane is 90 degrees rotated) + var planeXAxis = planeAnchor.Transform.Column0.Xyz; + var axisFlipped = Math.Abs (SCNVector3.Dot (planeXAxis, this.WorldRight)) < 0.5f; + + // Flip dimensions if necessary + var planeExtent = planeAnchor.Extent; + if (axisFlipped) { + planeExtent = new OpenTK.NVector3 (planeExtent.Z, 0f, planeExtent.X); + } + + // Scale board to the max extent that fits in the plane + var width = Math.Min (planeExtent.X, GameBoard.MaximumScale); + var depth = Math.Min (planeExtent.Z, width * this.AspectRatio); + width = depth / this.AspectRatio; + this.Scale = new SCNVector3 (width, width, width); + + // Adjust position of board within plane's bounds + var planeLocalExtent = new SCNVector3 (width, 0f, depth); + if (axisFlipped) { + planeLocalExtent = new SCNVector3 (planeLocalExtent.Z, 0f, planeLocalExtent.X); + } + + this.AdjustPosition (planeAnchor, planeLocalExtent); + } + + private void AdjustPosition (ARPlaneAnchor planeAnchor, SCNVector3 extent) + { + var positionAdjusted = false; + var planeAnchorTransform = planeAnchor.Transform.ToSCNMatrix4 (); + var worldToPlane = SCNMatrix4.Invert (planeAnchorTransform); + + // Get current position in the local plane coordinate space + var planeLocalPosition = worldToPlane.Multiply (this.Transform.Column3); + + // Compute bounds min and max + var boardMin = planeLocalPosition.Xyz - extent / 2f; + var boardMax = planeLocalPosition.Xyz + extent / 2f; + + var planeAnchorCenter = planeAnchor.Center.ToSCNVector3 (); + var planeAnchorExtent = planeAnchor.Extent.ToSCNVector3 (); + var planeMin = planeAnchorCenter - planeAnchorExtent / 2f; + var planeMax = planeAnchorCenter + planeAnchorExtent / 2f; + + // Adjust position for x within plane bounds + if (boardMin.X < planeMin.X) { + planeLocalPosition.X += planeMin.X - boardMin.X; + positionAdjusted = true; + } else if (boardMax.X > planeMax.X) { + planeLocalPosition.X -= boardMax.X - planeMax.X; + positionAdjusted = true; + } + + // Adjust position for z within plane bounds + if (boardMin.Z < planeMin.Z) { + planeLocalPosition.Z += planeMin.Z - boardMin.Z; + positionAdjusted = true; + } else if (boardMax.Z > planeMax.Z) { + planeLocalPosition.Z -= boardMax.Z - planeMax.Z; + positionAdjusted = true; + } + + if (positionAdjusted) { + this.Position = (planeAnchorTransform.Multiply (planeLocalPosition)).Xyz; + } + } + + private void UpdateBorderAspectRatio () + { + var borderSize = new CGSize (1f, this.AspectRatio); + foreach (var segment in this.borderSegments) { + segment.BorderSize = borderSize; + } + + if (this.FillPlane.Geometry is SCNPlane plane) { + var length = 1 - 2 * BorderSegment.Thickness; + plane.Height = length * this.AspectRatio; + + var textureScale = SimdExtensions.CreateFromScale (new SCNVector3 (40f, 40f * this.AspectRatio, 1f)); + if (plane.FirstMaterial != null) { + plane.FirstMaterial.Diffuse.ContentsTransform = textureScale; + plane.FirstMaterial.Emission.ContentsTransform = textureScale; + } + } + + this.isBorderOpen = false; + } + + #endregion + + #region Animations + + private void PerformOpenAnimation () + { + if (!this.isBorderOpen && !this.isAnimating) { + this.isBorderOpen = true; + this.isAnimating = true; + + // Open animation + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = GameBoard.AnimationDuration / 4f; + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); + + this.borderNode.Opacity = 1f; + foreach (var segment in this.borderSegments) { + segment.Open (); + } + + this.Scale = new SCNVector3 (GameBoard.MinimumScale, GameBoard.MinimumScale, GameBoard.MinimumScale); + + // completion is run on main-thread + SCNTransaction.SetCompletionBlock (() => { + SCNTransaction.Begin (); + this.borderNode.RunAction (this.PulseAction (), "pulse"); + this.isAnimating = false; + SCNTransaction.Commit (); + }); + + + SCNTransaction.Commit (); + } + } + + private void PerformCloseAnimation (bool flash = false) + { + if (this.isBorderOpen && !this.isAnimating) { + this.isBorderOpen = false; + this.isAnimating = true; + + this.borderNode.RemoveAction ("pulse"); + this.borderNode.Opacity = 1f; + + // Close animation + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = GameBoard.AnimationDuration / 2f; + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); + + this.borderNode.Opacity = 0.99f; + SCNTransaction.SetCompletionBlock (() => { + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = GameBoard.AnimationDuration / 2f; + SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); + + foreach (var segment in this.borderSegments) { + segment.Close (); + } + + SCNTransaction.SetCompletionBlock (() => { + this.isAnimating = false; + }); + + SCNTransaction.Commit (); + }); + + SCNTransaction.Commit (); + + if (flash) { + var waitAction = SCNAction.Wait (GameBoard.AnimationDuration * 0.75f); + var fadeInAction = SCNAction.FadeOpacityTo (0.6f, GameBoard.AnimationDuration * 0.125f); + var fadeOutAction = SCNAction.FadeOpacityTo (0f, GameBoard.AnimationDuration * 0.125f); + this.FillPlane.RunAction (SCNAction.Sequence (new SCNAction [] { waitAction, fadeOutAction, fadeInAction })); + } + } + } + + #endregion + + #region Convenience Methods + + protected SCNNode FillPlane => this.GetFillPlane (); + + private SCNNode GetFillPlane () + { + var length = 1f - 2f * BorderSegment.Thickness; + var plane = SCNPlane.Create (length, length * this.AspectRatio); + var node = SCNNode.FromGeometry (plane); + node.Name = "fillPlane"; + node.Opacity = 0.6f; + + var material = plane.FirstMaterial; + material.Diffuse.Contents = UIImage.FromBundle ("art.scnassets/textures/grid.png"); + + var textureScale = SimdExtensions.CreateFromScale (new SCNVector3 (40f, 40f * this.AspectRatio, 1f)); + material.Diffuse.ContentsTransform = textureScale; + material.Emission.Contents = UIImage.FromBundle ("art.scnassets/textures/grid.png"); + material.Emission.ContentsTransform = textureScale; + material.Diffuse.WrapS = SCNWrapMode.Repeat; + material.Diffuse.WrapT = SCNWrapMode.Repeat; + material.DoubleSided = true; + material.Ambient.Contents = UIColor.Black; + material.LightingModelName = SCNLightingModel.Constant; + + return node; + } + + #endregion + + #region Animations and Actions + + private SCNAction PulseAction () + { + var pulseOutAction = SCNAction.FadeOpacityTo (0.4f, 0.5f); + var pulseInAction = SCNAction.FadeOpacityTo (1f, 0.5f); + pulseOutAction.TimingMode = SCNActionTimingMode.EaseInEaseOut; + pulseInAction.TimingMode = SCNActionTimingMode.EaseInEaseOut; + + return SCNAction.RepeatActionForever (SCNAction.Sequence (new SCNAction [] { pulseOutAction, pulseInAction })); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoardBorderSegment.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoardBorderSegment.cs index c8a9938c6..749afb982 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoardBorderSegment.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBoardBorderSegment.cs @@ -1,175 +1,158 @@ - -namespace XamarinShot.Models -{ - using CoreGraphics; - using Foundation; - using SceneKit; - using System; - using UIKit; - - public enum Corner - { - TopLeft, - TopRight, - BottomLeft, - BottomRight, - } - - public enum Alignment - { - Horizontal, - Vertical - } - - public static class CornerExtensions - { - public static float U(this Corner corner) - { - switch (corner) - { - case Corner.TopLeft: return -1; - case Corner.TopRight: return 1; - case Corner.BottomLeft: return -1; - case Corner.BottomRight: return 1; - } - - throw new NotImplementedException(); - } - - public static float V(this Corner corner) - { - switch (corner) - { - case Corner.TopLeft: return -1; - case Corner.TopRight: return -1; - case Corner.BottomLeft: return 1; - case Corner.BottomRight: return 1; - } - - throw new NotImplementedException(); - } - } - - public static class AlignmentExtensions - { - public static float xOffset(this Alignment alignment, CGSize size) - { - switch (alignment) - { - case Alignment.Horizontal: - return (float)(size.Width / 2f - BorderSegment.Thickness) / 2f; - case Alignment.Vertical: - return (float)(size.Width / 2f); - } - - throw new NotImplementedException(); - } - - public static float yOffset(this Alignment alignment, CGSize size) - { - switch (alignment) - { - case Alignment.Horizontal: - return (float)(size.Height / 2f - BorderSegment.Thickness / 2f); - case Alignment.Vertical: - return (float)(size.Height / 2f) / 2f; - } - - throw new NotImplementedException(); - } - } - - public class BorderSegment : SCNNode - { - /// Thickness of the border lines. - public const float Thickness = 0.012f; - - /// The scale of segment's length when in the open state - private const float OpenScale = 0.4f; - - private readonly Corner corner; - private readonly Alignment alignment; - private readonly SCNPlane plane; - - private CGSize borderSize; - - public BorderSegment(Corner corner, Alignment alignment, CGSize borderSize) : base() - { - this.corner = corner; - this.alignment = alignment; - - this.plane = SCNPlane.Create(BorderSegment.Thickness, BorderSegment.Thickness); - this.borderSize = borderSize; - - var material = this.plane.FirstMaterial; - material.Diffuse.Contents = GameBoard.BorderColor; - material.Emission.Contents = GameBoard.BorderColor; - material.DoubleSided = true; - material.Ambient.Contents = UIColor.Black; - material.LightingModelName = SCNLightingModel.Constant; - - this.Geometry = this.plane; - this.Opacity = 0.8f; - } - - public BorderSegment(NSCoder coder) => throw new NotImplementedException("it has not been implemented"); - - public CGSize BorderSize - { - get - { - return this.borderSize; - } - - set - { - this.borderSize = value; - switch (this.alignment) - { - case Alignment.Horizontal: - this.plane.Width = this.borderSize.Width / 2f; - break; - case Alignment.Vertical: - this.plane.Height = this.borderSize.Height / 2f; - break; - } - - this.Scale = SCNVector3.One; - this.Position = new SCNVector3(this.corner.U() * this.alignment.xOffset(this.borderSize), - this.corner.V() * this.alignment.yOffset(this.borderSize), - 0f); - } - } - - #region Animating Open/Closed - - public void Open() - { - var offset = new OpenTK.Vector2(); - if (this.alignment == Alignment.Horizontal) - { - this.Scale = new SCNVector3(BorderSegment.OpenScale, 1f, 1f); - offset.X = (1f - BorderSegment.OpenScale) * (float)(this.borderSize.Width) / 4f; - } - else - { - this.Scale = new SCNVector3(1f, BorderSegment.OpenScale, 1f); - offset.Y = (1f - BorderSegment.OpenScale) * (float)(this.borderSize.Height) / 4f; - } - - this.Position = new SCNVector3(this.corner.U() * this.alignment.xOffset(this.borderSize) + this.corner.U() * offset.X, - this.corner.V() * this.alignment.yOffset(this.borderSize) + this.corner.V() * offset.Y, - 0f); - } - - public void Close() - { - this.Scale = SCNVector3.One; - this.Position = new SCNVector3(this.corner.U() * this.alignment.xOffset(this.borderSize), - this.corner.V() * this.alignment.yOffset(this.borderSize), - 0f); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using CoreGraphics; + using Foundation; + using SceneKit; + using System; + using UIKit; + + public enum Corner { + TopLeft, + TopRight, + BottomLeft, + BottomRight, + } + + public enum Alignment { + Horizontal, + Vertical + } + + public static class CornerExtensions { + public static float U (this Corner corner) + { + switch (corner) { + case Corner.TopLeft: return -1; + case Corner.TopRight: return 1; + case Corner.BottomLeft: return -1; + case Corner.BottomRight: return 1; + } + + throw new NotImplementedException (); + } + + public static float V (this Corner corner) + { + switch (corner) { + case Corner.TopLeft: return -1; + case Corner.TopRight: return -1; + case Corner.BottomLeft: return 1; + case Corner.BottomRight: return 1; + } + + throw new NotImplementedException (); + } + } + + public static class AlignmentExtensions { + public static float xOffset (this Alignment alignment, CGSize size) + { + switch (alignment) { + case Alignment.Horizontal: + return (float) (size.Width / 2f - BorderSegment.Thickness) / 2f; + case Alignment.Vertical: + return (float) (size.Width / 2f); + } + + throw new NotImplementedException (); + } + + public static float yOffset (this Alignment alignment, CGSize size) + { + switch (alignment) { + case Alignment.Horizontal: + return (float) (size.Height / 2f - BorderSegment.Thickness / 2f); + case Alignment.Vertical: + return (float) (size.Height / 2f) / 2f; + } + + throw new NotImplementedException (); + } + } + + public class BorderSegment : SCNNode { + /// Thickness of the border lines. + public const float Thickness = 0.012f; + + /// The scale of segment's length when in the open state + private const float OpenScale = 0.4f; + + private readonly Corner corner; + private readonly Alignment alignment; + private readonly SCNPlane plane; + + private CGSize borderSize; + + public BorderSegment (Corner corner, Alignment alignment, CGSize borderSize) : base () + { + this.corner = corner; + this.alignment = alignment; + + this.plane = SCNPlane.Create (BorderSegment.Thickness, BorderSegment.Thickness); + this.borderSize = borderSize; + + var material = this.plane.FirstMaterial; + material.Diffuse.Contents = GameBoard.BorderColor; + material.Emission.Contents = GameBoard.BorderColor; + material.DoubleSided = true; + material.Ambient.Contents = UIColor.Black; + material.LightingModelName = SCNLightingModel.Constant; + + this.Geometry = this.plane; + this.Opacity = 0.8f; + } + + public BorderSegment (NSCoder coder) => throw new NotImplementedException ("it has not been implemented"); + + public CGSize BorderSize { + get { + return this.borderSize; + } + + set { + this.borderSize = value; + switch (this.alignment) { + case Alignment.Horizontal: + this.plane.Width = this.borderSize.Width / 2f; + break; + case Alignment.Vertical: + this.plane.Height = this.borderSize.Height / 2f; + break; + } + + this.Scale = SCNVector3.One; + this.Position = new SCNVector3 (this.corner.U () * this.alignment.xOffset (this.borderSize), + this.corner.V () * this.alignment.yOffset (this.borderSize), + 0f); + } + } + + #region Animating Open/Closed + + public void Open () + { + var offset = new OpenTK.Vector2 (); + if (this.alignment == Alignment.Horizontal) { + this.Scale = new SCNVector3 (BorderSegment.OpenScale, 1f, 1f); + offset.X = (1f - BorderSegment.OpenScale) * (float) (this.borderSize.Width) / 4f; + } else { + this.Scale = new SCNVector3 (1f, BorderSegment.OpenScale, 1f); + offset.Y = (1f - BorderSegment.OpenScale) * (float) (this.borderSize.Height) / 4f; + } + + this.Position = new SCNVector3 (this.corner.U () * this.alignment.xOffset (this.borderSize) + this.corner.U () * offset.X, + this.corner.V () * this.alignment.yOffset (this.borderSize) + this.corner.V () * offset.Y, + 0f); + } + + public void Close () + { + this.Scale = SCNVector3.One; + this.Position = new SCNVector3 (this.corner.U () * this.alignment.xOffset (this.borderSize), + this.corner.V () * this.alignment.yOffset (this.borderSize), + 0f); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBrowser.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBrowser.cs index e828459bb..4bdd088ac 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBrowser.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameBrowser.cs @@ -1,106 +1,96 @@ - -namespace XamarinShot.Models -{ - using CoreFoundation; - using Foundation; - using MultipeerConnectivity; - using XamarinShot.Utils; - using System.Collections.Generic; - using System.Linq; - - public interface IGameBrowserDelegate - { - void SawGames(GameBrowser browser, IList<NetworkGame> games); - } - - public class GameBrowser : NSObject, IMCNearbyServiceBrowserDelegate - { - private readonly IList<NetworkGame> games = new List<NetworkGame>(); - - private readonly MCNearbyServiceBrowser serviceBrowser; - - private readonly Player myself; - - public GameBrowser(Player myself) : base() - { - this.myself = myself; - this.serviceBrowser = new MCNearbyServiceBrowser(this.myself.PeerId, XamarinShotGameService.PlayerService) { Delegate = this }; - this.serviceBrowser.Delegate = this; - } - - public IGameBrowserDelegate Delegate { get; set; } - - public void Start() - { - // looking for peers - this.serviceBrowser.StartBrowsingForPeers(); - } - - public void Stop() - { - // stopping the search for peers - this.serviceBrowser.StopBrowsingForPeers(); - } - - public NetworkSession Join(NetworkGame game) - { - NetworkSession result = null; - if (this.games.Contains(game)) - { - result = new NetworkSession(this.myself, false, game.Location, game.Host); - this.serviceBrowser.InvitePeer(game.Host.PeerId, result.Session, null, 30d); - } - - return result; - } - - public void Refresh() - { - this.Delegate?.SawGames(this, new List<NetworkGame>(this.games)); - } - - #region IMCNearbyServiceBrowserDelegate - - public void FoundPeer(MCNearbyServiceBrowser browser, MCPeerID peerID, NSDictionary info) - { - if (peerID != this.myself.PeerId) - { - var appIdentifier = info?[XamarinShotGameAttribute.AppIdentifier]; - if (appIdentifier?.ToString() == NSBundle.MainBundle.BundleIdentifier) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var player = new Player(peerID); - var gameName = info?[XamarinShotGameAttribute.Name] as NSString; - - GameTableLocation location = null; - var locationIdString = info?[XamarinShotGameAttribute.Location] as NSString; - if (!string.IsNullOrEmpty(locationIdString) && int.TryParse(locationIdString, out int locationId)) - { - location = GameTableLocation.GetLocation(locationId); - } - - var game = new NetworkGame(player, gameName, location?.Identifier ?? 0); - this.games.Add(game); - this.Delegate?.SawGames(this, new List<NetworkGame>(this.games)); - }); - } - } - } - - public void LostPeer(MCNearbyServiceBrowser browser, MCPeerID peerID) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var removed = this.games.FirstOrDefault(game => game.Host.PeerId != peerID); - if (removed != null) - { - this.games.Remove(removed); - this.Delegate?.SawGames(this, new List<NetworkGame>(this.games)); - } - }); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using CoreFoundation; + using Foundation; + using MultipeerConnectivity; + using XamarinShot.Utils; + using System.Collections.Generic; + using System.Linq; + + public interface IGameBrowserDelegate { + void SawGames (GameBrowser browser, IList<NetworkGame> games); + } + + public class GameBrowser : NSObject, IMCNearbyServiceBrowserDelegate { + private readonly IList<NetworkGame> games = new List<NetworkGame> (); + + private readonly MCNearbyServiceBrowser serviceBrowser; + + private readonly Player myself; + + public GameBrowser (Player myself) : base () + { + this.myself = myself; + this.serviceBrowser = new MCNearbyServiceBrowser (this.myself.PeerId, XamarinShotGameService.PlayerService) { Delegate = this }; + this.serviceBrowser.Delegate = this; + } + + public IGameBrowserDelegate Delegate { get; set; } + + public void Start () + { + // looking for peers + this.serviceBrowser.StartBrowsingForPeers (); + } + + public void Stop () + { + // stopping the search for peers + this.serviceBrowser.StopBrowsingForPeers (); + } + + public NetworkSession Join (NetworkGame game) + { + NetworkSession result = null; + if (this.games.Contains (game)) { + result = new NetworkSession (this.myself, false, game.Location, game.Host); + this.serviceBrowser.InvitePeer (game.Host.PeerId, result.Session, null, 30d); + } + + return result; + } + + public void Refresh () + { + this.Delegate?.SawGames (this, new List<NetworkGame> (this.games)); + } + + #region IMCNearbyServiceBrowserDelegate + + public void FoundPeer (MCNearbyServiceBrowser browser, MCPeerID peerID, NSDictionary info) + { + if (peerID != this.myself.PeerId) { + var appIdentifier = info? [XamarinShotGameAttribute.AppIdentifier]; + if (appIdentifier?.ToString () == NSBundle.MainBundle.BundleIdentifier) { + DispatchQueue.MainQueue.DispatchAsync (() => { + var player = new Player (peerID); + var gameName = info? [XamarinShotGameAttribute.Name] as NSString; + + GameTableLocation location = null; + var locationIdString = info? [XamarinShotGameAttribute.Location] as NSString; + if (!string.IsNullOrEmpty (locationIdString) && int.TryParse (locationIdString, out int locationId)) { + location = GameTableLocation.GetLocation (locationId); + } + + var game = new NetworkGame (player, gameName, location?.Identifier ?? 0); + this.games.Add (game); + this.Delegate?.SawGames (this, new List<NetworkGame> (this.games)); + }); + } + } + } + + public void LostPeer (MCNearbyServiceBrowser browser, MCPeerID peerID) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + var removed = this.games.FirstOrDefault (game => game.Host.PeerId != peerID); + if (removed != null) { + this.games.Remove (removed); + this.Delegate?.SawGames (this, new List<NetworkGame> (this.games)); + } + }); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameCommand.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameCommand.cs index 405f0fdd3..9f1e030d7 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameCommand.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameCommand.cs @@ -1,134 +1,123 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Utils; - using System.Collections.Generic; - - public class CameraInfo - { - public CameraInfo(SCNMatrix4 transform) - { - this.Transform = transform; - } - - public SCNMatrix4 Transform { get; private set; } - - [Newtonsoft.Json.JsonIgnore] - public Ray Ray - { - get - { - var position = this.Transform.GetTranslation(); - var direction = SCNVector3.Normalize(this.Transform.Multiply(new SCNVector4(0f, 0f, -1f, 0f)).Xyz); - return new Ray(position, direction); - } - } - } - - public class GameCommand - { - public GameCommand(Player player, GAction action) - { - this.Player = player; - this.Action = action; - } - - public Player Player { get; private set; } - - public GAction Action { get; private set; } - } - - /// <summary> - /// When a catapult is knocked down - /// </summary> - public class HitCatapult - { - public HitCatapult(int catapultId, bool justKnockedout, bool vortex) - { - this.CatapultId = catapultId; - this.JustKnockedout = justKnockedout; - this.Vortex = vortex; - } - - public int CatapultId { get; private set; } - - public bool JustKnockedout { get; private set; } - - public bool Vortex { get; private set; } - } - - // GameVelocity stores the origin and vector of velocity. - // It is similar to ray, but whereas ray will have normalized direction, the .vector is the velocity vector - public class GameVelocity - { - public GameVelocity(SCNVector3 origin, SCNVector3 vector) - { - this.Origin = origin; - this.Vector = vector; - } - - public SCNVector3 Origin { get; private set; } - - public SCNVector3 Vector { get; private set; } - - [Newtonsoft.Json.JsonIgnore] - public static GameVelocity Zero { get; } = new GameVelocity(SCNVector3.Zero, SCNVector3.Zero); - } - - public class SlingData - { - public SlingData(int catapultId, ProjectileType projectileType, GameVelocity velocity) - { - CatapultId = catapultId; - ProjectileType = projectileType; - Velocity = velocity; - } - - public int CatapultId { get; private set; } - - public ProjectileType ProjectileType { get; private set; } - - public GameVelocity Velocity { get; private set; } - } - - public class GrabInfo - { - public GrabInfo(int grabbableId, CameraInfo cameraInfo) - { - this.GrabbableId = grabbableId; - this.CameraInfo = cameraInfo; - } - - public int GrabbableId { get; private set; } - - public CameraInfo CameraInfo { get; private set; } - } - - public class LeverMove - { - public LeverMove(int leverId, float eulerAngleX) - { - this.LeverId = leverId; - this.EulerAngleX = eulerAngleX; - } - - public int LeverId { get; private set; } - - public float EulerAngleX { get; private set; } - } - - public class StartGameMusicTime - { - public StartGameMusicTime(bool startNow, List<double> timestamps) - { - this.StartNow = startNow; - this.Timestamps = timestamps; - } - - public bool StartNow { get; private set; } - - public List<double> Timestamps { get; private set; } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Utils; + using System.Collections.Generic; + + public class CameraInfo { + public CameraInfo (SCNMatrix4 transform) + { + this.Transform = transform; + } + + public SCNMatrix4 Transform { get; private set; } + + [Newtonsoft.Json.JsonIgnore] + public Ray Ray { + get { + var position = this.Transform.GetTranslation (); + var direction = SCNVector3.Normalize (this.Transform.Multiply (new SCNVector4 (0f, 0f, -1f, 0f)).Xyz); + return new Ray (position, direction); + } + } + } + + public class GameCommand { + public GameCommand (Player player, GAction action) + { + this.Player = player; + this.Action = action; + } + + public Player Player { get; private set; } + + public GAction Action { get; private set; } + } + + /// <summary> + /// When a catapult is knocked down + /// </summary> + public class HitCatapult { + public HitCatapult (int catapultId, bool justKnockedout, bool vortex) + { + this.CatapultId = catapultId; + this.JustKnockedout = justKnockedout; + this.Vortex = vortex; + } + + public int CatapultId { get; private set; } + + public bool JustKnockedout { get; private set; } + + public bool Vortex { get; private set; } + } + + // GameVelocity stores the origin and vector of velocity. + // It is similar to ray, but whereas ray will have normalized direction, the .vector is the velocity vector + public class GameVelocity { + public GameVelocity (SCNVector3 origin, SCNVector3 vector) + { + this.Origin = origin; + this.Vector = vector; + } + + public SCNVector3 Origin { get; private set; } + + public SCNVector3 Vector { get; private set; } + + [Newtonsoft.Json.JsonIgnore] + public static GameVelocity Zero { get; } = new GameVelocity (SCNVector3.Zero, SCNVector3.Zero); + } + + public class SlingData { + public SlingData (int catapultId, ProjectileType projectileType, GameVelocity velocity) + { + CatapultId = catapultId; + ProjectileType = projectileType; + Velocity = velocity; + } + + public int CatapultId { get; private set; } + + public ProjectileType ProjectileType { get; private set; } + + public GameVelocity Velocity { get; private set; } + } + + public class GrabInfo { + public GrabInfo (int grabbableId, CameraInfo cameraInfo) + { + this.GrabbableId = grabbableId; + this.CameraInfo = cameraInfo; + } + + public int GrabbableId { get; private set; } + + public CameraInfo CameraInfo { get; private set; } + } + + public class LeverMove { + public LeverMove (int leverId, float eulerAngleX) + { + this.LeverId = leverId; + this.EulerAngleX = eulerAngleX; + } + + public int LeverId { get; private set; } + + public float EulerAngleX { get; private set; } + } + + public class StartGameMusicTime { + public StartGameMusicTime (bool startNow, List<double> timestamps) + { + this.StartNow = startNow; + this.Timestamps = timestamps; + } + + public bool StartNow { get; private set; } + + public List<double> Timestamps { get; private set; } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameLevel.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameLevel.cs index 3a0d69ef6..e6938b9c5 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameLevel.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameLevel.cs @@ -1,277 +1,245 @@ - -namespace XamarinShot.Models -{ - using CoreGraphics; - using Foundation; - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - - public class GameLevel : IDisposable - { - private const string LevelsPath = "art.scnassets/levels/"; - private const string DefaultLevelName = "gateway"; - private const string LevelStrings = "levels"; - - private readonly CGSize defaultSize = new CGSize(1.5f, 2.7f); - - private readonly NSLock @lock = new NSLock(); - - private readonly Definition definition; - - private SCNNode levelNodeTemplate; - - private SCNNode levelNodeClone; - - private SCNScene scene; - - private GameLevel(Definition definition) - { - this.definition = definition; - this.TargetSize = this.defaultSize; - } - - public string Name => this.definition.Name; - - public string Key => this.definition.Key; - - private string Identifier => this.definition.Identifier; - - public bool Placed { get; private set; } - - /// <summary> - /// Size of the level in meters - /// </summary> - public CGSize TargetSize { get; private set; } - - public float LodScale { get; private set; } = 1f; - - public string Path => LevelsPath + this.Identifier; - - public static GameLevel DefaultLevel { get; } = GameLevel.Level(DefaultLevelName); - - /// <summary> - /// An instance of the active level - /// </summary> - public SCNNode ActiveLevel - { - get - { - if (this.levelNodeTemplate == null) - { - return null; - } - - if (this.levelNodeClone != null) - { - return this.levelNodeClone; - } - - this.levelNodeClone = this.levelNodeTemplate.Clone(); - return this.levelNodeClone; - } - } - - /// <summary> - /// Scale factor to assign to the level to make it appear 1 unit wide. - /// </summary> - public float NormalizedScale - { - get - { - if (this.levelNodeTemplate == null) - { - return 1f; - } - - var levelSize = this.levelNodeTemplate.GetHorizontalSize().X; - if (levelSize > 0) - { - return 1f / levelSize; - } - else - { - throw new Exception("Level size is 0. This might indicate something is wrong with the assets"); - } - } - } - - private static List<GameLevel> allLevels; - public static List<GameLevel> AllLevels - { - get - { - if (allLevels == null) - { - var url = NSBundle.MainBundle.GetUrlForResource("art.scnassets/data/levels", "json"); - if (url == null) - { - throw new Exception("Could not find levels.json"); - } - - var json = NSString.FromData(NSData.FromUrl(url), NSStringEncoding.UTF8).ToString(); - var definitions = json.Parse<List<Definition>>(); - if (definitions != null) - { - allLevels = definitions.Select(definition => new GameLevel(definition)).ToList(); - } - else - { - throw new Exception($"Could not find level information at {url}"); - } - } - - return allLevels; - } - } - - public static GameLevel Level(int index) - { - return index < AllLevels.Count ? AllLevels[index] : null; - } - - public static GameLevel Level(string key) - { - return AllLevels.FirstOrDefault(level => level.Key == key); - } - - public void Load() - { - // have to do this - this.@lock.Lock(); - - // only load once - can be called from preload on another thread, or regular load - if (this.scene == null) - { - var sceneUrl = NSBundle.MainBundle.GetUrlForResource(this.Path, "scn"); - if (sceneUrl == null) - { - throw new Exception($"Level {this.Path} not found"); - } - - var scene = SCNScene.FromUrl(sceneUrl, (SCNSceneLoadingOptions)null, out NSError error); - if (error != null) - { - throw new Exception($"Could not load level {sceneUrl}: {error.LocalizedDescription}"); - } - - // start with animations and physics paused until the board is placed - // we don't want any animations or things falling over while ARSceneView - // is driving SceneKit and the view. - scene.Paused = true; - - // walk down the scenegraph and update the children - scene.RootNode.FixMaterials(); - - this.scene = scene; - - // this may not be the root, but lookup the identifier - // will clone the tree done from this node - this.levelNodeTemplate = this.scene.RootNode.FindChildNode("_" + Identifier, true); - } - - this.@lock.Unlock(); - } - - public void Reset() - { - this.Placed = false; - this.ActiveLevel.RemoveFromParentNode(); - if (this.levelNodeClone != null) - { - this.levelNodeClone.Dispose(); - this.levelNodeClone = null; - } - } - - public void PlaceLevel(SCNNode node, SCNScene gameScene, float boardScale) - { - if (this.ActiveLevel != null) - { - if (this.scene != null) - { - // set the environment onto the SCNView - gameScene.LightingEnvironment.Contents = this.scene.LightingEnvironment.Contents; - gameScene.LightingEnvironment.Intensity = this.scene.LightingEnvironment.Intensity; - - // set the cloned nodes representing the active level - node.AddChildNode(this.ActiveLevel); - - this.Placed = true; - - // the lod system doesn't honor the scaled camera, - // so have to fix this manually in fixLevelsOfDetail with inverse scale - // applied to the screenSpaceRadius - this.LodScale = this.NormalizedScale * boardScale; - } - } - } - - #region helpers - - public enum GameLevelKey - { - Gateway, - Bridge, - Farm, - ArchFort, - Towers, - } - - class Definition - { - public string Key { get; set; } - - public string Identifier { get; set; } - - public string Name => NSBundle.MainBundle.GetLocalizedString(this.Key); - } - - #endregion - - #region IDisposable - - private bool isDisposed = false; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!isDisposed) - { - if (disposing) - { - if (this.levelNodeTemplate != null) - { - this.levelNodeTemplate.Dispose(); - this.levelNodeTemplate = null; - } - - if (this.levelNodeClone != null) - { - this.levelNodeClone.Dispose(); - this.levelNodeClone = null; - } - - if (this.scene != null) - { - this.scene.Dispose(); - this.scene = null; - } - - this.@lock.Dispose(); - } - - isDisposed = true; - } - } - - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(true); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using CoreGraphics; + using Foundation; + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + public class GameLevel : IDisposable { + private const string LevelsPath = "art.scnassets/levels/"; + private const string DefaultLevelName = "gateway"; + private const string LevelStrings = "levels"; + + private readonly CGSize defaultSize = new CGSize (1.5f, 2.7f); + + private readonly NSLock @lock = new NSLock (); + + private readonly Definition definition; + + private SCNNode levelNodeTemplate; + + private SCNNode levelNodeClone; + + private SCNScene scene; + + private GameLevel (Definition definition) + { + this.definition = definition; + this.TargetSize = this.defaultSize; + } + + public string Name => this.definition.Name; + + public string Key => this.definition.Key; + + private string Identifier => this.definition.Identifier; + + public bool Placed { get; private set; } + + /// <summary> + /// Size of the level in meters + /// </summary> + public CGSize TargetSize { get; private set; } + + public float LodScale { get; private set; } = 1f; + + public string Path => LevelsPath + this.Identifier; + + public static GameLevel DefaultLevel { get; } = GameLevel.Level (DefaultLevelName); + + /// <summary> + /// An instance of the active level + /// </summary> + public SCNNode ActiveLevel { + get { + if (this.levelNodeTemplate == null) { + return null; + } + + if (this.levelNodeClone != null) { + return this.levelNodeClone; + } + + this.levelNodeClone = this.levelNodeTemplate.Clone (); + return this.levelNodeClone; + } + } + + /// <summary> + /// Scale factor to assign to the level to make it appear 1 unit wide. + /// </summary> + public float NormalizedScale { + get { + if (this.levelNodeTemplate == null) { + return 1f; + } + + var levelSize = this.levelNodeTemplate.GetHorizontalSize ().X; + if (levelSize > 0) { + return 1f / levelSize; + } else { + throw new Exception ("Level size is 0. This might indicate something is wrong with the assets"); + } + } + } + + private static List<GameLevel> allLevels; + public static List<GameLevel> AllLevels { + get { + if (allLevels == null) { + var url = NSBundle.MainBundle.GetUrlForResource ("art.scnassets/data/levels", "json"); + if (url == null) { + throw new Exception ("Could not find levels.json"); + } + + var json = NSString.FromData (NSData.FromUrl (url), NSStringEncoding.UTF8).ToString (); + var definitions = json.Parse<List<Definition>> (); + if (definitions != null) { + allLevels = definitions.Select (definition => new GameLevel (definition)).ToList (); + } else { + throw new Exception ($"Could not find level information at {url}"); + } + } + + return allLevels; + } + } + + public static GameLevel Level (int index) + { + return index < AllLevels.Count ? AllLevels [index] : null; + } + + public static GameLevel Level (string key) + { + return AllLevels.FirstOrDefault (level => level.Key == key); + } + + public void Load () + { + // have to do this + this.@lock.Lock (); + + // only load once - can be called from preload on another thread, or regular load + if (this.scene == null) { + var sceneUrl = NSBundle.MainBundle.GetUrlForResource (this.Path, "scn"); + if (sceneUrl == null) { + throw new Exception ($"Level {this.Path} not found"); + } + + var scene = SCNScene.FromUrl (sceneUrl, (SCNSceneLoadingOptions) null, out NSError error); + if (error != null) { + throw new Exception ($"Could not load level {sceneUrl}: {error.LocalizedDescription}"); + } + + // start with animations and physics paused until the board is placed + // we don't want any animations or things falling over while ARSceneView + // is driving SceneKit and the view. + scene.Paused = true; + + // walk down the scenegraph and update the children + scene.RootNode.FixMaterials (); + + this.scene = scene; + + // this may not be the root, but lookup the identifier + // will clone the tree done from this node + this.levelNodeTemplate = this.scene.RootNode.FindChildNode ("_" + Identifier, true); + } + + this.@lock.Unlock (); + } + + public void Reset () + { + this.Placed = false; + this.ActiveLevel.RemoveFromParentNode (); + if (this.levelNodeClone != null) { + this.levelNodeClone.Dispose (); + this.levelNodeClone = null; + } + } + + public void PlaceLevel (SCNNode node, SCNScene gameScene, float boardScale) + { + if (this.ActiveLevel != null) { + if (this.scene != null) { + // set the environment onto the SCNView + gameScene.LightingEnvironment.Contents = this.scene.LightingEnvironment.Contents; + gameScene.LightingEnvironment.Intensity = this.scene.LightingEnvironment.Intensity; + + // set the cloned nodes representing the active level + node.AddChildNode (this.ActiveLevel); + + this.Placed = true; + + // the lod system doesn't honor the scaled camera, + // so have to fix this manually in fixLevelsOfDetail with inverse scale + // applied to the screenSpaceRadius + this.LodScale = this.NormalizedScale * boardScale; + } + } + } + + #region helpers + + public enum GameLevelKey { + Gateway, + Bridge, + Farm, + ArchFort, + Towers, + } + + class Definition { + public string Key { get; set; } + + public string Identifier { get; set; } + + public string Name => NSBundle.MainBundle.GetLocalizedString (this.Key); + } + + #endregion + + #region IDisposable + + private bool isDisposed = false; // To detect redundant calls + + protected virtual void Dispose (bool disposing) + { + if (!isDisposed) { + if (disposing) { + if (this.levelNodeTemplate != null) { + this.levelNodeTemplate.Dispose (); + this.levelNodeTemplate = null; + } + + if (this.levelNodeClone != null) { + this.levelNodeClone.Dispose (); + this.levelNodeClone = null; + } + + if (this.scene != null) { + this.scene.Dispose (); + this.scene = null; + } + + this.@lock.Dispose (); + } + + isDisposed = true; + } + } + + public void Dispose () + { + this.Dispose (true); + GC.SuppressFinalize (true); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameTableLocation.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameTableLocation.cs index 04d9e5633..63e494bae 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameTableLocation.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/GameTableLocation.cs @@ -1,51 +1,48 @@ - -namespace XamarinShot.Models -{ - using System.Collections.Generic; - - public class GameTableLocation - { - private static Dictionary<int, GameTableLocation> Locations = new Dictionary<int, GameTableLocation>(); - - private readonly string name; - - public GameTableLocation(int identifier) - { - this.Identifier = identifier; - this.name = $"Table {this.Identifier}"; - } - - public int Identifier { get; private set; } - - public override int GetHashCode() - { - return this.Identifier.GetHashCode(); - } - - public static GameTableLocation GetLocation(int identifier) - { - if (!Locations.TryGetValue(identifier, out GameTableLocation location)) - { - location = new GameTableLocation(identifier); - Locations[identifier] = location; - } - - return location; - } - - public override bool Equals(object obj) - { - return this.Identifier == (obj as GameTableLocation)?.Identifier; - } - - public static bool operator ==(GameTableLocation lhs, GameTableLocation rhs) - { - return lhs?.Identifier == rhs?.Identifier; - } - - public static bool operator !=(GameTableLocation lhs, GameTableLocation rhs) - { - return lhs?.Identifier != rhs?.Identifier; - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using System.Collections.Generic; + + public class GameTableLocation { + private static Dictionary<int, GameTableLocation> Locations = new Dictionary<int, GameTableLocation> (); + + private readonly string name; + + public GameTableLocation (int identifier) + { + this.Identifier = identifier; + this.name = $"Table {this.Identifier}"; + } + + public int Identifier { get; private set; } + + public override int GetHashCode () + { + return this.Identifier.GetHashCode (); + } + + public static GameTableLocation GetLocation (int identifier) + { + if (!Locations.TryGetValue (identifier, out GameTableLocation location)) { + location = new GameTableLocation (identifier); + Locations [identifier] = location; + } + + return location; + } + + public override bool Equals (object obj) + { + return this.Identifier == (obj as GameTableLocation)?.Identifier; + } + + public static bool operator == (GameTableLocation lhs, GameTableLocation rhs) + { + return lhs?.Identifier == rhs?.Identifier; + } + + public static bool operator != (GameTableLocation lhs, GameTableLocation rhs) + { + return lhs?.Identifier != rhs?.Identifier; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkGame.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkGame.cs index 477df24e7..bb7a70025 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkGame.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkGame.cs @@ -1,21 +1,19 @@ - -namespace XamarinShot.Models -{ - public class NetworkGame - { - private readonly int locationId; - public NetworkGame(Player host, string name = null, int locationId = 0) - { - this.Host = host; - this.Name = name ?? $"{this.Host.Username}'s Game"; - this.locationId = locationId; - } +namespace XamarinShot.Models { + public class NetworkGame { + private readonly int locationId; - public GameTableLocation Location => GameTableLocation.GetLocation(this.locationId); + public NetworkGame (Player host, string name = null, int locationId = 0) + { + this.Host = host; + this.Name = name ?? $"{this.Host.Username}'s Game"; + this.locationId = locationId; + } - public Player Host { get; private set; } + public GameTableLocation Location => GameTableLocation.GetLocation (this.locationId); - public string Name { get; private set; } - } -} \ No newline at end of file + public Player Host { get; private set; } + + public string Name { get; private set; } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkSession.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkSession.cs index 098f5b68a..a375de2d5 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkSession.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/NetworkSession.cs @@ -1,225 +1,210 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using MultipeerConnectivity; - using System.Collections.Generic; - using System.Linq; - using XamarinShot.Utils; - using Newtonsoft.Json; - using CoreFoundation; - - public interface INetworkSessionDelegate - { - void NetworkSessionReceived(NetworkSession session, GameCommand command); - - void NetworkSessionJoining(NetworkSession session, Player player); - - void NetworkSessionLeaving(NetworkSession session, Player player); - } - - public class NetworkSession : NSObject, IMCSessionDelegate, IMCNearbyServiceAdvertiserDelegate - { - private const string LocationKey = "LocationAttributeName"; - - private readonly List<Player> peers = new List<Player>(); - - private readonly Player myself; - - private GameTableLocation location; - - private MCNearbyServiceAdvertiser serviceAdvertiser; - - private readonly string appIdentifier; - - public NetworkSession(Player myself, bool asServer, GameTableLocation location, Player host) : base() - { - this.myself = myself; - this.Session = new MCSession(this.myself.PeerId, null, MCEncryptionPreference.Required); - this.IsServer = asServer; - this.location = location; - this.Host = host; - - this.appIdentifier = NSBundle.MainBundle.BundleIdentifier; - this.Session.Delegate = this; - } - - public MCSession Session { get; private set; } - - public Player Host { get; private set; } - - public bool IsServer { get; private set; } - - public INetworkSessionDelegate Delegate { get; set; } - - public bool IsAnyActivePeers => this.peers.Any(); - - /// <summary> - /// For use when acting as game server - /// </summary> - public void StartAdvertising() - { - if (this.serviceAdvertiser == null) - { - var discoveryInfo = NSDictionary.FromObjectAndKey(new NSString(appIdentifier), new NSString(XamarinShotGameAttribute.AppIdentifier)); - if (this.location != null) - { - discoveryInfo[LocationKey] = new NSString(this.location.Identifier.ToString()); - } - - var advertiser = new MCNearbyServiceAdvertiser(this.myself.PeerId, discoveryInfo, XamarinShotGameService.PlayerService); - advertiser.Delegate = this; - advertiser.StartAdvertisingPeer(); - this.serviceAdvertiser = advertiser; - } - } - - public void StopAdvertising() - { - // stop advertising - this.serviceAdvertiser?.StopAdvertisingPeer(); - this.serviceAdvertiser = null; - } - - /// <summary> - /// for beacon use - /// </summary> - /// <param name="newLocation">New location.</param> - public void UpdateLocation(GameTableLocation newLocation) - { - this.location = newLocation; - } - - #region Actions - - private readonly DispatchQueue messagesQueue = new DispatchQueue("messages", true); - - private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings - { - NullValueHandling = NullValueHandling.Ignore, - ReferenceLoopHandling = ReferenceLoopHandling.Ignore, - Converters = new List<JsonConverter> - { - new Formattings.BoolFormatting(), - new Formattings.SCNVector3Formatting(), - new Formattings.SCNVector4Formatting(), - new Formattings.SCNMatrix4Formatting(), - new Formattings.SCNQuaternionFormatting(), - } - }; - - public void Send(GAction action) - { - if (this.peers.Any()) - { - var peerIds = this.peers.Select(peer => peer.PeerId).ToArray(); - this.Send(action, peerIds); - } - } - - public void Send(GAction action, Player player) - { - this.Send(action, new MCPeerID[] { player.PeerId }); - } - - private void Send(GAction action, MCPeerID[] peerIds) - { - var json = JsonConvert.SerializeObject(action, this.serializerSettings); - this.messagesQueue.DispatchAsync(() => - { - using (var data = NSData.FromString(json)) - { - this.Session.SendData(data, peerIds, MCSessionSendDataMode.Reliable, out NSError error); - } - }); - } - - public void Receive(NSData data, MCPeerID peerID) - { - var player = this.peers.FirstOrDefault(peer => peer.PeerId == peerID); - if (player != null) - { - string json; - using (data) - { - json = NSString.FromData(data, NSStringEncoding.UTF8)?.ToString(); - } - - if (!string.IsNullOrEmpty(json)) - { - var action = JsonConvert.DeserializeObject<GAction>(json); - var command = new GameCommand(player, action); - this.Delegate?.NetworkSessionReceived(this, command); - } - } - } - - #endregion - - #region IMCSessionDelegate - - public void DidChangeState(MCSession session, MCPeerID peerID, MCSessionState state) - { - var player = new Player(peerID); - switch (state) - { - case MCSessionState.Connected: - this.peers.Add(player); - this.Delegate?.NetworkSessionJoining(this, player); - break; - - case MCSessionState.Connecting: - break; - - case MCSessionState.NotConnected: - this.peers.Remove(player); - this.Delegate?.NetworkSessionLeaving(this, player); - break; - } - } - - public void DidReceiveData(MCSession session, NSData data, MCPeerID peerID) - { - this.Receive(data, peerID); - } - - public void DidReceiveStream(MCSession session, NSInputStream stream, string streamName, MCPeerID peerID) - { - // this app doesn't use streams. - } - - public void DidStartReceivingResource(MCSession session, string resourceName, MCPeerID fromPeer, NSProgress progress) - { - // this app doesn't use named resources. - } - - public void DidFinishReceivingResource(MCSession session, string resourceName, MCPeerID fromPeer, NSUrl localUrl, NSError error) - { - if (error == null && localUrl != null) - { - // .mappedIfSafe makes the initializer attempt to map the file directly into memory - // using mmap(2), rather than serially copying the bytes into memory. - // this is faster and our app isn't charged for the memory usage. - var data = NSData.FromUrl(localUrl, NSDataReadingOptions.Mapped, out NSError readError); - if (readError != null) - { - this.Receive(data, fromPeer); - } - - // removing the file is done by the session, so long as we're done with it before the - // delegate method returns. - } - } - - #endregion - - #region IMCNearbyServiceAdvertiserDelegate - - public void DidReceiveInvitationFromPeer(MCNearbyServiceAdvertiser advertiser, MCPeerID peerID, NSData context, MCNearbyServiceAdvertiserInvitationHandler invitationHandler) - { - invitationHandler(true, Session); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using MultipeerConnectivity; + using System.Collections.Generic; + using System.Linq; + using XamarinShot.Utils; + using Newtonsoft.Json; + using CoreFoundation; + + public interface INetworkSessionDelegate { + void NetworkSessionReceived (NetworkSession session, GameCommand command); + + void NetworkSessionJoining (NetworkSession session, Player player); + + void NetworkSessionLeaving (NetworkSession session, Player player); + } + + public class NetworkSession : NSObject, IMCSessionDelegate, IMCNearbyServiceAdvertiserDelegate { + private const string LocationKey = "LocationAttributeName"; + + private readonly List<Player> peers = new List<Player> (); + + private readonly Player myself; + + private GameTableLocation location; + + private MCNearbyServiceAdvertiser serviceAdvertiser; + + private readonly string appIdentifier; + + public NetworkSession (Player myself, bool asServer, GameTableLocation location, Player host) : base () + { + this.myself = myself; + this.Session = new MCSession (this.myself.PeerId, null, MCEncryptionPreference.Required); + this.IsServer = asServer; + this.location = location; + this.Host = host; + + this.appIdentifier = NSBundle.MainBundle.BundleIdentifier; + this.Session.Delegate = this; + } + + public MCSession Session { get; private set; } + + public Player Host { get; private set; } + + public bool IsServer { get; private set; } + + public INetworkSessionDelegate Delegate { get; set; } + + public bool IsAnyActivePeers => this.peers.Any (); + + /// <summary> + /// For use when acting as game server + /// </summary> + public void StartAdvertising () + { + if (this.serviceAdvertiser == null) { + var discoveryInfo = NSDictionary.FromObjectAndKey (new NSString (appIdentifier), new NSString (XamarinShotGameAttribute.AppIdentifier)); + if (this.location != null) { + discoveryInfo [LocationKey] = new NSString (this.location.Identifier.ToString ()); + } + + var advertiser = new MCNearbyServiceAdvertiser (this.myself.PeerId, discoveryInfo, XamarinShotGameService.PlayerService); + advertiser.Delegate = this; + advertiser.StartAdvertisingPeer (); + this.serviceAdvertiser = advertiser; + } + } + + public void StopAdvertising () + { + // stop advertising + this.serviceAdvertiser?.StopAdvertisingPeer (); + this.serviceAdvertiser = null; + } + + /// <summary> + /// for beacon use + /// </summary> + /// <param name="newLocation">New location.</param> + public void UpdateLocation (GameTableLocation newLocation) + { + this.location = newLocation; + } + + #region Actions + + private readonly DispatchQueue messagesQueue = new DispatchQueue ("messages", true); + + private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings { + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Ignore, + Converters = new List<JsonConverter> + { + new Formattings.BoolFormatting(), + new Formattings.SCNVector3Formatting(), + new Formattings.SCNVector4Formatting(), + new Formattings.SCNMatrix4Formatting(), + new Formattings.SCNQuaternionFormatting(), + } + }; + + public void Send (GAction action) + { + if (this.peers.Any ()) { + var peerIds = this.peers.Select (peer => peer.PeerId).ToArray (); + this.Send (action, peerIds); + } + } + + public void Send (GAction action, Player player) + { + this.Send (action, new MCPeerID [] { player.PeerId }); + } + + private void Send (GAction action, MCPeerID [] peerIds) + { + var json = JsonConvert.SerializeObject (action, this.serializerSettings); + this.messagesQueue.DispatchAsync (() => { + using (var data = NSData.FromString (json)) { + this.Session.SendData (data, peerIds, MCSessionSendDataMode.Reliable, out NSError error); + } + }); + } + + public void Receive (NSData data, MCPeerID peerID) + { + var player = this.peers.FirstOrDefault (peer => peer.PeerId == peerID); + if (player != null) { + string json; + using (data) { + json = NSString.FromData (data, NSStringEncoding.UTF8)?.ToString (); + } + + if (!string.IsNullOrEmpty (json)) { + var action = JsonConvert.DeserializeObject<GAction> (json); + var command = new GameCommand (player, action); + this.Delegate?.NetworkSessionReceived (this, command); + } + } + } + + #endregion + + #region IMCSessionDelegate + + public void DidChangeState (MCSession session, MCPeerID peerID, MCSessionState state) + { + var player = new Player (peerID); + switch (state) { + case MCSessionState.Connected: + this.peers.Add (player); + this.Delegate?.NetworkSessionJoining (this, player); + break; + + case MCSessionState.Connecting: + break; + + case MCSessionState.NotConnected: + this.peers.Remove (player); + this.Delegate?.NetworkSessionLeaving (this, player); + break; + } + } + + public void DidReceiveData (MCSession session, NSData data, MCPeerID peerID) + { + this.Receive (data, peerID); + } + + public void DidReceiveStream (MCSession session, NSInputStream stream, string streamName, MCPeerID peerID) + { + // this app doesn't use streams. + } + + public void DidStartReceivingResource (MCSession session, string resourceName, MCPeerID fromPeer, NSProgress progress) + { + // this app doesn't use named resources. + } + + public void DidFinishReceivingResource (MCSession session, string resourceName, MCPeerID fromPeer, NSUrl localUrl, NSError error) + { + if (error == null && localUrl != null) { + // .mappedIfSafe makes the initializer attempt to map the file directly into memory + // using mmap(2), rather than serially copying the bytes into memory. + // this is faster and our app isn't charged for the memory usage. + var data = NSData.FromUrl (localUrl, NSDataReadingOptions.Mapped, out NSError readError); + if (readError != null) { + this.Receive (data, fromPeer); + } + + // removing the file is done by the session, so long as we're done with it before the + // delegate method returns. + } + } + + #endregion + + #region IMCNearbyServiceAdvertiserDelegate + + public void DidReceiveInvitationFromPeer (MCNearbyServiceAdvertiser advertiser, MCPeerID peerID, NSData context, MCNearbyServiceAdvertiserInvitationHandler invitationHandler) + { + invitationHandler (true, Session); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Player.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Player.cs index d411b0f23..4c7235b3e 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Player.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Player.cs @@ -1,37 +1,35 @@ - -namespace XamarinShot.Models -{ - using System; - using MultipeerConnectivity; - - public class Player - { - private readonly int hashValue; - - public Player(MCPeerID peerID) - { - this.PeerId = peerID; - this.hashValue = peerID.GetHashCode(); - } - - public Player(string username) - { - this.PeerId = new MCPeerID(username); - this.hashValue = this.PeerId.GetHashCode(); - } - - public string Username => this.PeerId.DisplayName; - - public MCPeerID PeerId { get; private set; } - - public override bool Equals(object obj) - { - return this.PeerId == (obj as Player)?.PeerId; - } - - public override int GetHashCode() - { - return this.PeerId.GetHashCode(); - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using System; + using MultipeerConnectivity; + + public class Player { + private readonly int hashValue; + + public Player (MCPeerID peerID) + { + this.PeerId = peerID; + this.hashValue = peerID.GetHashCode (); + } + + public Player (string username) + { + this.PeerId = new MCPeerID (username); + this.hashValue = this.PeerId.GetHashCode (); + } + + public string Username => this.PeerId.DisplayName; + + public MCPeerID PeerId { get; private set; } + + public override bool Equals (object obj) + { + return this.PeerId == (obj as Player)?.PeerId; + } + + public override int GetHashCode () + { + return this.PeerId.GetHashCode (); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/ProximityManager.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/ProximityManager.cs index f22dd03f1..690ece348 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/ProximityManager.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/ProximityManager.cs @@ -1,94 +1,85 @@ - -namespace XamarinShot.Models -{ - using CoreLocation; - using Foundation; - using System.Linq; - - public interface IProximityManagerDelegate - { - void LocationChanged(ProximityManager manager, GameTableLocation location); - - void AuthorizationChanged(ProximityManager manager, bool authorization); - } - - public class ProximityManager : CLLocationManagerDelegate - { - private readonly NSUuid RegionUUID = new NSUuid("53FA6CD3-DFE4-493C-8795-56E71D2DAEAF"); - - private const string RegionId = "GameRoom"; - - private readonly CLLocationManager locationManager = new CLLocationManager(); - - private readonly CLBeaconRegion region; - - public ProximityManager() : base() - { - this.region = new CLBeaconRegion(RegionUUID, RegionId); - - this.locationManager.Delegate = this; - this.RequestAuthorization(); - } - - public static ProximityManager Shared { get; } = new ProximityManager(); - - public IProximityManagerDelegate Delegate { get; set; } - - public GameTableLocation ClosestLocation { get; private set; } - - public bool IsAvailable => CLLocationManager.IsMonitoringAvailable(typeof(CLBeaconRegion)); - - public bool IsAuthorized => CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse || - CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways; - - public void Start() - { - if (this.IsAvailable) - { - this.locationManager.StartRangingBeacons(this.region); - } - } - - public void Stop() - { - if (this.IsAvailable) - { - this.locationManager.StopRangingBeacons(region); - } - } - - public override void DidRangeBeacons(CLLocationManager manager, CLBeacon[] beacons, CLBeaconRegion region) - { - // we want to filter out beacons that have unknown proximity - var knownBeacon = beacons.FirstOrDefault(beacon => beacon.Proximity != CLProximity.Unknown); - if (knownBeacon != null) - { - GameTableLocation location = null; - if (knownBeacon.Proximity == CLProximity.Near || knownBeacon.Proximity == CLProximity.Immediate) - { - location = GameTableLocation.GetLocation(knownBeacon.Minor.Int32Value); - } - - if (this.ClosestLocation != location) - { - // Closest location changed - this.ClosestLocation = location; - this.Delegate?.LocationChanged(this, location); - } - } - } - - public override void AuthorizationChanged(CLLocationManager manager, CLAuthorizationStatus status) - { - this.Delegate?.AuthorizationChanged(this, this.IsAuthorized); - } - - private void RequestAuthorization() - { - if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) - { - this.locationManager.RequestWhenInUseAuthorization(); - } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using CoreLocation; + using Foundation; + using System.Linq; + + public interface IProximityManagerDelegate { + void LocationChanged (ProximityManager manager, GameTableLocation location); + + void AuthorizationChanged (ProximityManager manager, bool authorization); + } + + public class ProximityManager : CLLocationManagerDelegate { + private readonly NSUuid RegionUUID = new NSUuid ("53FA6CD3-DFE4-493C-8795-56E71D2DAEAF"); + + private const string RegionId = "GameRoom"; + + private readonly CLLocationManager locationManager = new CLLocationManager (); + + private readonly CLBeaconRegion region; + + public ProximityManager () : base () + { + this.region = new CLBeaconRegion (RegionUUID, RegionId); + + this.locationManager.Delegate = this; + this.RequestAuthorization (); + } + + public static ProximityManager Shared { get; } = new ProximityManager (); + + public IProximityManagerDelegate Delegate { get; set; } + + public GameTableLocation ClosestLocation { get; private set; } + + public bool IsAvailable => CLLocationManager.IsMonitoringAvailable (typeof (CLBeaconRegion)); + + public bool IsAuthorized => CLLocationManager.Status == CLAuthorizationStatus.AuthorizedWhenInUse || + CLLocationManager.Status == CLAuthorizationStatus.AuthorizedAlways; + + public void Start () + { + if (this.IsAvailable) { + this.locationManager.StartRangingBeacons (this.region); + } + } + + public void Stop () + { + if (this.IsAvailable) { + this.locationManager.StopRangingBeacons (region); + } + } + + public override void DidRangeBeacons (CLLocationManager manager, CLBeacon [] beacons, CLBeaconRegion region) + { + // we want to filter out beacons that have unknown proximity + var knownBeacon = beacons.FirstOrDefault (beacon => beacon.Proximity != CLProximity.Unknown); + if (knownBeacon != null) { + GameTableLocation location = null; + if (knownBeacon.Proximity == CLProximity.Near || knownBeacon.Proximity == CLProximity.Immediate) { + location = GameTableLocation.GetLocation (knownBeacon.Minor.Int32Value); + } + + if (this.ClosestLocation != location) { + // Closest location changed + this.ClosestLocation = location; + this.Delegate?.LocationChanged (this, location); + } + } + } + + public override void AuthorizationChanged (CLLocationManager manager, CLAuthorizationStatus status) + { + this.Delegate?.AuthorizationChanged (this, this.IsAuthorized); + } + + private void RequestAuthorization () + { + if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) { + this.locationManager.RequestWhenInUseAuthorization (); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Ray.cs b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Ray.cs index a192ba517..beb3e7afb 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Local Networking/Ray.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Local Networking/Ray.cs @@ -1,20 +1,18 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - public class Ray - { - public Ray(SCNVector3 position, SCNVector3 direction) - { - this.Position = position; - this.Direction = direction; - } +namespace XamarinShot.Models { + using SceneKit; - public SCNVector3 Position { get; set; } + public class Ray { + public Ray (SCNVector3 position, SCNVector3 direction) + { + this.Position = position; + this.Direction = direction; + } - public SCNVector3 Direction { get; set; } + public SCNVector3 Position { get; set; } - public static Ray Zero => new Ray(SCNVector3.Zero, SCNVector3.Zero); - } -} \ No newline at end of file + public SCNVector3 Direction { get; set; } + + public static Ray Zero => new Ray (SCNVector3.Zero, SCNVector3.Zero); + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/CollisionSoundData.cs b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/CollisionSoundData.cs index c74fc4017..3e51d267b 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/CollisionSoundData.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/CollisionSoundData.cs @@ -1,16 +1,14 @@ - -namespace XamarinShot.Models -{ - public class CollisionSoundData - { - public CollisionSoundData(int gameObjectIndex, CollisionEvent soundEvent) - { - this.GameObjectIndex = gameObjectIndex; - this.SoundEvent = soundEvent; - } - public int GameObjectIndex { get; set; } +namespace XamarinShot.Models { + public class CollisionSoundData { + public CollisionSoundData (int gameObjectIndex, CollisionEvent soundEvent) + { + this.GameObjectIndex = gameObjectIndex; + this.SoundEvent = soundEvent; + } - public CollisionEvent SoundEvent { get; set; } - } -} \ No newline at end of file + public int GameObjectIndex { get; set; } + + public CollisionEvent SoundEvent { get; set; } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsNodeData.cs b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsNodeData.cs index cbbe4545f..d77a504ee 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsNodeData.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsNodeData.cs @@ -1,72 +1,66 @@ - -namespace XamarinShot.Models -{ - using Newtonsoft.Json; - using SceneKit; - using XamarinShot.Models.Formattings; - using XamarinShot.Utils; - - [JsonConverter(typeof(PhysicsNodeDataFormatting))] - public class PhysicsNodeData - { - // Below these delta values, node's linear/angular velocity will not sync across - private const float PositionDeltaToConsiderNotMoving = 0.0002f; - - private const float OrientationDeltaToConsiderNotMoving = 0.002f; - - public PhysicsNodeData() { } - - public PhysicsNodeData(SCNNode node, bool alive, Team team = Team.None) - { - this.IsAlive = alive; - this.Team = team; - - var presentationNode = node.PresentationNode; - var newPosition = presentationNode.WorldPosition; - var newOrientation = presentationNode.Orientation; - - this.Position = newPosition; - this.Orientation = newOrientation; - - var physicsBody = node.PhysicsBody; - if (physicsBody != null) - { - // Do not sync across physicsBodies - this.IsMoving = !newPosition.AlmostEqual(this.Position, PositionDeltaToConsiderNotMoving) || - !newOrientation.GetVector().AlmostEqual(this.Orientation.GetVector(), OrientationDeltaToConsiderNotMoving); - - if (this.IsMoving) - { - this.Velocity = physicsBody.Velocity; - this.AngularVelocity = physicsBody.AngularVelocity; - } - else - { - this.Velocity = SCNVector3.Zero; - this.AngularVelocity = SCNVector4.UnitW; - } - } - } - - public bool IsAlive { get; set; } = true; - - public bool IsMoving { get; set; } - - public Team Team { get; set; } = Team.None; - - public SCNVector3 Position { get; set; } = SCNVector3.Zero; - - public SCNQuaternion Orientation { get; set; } = SCNQuaternion.Identity; - - public SCNVector3 Velocity { get; set; } = SCNVector3.Zero; - - public SCNVector4 AngularVelocity { get; set; } = SCNVector4.Zero; - - public override string ToString() - { - var position = this.Position; - var rot = this.Orientation.GetVector(); - return $"isMoving:{this.IsMoving}, pos:{position.X},{position.Y},{position.Z}, rot:{rot.X},{rot.Y},{rot.Z},{rot.W}"; - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Newtonsoft.Json; + using SceneKit; + using XamarinShot.Models.Formattings; + using XamarinShot.Utils; + + [JsonConverter (typeof (PhysicsNodeDataFormatting))] + public class PhysicsNodeData { + // Below these delta values, node's linear/angular velocity will not sync across + private const float PositionDeltaToConsiderNotMoving = 0.0002f; + + private const float OrientationDeltaToConsiderNotMoving = 0.002f; + + public PhysicsNodeData () { } + + public PhysicsNodeData (SCNNode node, bool alive, Team team = Team.None) + { + this.IsAlive = alive; + this.Team = team; + + var presentationNode = node.PresentationNode; + var newPosition = presentationNode.WorldPosition; + var newOrientation = presentationNode.Orientation; + + this.Position = newPosition; + this.Orientation = newOrientation; + + var physicsBody = node.PhysicsBody; + if (physicsBody != null) { + // Do not sync across physicsBodies + this.IsMoving = !newPosition.AlmostEqual (this.Position, PositionDeltaToConsiderNotMoving) || + !newOrientation.GetVector ().AlmostEqual (this.Orientation.GetVector (), OrientationDeltaToConsiderNotMoving); + + if (this.IsMoving) { + this.Velocity = physicsBody.Velocity; + this.AngularVelocity = physicsBody.AngularVelocity; + } else { + this.Velocity = SCNVector3.Zero; + this.AngularVelocity = SCNVector4.UnitW; + } + } + } + + public bool IsAlive { get; set; } = true; + + public bool IsMoving { get; set; } + + public Team Team { get; set; } = Team.None; + + public SCNVector3 Position { get; set; } = SCNVector3.Zero; + + public SCNQuaternion Orientation { get; set; } = SCNQuaternion.Identity; + + public SCNVector3 Velocity { get; set; } = SCNVector3.Zero; + + public SCNVector4 AngularVelocity { get; set; } = SCNVector4.Zero; + + public override string ToString () + { + var position = this.Position; + var rot = this.Orientation.GetVector (); + return $"isMoving:{this.IsMoving}, pos:{position.X},{position.Y},{position.Z}, rot:{rot.X},{rot.Y},{rot.Z},{rot.W}"; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncData.cs b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncData.cs index d50d3a4ae..45523b325 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncData.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncData.cs @@ -1,36 +1,34 @@ - -namespace XamarinShot.Models -{ - using System; - using System.Collections.Generic; - public class PhysicsSyncData - { - public PhysicsSyncData(int packetNumber, - List<PhysicsNodeData> nodeData, - List<PhysicsNodeData> projectileData, - List<CollisionSoundData> soundData) - { - this.PacketNumber = packetNumber; - this.NodeData = nodeData; - this.ProjectileData = projectileData; - this.SoundData = soundData; - } +namespace XamarinShot.Models { + using System; + using System.Collections.Generic; - public int PacketNumber { get; set; } + public class PhysicsSyncData { + public PhysicsSyncData (int packetNumber, + List<PhysicsNodeData> nodeData, + List<PhysicsNodeData> projectileData, + List<CollisionSoundData> soundData) + { + this.PacketNumber = packetNumber; + this.NodeData = nodeData; + this.ProjectileData = projectileData; + this.SoundData = soundData; + } - public List<PhysicsNodeData> NodeData { get; set; } + public int PacketNumber { get; set; } - public List<PhysicsNodeData> ProjectileData { get; set; } + public List<PhysicsNodeData> NodeData { get; set; } - public List<CollisionSoundData> SoundData { get; set; } + public List<PhysicsNodeData> ProjectileData { get; set; } - public static int PacketNumberBits = 12; // 12 bits represents packetNumber reset every minute + public List<CollisionSoundData> SoundData { get; set; } - public static int NodeCountBits = 9; + public static int PacketNumberBits = 12; // 12 bits represents packetNumber reset every minute - public static int MaxPacketNumber = (int)Math.Pow(2d, PacketNumberBits); + public static int NodeCountBits = 9; - public static int HalfMaxPacketNumber = MaxPacketNumber / 2; - } -} \ No newline at end of file + public static int MaxPacketNumber = (int) Math.Pow (2d, PacketNumberBits); + + public static int HalfMaxPacketNumber = MaxPacketNumber / 2; + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncSceneData.cs b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncSceneData.cs index 84b022901..aebfac6bd 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncSceneData.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Physics Synchronization/PhysicsSyncSceneData.cs @@ -1,327 +1,286 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - - public interface IPhysicsSyncSceneDataDelegate - { - void HasNetworkDelayStatusChanged(bool hasNetworkDelay); - - Projectile SpawnProjectile(int objectIndex); - - void DespawnProjectile(Projectile projectile); - - void PlayPhysicsSound(int objectIndex, CollisionEvent soundEvent); - } - - public class PhysicsSyncSceneData - { - private const int PacketCountToSlowDataUsage = 4; - - private const float NetworkDelayStatusLifetime = 3f; - - private const int MaxPacketCount = 8; - - private readonly NSLock @lock = new NSLock();// need thread protection because add used in main thread, while pack used in render update thread - - // Non-projectile sync - private readonly List<GameObject> objectList = new List<GameObject>(); - private List<PhysicsNodeData> nodeDataList = new List<PhysicsNodeData>(); - - // Projectile sync - private readonly List<Projectile> projectileList = new List<Projectile>(); - private List<PhysicsNodeData> projectileDataList = new List<PhysicsNodeData>(); - - // Sound sync - private List<CollisionSoundData> soundDataList = new List<CollisionSoundData>(); - - // Put data into queue to help with stutters caused by data packet delays - private readonly List<PhysicsSyncData> packetQueue = new List<PhysicsSyncData>(); - - private bool shouldRefillPackets = true; - private bool justUpdatedHalfway = false; - private int packetReceived = 0; - - // Network Delay - private double lastNetworkDelay = 0d; - - // Put up a packet number to make sure that packets are in order - private int lastPacketNumberRead = 0; - - public IPhysicsSyncSceneDataDelegate Delegate { get; set; } - - public bool IsInitialized => this.Delegate != null; - - public bool HasNetworkDelay { get; private set; } - - public void AddObject(GameObject @object) - { - var data = @object.GeneratePhysicsData(); - if (data != null) - { - this.@lock.Lock(); - this.objectList.Add(@object); - this.nodeDataList.Add(data); - this.@lock.Unlock(); - } - } - - public PhysicsSyncData GenerateData() - { - this.@lock.Lock(); - - // Update Data of normal nodes - for (var index = 0; index < this.objectList.Count; index++) - { - var data = this.objectList[index].GeneratePhysicsData(); - if (data != null) - { - this.nodeDataList[index] = data; - } - } - - // Update Data of projectiles in the pool - for (var index = 0; index < this.projectileList.Count; index++) - { - var data = this.projectileList[index].GeneratePhysicsData(); - if(data != null) - { - this.projectileDataList[index] = data; - } - } - - // Packet number is used to determined the order of sync data. - // Because Multipeer Connectivity does not guarantee the order of packet delivery, - // we use the packet number to discard out of order packets. - var packetNumber = GameTime.FrameCount % PhysicsSyncData.MaxPacketNumber; - var packet = new PhysicsSyncData(packetNumber, this.nodeDataList, this.projectileDataList, this.soundDataList); - - // Clear sound data since it only needs to be played once - this.soundDataList.Clear(); - this.@lock.Unlock(); - - return packet; - } - - public void UpdateFromReceivedData() - { - this.@lock.Lock(); - this.DiscardOutOfOrderData(); - - if (this.shouldRefillPackets) - { - if (this.packetQueue.Count >= MaxPacketCount) - { - this.shouldRefillPackets = false; - } - - this.@lock.Unlock(); - return; - } - - var oldestData = this.packetQueue.FirstOrDefault(); - if (oldestData != null) - { - // Case when running out of data: Use one packet for two frames - if (this.justUpdatedHalfway) - { - this.UpdateObjectsFromData(false); - this.justUpdatedHalfway = false; - } - else if (this.packetQueue.Count <= PacketCountToSlowDataUsage) - { - if (!this.justUpdatedHalfway) - { - this.Apply(oldestData); - this.packetQueue.RemoveAt(0); - - this.UpdateObjectsFromData(true); - this.justUpdatedHalfway = true; - } - - // Case when enough data: Use one packet per frame as usual - } - else - { - this.Apply(oldestData); - this.packetQueue.RemoveAt(0); - } - } - else - { - this.shouldRefillPackets = true; - //os_log(.info, "out of packets") - - // Update network delay status used to display in sceneViewController - if (!this.HasNetworkDelay) - { - this.Delegate?.HasNetworkDelayStatusChanged(true); - } - - this.HasNetworkDelay = true; - this.lastNetworkDelay = GameTime.Time; - } - - while (this.packetQueue.Count > MaxPacketCount) - { - this.packetQueue.RemoveAt(0); - } - - // Remove networkDelay status after time passsed without a delay - if (this.HasNetworkDelay && GameTime.Time - this.lastNetworkDelay > NetworkDelayStatusLifetime) - { - this.Delegate?.HasNetworkDelayStatusChanged(false); - this.HasNetworkDelay = false; - } - - this.@lock.Unlock(); - } - - public void Receive(PhysicsSyncData packet) - { - this.@lock.Lock(); - - this.packetQueue.Add(packet); - this.packetReceived += 1; - - this.@lock.Unlock(); - } - - private void Apply(PhysicsSyncData packet) - { - this.lastPacketNumberRead = packet.PacketNumber; - this.nodeDataList = packet.NodeData; - this.projectileDataList = packet.ProjectileData; - this.soundDataList = packet.SoundData; - - // Play sound right away and clear the list - if (this.Delegate == null) - { - throw new Exception("No Delegate"); - } - - foreach (var soundData in this.soundDataList) - { - this.Delegate.PlayPhysicsSound(soundData.GameObjectIndex, soundData.SoundEvent); - } - - this.soundDataList.Clear(); - this.UpdateObjectsFromData(false); - } - - private void UpdateObjectsFromData(bool isHalfway) - { - // Update Nodes - var objectCount = Math.Min(this.objectList.Count, this.nodeDataList.Count); - for (var index = 0; index < objectCount; index++) - { - if (this.nodeDataList[index].IsAlive) - { - this.objectList[index].Apply(this.nodeDataList[index], isHalfway); - } - } - - if (this.Delegate == null) - { - throw new Exception("No delegate"); - } - - for (var arrayIndex = 0; arrayIndex < this.projectileList.Count; arrayIndex++) - { - var projectile = this.projectileList[arrayIndex]; - var nodeData = this.projectileDataList[arrayIndex]; - - // If the projectile must be spawned, spawn it. - if (nodeData.IsAlive) - { - // Spawn the projectile if it is exists on the other side, but not here - if (!projectile.IsAlive) - { - projectile = this.Delegate.SpawnProjectile(projectile.Index); - projectile.Team = nodeData.Team; - this.projectileList[arrayIndex] = projectile; - } - - projectile.Apply(nodeData, isHalfway); - } - else - { - // Despawn the projectile if it was despawned on the other side - if (projectile.IsAlive) - { - this.Delegate.DespawnProjectile(projectile); - } - } - } - } - - private void DiscardOutOfOrderData() - { - // Discard data that are out of order - var oldestData = this.packetQueue.FirstOrDefault(); - while (oldestData != null) - { - var packetNumber = oldestData.PacketNumber; - // If packet number of more than last packet number, then it is in order. - // For the edge case where packet number resets to 0 again, we test if the difference is more than half the max packet number. - if (packetNumber > this.lastPacketNumberRead || - (this.lastPacketNumberRead - packetNumber) > PhysicsSyncData.HalfMaxPacketNumber) - { - break; - } - else - { - //os_log(.error, "Packet out of order") - this.packetQueue.RemoveAt(0); - } - - oldestData = this.packetQueue.FirstOrDefault(); - } - } - - #region Projectile Sync - - public void AddProjectile(Projectile projectile) - { - var data = projectile.GeneratePhysicsData(); - if (data != null) - { - this.@lock.Lock(); - this.projectileList.Add(projectile); - this.projectileDataList.Add(data); - this.@lock.Unlock(); - } - } - - public void ReplaceProjectile(Projectile projectile) - { - this.@lock.Lock(); - - var oldProjectile = this.projectileList.FirstOrDefault(tile => tile.Index == projectile.Index); - if (oldProjectile != null) - { - this.projectileList[this.projectileList.IndexOf(oldProjectile)] = projectile; - } - else - { - throw new Exception($"Cannot find the projectile to replace {projectile.Index}"); - } - - this.@lock.Unlock(); - } - - #endregion - - #region Sound Sync - - public void AddSound(int gameObjectIndex, CollisionEvent soundEvent) - { - this.soundDataList.Add(new CollisionSoundData(gameObjectIndex, soundEvent)); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + + public interface IPhysicsSyncSceneDataDelegate { + void HasNetworkDelayStatusChanged (bool hasNetworkDelay); + + Projectile SpawnProjectile (int objectIndex); + + void DespawnProjectile (Projectile projectile); + + void PlayPhysicsSound (int objectIndex, CollisionEvent soundEvent); + } + + public class PhysicsSyncSceneData { + private const int PacketCountToSlowDataUsage = 4; + + private const float NetworkDelayStatusLifetime = 3f; + + private const int MaxPacketCount = 8; + + private readonly NSLock @lock = new NSLock ();// need thread protection because add used in main thread, while pack used in render update thread + + // Non-projectile sync + private readonly List<GameObject> objectList = new List<GameObject> (); + private List<PhysicsNodeData> nodeDataList = new List<PhysicsNodeData> (); + + // Projectile sync + private readonly List<Projectile> projectileList = new List<Projectile> (); + private List<PhysicsNodeData> projectileDataList = new List<PhysicsNodeData> (); + + // Sound sync + private List<CollisionSoundData> soundDataList = new List<CollisionSoundData> (); + + // Put data into queue to help with stutters caused by data packet delays + private readonly List<PhysicsSyncData> packetQueue = new List<PhysicsSyncData> (); + + private bool shouldRefillPackets = true; + private bool justUpdatedHalfway = false; + private int packetReceived = 0; + + // Network Delay + private double lastNetworkDelay = 0d; + + // Put up a packet number to make sure that packets are in order + private int lastPacketNumberRead = 0; + + public IPhysicsSyncSceneDataDelegate Delegate { get; set; } + + public bool IsInitialized => this.Delegate != null; + + public bool HasNetworkDelay { get; private set; } + + public void AddObject (GameObject @object) + { + var data = @object.GeneratePhysicsData (); + if (data != null) { + this.@lock.Lock (); + this.objectList.Add (@object); + this.nodeDataList.Add (data); + this.@lock.Unlock (); + } + } + + public PhysicsSyncData GenerateData () + { + this.@lock.Lock (); + + // Update Data of normal nodes + for (var index = 0; index < this.objectList.Count; index++) { + var data = this.objectList [index].GeneratePhysicsData (); + if (data != null) { + this.nodeDataList [index] = data; + } + } + + // Update Data of projectiles in the pool + for (var index = 0; index < this.projectileList.Count; index++) { + var data = this.projectileList [index].GeneratePhysicsData (); + if (data != null) { + this.projectileDataList [index] = data; + } + } + + // Packet number is used to determined the order of sync data. + // Because Multipeer Connectivity does not guarantee the order of packet delivery, + // we use the packet number to discard out of order packets. + var packetNumber = GameTime.FrameCount % PhysicsSyncData.MaxPacketNumber; + var packet = new PhysicsSyncData (packetNumber, this.nodeDataList, this.projectileDataList, this.soundDataList); + + // Clear sound data since it only needs to be played once + this.soundDataList.Clear (); + this.@lock.Unlock (); + + return packet; + } + + public void UpdateFromReceivedData () + { + this.@lock.Lock (); + this.DiscardOutOfOrderData (); + + if (this.shouldRefillPackets) { + if (this.packetQueue.Count >= MaxPacketCount) { + this.shouldRefillPackets = false; + } + + this.@lock.Unlock (); + return; + } + + var oldestData = this.packetQueue.FirstOrDefault (); + if (oldestData != null) { + // Case when running out of data: Use one packet for two frames + if (this.justUpdatedHalfway) { + this.UpdateObjectsFromData (false); + this.justUpdatedHalfway = false; + } else if (this.packetQueue.Count <= PacketCountToSlowDataUsage) { + if (!this.justUpdatedHalfway) { + this.Apply (oldestData); + this.packetQueue.RemoveAt (0); + + this.UpdateObjectsFromData (true); + this.justUpdatedHalfway = true; + } + + // Case when enough data: Use one packet per frame as usual + } else { + this.Apply (oldestData); + this.packetQueue.RemoveAt (0); + } + } else { + this.shouldRefillPackets = true; + //os_log(.info, "out of packets") + + // Update network delay status used to display in sceneViewController + if (!this.HasNetworkDelay) { + this.Delegate?.HasNetworkDelayStatusChanged (true); + } + + this.HasNetworkDelay = true; + this.lastNetworkDelay = GameTime.Time; + } + + while (this.packetQueue.Count > MaxPacketCount) { + this.packetQueue.RemoveAt (0); + } + + // Remove networkDelay status after time passsed without a delay + if (this.HasNetworkDelay && GameTime.Time - this.lastNetworkDelay > NetworkDelayStatusLifetime) { + this.Delegate?.HasNetworkDelayStatusChanged (false); + this.HasNetworkDelay = false; + } + + this.@lock.Unlock (); + } + + public void Receive (PhysicsSyncData packet) + { + this.@lock.Lock (); + + this.packetQueue.Add (packet); + this.packetReceived += 1; + + this.@lock.Unlock (); + } + + private void Apply (PhysicsSyncData packet) + { + this.lastPacketNumberRead = packet.PacketNumber; + this.nodeDataList = packet.NodeData; + this.projectileDataList = packet.ProjectileData; + this.soundDataList = packet.SoundData; + + // Play sound right away and clear the list + if (this.Delegate == null) { + throw new Exception ("No Delegate"); + } + + foreach (var soundData in this.soundDataList) { + this.Delegate.PlayPhysicsSound (soundData.GameObjectIndex, soundData.SoundEvent); + } + + this.soundDataList.Clear (); + this.UpdateObjectsFromData (false); + } + + private void UpdateObjectsFromData (bool isHalfway) + { + // Update Nodes + var objectCount = Math.Min (this.objectList.Count, this.nodeDataList.Count); + for (var index = 0; index < objectCount; index++) { + if (this.nodeDataList [index].IsAlive) { + this.objectList [index].Apply (this.nodeDataList [index], isHalfway); + } + } + + if (this.Delegate == null) { + throw new Exception ("No delegate"); + } + + for (var arrayIndex = 0; arrayIndex < this.projectileList.Count; arrayIndex++) { + var projectile = this.projectileList [arrayIndex]; + var nodeData = this.projectileDataList [arrayIndex]; + + // If the projectile must be spawned, spawn it. + if (nodeData.IsAlive) { + // Spawn the projectile if it is exists on the other side, but not here + if (!projectile.IsAlive) { + projectile = this.Delegate.SpawnProjectile (projectile.Index); + projectile.Team = nodeData.Team; + this.projectileList [arrayIndex] = projectile; + } + + projectile.Apply (nodeData, isHalfway); + } else { + // Despawn the projectile if it was despawned on the other side + if (projectile.IsAlive) { + this.Delegate.DespawnProjectile (projectile); + } + } + } + } + + private void DiscardOutOfOrderData () + { + // Discard data that are out of order + var oldestData = this.packetQueue.FirstOrDefault (); + while (oldestData != null) { + var packetNumber = oldestData.PacketNumber; + // If packet number of more than last packet number, then it is in order. + // For the edge case where packet number resets to 0 again, we test if the difference is more than half the max packet number. + if (packetNumber > this.lastPacketNumberRead || + (this.lastPacketNumberRead - packetNumber) > PhysicsSyncData.HalfMaxPacketNumber) { + break; + } else { + //os_log(.error, "Packet out of order") + this.packetQueue.RemoveAt (0); + } + + oldestData = this.packetQueue.FirstOrDefault (); + } + } + + #region Projectile Sync + + public void AddProjectile (Projectile projectile) + { + var data = projectile.GeneratePhysicsData (); + if (data != null) { + this.@lock.Lock (); + this.projectileList.Add (projectile); + this.projectileDataList.Add (data); + this.@lock.Unlock (); + } + } + + public void ReplaceProjectile (Projectile projectile) + { + this.@lock.Lock (); + + var oldProjectile = this.projectileList.FirstOrDefault (tile => tile.Index == projectile.Index); + if (oldProjectile != null) { + this.projectileList [this.projectileList.IndexOf (oldProjectile)] = projectile; + } else { + throw new Exception ($"Cannot find the projectile to replace {projectile.Index}"); + } + + this.@lock.Unlock (); + } + + #endregion + + #region Sound Sync + + public void AddSound (int gameObjectIndex, CollisionEvent soundEvent) + { + this.soundDataList.Add (new CollisionSoundData (gameObjectIndex, soundEvent)); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/Catapult.cs b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/Catapult.cs index 87585ab17..ef08f5e6f 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/Catapult.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/Catapult.cs @@ -1,1086 +1,993 @@ - -namespace XamarinShot.Models -{ - using AVFoundation; - using CoreImage; - using Foundation; - using SceneKit; - using XamarinShot.Models.Enums; - using XamarinShot.Models.GameplayState; - using XamarinShot.Models.Interactions; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using UIKit; - - public enum Team - { - None = 0, // default - TeamA, - TeamB - } - - public static class TeamExtensions - { - public static string GetDescription(this Team team) - { - switch (team) - { - case Team.None: return NSBundle.MainBundle.GetLocalizedString("none"); - case Team.TeamA: return NSBundle.MainBundle.GetLocalizedString("Blue"); - case Team.TeamB: return NSBundle.MainBundle.GetLocalizedString("Yellow"); - } - throw new NotImplementedException(); - } - - public static UIColor GetColor(this Team team) - { - switch (team) - { - case Team.None: return UIColor.White; - case Team.TeamA: return UIColorExtensions.Create(45, 128, 208); - case Team.TeamB: return UIColorExtensions.Create(239, 153, 55); - } - throw new NotImplementedException(); - } - } - - public static class UIColorExtensions - { - public static UIColor Create(byte hexRed, byte green, byte blue) - { - var fred = (float)hexRed / 255f; - var fgreen = (float)green / 255f; - var fblue = (float)blue / 255f; - - return new UIColor(fred, fgreen, fblue, 1f); - } - } - - public interface ICatapultDelegate - { - void DidBeginGrab(Catapult catapult); - void DidMove(Catapult catapult, float stretchDistance, float stretchRate); - void DidLaunch(Catapult catapult, GameVelocity velocity); - void DidBreak(Catapult catapult, bool justKnockedout, bool vortex); - } - - public class CatapultProperties - { - // angle of rotation around base from 0 - public double MinYaw { get; set; } = -45.0; - public double MaxYaw { get; set; } = 45.0; - - // angle of rotation up/down to angle shots - public double MinPitch { get; set; } = -30.0; - public double MaxPitch { get; set; } = 30.0; - - // when launched, the pull distance is normalized and scaled to this (linear not exponential power) - public double MinVelocity { get; set; } = 1.0; // so the ball doesn't just drop and take out your own stuff - public double MaxVelocity { get; set; } = 50.0; - - // when pulled, these are the min/max stretch of pull - public double MinStretch { get; set; } = 0.05; // always have some energy, so ball doesn't just drop - public double MaxStretch { get; set; } = 5.0; // ball will poke through sling if bigger - - // these animations play with these times - public double GrowAnimationTime { get; set; } = 0.2; - public double DropAnimationTime { get; set; } = 0.3; - public double GrabAnimationTime { get; set; } = 0.15; // don't set to 0.2, ball/sling separate - - // before another ball appears, there is a cooldown and the grow/drop animation - public double CooldownTime { get; set; } = 3.0; - - // how close payer has to be from the pull to grab it - public double PickRadius { get; set; } = 5.0; - } - - public enum StrapVisible - { - Hidden, - Visible - } - - public enum BallVisible - { - Hidden, - Partial, - Visible, - } - - // Catapult provides an interface which users can use to manipulate the sling - // CatapultInteraction which represents player's interaction with the catapult use these interfaces to manipulate catapult locally - // Network sync is handled by CatapultInteraction - public class Catapult : GameObject, IGrabbable - { - // convenience for idenfifying catapult during collisions - private const string CollisionKey = "id"; - - private readonly CatapultProperties properties = new CatapultProperties(); - - // highlight assistance - private readonly UIColor highlightColor = UIColor.White; - - // for audio: - private readonly AVAudioEnvironmentNode audioEnvironment; - - private readonly SCNNode catapultStrap; - - // Can drop the ball from the active to below with a transaction. - // Below rests on the strap, and above is above that at the top of the fork. - // This must be finish before the catapult can be grabbed, or the transition - // animations will compete. - private readonly SCNNode ballOriginInactiveAbove; - private readonly SCNNode ballOriginInactiveBelow; - - // This is a rope simulator only for the new catapult. - private readonly CatapultRope rope; - - // original world position of sling to restore the position to - private SCNVector3 baseWorldPosition = SCNVector3.Zero; - - // Projectiles are fired out of the local -Z axis direction. (worldFront) - // This is the upper center of the base where projectiles are fired through. - private SCNNode pullOrigin; - - private bool ballCanBeGrabbed; - - // The starting position of the player when they grab the pull - private SCNVector3 playerWorldPosition = SCNVector3.Zero; - - // Can only pull back the slingshot for now. Eventually will be able to direct shots within a cone. - private double stretch = 0d; - private double lastStretch = 0d; - private double lastStretchTime = 0d; - - // Track the start of the grab. Can use for time exceeded auto-launch. - private double firstGrabTime = 0d; - - // Stores the last launch of a projectile. Cooldown while sling animates and bounces back. - private double lastLaunchTime = 0d; - - private SCNVector3 projectileScale = SCNVector3.One; - - public Catapult(SCNNode node, SFXCoordinator sfxCoordinator, int identifier, Dictionary<string, object> gamedefs) : base(node, null, gamedefs, true, false) - { - this.Base = node; - this.audioEnvironment = sfxCoordinator.AudioEnvironment; - - // Base teamID and name off looking up teamA or teamB folder in the level parents - // This won't work on the old levels. - this.Team = this.Base.GetTeam(); - this.TeamName = this.Team.GetDescription(); - - // have team id established - this.Base.SetPaintColors(); - - // correct for the pivot point to place catapult flat on ground - this.Base.Position = new SCNVector3(this.Base.Position.X, this.Base.Position.Y - 0.13f, this.Base.Position.Z); - - // highlight setup - this.HighlightObject = node.FindChildNode("Highlight", true); - if (this.HighlightObject != null) - { - this.HighlightObject = this.HighlightObject.FindNodeWithGeometry(); - } - - // hide the highlights on load - if (this.HighlightObject != null) - { - this.HighlightObject.Hidden = true; - } - if (this.HighlightObject?.Geometry?.FirstMaterial?.Diffuse?.Contents is UIColor color) - { - this.highlightColor = color; - } +namespace XamarinShot.Models { + using AVFoundation; + using CoreImage; + using Foundation; + using SceneKit; + using XamarinShot.Models.Enums; + using XamarinShot.Models.GameplayState; + using XamarinShot.Models.Interactions; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using UIKit; + + public enum Team { + None = 0, // default + TeamA, + TeamB + } + + public static class TeamExtensions { + public static string GetDescription (this Team team) + { + switch (team) { + case Team.None: return NSBundle.MainBundle.GetLocalizedString ("none"); + case Team.TeamA: return NSBundle.MainBundle.GetLocalizedString ("Blue"); + case Team.TeamB: return NSBundle.MainBundle.GetLocalizedString ("Yellow"); + } + throw new NotImplementedException (); + } + + public static UIColor GetColor (this Team team) + { + switch (team) { + case Team.None: return UIColor.White; + case Team.TeamA: return UIColorExtensions.Create (45, 128, 208); + case Team.TeamB: return UIColorExtensions.Create (239, 153, 55); + } + throw new NotImplementedException (); + } + } + + public static class UIColorExtensions { + public static UIColor Create (byte hexRed, byte green, byte blue) + { + var fred = (float) hexRed / 255f; + var fgreen = (float) green / 255f; + var fblue = (float) blue / 255f; + + return new UIColor (fred, fgreen, fblue, 1f); + } + } + + public interface ICatapultDelegate { + void DidBeginGrab (Catapult catapult); + void DidMove (Catapult catapult, float stretchDistance, float stretchRate); + void DidLaunch (Catapult catapult, GameVelocity velocity); + void DidBreak (Catapult catapult, bool justKnockedout, bool vortex); + } + + public class CatapultProperties { + // angle of rotation around base from 0 + public double MinYaw { get; set; } = -45.0; + public double MaxYaw { get; set; } = 45.0; + + // angle of rotation up/down to angle shots + public double MinPitch { get; set; } = -30.0; + public double MaxPitch { get; set; } = 30.0; + + // when launched, the pull distance is normalized and scaled to this (linear not exponential power) + public double MinVelocity { get; set; } = 1.0; // so the ball doesn't just drop and take out your own stuff + public double MaxVelocity { get; set; } = 50.0; + + // when pulled, these are the min/max stretch of pull + public double MinStretch { get; set; } = 0.05; // always have some energy, so ball doesn't just drop + public double MaxStretch { get; set; } = 5.0; // ball will poke through sling if bigger + + // these animations play with these times + public double GrowAnimationTime { get; set; } = 0.2; + public double DropAnimationTime { get; set; } = 0.3; + public double GrabAnimationTime { get; set; } = 0.15; // don't set to 0.2, ball/sling separate + + // before another ball appears, there is a cooldown and the grow/drop animation + public double CooldownTime { get; set; } = 3.0; + + // how close payer has to be from the pull to grab it + public double PickRadius { get; set; } = 5.0; + } + + public enum StrapVisible { + Hidden, + Visible + } + + public enum BallVisible { + Hidden, + Partial, + Visible, + } + + // Catapult provides an interface which users can use to manipulate the sling + // CatapultInteraction which represents player's interaction with the catapult use these interfaces to manipulate catapult locally + // Network sync is handled by CatapultInteraction + public class Catapult : GameObject, IGrabbable { + // convenience for idenfifying catapult during collisions + private const string CollisionKey = "id"; + + private readonly CatapultProperties properties = new CatapultProperties (); + + // highlight assistance + private readonly UIColor highlightColor = UIColor.White; + + // for audio: + private readonly AVAudioEnvironmentNode audioEnvironment; + + private readonly SCNNode catapultStrap; + + // Can drop the ball from the active to below with a transaction. + // Below rests on the strap, and above is above that at the top of the fork. + // This must be finish before the catapult can be grabbed, or the transition + // animations will compete. + private readonly SCNNode ballOriginInactiveAbove; + private readonly SCNNode ballOriginInactiveBelow; + + // This is a rope simulator only for the new catapult. + private readonly CatapultRope rope; + + // original world position of sling to restore the position to + private SCNVector3 baseWorldPosition = SCNVector3.Zero; + + // Projectiles are fired out of the local -Z axis direction. (worldFront) + // This is the upper center of the base where projectiles are fired through. + private SCNNode pullOrigin; + + private bool ballCanBeGrabbed; + + // The starting position of the player when they grab the pull + private SCNVector3 playerWorldPosition = SCNVector3.Zero; + + // Can only pull back the slingshot for now. Eventually will be able to direct shots within a cone. + private double stretch = 0d; + private double lastStretch = 0d; + private double lastStretchTime = 0d; + + // Track the start of the grab. Can use for time exceeded auto-launch. + private double firstGrabTime = 0d; + + // Stores the last launch of a projectile. Cooldown while sling animates and bounces back. + private double lastLaunchTime = 0d; + + private SCNVector3 projectileScale = SCNVector3.One; + + public Catapult (SCNNode node, SFXCoordinator sfxCoordinator, int identifier, Dictionary<string, object> gamedefs) : base (node, null, gamedefs, true, false) + { + this.Base = node; + this.audioEnvironment = sfxCoordinator.AudioEnvironment; - // they should only have y orientation, nothing in x or z - // current scene files have the catapults with correct orientation, but the - // eulerAngles are different - x and z are both π, y is within epsilon of 0 - // That's from bad decomposition of the matrix. Need to restore the eulerAngles from the source. - // Especially if we have animations tied to the euler angles. - if (Math.Abs(node.EulerAngles.X) > 0.001f || Math.Abs(node.EulerAngles.Z) > 0.001f) - { - //Console.WriteLine("Catapult can only have y rotation applied"); - } + // Base teamID and name off looking up teamA or teamB folder in the level parents + // This won't work on the old levels. + this.Team = this.Base.GetTeam (); + this.TeamName = this.Team.GetDescription (); - // where to place the ball so it sits on the strap - this.catapultStrap = this.Base.FindChildNode("catapultStrap", true); - if (this.catapultStrap == null) - { - throw new Exception("No node with name catapultStrap"); - } + // have team id established + this.Base.SetPaintColors (); - // this only rotates, and represents the center of the catapult through which to fire - this.pullOrigin = this.Base.FindChildNode("pullOrigin", true); - if (this.pullOrigin == null) - { - throw new Exception("No node with name pullOrigin"); - } + // correct for the pivot point to place catapult flat on ground + this.Base.Position = new SCNVector3 (this.Base.Position.X, this.Base.Position.Y - 0.13f, this.Base.Position.Z); - // This is a rope simulation meant for a fixed catapult, the catapult rotates. - this.rope = new CatapultRope(node); - - // attach ball to the inactive strap, search for ballOriginInactiveBelow - this.ballOriginInactiveBelow = this.Base.FindChildNode("ballOriginInactiveBelow", true); - if (this.ballOriginInactiveBelow == null) - { - throw new Exception("No node with name ballOriginInactiveBelow"); - } - - this.ballOriginInactiveAbove = this.Base.FindChildNode("ballOriginInactiveAbove", true); - if (this.ballOriginInactiveAbove == null) - { - throw new Exception("No node with name ballOriginInactiveAbove"); - } - - // ball will be made visible and drop once projectile is set and cooldown exceeded - this.StrapVisible = StrapVisible.Visible; - - this.CatapultId = identifier; - - this.Base.SetValueForKey(NSObject.FromObject(this.CatapultId), new NSString(Catapult.CollisionKey)); - - this.AudioPlayer = new CatapultAudioSampler(this.Base, sfxCoordinator); - - // use the teamID to set the collision category mask - if (this.PhysicsNode?.PhysicsBody != null) - { - if (this.Team == Team.TeamA) - { - this.PhysicsNode.PhysicsBody.CategoryBitMask = (int)CollisionMask.CatapultTeamA; - var collisionBitMask = (CollisionMask)(int)this.PhysicsNode.PhysicsBody.CollisionBitMask; - this.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint)(int)(collisionBitMask | CollisionMask.CatapultTeamB); - } - else if (this.Team == Team.TeamB) - { - this.PhysicsNode.PhysicsBody.CategoryBitMask = (int)CollisionMask.CatapultTeamB; - var collisionBitMask = (CollisionMask)(int)this.PhysicsNode.PhysicsBody.CollisionBitMask; - this.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint)(int)(collisionBitMask | CollisionMask.CatapultTeamA); - } - } - } - - public Catapult(NSCoder coder) : base(coder) => throw new NotImplementedException("init(coder:) has not been implemented"); - - public double CoolDownTime => this.properties.CooldownTime; - - public SCNNode Base { get; } - - public ICatapultDelegate Delegate { get; set; } - - public bool IsPulledTooFar { get; private set; } - - public CameraInfo LastCameraInfo { get; set; } = new CameraInfo(SCNMatrix4.Identity); - - public SCNNode Projectile { get; private set; } - - public ProjectileType ProjectileType { get; private set; } = ProjectileType.None; - - public bool Disabled { get; private set; } - - public CatapultAudioSampler AudioPlayer { get; private set; } - - // Each catapult has a unique index. - // 1-3 are on one side, 4-6 are on the other side - public int CatapultId { get; private set; } = 0; - - public Team Team { get; private set; } = Team.None; - - public string TeamName { get; private set; } - - // highlight assistance - public SCNVector3 ProjectedPosition { get; set; } = SCNVector3.Zero; - - public SCNNode HighlightObject { get; private set; } - - /// <summary> - /// Grabbable Id to be set by GrabInteraction - /// </summary> - public int GrabbableId { get; set; } = 0; - - // Player who grabbed a catapult. A player can only operate one catapult at a time. - // Players/teams may be restricted to a set of catapults. - // Note: Player setting is managed by CatapultInteraction which will resolves sync. - // Player do not get set in clients, since clients do not need to know who grabbed the catapult, - // whereas server needs to know the player owning the catapult to avoid conflicts. - public Player Player { get; set; } - - private bool isGrabbed; - - public bool IsGrabbed - { - get - { - return this.isGrabbed; - } - - // In the case of clients, actual player owner does not need to be known - set - { - this.isGrabbed = value; - if (!this.isGrabbed) - { - this.Player = null; - } - } - } - - /// <summary> - /// Highlight assistance - /// </summary> - /// <value><c>true</c> if is visible; otherwise, <c>false</c>.</value> - public bool IsVisible { get; set; } - - /// <summary> - /// Highlight assistance - /// </summary> - public bool IsHighlighted { get; private set; } - - private StrapVisible strapVisible = StrapVisible.Hidden; - public StrapVisible StrapVisible - { - get - { - return this.strapVisible; - } - - set - { - this.strapVisible = value; - this.UpdateStrapVisibility(); - } - } - - private void UpdateStrapVisibility() - { - switch (this.strapVisible) - { - case StrapVisible.Hidden: - this.catapultStrap.Hidden = true; - break; - - case StrapVisible.Visible: - this.catapultStrap.Hidden = false; - break; - } - } - - private BallVisible ballVisible = BallVisible.Hidden; - /// <summary> - /// Whether the ball in the sling is visible or partially visible. - /// </summary> - public BallVisible BallVisible - { - get - { - return this.ballVisible; - } - - set - { - this.ballVisible = value; - this.UpdateFakeProjectileVisibility(); - } - } - - private void UpdateFakeProjectileVisibility() - { - switch (ballVisible) - { - case BallVisible.Hidden: - if (this.Projectile != null) - { - this.Projectile.Opacity = 1f; - this.Projectile.Hidden = true; - this.Projectile.WorldPosition = this.ballOriginInactiveAbove.WorldPosition; - this.Projectile.Scale = new SCNVector3(0.01f, 0.01f, 0.01f); - } - break; - - case BallVisible.Partial: - if (this.Projectile != null) - { - this.Projectile.Opacity = 1f; - this.Projectile.Hidden = false; - this.AnimateBallGrowAndDrop(); - } - break; - - case BallVisible.Visible: - if (this.Projectile != null) - { - this.Projectile.Opacity = 1f; - this.Projectile.Hidden = false; - // it's in the strap fromn .partial animation - } - break; - } - } - - public void AnimationRopeToRestPose(double duration) - { - this.rope.InterpolateToRestPoseAnimation(duration); - } - - public void AnimateBallGrowAndDrop() - { - // the block is the total time of the transcation, so sub-blocks are limited by that too - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = this.properties.GrowAnimationTime; - - // correct the rope sim by animating back to reset pose no matter what - var fixupLaunchAnimationTime = 0.1f; - this.rope.InterpolateToRestPoseAnimation(fixupLaunchAnimationTime); - - // first scale the ball from small to original size - if (this.Projectile != null) - { - this.Projectile.Scale = this.projectileScale; - } - - SCNTransaction.SetCompletionBlock(() => - { - // after back to scale, then run the ball drop - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = this.properties.DropAnimationTime; - - // next drop from ballOriginInactiveAbove to ballOriginInactive - if (this.Projectile != null) - { - this.Projectile.WorldPosition = this.ballOriginInactiveBelow.WorldPosition; - } - - SCNTransaction.SetCompletionBlock(() => - { - // only allow the ball to be grabbed after animation completes - this.ballCanBeGrabbed = true; - }); - - SCNTransaction.Commit(); - }); - - SCNTransaction.Commit(); - } - - /// <summary> - /// Distance away from catapult base - /// </summary> - public float DistanceFrom(SCNVector3 worldPosition) - { - var distance = worldPosition - this.Base.WorldPosition; - return distance.Length; - } - - public static SCNNode ReplaceCatapultPlaceholder(SCNNode placeholder) - { - var node = SCNNodeExtensions.LoadSCNAsset("catapult"); - - // somehow setting the world transform doesn't update the Euler angles (180, 0, 180) is decoded - // but need it to be 0, 180, 0 - node.Transform = placeholder.Transform; - node.EulerAngles = placeholder.EulerAngles; - - // Add physics body to it - node.WorldPosition += new SCNVector3(0f, 0.2f, 0f); - node.PhysicsBody?.ResetTransform(); - - var baseGeomNode = node.FindChildNode("catapultBase", true); - if (baseGeomNode == null) - { - throw new Exception("No catapultBase"); - } - - var prongGeomNode = node.FindChildNode("catapultProngs", true); - if (prongGeomNode == null) - { - throw new Exception("No catapultProngs"); - } - - // shift center of mass of the prong from the bottom - // the 0.55 value is from experimentation - var prongPivotShiftUp = new SCNVector3(0f, 0.55f, 0f); - prongGeomNode.Pivot = SCNMatrix4.CreateTranslation(prongPivotShiftUp); - prongGeomNode.Position += prongPivotShiftUp; - - var baseShape = SCNPhysicsShape.Create(baseGeomNode, new SCNPhysicsShapeOptions() { ShapeType = SCNPhysicsShapeType.ConvexHull }); - var prongShape = SCNPhysicsShape.Create(prongGeomNode, new SCNPhysicsShapeOptions() { ShapeType = SCNPhysicsShapeType.ConvexHull }); - - var compoundShape = SCNPhysicsShape.Create(new SCNPhysicsShape[] { baseShape, prongShape }, - new SCNMatrix4[] { SCNMatrix4.Identity, SCNMatrix4.Identity }); - if (node.PhysicsBody != null) - { - node.PhysicsBody.PhysicsShape = compoundShape; - } - - // rename back to placeholder name must happen after gameObject is assigned - // currently placeholders are all Catapult1 to Catapult6, they may be under a teamA, teamB parent - // so stash the placeholder name for later - if (!string.IsNullOrEmpty(placeholder.Name)) - { - node.SetValueForKey(new NSString(placeholder.Name), new NSString("nameRestore")); - } - - placeholder.ParentNode.ReplaceChildNode(placeholder, node); - - node.Name = "catapult"; - - return node; - } - - public void SetProjectileType(ProjectileType projectileType, SCNNode projectile) - { - this.Projectile?.RemoveFromParentNode(); - this.Projectile = projectile; - this.ProjectileType = projectileType; - this.projectileScale = projectile.Scale; - - // the rope adjusts to the radius of the ball - var projectilePaddingScale = 1f; - - nfloat radius = 0f; - var temp = SCNVector3.Zero; - projectile.GetBoundingSphere(ref temp, ref radius); - this.rope.SetBallRadius((float)radius * projectilePaddingScale); - - // need ball to set a teamID, and then can color with same mechanism - //projectile.setPaintColor() - - // will be made visible and drop when cooldown is exceeded, - // this way ball doesn't change suddenly while visible - this.BallVisible = BallVisible.Hidden; - this.UpdateFakeProjectileVisibility(); - } - - public void UpdateProperties() - { - this.properties.MinStretch = this.PropDouble("minStretch").Value; - this.properties.MaxStretch = this.PropDouble("maxStretch").Value; - - this.properties.MinYaw = this.PropDouble("minYaw").Value; - this.properties.MaxYaw = this.PropDouble("maxYaw").Value; - - this.properties.MinPitch = this.PropDouble("minPitch").Value; - this.properties.MaxPitch = this.PropDouble("maxPitch").Value; - - this.properties.MinVelocity = this.PropDouble("minVelocity").Value; - this.properties.MaxVelocity = this.PropDouble("maxVelocity").Value; - - this.properties.CooldownTime = this.PropDouble("cooldownTime").Value; - this.properties.PickRadius = this.PropDouble("pickRadius").Value; - } - - #region Catapult Grab - - public bool CanGrab(Ray cameraRay) - { - if (this.isGrabbed) - { - return false; - } - - if (this.Disabled) - { - return false; - } - - // there is a cooldown timer before you can launch again - // when animation completes this will be set to true - if (!this.ballCanBeGrabbed) - { - return false; - } - - if (!this.isCatapultStable) - { - return false; - } - - if (!this.HitTestPull(cameraRay)) - { - return false; - } - - return true; - } - - private bool HitTestPull(Ray cameraRay) - { - // Careful not to make this too large or you'll pick a neighboring slingshot or one across the table. - // We're not sorting hits across all of the slignshots and picking the smallest, but we visit them all. - // Within radius behind the ball/pull allow the slingshot to be picked. - var playerDistanceFromPull = cameraRay.Position - this.pullOrigin.WorldPosition; - - // This is a linear distance along the current firing direction of the catapult - // Just using it here to make sure you're behind the pull (the pull is visible). - var stretchDistance = SCNVector3.Dot(playerDistanceFromPull, -this.FiringDirection()); - - // make sure player is on positive side of pull + some fudge factor to make sure we can see it - // to avoid flickering highlight on and off, we add a buffer when highlighted - if (stretchDistance <= 0.01f && this.HighlightObject != null && this.HighlightObject.Hidden) - { - return false; - } - else if (stretchDistance < -0.03f) - { - // slack during highlight mode - return false; - } - - // player can be inside a highlight radius or the pick radius - // one approach is to auto grab when within radius (but facing the catapult) - if (playerDistanceFromPull.Length > properties.PickRadius) - { - return false; - } - - return true; - } - - private bool isCatapultStable = true; // Stable means not knocked and not moving - private bool isCatapultKnocked = false; // Knocked means it is either tilted or fell off the table - private SCNVector3? lastPosition; - - private double catapultKnockedStartTime = 0d; - public double CatapultKnockedTime => !this.isCatapultKnocked ? 0d : GameTime.Time - this.catapultKnockedStartTime; - - private const double CatapultPhysicsSettleTime = 5d; - private const float MinStableTiltBaseUpY = 0.7f; - private const float MaxSpeedToCountAsStable = 0.05f; - - private void UpdateCatapultStable() - { - if (!this.Disabled) - { - // Catapult will be unstable when the physics settles, therefore we do not update catapult's stability status - if (GameTime.TimeSinceLevelStart > CatapultPhysicsSettleTime) - { - // Cannot use simdVelocity on client since simdVelocity could be high from physicsSync interacting with local physics engine - if (!this.lastPosition.HasValue) - { - this.lastPosition = this.Base.PresentationNode.WorldPosition; - return; - } - - var position = this.Base.PresentationNode.WorldPosition; - var speed = ((position - this.lastPosition.Value) / (float)GameTime.DeltaTime).Length; - this.lastPosition = position; - - // Base below table? - // Base tilted? base's up vector must maintain some amount of y to be determined as stable - var transform = this.Base.PresentationNode.Transform; - transform.Transpose(); - var baseUp = SCNVector4.Normalize(transform.Column1); - if (position.Y < -1f || Math.Abs(baseUp.Y) < MinStableTiltBaseUpY) - { - // Switch to knocked mode - if (!this.isCatapultKnocked) - { - this.catapultKnockedStartTime = GameTime.Time; - } - - this.isCatapultKnocked = true; - this.isCatapultStable = false; - return; - } - - this.isCatapultKnocked = false; - - // Base could be moving although the catapult is not knocked - this.isCatapultStable = speed < MaxSpeedToCountAsStable; - } - } - } - - /// <summary> - /// When a user has control of a slingshot, no other player can grab it. - /// </summary> - public void ServerGrab(Ray cameraRay) - { - // Trying to grab catapult with player - if (!this.isGrabbed) - { - // do slingshot grab - if (this.Base.GetGameObject()?.GetComponent(typeof(SlingshotComponent)) is SlingshotComponent slingComponent) - { - slingComponent.SetGrabMode(true); - } - } - } - - public void OnGrabStart() - { - // do local effects/haptics if this event was generated by the current player - this.Delegate?.DidBeginGrab(this); - } - - public void OnGrab(CameraInfo cameraInfo) - { - // this is now always at the center, so it shouldn't be affected by yaw - this.baseWorldPosition = this.Base.PresentationNode.WorldPosition; - - this.firstGrabTime = GameTime.Time; - - this.playerWorldPosition = cameraInfo.Ray.Position; - - var ballPosition = this.ComputeBallPosition(cameraInfo); - this.rope.GrabBall(ballPosition); - - this.strapVisible = StrapVisible.Visible; - this.BallVisible = BallVisible.Visible; - - this.AlignCatapult(cameraInfo); // rotate the slingshot before we move it - this.AnimateGrab(ballPosition); - - this.IsPulledTooFar = false; - } - - private void AnimateGrab(SCNVector3 ballPosition) - { - // here we want to animate the rotation of the current yaw to the new yaw - // and also animate the strap moving to the center of the view - - // drop from ballOriginInactiveAbove to ballOriginInactive in a transaction - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = this.properties.GrabAnimationTime; - - // animate the sling and ball to the camera - this.rope.UpdateRopeModel(); - - // animate the ball to the player - if (this.Projectile != null) - { - this.Projectile.WorldPosition = ballPosition; - } - - SCNTransaction.Commit(); - } - - private readonly DateTime Time1970 = new DateTime(1970, 1, 1); - - public void DoHighlight(bool show, SFXCoordinator sfxCoordinator) - { - if (this.HighlightObject != null) - { - this.IsHighlighted = show; - this.HighlightObject.Hidden = !show; - - if (show) - { - var seconds = (DateTime.UtcNow - Time1970).TotalSeconds; - var intensity = (float)(Math.Sin(seconds.TruncatingRemainder(1) * 3.1415 * 2.0) * 0.2); - if (this.HighlightObject.Geometry?.FirstMaterial != null) - { - var color = new CIColor(this.highlightColor); - this.HighlightObject.Geometry.FirstMaterial.Diffuse.Contents = UIColor.FromRGBA((Single)DigitExtensions.Clamp(color.Red + intensity, 0, 1), - (Single)DigitExtensions.Clamp(color.Green + intensity, 0, 1), - (Single)DigitExtensions.Clamp(color.Blue + intensity, 0, 1), - (Single)1); - } - } - - sfxCoordinator?.CatapultDidChangeHighlight(this, show); - } - } - - private SCNVector3 FiringDirection() - { - // this can change as the catapult rotates - return this.Base.WorldFront; - } - - #endregion - - #region Sling Move - - private SCNVector3 ComputeBallPosition(CameraInfo cameraInfo) - { - var cameraRay = cameraInfo.Ray; - - // These should be based on the projectile radius. - // This affects centering of ball, and can hit near plane of camera - // This is always centering to one edge of screen independent of screen orient - // We always want the ball at the bottom of the screen. - var distancePullToCamera = 0.21f; - var ballShiftDown = 0.2f; - - var targetBallPosition = cameraRay.Position + cameraRay.Direction * distancePullToCamera; - - var cameraDown = -SCNVector4.Normalize(cameraInfo.Transform.Column1).Xyz; - targetBallPosition += cameraDown * ballShiftDown; - - // Clamp to only the valid side - var pullWorldPosition = this.pullOrigin.WorldPosition; - if (pullWorldPosition.Z < 0f) - { - targetBallPosition.Z = Math.Min(targetBallPosition.Z, pullWorldPosition.Z); - } - else - { - targetBallPosition.Z = Math.Max(targetBallPosition.Z, pullWorldPosition.Z); - } - - // Clamp to cone/circular core - var yDistanceFromPull = Math.Max(0f, pullWorldPosition.Y - targetBallPosition.Y); - var minBallDistanceFromPull = 0.5f; - var pullBlockConeSlope = 1.0f; - var pullBlockConeRadius = yDistanceFromPull / pullBlockConeSlope; - var pullBlockCoreRadius = Math.Max(minBallDistanceFromPull, pullBlockConeRadius); - - // if pull is in the core, move it out. - var pullWorldPositionGrounded = new SCNVector3(pullWorldPosition.X, 0f, pullWorldPosition.Z); - var targetPullPositionGrounded = new SCNVector3(targetBallPosition.X, 0f, targetBallPosition.Z); - var targetInitialToTargetPull = targetPullPositionGrounded - pullWorldPositionGrounded; - - if (pullBlockCoreRadius > targetInitialToTargetPull.Length) - { - var moveOutDirection = SCNVector3.Normalize(targetInitialToTargetPull); - var newTargetPullPositionGrounded = pullWorldPositionGrounded + moveOutDirection * pullBlockCoreRadius; - targetBallPosition = new SCNVector3(newTargetPullPositionGrounded.X, targetBallPosition.Y, newTargetPullPositionGrounded.Z); - } - - // only use the 2d distance, so that user can gauage stretch indepdent of mtch - var distance2D = targetBallPosition - pullWorldPosition; - var stretchY = Math.Abs(distance2D.Y); - distance2D.Y = 0f; - - var stretchDistance = distance2D.Length; - this.stretch = DigitExtensions.Clamp((double)stretchDistance, this.properties.MinStretch, this.properties.MaxStretch); - - // clamp a little bit farther than maxStretch - // can't let the strap move back too far right now - var clampedStretchDistance = (float)(1.1d * this.properties.MaxStretch); - if (stretchDistance > clampedStretchDistance) - { - targetBallPosition = (clampedStretchDistance / stretchDistance) * (targetBallPosition - pullWorldPosition) + pullWorldPosition; - stretchDistance = clampedStretchDistance; - } - - // Make this optional, not required. You're often at max stretch. - // Also have a timer for auto-launch. This makes it very difficuilt to test - // storing state in member data - this.IsPulledTooFar = stretchDistance > (float)(this.properties.MaxStretch) || stretchY > (float)(this.properties.MaxStretch); - - return targetBallPosition; - } - - private void AlignCatapult(CameraInfo cameraInfo) - { - var targetBallPosition = this.ComputeBallPosition(cameraInfo); - - // Set catapult position - var catapultFront = pullOrigin.WorldPosition - targetBallPosition; - catapultFront.Y = 0f; - this.Base.WorldPosition = this.baseWorldPosition; - this.Base.Look(this.baseWorldPosition + catapultFront); - - if (this.Base.PhysicsBody != null) - { - this.Base.PhysicsBody.AffectedByGravity = false; - this.Base.PhysicsBody.ResetTransform(); - } - } - - /// <summary> - /// As players move, track the stretch of the sling. - /// </summary> - public void Move(CameraInfo cameraInfo) - { - // move actions can be processed only after the catapult has been released - if (this.isGrabbed) - { - // trying to move before grabbing catapult - - this.LastCameraInfo = cameraInfo; - var targetBallPosition = this.ComputeBallPosition(cameraInfo); - - // Set catapult position - var catapultFront = this.pullOrigin.WorldPosition - targetBallPosition; - catapultFront.Y = 0f; - this.Base.WorldPosition = this.baseWorldPosition; - this.Base.Look(this.baseWorldPosition + catapultFront); - - if (this.Base.PhysicsBody != null) - { - this.Base.PhysicsBody.AffectedByGravity = false; - this.Base.PhysicsBody.ResetTransform(); - } - - if (this.Projectile == null) - { - throw new Exception("Grabbed but no projectile"); - } - - this.Projectile.WorldPosition = targetBallPosition; - - this.rope.MoveBall(targetBallPosition); - - // calculate the change in stretch position and rate for audio: - var stretchRate = 0f; - if (GameTime.Time - this.lastStretchTime > 0) - { - stretchRate = (float)((this.stretch - this.lastStretch) / (GameTime.Time - this.lastStretchTime)); - } - - this.Delegate?.DidMove(this, (float)this.stretch, stretchRate); - - this.lastStretch = stretch; - this.lastStretchTime = GameTime.Time; - } - } - - #endregion - - #region Catapult Launch - - public void OnLaunch(GameVelocity velocity) - { - if (this.isGrabbed) - { - // can't grab again until the cooldown animations play - ballCanBeGrabbed = false; - - // update local information for current player if that is what is pulling the catapult - - // start the launch animation - this.rope.LaunchBall(); - - // must reset the move to distance 0 before the launch, otherwise it will start a new - // stretch sound. - this.Delegate?.DidMove(this, 0f, 0f); - this.Delegate?.DidLaunch(this, velocity); - - // set the ball to invisible - this.BallVisible = BallVisible.Hidden; - - // record the last launch time, and enforce a cooldown before ball reappears (need an update call then?) - this.lastLaunchTime = GameTime.Time; - } - } - - public GameVelocity TryGetLaunchVelocity(CameraInfo cameraInfo) - { - GameVelocity result = null; - - if (this.Projectile == null) - { - throw new Exception("Trying to launch without a ball"); - } - - // Move the catapult to make sure that it is moved at least once before launch (prevent NaN in launch direction) - this.Move(cameraInfo); - - var stretchNormalized = DigitExtensions.Clamp((this.stretch - this.properties.MinStretch) / (this.properties.MaxStretch - this.properties.MinStretch), 0.0, 1.0); - - // this is a lerp - var velocity = (float)(this.properties.MinVelocity * (1d - stretchNormalized) + this.properties.MaxVelocity * stretchNormalized); - - var launchDir = SCNVector3.Normalize(this.pullOrigin.WorldPosition - this.Projectile.WorldPosition); - if (!launchDir.HasNaN()) - { - var liftFactor = 0.05f * Math.Abs(1f - SCNVector3.Dot(launchDir, SCNVector3.UnitY)); // used to keep ball in air longer - var lift = SCNVector3.UnitY * velocity * liftFactor; - - result = new GameVelocity(this.Projectile.WorldPosition, launchDir * velocity + lift); - } - - return result; - } - - public void ReleaseSlingGrab() - { - // restore the pull back to resting state - // do this by calling slingshot release - if (this.Base.GetGameObject()?.GetComponent(typeof(SlingshotComponent)) is SlingshotComponent slingComponent) - { - slingComponent.SetGrabMode(false); - } - - this.Base.PhysicsBody.AffectedByGravity = true; - } - - #endregion - - #region Hit By Object - - public void ProcessKnockOut(HitCatapult knockoutInfo) - { - // hide the ball and strap - this.strapVisible = StrapVisible.Hidden; - this.BallVisible = BallVisible.Hidden; - this.Disabled = true; - - // Remove everything except catpault base/prong - this.Delegate?.DidBreak(this, knockoutInfo.JustKnockedout, knockoutInfo.Vortex); - } - - #endregion - - #region Auxiliary - - public void Update() - { - if (this.Disabled) - { - this.BallVisible = BallVisible.Hidden; - } - else - { - this.rope.UpdateRopeModel(); - - // ball on the sling will remain invisible until cooldown time exceeded - // base this on animation of sling coming back to rest - if (this.ballVisible == BallVisible.Hidden) - { - // make sure cooldown doesn't occur starting the ball animation - // until a few seconds after loading the level - if (this.lastLaunchTime == 0d) - { - this.lastLaunchTime = GameTime.Time; - } - - // only allow grabbing the ball after the cooldown animations play (grow + drop) - var timeElapsed = GameTime.Time - this.lastLaunchTime; - var timeForCooldown = this.properties.CooldownTime - this.properties.GrowAnimationTime - this.properties.DropAnimationTime; - if (timeForCooldown < 0.01) - { - timeForCooldown = 0d; - } - - var startCooldownAnimation = timeElapsed > timeForCooldown; - if (startCooldownAnimation) - { - // show the ball at the ballOrigin, that's in the sling - this.BallVisible = BallVisible.Partial; - } - } - - this.UpdateCatapultStable(); - - // Make sure that the ball stays in its place even if the catapult move - if (this.ballCanBeGrabbed) - { - if (this.isGrabbed) - { - if (this.Projectile == null) - { - throw new Exception("isGrabbed but has no projectile"); - } - - this.rope.MoveBall(this.Projectile.WorldPosition); - } - else - { - if (this.Projectile != null) - { - this.Projectile.WorldPosition = this.ballOriginInactiveBelow.PresentationNode.WorldPosition; - } - } - } - } - } - - #endregion - } -} \ No newline at end of file + // highlight setup + this.HighlightObject = node.FindChildNode ("Highlight", true); + if (this.HighlightObject != null) { + this.HighlightObject = this.HighlightObject.FindNodeWithGeometry (); + } + + // hide the highlights on load + if (this.HighlightObject != null) { + this.HighlightObject.Hidden = true; + } + + if (this.HighlightObject?.Geometry?.FirstMaterial?.Diffuse?.Contents is UIColor color) { + this.highlightColor = color; + } + + // they should only have y orientation, nothing in x or z + // current scene files have the catapults with correct orientation, but the + // eulerAngles are different - x and z are both π, y is within epsilon of 0 + // That's from bad decomposition of the matrix. Need to restore the eulerAngles from the source. + // Especially if we have animations tied to the euler angles. + if (Math.Abs (node.EulerAngles.X) > 0.001f || Math.Abs (node.EulerAngles.Z) > 0.001f) { + //Console.WriteLine("Catapult can only have y rotation applied"); + } + + // where to place the ball so it sits on the strap + this.catapultStrap = this.Base.FindChildNode ("catapultStrap", true); + if (this.catapultStrap == null) { + throw new Exception ("No node with name catapultStrap"); + } + + // this only rotates, and represents the center of the catapult through which to fire + this.pullOrigin = this.Base.FindChildNode ("pullOrigin", true); + if (this.pullOrigin == null) { + throw new Exception ("No node with name pullOrigin"); + } + + // This is a rope simulation meant for a fixed catapult, the catapult rotates. + this.rope = new CatapultRope (node); + + // attach ball to the inactive strap, search for ballOriginInactiveBelow + this.ballOriginInactiveBelow = this.Base.FindChildNode ("ballOriginInactiveBelow", true); + if (this.ballOriginInactiveBelow == null) { + throw new Exception ("No node with name ballOriginInactiveBelow"); + } + + this.ballOriginInactiveAbove = this.Base.FindChildNode ("ballOriginInactiveAbove", true); + if (this.ballOriginInactiveAbove == null) { + throw new Exception ("No node with name ballOriginInactiveAbove"); + } + + // ball will be made visible and drop once projectile is set and cooldown exceeded + this.StrapVisible = StrapVisible.Visible; + + this.CatapultId = identifier; + + this.Base.SetValueForKey (NSObject.FromObject (this.CatapultId), new NSString (Catapult.CollisionKey)); + + this.AudioPlayer = new CatapultAudioSampler (this.Base, sfxCoordinator); + + // use the teamID to set the collision category mask + if (this.PhysicsNode?.PhysicsBody != null) { + if (this.Team == Team.TeamA) { + this.PhysicsNode.PhysicsBody.CategoryBitMask = (int) CollisionMask.CatapultTeamA; + var collisionBitMask = (CollisionMask) (int) this.PhysicsNode.PhysicsBody.CollisionBitMask; + this.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint) (int) (collisionBitMask | CollisionMask.CatapultTeamB); + } else if (this.Team == Team.TeamB) { + this.PhysicsNode.PhysicsBody.CategoryBitMask = (int) CollisionMask.CatapultTeamB; + var collisionBitMask = (CollisionMask) (int) this.PhysicsNode.PhysicsBody.CollisionBitMask; + this.PhysicsNode.PhysicsBody.CollisionBitMask = (nuint) (int) (collisionBitMask | CollisionMask.CatapultTeamA); + } + } + } + + public Catapult (NSCoder coder) : base (coder) => throw new NotImplementedException ("init(coder:) has not been implemented"); + + public double CoolDownTime => this.properties.CooldownTime; + + public SCNNode Base { get; } + + public ICatapultDelegate Delegate { get; set; } + + public bool IsPulledTooFar { get; private set; } + + public CameraInfo LastCameraInfo { get; set; } = new CameraInfo (SCNMatrix4.Identity); + + public SCNNode Projectile { get; private set; } + + public ProjectileType ProjectileType { get; private set; } = ProjectileType.None; + + public bool Disabled { get; private set; } + + public CatapultAudioSampler AudioPlayer { get; private set; } + + // Each catapult has a unique index. + // 1-3 are on one side, 4-6 are on the other side + public int CatapultId { get; private set; } = 0; + + public Team Team { get; private set; } = Team.None; + + public string TeamName { get; private set; } + + // highlight assistance + public SCNVector3 ProjectedPosition { get; set; } = SCNVector3.Zero; + + public SCNNode HighlightObject { get; private set; } + + /// <summary> + /// Grabbable Id to be set by GrabInteraction + /// </summary> + public int GrabbableId { get; set; } = 0; + + // Player who grabbed a catapult. A player can only operate one catapult at a time. + // Players/teams may be restricted to a set of catapults. + // Note: Player setting is managed by CatapultInteraction which will resolves sync. + // Player do not get set in clients, since clients do not need to know who grabbed the catapult, + // whereas server needs to know the player owning the catapult to avoid conflicts. + public Player Player { get; set; } + + private bool isGrabbed; + + public bool IsGrabbed { + get { + return this.isGrabbed; + } + + // In the case of clients, actual player owner does not need to be known + set { + this.isGrabbed = value; + if (!this.isGrabbed) { + this.Player = null; + } + } + } + + /// <summary> + /// Highlight assistance + /// </summary> + /// <value><c>true</c> if is visible; otherwise, <c>false</c>.</value> + public bool IsVisible { get; set; } + + /// <summary> + /// Highlight assistance + /// </summary> + public bool IsHighlighted { get; private set; } + + private StrapVisible strapVisible = StrapVisible.Hidden; + public StrapVisible StrapVisible { + get { + return this.strapVisible; + } + + set { + this.strapVisible = value; + this.UpdateStrapVisibility (); + } + } + + private void UpdateStrapVisibility () + { + switch (this.strapVisible) { + case StrapVisible.Hidden: + this.catapultStrap.Hidden = true; + break; + + case StrapVisible.Visible: + this.catapultStrap.Hidden = false; + break; + } + } + + private BallVisible ballVisible = BallVisible.Hidden; + /// <summary> + /// Whether the ball in the sling is visible or partially visible. + /// </summary> + public BallVisible BallVisible { + get { + return this.ballVisible; + } + + set { + this.ballVisible = value; + this.UpdateFakeProjectileVisibility (); + } + } + + private void UpdateFakeProjectileVisibility () + { + switch (ballVisible) { + case BallVisible.Hidden: + if (this.Projectile != null) { + this.Projectile.Opacity = 1f; + this.Projectile.Hidden = true; + this.Projectile.WorldPosition = this.ballOriginInactiveAbove.WorldPosition; + this.Projectile.Scale = new SCNVector3 (0.01f, 0.01f, 0.01f); + } + break; + + case BallVisible.Partial: + if (this.Projectile != null) { + this.Projectile.Opacity = 1f; + this.Projectile.Hidden = false; + this.AnimateBallGrowAndDrop (); + } + break; + + case BallVisible.Visible: + if (this.Projectile != null) { + this.Projectile.Opacity = 1f; + this.Projectile.Hidden = false; + // it's in the strap fromn .partial animation + } + break; + } + } + + public void AnimationRopeToRestPose (double duration) + { + this.rope.InterpolateToRestPoseAnimation (duration); + } + + public void AnimateBallGrowAndDrop () + { + // the block is the total time of the transcation, so sub-blocks are limited by that too + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = this.properties.GrowAnimationTime; + + // correct the rope sim by animating back to reset pose no matter what + var fixupLaunchAnimationTime = 0.1f; + this.rope.InterpolateToRestPoseAnimation (fixupLaunchAnimationTime); + + // first scale the ball from small to original size + if (this.Projectile != null) { + this.Projectile.Scale = this.projectileScale; + } + + SCNTransaction.SetCompletionBlock (() => { + // after back to scale, then run the ball drop + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = this.properties.DropAnimationTime; + + // next drop from ballOriginInactiveAbove to ballOriginInactive + if (this.Projectile != null) { + this.Projectile.WorldPosition = this.ballOriginInactiveBelow.WorldPosition; + } + + SCNTransaction.SetCompletionBlock (() => { + // only allow the ball to be grabbed after animation completes + this.ballCanBeGrabbed = true; + }); + + SCNTransaction.Commit (); + }); + + SCNTransaction.Commit (); + } + + /// <summary> + /// Distance away from catapult base + /// </summary> + public float DistanceFrom (SCNVector3 worldPosition) + { + var distance = worldPosition - this.Base.WorldPosition; + return distance.Length; + } + + public static SCNNode ReplaceCatapultPlaceholder (SCNNode placeholder) + { + var node = SCNNodeExtensions.LoadSCNAsset ("catapult"); + + // somehow setting the world transform doesn't update the Euler angles (180, 0, 180) is decoded + // but need it to be 0, 180, 0 + node.Transform = placeholder.Transform; + node.EulerAngles = placeholder.EulerAngles; + + // Add physics body to it + node.WorldPosition += new SCNVector3 (0f, 0.2f, 0f); + node.PhysicsBody?.ResetTransform (); + + var baseGeomNode = node.FindChildNode ("catapultBase", true); + if (baseGeomNode == null) { + throw new Exception ("No catapultBase"); + } + + var prongGeomNode = node.FindChildNode ("catapultProngs", true); + if (prongGeomNode == null) { + throw new Exception ("No catapultProngs"); + } + + // shift center of mass of the prong from the bottom + // the 0.55 value is from experimentation + var prongPivotShiftUp = new SCNVector3 (0f, 0.55f, 0f); + prongGeomNode.Pivot = SCNMatrix4.CreateTranslation (prongPivotShiftUp); + prongGeomNode.Position += prongPivotShiftUp; + + var baseShape = SCNPhysicsShape.Create (baseGeomNode, new SCNPhysicsShapeOptions () { ShapeType = SCNPhysicsShapeType.ConvexHull }); + var prongShape = SCNPhysicsShape.Create (prongGeomNode, new SCNPhysicsShapeOptions () { ShapeType = SCNPhysicsShapeType.ConvexHull }); + + var compoundShape = SCNPhysicsShape.Create (new SCNPhysicsShape [] { baseShape, prongShape }, + new SCNMatrix4 [] { SCNMatrix4.Identity, SCNMatrix4.Identity }); + if (node.PhysicsBody != null) { + node.PhysicsBody.PhysicsShape = compoundShape; + } + + // rename back to placeholder name must happen after gameObject is assigned + // currently placeholders are all Catapult1 to Catapult6, they may be under a teamA, teamB parent + // so stash the placeholder name for later + if (!string.IsNullOrEmpty (placeholder.Name)) { + node.SetValueForKey (new NSString (placeholder.Name), new NSString ("nameRestore")); + } + + placeholder.ParentNode.ReplaceChildNode (placeholder, node); + + node.Name = "catapult"; + + return node; + } + + public void SetProjectileType (ProjectileType projectileType, SCNNode projectile) + { + this.Projectile?.RemoveFromParentNode (); + this.Projectile = projectile; + this.ProjectileType = projectileType; + this.projectileScale = projectile.Scale; + + // the rope adjusts to the radius of the ball + var projectilePaddingScale = 1f; + + nfloat radius = 0f; + var temp = SCNVector3.Zero; + projectile.GetBoundingSphere (ref temp, ref radius); + this.rope.SetBallRadius ((float) radius * projectilePaddingScale); + + // need ball to set a teamID, and then can color with same mechanism + //projectile.setPaintColor() + + // will be made visible and drop when cooldown is exceeded, + // this way ball doesn't change suddenly while visible + this.BallVisible = BallVisible.Hidden; + this.UpdateFakeProjectileVisibility (); + } + + public void UpdateProperties () + { + this.properties.MinStretch = this.PropDouble ("minStretch").Value; + this.properties.MaxStretch = this.PropDouble ("maxStretch").Value; + + this.properties.MinYaw = this.PropDouble ("minYaw").Value; + this.properties.MaxYaw = this.PropDouble ("maxYaw").Value; + + this.properties.MinPitch = this.PropDouble ("minPitch").Value; + this.properties.MaxPitch = this.PropDouble ("maxPitch").Value; + + this.properties.MinVelocity = this.PropDouble ("minVelocity").Value; + this.properties.MaxVelocity = this.PropDouble ("maxVelocity").Value; + + this.properties.CooldownTime = this.PropDouble ("cooldownTime").Value; + this.properties.PickRadius = this.PropDouble ("pickRadius").Value; + } + + #region Catapult Grab + + public bool CanGrab (Ray cameraRay) + { + if (this.isGrabbed) { + return false; + } + + if (this.Disabled) { + return false; + } + + // there is a cooldown timer before you can launch again + // when animation completes this will be set to true + if (!this.ballCanBeGrabbed) { + return false; + } + + if (!this.isCatapultStable) { + return false; + } + + if (!this.HitTestPull (cameraRay)) { + return false; + } + + return true; + } + + private bool HitTestPull (Ray cameraRay) + { + // Careful not to make this too large or you'll pick a neighboring slingshot or one across the table. + // We're not sorting hits across all of the slignshots and picking the smallest, but we visit them all. + // Within radius behind the ball/pull allow the slingshot to be picked. + var playerDistanceFromPull = cameraRay.Position - this.pullOrigin.WorldPosition; + + // This is a linear distance along the current firing direction of the catapult + // Just using it here to make sure you're behind the pull (the pull is visible). + var stretchDistance = SCNVector3.Dot (playerDistanceFromPull, -this.FiringDirection ()); + + // make sure player is on positive side of pull + some fudge factor to make sure we can see it + // to avoid flickering highlight on and off, we add a buffer when highlighted + if (stretchDistance <= 0.01f && this.HighlightObject != null && this.HighlightObject.Hidden) { + return false; + } else if (stretchDistance < -0.03f) { + // slack during highlight mode + return false; + } + + // player can be inside a highlight radius or the pick radius + // one approach is to auto grab when within radius (but facing the catapult) + if (playerDistanceFromPull.Length > properties.PickRadius) { + return false; + } + + return true; + } + + private bool isCatapultStable = true; // Stable means not knocked and not moving + private bool isCatapultKnocked = false; // Knocked means it is either tilted or fell off the table + private SCNVector3? lastPosition; + + private double catapultKnockedStartTime = 0d; + public double CatapultKnockedTime => !this.isCatapultKnocked ? 0d : GameTime.Time - this.catapultKnockedStartTime; + + private const double CatapultPhysicsSettleTime = 5d; + private const float MinStableTiltBaseUpY = 0.7f; + private const float MaxSpeedToCountAsStable = 0.05f; + + private void UpdateCatapultStable () + { + if (!this.Disabled) { + // Catapult will be unstable when the physics settles, therefore we do not update catapult's stability status + if (GameTime.TimeSinceLevelStart > CatapultPhysicsSettleTime) { + // Cannot use simdVelocity on client since simdVelocity could be high from physicsSync interacting with local physics engine + if (!this.lastPosition.HasValue) { + this.lastPosition = this.Base.PresentationNode.WorldPosition; + return; + } + + var position = this.Base.PresentationNode.WorldPosition; + var speed = ((position - this.lastPosition.Value) / (float) GameTime.DeltaTime).Length; + this.lastPosition = position; + + // Base below table? + // Base tilted? base's up vector must maintain some amount of y to be determined as stable + var transform = this.Base.PresentationNode.Transform; + transform.Transpose (); + var baseUp = SCNVector4.Normalize (transform.Column1); + if (position.Y < -1f || Math.Abs (baseUp.Y) < MinStableTiltBaseUpY) { + // Switch to knocked mode + if (!this.isCatapultKnocked) { + this.catapultKnockedStartTime = GameTime.Time; + } + + this.isCatapultKnocked = true; + this.isCatapultStable = false; + return; + } + + this.isCatapultKnocked = false; + + // Base could be moving although the catapult is not knocked + this.isCatapultStable = speed < MaxSpeedToCountAsStable; + } + } + } + + /// <summary> + /// When a user has control of a slingshot, no other player can grab it. + /// </summary> + public void ServerGrab (Ray cameraRay) + { + // Trying to grab catapult with player + if (!this.isGrabbed) { + // do slingshot grab + if (this.Base.GetGameObject ()?.GetComponent (typeof (SlingshotComponent)) is SlingshotComponent slingComponent) { + slingComponent.SetGrabMode (true); + } + } + } + + public void OnGrabStart () + { + // do local effects/haptics if this event was generated by the current player + this.Delegate?.DidBeginGrab (this); + } + + public void OnGrab (CameraInfo cameraInfo) + { + // this is now always at the center, so it shouldn't be affected by yaw + this.baseWorldPosition = this.Base.PresentationNode.WorldPosition; + + this.firstGrabTime = GameTime.Time; + + this.playerWorldPosition = cameraInfo.Ray.Position; + + var ballPosition = this.ComputeBallPosition (cameraInfo); + this.rope.GrabBall (ballPosition); + + this.strapVisible = StrapVisible.Visible; + this.BallVisible = BallVisible.Visible; + + this.AlignCatapult (cameraInfo); // rotate the slingshot before we move it + this.AnimateGrab (ballPosition); + + this.IsPulledTooFar = false; + } + + private void AnimateGrab (SCNVector3 ballPosition) + { + // here we want to animate the rotation of the current yaw to the new yaw + // and also animate the strap moving to the center of the view + + // drop from ballOriginInactiveAbove to ballOriginInactive in a transaction + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = this.properties.GrabAnimationTime; + + // animate the sling and ball to the camera + this.rope.UpdateRopeModel (); + + // animate the ball to the player + if (this.Projectile != null) { + this.Projectile.WorldPosition = ballPosition; + } + + SCNTransaction.Commit (); + } + + private readonly DateTime Time1970 = new DateTime (1970, 1, 1); + + public void DoHighlight (bool show, SFXCoordinator sfxCoordinator) + { + if (this.HighlightObject != null) { + this.IsHighlighted = show; + this.HighlightObject.Hidden = !show; + + if (show) { + var seconds = (DateTime.UtcNow - Time1970).TotalSeconds; + var intensity = (float) (Math.Sin (seconds.TruncatingRemainder (1) * 3.1415 * 2.0) * 0.2); + if (this.HighlightObject.Geometry?.FirstMaterial != null) { + var color = new CIColor (this.highlightColor); + this.HighlightObject.Geometry.FirstMaterial.Diffuse.Contents = UIColor.FromRGBA ((Single) DigitExtensions.Clamp (color.Red + intensity, 0, 1), + (Single) DigitExtensions.Clamp (color.Green + intensity, 0, 1), + (Single) DigitExtensions.Clamp (color.Blue + intensity, 0, 1), + (Single) 1); + } + } + + sfxCoordinator?.CatapultDidChangeHighlight (this, show); + } + } + + private SCNVector3 FiringDirection () + { + // this can change as the catapult rotates + return this.Base.WorldFront; + } + + #endregion + + #region Sling Move + + private SCNVector3 ComputeBallPosition (CameraInfo cameraInfo) + { + var cameraRay = cameraInfo.Ray; + + // These should be based on the projectile radius. + // This affects centering of ball, and can hit near plane of camera + // This is always centering to one edge of screen independent of screen orient + // We always want the ball at the bottom of the screen. + var distancePullToCamera = 0.21f; + var ballShiftDown = 0.2f; + + var targetBallPosition = cameraRay.Position + cameraRay.Direction * distancePullToCamera; + + var cameraDown = -SCNVector4.Normalize (cameraInfo.Transform.Column1).Xyz; + targetBallPosition += cameraDown * ballShiftDown; + + // Clamp to only the valid side + var pullWorldPosition = this.pullOrigin.WorldPosition; + if (pullWorldPosition.Z < 0f) { + targetBallPosition.Z = Math.Min (targetBallPosition.Z, pullWorldPosition.Z); + } else { + targetBallPosition.Z = Math.Max (targetBallPosition.Z, pullWorldPosition.Z); + } + + // Clamp to cone/circular core + var yDistanceFromPull = Math.Max (0f, pullWorldPosition.Y - targetBallPosition.Y); + var minBallDistanceFromPull = 0.5f; + var pullBlockConeSlope = 1.0f; + var pullBlockConeRadius = yDistanceFromPull / pullBlockConeSlope; + var pullBlockCoreRadius = Math.Max (minBallDistanceFromPull, pullBlockConeRadius); + + // if pull is in the core, move it out. + var pullWorldPositionGrounded = new SCNVector3 (pullWorldPosition.X, 0f, pullWorldPosition.Z); + var targetPullPositionGrounded = new SCNVector3 (targetBallPosition.X, 0f, targetBallPosition.Z); + var targetInitialToTargetPull = targetPullPositionGrounded - pullWorldPositionGrounded; + + if (pullBlockCoreRadius > targetInitialToTargetPull.Length) { + var moveOutDirection = SCNVector3.Normalize (targetInitialToTargetPull); + var newTargetPullPositionGrounded = pullWorldPositionGrounded + moveOutDirection * pullBlockCoreRadius; + targetBallPosition = new SCNVector3 (newTargetPullPositionGrounded.X, targetBallPosition.Y, newTargetPullPositionGrounded.Z); + } + + // only use the 2d distance, so that user can gauage stretch indepdent of mtch + var distance2D = targetBallPosition - pullWorldPosition; + var stretchY = Math.Abs (distance2D.Y); + distance2D.Y = 0f; + + var stretchDistance = distance2D.Length; + this.stretch = DigitExtensions.Clamp ((double) stretchDistance, this.properties.MinStretch, this.properties.MaxStretch); + + // clamp a little bit farther than maxStretch + // can't let the strap move back too far right now + var clampedStretchDistance = (float) (1.1d * this.properties.MaxStretch); + if (stretchDistance > clampedStretchDistance) { + targetBallPosition = (clampedStretchDistance / stretchDistance) * (targetBallPosition - pullWorldPosition) + pullWorldPosition; + stretchDistance = clampedStretchDistance; + } + + // Make this optional, not required. You're often at max stretch. + // Also have a timer for auto-launch. This makes it very difficuilt to test + // storing state in member data + this.IsPulledTooFar = stretchDistance > (float) (this.properties.MaxStretch) || stretchY > (float) (this.properties.MaxStretch); + + return targetBallPosition; + } + + private void AlignCatapult (CameraInfo cameraInfo) + { + var targetBallPosition = this.ComputeBallPosition (cameraInfo); + + // Set catapult position + var catapultFront = pullOrigin.WorldPosition - targetBallPosition; + catapultFront.Y = 0f; + this.Base.WorldPosition = this.baseWorldPosition; + this.Base.Look (this.baseWorldPosition + catapultFront); + + if (this.Base.PhysicsBody != null) { + this.Base.PhysicsBody.AffectedByGravity = false; + this.Base.PhysicsBody.ResetTransform (); + } + } + + /// <summary> + /// As players move, track the stretch of the sling. + /// </summary> + public void Move (CameraInfo cameraInfo) + { + // move actions can be processed only after the catapult has been released + if (this.isGrabbed) { + // trying to move before grabbing catapult + + this.LastCameraInfo = cameraInfo; + var targetBallPosition = this.ComputeBallPosition (cameraInfo); + + // Set catapult position + var catapultFront = this.pullOrigin.WorldPosition - targetBallPosition; + catapultFront.Y = 0f; + this.Base.WorldPosition = this.baseWorldPosition; + this.Base.Look (this.baseWorldPosition + catapultFront); + + if (this.Base.PhysicsBody != null) { + this.Base.PhysicsBody.AffectedByGravity = false; + this.Base.PhysicsBody.ResetTransform (); + } + + if (this.Projectile == null) { + throw new Exception ("Grabbed but no projectile"); + } + + this.Projectile.WorldPosition = targetBallPosition; + + this.rope.MoveBall (targetBallPosition); + + // calculate the change in stretch position and rate for audio: + var stretchRate = 0f; + if (GameTime.Time - this.lastStretchTime > 0) { + stretchRate = (float) ((this.stretch - this.lastStretch) / (GameTime.Time - this.lastStretchTime)); + } + + this.Delegate?.DidMove (this, (float) this.stretch, stretchRate); + + this.lastStretch = stretch; + this.lastStretchTime = GameTime.Time; + } + } + + #endregion + + #region Catapult Launch + + public void OnLaunch (GameVelocity velocity) + { + if (this.isGrabbed) { + // can't grab again until the cooldown animations play + ballCanBeGrabbed = false; + + // update local information for current player if that is what is pulling the catapult + + // start the launch animation + this.rope.LaunchBall (); + + // must reset the move to distance 0 before the launch, otherwise it will start a new + // stretch sound. + this.Delegate?.DidMove (this, 0f, 0f); + this.Delegate?.DidLaunch (this, velocity); + + // set the ball to invisible + this.BallVisible = BallVisible.Hidden; + + // record the last launch time, and enforce a cooldown before ball reappears (need an update call then?) + this.lastLaunchTime = GameTime.Time; + } + } + + public GameVelocity TryGetLaunchVelocity (CameraInfo cameraInfo) + { + GameVelocity result = null; + + if (this.Projectile == null) { + throw new Exception ("Trying to launch without a ball"); + } + + // Move the catapult to make sure that it is moved at least once before launch (prevent NaN in launch direction) + this.Move (cameraInfo); + + var stretchNormalized = DigitExtensions.Clamp ((this.stretch - this.properties.MinStretch) / (this.properties.MaxStretch - this.properties.MinStretch), 0.0, 1.0); + + // this is a lerp + var velocity = (float) (this.properties.MinVelocity * (1d - stretchNormalized) + this.properties.MaxVelocity * stretchNormalized); + + var launchDir = SCNVector3.Normalize (this.pullOrigin.WorldPosition - this.Projectile.WorldPosition); + if (!launchDir.HasNaN ()) { + var liftFactor = 0.05f * Math.Abs (1f - SCNVector3.Dot (launchDir, SCNVector3.UnitY)); // used to keep ball in air longer + var lift = SCNVector3.UnitY * velocity * liftFactor; + + result = new GameVelocity (this.Projectile.WorldPosition, launchDir * velocity + lift); + } + + return result; + } + + public void ReleaseSlingGrab () + { + // restore the pull back to resting state + // do this by calling slingshot release + if (this.Base.GetGameObject ()?.GetComponent (typeof (SlingshotComponent)) is SlingshotComponent slingComponent) { + slingComponent.SetGrabMode (false); + } + + this.Base.PhysicsBody.AffectedByGravity = true; + } + + #endregion + + #region Hit By Object + + public void ProcessKnockOut (HitCatapult knockoutInfo) + { + // hide the ball and strap + this.strapVisible = StrapVisible.Hidden; + this.BallVisible = BallVisible.Hidden; + this.Disabled = true; + + // Remove everything except catpault base/prong + this.Delegate?.DidBreak (this, knockoutInfo.JustKnockedout, knockoutInfo.Vortex); + } + + #endregion + + #region Auxiliary + + public void Update () + { + if (this.Disabled) { + this.BallVisible = BallVisible.Hidden; + } else { + this.rope.UpdateRopeModel (); + + // ball on the sling will remain invisible until cooldown time exceeded + // base this on animation of sling coming back to rest + if (this.ballVisible == BallVisible.Hidden) { + // make sure cooldown doesn't occur starting the ball animation + // until a few seconds after loading the level + if (this.lastLaunchTime == 0d) { + this.lastLaunchTime = GameTime.Time; + } + + // only allow grabbing the ball after the cooldown animations play (grow + drop) + var timeElapsed = GameTime.Time - this.lastLaunchTime; + var timeForCooldown = this.properties.CooldownTime - this.properties.GrowAnimationTime - this.properties.DropAnimationTime; + if (timeForCooldown < 0.01) { + timeForCooldown = 0d; + } + + var startCooldownAnimation = timeElapsed > timeForCooldown; + if (startCooldownAnimation) { + // show the ball at the ballOrigin, that's in the sling + this.BallVisible = BallVisible.Partial; + } + } + + this.UpdateCatapultStable (); + + // Make sure that the ball stays in its place even if the catapult move + if (this.ballCanBeGrabbed) { + if (this.isGrabbed) { + if (this.Projectile == null) { + throw new Exception ("isGrabbed but has no projectile"); + } + + this.rope.MoveBall (this.Projectile.WorldPosition); + } else { + if (this.Projectile != null) { + this.Projectile.WorldPosition = this.ballOriginInactiveBelow.PresentationNode.WorldPosition; + } + } + } + } + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/CatapultRope.cs b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/CatapultRope.cs index 275d15b31..33ac6e2de 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/CatapultRope.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/CatapultRope.cs @@ -1,155 +1,143 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Utils; - using System.Collections.Generic; - - public class CatapultRope - { - private const int NumStrapBones = 35; - - // hold onto the rope shapes, will copy transforms into these - private readonly List<SCNNode> ropeShapes = new List<SCNNode>(); - - private readonly SCNNode @base; - - private SlingShotSimulation rope; - - private double animatingLaunchTimestamp = 0d; - - private State state = State.None; - - public CatapultRope(SCNNode @base) - { - this.@base = @base; - - // setup the rope simulation - // segmentRadius is size of the rigid bodies that represent the rope - this.rope = new SlingShotSimulation(this.@base, NumStrapBones, 0.02f * 5f); - - // this will be set when projectile set onto catapult - this.rope.BallRadius = 0.275f; - - // the projectile is resting atop the strap when inactive, will it settle okay - // what about the orient of the projectile - // The ball will jump as the strap is pulled - - this.rope.BallPosition = this.@base.FindChildNode("ballOriginInactiveBelow", true).WorldPosition; - - // grab an array of each bone from the rig, these are called sling0...sling<count> - // these are in the inactive strap - var originalTotalLength = 0f; - var originalLeatherLength = 0f; - for (int i = 0; i < NumStrapBones; i++) - { - this.ropeShapes.Add(this.@base.FindChildNode($"strap{i}", true)); - if (i > 1) - { - // estimate with linear length - var delta = (this.ropeShapes[i].WorldPosition - this.ropeShapes[i - 1].WorldPosition).Length; - originalTotalLength += delta; - if (i >= 13 && i <= 21) - { - originalLeatherLength += delta; - } - } - } - - this.rope.OriginalTotalLength = originalTotalLength; - this.rope.OriginalLeatherLength = originalLeatherLength; - - this.rope.SetInitialRestPose(this.@base, this.ropeShapes); - } - - public void SetBallRadius(float ballRadius) - { - this.rope.BallRadius = ballRadius; - } - - public void GrabBall(SCNVector3 ballPosition) - { - this.MoveBall(ballPosition); - } - - public void MoveBall(SCNVector3 ballPosition) - { - // grab must be called prior, and it sets .move mode up - this.state = State.Move; - this.rope.BallPosition = ballPosition; - - // this is really the currently rotated space of the base - var worldTransform = this.@base.WorldTransform; - worldTransform.Transpose(); - this.rope.RestPoseSpace = worldTransform; - - // disables simulation, sets mask to zero, and drives it by the rig - this.rope.EnableInputPose(); - } - - private bool useSim = true; - - public void LaunchBall() - { - this.state = State.Launch; - this.animatingLaunchTimestamp = GameTime.Time; - - this.useSim = UserDefaults.ShowRopeSimulation; - - // this lets the rope fly - if (this.useSim) - { - this.rope.StartLaunchSimulation(); - } - else - { - this.InterpolateToRestPoseAnimation(this.rope.LinearLaunchAnimationTime); - } - } - - public void InterpolateToRestPoseAnimation(double duration) - { - this.rope.InterpolateToRestPoseAnimation(duration, this.ropeShapes); - } - - /// <summary> - /// Called at start of render phase, but before render scaling - /// </summary> - public void UpdateRopeModel() - { - if (this.state == State.None || (!this.useSim && this.state == State.Launch)) - { - return; - } - - var time = GameTime.Time; - - // this advances by at most a fixed timestep - this.rope.SimulateStep(time); - - // copy the bone locations back to the rig - // don't change the begin and end bones, those are static and will separate if changed - for (var i = this.rope.BoneInset; i < NumStrapBones - this.rope.BoneInset; i++) - { - // presentation node actually has the results of the simulation - this.ropeShapes[i].WorldTransform = this.rope.SimulatedTransformAsFloat4x4(i); - } - - // reset the animation state back to none - // this can't be longer than the cooldownTime - grow/drop time (around 2.5s) - // but has to be long enough to let the rope sim settle back to reset pose - var delta = time - this.animatingLaunchTimestamp; - if (this.state == State.Launch && delta >= this.rope.SimLaunchAnimationTime) - { - this.state = State.None; - } - } - - enum State - { - None, - Move, - Launch, - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Utils; + using System.Collections.Generic; + + public class CatapultRope { + private const int NumStrapBones = 35; + + // hold onto the rope shapes, will copy transforms into these + private readonly List<SCNNode> ropeShapes = new List<SCNNode> (); + + private readonly SCNNode @base; + + private SlingShotSimulation rope; + + private double animatingLaunchTimestamp = 0d; + + private State state = State.None; + + public CatapultRope (SCNNode @base) + { + this.@base = @base; + + // setup the rope simulation + // segmentRadius is size of the rigid bodies that represent the rope + this.rope = new SlingShotSimulation (this.@base, NumStrapBones, 0.02f * 5f); + + // this will be set when projectile set onto catapult + this.rope.BallRadius = 0.275f; + + // the projectile is resting atop the strap when inactive, will it settle okay + // what about the orient of the projectile + // The ball will jump as the strap is pulled + + this.rope.BallPosition = this.@base.FindChildNode ("ballOriginInactiveBelow", true).WorldPosition; + + // grab an array of each bone from the rig, these are called sling0...sling<count> + // these are in the inactive strap + var originalTotalLength = 0f; + var originalLeatherLength = 0f; + for (int i = 0; i < NumStrapBones; i++) { + this.ropeShapes.Add (this.@base.FindChildNode ($"strap{i}", true)); + if (i > 1) { + // estimate with linear length + var delta = (this.ropeShapes [i].WorldPosition - this.ropeShapes [i - 1].WorldPosition).Length; + originalTotalLength += delta; + if (i >= 13 && i <= 21) { + originalLeatherLength += delta; + } + } + } + + this.rope.OriginalTotalLength = originalTotalLength; + this.rope.OriginalLeatherLength = originalLeatherLength; + + this.rope.SetInitialRestPose (this.@base, this.ropeShapes); + } + + public void SetBallRadius (float ballRadius) + { + this.rope.BallRadius = ballRadius; + } + + public void GrabBall (SCNVector3 ballPosition) + { + this.MoveBall (ballPosition); + } + + public void MoveBall (SCNVector3 ballPosition) + { + // grab must be called prior, and it sets .move mode up + this.state = State.Move; + this.rope.BallPosition = ballPosition; + + // this is really the currently rotated space of the base + var worldTransform = this.@base.WorldTransform; + worldTransform.Transpose (); + this.rope.RestPoseSpace = worldTransform; + + // disables simulation, sets mask to zero, and drives it by the rig + this.rope.EnableInputPose (); + } + + private bool useSim = true; + + public void LaunchBall () + { + this.state = State.Launch; + this.animatingLaunchTimestamp = GameTime.Time; + + this.useSim = UserDefaults.ShowRopeSimulation; + + // this lets the rope fly + if (this.useSim) { + this.rope.StartLaunchSimulation (); + } else { + this.InterpolateToRestPoseAnimation (this.rope.LinearLaunchAnimationTime); + } + } + + public void InterpolateToRestPoseAnimation (double duration) + { + this.rope.InterpolateToRestPoseAnimation (duration, this.ropeShapes); + } + + /// <summary> + /// Called at start of render phase, but before render scaling + /// </summary> + public void UpdateRopeModel () + { + if (this.state == State.None || (!this.useSim && this.state == State.Launch)) { + return; + } + + var time = GameTime.Time; + + // this advances by at most a fixed timestep + this.rope.SimulateStep (time); + + // copy the bone locations back to the rig + // don't change the begin and end bones, those are static and will separate if changed + for (var i = this.rope.BoneInset; i < NumStrapBones - this.rope.BoneInset; i++) { + // presentation node actually has the results of the simulation + this.ropeShapes [i].WorldTransform = this.rope.SimulatedTransformAsFloat4x4 (i); + } + + // reset the animation state back to none + // this can't be longer than the cooldownTime - grow/drop time (around 2.5s) + // but has to be long enough to let the rope sim settle back to reset pose + var delta = time - this.animatingLaunchTimestamp; + if (this.state == State.Launch && delta >= this.rope.SimLaunchAnimationTime) { + this.state = State.None; + } + } + + enum State { + None, + Move, + Launch, + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/ComputedValue.cs b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/ComputedValue.cs index 220783f14..c2626d370 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/ComputedValue.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/ComputedValue.cs @@ -1,51 +1,46 @@ - -namespace XamarinShot.Models -{ - using System; - - // Using a provided closure the value is computed upon request. - // Managing classes can set the dirty state of the ComputedValue to - // force a consecutive compute of the value. - - /// <summary> - /// Wrapper class for lazily computed values for use as properties elsewhere. - /// </summary> - public class ComputedValue<T> - { - private Func<T> compute; - - private T storage; - - public ComputedValue(Func<T> compute) - { - this.compute = compute; - } - - // a flag specifying if the value has to be re-computed. - // note: there is no way to set the flag to false from the outside - public bool IsDirty { get; set; } - - /// <summary> - /// accessor property to retrieved the computed value. - /// </summary> - public T Value - { - get - { - this.ComputeIfRequired(); - return this.storage; - } - } - - private void ComputeIfRequired() - { - if (!this.IsDirty) - { - return; - } - - this.storage = this.compute(); - this.IsDirty = false; - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using System; + + // Using a provided closure the value is computed upon request. + // Managing classes can set the dirty state of the ComputedValue to + // force a consecutive compute of the value. + + /// <summary> + /// Wrapper class for lazily computed values for use as properties elsewhere. + /// </summary> + public class ComputedValue<T> { + private Func<T> compute; + + private T storage; + + public ComputedValue (Func<T> compute) + { + this.compute = compute; + } + + // a flag specifying if the value has to be re-computed. + // note: there is no way to set the flag to false from the outside + public bool IsDirty { get; set; } + + /// <summary> + /// accessor property to retrieved the computed value. + /// </summary> + public T Value { + get { + this.ComputeIfRequired (); + return this.storage; + } + } + + private void ComputeIfRequired () + { + if (!this.IsDirty) { + return; + } + + this.storage = this.compute (); + this.IsDirty = false; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotPose.cs b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotPose.cs index 7f7e883c1..5a532af71 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotPose.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotPose.cs @@ -1,118 +1,112 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Utils; - using System.Collections.Generic; - - // The pose provides positions and tangents along the rope - // as well as upvector information. - // The SlingShotPose further provides methods to interpolate positions, - // tangents or full transforms along the rope. - public class SlingShotPose - { - private int lastIndex = 0; - - /// <summary> - /// Returns the total length of the slingshot rope - /// </summary> - public float TotalLength => this.Lengths[this.Lengths.Count - 1]; - - public List<SCNVector3> Positions { get; } = new List<SCNVector3>(); - - public List<SCNVector3> Tangents { get; } = new List<SCNVector3>(); - - public List<float> Lengths { get; } = new List<float>(); - - public SCNVector3 UpVector { get; set; } = SCNVector3.UnitY; // Vector used to compute orientation of each segment - - private float FindIndex(float l) - { - if (l <= 0) - { - this.lastIndex = 0; - return 0f; - } - - if (l >= this.TotalLength) - { - this.lastIndex = this.Lengths.Count - 2; - return 1f; - } - - while (this.Lengths[this.lastIndex] > l) - { - this.lastIndex -= 1; - } - - while (this.Lengths[this.lastIndex + 1] < l) - { - this.lastIndex += 1; - } - - return (l - this.Lengths[this.lastIndex]) / (this.Lengths[this.lastIndex + 1] - this.Lengths[this.lastIndex]); - } - - /// <summary> - /// Returns the interpolated position at a given length (l from 0.0 to totalLength) - /// </summary> - public SCNVector3 Position(float l) - { - var s = this.FindIndex(l); - return SimdExtensions.Mix(this.Positions[this.lastIndex], - this.Positions[this.lastIndex + 1], - new SCNVector3(s, s, s)); - } - - /// <summary> - /// Returns the position for a given index - /// </summary> - public SCNVector3 PositionForIndex(int index) - { - return this.Positions[index]; - } - - /// <summary> - /// Returns the interpolated tangent at a given length (l from 0.0 to totalLength) - /// </summary> - public SCNVector3 Tangent(float l) - { - var s = this.FindIndex(l); - return SCNVector3.Normalize(SimdExtensions.Mix(this.Tangents[this.lastIndex], - this.Tangents[this.lastIndex + 1], - new SCNVector3(s, s, s))); - } - - /// <summary> - /// Returns the interpolated transform at a given length (l from 0.0 to totalLength) - /// </summary> - public SCNMatrix4 Transform(float l) - { - var position = this.Position(l); - var x = this.Tangent(l); - var y = SCNVector3.Normalize(this.UpVector); - var z = SCNVector3.Normalize(SCNVector3.Cross(x, y)); - y = SCNVector3.Normalize(SCNVector3.Cross(z, x)); - - var rot = new OpenTK.Matrix3(x.X, y.X, z.X, x.Y, y.Y, z.Y, x.Z, y.Z, z.Z); - var matrix = SCNMatrix4.Rotate(rot.ToQuaternion()); - return matrix.SetTranslation((OpenTK.Vector3)position); - } - - /// <summary> - /// Returns the distance to the previous segment for a given index - /// </summary> - public float DistanceToPrev(int index) - { - return this.Lengths[index] - this.Lengths[index - 1]; - } - - /// <summary> - /// Returns the distance to the next segment for a given index - /// </summary> - public float DistanceToNext(int index) - { - return this.Lengths[index + 1] - this.Lengths[index]; - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Utils; + using System.Collections.Generic; + + // The pose provides positions and tangents along the rope + // as well as upvector information. + // The SlingShotPose further provides methods to interpolate positions, + // tangents or full transforms along the rope. + public class SlingShotPose { + private int lastIndex = 0; + + /// <summary> + /// Returns the total length of the slingshot rope + /// </summary> + public float TotalLength => this.Lengths [this.Lengths.Count - 1]; + + public List<SCNVector3> Positions { get; } = new List<SCNVector3> (); + + public List<SCNVector3> Tangents { get; } = new List<SCNVector3> (); + + public List<float> Lengths { get; } = new List<float> (); + + public SCNVector3 UpVector { get; set; } = SCNVector3.UnitY; // Vector used to compute orientation of each segment + + private float FindIndex (float l) + { + if (l <= 0) { + this.lastIndex = 0; + return 0f; + } + + if (l >= this.TotalLength) { + this.lastIndex = this.Lengths.Count - 2; + return 1f; + } + + while (this.Lengths [this.lastIndex] > l) { + this.lastIndex -= 1; + } + + while (this.Lengths [this.lastIndex + 1] < l) { + this.lastIndex += 1; + } + + return (l - this.Lengths [this.lastIndex]) / (this.Lengths [this.lastIndex + 1] - this.Lengths [this.lastIndex]); + } + + /// <summary> + /// Returns the interpolated position at a given length (l from 0.0 to totalLength) + /// </summary> + public SCNVector3 Position (float l) + { + var s = this.FindIndex (l); + return SimdExtensions.Mix (this.Positions [this.lastIndex], + this.Positions [this.lastIndex + 1], + new SCNVector3 (s, s, s)); + } + + /// <summary> + /// Returns the position for a given index + /// </summary> + public SCNVector3 PositionForIndex (int index) + { + return this.Positions [index]; + } + + /// <summary> + /// Returns the interpolated tangent at a given length (l from 0.0 to totalLength) + /// </summary> + public SCNVector3 Tangent (float l) + { + var s = this.FindIndex (l); + return SCNVector3.Normalize (SimdExtensions.Mix (this.Tangents [this.lastIndex], + this.Tangents [this.lastIndex + 1], + new SCNVector3 (s, s, s))); + } + + /// <summary> + /// Returns the interpolated transform at a given length (l from 0.0 to totalLength) + /// </summary> + public SCNMatrix4 Transform (float l) + { + var position = this.Position (l); + var x = this.Tangent (l); + var y = SCNVector3.Normalize (this.UpVector); + var z = SCNVector3.Normalize (SCNVector3.Cross (x, y)); + y = SCNVector3.Normalize (SCNVector3.Cross (z, x)); + + var rot = new OpenTK.Matrix3 (x.X, y.X, z.X, x.Y, y.Y, z.Y, x.Z, y.Z, z.Z); + var matrix = SCNMatrix4.Rotate (rot.ToQuaternion ()); + return matrix.SetTranslation ((OpenTK.Vector3) position); + } + + /// <summary> + /// Returns the distance to the previous segment for a given index + /// </summary> + public float DistanceToPrev (int index) + { + return this.Lengths [index] - this.Lengths [index - 1]; + } + + /// <summary> + /// Returns the distance to the next segment for a given index + /// </summary> + public float DistanceToNext (int index) + { + return this.Lengths [index + 1] - this.Lengths [index]; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotSimulation.cs b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotSimulation.cs index 5d0b60fa2..23eb88aa5 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotSimulation.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/SlingShotSimulation.cs @@ -1,686 +1,631 @@ - -namespace XamarinShot.Models -{ - using Foundation; - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - - public class SimulatedTransform - { - public SimulatedTransform(SCNVector3 position, SCNQuaternion orientation, SCNVector3 velocity, bool dynamic) - { - this.Position = position; - this.Orientation = orientation; - this.Velocity = velocity; - this.Dynamic = dynamic; - } - - public SCNVector3 Position { get; set; } - - public SCNQuaternion Orientation { get; set; } - - public SCNVector3 Velocity { get; set; } - - public bool Dynamic { get; set; } - } - - // Provides access to most variables used to describe the simulation parameters as well as - // the management of the SceneKit rigid bodies. - public class SlingShotSimulation : NSObject - { - public double LinearLaunchAnimationTime { get; } = 0.5f; - public double SimLaunchAnimationTime { get; } = 2.5f; // needs more time to settle - - private const float SimDamping = 0.85f; // the amount of damping to apply to the rigid 5odies - private const float SimBounce = 0f; // the amount of restitution to apply to the rigid bodies - private const float SimShotStrength = 20f; // the strength of the shot when released - private const float SimNeighborStrength = 350f; // the strength for the neighbor springs - private const float SimRestPoseStrength = 5f; // the strength for the restpose force - private const float SimBlend = 0.08f; // the amount of lerp to restPose per iteration, - // higher ends faster, related to finishing sim before simLaunchAnimationTime expires - // the collision plane distance - private const float CollisionPlane = 0.15f; // using half depth of catatpult at 0.25 / 2 ~ 0.125 + slop - - // smoothing the rope from 0 to 1 - private const float SmoothRope = 0.25f; - - // the parent space of the slingshot - private SCNMatrix4 restPoseSpace = new SCNMatrix4(); - - private SCNMatrix4 originalRestPoseSpace = new SCNMatrix4(); - - private List<SCNMatrix4> restPoseTransforms = new List<SCNMatrix4>(); - - public SlingShotSimulation(SCNNode rootNode, int count, float segmentRadius) : base() - { - this.InitializeHelpers(); - - for (var i = 0; i < count; i++) - { - var isStatic = (i < this.BoneInset) || (i >= count - this.BoneInset); - var quaternion = SCNQuaternion.FromAxisAngle(SCNVector3.UnitX, 0); - - var transform = new SimulatedTransform(SCNVector3.Zero, quaternion, SCNVector3.Zero, !isStatic); - this.simulatedTransforms.Add(transform); - } - } - - /// <summary> - /// The rest pose of the slingshot in world space - /// </summary> - public SlingShotPose RestPose => this.computedRestPose.Value; - - private ComputedValue<SlingShotPose> computedRestPose; - - public SCNVector3 FixturePositionL => this.RestPose.Positions.First(); - - public SCNVector3 FixturePositionR => this.RestPose.Positions.Last(); - - public SCNVector3 UpVector => SimdExtensions.CreateQuaternion(this.restPoseSpace).Act(SCNVector3.UnitY); - - // return the number of simulated transforms in this slingshot - public int SimulatedTransformCount => this.simulatedTransforms.Count; - - /// <summary> - /// ignore these bones - /// weight the vertices at the edge of the rope on first/last bone 100% to avoid cord pulling out - /// </summary> - /// <value>The bone inset.</value> - public int BoneInset { get; set; } = 1; - - /// <summary> - /// Defines the original (unstretched) length of the rope - /// </summary> - public float OriginalTotalLength { get; set; } = 100f; - - /// <summary> - /// Defines the original (unstretched) length of the leather portion of the rope - /// </summary> - public float OriginalLeatherLength { get; set; } = 45f; - - public SCNMatrix4 RestPoseSpace - { - get - { - return this.restPoseSpace; - } - - set - { - this.restPoseSpace = value; - this.DirtyCachedValues(); - } - } - - /// <summary> - /// Returns a simulated transform within this simulation - /// </summary> - public SimulatedTransform SimulatedTransform(int index) - { - return this.simulatedTransforms[index]; - } - - /// <summary> - /// Returns a simulated transform within this simulation as float4x4 - /// </summary> - public SCNMatrix4 SimulatedTransformAsFloat4x4(int index) - { - var mSim = this.simulatedTransforms[index]; - var quaternion = mSim.Orientation.ToQuaternion(); - var matrix = SCNMatrix4.Rotate(quaternion); - - matrix.M41 = mSim.Position.X; - matrix.M42 = mSim.Position.Y; - matrix.M43 = mSim.Position.Z; - matrix.M44 = 1f; - - return matrix; - } - - private readonly List<SimulatedTransform> simulatedTransforms = new List<SimulatedTransform>(); - - private double time; - - // the position of the ball - used to compute the input pose. - private SCNVector3 ballPosition = new SCNVector3(0f, 0f, -175f); - public SCNVector3 BallPosition - { - get - { - return this.ballPosition; - } - - set - { - this.ballPosition = value; - this.DirtyCachedValues(); - } - } - - // the radius of the ball - used to compute the input pose - private float ballRadius = 6f; - public float BallRadius - { - get - { - return this.ballRadius; - } - - set - { - this.ballRadius = value; - this.DirtyCachedValues(); - } - } - - // the position on the left side of the ball where the straight part of the rope touches - private SCNVector3 TangentPositionL => this.computedTangentPositionL.Value; - private ComputedValue<SCNVector3> computedTangentPositionL; - - // the position on the right side of the ball where the straight part of the rope touches - private SCNVector3 TangentPositionR => this.computedTangentPositionR.Value; - private ComputedValue<SCNVector3> computedTangentPositionR; - - // the center position within the triangle spanned by the ball and both fixture positions - private SCNVector3 CenterPosition => this.computedCenterPosition.Value; - private ComputedValue<SCNVector3> computedCenterPosition; - - // the angle of the arc portion of the rope touching the ball - public float BetaAngle => this.computedBetaAngle.Value; - private ComputedValue<float> computedBetaAngle; - - // the resulting input pose of the sling shot rope - public SlingShotPose InputPose => this.computedInputPose.Value; - private ComputedValue<SlingShotPose> computedInputPose; - - private void InitializeHelpers() - { - this.computedInputPose = new ComputedValue<SlingShotPose>(() => this.ComputeInputPose()); - this.computedTangentPositionR = new ComputedValue<SCNVector3>(() => this.TangentPosition(this.FixturePositionR)); - this.computedTangentPositionL = new ComputedValue<SCNVector3>(() => this.TangentPosition(this.FixturePositionL)); - - this.computedBetaAngle = new ComputedValue<float>(() => - { - var d = SCNVector3.Normalize(this.ballPosition - this.CenterPosition); - var t = SCNVector3.Normalize(this.TangentPositionL - this.ballPosition); - - var quaternion = SimdExtensions.CreateQuaternion(d, t); - quaternion.ToAxisAngle(out SCNVector3 _, out float angle); - return 2f * angle; - }); - - this.computedCenterPosition = new ComputedValue<SCNVector3>(() => - { - var direction = SCNVector3.Cross(this.UpVector, this.TangentPositionR - this.TangentPositionL); - return this.ballPosition - SCNVector3.Normalize(direction) * 1.25f * this.ballRadius; - }); - - this.computedRestPose = new ComputedValue<SlingShotPose>(() => - { - var data = new SlingShotPose(); - - for (var i = 0; i < this.restPoseTransforms.Count ; i++) - { - var transform = this.restPoseSpace * this.restPoseTransforms[i]; - var p = new SCNVector3(transform.Column3.X, transform.Column3.Y, transform.Column3.Z); - var t = SimdExtensions.CreateQuaternion(transform).Act(new SCNVector3(1f, 0f, 0f)); - - var l = 0f; - if (i > 0) - { - l = data.Lengths[i - 1] + (p - data.Positions[i - 1]).Length; - } - - data.Positions.Add(p); - data.Tangents.Add(t); - data.Lengths.Add(l); - } - - return data; - }); - } - - public SlingShotPose ComputeInputPose() - { - // note the -1 here differs from other usage - var data = new SlingShotPose { UpVector = -this.UpVector /* negated because the strap Y-axis points down */ }; - - var startBend = this.CurrentLengthL / this.CurrentTotalLength; - var endBend = 1f - this.CurrentLengthR / this.CurrentTotalLength; - var leatherOnStraights = this.OriginalLeatherLength - this.CurrentLengthOnBall; - var segmentAStart = 0f; - var segmentAEnd = this.CurrentLengthL - leatherOnStraights * 0.5f; - var segmentCStart = segmentAEnd + this.OriginalLeatherLength; - var segmentCEnd = this.CurrentTotalLength; - var originalLeatherRange = this.OriginalLeatherLength / this.OriginalTotalLength; - var currentLeatherRange = this.OriginalLeatherLength / this.CurrentTotalLength; - - for (var i = 0; i < this.SimulatedTransformCount; i++) - { - var l = this.OriginalTotalLength * (float)i / (float)(this.SimulatedTransformCount - 1f); - var u = l / this.OriginalTotalLength; - - // remap the u value depending on the material (rubber vs leather) - var isRubber = Math.Abs(0.5f - u) > originalLeatherRange * 0.5f; - if (isRubber) - { - if (u< 0.5f) - { - u = u / (0.5f - originalLeatherRange * 0.5f); - u = (segmentAStart + (segmentAEnd - segmentAStart) * u) / this.CurrentTotalLength; - } - else - { - u = 1f - (1f - u) / (0.5f - originalLeatherRange * 0.5f); - u = (segmentCStart + (segmentCEnd - segmentCStart) * u) / this.CurrentTotalLength; - } - } - else - { - u = (startBend + endBend) * 0.5f - (0.5f - u) * (currentLeatherRange / originalLeatherRange); - } - - var p = SCNVector3.Zero; - var t = SCNVector3.UnitX; - if (u < startBend) - { - // left straight - var value = u / startBend; - p = SimdExtensions.Mix(this.FixturePositionL, - this.TangentPositionL, - new SCNVector3(value, value, value)); // left rubber band - t = SCNVector3.Normalize(this.TangentPositionL - this.FixturePositionL); - } - else if (u > endBend) - { - // right straight - var value = (1f - u) / (1f - endBend); - p = SimdExtensions.Mix(this.FixturePositionR, - this.TangentPositionR, - new SCNVector3(value, value, value)); // right rubber band - t = SCNVector3.Normalize(this.FixturePositionR - this.TangentPositionR); - } - else - { - // on the ball - var upv = this.UpVector; - var rot = SCNQuaternion.FromAxisAngle(upv , - this.BetaAngle * (u - startBend) / (endBend - startBend)); - p = this.ballPosition + rot.Act(this.TangentPositionL - this.ballPosition); - t = SCNVector3.Cross(upv, SCNVector3.Normalize(this.ballPosition - p)); - } - - data.Positions.Add(p); - data.Tangents.Add(t); - data.Lengths.Add(l); - } - - return data; - } - - /// <summary> - /// Mark all computed values as dirty - to force a recompute - /// </summary> - private void DirtyCachedValues() - { - this.computedTangentPositionL.IsDirty = true; - this.computedTangentPositionR.IsDirty = true; - this.computedCenterPosition.IsDirty = true; - this.computedBetaAngle.IsDirty = true; - this.computedInputPose.IsDirty = true; - this.computedRestPose.IsDirty = true; - } - - /// <summary> - /// Computes the tangent position of the rope based on a given fixture - /// </summary> - private SCNVector3 TangentPosition(SCNVector3 fixture) - { - var r = this.ballRadius; - var d = fixture - this.ballPosition; - var alpha = (float)Math.Acos(r / d.Length); - d = this.ballRadius * SCNVector3.Normalize(d); - var rot = SCNQuaternion.FromAxisAngle(this.UpVector, fixture == this.FixturePositionL ? -alpha : alpha); - var d_rotated = rot.Act(d); - return d_rotated + this.ballPosition; - } - - /// <summary> - /// Sets the initial rest pose of the slingshot, all args are in global space - /// </summary> - private void SetInitialRestPose(SCNMatrix4 slingshotSpace, List<SCNMatrix4> transforms) - { - this.originalRestPoseSpace = slingshotSpace; - this.RestPoseSpace = slingshotSpace; - - this.restPoseTransforms = new List<SCNMatrix4>(); - - for (var i = 0; i < transforms.Count; i++) - { - this.restPoseTransforms.Add(SCNMatrix4.Invert(this.originalRestPoseSpace) * transforms[i]); - } - - this.computedRestPose.IsDirty = true; - } - - /// <summary> - /// Sets the initial rest pose from a series of scenekit nodes - /// </summary> - public void SetInitialRestPose(SCNNode slingshotBase, List<SCNNode> bones) - { - var space = slingshotBase.WorldTransform; - space.Transpose(); - - var transforms = new List<SCNMatrix4>(); - - for (var i = 0; i < bones.Count; i++) - { - var worldTransform = bones[i].WorldTransform; - worldTransform.Transpose(); - transforms.Add(worldTransform); - } - - this.SetInitialRestPose(space, transforms); - } - - // returns the length of the rope touching the ball - public float CurrentLengthOnBall => this.BetaAngle * this.ballRadius; - - // returns the length of the straight portion of the rope on the left side of the ball - public float CurrentLengthL => (this.TangentPositionL - this.FixturePositionL).Length; - - // returns the length of the straight portion of the rope on the right side of the ball - public float CurrentLengthR => (this.TangentPositionR - this.FixturePositionR).Length; - - // returns the current total length of the rope - public float CurrentTotalLength => this.CurrentLengthL + this.CurrentLengthOnBall + this.CurrentLengthR; - - /// <summary> - /// Returns the interpolated transform on the restpose given a length l (from 0.0 to originalTotalLength) - /// </summary> - private SCNMatrix4 RestPoseTransform(float l) - { - if (this.CurrentTotalLength == 0f) - { - return new SCNMatrix4(); - } - - var normalizedL = this.RestPose.TotalLength * l / this.OriginalTotalLength; - return this.RestPose.Transform(normalizedL); - } - - /// <summary> - /// Returns the interpolated transform on the input pose given a length l (from 0.0 to currentTotalLength) - /// </summary> - private SCNMatrix4 InputPoseTransform(float l) - { - if (this.CurrentTotalLength == 0f) - { - return new SCNMatrix4(); - } - - return this.InputPose.Transform(l); - } - - public void InterpolateToRestPoseAnimation(double duration, List<SCNNode> ropeShapes) - { - // use relative tr[ansforms here, these are safer when the catapult gets hit - if (duration == 0d) - { - for (var i = this.BoneInset; i < ropeShapes.Count - this.BoneInset; i++) - { - var worldTransform = this.restPoseSpace * this.restPoseTransforms[i]; - worldTransform.Transpose(); - ropeShapes[i].WorldTransform = worldTransform; - } - } - else - { - SCNTransaction.Begin(); - SCNTransaction.AnimationDuration = duration; - - for (var i = this.BoneInset; i < ropeShapes.Count - this.BoneInset; i++) - { - var worldTransform = this.restPoseSpace * this.restPoseTransforms[i]; - worldTransform.Transpose(); - ropeShapes[i].WorldTransform = worldTransform; - } - - SCNTransaction.Commit(); - } - } - - /// <summary> - /// Disables the simulation on the slingshot and sets the rigid bodies to be driven by the input pose - /// </summary> - public void EnableInputPose() - { - for (var i = 0; i < this.simulatedTransforms.Count; i++) - { - var l = this.OriginalTotalLength * (float)i / (float)(this.simulatedTransforms.Count - 1); - var transform = this.InputPoseTransform(l); - - var position = new SCNVector3(transform.Column3.X, transform.Column3.Y, transform.Column3.Z); - this.simulatedTransforms[i].Position = position; - this.simulatedTransforms[i].Orientation = SimdExtensions.CreateQuaternion(transform); - this.simulatedTransforms[i].Velocity = SCNVector3.Zero; - this.simulatedTransforms[i].Dynamic = false; - } - } - - /// <summary> - /// Starts the simulation for the slingshot - /// </summary> - public void StartLaunchSimulation() - { - var center = (this.FixturePositionL + this.FixturePositionR) * 0.5f; - var force = center - this.ballPosition; - var strength = (float)SimShotStrength; - - for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) - { - this.simulatedTransforms[i].Dynamic = true; - - // apply a force - var u = (float)i / (float)(this.simulatedTransforms.Count - 1); - var restPoseFactorAlongRope = 1f - Math.Abs(u - 0.5f) / 0.5f; - - this.simulatedTransforms[i].Velocity = force * restPoseFactorAlongRope * strength; - } - } - - /// <summary> - /// Computes and applies the custom forces for the slingshot rope. - /// This should be called every frame. - /// </summary> - private void ApplyForces() - { - var b = new SCNVector3(SimBlend, SimBlend, SimBlend); - - for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) - { - if (!this.simulatedTransforms[i].Dynamic) - { - continue; - } - - var force = SCNVector3.Zero; - - if (i > 0) - { - var restA = this.RestPose.Positions[i - 1]; - var restB = this.RestPose.Positions[i]; - var currentA = this.simulatedTransforms[i - 1].Position; - var currentB = this.simulatedTransforms[i].Position; - var restDistance = (restA - restB).Length; - var currentDistance = (currentA - currentB).Length; - force += SCNVector3.Normalize(currentA - currentB) * (currentDistance - restDistance) * SimNeighborStrength; - } - - if (i < this.simulatedTransforms.Count - 1) - { - var restA = this.RestPose.Positions[i + 1]; - var restB = this.RestPose.Positions[i]; - var currentA = this.simulatedTransforms[i + 1].Position; - var currentB = this.simulatedTransforms[i].Position; - var restDistance = (restA - restB).Length; - var currentDistance = (currentA - currentB).Length; - force += SCNVector3.Normalize(currentA - currentB) * (currentDistance - restDistance) * SimNeighborStrength; - } - - force += (this.RestPose.Positions[i] - this.simulatedTransforms[i].Position) * SimRestPoseStrength; - - - var vel = this.simulatedTransforms[i].Velocity; - this.simulatedTransforms[i].Velocity = SimdExtensions.Mix(vel, force, b); - } - } - - private void AverageVelocities() - { - var currentTransforms = new List<SimulatedTransform>(); - currentTransforms.AddRange(this.simulatedTransforms); - - for (var i = this.BoneInset; i < this.SimulatedTransformCount - this.BoneInset; i++) - { - if (!this.simulatedTransforms[i].Dynamic) - { - continue; - } - - var a = currentTransforms[i - 1].Velocity; - var b = currentTransforms[i].Velocity; - var c = currentTransforms[i + 1].Velocity; - var ab = SimdExtensions.Mix(a, b, new SCNVector3(0.5f, 0.5f, 0.5f)); - var bc = SimdExtensions.Mix(b, c, new SCNVector3(0.5f, 0.5f, 0.5f)); - this.simulatedTransforms[i].Velocity = SimdExtensions.Mix(ab, bc, t: new SCNVector3(0.5f, 0.5f, 0.5f)); - - var center = SimdExtensions.Mix(currentTransforms[i - 1].Position, currentTransforms[i + 1].Position, new SCNVector3(0.5f, 0.5f, 0.5f)); - this.simulatedTransforms[i].Position = SimdExtensions.Mix(this.simulatedTransforms[i].Position, center, new SCNVector3(SmoothRope, SmoothRope, SmoothRope)); - } - } - - private void PerformPlaneCollision(List<SimulatedTransform> previousTransforms, float seconds) - { - for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) - { - if (!this.simulatedTransforms[i].Dynamic) - { - continue; - } - - var p = this.simulatedTransforms[i].Position; - var v = this.simulatedTransforms[i].Velocity; - - // project into the space of the base - var pM = SCNMatrix4.Identity.SetTranslation((OpenTK.Vector3)p); - - var pLocal = SCNMatrix4.Invert(this.restPoseSpace) * pM; - - if (pLocal.Column3.Z <= CollisionPlane) - { - pLocal.M34 = CollisionPlane; - pM = this.restPoseSpace * pLocal; - - var pOnPlane = new SCNVector3(pM.Column3.X, pM.Column3.Y, pM.Column3.Z); - - var blend = new SCNVector3(0.3f, 0.3f, 0.3f); - this.simulatedTransforms[i].Position = SimdExtensions.Mix(p, pOnPlane, blend); - - var correctedVelocity = (this.simulatedTransforms[i].Position - previousTransforms[i].Position) / seconds; - correctedVelocity = SCNVector3.Multiply(correctedVelocity, new SCNVector3(0.7f, 0.1f, 0.7f)); - - // verlet integration - this.simulatedTransforms[i].Velocity = SimdExtensions.Mix(v, correctedVelocity, blend); - - p = this.simulatedTransforms[i].Position; - v = this.simulatedTransforms[i].Velocity; - } - - if (pLocal.Column3.Y <= CollisionPlane + 0.3f) - { - pLocal.M24 = CollisionPlane + 0.3f; - pM = this.restPoseSpace * pLocal; - - var pOnPlane = new SCNVector3(pM.Column3.X, pM.Column3.Y, pM.Column3.Z); - - var blend = new SCNVector3(0.3f, 0.3f, 0.3f); - this.simulatedTransforms[i].Position = SimdExtensions.Mix(p, pOnPlane, blend); - - var correctedVelocity = (this.simulatedTransforms[i].Position - previousTransforms[i].Position) / seconds; - - // verlet integration - this.simulatedTransforms[i].Velocity = SimdExtensions.Mix(v, correctedVelocity, blend); - } - } - } - - /// <summary> - /// Aligns the rigid bodies by correcting their orienation - /// This should be called after the simulation step - /// </summary> - private void AlignBones() - { - // orient the bodies accordingly - for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) - { - if (!this.simulatedTransforms[i].Dynamic) - { - continue; - } - - var a = this.simulatedTransforms[i - 1].Position; - var b = this.simulatedTransforms[i + 1].Position; - - // this is the upVector computed for each bone of the rest pose - var transform = this.restPoseSpace * this.restPoseTransforms[i]; // todo: direction of multiply? - var y = SimdExtensions.CreateQuaternion(transform).Act(new SCNVector3(0f, 1f, 0f)); - - var x = SCNVector3.Normalize(b - a); - var z = SCNVector3.Normalize(SCNVector3.Cross(x, y)); - y = SCNVector3.Normalize(SCNVector3.Cross(z, x)); - - var rot = new OpenTK.Matrix3(x.X, y.X, z.X, x.Y, y.Y, z.Y, x.Z, y.Z, z.Z); - this.simulatedTransforms[i].Orientation = new SCNQuaternion(rot.ToQuaternion()); - } - } - - public void SimulateStep(double time) - { - var minUpdateSeconds = 1f / 120f; - var maxUpdateSeconds = 1f / 30f; - var seconds = DigitExtensions.Clamp((float)(time - this.time), minUpdateSeconds, maxUpdateSeconds); - - // could run multiple iterations if greater than maxUpdateSeconds, but for now just run one - - this.ApplyForces(); - this.AverageVelocities(); - - // copy the current state - var currentTransforms = new List<SimulatedTransform>(); - currentTransforms.AddRange(this.simulatedTransforms); - - // simulate forward - for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) - { - if (!currentTransforms[i].Dynamic) - { - continue; - } - var p = currentTransforms[i].Position; - var v = currentTransforms[i].Velocity; - p += v * seconds; +namespace XamarinShot.Models { + using Foundation; + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + public class SimulatedTransform { + public SimulatedTransform (SCNVector3 position, SCNQuaternion orientation, SCNVector3 velocity, bool dynamic) + { + this.Position = position; + this.Orientation = orientation; + this.Velocity = velocity; + this.Dynamic = dynamic; + } + + public SCNVector3 Position { get; set; } + + public SCNQuaternion Orientation { get; set; } + + public SCNVector3 Velocity { get; set; } + + public bool Dynamic { get; set; } + } + + // Provides access to most variables used to describe the simulation parameters as well as + // the management of the SceneKit rigid bodies. + public class SlingShotSimulation : NSObject { + public double LinearLaunchAnimationTime { get; } = 0.5f; + public double SimLaunchAnimationTime { get; } = 2.5f; // needs more time to settle + + private const float SimDamping = 0.85f; // the amount of damping to apply to the rigid 5odies + private const float SimBounce = 0f; // the amount of restitution to apply to the rigid bodies + private const float SimShotStrength = 20f; // the strength of the shot when released + private const float SimNeighborStrength = 350f; // the strength for the neighbor springs + private const float SimRestPoseStrength = 5f; // the strength for the restpose force + private const float SimBlend = 0.08f; // the amount of lerp to restPose per iteration, + // higher ends faster, related to finishing sim before simLaunchAnimationTime expires + // the collision plane distance + private const float CollisionPlane = 0.15f; // using half depth of catatpult at 0.25 / 2 ~ 0.125 + slop + + // smoothing the rope from 0 to 1 + private const float SmoothRope = 0.25f; + + // the parent space of the slingshot + private SCNMatrix4 restPoseSpace = new SCNMatrix4 (); + + private SCNMatrix4 originalRestPoseSpace = new SCNMatrix4 (); + + private List<SCNMatrix4> restPoseTransforms = new List<SCNMatrix4> (); + + public SlingShotSimulation (SCNNode rootNode, int count, float segmentRadius) : base () + { + this.InitializeHelpers (); + + for (var i = 0; i < count; i++) { + var isStatic = (i < this.BoneInset) || (i >= count - this.BoneInset); + var quaternion = SCNQuaternion.FromAxisAngle (SCNVector3.UnitX, 0); + + var transform = new SimulatedTransform (SCNVector3.Zero, quaternion, SCNVector3.Zero, !isStatic); + this.simulatedTransforms.Add (transform); + } + } + + /// <summary> + /// The rest pose of the slingshot in world space + /// </summary> + public SlingShotPose RestPose => this.computedRestPose.Value; + + private ComputedValue<SlingShotPose> computedRestPose; + + public SCNVector3 FixturePositionL => this.RestPose.Positions.First (); + + public SCNVector3 FixturePositionR => this.RestPose.Positions.Last (); + + public SCNVector3 UpVector => SimdExtensions.CreateQuaternion (this.restPoseSpace).Act (SCNVector3.UnitY); + + // return the number of simulated transforms in this slingshot + public int SimulatedTransformCount => this.simulatedTransforms.Count; + + /// <summary> + /// ignore these bones + /// weight the vertices at the edge of the rope on first/last bone 100% to avoid cord pulling out + /// </summary> + /// <value>The bone inset.</value> + public int BoneInset { get; set; } = 1; + + /// <summary> + /// Defines the original (unstretched) length of the rope + /// </summary> + public float OriginalTotalLength { get; set; } = 100f; + + /// <summary> + /// Defines the original (unstretched) length of the leather portion of the rope + /// </summary> + public float OriginalLeatherLength { get; set; } = 45f; + + public SCNMatrix4 RestPoseSpace { + get { + return this.restPoseSpace; + } + + set { + this.restPoseSpace = value; + this.DirtyCachedValues (); + } + } + + /// <summary> + /// Returns a simulated transform within this simulation + /// </summary> + public SimulatedTransform SimulatedTransform (int index) + { + return this.simulatedTransforms [index]; + } + + /// <summary> + /// Returns a simulated transform within this simulation as float4x4 + /// </summary> + public SCNMatrix4 SimulatedTransformAsFloat4x4 (int index) + { + var mSim = this.simulatedTransforms [index]; + var quaternion = mSim.Orientation.ToQuaternion (); + var matrix = SCNMatrix4.Rotate (quaternion); + + matrix.M41 = mSim.Position.X; + matrix.M42 = mSim.Position.Y; + matrix.M43 = mSim.Position.Z; + matrix.M44 = 1f; + + return matrix; + } + + private readonly List<SimulatedTransform> simulatedTransforms = new List<SimulatedTransform> (); + + private double time; + + // the position of the ball - used to compute the input pose. + private SCNVector3 ballPosition = new SCNVector3 (0f, 0f, -175f); + public SCNVector3 BallPosition { + get { + return this.ballPosition; + } + + set { + this.ballPosition = value; + this.DirtyCachedValues (); + } + } + + // the radius of the ball - used to compute the input pose + private float ballRadius = 6f; + public float BallRadius { + get { + return this.ballRadius; + } + + set { + this.ballRadius = value; + this.DirtyCachedValues (); + } + } + + // the position on the left side of the ball where the straight part of the rope touches + private SCNVector3 TangentPositionL => this.computedTangentPositionL.Value; + private ComputedValue<SCNVector3> computedTangentPositionL; + + // the position on the right side of the ball where the straight part of the rope touches + private SCNVector3 TangentPositionR => this.computedTangentPositionR.Value; + private ComputedValue<SCNVector3> computedTangentPositionR; + + // the center position within the triangle spanned by the ball and both fixture positions + private SCNVector3 CenterPosition => this.computedCenterPosition.Value; + private ComputedValue<SCNVector3> computedCenterPosition; + + // the angle of the arc portion of the rope touching the ball + public float BetaAngle => this.computedBetaAngle.Value; + private ComputedValue<float> computedBetaAngle; + + // the resulting input pose of the sling shot rope + public SlingShotPose InputPose => this.computedInputPose.Value; + private ComputedValue<SlingShotPose> computedInputPose; + + private void InitializeHelpers () + { + this.computedInputPose = new ComputedValue<SlingShotPose> (() => this.ComputeInputPose ()); + this.computedTangentPositionR = new ComputedValue<SCNVector3> (() => this.TangentPosition (this.FixturePositionR)); + this.computedTangentPositionL = new ComputedValue<SCNVector3> (() => this.TangentPosition (this.FixturePositionL)); + + this.computedBetaAngle = new ComputedValue<float> (() => { + var d = SCNVector3.Normalize (this.ballPosition - this.CenterPosition); + var t = SCNVector3.Normalize (this.TangentPositionL - this.ballPosition); + + var quaternion = SimdExtensions.CreateQuaternion (d, t); + quaternion.ToAxisAngle (out SCNVector3 _, out float angle); + return 2f * angle; + }); + + this.computedCenterPosition = new ComputedValue<SCNVector3> (() => { + var direction = SCNVector3.Cross (this.UpVector, this.TangentPositionR - this.TangentPositionL); + return this.ballPosition - SCNVector3.Normalize (direction) * 1.25f * this.ballRadius; + }); + + this.computedRestPose = new ComputedValue<SlingShotPose> (() => { + var data = new SlingShotPose (); + + for (var i = 0; i < this.restPoseTransforms.Count; i++) { + var transform = this.restPoseSpace * this.restPoseTransforms [i]; + var p = new SCNVector3 (transform.Column3.X, transform.Column3.Y, transform.Column3.Z); + var t = SimdExtensions.CreateQuaternion (transform).Act (new SCNVector3 (1f, 0f, 0f)); + + var l = 0f; + if (i > 0) { + l = data.Lengths [i - 1] + (p - data.Positions [i - 1]).Length; + } + + data.Positions.Add (p); + data.Tangents.Add (t); + data.Lengths.Add (l); + } + + return data; + }); + } + + public SlingShotPose ComputeInputPose () + { + // note the -1 here differs from other usage + var data = new SlingShotPose { UpVector = -this.UpVector /* negated because the strap Y-axis points down */ }; + + var startBend = this.CurrentLengthL / this.CurrentTotalLength; + var endBend = 1f - this.CurrentLengthR / this.CurrentTotalLength; + var leatherOnStraights = this.OriginalLeatherLength - this.CurrentLengthOnBall; + var segmentAStart = 0f; + var segmentAEnd = this.CurrentLengthL - leatherOnStraights * 0.5f; + var segmentCStart = segmentAEnd + this.OriginalLeatherLength; + var segmentCEnd = this.CurrentTotalLength; + var originalLeatherRange = this.OriginalLeatherLength / this.OriginalTotalLength; + var currentLeatherRange = this.OriginalLeatherLength / this.CurrentTotalLength; + + for (var i = 0; i < this.SimulatedTransformCount; i++) { + var l = this.OriginalTotalLength * (float) i / (float) (this.SimulatedTransformCount - 1f); + var u = l / this.OriginalTotalLength; + + // remap the u value depending on the material (rubber vs leather) + var isRubber = Math.Abs (0.5f - u) > originalLeatherRange * 0.5f; + if (isRubber) { + if (u < 0.5f) { + u = u / (0.5f - originalLeatherRange * 0.5f); + u = (segmentAStart + (segmentAEnd - segmentAStart) * u) / this.CurrentTotalLength; + } else { + u = 1f - (1f - u) / (0.5f - originalLeatherRange * 0.5f); + u = (segmentCStart + (segmentCEnd - segmentCStart) * u) / this.CurrentTotalLength; + } + } else { + u = (startBend + endBend) * 0.5f - (0.5f - u) * (currentLeatherRange / originalLeatherRange); + } + + var p = SCNVector3.Zero; + var t = SCNVector3.UnitX; + if (u < startBend) { + // left straight + var value = u / startBend; + p = SimdExtensions.Mix (this.FixturePositionL, + this.TangentPositionL, + new SCNVector3 (value, value, value)); // left rubber band + t = SCNVector3.Normalize (this.TangentPositionL - this.FixturePositionL); + } else if (u > endBend) { + // right straight + var value = (1f - u) / (1f - endBend); + p = SimdExtensions.Mix (this.FixturePositionR, + this.TangentPositionR, + new SCNVector3 (value, value, value)); // right rubber band + t = SCNVector3.Normalize (this.FixturePositionR - this.TangentPositionR); + } else { + // on the ball + var upv = this.UpVector; + var rot = SCNQuaternion.FromAxisAngle (upv, -this.BetaAngle * (u - startBend) / (endBend - startBend)); + p = this.ballPosition + rot.Act (this.TangentPositionL - this.ballPosition); + t = SCNVector3.Cross (upv, SCNVector3.Normalize (this.ballPosition - p)); + } + + data.Positions.Add (p); + data.Tangents.Add (t); + data.Lengths.Add (l); + } + + return data; + } + + /// <summary> + /// Mark all computed values as dirty - to force a recompute + /// </summary> + private void DirtyCachedValues () + { + this.computedTangentPositionL.IsDirty = true; + this.computedTangentPositionR.IsDirty = true; + this.computedCenterPosition.IsDirty = true; + this.computedBetaAngle.IsDirty = true; + this.computedInputPose.IsDirty = true; + this.computedRestPose.IsDirty = true; + } + + /// <summary> + /// Computes the tangent position of the rope based on a given fixture + /// </summary> + private SCNVector3 TangentPosition (SCNVector3 fixture) + { + var r = this.ballRadius; + var d = fixture - this.ballPosition; + var alpha = (float) Math.Acos (r / d.Length); + d = this.ballRadius * SCNVector3.Normalize (d); + var rot = SCNQuaternion.FromAxisAngle (this.UpVector, fixture == this.FixturePositionL ? -alpha : alpha); + var d_rotated = rot.Act (d); + return d_rotated + this.ballPosition; + } + + /// <summary> + /// Sets the initial rest pose of the slingshot, all args are in global space + /// </summary> + private void SetInitialRestPose (SCNMatrix4 slingshotSpace, List<SCNMatrix4> transforms) + { + this.originalRestPoseSpace = slingshotSpace; + this.RestPoseSpace = slingshotSpace; + + this.restPoseTransforms = new List<SCNMatrix4> (); + + for (var i = 0; i < transforms.Count; i++) { + this.restPoseTransforms.Add (SCNMatrix4.Invert (this.originalRestPoseSpace) * transforms [i]); + } + + this.computedRestPose.IsDirty = true; + } + + /// <summary> + /// Sets the initial rest pose from a series of scenekit nodes + /// </summary> + public void SetInitialRestPose (SCNNode slingshotBase, List<SCNNode> bones) + { + var space = slingshotBase.WorldTransform; + space.Transpose (); + + var transforms = new List<SCNMatrix4> (); + + for (var i = 0; i < bones.Count; i++) { + var worldTransform = bones [i].WorldTransform; + worldTransform.Transpose (); + transforms.Add (worldTransform); + } + + this.SetInitialRestPose (space, transforms); + } + + // returns the length of the rope touching the ball + public float CurrentLengthOnBall => this.BetaAngle * this.ballRadius; + + // returns the length of the straight portion of the rope on the left side of the ball + public float CurrentLengthL => (this.TangentPositionL - this.FixturePositionL).Length; + + // returns the length of the straight portion of the rope on the right side of the ball + public float CurrentLengthR => (this.TangentPositionR - this.FixturePositionR).Length; + + // returns the current total length of the rope + public float CurrentTotalLength => this.CurrentLengthL + this.CurrentLengthOnBall + this.CurrentLengthR; + + /// <summary> + /// Returns the interpolated transform on the restpose given a length l (from 0.0 to originalTotalLength) + /// </summary> + private SCNMatrix4 RestPoseTransform (float l) + { + if (this.CurrentTotalLength == 0f) { + return new SCNMatrix4 (); + } + + var normalizedL = this.RestPose.TotalLength * l / this.OriginalTotalLength; + return this.RestPose.Transform (normalizedL); + } + + /// <summary> + /// Returns the interpolated transform on the input pose given a length l (from 0.0 to currentTotalLength) + /// </summary> + private SCNMatrix4 InputPoseTransform (float l) + { + if (this.CurrentTotalLength == 0f) { + return new SCNMatrix4 (); + } + + return this.InputPose.Transform (l); + } + + public void InterpolateToRestPoseAnimation (double duration, List<SCNNode> ropeShapes) + { + // use relative tr[ansforms here, these are safer when the catapult gets hit + if (duration == 0d) { + for (var i = this.BoneInset; i < ropeShapes.Count - this.BoneInset; i++) { + var worldTransform = this.restPoseSpace * this.restPoseTransforms [i]; + worldTransform.Transpose (); + ropeShapes [i].WorldTransform = worldTransform; + } + } else { + SCNTransaction.Begin (); + SCNTransaction.AnimationDuration = duration; + + for (var i = this.BoneInset; i < ropeShapes.Count - this.BoneInset; i++) { + var worldTransform = this.restPoseSpace * this.restPoseTransforms [i]; + worldTransform.Transpose (); + ropeShapes [i].WorldTransform = worldTransform; + } + + SCNTransaction.Commit (); + } + } + + /// <summary> + /// Disables the simulation on the slingshot and sets the rigid bodies to be driven by the input pose + /// </summary> + public void EnableInputPose () + { + for (var i = 0; i < this.simulatedTransforms.Count; i++) { + var l = this.OriginalTotalLength * (float) i / (float) (this.simulatedTransforms.Count - 1); + var transform = this.InputPoseTransform (l); + + var position = new SCNVector3 (transform.Column3.X, transform.Column3.Y, transform.Column3.Z); + this.simulatedTransforms [i].Position = position; + this.simulatedTransforms [i].Orientation = SimdExtensions.CreateQuaternion (transform); + this.simulatedTransforms [i].Velocity = SCNVector3.Zero; + this.simulatedTransforms [i].Dynamic = false; + } + } + + /// <summary> + /// Starts the simulation for the slingshot + /// </summary> + public void StartLaunchSimulation () + { + var center = (this.FixturePositionL + this.FixturePositionR) * 0.5f; + var force = center - this.ballPosition; + var strength = (float) SimShotStrength; + + for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) { + this.simulatedTransforms [i].Dynamic = true; + + // apply a force + var u = (float) i / (float) (this.simulatedTransforms.Count - 1); + var restPoseFactorAlongRope = 1f - Math.Abs (u - 0.5f) / 0.5f; + + this.simulatedTransforms [i].Velocity = force * restPoseFactorAlongRope * strength; + } + } + + /// <summary> + /// Computes and applies the custom forces for the slingshot rope. + /// This should be called every frame. + /// </summary> + private void ApplyForces () + { + var b = new SCNVector3 (SimBlend, SimBlend, SimBlend); + + for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) { + if (!this.simulatedTransforms [i].Dynamic) { + continue; + } + + var force = SCNVector3.Zero; + + if (i > 0) { + var restA = this.RestPose.Positions [i - 1]; + var restB = this.RestPose.Positions [i]; + var currentA = this.simulatedTransforms [i - 1].Position; + var currentB = this.simulatedTransforms [i].Position; + var restDistance = (restA - restB).Length; + var currentDistance = (currentA - currentB).Length; + force += SCNVector3.Normalize (currentA - currentB) * (currentDistance - restDistance) * SimNeighborStrength; + } + + if (i < this.simulatedTransforms.Count - 1) { + var restA = this.RestPose.Positions [i + 1]; + var restB = this.RestPose.Positions [i]; + var currentA = this.simulatedTransforms [i + 1].Position; + var currentB = this.simulatedTransforms [i].Position; + var restDistance = (restA - restB).Length; + var currentDistance = (currentA - currentB).Length; + force += SCNVector3.Normalize (currentA - currentB) * (currentDistance - restDistance) * SimNeighborStrength; + } + + force += (this.RestPose.Positions [i] - this.simulatedTransforms [i].Position) * SimRestPoseStrength; + + + var vel = this.simulatedTransforms [i].Velocity; + this.simulatedTransforms [i].Velocity = SimdExtensions.Mix (vel, force, b); + } + } + + private void AverageVelocities () + { + var currentTransforms = new List<SimulatedTransform> (); + currentTransforms.AddRange (this.simulatedTransforms); + + for (var i = this.BoneInset; i < this.SimulatedTransformCount - this.BoneInset; i++) { + if (!this.simulatedTransforms [i].Dynamic) { + continue; + } + + var a = currentTransforms [i - 1].Velocity; + var b = currentTransforms [i].Velocity; + var c = currentTransforms [i + 1].Velocity; + var ab = SimdExtensions.Mix (a, b, new SCNVector3 (0.5f, 0.5f, 0.5f)); + var bc = SimdExtensions.Mix (b, c, new SCNVector3 (0.5f, 0.5f, 0.5f)); + this.simulatedTransforms [i].Velocity = SimdExtensions.Mix (ab, bc, t: new SCNVector3 (0.5f, 0.5f, 0.5f)); + + var center = SimdExtensions.Mix (currentTransforms [i - 1].Position, currentTransforms [i + 1].Position, new SCNVector3 (0.5f, 0.5f, 0.5f)); + this.simulatedTransforms [i].Position = SimdExtensions.Mix (this.simulatedTransforms [i].Position, center, new SCNVector3 (SmoothRope, SmoothRope, SmoothRope)); + } + } + + private void PerformPlaneCollision (List<SimulatedTransform> previousTransforms, float seconds) + { + for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) { + if (!this.simulatedTransforms [i].Dynamic) { + continue; + } + + var p = this.simulatedTransforms [i].Position; + var v = this.simulatedTransforms [i].Velocity; + + // project into the space of the base + var pM = SCNMatrix4.Identity.SetTranslation ((OpenTK.Vector3) p); + + var pLocal = SCNMatrix4.Invert (this.restPoseSpace) * pM; + + if (pLocal.Column3.Z <= CollisionPlane) { + pLocal.M34 = CollisionPlane; + pM = this.restPoseSpace * pLocal; + + var pOnPlane = new SCNVector3 (pM.Column3.X, pM.Column3.Y, pM.Column3.Z); + + var blend = new SCNVector3 (0.3f, 0.3f, 0.3f); + this.simulatedTransforms [i].Position = SimdExtensions.Mix (p, pOnPlane, blend); + + var correctedVelocity = (this.simulatedTransforms [i].Position - previousTransforms [i].Position) / seconds; + correctedVelocity = SCNVector3.Multiply (correctedVelocity, new SCNVector3 (0.7f, 0.1f, 0.7f)); + + // verlet integration + this.simulatedTransforms [i].Velocity = SimdExtensions.Mix (v, correctedVelocity, blend); + + p = this.simulatedTransforms [i].Position; + v = this.simulatedTransforms [i].Velocity; + } + + if (pLocal.Column3.Y <= CollisionPlane + 0.3f) { + pLocal.M24 = CollisionPlane + 0.3f; + pM = this.restPoseSpace * pLocal; + + var pOnPlane = new SCNVector3 (pM.Column3.X, pM.Column3.Y, pM.Column3.Z); + + var blend = new SCNVector3 (0.3f, 0.3f, 0.3f); + this.simulatedTransforms [i].Position = SimdExtensions.Mix (p, pOnPlane, blend); + + var correctedVelocity = (this.simulatedTransforms [i].Position - previousTransforms [i].Position) / seconds; + + // verlet integration + this.simulatedTransforms [i].Velocity = SimdExtensions.Mix (v, correctedVelocity, blend); + } + } + } + + /// <summary> + /// Aligns the rigid bodies by correcting their orienation + /// This should be called after the simulation step + /// </summary> + private void AlignBones () + { + // orient the bodies accordingly + for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) { + if (!this.simulatedTransforms [i].Dynamic) { + continue; + } + + var a = this.simulatedTransforms [i - 1].Position; + var b = this.simulatedTransforms [i + 1].Position; + + // this is the upVector computed for each bone of the rest pose + var transform = this.restPoseSpace * this.restPoseTransforms [i]; // todo: direction of multiply? + var y = SimdExtensions.CreateQuaternion (transform).Act (new SCNVector3 (0f, 1f, 0f)); - this.simulatedTransforms[i].Position = p; - } - - this.PerformPlaneCollision(currentTransforms, seconds); - this.AlignBones(); - - this.time = time; - } - } -} \ No newline at end of file + var x = SCNVector3.Normalize (b - a); + var z = SCNVector3.Normalize (SCNVector3.Cross (x, y)); + y = SCNVector3.Normalize (SCNVector3.Cross (z, x)); + + var rot = new OpenTK.Matrix3 (x.X, y.X, z.X, x.Y, y.Y, z.Y, x.Z, y.Z, z.Z); + this.simulatedTransforms [i].Orientation = new SCNQuaternion (rot.ToQuaternion ()); + } + } + + public void SimulateStep (double time) + { + var minUpdateSeconds = 1f / 120f; + var maxUpdateSeconds = 1f / 30f; + var seconds = DigitExtensions.Clamp ((float) (time - this.time), minUpdateSeconds, maxUpdateSeconds); + + // could run multiple iterations if greater than maxUpdateSeconds, but for now just run one + + this.ApplyForces (); + this.AverageVelocities (); + + // copy the current state + var currentTransforms = new List<SimulatedTransform> (); + currentTransforms.AddRange (this.simulatedTransforms); + + // simulate forward + for (var i = this.BoneInset; i < this.simulatedTransforms.Count - this.BoneInset; i++) { + if (!currentTransforms [i].Dynamic) { + continue; + } + + var p = currentTransforms [i].Position; + var v = currentTransforms [i].Velocity; + p += v * seconds; + + this.simulatedTransforms [i].Position = p; + } + + this.PerformPlaneCollision (currentTransforms, seconds); + this.AlignBones (); + + this.time = time; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/TeamId.cs b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/TeamId.cs index 9e69904a5..426c1a45b 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/TeamId.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Slingshot Behavior/TeamId.cs @@ -1,32 +1,28 @@ - + using UIKit; -namespace SwiftShot.Models -{ - public enum TeamId - { - None = 0, // default +namespace SwiftShot.Models { + public enum TeamId { + None = 0, // default - Blue, + Blue, - Yellow, - } + Yellow, + } - public static class TeamIdExtensions - { - public static UIColor GetColor(this TeamId teamId) - { - switch (teamId) - { - case TeamId.None: - return UIColor.White; - case TeamId.Blue: - return UIColor.FromRGB(45, 128, 208);// srgb - case TeamId.Yellow: - return UIColor.FromRGB(239, 153, 55); - } + public static class TeamIdExtensions { + public static UIColor GetColor (this TeamId teamId) + { + switch (teamId) { + case TeamId.None: + return UIColor.White; + case TeamId.Blue: + return UIColor.FromRGB (45, 128, 208);// srgb + case TeamId.Yellow: + return UIColor.FromRGB (239, 153, 55); + } - throw new System.NotSupportedException(); - } - } -} \ No newline at end of file + throw new System.NotSupportedException (); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AUSamplerNode.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AUSamplerNode.cs index 2683eec56..259e0ee0b 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AUSamplerNode.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AUSamplerNode.cs @@ -1,21 +1,19 @@ - -namespace XamarinShot.Models -{ - using AudioUnit; - using AVFoundation; - public class AUSamplerNode : AVAudioUnitMidiInstrument - { - private static AudioComponentDescription auSamplerDescription = AudioComponentDescription.CreateGeneric(AudioComponentType.MusicDevice, - (int)AudioUnitSubType.Sampler); +namespace XamarinShot.Models { + using AudioUnit; + using AVFoundation; - public AUSamplerNode() : this(auSamplerDescription) - { - auSamplerDescription.ComponentFlags = 0; - auSamplerDescription.ComponentFlagsMask = 0; - auSamplerDescription.ComponentManufacturer = AudioComponentManufacturerType.Apple; - } + public class AUSamplerNode : AVAudioUnitMidiInstrument { + private static AudioComponentDescription auSamplerDescription = AudioComponentDescription.CreateGeneric (AudioComponentType.MusicDevice, + (int) AudioUnitSubType.Sampler); - public AUSamplerNode(AudioComponentDescription auSamplerDescription) : base(auSamplerDescription) { } - } + public AUSamplerNode () : this (auSamplerDescription) + { + auSamplerDescription.ComponentFlags = 0; + auSamplerDescription.ComponentFlagsMask = 0; + auSamplerDescription.ComponentManufacturer = AudioComponentManufacturerType.Apple; + } + + public AUSamplerNode (AudioComponentDescription auSamplerDescription) : base (auSamplerDescription) { } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AudioSampler.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AudioSampler.cs index a9ebcfc4b..530d34ed0 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AudioSampler.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/AudioSampler.cs @@ -1,160 +1,146 @@ - -namespace XamarinShot.Models -{ - using CoreFoundation; - using Foundation; - using SceneKit; - using XamarinShot.Utils; - using System; - - public class AudioSampler : IDisposable - { - // serial queue for loading the sampler presets at background priority - private static DispatchQueue LoadingQueue; - - private readonly NSConditionLock loaded = new NSConditionLock(0); - - private SCNNode node; - - private NSUrl presetUrl; - - private float pitchBend = 0f; - - private float modWheel = 0f; - - static AudioSampler() - { - LoadingQueue = new DispatchQueue("AudioSampler.loading"); - } - - public AudioSampler(string name, SCNNode node, SFXCoordinator sfxCoordinator) - { - this.node = node; - this.AudioNode = new AUSamplerNode(); - this.AudioPlayer = new SCNAudioPlayer(this.AudioNode); - - this.presetUrl = NSBundle.MainBundle.GetUrlForResource($"Sounds/{name}", "aupreset"); - if (this.presetUrl == null) - { - throw new System.IO.FileNotFoundException("Failed to load preset."); - } - - AudioSampler.LoadingQueue.DispatchAsync(() => - { - this.loaded.LockWhenCondition(0); - - this.AudioNode.LoadAudioUnitPreset(this.presetUrl, out NSError error); - - sfxCoordinator.AttachSampler(this, this.node); - - // now this sampler is ready to play. - this.loaded.UnlockWithCondition(1); - }); - } - - public SCNAudioPlayer AudioPlayer { get; private set; } - - public AUSamplerNode AudioNode { get; private set; } - - public float PitchBend - { - get - { - return this.pitchBend; - } - - set - { - this.pitchBend = value; - // MIDI pitch bend is a 14-bit value from 0..16383, with zero pitch bend - // applied at 8192. - var shortValue = (ushort)(8192 + DigitExtensions.Clamp(this.pitchBend, -1, 1) * 8191); - this.AudioNode.SendPitchBend(shortValue, 0); - } - } - - public float ModWheel - { - get - { - return this.modWheel; - } - - set - { - this.modWheel = value; - // MIDI mod wheel is controller #1 and in range 0..127 - var byteValue = (byte)(DigitExtensions.Clamp(this.modWheel, 0, 1) * 127); - this.AudioNode.SendController(1, byteValue, 0); - } - } - - protected void After(Action action, int interval = 1) - { - // DispatchQueue.main.asyncAfter(deadline: .now() + interval, execute: action) - System.Threading.Thread.Sleep(interval); - DispatchQueue.MainQueue.DispatchAsync(action); - } - - public void ReloadPreset() - { - this.AudioNode.LoadAudioUnitPreset(this.presetUrl, out NSError error); - } - - public void Play(byte note, byte velocity, bool autoStop = true) - { - if (this.loaded.Condition == 1) - { - this.AudioNode.StartNote(note, velocity, 0); - - if (autoStop) - { - this.After(() => this.AudioNode.StopNote(note, 0)); - } - } - } - - public void Stop(byte note) - { - this.AudioNode.StopNote(note, 0); - } - - public void StopAllNotes() - { - // Send All Notes Off control message. - this.AudioNode.SendController(123, 0, 0); - } - - #region IDisposable - - private bool isDisposed = false; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!this.isDisposed) - { - if (disposing) - { - this.loaded.Dispose(); - this.presetUrl.Dispose(); - - this.AudioNode.Dispose(); - this.AudioNode = null; - - this.AudioPlayer.Dispose(); - this.AudioPlayer = null; - } - - this.isDisposed = true; - } - } - - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(true); - } - - #endregion - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using CoreFoundation; + using Foundation; + using SceneKit; + using XamarinShot.Utils; + using System; + + public class AudioSampler : IDisposable { + // serial queue for loading the sampler presets at background priority + private static DispatchQueue LoadingQueue; + + private readonly NSConditionLock loaded = new NSConditionLock (0); + + private SCNNode node; + + private NSUrl presetUrl; + + private float pitchBend = 0f; + + private float modWheel = 0f; + + static AudioSampler () + { + LoadingQueue = new DispatchQueue ("AudioSampler.loading"); + } + + public AudioSampler (string name, SCNNode node, SFXCoordinator sfxCoordinator) + { + this.node = node; + this.AudioNode = new AUSamplerNode (); + this.AudioPlayer = new SCNAudioPlayer (this.AudioNode); + + this.presetUrl = NSBundle.MainBundle.GetUrlForResource ($"Sounds/{name}", "aupreset"); + if (this.presetUrl == null) { + throw new System.IO.FileNotFoundException ("Failed to load preset."); + } + + AudioSampler.LoadingQueue.DispatchAsync (() => { + this.loaded.LockWhenCondition (0); + + this.AudioNode.LoadAudioUnitPreset (this.presetUrl, out NSError error); + + sfxCoordinator.AttachSampler (this, this.node); + + // now this sampler is ready to play. + this.loaded.UnlockWithCondition (1); + }); + } + + public SCNAudioPlayer AudioPlayer { get; private set; } + + public AUSamplerNode AudioNode { get; private set; } + + public float PitchBend { + get { + return this.pitchBend; + } + + set { + this.pitchBend = value; + // MIDI pitch bend is a 14-bit value from 0..16383, with zero pitch bend + // applied at 8192. + var shortValue = (ushort) (8192 + DigitExtensions.Clamp (this.pitchBend, -1, 1) * 8191); + this.AudioNode.SendPitchBend (shortValue, 0); + } + } + + public float ModWheel { + get { + return this.modWheel; + } + + set { + this.modWheel = value; + // MIDI mod wheel is controller #1 and in range 0..127 + var byteValue = (byte) (DigitExtensions.Clamp (this.modWheel, 0, 1) * 127); + this.AudioNode.SendController (1, byteValue, 0); + } + } + + protected void After (Action action, int interval = 1) + { + // DispatchQueue.main.asyncAfter(deadline: .now() + interval, execute: action) + System.Threading.Thread.Sleep (interval); + DispatchQueue.MainQueue.DispatchAsync (action); + } + + public void ReloadPreset () + { + this.AudioNode.LoadAudioUnitPreset (this.presetUrl, out NSError error); + } + + public void Play (byte note, byte velocity, bool autoStop = true) + { + if (this.loaded.Condition == 1) { + this.AudioNode.StartNote (note, velocity, 0); + + if (autoStop) { + this.After (() => this.AudioNode.StopNote (note, 0)); + } + } + } + + public void Stop (byte note) + { + this.AudioNode.StopNote (note, 0); + } + + public void StopAllNotes () + { + // Send All Notes Off control message. + this.AudioNode.SendController (123, 0, 0); + } + + #region IDisposable + + private bool isDisposed = false; // To detect redundant calls + + protected virtual void Dispose (bool disposing) + { + if (!this.isDisposed) { + if (disposing) { + this.loaded.Dispose (); + this.presetUrl.Dispose (); + + this.AudioNode.Dispose (); + this.AudioNode = null; + + this.AudioPlayer.Dispose (); + this.AudioPlayer = null; + } + + this.isDisposed = true; + } + } + + public void Dispose () + { + this.Dispose (true); + GC.SuppressFinalize (true); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/ButtonBeep.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/ButtonBeep.cs index a43b5c25c..cd6907ab6 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/ButtonBeep.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/ButtonBeep.cs @@ -1,67 +1,58 @@ - -namespace XamarinShot.Models -{ - using AVFoundation; - using Foundation; - using System.Collections.Generic; - /// <summary> - /// Simple wrapper for UI audio effects. - /// </summary> - public class ButtonBeep - { - private static Dictionary<string, AVAudioPlayer> players;// = new Dictionary<string, AVAudioPlayer>(); - - private readonly float volume; - - static ButtonBeep() - { - players = new Dictionary<string, AVAudioPlayer>(); - } - - public ButtonBeep(float volume) - { - this.volume = volume; - } - - public AVAudioPlayer Player { get; set; } - - public static ButtonBeep Create(string name, float volume) - { - var result = new ButtonBeep(volume); - if (ButtonBeep.players.TryGetValue(name, out AVAudioPlayer player)) - { - result.Player = player; - } - else - { - var splitted = name.Split(new char[] { '.' }, System.StringSplitOptions.RemoveEmptyEntries); - var url = NSBundle.MainBundle.GetUrlForResource($"Sounds/{splitted[0]}", splitted[1]); - if(url == null) - { - return null; - } - - player = AVAudioPlayer.FromUrl(url, out NSError error); - if (player != null) - { - player.PrepareToPlay(); - result.Player = player; - ButtonBeep.players[name] = player; - } - else - { - return null; - } - } - - return result; - } - - public void Play() - { - this.Player.Volume = this.volume * SFXCoordinator.EffectsGain(); - this.Player.Play(); - } - } -} \ No newline at end of file +namespace XamarinShot.Models { + using AVFoundation; + using Foundation; + using System.Collections.Generic; + + /// <summary> + /// Simple wrapper for UI audio effects. + /// </summary> + public class ButtonBeep { + private static Dictionary<string, AVAudioPlayer> players;// = new Dictionary<string, AVAudioPlayer>(); + + private readonly float volume; + + static ButtonBeep () + { + players = new Dictionary<string, AVAudioPlayer> (); + } + + public ButtonBeep (float volume) + { + this.volume = volume; + } + + public AVAudioPlayer Player { get; set; } + + public static ButtonBeep Create (string name, float volume) + { + var result = new ButtonBeep (volume); + if (ButtonBeep.players.TryGetValue (name, out AVAudioPlayer player)) { + result.Player = player; + } else { + var splitted = name.Split (new char [] { '.' }, System.StringSplitOptions.RemoveEmptyEntries); + var url = NSBundle.MainBundle.GetUrlForResource ($"Sounds/{splitted [0]}", splitted [1]); + if (url == null) { + return null; + } + + player = AVAudioPlayer.FromUrl (url, out NSError error); + if (player != null) { + player.PrepareToPlay (); + result.Player = player; + ButtonBeep.players [name] = player; + } else { + return null; + } + } + + return result; + } + + public void Play () + { + this.Player.Volume = this.volume * SFXCoordinator.EffectsGain (); + this.Player.Play (); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CatapultAudioSampler.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CatapultAudioSampler.cs index 92dde3568..086a42dca 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CatapultAudioSampler.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CatapultAudioSampler.cs @@ -1,116 +1,105 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Utils; - - public class CatapultAudioSampler : AudioSampler - { - private const float StretchMinimumExpression = 75f; // in Midi controller value range 0..127 - private const float StretchMaximumExpression = 127f; // in Midi controller value range 0..127 - private const float StretchMaximumRate = 2.5f; - - private float stretchDistance = 0f; - private float stretchRate = 0f; - - public CatapultAudioSampler(SCNNode node, SFXCoordinator sfxCoordinator) : base("catapult", node, sfxCoordinator) { } - - public float StretchDistance - { - get - { - return this.stretchDistance; - } - - set - { - this.stretchDistance = value; - if (!float.IsNaN(this.stretchDistance)) - { - // apply stretch distance as pitch bend from 0...1, using pitch variation defined - // in the AUSampler preset. - this.PitchBend = DigitExtensions.Clamp(stretchDistance, 0, 1); - } - } - } - - public float StretchRate - { - get - { - return this.stretchRate; - } - - set - { - this.stretchRate = value; - if (!float.IsNaN(this.stretchRate)) - { - var normalizedStretch = this.stretchRate / StretchMaximumRate; - var controllerValue = (byte)(DigitExtensions.Clamp(StretchMinimumExpression + normalizedStretch * (StretchMaximumExpression - StretchMinimumExpression), 0, 127)); - // midi expression, controller change# 11 - this.AudioNode.SendController(11, controllerValue, 0); - } - } - } - - public void StartStretch() - { - this.AudioNode.SendController(11, 127, 0); - this.Play(Note.Stretch, 105, false); - this.PitchBend = 0; - } - - public void StopStretch() - { - this.Stop(note: Note.Stretch); - this.PitchBend = 0; - } - - public void PlayLaunch(GameVelocity velocity) - { - // For the launch, we will play two sounds: a launch twang and a swish - var length = velocity.Vector.Length; - length = float.IsNaN(length) ? 0 : DigitExtensions.Clamp(length, 0, 1); - - var launchVel = (byte)(length * 30 + 80); - this.Play(Note.Launch, launchVel); - - var swishVel = (byte)(length * 63 + 64); - this.After(() => this.Play(Note.LaunchSwish, swishVel), 1); - } - - public void PlayHighlightOn() - { - this.Play(Note.HighlightOn, 90); - } - - public void PlayHighlightOff() - { - this.Play(Note.HighlightOff, 90); - } - - public void PlayGrabBall() - { - // reset pitch bend to 0 on grab - this.PitchBend = 0; - this.Play(Note.GrabBall, 110); - } - - public void PlayBreak() - { - this.Play(Note.Broken, 85); - } - - static class Note - { - public static byte Stretch { get; set; } = 24; // Midi note for C1 - public static byte Launch { get; set; } = 26; // Midi note for D1 - public static byte LaunchSwish { get; set; } = 28; // Midi note for E1 - public static byte GrabBall { get; set; } = 31; // Midi note for G1 - public static byte HighlightOn { get; set; } = 38;// Midi note for D2 - public static byte HighlightOff { get; set; } = 41;// Midi note for F2 - public static byte Broken { get; set; } = 33; // Midi note for A1 - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Utils; + + public class CatapultAudioSampler : AudioSampler { + private const float StretchMinimumExpression = 75f; // in Midi controller value range 0..127 + private const float StretchMaximumExpression = 127f; // in Midi controller value range 0..127 + private const float StretchMaximumRate = 2.5f; + + private float stretchDistance = 0f; + private float stretchRate = 0f; + + public CatapultAudioSampler (SCNNode node, SFXCoordinator sfxCoordinator) : base ("catapult", node, sfxCoordinator) { } + + public float StretchDistance { + get { + return this.stretchDistance; + } + + set { + this.stretchDistance = value; + if (!float.IsNaN (this.stretchDistance)) { + // apply stretch distance as pitch bend from 0...1, using pitch variation defined + // in the AUSampler preset. + this.PitchBend = DigitExtensions.Clamp (stretchDistance, 0, 1); + } + } + } + + public float StretchRate { + get { + return this.stretchRate; + } + + set { + this.stretchRate = value; + if (!float.IsNaN (this.stretchRate)) { + var normalizedStretch = this.stretchRate / StretchMaximumRate; + var controllerValue = (byte) (DigitExtensions.Clamp (StretchMinimumExpression + normalizedStretch * (StretchMaximumExpression - StretchMinimumExpression), 0, 127)); + // midi expression, controller change# 11 + this.AudioNode.SendController (11, controllerValue, 0); + } + } + } + + public void StartStretch () + { + this.AudioNode.SendController (11, 127, 0); + this.Play (Note.Stretch, 105, false); + this.PitchBend = 0; + } + + public void StopStretch () + { + this.Stop (note: Note.Stretch); + this.PitchBend = 0; + } + + public void PlayLaunch (GameVelocity velocity) + { + // For the launch, we will play two sounds: a launch twang and a swish + var length = velocity.Vector.Length; + length = float.IsNaN (length) ? 0 : DigitExtensions.Clamp (length, 0, 1); + + var launchVel = (byte) (length * 30 + 80); + this.Play (Note.Launch, launchVel); + + var swishVel = (byte) (length * 63 + 64); + this.After (() => this.Play (Note.LaunchSwish, swishVel), 1); + } + + public void PlayHighlightOn () + { + this.Play (Note.HighlightOn, 90); + } + + public void PlayHighlightOff () + { + this.Play (Note.HighlightOff, 90); + } + + public void PlayGrabBall () + { + // reset pitch bend to 0 on grab + this.PitchBend = 0; + this.Play (Note.GrabBall, 110); + } + + public void PlayBreak () + { + this.Play (Note.Broken, 85); + } + + static class Note { + public static byte Stretch { get; set; } = 24; // Midi note for C1 + public static byte Launch { get; set; } = 26; // Midi note for D1 + public static byte LaunchSwish { get; set; } = 28; // Midi note for E1 + public static byte GrabBall { get; set; } = 31; // Midi note for G1 + public static byte HighlightOn { get; set; } = 38;// Midi note for D2 + public static byte HighlightOff { get; set; } = 41;// Midi note for F2 + public static byte Broken { get; set; } = 33; // Midi note for A1 + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionAudioSampler.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionAudioSampler.cs index 91be896c6..d4ec4f48d 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionAudioSampler.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionAudioSampler.cs @@ -1,135 +1,121 @@ - -namespace XamarinShot.Models -{ - using SceneKit; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - - public class CollisionAudioSampler : AudioSampler - { - private readonly Config configuration; - - // Each time a note is played, choose a variant of +/- a bit of the midi note. - // The sampler cannot play two of the same note at the same time (which makes - // sense for music instruments like pianos, but we may want to hear two ball - // bounce sounds, so they need to be different midi notes.) - private short[] variant = new short[] { -1, 0, 1, 2 }; - - public CollisionAudioSampler(SCNNode node, Config config, SFXCoordinator sfxCoordinator) : base(config.PresetName, node, sfxCoordinator) - { - this.configuration = config; - } - - public CollisionEvent CreateCollisionEvent(float impulse, bool withBall, bool withTable) - { - CollisionEvent result = null; - if (float.IsNaN(impulse) || impulse < this.configuration.MinimumImpulse) - { - - } - else - { - // Set mod wheel according to the impulse value. This will vary the attack of the sound - // and make them less repetitive and more dynamic. The sampler patch is set up to play the full - // sound with modWheel off, and shortened attack with increasing modwheel value. So we invert the - // normalized range. - // - // Also, we want to alter the velocity so that higher impulse means a louder note. - - byte note; - if (withTable) - { - note = Note.CollisionWithTable; - } - else if (withBall) - { - note = Note.CollisionWithBall; - } - else - { - note = Note.CollisionWithBlock; - } - - note = (byte)(note + this.variant[0]); - - // move this variant randomly to another position - var otherIndex = new Random().Next(variant.Length - 1);// Int(arc4random_uniform(UInt32(variant.count - 1))) - - //variant.swapAt(0, 1 + otherIndex) - var temp = variant[0]; - variant[0] = variant[1 + otherIndex]; - variant[1 + otherIndex] = temp; - - var normalizedImpulse = DigitExtensions.Clamp((impulse - this.configuration.MinimumImpulse) / (this.configuration.MaximumImpulse - this.configuration.MinimumImpulse), - 0f, - 1f); - - // Once the impulse is normalized to the range 0...1, doing a sqrt - // on it causes lower values to be higher. This curve was chosen because - // it sounded better aesthetically. - normalizedImpulse = (float)Math.Sqrt(normalizedImpulse); - - var rangedImpulse = this.configuration.VelocityMinimum + (this.configuration.VelocityMaximum - this.configuration.VelocityMinimum) * normalizedImpulse; - var velocity = (byte)(DigitExtensions.Clamp(rangedImpulse, 0, 127)); - - result = new CollisionEvent - { - Note = note, - Velocity = velocity, - ModWheel = 1f - normalizedImpulse, - }; - } - - return result; - } - - public void Play(CollisionEvent collisionEvent) - { - this.ModWheel = collisionEvent.ModWheel; - this.Play(collisionEvent.Note, collisionEvent.Velocity); - } - - /* helpers */ - - static class Note - { - public static byte CollisionWithBall { get; } = 60; // Midi note for C4 - - public static byte CollisionWithBlock { get; } = 52; // Midi note for E3 - - public static byte CollisionWithTable { get; } = 55; // Midi note for G3 - } - - public class Config - { - public float MinimumImpulse { get; set; } - - public float MaximumImpulse { get; set; } - - public float VelocityMinimum { get; set; } - - public float VelocityMaximum { get; set; } - - public string PresetName { get; set; } - - public static Config Create(Dictionary<string, object> properties) - { - var minimumImpulse = properties["minimumImpulse"]; - var maximumImpulse = properties["maximumImpulse"]; - var velocityMinimum = properties["velocityMinimum"]; - var velocityMaximum = properties["velocityMaximum"]; - var presetName = properties["presetName"]; - - return new Config - { - MinimumImpulse = float.Parse(minimumImpulse.ToString()), - MaximumImpulse = float.Parse(maximumImpulse.ToString()), - VelocityMinimum = float.Parse(velocityMinimum.ToString()), - VelocityMaximum = float.Parse(velocityMaximum.ToString()), - PresetName = presetName.ToString() - }; - } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using SceneKit; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + + public class CollisionAudioSampler : AudioSampler { + private readonly Config configuration; + + // Each time a note is played, choose a variant of +/- a bit of the midi note. + // The sampler cannot play two of the same note at the same time (which makes + // sense for music instruments like pianos, but we may want to hear two ball + // bounce sounds, so they need to be different midi notes.) + private short [] variant = new short [] { -1, 0, 1, 2 }; + + public CollisionAudioSampler (SCNNode node, Config config, SFXCoordinator sfxCoordinator) : base (config.PresetName, node, sfxCoordinator) + { + this.configuration = config; + } + + public CollisionEvent CreateCollisionEvent (float impulse, bool withBall, bool withTable) + { + CollisionEvent result = null; + if (float.IsNaN (impulse) || impulse < this.configuration.MinimumImpulse) { + + } else { + // Set mod wheel according to the impulse value. This will vary the attack of the sound + // and make them less repetitive and more dynamic. The sampler patch is set up to play the full + // sound with modWheel off, and shortened attack with increasing modwheel value. So we invert the + // normalized range. + // + // Also, we want to alter the velocity so that higher impulse means a louder note. + + byte note; + if (withTable) { + note = Note.CollisionWithTable; + } else if (withBall) { + note = Note.CollisionWithBall; + } else { + note = Note.CollisionWithBlock; + } + + note = (byte) (note + this.variant [0]); + + // move this variant randomly to another position + var otherIndex = new Random ().Next (variant.Length - 1);// Int(arc4random_uniform(UInt32(variant.count - 1))) + + //variant.swapAt(0, 1 + otherIndex) + var temp = variant [0]; + variant [0] = variant [1 + otherIndex]; + variant [1 + otherIndex] = temp; + + var normalizedImpulse = DigitExtensions.Clamp ((impulse - this.configuration.MinimumImpulse) / (this.configuration.MaximumImpulse - this.configuration.MinimumImpulse), + 0f, + 1f); + + // Once the impulse is normalized to the range 0...1, doing a sqrt + // on it causes lower values to be higher. This curve was chosen because + // it sounded better aesthetically. + normalizedImpulse = (float) Math.Sqrt (normalizedImpulse); + + var rangedImpulse = this.configuration.VelocityMinimum + (this.configuration.VelocityMaximum - this.configuration.VelocityMinimum) * normalizedImpulse; + var velocity = (byte) (DigitExtensions.Clamp (rangedImpulse, 0, 127)); + + result = new CollisionEvent { + Note = note, + Velocity = velocity, + ModWheel = 1f - normalizedImpulse, + }; + } + + return result; + } + + public void Play (CollisionEvent collisionEvent) + { + this.ModWheel = collisionEvent.ModWheel; + this.Play (collisionEvent.Note, collisionEvent.Velocity); + } + + /* helpers */ + + static class Note { + public static byte CollisionWithBall { get; } = 60; // Midi note for C4 + + public static byte CollisionWithBlock { get; } = 52; // Midi note for E3 + + public static byte CollisionWithTable { get; } = 55; // Midi note for G3 + } + + public class Config { + public float MinimumImpulse { get; set; } + + public float MaximumImpulse { get; set; } + + public float VelocityMinimum { get; set; } + + public float VelocityMaximum { get; set; } + + public string PresetName { get; set; } + + public static Config Create (Dictionary<string, object> properties) + { + var minimumImpulse = properties ["minimumImpulse"]; + var maximumImpulse = properties ["maximumImpulse"]; + var velocityMinimum = properties ["velocityMinimum"]; + var velocityMaximum = properties ["velocityMaximum"]; + var presetName = properties ["presetName"]; + + return new Config { + MinimumImpulse = float.Parse (minimumImpulse.ToString ()), + MaximumImpulse = float.Parse (maximumImpulse.ToString ()), + VelocityMinimum = float.Parse (velocityMinimum.ToString ()), + VelocityMaximum = float.Parse (velocityMaximum.ToString ()), + PresetName = presetName.ToString () + }; + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionEvent.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionEvent.cs index 4f90c2358..8fbd5bf49 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionEvent.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/CollisionEvent.cs @@ -1,16 +1,14 @@ - -namespace XamarinShot.Models -{ - public class CollisionEvent - { - public byte Note { get; set; } - public byte Velocity { get; set; } +namespace XamarinShot.Models { + public class CollisionEvent { + public byte Note { get; set; } - /// <summary> - /// only requires 7-bit accuracy in range 0..1 - /// </summary> - /// <value>The mod wheel.</value> - public float ModWheel { get; set; } - } + public byte Velocity { get; set; } + + /// <summary> + /// only requires 7-bit accuracy in range 0..1 + /// </summary> + /// <value>The mod wheel.</value> + public float ModWheel { get; set; } + } } diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/HapticsGenerator.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/HapticsGenerator.cs index 362315ee1..c517383ac 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/HapticsGenerator.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/HapticsGenerator.cs @@ -1,67 +1,60 @@ - -namespace XamarinShot.Models -{ - using CoreFoundation; - using System; - using UIKit; - public class HapticsGenerator : IDisposable - { - private readonly UIImpactFeedbackGenerator impact = new UIImpactFeedbackGenerator(UIImpactFeedbackStyle.Medium); - - private readonly UISelectionFeedbackGenerator selection = new UISelectionFeedbackGenerator(); - - private readonly UINotificationFeedbackGenerator notification = new UINotificationFeedbackGenerator(); - - public void GenerateImpactFeedback() - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.impact.ImpactOccurred(); - }); - } - - public void GenerateSelectionFeedback() - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.selection.SelectionChanged(); - }); - } - - public void GenerateNotificationFeedback(UINotificationFeedbackType notificationType) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.notification.NotificationOccurred(notificationType); - }); - } - - #region IDisposable - - private bool isDisposed = false; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!this.isDisposed) - { - if (disposing) - { - this.impact.Dispose(); - this.selection.Dispose(); - this.notification.Dispose(); - } - - this.isDisposed = true; - } - } - - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(true); - } - - #endregion - } -} \ No newline at end of file +namespace XamarinShot.Models { + using CoreFoundation; + using System; + using UIKit; + + public class HapticsGenerator : IDisposable { + private readonly UIImpactFeedbackGenerator impact = new UIImpactFeedbackGenerator (UIImpactFeedbackStyle.Medium); + + private readonly UISelectionFeedbackGenerator selection = new UISelectionFeedbackGenerator (); + + private readonly UINotificationFeedbackGenerator notification = new UINotificationFeedbackGenerator (); + + public void GenerateImpactFeedback () + { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.impact.ImpactOccurred (); + }); + } + + public void GenerateSelectionFeedback () + { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.selection.SelectionChanged (); + }); + } + + public void GenerateNotificationFeedback (UINotificationFeedbackType notificationType) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.notification.NotificationOccurred (notificationType); + }); + } + + #region IDisposable + + private bool isDisposed = false; // To detect redundant calls + + protected virtual void Dispose (bool disposing) + { + if (!this.isDisposed) { + if (disposing) { + this.impact.Dispose (); + this.selection.Dispose (); + this.notification.Dispose (); + } + + this.isDisposed = true; + } + } + + public void Dispose () + { + this.Dispose (true); + GC.SuppressFinalize (true); + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/MusicCoordinator.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/MusicCoordinator.cs index ece89436a..7e2d3217b 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/MusicCoordinator.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/MusicCoordinator.cs @@ -1,229 +1,206 @@ - -namespace XamarinShot.Models -{ - using AVFoundation; - using CoreFoundation; - using Foundation; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using System.Linq; - - public class MusicCoordinator : NSObject - { - private readonly Dictionary<string, MusicPlayer> musicPlayers = new Dictionary<string, MusicPlayer>(); - - private readonly Dictionary<string, MusicConfig> musicConfigurations; - - private const double DefaultFadeOut = 0.2d; - - private float musicGain = 1f; - - public MusicCoordinator() : base() - { - this.UpdateMusicVolume(); - - var url = NSBundle.MainBundle.GetUrlForResource("Sounds/music", "json"); - if (url == null) - { - throw new Exception("Failed to load music config from Sounds/music.json"); - } - - // parse - var json = NSString.FromData(NSData.FromUrl(url), NSStringEncoding.UTF8).ToString(); - this.musicConfigurations = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, MusicConfig>>(json); - - NSNotificationCenter.DefaultCenter.AddObserver(NSUserDefaults.DidChangeNotification, this.HandleDefaultsDidChange); - } - - public MusicPlayer CurrentMusicPlayer { get; private set; } - - private void HandleDefaultsDidChange(NSNotification notification) - { - this.UpdateMusicVolume(); - } - - private void UpdateMusicVolume() - { - var volume = UserDefaults.MusicVolume; - // Map the slider value from 0...1 to a more natural curve: - this.musicGain = volume * volume; - - foreach(var (_, player) in this.musicPlayers.Where(player => player.Value.State == MusicState.Playing)) - { - var audioVolume = DigitExtensions.Clamp(this.musicGain * (float)Math.Pow(10f, player.Config.VolumeDB / 20f), 0f, 1f); - player.AudioPlayer.SetVolume(audioVolume, 0.1d); - } - } - - /// <summary> - /// Get the current play position for the currently playing music - /// </summary> - /// <returns>Time in seconds, or -1 if nothing is playing.</returns> - public double CurrentMusicTime() - { - if (this.CurrentMusicPlayer != null) - { - return this.CurrentMusicPlayer.AudioPlayer.CurrentTime; - } - else - { - return -1d; - } - } - - public MusicPlayer MusicPlayer(string name) - { - if (this.musicPlayers.TryGetValue(name, out MusicPlayer player)) - { - return player; - } - - if (!this.musicConfigurations.TryGetValue(name, out MusicConfig config)) - { - throw new Exception($"Missing music config for music event named '{name}'"); - } - - player = new MusicPlayer(name, config); - this.musicPlayers[name] = player; - return player; - } - - public MusicPlayer PlayMusic(string name, double fadeIn = 0d) - { - return this.PlayMusic(name, 0, fadeIn); - } - - public MusicPlayer PlayMusic(string name, double startTime, double fadeIn = 0d) - { - var player = this.MusicPlayer(name); - var audioPlayer = player.AudioPlayer; - - if (this.CurrentMusicPlayer != null) - { - this.StopMusic(this.CurrentMusicPlayer); - } - - switch (player.State) - { - case MusicState.Playing: - // Nothing to do - return player; - - case MusicState.Stopped: - // Configure the audioPlayer, starting with volume at 0 and then fade in. - audioPlayer.Volume = 0; - audioPlayer.CurrentTime = 0; - if (player.Config.Loops) - { - audioPlayer.NumberOfLoops = -1; - } - else - { - audioPlayer.NumberOfLoops = 0; - } - - audioPlayer.CurrentTime = startTime; - audioPlayer.Play(); - break; - - case MusicState.Stopping: - // Leave it playing. Update the volume and play state below. - break; - } - - var volume = DigitExtensions.Clamp(this.musicGain * (float)Math.Pow(10f, player.Config.VolumeDB / 20f), 0f, 1f); - audioPlayer.SetVolume(volume, fadeIn); - - player.State = MusicState.Playing; - this.CurrentMusicPlayer = player; - - return player; - } - - public void StopMusic(string name, double fadeOut = MusicCoordinator.DefaultFadeOut) - { - var player = this.MusicPlayer(name); - this.StopMusic(player, fadeOut); - } - - public void StopCurrentMusic(double fadeOut = MusicCoordinator.DefaultFadeOut) - { - if (this.CurrentMusicPlayer != null) - { - this.StopMusic(this.CurrentMusicPlayer, fadeOut); - } - } - - public void StopMusic(MusicPlayer player, double fadeOut = MusicCoordinator.DefaultFadeOut) - { - if (player.State == MusicState.Playing) - { - player.State = MusicState.Stopping; - var audioPlayer = player.AudioPlayer; - audioPlayer.SetVolume(0f, fadeOut); - // TODO; - //DispatchQueue.MainQueue.DispatchAsync(deadline: .now() + fadeOut) { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (player.State == MusicState.Stopping) - { - audioPlayer.Stop(); - player.State = MusicState.Stopped; - } - }); - } - } - - /* helpers */ - - public enum MusicState - { - Stopped, - Playing, - Stopping, // transition from play to stop, fading out. - } - - public class MusicConfig - { - public string FileName { get; set; } - - public float VolumeDB { get; set; } - - public bool Loops { get; set; } - } - } - - public class MusicPlayer - { - public MusicPlayer(string name, MusicCoordinator.MusicConfig config) - { - this.Name = name; - this.Config = config; - this.State = MusicCoordinator.MusicState.Stopped; - - var splittedPath = config.FileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); - var url = NSBundle.MainBundle.GetUrlForResource(splittedPath[0], splittedPath[1]); - if (url == null) - { - throw new Exception($"Failed to load sound for: {name} expected at: {config.FileName}"); - } - - this.AudioPlayer = AVAudioPlayer.FromUrl(url, out NSError error); - if (error != null) - { - throw new Exception($"Failed to load sound for: {name} expected at: {config.FileName}"); - } - } - - public double Duration => this.AudioPlayer.Duration; - - public string Name { get; set; } - - public MusicCoordinator.MusicState State { get; set; } - - public AVAudioPlayer AudioPlayer { get; private set; } - - public MusicCoordinator.MusicConfig Config { get; private set; } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using AVFoundation; + using CoreFoundation; + using Foundation; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using System.Linq; + + public class MusicCoordinator : NSObject { + private readonly Dictionary<string, MusicPlayer> musicPlayers = new Dictionary<string, MusicPlayer> (); + + private readonly Dictionary<string, MusicConfig> musicConfigurations; + + private const double DefaultFadeOut = 0.2d; + + private float musicGain = 1f; + + public MusicCoordinator () : base () + { + this.UpdateMusicVolume (); + + var url = NSBundle.MainBundle.GetUrlForResource ("Sounds/music", "json"); + if (url == null) { + throw new Exception ("Failed to load music config from Sounds/music.json"); + } + + // parse + var json = NSString.FromData (NSData.FromUrl (url), NSStringEncoding.UTF8).ToString (); + this.musicConfigurations = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, MusicConfig>> (json); + + NSNotificationCenter.DefaultCenter.AddObserver (NSUserDefaults.DidChangeNotification, this.HandleDefaultsDidChange); + } + + public MusicPlayer CurrentMusicPlayer { get; private set; } + + private void HandleDefaultsDidChange (NSNotification notification) + { + this.UpdateMusicVolume (); + } + + private void UpdateMusicVolume () + { + var volume = UserDefaults.MusicVolume; + // Map the slider value from 0...1 to a more natural curve: + this.musicGain = volume * volume; + + foreach (var (_, player) in this.musicPlayers.Where (player => player.Value.State == MusicState.Playing)) { + var audioVolume = DigitExtensions.Clamp (this.musicGain * (float) Math.Pow (10f, player.Config.VolumeDB / 20f), 0f, 1f); + player.AudioPlayer.SetVolume (audioVolume, 0.1d); + } + } + + /// <summary> + /// Get the current play position for the currently playing music + /// </summary> + /// <returns>Time in seconds, or -1 if nothing is playing.</returns> + public double CurrentMusicTime () + { + if (this.CurrentMusicPlayer != null) { + return this.CurrentMusicPlayer.AudioPlayer.CurrentTime; + } else { + return -1d; + } + } + + public MusicPlayer MusicPlayer (string name) + { + if (this.musicPlayers.TryGetValue (name, out MusicPlayer player)) { + return player; + } + + if (!this.musicConfigurations.TryGetValue (name, out MusicConfig config)) { + throw new Exception ($"Missing music config for music event named '{name}'"); + } + + player = new MusicPlayer (name, config); + this.musicPlayers [name] = player; + return player; + } + + public MusicPlayer PlayMusic (string name, double fadeIn = 0d) + { + return this.PlayMusic (name, 0, fadeIn); + } + + public MusicPlayer PlayMusic (string name, double startTime, double fadeIn = 0d) + { + var player = this.MusicPlayer (name); + var audioPlayer = player.AudioPlayer; + + if (this.CurrentMusicPlayer != null) { + this.StopMusic (this.CurrentMusicPlayer); + } + + switch (player.State) { + case MusicState.Playing: + // Nothing to do + return player; + + case MusicState.Stopped: + // Configure the audioPlayer, starting with volume at 0 and then fade in. + audioPlayer.Volume = 0; + audioPlayer.CurrentTime = 0; + if (player.Config.Loops) { + audioPlayer.NumberOfLoops = -1; + } else { + audioPlayer.NumberOfLoops = 0; + } + + audioPlayer.CurrentTime = startTime; + audioPlayer.Play (); + break; + + case MusicState.Stopping: + // Leave it playing. Update the volume and play state below. + break; + } + + var volume = DigitExtensions.Clamp (this.musicGain * (float) Math.Pow (10f, player.Config.VolumeDB / 20f), 0f, 1f); + audioPlayer.SetVolume (volume, fadeIn); + + player.State = MusicState.Playing; + this.CurrentMusicPlayer = player; + + return player; + } + + public void StopMusic (string name, double fadeOut = MusicCoordinator.DefaultFadeOut) + { + var player = this.MusicPlayer (name); + this.StopMusic (player, fadeOut); + } + + public void StopCurrentMusic (double fadeOut = MusicCoordinator.DefaultFadeOut) + { + if (this.CurrentMusicPlayer != null) { + this.StopMusic (this.CurrentMusicPlayer, fadeOut); + } + } + + public void StopMusic (MusicPlayer player, double fadeOut = MusicCoordinator.DefaultFadeOut) + { + if (player.State == MusicState.Playing) { + player.State = MusicState.Stopping; + var audioPlayer = player.AudioPlayer; + audioPlayer.SetVolume (0f, fadeOut); + // TODO; + //DispatchQueue.MainQueue.DispatchAsync(deadline: .now() + fadeOut) { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (player.State == MusicState.Stopping) { + audioPlayer.Stop (); + player.State = MusicState.Stopped; + } + }); + } + } + + /* helpers */ + + public enum MusicState { + Stopped, + Playing, + Stopping, // transition from play to stop, fading out. + } + + public class MusicConfig { + public string FileName { get; set; } + + public float VolumeDB { get; set; } + + public bool Loops { get; set; } + } + } + + public class MusicPlayer { + public MusicPlayer (string name, MusicCoordinator.MusicConfig config) + { + this.Name = name; + this.Config = config; + this.State = MusicCoordinator.MusicState.Stopped; + + var splittedPath = config.FileName.Split (new char [] { '.' }, StringSplitOptions.RemoveEmptyEntries); + var url = NSBundle.MainBundle.GetUrlForResource (splittedPath [0], splittedPath [1]); + if (url == null) { + throw new Exception ($"Failed to load sound for: {name} expected at: {config.FileName}"); + } + + this.AudioPlayer = AVAudioPlayer.FromUrl (url, out NSError error); + if (error != null) { + throw new Exception ($"Failed to load sound for: {name} expected at: {config.FileName}"); + } + } + + public double Duration => this.AudioPlayer.Duration; + + public string Name { get; set; } + + public MusicCoordinator.MusicState State { get; set; } + + public AVAudioPlayer AudioPlayer { get; private set; } + + public MusicCoordinator.MusicConfig Config { get; private set; } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/SFXCoordinator.cs b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/SFXCoordinator.cs index 91088e728..7892769bf 100644 --- a/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/SFXCoordinator.cs +++ b/ios12/XamarinShot/XamarinShot/Core/Sounds and Haptics/SFXCoordinator.cs @@ -1,396 +1,341 @@ - -namespace XamarinShot.Models -{ - using AVFoundation; - using CoreFoundation; - using Foundation; - using SceneKit; - using XamarinShot.Models.GameplayState; - using XamarinShot.Utils; - using System; - using System.Collections.Generic; - using UIKit; - - public class SFXCoordinator : NSObject - { - private readonly string[] preloadAudioFiles = - { - "vortex_04", - "catapult_highlight_on_02", - "catapult_highlight_off_02" - }; - - private readonly Dictionary<string, AVAudioPlayer> audioPlayers = new Dictionary<string, AVAudioPlayer>(); - private readonly DispatchQueue playerQueue = new DispatchQueue("SFXCoordinator"); - private readonly DispatchQueue loadQueue = new DispatchQueue("SFXCoordinator.loading"); - - private readonly List<AudioSampler> audioSamplers = new List<AudioSampler>(); - - private readonly HapticsGenerator hapticsGenerator = new HapticsGenerator(); - private bool isStretchPlaying; - private DateTime? timeSinceLastHaptic; - private float? prevStretchDistance; - private Catapult highlightedCatapult; - private bool firstVortexCatapultBreak = true; - - private float effectsGain = 1f; - - public SFXCoordinator(AVAudioEnvironmentNode audioEnvironment) : base() - { - this.AudioEnvironment = audioEnvironment; - - this.loadQueue.DispatchAsync(() => - { - foreach (var file in preloadAudioFiles) - { - this.PrepareAudioFile(file); - } - }); - - // Because the coordinate space is scaled, let's apply some adjustments to the - // distance attenuation parameters to make the distance rolloff sound more - // realistic. - - this.AudioEnvironment.DistanceAttenuationParameters.ReferenceDistance = 5f; - this.AudioEnvironment.DistanceAttenuationParameters.MaximumDistance = 40f; - this.AudioEnvironment.DistanceAttenuationParameters.RolloffFactor = 1f; - this.AudioEnvironment.DistanceAttenuationParameters.DistanceAttenuationModel = AVAudioEnvironmentDistanceAttenuationModel.Inverse; - - this.UpdateEffectsVolume(); - - // When the route changes, we need to reload our audio samplers because sometimes those - // audio units are being reset. - NSNotificationCenter.DefaultCenter.AddObserver(AVAudioSession.RouteChangeNotification, this.HandleRouteChange); - - // Subscribe to notifications of user defaults changing so that we can apply them to - // sound effects. - NSNotificationCenter.DefaultCenter.AddObserver(NSUserDefaults.DidChangeNotification, this.HandleDefaultsDidChange); - - NSNotificationCenter.DefaultCenter.AddObserver(UIApplication.DidEnterBackgroundNotification, this.HandleAppDidEnterBackground); - } - - public AVAudioEnvironmentNode AudioEnvironment { get; private set; } - - public SCNMatrix4 RenderToSimulationTransform { get; set; } = SCNMatrix4.Identity; - - private void HandleRouteChange(NSNotification notification) - { - this.loadQueue.DispatchAsync(() => - { - foreach (var sampler in this.audioSamplers) - { - sampler.ReloadPreset(); - } - }); - } - - private void HandleDefaultsDidChange(NSNotification notification) - { - this.UpdateEffectsVolume(); - } - - private void HandleAppDidEnterBackground(NSNotification notification) - { - foreach (var sampler in this.audioSamplers) - { - sampler.StopAllNotes(); - } - } - - public static float EffectsGain() - { - var effectsVolume = UserDefaults.EffectsVolume; - // Map the slider value from 0...1 to a more natural curve: - return effectsVolume * effectsVolume; - } - - private void UpdateEffectsVolume() - { - this.effectsGain = SFXCoordinator.EffectsGain(); - this.AudioEnvironment.OutputVolume = effectsGain; - } - - public void SetupGameAudioComponent(GameAudioComponent component) - { - component.SfxCoordinator = this; - } - - public void AttachSampler(AudioSampler audioSampler, SCNNode node) - { - // Add the audio Player to the scenekit node so that it gets correct positional - // adjustments - node.AddAudioPlayer(audioSampler.AudioPlayer); - - // NOTE: AVAudioNodes that are not AVAudioPlayerNodes are not - // automatically added to an AVAudioEngine by SceneKit. So we add - // this audio node to the SCNNode so that it can get position updates - // but we connect it manually to the AVAudioEnvironmentNode that we - // get passed to us. This comes from ARSCNView in GameSceneViewController. - if (this.AudioEnvironment.Engine != null) - { - var engine = this.AudioEnvironment.Engine; - - // attach the node - var audioNode = audioSampler.AudioNode; - engine.AttachNode(audioNode); - - // connect - var engineFormat = engine.OutputNode.GetBusInputFormat(0); - var format = new AVAudioFormat(engineFormat.SampleRate, 1); - engine.Connect(audioNode, AudioEnvironment, format); - - // addd to the local collection - this.audioSamplers.Add(audioSampler); - } - } - - public void RemoveAllAudioSamplers() - { - if (this.AudioEnvironment.Engine != null) - { - this.playerQueue.DispatchAsync(() => - { - foreach (var sampler in this.audioSamplers) - { - this.AudioEnvironment.Engine.DetachNode(sampler.AudioNode); - sampler.Dispose(); - } - - this.audioPlayers.Clear(); - this.audioSamplers.Clear(); - }); - } - } - - private NSUrl UrlForSound(string name) - { - NSUrl result = null; - foreach (var fileExtension in new string[] { "wav", "m4a" }) - { - var filename = $"Sounds/{name}"; - result = NSBundle.MainBundle.GetUrlForResource(filename, fileExtension); - if (result != null) - { - break; - } - } - - return result; - } - - public AVAudioPlayer CreatePlayer(string name) - { - var url = this.UrlForSound(name); - if (url == null) - { - throw new Exception($"Failed to load sound for: {name}"); - } - - var player = AVAudioPlayer.FromUrl(url, out NSError error); - if (error != null) - { - throw new Exception($"Failed to load sound for: {name}.\n{error?.LocalizedDescription}"); - } - - return player; - } - - public void PrepareAudioFile(string name) - { - var needsToLoad = false; - this.playerQueue.DispatchSync(() => - { - needsToLoad = !this.audioPlayers.ContainsKey(name) || this.audioPlayers[name] == null; - }); - - if (needsToLoad) - { - var player = this.CreatePlayer(name); - player.PrepareToPlay(); - this.playerQueue.DispatchSync(() => - { - this.audioPlayers[name] = player; - }); - } - } - - public void PlayAudioFile(string name, float volume = 1f, bool loop = false) - { - this.playerQueue.DispatchSync(() => - { - this.audioPlayers.TryGetValue(name, out AVAudioPlayer player); - if (player == null) - { - player = this.CreatePlayer(name); - this.audioPlayers[name] = player; - } - - if (player != null) - { - player.Volume = volume * this.effectsGain; - player.Play(); - if (loop) - { - player.NumberOfLoops = -1; - } - } - }); - } - - public void StopAudioFile(string name, double fadeDuration) - { - this.playerQueue.DispatchSync(() => - { - if (this.audioPlayers.TryGetValue(name, out AVAudioPlayer player)) - { - player.SetVolume(0f, fadeDuration); - // TODO: DispatchQueue.main.asyncAfter(deadline: .now() + fadeDur) - DispatchQueue.MainQueue.DispatchAsync(player.Stop); - } - }); - } - - public void PlayStretch(Catapult catapult, float stretchDistance, float stretchRate, bool playHaptic) - { - var normalizedDistance = DigitExtensions.Clamp((stretchDistance - 0.1f) / 2f, 0f, 1f); - - if (this.isStretchPlaying) - { - // Set the stretch distance and rate on the audio - // player to module the strech sound effect. - catapult.AudioPlayer.StretchDistance = normalizedDistance; - catapult.AudioPlayer.StretchRate = stretchRate; - } - else - { - catapult.AudioPlayer.StartStretch(); - this.isStretchPlaying = true; - } - - if (playHaptic) - { - double interval; - if (normalizedDistance >= 0.25 && normalizedDistance < 0.5) - { - interval = 0.5; - } - else if (normalizedDistance >= 0.5) - { - interval = 0.25; - } - else - { - interval = 1.0; - } - - if (this.prevStretchDistance.HasValue) - { - var delta = Math.Abs(stretchDistance - this.prevStretchDistance.Value); - this.prevStretchDistance = stretchDistance; - if (delta < 0.0075f) - { - return; - } - } - else - { - this.prevStretchDistance = stretchDistance; - } - - if (this.timeSinceLastHaptic.HasValue) - { - if ((DateTime.UtcNow - this.timeSinceLastHaptic.Value).TotalSeconds > interval) - { - this.hapticsGenerator.GenerateImpactFeedback(); - this.timeSinceLastHaptic = DateTime.UtcNow; - } - } - else - { - this.hapticsGenerator.GenerateImpactFeedback(); - this.timeSinceLastHaptic = DateTime.UtcNow; - } - } - } - - public void StopStretch(Catapult catapult) - { - catapult.AudioPlayer.StopStretch(); - catapult.AudioPlayer.StretchDistance = 0f; - this.isStretchPlaying = false; - this.timeSinceLastHaptic = null; - } - - public void PlayLaunch(Catapult catapult, GameVelocity velocity, bool playHaptic) - { - if (playHaptic) - { - this.hapticsGenerator.GenerateNotificationFeedback(UINotificationFeedbackType.Success); - } - - catapult.AudioPlayer.PlayLaunch(velocity); - } - - public void PlayGrabBall(Catapult catapult) - { - catapult.AudioPlayer.PlayGrabBall(); - // clear the highlight state so we don't play the highlight off - // sound after the player has grabbed the ball. - this.highlightedCatapult = null; - } - - public void CatapultDidChangeHighlight(Catapult catapult, bool highlighted) - { - if (highlighted) - { - if (this.highlightedCatapult != catapult) - { - catapult.AudioPlayer.PlayHighlightOn(); - this.highlightedCatapult = catapult; - } - } - else - { - if (this.highlightedCatapult == catapult) - { - catapult.AudioPlayer.PlayHighlightOff(); - this.highlightedCatapult = null; - } - } - } - - public void PlayCatapultBreak(Catapult catapult, bool vortex) - { - // os_log(.info, "play catapult break for catapultID = %d", catapult.catapultID) - var shouldPlay = true; - if (vortex) - { - if (this.firstVortexCatapultBreak) - { - this.firstVortexCatapultBreak = false; - } - else - { - shouldPlay = false; - } - } - - if (shouldPlay) - { - catapult.AudioPlayer.PlayBreak(); - } - } - - public void PlayLeverHighlight(bool highlighted) - { - if (highlighted) - { - this.PlayAudioFile("catapult_highlight_on_02", 0.2f); - } - else - { - this.PlayAudioFile("catapult_highlight_off_02", 0.2f); - } - } - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using AVFoundation; + using CoreFoundation; + using Foundation; + using SceneKit; + using XamarinShot.Models.GameplayState; + using XamarinShot.Utils; + using System; + using System.Collections.Generic; + using UIKit; + + public class SFXCoordinator : NSObject { + private readonly string [] preloadAudioFiles = + { + "vortex_04", + "catapult_highlight_on_02", + "catapult_highlight_off_02" + }; + + private readonly Dictionary<string, AVAudioPlayer> audioPlayers = new Dictionary<string, AVAudioPlayer> (); + private readonly DispatchQueue playerQueue = new DispatchQueue ("SFXCoordinator"); + private readonly DispatchQueue loadQueue = new DispatchQueue ("SFXCoordinator.loading"); + + private readonly List<AudioSampler> audioSamplers = new List<AudioSampler> (); + + private readonly HapticsGenerator hapticsGenerator = new HapticsGenerator (); + private bool isStretchPlaying; + private DateTime? timeSinceLastHaptic; + private float? prevStretchDistance; + private Catapult highlightedCatapult; + private bool firstVortexCatapultBreak = true; + + private float effectsGain = 1f; + + public SFXCoordinator (AVAudioEnvironmentNode audioEnvironment) : base () + { + this.AudioEnvironment = audioEnvironment; + + this.loadQueue.DispatchAsync (() => { + foreach (var file in preloadAudioFiles) { + this.PrepareAudioFile (file); + } + }); + + // Because the coordinate space is scaled, let's apply some adjustments to the + // distance attenuation parameters to make the distance rolloff sound more + // realistic. + + this.AudioEnvironment.DistanceAttenuationParameters.ReferenceDistance = 5f; + this.AudioEnvironment.DistanceAttenuationParameters.MaximumDistance = 40f; + this.AudioEnvironment.DistanceAttenuationParameters.RolloffFactor = 1f; + this.AudioEnvironment.DistanceAttenuationParameters.DistanceAttenuationModel = AVAudioEnvironmentDistanceAttenuationModel.Inverse; + + this.UpdateEffectsVolume (); + + // When the route changes, we need to reload our audio samplers because sometimes those + // audio units are being reset. + NSNotificationCenter.DefaultCenter.AddObserver (AVAudioSession.RouteChangeNotification, this.HandleRouteChange); + + // Subscribe to notifications of user defaults changing so that we can apply them to + // sound effects. + NSNotificationCenter.DefaultCenter.AddObserver (NSUserDefaults.DidChangeNotification, this.HandleDefaultsDidChange); + + NSNotificationCenter.DefaultCenter.AddObserver (UIApplication.DidEnterBackgroundNotification, this.HandleAppDidEnterBackground); + } + + public AVAudioEnvironmentNode AudioEnvironment { get; private set; } + + public SCNMatrix4 RenderToSimulationTransform { get; set; } = SCNMatrix4.Identity; + + private void HandleRouteChange (NSNotification notification) + { + this.loadQueue.DispatchAsync (() => { + foreach (var sampler in this.audioSamplers) { + sampler.ReloadPreset (); + } + }); + } + + private void HandleDefaultsDidChange (NSNotification notification) + { + this.UpdateEffectsVolume (); + } + + private void HandleAppDidEnterBackground (NSNotification notification) + { + foreach (var sampler in this.audioSamplers) { + sampler.StopAllNotes (); + } + } + + public static float EffectsGain () + { + var effectsVolume = UserDefaults.EffectsVolume; + // Map the slider value from 0...1 to a more natural curve: + return effectsVolume * effectsVolume; + } + + private void UpdateEffectsVolume () + { + this.effectsGain = SFXCoordinator.EffectsGain (); + this.AudioEnvironment.OutputVolume = effectsGain; + } + + public void SetupGameAudioComponent (GameAudioComponent component) + { + component.SfxCoordinator = this; + } + + public void AttachSampler (AudioSampler audioSampler, SCNNode node) + { + // Add the audio Player to the scenekit node so that it gets correct positional + // adjustments + node.AddAudioPlayer (audioSampler.AudioPlayer); + + // NOTE: AVAudioNodes that are not AVAudioPlayerNodes are not + // automatically added to an AVAudioEngine by SceneKit. So we add + // this audio node to the SCNNode so that it can get position updates + // but we connect it manually to the AVAudioEnvironmentNode that we + // get passed to us. This comes from ARSCNView in GameSceneViewController. + if (this.AudioEnvironment.Engine != null) { + var engine = this.AudioEnvironment.Engine; + + // attach the node + var audioNode = audioSampler.AudioNode; + engine.AttachNode (audioNode); + + // connect + var engineFormat = engine.OutputNode.GetBusInputFormat (0); + var format = new AVAudioFormat (engineFormat.SampleRate, 1); + engine.Connect (audioNode, AudioEnvironment, format); + + // addd to the local collection + this.audioSamplers.Add (audioSampler); + } + } + + public void RemoveAllAudioSamplers () + { + if (this.AudioEnvironment.Engine != null) { + this.playerQueue.DispatchAsync (() => { + foreach (var sampler in this.audioSamplers) { + this.AudioEnvironment.Engine.DetachNode (sampler.AudioNode); + sampler.Dispose (); + } + + this.audioPlayers.Clear (); + this.audioSamplers.Clear (); + }); + } + } + + private NSUrl UrlForSound (string name) + { + NSUrl result = null; + foreach (var fileExtension in new string [] { "wav", "m4a" }) { + var filename = $"Sounds/{name}"; + result = NSBundle.MainBundle.GetUrlForResource (filename, fileExtension); + if (result != null) { + break; + } + } + + return result; + } + + public AVAudioPlayer CreatePlayer (string name) + { + var url = this.UrlForSound (name); + if (url == null) { + throw new Exception ($"Failed to load sound for: {name}"); + } + + var player = AVAudioPlayer.FromUrl (url, out NSError error); + if (error != null) { + throw new Exception ($"Failed to load sound for: {name}.\n{error?.LocalizedDescription}"); + } + + return player; + } + + public void PrepareAudioFile (string name) + { + var needsToLoad = false; + this.playerQueue.DispatchSync (() => { + needsToLoad = !this.audioPlayers.ContainsKey (name) || this.audioPlayers [name] == null; + }); + + if (needsToLoad) { + var player = this.CreatePlayer (name); + player.PrepareToPlay (); + this.playerQueue.DispatchSync (() => { + this.audioPlayers [name] = player; + }); + } + } + + public void PlayAudioFile (string name, float volume = 1f, bool loop = false) + { + this.playerQueue.DispatchSync (() => { + this.audioPlayers.TryGetValue (name, out AVAudioPlayer player); + if (player == null) { + player = this.CreatePlayer (name); + this.audioPlayers [name] = player; + } + + if (player != null) { + player.Volume = volume * this.effectsGain; + player.Play (); + if (loop) { + player.NumberOfLoops = -1; + } + } + }); + } + + public void StopAudioFile (string name, double fadeDuration) + { + this.playerQueue.DispatchSync (() => { + if (this.audioPlayers.TryGetValue (name, out AVAudioPlayer player)) { + player.SetVolume (0f, fadeDuration); + // TODO: DispatchQueue.main.asyncAfter(deadline: .now() + fadeDur) + DispatchQueue.MainQueue.DispatchAsync (player.Stop); + } + }); + } + + public void PlayStretch (Catapult catapult, float stretchDistance, float stretchRate, bool playHaptic) + { + var normalizedDistance = DigitExtensions.Clamp ((stretchDistance - 0.1f) / 2f, 0f, 1f); + + if (this.isStretchPlaying) { + // Set the stretch distance and rate on the audio + // player to module the strech sound effect. + catapult.AudioPlayer.StretchDistance = normalizedDistance; + catapult.AudioPlayer.StretchRate = stretchRate; + } else { + catapult.AudioPlayer.StartStretch (); + this.isStretchPlaying = true; + } + + if (playHaptic) { + double interval; + if (normalizedDistance >= 0.25 && normalizedDistance < 0.5) { + interval = 0.5; + } else if (normalizedDistance >= 0.5) { + interval = 0.25; + } else { + interval = 1.0; + } + + if (this.prevStretchDistance.HasValue) { + var delta = Math.Abs (stretchDistance - this.prevStretchDistance.Value); + this.prevStretchDistance = stretchDistance; + if (delta < 0.0075f) { + return; + } + } else { + this.prevStretchDistance = stretchDistance; + } + + if (this.timeSinceLastHaptic.HasValue) { + if ((DateTime.UtcNow - this.timeSinceLastHaptic.Value).TotalSeconds > interval) { + this.hapticsGenerator.GenerateImpactFeedback (); + this.timeSinceLastHaptic = DateTime.UtcNow; + } + } else { + this.hapticsGenerator.GenerateImpactFeedback (); + this.timeSinceLastHaptic = DateTime.UtcNow; + } + } + } + + public void StopStretch (Catapult catapult) + { + catapult.AudioPlayer.StopStretch (); + catapult.AudioPlayer.StretchDistance = 0f; + this.isStretchPlaying = false; + this.timeSinceLastHaptic = null; + } + + public void PlayLaunch (Catapult catapult, GameVelocity velocity, bool playHaptic) + { + if (playHaptic) { + this.hapticsGenerator.GenerateNotificationFeedback (UINotificationFeedbackType.Success); + } + + catapult.AudioPlayer.PlayLaunch (velocity); + } + + public void PlayGrabBall (Catapult catapult) + { + catapult.AudioPlayer.PlayGrabBall (); + // clear the highlight state so we don't play the highlight off + // sound after the player has grabbed the ball. + this.highlightedCatapult = null; + } + + public void CatapultDidChangeHighlight (Catapult catapult, bool highlighted) + { + if (highlighted) { + if (this.highlightedCatapult != catapult) { + catapult.AudioPlayer.PlayHighlightOn (); + this.highlightedCatapult = catapult; + } + } else { + if (this.highlightedCatapult == catapult) { + catapult.AudioPlayer.PlayHighlightOff (); + this.highlightedCatapult = null; + } + } + } + + public void PlayCatapultBreak (Catapult catapult, bool vortex) + { + // os_log(.info, "play catapult break for catapultID = %d", catapult.catapultID) + var shouldPlay = true; + if (vortex) { + if (this.firstVortexCatapultBreak) { + this.firstVortexCatapultBreak = false; + } else { + shouldPlay = false; + } + } + + if (shouldPlay) { + catapult.AudioPlayer.PlayBreak (); + } + } + + public void PlayLeverHighlight (bool highlighted) + { + if (highlighted) { + this.PlayAudioFile ("catapult_highlight_on_02", 0.2f); + } else { + this.PlayAudioFile ("catapult_highlight_off_02", 0.2f); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/World Map Loading/BoardAnchor.cs b/ios12/XamarinShot/XamarinShot/Core/World Map Loading/BoardAnchor.cs index 103c50958..496f162e5 100644 --- a/ios12/XamarinShot/XamarinShot/Core/World Map Loading/BoardAnchor.cs +++ b/ios12/XamarinShot/XamarinShot/Core/World Map Loading/BoardAnchor.cs @@ -1,55 +1,53 @@ - -namespace XamarinShot.Models -{ - using ARKit; - using CoreGraphics; - using Foundation; - using SceneKit; - using XamarinShot.Utils; - using System; - - public class BoardAnchor : ARAnchor - { - public BoardAnchor(IntPtr handle) : base(handle) { } - - public BoardAnchor(SCNMatrix4 transform, CGSize size) : base("Board", transform.ToNMatrix4()) - { - this.Size = size; - } - - [Export("initWithCoder:")] - public BoardAnchor(NSCoder coder) : base(coder) - { - var width = coder.DecodeFloat("width"); - var height = coder.DecodeFloat("height"); - this.Size = new CGSize(width, height); - } - - // this is guaranteed to be called with something of the same class - public BoardAnchor(ARAnchor anchor) : base(anchor) - { - var other = anchor as BoardAnchor; - this.Size = other.Size; - } - - public CGSize Size { get; private set; } - - public override NSObject Copy(NSZone zone) - { - // required by objc method override - var copy = base.Copy(zone) as BoardAnchor; - copy.Size = this.Size; - return copy; - } - - public override void EncodeTo(NSCoder encoder) - { - base.EncodeTo(encoder); - encoder.Encode(this.Size.Width, "width"); - encoder.Encode(this.Size.Height, "height"); - } - - [Export("supportsSecureCoding")] - public static bool SupportsSecureCoding => true; - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using ARKit; + using CoreGraphics; + using Foundation; + using SceneKit; + using XamarinShot.Utils; + using System; + + public class BoardAnchor : ARAnchor { + public BoardAnchor (IntPtr handle) : base (handle) { } + + public BoardAnchor (SCNMatrix4 transform, CGSize size) : base ("Board", transform.ToNMatrix4 ()) + { + this.Size = size; + } + + [Export ("initWithCoder:")] + public BoardAnchor (NSCoder coder) : base (coder) + { + var width = coder.DecodeFloat ("width"); + var height = coder.DecodeFloat ("height"); + this.Size = new CGSize (width, height); + } + + // this is guaranteed to be called with something of the same class + public BoardAnchor (ARAnchor anchor) : base (anchor) + { + var other = anchor as BoardAnchor; + this.Size = other.Size; + } + + public CGSize Size { get; private set; } + + public override NSObject Copy (NSZone zone) + { + // required by objc method override + var copy = base.Copy (zone) as BoardAnchor; + copy.Size = this.Size; + return copy; + } + + public override void EncodeTo (NSCoder encoder) + { + base.EncodeTo (encoder); + encoder.Encode (this.Size.Width, "width"); + encoder.Encode (this.Size.Height, "height"); + } + + [Export ("supportsSecureCoding")] + public static bool SupportsSecureCoding => true; + } +} diff --git a/ios12/XamarinShot/XamarinShot/Core/World Map Loading/KeyPositionAnchor.cs b/ios12/XamarinShot/XamarinShot/Core/World Map Loading/KeyPositionAnchor.cs index 49b6df6be..1ef676d40 100644 --- a/ios12/XamarinShot/XamarinShot/Core/World Map Loading/KeyPositionAnchor.cs +++ b/ios12/XamarinShot/XamarinShot/Core/World Map Loading/KeyPositionAnchor.cs @@ -1,63 +1,58 @@ - -namespace XamarinShot.Models -{ - using ARKit; - using Foundation; - using System; - using UIKit; - - public class KeyPositionAnchor : ARAnchor - { - public KeyPositionAnchor(UIImage image, OpenTK.NMatrix4 transform, ARWorldMappingStatus mappingStatus) : base("KeyPosition", transform) - { - this.Image = image; - this.MappingStatus = mappingStatus; - } - - // this is guaranteed to be called with something of the same class - public KeyPositionAnchor(ARAnchor anchor) : base(anchor) - { - var other = anchor as KeyPositionAnchor; - this.Image = other.Image; - this.MappingStatus = other.MappingStatus; - } - - [Export("initWithCoder:")] - public KeyPositionAnchor(NSCoder coder) : base(coder) - { - if (coder.DecodeObject("image") is UIImage image) - { - this.Image = image; - var mappingValue = coder.DecodeInt("mappingStatus"); - this.MappingStatus = (ARWorldMappingStatus)mappingValue; - } - else - { - throw new Exception(); - } - } - - public UIImage Image { get; private set; } - - public ARWorldMappingStatus MappingStatus { get; private set; } - - public override void EncodeTo(NSCoder encoder) - { - base.EncodeTo(encoder); - encoder.Encode(this.Image, "image"); - encoder.Encode((int)this.MappingStatus, "mappingStatus"); - } - - public override NSObject Copy(NSZone zone) - { - // required by objc method override - var copy = base.Copy(zone) as KeyPositionAnchor; - copy.Image = this.Image; - copy.MappingStatus = this.MappingStatus; - return copy; - } - - [Export("supportsSecureCoding")] - public static bool SupportsSecureCoding => true; - } -} \ No newline at end of file + +namespace XamarinShot.Models { + using ARKit; + using Foundation; + using System; + using UIKit; + + public class KeyPositionAnchor : ARAnchor { + public KeyPositionAnchor (UIImage image, OpenTK.NMatrix4 transform, ARWorldMappingStatus mappingStatus) : base ("KeyPosition", transform) + { + this.Image = image; + this.MappingStatus = mappingStatus; + } + + // this is guaranteed to be called with something of the same class + public KeyPositionAnchor (ARAnchor anchor) : base (anchor) + { + var other = anchor as KeyPositionAnchor; + this.Image = other.Image; + this.MappingStatus = other.MappingStatus; + } + + [Export ("initWithCoder:")] + public KeyPositionAnchor (NSCoder coder) : base (coder) + { + if (coder.DecodeObject ("image") is UIImage image) { + this.Image = image; + var mappingValue = coder.DecodeInt ("mappingStatus"); + this.MappingStatus = (ARWorldMappingStatus) mappingValue; + } else { + throw new Exception (); + } + } + + public UIImage Image { get; private set; } + + public ARWorldMappingStatus MappingStatus { get; private set; } + + public override void EncodeTo (NSCoder encoder) + { + base.EncodeTo (encoder); + encoder.Encode (this.Image, "image"); + encoder.Encode ((int) this.MappingStatus, "mappingStatus"); + } + + public override NSObject Copy (NSZone zone) + { + // required by objc method override + var copy = base.Copy (zone) as KeyPositionAnchor; + copy.Image = this.Image; + copy.MappingStatus = this.MappingStatus; + return copy; + } + + [Export ("supportsSecureCoding")] + public static bool SupportsSecureCoding => true; + } +} diff --git a/ios12/XamarinShot/XamarinShot/Main.cs b/ios12/XamarinShot/XamarinShot/Main.cs index 8c0924b03..ebf37aa51 100644 --- a/ios12/XamarinShot/XamarinShot/Main.cs +++ b/ios12/XamarinShot/XamarinShot/Main.cs @@ -1,16 +1,14 @@ - -namespace XamarinShot -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace XamarinShot { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/ARSCNViewExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/ARSCNViewExtensions.cs index cf80f174f..d06f8ffa7 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/ARSCNViewExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/ARSCNViewExtensions.cs @@ -1,57 +1,52 @@ - -namespace XamarinShot.Utils -{ - using ARKit; - using CoreImage; - using Foundation; - using UIKit; - - /// <summary> - /// Convenience extension for generating screeshots from ARSCNView. - /// </summary> - public static class ARSCNViewExtensions - { - public static UIImage CreateScreenshot(this ARSCNView view, UIDeviceOrientation interfaceOrientation) - { - if(view.Session.CurrentFrame == null) - { - return null; - } - - var ciImage = new CIImage(view.Session.CurrentFrame.CapturedImage); - - // TODO: check - var keys = new NSString[] { CIFilterInputKey.Scale , CIFilterInputKey.AspectRatio }; - var objects = new NSNumber[] { new NSNumber(0.5f), new NSNumber(1f) }; - - var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys); - var scaledImage = ciImage.CreateByFiltering("CILanczosScaleTransform", dictionary); - - var context = new CIContext(new CIContextOptions { UseSoftwareRenderer = false }); - var cgimage = context.CreateCGImage(scaledImage, scaledImage.Extent); - if(cgimage != null) - { - var orientation = UIImageOrientation.Right; - switch (interfaceOrientation) - { - case UIDeviceOrientation.Portrait: - orientation = UIImageOrientation.Right; - break; - case UIDeviceOrientation.PortraitUpsideDown: - orientation = UIImageOrientation.Left; - break; - case UIDeviceOrientation.LandscapeLeft: - orientation = UIImageOrientation.Up; - break; - case UIDeviceOrientation.LandscapeRight: - orientation = UIImageOrientation.Down; - break; - } - - return new UIImage(cgimage, 1f, orientation); - } - - return null; - } - } -} \ No newline at end of file + +namespace XamarinShot.Utils { + using ARKit; + using CoreImage; + using Foundation; + using UIKit; + + /// <summary> + /// Convenience extension for generating screeshots from ARSCNView. + /// </summary> + public static class ARSCNViewExtensions { + public static UIImage CreateScreenshot (this ARSCNView view, UIDeviceOrientation interfaceOrientation) + { + if (view.Session.CurrentFrame == null) { + return null; + } + + var ciImage = new CIImage (view.Session.CurrentFrame.CapturedImage); + + // TODO: check + var keys = new NSString [] { CIFilterInputKey.Scale, CIFilterInputKey.AspectRatio }; + var objects = new NSNumber [] { new NSNumber (0.5f), new NSNumber (1f) }; + + var dictionary = NSDictionary.FromObjectsAndKeys (objects, keys); + var scaledImage = ciImage.CreateByFiltering ("CILanczosScaleTransform", dictionary); + + var context = new CIContext (new CIContextOptions { UseSoftwareRenderer = false }); + var cgimage = context.CreateCGImage (scaledImage, scaledImage.Extent); + if (cgimage != null) { + var orientation = UIImageOrientation.Right; + switch (interfaceOrientation) { + case UIDeviceOrientation.Portrait: + orientation = UIImageOrientation.Right; + break; + case UIDeviceOrientation.PortraitUpsideDown: + orientation = UIImageOrientation.Left; + break; + case UIDeviceOrientation.LandscapeLeft: + orientation = UIImageOrientation.Up; + break; + case UIDeviceOrientation.LandscapeRight: + orientation = UIImageOrientation.Down; + break; + } + + return new UIImage (cgimage, 1f, orientation); + } + + return null; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/ARWorldMapExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/ARWorldMapExtensions.cs index 6b926c749..5cf6cd176 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/ARWorldMapExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/ARWorldMapExtensions.cs @@ -1,21 +1,19 @@ - -namespace XamarinShot.Utils -{ - using ARKit; - using System.Collections.Generic; - using System.Linq; - using XamarinShot.Models; - public static class ARWorldMapExtensions - { - public static BoardAnchor BoardAnchor(this ARWorldMap self) - { - return self.Anchors.FirstOrDefault(anchor => anchor is BoardAnchor) as BoardAnchor; - } +namespace XamarinShot.Utils { + using ARKit; + using System.Collections.Generic; + using System.Linq; + using XamarinShot.Models; - public static List<KeyPositionAnchor> KeyPositionAnchors(this ARWorldMap self) - { - return self.Anchors.Where(anchor => anchor is KeyPositionAnchor).Cast<KeyPositionAnchor>().ToList(); - } - } -} \ No newline at end of file + public static class ARWorldMapExtensions { + public static BoardAnchor BoardAnchor (this ARWorldMap self) + { + return self.Anchors.FirstOrDefault (anchor => anchor is BoardAnchor) as BoardAnchor; + } + + public static List<KeyPositionAnchor> KeyPositionAnchors (this ARWorldMap self) + { + return self.Anchors.Where (anchor => anchor is KeyPositionAnchor).Cast<KeyPositionAnchor> ().ToList (); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/CGPointExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/CGPointExtensions.cs index a3b5bb297..52f1fd6d0 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/CGPointExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/CGPointExtensions.cs @@ -1,20 +1,18 @@ - -namespace XamarinShot.Utils -{ - using System; - using CoreGraphics; - /// <summary> - /// Helpers for CGPoint - /// </summary> - public static class CGPointExtensions - { - /// <summary> - /// /// Returns the length of a point when considered as a vector. (Used with gesture recognizers.) - /// </summary> - public static float Length(this CGPoint point) - { - return (float)Math.Sqrt(point.X * point.X + point.Y * point.Y); - } - } -} \ No newline at end of file +namespace XamarinShot.Utils { + using System; + using CoreGraphics; + + /// <summary> + /// Helpers for CGPoint + /// </summary> + public static class CGPointExtensions { + /// <summary> + /// /// Returns the length of a point when considered as a vector. (Used with gesture recognizers.) + /// </summary> + public static float Length (this CGPoint point) + { + return (float) Math.Sqrt (point.X * point.X + point.Y * point.Y); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/DigitExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/DigitExtensions.cs index 23d5f5697..a3c39c57a 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/DigitExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/DigitExtensions.cs @@ -1,73 +1,67 @@ - -namespace XamarinShot.Utils -{ - using System; - public static class DigitExtensions - { - public static float Clamp(float value, float minValue, float maxValue) - { - return Math.Min(Math.Max(value, minValue), maxValue); - } +namespace XamarinShot.Utils { + using System; - public static double Clamp(double value, double minValue, double maxValue) - { - return Math.Min(Math.Max(value, minValue), maxValue); - } + public static class DigitExtensions { + public static float Clamp (float value, float minValue, float maxValue) + { + return Math.Min (Math.Max (value, minValue), maxValue); + } - public static float NormalizedAngle(this float value, float angle, float increment) - { - var normalized = value; - while (Math.Abs(normalized - angle) > increment / 2) - { - if (value > angle) - { - normalized -= increment; - } - else - { - normalized += increment; - } - } - - return normalized; - } + public static double Clamp (double value, double minValue, double maxValue) + { + return Math.Min (Math.Max (value, minValue), maxValue); + } - /// Returns the remainder of this value divided by the given value using - /// truncating division. - /// - /// Performing truncating division with floating-point values results in a - /// truncated integer quotient and a remainder. For values `x` and `y` and - /// their truncated integer quotient `q`, the remainder `r` satisfies - /// `x == y * q + r`. - /// - /// The following example calculates the truncating remainder of dividing - /// 8.625 by 0.75: - /// - /// let x = 8.625 - /// print(x / 0.75) - /// // Prints "11.5" - /// - /// let q = (x / 0.75).rounded(.towardZero) - /// // q == 11.0 - /// let r = x.truncatingRemainder(dividingBy: 0.75) - /// // r == 0.375 - /// - /// let x1 = 0.75 * q + r - /// // x1 == 8.625 - /// - /// If this value and `other` are both finite numbers, the truncating - /// remainder has the same sign as this value and is strictly smaller in - /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method - /// is always exact. - /// - /// - Parameter other: The value to use when dividing this value. - /// - Returns: The remainder of this value divided by `other` using - /// truncating division. - public static double TruncatingRemainder(this double value, double other) - { - var q = Math.Round(value / other, MidpointRounding.ToEven); - return value - (other * q); - } - } -} \ No newline at end of file + public static float NormalizedAngle (this float value, float angle, float increment) + { + var normalized = value; + while (Math.Abs (normalized - angle) > increment / 2) { + if (value > angle) { + normalized -= increment; + } else { + normalized += increment; + } + } + + return normalized; + } + + /// Returns the remainder of this value divided by the given value using + /// truncating division. + /// + /// Performing truncating division with floating-point values results in a + /// truncated integer quotient and a remainder. For values `x` and `y` and + /// their truncated integer quotient `q`, the remainder `r` satisfies + /// `x == y * q + r`. + /// + /// The following example calculates the truncating remainder of dividing + /// 8.625 by 0.75: + /// + /// let x = 8.625 + /// print(x / 0.75) + /// // Prints "11.5" + /// + /// let q = (x / 0.75).rounded(.towardZero) + /// // q == 11.0 + /// let r = x.truncatingRemainder(dividingBy: 0.75) + /// // r == 0.375 + /// + /// let x1 = 0.75 * q + r + /// // x1 == 8.625 + /// + /// If this value and `other` are both finite numbers, the truncating + /// remainder has the same sign as this value and is strictly smaller in + /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method + /// is always exact. + /// + /// - Parameter other: The value to use when dividing this value. + /// - Returns: The remainder of this value divided by `other` using + /// truncating division. + public static double TruncatingRemainder (this double value, double other) + { + var q = Math.Round (value / other, MidpointRounding.ToEven); + return value - (other * q); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/ListExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/ListExtensions.cs index 45a22378a..c25d619e8 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/ListExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/ListExtensions.cs @@ -1,17 +1,14 @@ - -namespace XamarinShot.Utils -{ - using System; - using System.Collections.Generic; - public static class ListExtensions - { - public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action) - { - foreach (var item in collection) - { - action(item); - } - } - } -} \ No newline at end of file +namespace XamarinShot.Utils { + using System; + using System.Collections.Generic; + + public static class ListExtensions { + public static void ForEach<T> (this IEnumerable<T> collection, Action<T> action) + { + foreach (var item in collection) { + action (item); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/ParserExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/ParserExtensions.cs index 744c055e7..2834168f6 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/ParserExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/ParserExtensions.cs @@ -1,39 +1,31 @@ - -namespace XamarinShot.Utils -{ - using System.Collections.Generic; - public static class ParserExtensions - { - public static T Parse<T>(this string json) - { - return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); - } +namespace XamarinShot.Utils { + using System.Collections.Generic; - public static bool TryGet<T>(this Dictionary<string, object> dictionary, string key, out T result) - { - var isSucceed = false; - result = default(T); + public static class ParserExtensions { + public static T Parse<T> (this string json) + { + return Newtonsoft.Json.JsonConvert.DeserializeObject<T> (json); + } - if (dictionary.TryGetValue(key, out object value)) - { - if (value is T converted) - { - result = converted; - isSucceed = true; - } - else - { - try - { - result = value.ToString().Parse<T>(); - isSucceed = true; - } - catch(Newtonsoft.Json.JsonException) { /* another type possible */ } - } - } + public static bool TryGet<T> (this Dictionary<string, object> dictionary, string key, out T result) + { + var isSucceed = false; + result = default (T); - return isSucceed; - } - } -} \ No newline at end of file + if (dictionary.TryGetValue (key, out object value)) { + if (value is T converted) { + result = converted; + isSucceed = true; + } else { + try { + result = value.ToString ().Parse<T> (); + isSucceed = true; + } catch (Newtonsoft.Json.JsonException) { /* another type possible */ } + } + } + + return isSucceed; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/SCNGeometrySourceExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/SCNGeometrySourceExtensions.cs index c864db9c0..b1421685c 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/SCNGeometrySourceExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/SCNGeometrySourceExtensions.cs @@ -1,45 +1,40 @@ - -namespace XamarinShot.Utils -{ - using Foundation; - using SceneKit; - using System; - using System.Linq; - using System.Collections.Generic; - public static class SCNGeometrySourceExtensions - { - public static SCNGeometrySource Create(List<SCNVector4> colors) - { - SCNGeometrySource result = null; - unsafe - { - var bytes = new List<byte>(); - var colorsArray = colors.ToArray(); +namespace XamarinShot.Utils { + using Foundation; + using SceneKit; + using System; + using System.Linq; + using System.Collections.Generic; - for (int i = 0; i < colors.Count; i++) - { - fixed (SCNVector4* point = &colorsArray[i]) - { - var intPtr = new IntPtr(point); - var data = NSData.FromBytes(intPtr, (nuint)SCNVector4.SizeInBytes); + public static class SCNGeometrySourceExtensions { + public static SCNGeometrySource Create (List<SCNVector4> colors) + { + SCNGeometrySource result = null; + unsafe { + var bytes = new List<byte> (); + var colorsArray = colors.ToArray (); - bytes.AddRange(data.ToList()); - } - } + for (int i = 0; i < colors.Count; i++) { + fixed (SCNVector4* point = &colorsArray [i]) { + var intPtr = new IntPtr (point); + var data = NSData.FromBytes (intPtr, (nuint) SCNVector4.SizeInBytes); - var colorData = NSData.FromArray(bytes.ToArray()); - result = SCNGeometrySource.FromData(colorData, - SCNGeometrySourceSemantics.Color, - colors.Count, - true, - 4, - sizeof(float), - 0, - SCNVector4.SizeInBytes); - } + bytes.AddRange (data.ToList ()); + } + } - return result; - } - } -} \ No newline at end of file + var colorData = NSData.FromArray (bytes.ToArray ()); + result = SCNGeometrySource.FromData (colorData, + SCNGeometrySourceSemantics.Color, + colors.Count, + true, + 4, + sizeof (float), + 0, + SCNVector4.SizeInBytes); + } + + return result; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/SCNMaterialExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/SCNMaterialExtensions.cs index 5c868177d..91d59e1a0 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/SCNMaterialExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/SCNMaterialExtensions.cs @@ -1,19 +1,17 @@ - -namespace XamarinShot.Utils -{ - using Foundation; - using SceneKit; - public static class SCNMaterialExtensions - { - public static SCNMaterial Create(NSObject diffuse) - { - var material = SCNMaterial.Create(); - material.Diffuse.Contents = diffuse; - material.DoubleSided = true; - material.LightingModelName = SCNLightingModel.PhysicallyBased; +namespace XamarinShot.Utils { + using Foundation; + using SceneKit; - return material; - } - } -} \ No newline at end of file + public static class SCNMaterialExtensions { + public static SCNMaterial Create (NSObject diffuse) + { + var material = SCNMaterial.Create (); + material.Diffuse.Contents = diffuse; + material.DoubleSided = true; + material.LightingModelName = SCNLightingModel.PhysicallyBased; + + return material; + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/SCNNodeExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/SCNNodeExtensions.cs index a3ae17560..ba85f2e5a 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/SCNNodeExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/SCNNodeExtensions.cs @@ -1,656 +1,567 @@ - -namespace XamarinShot.Utils -{ - using Foundation; - using SceneKit; - using XamarinShot.Models; - using XamarinShot.Models.GameplayState; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - - public static class SCNNodeExtensions - { - #region game object - - private static Dictionary<SCNNode, GameObject> map = new Dictionary<SCNNode, GameObject>(); - - public static GameObject GetGameObject(this SCNNode node) - { - map.TryGetValue(node, out GameObject @object); - return @object; - } - - public static void SetGameObject(this SCNNode node, GameObject value) - { - if (!map.ContainsKey(node)) - { - map.Add(node, value); - } - } - - #endregion - - #region fix materials - - public static void FixMaterials(this SCNNode node) - { - // walk down the scenegraph and update all children - node.FixNormalMaps(); - - // establish paint colors - node.CopyGeometryForPaintColors(); - node.SetPaintColors(); - } - - private static void FixNormalMap(this SCNGeometry geometry) - { - foreach (var material in geometry.Materials) - { - var prop = material.Normal; - // astc needs gggr and .ag to compress to L+A, - // but will compress rg01 to RGB single plane (less quality) - // bc/eac/explicit/no compression use rg01 and .rg - // rg01 is easier to see and edit in texture editors - - // set the normal to RED | GREEN (rg01 compression) - // uses single plane on ASTC, dual on BC5/EAC_RG11/Explicit - prop.TextureComponents = SCNColorMask.Red | SCNColorMask.Green; - - // set the normal to ALPHA | GREEN (gggr compression) - // uses dual plane for ASTC, BC3nm - // prop.textureComponents = [.alpha, .green] - } - } - - /// <summary> - /// Fix the normal map reconstruction on scn files for compressed textures - /// </summary> - public static void FixNormalMaps(this SCNNode node) - { - if (node.Geometry != null) - { - node.Geometry.FixNormalMap(); - - // these will often just have the same material applied - if (node.Geometry.LevelsOfDetail != null) - { - foreach (var lod in node.Geometry.LevelsOfDetail) - { - if (lod.Geometry != null) - { - lod.Geometry.FixNormalMap(); - } - } - } - } - - foreach (var child in node.ChildNodes) - { - child.FixNormalMaps(); - } - } - - // We load all nodes as references which means they share the same - // geometry and materials. For team colors, we need to set geometry overrides - // and so need unique geometry with shadable overrides for each node created. - - public static void CopyGeometryForPaintColors(this SCNNode node) - { - // neutral blocks also need to be tinted - if (node.Geometry != null && !string.IsNullOrEmpty(node.Name)) - { - // does this copy the LOD as well ? - if (node.Geometry.Copy() is SCNGeometry geometryCopy) - { - SetupPaintColorMask(geometryCopy, node.Name); - - // this may already done by the copy() above, but just be safe - if (node.Geometry.LevelsOfDetail != null) - { - var lodsNew = new List<SCNLevelOfDetail>(); - foreach (var lod in node.Geometry.LevelsOfDetail) - { - if (lod.Geometry != null) - { - if (lod.ScreenSpaceRadius > 0) - { - if (lod.Geometry.Copy() is SCNGeometry lodGeometryCopy) - { - lodGeometryCopy.SetupPaintColorMask(node.Name); - lodsNew.Add(SCNLevelOfDetail.CreateWithScreenSpaceRadius(lodGeometryCopy, lod.ScreenSpaceRadius)); - } - } - else - { - if (lod.Geometry.Copy() is SCNGeometry lodGeometryCopy) - { - SetupPaintColorMask(lodGeometryCopy, node.Name); - lodsNew.Add(SCNLevelOfDetail.CreateWithWorldSpaceDistance(lodGeometryCopy, lod.WorldSpaceDistance)); - } - } - } - } - - geometryCopy.LevelsOfDetail = lodsNew.ToArray(); - } - - // set the new geometry and LOD - node.UpdateGeometry(geometryCopy); - } - } - - foreach (var child in node.ChildNodes) - { - child.CopyGeometryForPaintColors(); - } - } - - public static void UpdateGeometry(this SCNNode node, SCNGeometry geometry) - { - var oldGeometry = node.Geometry; - node.Geometry = geometry; - - oldGeometry.Dispose(); - oldGeometry = null; - } - - #endregion - - public static string GetTypeIdentifier(this SCNNode node) - { - string result = null; - if (!string.IsNullOrEmpty(node.Name) && !node.Name.StartsWith("_", StringComparison.Ordinal)) - { - result = node.Name.Split('_').FirstOrDefault(); - } - - return result; - } - - public static GameObject NearestParentGameObject(this SCNNode node) - { - var result = GetGameObject(node); - if (result == null) - { - if (node.ParentNode != null) - { - node.ParentNode.NearestParentGameObject(); - } - } - - return result; - } - - // Returns the size of the horizontal parts of the node's bounding box. - // x is the width, y is the depth. - public static OpenTK.Vector2 GetHorizontalSize(this SCNNode node) - { - var minBox = SCNVector3.Zero; - var maxBox = SCNVector3.Zero; - node.GetBoundingBox(ref minBox, ref maxBox); - - // Scene is y-up, horizontal extent is calculated on x and z - var sceneWidth = Math.Abs(maxBox.X - minBox.X); - var sceneLength = Math.Abs(maxBox.Z - minBox.Z); - return new OpenTK.Vector2(sceneWidth, sceneLength); - } - - #region find node - - public static SCNNode FindNodeWithPhysicsBody(this SCNNode node) - { - return FindNodeWithPhysicsBodyHelper(node); - } - - public static SCNNode FindNodeWithGeometry(this SCNNode node) - { - return FindNodeWithGeometryHelper(node); - } - - private static SCNNode FindNodeWithPhysicsBodyHelper(SCNNode node) - { - SCNNode result = null; - if (node.PhysicsBody != null) - { - result = node; - } - else - { - foreach (var child in node.ChildNodes) - { - if (ShouldContinueSpecialNodeSearch(child)) - { - var childWithPhysicsBody = FindNodeWithPhysicsBodyHelper(child); - if (childWithPhysicsBody != null) - { - result = childWithPhysicsBody; - } - } - } - } - - return result; - } - - private static SCNNode FindNodeWithGeometryHelper(SCNNode node) - { - SCNNode result = null; - if (node.Geometry != null) - { - result = node; - } - else - { - foreach (var child in node.ChildNodes) - { - if (ShouldContinueSpecialNodeSearch(child)) - { - var childWithGeosBody = FindNodeWithGeometryHelper(child); - if (childWithGeosBody != null) - { - result = childWithGeosBody; - } - } - } - } - - return result; - } - - private static bool ShouldContinueSpecialNodeSearch(SCNNode node) - { - bool result = true; - - // end geo + physics search when a system collection is found - var value = node.ValueForKey(new NSString("isEndpoint")); - if (value != null) - { - if (Convert.ToBoolean(value)) - { - result = false; - } - - } - - return result; - } - - #endregion - - public static SCNNode ParentWithPrefix(this SCNNode node, string prefix) - { - SCNNode result = null; - if (!string.IsNullOrEmpty(node.Name) && node.Name.StartsWith(prefix, StringComparison.Ordinal)) - { - result = node; - } - else if (node.ParentNode != null) - { - result = node.ParentNode.ParentWithPrefix(prefix); - } - - return result; - } - - public static bool HasConstraints(this SCNNode node) - { - var balljoints = FindAllJoints(node, ConstrainHierarchyComponent.JointName); - var hingeJoints = FindAllJoints(node, ConstrainHierarchyComponent.HingeName); - return balljoints.Any() && hingeJoints.Any(); - } - - public static List<SCNNode> FindAllJoints(this SCNNode node, string prefix) - { - var result = new List<SCNNode>(); - - var physicsNode = FindNodeWithPhysicsBody(node); - if (physicsNode != null) - { - // ball joints have the correct prefix and are first generation children of entity node - foreach (var child in physicsNode.ChildNodes) - { - if (!string.IsNullOrEmpty(child.Name) && child.Name.StartsWith(prefix, StringComparison.Ordinal)) - { - result.Add(child); - } - } - } - - return result; - } - - public static Team GetTeam(this SCNNode node) - { - var parent = node.ParentNode; - while (parent != null) - { - if (parent.Name == "_teamA") - { - return Team.TeamA; - } - else if (parent.Name == "_teamB") - { - return Team.TeamB; - } - - parent = parent.ParentNode; - } - - return Team.None; - } - - #region paint mask - - private static readonly string PaintMaskColorKey = "paintMaskColor"; - - /// <summary> - /// Recursively set team color into any nodes that use it - /// </summary> - public static void SetPaintColors(this SCNNode node) - { - var geometry = node?.Geometry; - if (geometry != null) - { - // paintColor can be UIColor or SCNVector4 - var paintColor = node.GetTeam().GetColor(); - - if (geometry.HasUniform(PaintMaskColorKey)) - { - geometry.SetColor(PaintMaskColorKey, paintColor); - } - - var lods = geometry.LevelsOfDetail; - if (lods != null) - { - foreach (var lod in lods) - { - if (lod?.Geometry != null && lod.Geometry.HasUniform(PaintMaskColorKey)) - { - lod.Geometry.SetColor(PaintMaskColorKey, paintColor); - } - } - } - } - - foreach (var child in node.ChildNodes) - { - child.SetPaintColors(); - } - } - - #endregion - - #region copy - - /// <summary> - /// must copy geometry and materials to set unique data on both here we only want - /// </summary> - public static SCNGeometry CopyGeometryAndMaterials(this SCNGeometry geometry) - { - var result = geometry; - if (geometry.Copy() is SCNGeometry geometryCopy) - { - var materialsCopy = new List<SCNMaterial>(); - foreach (var material in geometryCopy.Materials) - { - if (material.Copy() is SCNMaterial materialCopy) - { - materialsCopy.Add(materialCopy); - } - } - - geometryCopy.Materials = materialsCopy.ToArray(); - - result = geometryCopy; - } - - return result; - } - - public static void CopyGeometryAndMaterials(this SCNNode node) - { - // this copies the material, but not the lod - if (node.Geometry != null) - { - node.UpdateGeometry(node.Geometry.CopyGeometryAndMaterials()); - - if (node.Geometry.LevelsOfDetail != null) - { - var lodsNew = new List<SCNLevelOfDetail>(); - foreach (var lod in node.Geometry.LevelsOfDetail) - { - if (lod.Geometry != null) - { - var lodGeometryCopy = lod.Geometry.CopyGeometryAndMaterials(); - lodsNew.Add(SCNLevelOfDetail.CreateWithScreenSpaceRadius(lodGeometryCopy, lod.ScreenSpaceRadius)); - } - } - - node.Geometry.LevelsOfDetail = lodsNew.ToArray(); - } - } - - foreach (var child in node.ChildNodes) - { - child.CopyGeometryAndMaterials(); - } - } - - #endregion - - /// <summary> - /// For lod, set the radius based on a percentage of the screen size - /// </summary> - public static float ComputeScreenSpaceRadius(float screenSpacePercent) - { - // Needs adjusted for screen size, and original bounds of shape - // eventually also look at physical size of device - var screenSize = UIScreen.MainScreen.NativeBounds; // main.bounds - var screenWidth = screenSize.Width; - var screenHeight = screenSize.Height; - var minDimension = (float)(Math.Min(screenWidth, screenHeight)); - - // work in percentages of screen area for low/high-res devices - // 10% of screen size - var screenSpaceDiameter = screenSpacePercent * minDimension; - return screenSpaceDiameter * 0.5f; - } - - public static void FixLevelsOfDetail(this SCNNode node, float screenSpaceRadius, bool showLOD) - { - // find the boundingRadius of the node, and scale to that - var lods = node?.Geometry?.LevelsOfDetail; - if (lods != null) - { - var lodsNew = new List<SCNLevelOfDetail>(); - foreach (var lod in lods) - { - if (lod.Geometry != null) - { - if (showLOD) - { - // visualize the lod - var lodGeometryCopy = lod.Geometry.CopyGeometryAndMaterials(); - - // override the emission - // this is not removed currently - foreach (var material in lodGeometryCopy.Materials) - { - material.Emission.Contents = UIColor.Red; - } - - lodsNew.Add(SCNLevelOfDetail.CreateWithScreenSpaceRadius(lodGeometryCopy, screenSpaceRadius)); - } - else - { - lodsNew.Add(SCNLevelOfDetail.CreateWithScreenSpaceRadius(lod.Geometry, screenSpaceRadius)); - } - } - } - - node.Geometry.LevelsOfDetail = lodsNew.ToArray(); - } - - foreach (var child in node.ChildNodes) - { - child.FixLevelsOfDetail(screenSpaceRadius, showLOD); - } - } - - public static void SetNodeToOccluder(this SCNNode node) - { - var material = SCNMaterialExtensions.Create(UIColor.White); - material.ColorBufferWriteMask = SCNColorMask.None; - material.WritesToDepthBuffer = true; - - if (node.Geometry == null) - { - throw new Exception("Node has no geometry"); - } - - node.Geometry.Materials = new SCNMaterial[] { material }; - node.RenderingOrder = -10; - node.CastsShadow = false; - } - - public static SCNNode LoadSCNAsset(string modelFileName) - { - var assetPaths = new string[] - { - "art.scnassets/models/", - "art.scnassets/blocks/", - "art.scnassets/projectiles/", - "art.scnassets/catapults/", - "art.scnassets/levels/", - "art.scnassets/effects/" - }; - - var assetExtensions = new string[] { "scn", "scnp" }; - - SCNReferenceNode nodeRefSearch = null; - foreach (var path in assetPaths) - { - foreach (var ext in assetExtensions) - { - var url = NSBundle.MainBundle.GetUrlForResource(path + modelFileName, ext); - if (url != null) - { - nodeRefSearch = SCNReferenceNode.CreateFromUrl(url); - if (nodeRefSearch != null) - { - break; - } - } - } - - if (nodeRefSearch != null) - { - break; - } - } - - if (nodeRefSearch != null) - { - // this does the load, default policy is load immediate - nodeRefSearch.Load(); - - // log an error if geo not nested under a physics shape - var node = nodeRefSearch.ChildNodes.FirstOrDefault(); - if (node == null) - { - throw new Exception($"model {modelFileName} has no child nodes"); - } - - if (nodeRefSearch.ChildNodes.Count() > 1) - { - //os_log(.error, "model %s should have a single root node", modelFileName) - } - - // walk down the scenegraph and update all children - node.FixMaterials(); - - return node; - } - else - { - throw new Exception($"couldn't load {modelFileName}"); - } - } - - public static void SetPaintColors(this SCNNode node, Team team) - { - if (node.Geometry != null) - { - // paintColor can be UIColor or SCNVector4 - var paintColor = team.GetColor(); - - if (node.Geometry.HasUniform(PaintMaskColorKey)) - { - node.Geometry.SetColor(PaintMaskColorKey, paintColor); - } - - if (node.Geometry.LevelsOfDetail != null) - { - foreach (var lod in node.Geometry.LevelsOfDetail) - { - if (lod.Geometry != null && lod.Geometry.HasUniform(PaintMaskColorKey)) - { - lod.Geometry.SetColor(PaintMaskColorKey, paintColor); - } - } - } - } - - foreach (var child in node.ChildNodes) - { - child.SetPaintColors(team); - } - } - - #region paint color mask - - /// <summary> - /// until pipeline is ready, use a map of material name to paintMask texture - /// </summary> - private static Dictionary<string, string> PaintColorMaskTextures = new Dictionary<string, string> - { - {"geom_block_boxB", "block_boxBMaterial_PaintMask"}, - {"geom_block_cylinderC", "block_cylinderCMaterial_Paintmask"}, - {"geom_block_halfCylinderA", "block_halfCylinderAMaterial_Paintmask"}, - {"flag_flagA", "flag_flagAMaterial_PaintMask"}, - {"catapultBase", "catapultBase_PaintMask"}, - {"catapultProngs", "catapultBase_PaintMask"}, - {"catapultStrap", "catapultSling_PaintMask"}, - {"catapultStrapInactive", "catapultSling_PaintMask"}, - - {"V", "letters_lettersMaterial_PaintMask"}, - {"I", "letters_lettersMaterial_PaintMask"}, - {"C", "letters_lettersMaterial_PaintMask"}, - {"T", "letters_lettersMaterial_PaintMask"}, - {"O", "letters_lettersMaterial_PaintMask"}, - {"R", "letters_lettersMaterial_PaintMask"}, - {"Y", "letters_lettersMaterial_PaintMask"}, - {"ExclamationPoint", "letters_lettersMaterial_PaintMask"} - }; - - public static void SetupPaintColorMask(this SCNGeometry geometry, string name) - { - // if we've already set it up, don't do it again - if (geometry.ValueForKey(new NSString(PaintMaskColorKey)) == null) - { - if (PaintColorMaskTextures.TryGetValue(name, out string paintMask)) - { - // all textures are absolute paths from the app folder - var texturePath = $"art.scnassets/textures/{paintMask}.ktx"; - - if (name.Contains("catapult")) - { - //os_log(.debug, "visited %s for texture", name) - } - - var surfaceScript = @" + +namespace XamarinShot.Utils { + using Foundation; + using SceneKit; + using XamarinShot.Models; + using XamarinShot.Models.GameplayState; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + + public static class SCNNodeExtensions { + #region game object + + private static Dictionary<SCNNode, GameObject> map = new Dictionary<SCNNode, GameObject> (); + + public static GameObject GetGameObject (this SCNNode node) + { + map.TryGetValue (node, out GameObject @object); + return @object; + } + + public static void SetGameObject (this SCNNode node, GameObject value) + { + if (!map.ContainsKey (node)) { + map.Add (node, value); + } + } + + #endregion + + #region fix materials + + public static void FixMaterials (this SCNNode node) + { + // walk down the scenegraph and update all children + node.FixNormalMaps (); + + // establish paint colors + node.CopyGeometryForPaintColors (); + node.SetPaintColors (); + } + + private static void FixNormalMap (this SCNGeometry geometry) + { + foreach (var material in geometry.Materials) { + var prop = material.Normal; + // astc needs gggr and .ag to compress to L+A, + // but will compress rg01 to RGB single plane (less quality) + // bc/eac/explicit/no compression use rg01 and .rg + // rg01 is easier to see and edit in texture editors + + // set the normal to RED | GREEN (rg01 compression) + // uses single plane on ASTC, dual on BC5/EAC_RG11/Explicit + prop.TextureComponents = SCNColorMask.Red | SCNColorMask.Green; + + // set the normal to ALPHA | GREEN (gggr compression) + // uses dual plane for ASTC, BC3nm + // prop.textureComponents = [.alpha, .green] + } + } + + /// <summary> + /// Fix the normal map reconstruction on scn files for compressed textures + /// </summary> + public static void FixNormalMaps (this SCNNode node) + { + if (node.Geometry != null) { + node.Geometry.FixNormalMap (); + + // these will often just have the same material applied + if (node.Geometry.LevelsOfDetail != null) { + foreach (var lod in node.Geometry.LevelsOfDetail) { + if (lod.Geometry != null) { + lod.Geometry.FixNormalMap (); + } + } + } + } + + foreach (var child in node.ChildNodes) { + child.FixNormalMaps (); + } + } + + // We load all nodes as references which means they share the same + // geometry and materials. For team colors, we need to set geometry overrides + // and so need unique geometry with shadable overrides for each node created. + + public static void CopyGeometryForPaintColors (this SCNNode node) + { + // neutral blocks also need to be tinted + if (node.Geometry != null && !string.IsNullOrEmpty (node.Name)) { + // does this copy the LOD as well ? + if (node.Geometry.Copy () is SCNGeometry geometryCopy) { + SetupPaintColorMask (geometryCopy, node.Name); + + // this may already done by the copy() above, but just be safe + if (node.Geometry.LevelsOfDetail != null) { + var lodsNew = new List<SCNLevelOfDetail> (); + foreach (var lod in node.Geometry.LevelsOfDetail) { + if (lod.Geometry != null) { + if (lod.ScreenSpaceRadius > 0) { + if (lod.Geometry.Copy () is SCNGeometry lodGeometryCopy) { + lodGeometryCopy.SetupPaintColorMask (node.Name); + lodsNew.Add (SCNLevelOfDetail.CreateWithScreenSpaceRadius (lodGeometryCopy, lod.ScreenSpaceRadius)); + } + } else { + if (lod.Geometry.Copy () is SCNGeometry lodGeometryCopy) { + SetupPaintColorMask (lodGeometryCopy, node.Name); + lodsNew.Add (SCNLevelOfDetail.CreateWithWorldSpaceDistance (lodGeometryCopy, lod.WorldSpaceDistance)); + } + } + } + } + + geometryCopy.LevelsOfDetail = lodsNew.ToArray (); + } + + // set the new geometry and LOD + node.UpdateGeometry (geometryCopy); + } + } + + foreach (var child in node.ChildNodes) { + child.CopyGeometryForPaintColors (); + } + } + + public static void UpdateGeometry (this SCNNode node, SCNGeometry geometry) + { + var oldGeometry = node.Geometry; + node.Geometry = geometry; + + oldGeometry.Dispose (); + oldGeometry = null; + } + + #endregion + + public static string GetTypeIdentifier (this SCNNode node) + { + string result = null; + if (!string.IsNullOrEmpty (node.Name) && !node.Name.StartsWith ("_", StringComparison.Ordinal)) { + result = node.Name.Split ('_').FirstOrDefault (); + } + + return result; + } + + public static GameObject NearestParentGameObject (this SCNNode node) + { + var result = GetGameObject (node); + if (result == null) { + if (node.ParentNode != null) { + node.ParentNode.NearestParentGameObject (); + } + } + + return result; + } + + // Returns the size of the horizontal parts of the node's bounding box. + // x is the width, y is the depth. + public static OpenTK.Vector2 GetHorizontalSize (this SCNNode node) + { + var minBox = SCNVector3.Zero; + var maxBox = SCNVector3.Zero; + node.GetBoundingBox (ref minBox, ref maxBox); + + // Scene is y-up, horizontal extent is calculated on x and z + var sceneWidth = Math.Abs (maxBox.X - minBox.X); + var sceneLength = Math.Abs (maxBox.Z - minBox.Z); + return new OpenTK.Vector2 (sceneWidth, sceneLength); + } + + #region find node + + public static SCNNode FindNodeWithPhysicsBody (this SCNNode node) + { + return FindNodeWithPhysicsBodyHelper (node); + } + + public static SCNNode FindNodeWithGeometry (this SCNNode node) + { + return FindNodeWithGeometryHelper (node); + } + + private static SCNNode FindNodeWithPhysicsBodyHelper (SCNNode node) + { + SCNNode result = null; + if (node.PhysicsBody != null) { + result = node; + } else { + foreach (var child in node.ChildNodes) { + if (ShouldContinueSpecialNodeSearch (child)) { + var childWithPhysicsBody = FindNodeWithPhysicsBodyHelper (child); + if (childWithPhysicsBody != null) { + result = childWithPhysicsBody; + } + } + } + } + + return result; + } + + private static SCNNode FindNodeWithGeometryHelper (SCNNode node) + { + SCNNode result = null; + if (node.Geometry != null) { + result = node; + } else { + foreach (var child in node.ChildNodes) { + if (ShouldContinueSpecialNodeSearch (child)) { + var childWithGeosBody = FindNodeWithGeometryHelper (child); + if (childWithGeosBody != null) { + result = childWithGeosBody; + } + } + } + } + + return result; + } + + private static bool ShouldContinueSpecialNodeSearch (SCNNode node) + { + bool result = true; + + // end geo + physics search when a system collection is found + var value = node.ValueForKey (new NSString ("isEndpoint")); + if (value != null) { + if (Convert.ToBoolean (value)) { + result = false; + } + + } + + return result; + } + + #endregion + + public static SCNNode ParentWithPrefix (this SCNNode node, string prefix) + { + SCNNode result = null; + if (!string.IsNullOrEmpty (node.Name) && node.Name.StartsWith (prefix, StringComparison.Ordinal)) { + result = node; + } else if (node.ParentNode != null) { + result = node.ParentNode.ParentWithPrefix (prefix); + } + + return result; + } + + public static bool HasConstraints (this SCNNode node) + { + var balljoints = FindAllJoints (node, ConstrainHierarchyComponent.JointName); + var hingeJoints = FindAllJoints (node, ConstrainHierarchyComponent.HingeName); + return balljoints.Any () && hingeJoints.Any (); + } + + public static List<SCNNode> FindAllJoints (this SCNNode node, string prefix) + { + var result = new List<SCNNode> (); + + var physicsNode = FindNodeWithPhysicsBody (node); + if (physicsNode != null) { + // ball joints have the correct prefix and are first generation children of entity node + foreach (var child in physicsNode.ChildNodes) { + if (!string.IsNullOrEmpty (child.Name) && child.Name.StartsWith (prefix, StringComparison.Ordinal)) { + result.Add (child); + } + } + } + + return result; + } + + public static Team GetTeam (this SCNNode node) + { + var parent = node.ParentNode; + while (parent != null) { + if (parent.Name == "_teamA") { + return Team.TeamA; + } else if (parent.Name == "_teamB") { + return Team.TeamB; + } + + parent = parent.ParentNode; + } + + return Team.None; + } + + #region paint mask + + private static readonly string PaintMaskColorKey = "paintMaskColor"; + + /// <summary> + /// Recursively set team color into any nodes that use it + /// </summary> + public static void SetPaintColors (this SCNNode node) + { + var geometry = node?.Geometry; + if (geometry != null) { + // paintColor can be UIColor or SCNVector4 + var paintColor = node.GetTeam ().GetColor (); + + if (geometry.HasUniform (PaintMaskColorKey)) { + geometry.SetColor (PaintMaskColorKey, paintColor); + } + + var lods = geometry.LevelsOfDetail; + if (lods != null) { + foreach (var lod in lods) { + if (lod?.Geometry != null && lod.Geometry.HasUniform (PaintMaskColorKey)) { + lod.Geometry.SetColor (PaintMaskColorKey, paintColor); + } + } + } + } + + foreach (var child in node.ChildNodes) { + child.SetPaintColors (); + } + } + + #endregion + + #region copy + + /// <summary> + /// must copy geometry and materials to set unique data on both here we only want + /// </summary> + public static SCNGeometry CopyGeometryAndMaterials (this SCNGeometry geometry) + { + var result = geometry; + if (geometry.Copy () is SCNGeometry geometryCopy) { + var materialsCopy = new List<SCNMaterial> (); + foreach (var material in geometryCopy.Materials) { + if (material.Copy () is SCNMaterial materialCopy) { + materialsCopy.Add (materialCopy); + } + } + + geometryCopy.Materials = materialsCopy.ToArray (); + + result = geometryCopy; + } + + return result; + } + + public static void CopyGeometryAndMaterials (this SCNNode node) + { + // this copies the material, but not the lod + if (node.Geometry != null) { + node.UpdateGeometry (node.Geometry.CopyGeometryAndMaterials ()); + + if (node.Geometry.LevelsOfDetail != null) { + var lodsNew = new List<SCNLevelOfDetail> (); + foreach (var lod in node.Geometry.LevelsOfDetail) { + if (lod.Geometry != null) { + var lodGeometryCopy = lod.Geometry.CopyGeometryAndMaterials (); + lodsNew.Add (SCNLevelOfDetail.CreateWithScreenSpaceRadius (lodGeometryCopy, lod.ScreenSpaceRadius)); + } + } + + node.Geometry.LevelsOfDetail = lodsNew.ToArray (); + } + } + + foreach (var child in node.ChildNodes) { + child.CopyGeometryAndMaterials (); + } + } + + #endregion + + /// <summary> + /// For lod, set the radius based on a percentage of the screen size + /// </summary> + public static float ComputeScreenSpaceRadius (float screenSpacePercent) + { + // Needs adjusted for screen size, and original bounds of shape + // eventually also look at physical size of device + var screenSize = UIScreen.MainScreen.NativeBounds; // main.bounds + var screenWidth = screenSize.Width; + var screenHeight = screenSize.Height; + var minDimension = (float) (Math.Min (screenWidth, screenHeight)); + + // work in percentages of screen area for low/high-res devices + // 10% of screen size + var screenSpaceDiameter = screenSpacePercent * minDimension; + return screenSpaceDiameter * 0.5f; + } + + public static void FixLevelsOfDetail (this SCNNode node, float screenSpaceRadius, bool showLOD) + { + // find the boundingRadius of the node, and scale to that + var lods = node?.Geometry?.LevelsOfDetail; + if (lods != null) { + var lodsNew = new List<SCNLevelOfDetail> (); + foreach (var lod in lods) { + if (lod.Geometry != null) { + if (showLOD) { + // visualize the lod + var lodGeometryCopy = lod.Geometry.CopyGeometryAndMaterials (); + + // override the emission + // this is not removed currently + foreach (var material in lodGeometryCopy.Materials) { + material.Emission.Contents = UIColor.Red; + } + + lodsNew.Add (SCNLevelOfDetail.CreateWithScreenSpaceRadius (lodGeometryCopy, screenSpaceRadius)); + } else { + lodsNew.Add (SCNLevelOfDetail.CreateWithScreenSpaceRadius (lod.Geometry, screenSpaceRadius)); + } + } + } + + node.Geometry.LevelsOfDetail = lodsNew.ToArray (); + } + + foreach (var child in node.ChildNodes) { + child.FixLevelsOfDetail (screenSpaceRadius, showLOD); + } + } + + public static void SetNodeToOccluder (this SCNNode node) + { + var material = SCNMaterialExtensions.Create (UIColor.White); + material.ColorBufferWriteMask = SCNColorMask.None; + material.WritesToDepthBuffer = true; + + if (node.Geometry == null) { + throw new Exception ("Node has no geometry"); + } + + node.Geometry.Materials = new SCNMaterial [] { material }; + node.RenderingOrder = -10; + node.CastsShadow = false; + } + + public static SCNNode LoadSCNAsset (string modelFileName) + { + var assetPaths = new string [] + { + "art.scnassets/models/", + "art.scnassets/blocks/", + "art.scnassets/projectiles/", + "art.scnassets/catapults/", + "art.scnassets/levels/", + "art.scnassets/effects/" + }; + + var assetExtensions = new string [] { "scn", "scnp" }; + + SCNReferenceNode nodeRefSearch = null; + foreach (var path in assetPaths) { + foreach (var ext in assetExtensions) { + var url = NSBundle.MainBundle.GetUrlForResource (path + modelFileName, ext); + if (url != null) { + nodeRefSearch = SCNReferenceNode.CreateFromUrl (url); + if (nodeRefSearch != null) { + break; + } + } + } + + if (nodeRefSearch != null) { + break; + } + } + + if (nodeRefSearch != null) { + // this does the load, default policy is load immediate + nodeRefSearch.Load (); + + // log an error if geo not nested under a physics shape + var node = nodeRefSearch.ChildNodes.FirstOrDefault (); + if (node == null) { + throw new Exception ($"model {modelFileName} has no child nodes"); + } + + if (nodeRefSearch.ChildNodes.Count () > 1) { + //os_log(.error, "model %s should have a single root node", modelFileName) + } + + // walk down the scenegraph and update all children + node.FixMaterials (); + + return node; + } else { + throw new Exception ($"couldn't load {modelFileName}"); + } + } + + public static void SetPaintColors (this SCNNode node, Team team) + { + if (node.Geometry != null) { + // paintColor can be UIColor or SCNVector4 + var paintColor = team.GetColor (); + + if (node.Geometry.HasUniform (PaintMaskColorKey)) { + node.Geometry.SetColor (PaintMaskColorKey, paintColor); + } + + if (node.Geometry.LevelsOfDetail != null) { + foreach (var lod in node.Geometry.LevelsOfDetail) { + if (lod.Geometry != null && lod.Geometry.HasUniform (PaintMaskColorKey)) { + lod.Geometry.SetColor (PaintMaskColorKey, paintColor); + } + } + } + } + + foreach (var child in node.ChildNodes) { + child.SetPaintColors (team); + } + } + + #region paint color mask + + /// <summary> + /// until pipeline is ready, use a map of material name to paintMask texture + /// </summary> + private static Dictionary<string, string> PaintColorMaskTextures = new Dictionary<string, string> + { + {"geom_block_boxB", "block_boxBMaterial_PaintMask"}, + {"geom_block_cylinderC", "block_cylinderCMaterial_Paintmask"}, + {"geom_block_halfCylinderA", "block_halfCylinderAMaterial_Paintmask"}, + {"flag_flagA", "flag_flagAMaterial_PaintMask"}, + {"catapultBase", "catapultBase_PaintMask"}, + {"catapultProngs", "catapultBase_PaintMask"}, + {"catapultStrap", "catapultSling_PaintMask"}, + {"catapultStrapInactive", "catapultSling_PaintMask"}, + + {"V", "letters_lettersMaterial_PaintMask"}, + {"I", "letters_lettersMaterial_PaintMask"}, + {"C", "letters_lettersMaterial_PaintMask"}, + {"T", "letters_lettersMaterial_PaintMask"}, + {"O", "letters_lettersMaterial_PaintMask"}, + {"R", "letters_lettersMaterial_PaintMask"}, + {"Y", "letters_lettersMaterial_PaintMask"}, + {"ExclamationPoint", "letters_lettersMaterial_PaintMask"} + }; + + public static void SetupPaintColorMask (this SCNGeometry geometry, string name) + { + // if we've already set it up, don't do it again + if (geometry.ValueForKey (new NSString (PaintMaskColorKey)) == null) { + if (PaintColorMaskTextures.TryGetValue (name, out string paintMask)) { + // all textures are absolute paths from the app folder + var texturePath = $"art.scnassets/textures/{paintMask}.ktx"; + + if (name.Contains ("catapult")) { + //os_log(.debug, "visited %s for texture", name) + } + + var surfaceScript = @" #pragma arguments texture2d<float> paintMaskTexture; @@ -667,96 +578,82 @@ public static void SetupPaintColorMask(this SCNGeometry geometry, string name) _surface.diffuse.rgb = mix(_surface.diffuse.rgb, paintMaskColor.rgb, paintMaskSelector); "; - geometry.ShaderModifiers = new SCNShaderModifiers() { EntryPointSurface = surfaceScript }; - - // mask pro - var prop = SCNMaterialProperty.Create(new NSString(texturePath)); - prop.MinificationFilter = SCNFilterMode.Linear; - prop.MagnificationFilter = SCNFilterMode.Nearest; - prop.MipFilter = SCNFilterMode.Nearest; - prop.MaxAnisotropy = 1; - - // set the uniforms, these will be overridden in the runtime - geometry.SetTexture("paintMaskTexture", prop); - geometry.SetFloat4(PaintMaskColorKey, SCNVector4.One); - } - } - } - - #endregion - - #region animations - - public static void PlayAllAnimations(this SCNNode node) - { - node.EnumerateChildNodes((SCNNode child, out bool stop) => - { - stop = false; - foreach (var key in child.GetAnimationKeys()) - { - var animationPlayer = child.GetAnimationPlayer(key); - if (animationPlayer != null) - { - animationPlayer.Play(); - } - } - }); - } - - public static void StopAllAnimations(this SCNNode node) - { - node.EnumerateChildNodes((SCNNode child, out bool stop) => - { - stop = false; - foreach (var key in child.GetAnimationKeys()) - { - var animationPlayer = child.GetAnimationPlayer(key); - if (animationPlayer != null) - { - animationPlayer.Stop(); - } - } - }); - } - - #endregion - - public static void CalculateMassFromDensity(this SCNNode node, string name, float density) - { - if (node.PhysicsBody != null) - { - // our naming convention lets us parse the shape geometry - var boundingBoxMin = SCNVector3.Zero; - var boundingBoxMax = SCNVector3.Zero; - node.GetBoundingBox(ref boundingBoxMin, ref boundingBoxMax); - var bounds = (boundingBoxMax - boundingBoxMin); - // calculate as a cylinder going up - if (node.Name.StartsWith("block_cylinder", StringComparison.Ordinal)) - { - var radius = bounds.X / 2f; - var mass = (float)Math.PI * radius * radius * bounds.Y; - node.PhysicsBody.Mass = density * mass; - } - else if (node.Name.StartsWith("block_halfCylinder", StringComparison.Ordinal)) - { - // half cylinder going up - var radius = Math.Min(bounds.X, bounds.Z); - var mass = (float)Math.PI * radius * radius * bounds.Y / 2f; - node.PhysicsBody.Mass = density * mass; - } - else if (node.Name.StartsWith("block_quarterCylinder", StringComparison.Ordinal)) - { - // this is a cylinder lying sideways - var radius = Math.Min(bounds.Y, bounds.Z); - var mass = (float)Math.PI * radius * radius * bounds.X / 4f; - node.PhysicsBody.Mass = density * mass; - } - else - { - // for now, treat as box shape - node.PhysicsBody.Mass = density * bounds.X * bounds.Y * bounds.Z; - } - } - } - } -} \ No newline at end of file + geometry.ShaderModifiers = new SCNShaderModifiers () { EntryPointSurface = surfaceScript }; + + // mask pro + var prop = SCNMaterialProperty.Create (new NSString (texturePath)); + prop.MinificationFilter = SCNFilterMode.Linear; + prop.MagnificationFilter = SCNFilterMode.Nearest; + prop.MipFilter = SCNFilterMode.Nearest; + prop.MaxAnisotropy = 1; + + // set the uniforms, these will be overridden in the runtime + geometry.SetTexture ("paintMaskTexture", prop); + geometry.SetFloat4 (PaintMaskColorKey, SCNVector4.One); + } + } + } + + #endregion + + #region animations + + public static void PlayAllAnimations (this SCNNode node) + { + node.EnumerateChildNodes ((SCNNode child, out bool stop) => { + stop = false; + foreach (var key in child.GetAnimationKeys ()) { + var animationPlayer = child.GetAnimationPlayer (key); + if (animationPlayer != null) { + animationPlayer.Play (); + } + } + }); + } + + public static void StopAllAnimations (this SCNNode node) + { + node.EnumerateChildNodes ((SCNNode child, out bool stop) => { + stop = false; + foreach (var key in child.GetAnimationKeys ()) { + var animationPlayer = child.GetAnimationPlayer (key); + if (animationPlayer != null) { + animationPlayer.Stop (); + } + } + }); + } + + #endregion + + public static void CalculateMassFromDensity (this SCNNode node, string name, float density) + { + if (node.PhysicsBody != null) { + // our naming convention lets us parse the shape geometry + var boundingBoxMin = SCNVector3.Zero; + var boundingBoxMax = SCNVector3.Zero; + node.GetBoundingBox (ref boundingBoxMin, ref boundingBoxMax); + var bounds = (boundingBoxMax - boundingBoxMin); + // calculate as a cylinder going up + if (node.Name.StartsWith ("block_cylinder", StringComparison.Ordinal)) { + var radius = bounds.X / 2f; + var mass = (float) Math.PI * radius * radius * bounds.Y; + node.PhysicsBody.Mass = density * mass; + } else if (node.Name.StartsWith ("block_halfCylinder", StringComparison.Ordinal)) { + // half cylinder going up + var radius = Math.Min (bounds.X, bounds.Z); + var mass = (float) Math.PI * radius * radius * bounds.Y / 2f; + node.PhysicsBody.Mass = density * mass; + } else if (node.Name.StartsWith ("block_quarterCylinder", StringComparison.Ordinal)) { + // this is a cylinder lying sideways + var radius = Math.Min (bounds.Y, bounds.Z); + var mass = (float) Math.PI * radius * radius * bounds.X / 4f; + node.PhysicsBody.Mass = density * mass; + } else { + // for now, treat as box shape + node.PhysicsBody.Mass = density * bounds.X * bounds.Y * bounds.Z; + } + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/SCNShadableExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/SCNShadableExtensions.cs index c730565c9..98bdb94b7 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/SCNShadableExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/SCNShadableExtensions.cs @@ -1,38 +1,36 @@ - -namespace XamarinShot.Utils -{ - using Foundation; - using SceneKit; - using UIKit; - public static class SCNShadableExtensions - { - // https://developer.apple.com/documentation/scenekit/scnshadable#1654834 - // Some of these can be animated inside of an SCNTransaction. - // Sets shader modifier data onto a material or all materials in a geometry. - public static void SetTexture(this SCNGeometry geometry, string uniform, SCNMaterialProperty texture) - { - // this must be the texture name, and not the sampler name - geometry.SetValueForKey(texture, new NSString(uniform)); - } +namespace XamarinShot.Utils { + using Foundation; + using SceneKit; + using UIKit; - public static void SetFloat4(this SCNGeometry geometry, string uniform, SCNVector4 value) - { - geometry.SetValueForKey(NSValue.FromVector(value), new NSString(uniform)); - } + public static class SCNShadableExtensions { + // https://developer.apple.com/documentation/scenekit/scnshadable#1654834 + // Some of these can be animated inside of an SCNTransaction. + // Sets shader modifier data onto a material or all materials in a geometry. + public static void SetTexture (this SCNGeometry geometry, string uniform, SCNMaterialProperty texture) + { + // this must be the texture name, and not the sampler name + geometry.SetValueForKey (texture, new NSString (uniform)); + } - public static void SetColor(this SCNGeometry geometry, string uniform, UIColor value) - { - geometry.SetValueForKey(value, new NSString(uniform)); - } + public static void SetFloat4 (this SCNGeometry geometry, string uniform, SCNVector4 value) + { + geometry.SetValueForKey (NSValue.FromVector (value), new NSString (uniform)); + } - #region getters + public static void SetColor (this SCNGeometry geometry, string uniform, UIColor value) + { + geometry.SetValueForKey (value, new NSString (uniform)); + } - public static bool HasUniform(this SCNGeometry geometry, string uniform) - { - return geometry.ValueForKey(new NSString(uniform)) != null; - } + #region getters - #endregion - } -} \ No newline at end of file + public static bool HasUniform (this SCNGeometry geometry, string uniform) + { + return geometry.ValueForKey (new NSString (uniform)) != null; + } + + #endregion + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/SimdExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/SimdExtensions.cs index a7440005c..d1662e99e 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/SimdExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/SimdExtensions.cs @@ -1,204 +1,198 @@ - -namespace XamarinShot.Utils -{ - using SceneKit; - using System; - using System.Collections.Generic; - using UIKit; - - public static class SimdExtensions - { - public static SCNMatrix4 SetTranslation(this SCNMatrix4 matrix, OpenTK.Vector3 value) - { - // only for column-major matrixes - matrix.M14 = value.X; - matrix.M24 = value.Y; - matrix.M34 = value.Z; - matrix.M44 = 1f; - - return matrix; - } - - public static SCNVector3 GetTranslation(this OpenTK.NMatrix4 matrix) - { - // only for column-major matrixes - return matrix.Column3.Xyz; - } - - public static SCNVector3 GetTranslation(this SCNMatrix4 matrix) - { - // only for column-major matrixes - return matrix.Column3.Xyz; - } - - public static bool HasNaN(this SCNVector4 self) - { - return float.IsNaN(self.X) || float.IsNaN(self.Y) || float.IsNaN(self.Z) || float.IsNaN(self.W); - } - - public static bool HasNaN(this SCNVector3 vector) - { - return float.IsNaN(vector.X) || float.IsNaN(vector.Y) || float.IsNaN(vector.Z); - } - - public static bool AlmostEqual(this SCNVector3 self, SCNVector3 value, float tolerance) - { - return (self - value).Length <= tolerance; - } - - public static bool AlmostEqual(this SCNVector4 self, SCNVector4 value, float tolerance) - { - return (self - value).Length <= tolerance; - } - - public static SCNMatrix4 CreateFromScale(SCNVector3 vector) - { - return new SCNMatrix4(new SCNVector4(vector.X, 0, 0, 0), - new SCNVector4(0, vector.Y, 0, 0), - new SCNVector4(0, 0, vector.Z, 0), - SCNVector4.UnitW); - } - - public static SCNMatrix4 CreateFromScale(float factor) - { - return SimdExtensions.CreateFromScale(new SCNVector3(factor, factor, factor)); - } - - public static SCNVector4 CreateVector4(UIColor color) - { - color.GetRGBA(out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha); - return new SCNVector4((float)red, (float)green, (float)blue, (float)alpha); - } - - public static SCNMatrix4 Normalize(this SCNMatrix4 matrix) - { - // for row-major matrixes only - var normalized = matrix; - - var row0 = SCNVector4.Normalize(matrix.Row0); - var row1 = SCNVector4.Normalize(matrix.Row1); - var row2 = SCNVector4.Normalize(matrix.Row2); - - normalized.Row0 = row0; - normalized.Row1 = row1; - normalized.Row2 = row2; - - return normalized; - } - - public static SCNVector3 Reduce(this IList<SCNVector3> items, SCNVector3 initialResult) - { - foreach (var item in items) - { - initialResult += item; - } - - return initialResult; - } - - public static SCNMatrix4 ToSCNMatrix4(this OpenTK.NMatrix4 self) - { - return new SCNMatrix4(self.Row0, self.Row1, self.Row2, self.Row3); - } - - public static OpenTK.NMatrix4 ToNMatrix4(this SCNMatrix4 self) - { - return new OpenTK.NMatrix4((OpenTK.Vector4)self.Row0, (OpenTK.Vector4)self.Row1, (OpenTK.Vector4)self.Row2, (OpenTK.Vector4)self.Row3); - } - - public static SCNVector3 ToSCNVector3(this OpenTK.NVector3 self) - { - return new SCNVector3(self.X, self.Y, self.Z); - } - - public static SCNVector3 Mix(SCNVector3 x, SCNVector3 y, SCNVector3 t) - { - return x + SCNVector3.Multiply(t, y - x); - } - - public static SCNVector4 Multiply(this SCNMatrix4 matrix, SCNVector4 vector) - { - var x = matrix.Column0.X * vector.X; - var y = matrix.Column0.Y * vector.X; - var z = matrix.Column0.Z * vector.X; - var w = matrix.Column0.W * vector.X; - - x += matrix.Column1.X * vector.Y; - y += matrix.Column1.Y * vector.Y; - z += matrix.Column1.Z * vector.Y; - w += matrix.Column1.W * vector.Y; - - x += matrix.Column2.X * vector.Z; - y += matrix.Column2.Y * vector.Z; - z += matrix.Column2.Z * vector.Z; - w += matrix.Column2.W * vector.Z; - - x += matrix.Column3.X * vector.W; - y += matrix.Column3.Y * vector.W; - z += matrix.Column3.Z * vector.W; - w += matrix.Column3.W * vector.W; - - return new SCNVector4(x, y, z, w); - } - - public static SCNQuaternion Divide(this SCNQuaternion left, SCNQuaternion right) - { - return SCNQuaternion.Multiply(left, SCNQuaternion.Invert(right)); - } - - public static OpenTK.Quaternion ToQuaternion(this SCNQuaternion self) - { - return new OpenTK.Quaternion(self.X, self.Y, self.Z, self.W); - } - - public static SCNVector4 GetVector(this SCNQuaternion self) - { - return new SCNVector4(self.Xyz, self.W); - } - - public static SCNVector3 Act(this SCNQuaternion self, SCNVector3 vector) - { - // Calculate the resulting vector using the Hamilton product - // P' = RPR' - // P = [0, p1, p2, p2] < -- vector - // R = [w, x, y, z] < -- rotation - // R' = [w, -x, -y, -z] - - var p = new SCNQuaternion(vector, 0f); - var r = self; - var rt = r; - rt.Conjugate(); - - return SCNQuaternion.Multiply(SCNQuaternion.Multiply(r, p), rt).Xyz; - } - - public static SCNQuaternion CreateQuaternion(SCNVector3 v1, SCNVector3 v2) - { - var a = SCNVector3.Cross(v1, v2); - var w = (float)Math.Sqrt(v1.LengthSquared * v2.LengthSquared) + SCNVector3.Dot(v1, v2); - var result = new SCNQuaternion(a.X, a.Y, a.Z, w); - result.Normalize(); - - return result; - } - - public static SCNQuaternion CreateQuaternion(SCNMatrix4 matrix) - { - //http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ - float w, x, y, z; - - var t = matrix.M11 + matrix.M22 + matrix.M33 + 1f; - if (t > 0) - { - var s = 0.5f / (float)Math.Sqrt(t); - w = 0.25f / s; - x = (matrix.M32 - matrix.M23) * s; - y = (matrix.M13 - matrix.M31) * s; - z = (matrix.M21 - matrix.M12) * s; - } - else - { - /*var tr = matrix.M11 + matrix.M22 + matrix.M33; + +namespace XamarinShot.Utils { + using SceneKit; + using System; + using System.Collections.Generic; + using UIKit; + + public static class SimdExtensions { + public static SCNMatrix4 SetTranslation (this SCNMatrix4 matrix, OpenTK.Vector3 value) + { + // only for column-major matrixes + matrix.M14 = value.X; + matrix.M24 = value.Y; + matrix.M34 = value.Z; + matrix.M44 = 1f; + + return matrix; + } + + public static SCNVector3 GetTranslation (this OpenTK.NMatrix4 matrix) + { + // only for column-major matrixes + return matrix.Column3.Xyz; + } + + public static SCNVector3 GetTranslation (this SCNMatrix4 matrix) + { + // only for column-major matrixes + return matrix.Column3.Xyz; + } + + public static bool HasNaN (this SCNVector4 self) + { + return float.IsNaN (self.X) || float.IsNaN (self.Y) || float.IsNaN (self.Z) || float.IsNaN (self.W); + } + + public static bool HasNaN (this SCNVector3 vector) + { + return float.IsNaN (vector.X) || float.IsNaN (vector.Y) || float.IsNaN (vector.Z); + } + + public static bool AlmostEqual (this SCNVector3 self, SCNVector3 value, float tolerance) + { + return (self - value).Length <= tolerance; + } + + public static bool AlmostEqual (this SCNVector4 self, SCNVector4 value, float tolerance) + { + return (self - value).Length <= tolerance; + } + + public static SCNMatrix4 CreateFromScale (SCNVector3 vector) + { + return new SCNMatrix4 (new SCNVector4 (vector.X, 0, 0, 0), + new SCNVector4 (0, vector.Y, 0, 0), + new SCNVector4 (0, 0, vector.Z, 0), + SCNVector4.UnitW); + } + + public static SCNMatrix4 CreateFromScale (float factor) + { + return SimdExtensions.CreateFromScale (new SCNVector3 (factor, factor, factor)); + } + + public static SCNVector4 CreateVector4 (UIColor color) + { + color.GetRGBA (out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha); + return new SCNVector4 ((float) red, (float) green, (float) blue, (float) alpha); + } + + public static SCNMatrix4 Normalize (this SCNMatrix4 matrix) + { + // for row-major matrixes only + var normalized = matrix; + + var row0 = SCNVector4.Normalize (matrix.Row0); + var row1 = SCNVector4.Normalize (matrix.Row1); + var row2 = SCNVector4.Normalize (matrix.Row2); + + normalized.Row0 = row0; + normalized.Row1 = row1; + normalized.Row2 = row2; + + return normalized; + } + + public static SCNVector3 Reduce (this IList<SCNVector3> items, SCNVector3 initialResult) + { + foreach (var item in items) { + initialResult += item; + } + + return initialResult; + } + + public static SCNMatrix4 ToSCNMatrix4 (this OpenTK.NMatrix4 self) + { + return new SCNMatrix4 (self.Row0, self.Row1, self.Row2, self.Row3); + } + + public static OpenTK.NMatrix4 ToNMatrix4 (this SCNMatrix4 self) + { + return new OpenTK.NMatrix4 ((OpenTK.Vector4) self.Row0, (OpenTK.Vector4) self.Row1, (OpenTK.Vector4) self.Row2, (OpenTK.Vector4) self.Row3); + } + + public static SCNVector3 ToSCNVector3 (this OpenTK.NVector3 self) + { + return new SCNVector3 (self.X, self.Y, self.Z); + } + + public static SCNVector3 Mix (SCNVector3 x, SCNVector3 y, SCNVector3 t) + { + return x + SCNVector3.Multiply (t, y - x); + } + + public static SCNVector4 Multiply (this SCNMatrix4 matrix, SCNVector4 vector) + { + var x = matrix.Column0.X * vector.X; + var y = matrix.Column0.Y * vector.X; + var z = matrix.Column0.Z * vector.X; + var w = matrix.Column0.W * vector.X; + + x += matrix.Column1.X * vector.Y; + y += matrix.Column1.Y * vector.Y; + z += matrix.Column1.Z * vector.Y; + w += matrix.Column1.W * vector.Y; + + x += matrix.Column2.X * vector.Z; + y += matrix.Column2.Y * vector.Z; + z += matrix.Column2.Z * vector.Z; + w += matrix.Column2.W * vector.Z; + + x += matrix.Column3.X * vector.W; + y += matrix.Column3.Y * vector.W; + z += matrix.Column3.Z * vector.W; + w += matrix.Column3.W * vector.W; + + return new SCNVector4 (x, y, z, w); + } + + public static SCNQuaternion Divide (this SCNQuaternion left, SCNQuaternion right) + { + return SCNQuaternion.Multiply (left, SCNQuaternion.Invert (right)); + } + + public static OpenTK.Quaternion ToQuaternion (this SCNQuaternion self) + { + return new OpenTK.Quaternion (self.X, self.Y, self.Z, self.W); + } + + public static SCNVector4 GetVector (this SCNQuaternion self) + { + return new SCNVector4 (self.Xyz, self.W); + } + + public static SCNVector3 Act (this SCNQuaternion self, SCNVector3 vector) + { + // Calculate the resulting vector using the Hamilton product + // P' = RPR' + // P = [0, p1, p2, p2] < -- vector + // R = [w, x, y, z] < -- rotation + // R' = [w, -x, -y, -z] + + var p = new SCNQuaternion (vector, 0f); + var r = self; + var rt = r; + rt.Conjugate (); + + return SCNQuaternion.Multiply (SCNQuaternion.Multiply (r, p), rt).Xyz; + } + + public static SCNQuaternion CreateQuaternion (SCNVector3 v1, SCNVector3 v2) + { + var a = SCNVector3.Cross (v1, v2); + var w = (float) Math.Sqrt (v1.LengthSquared * v2.LengthSquared) + SCNVector3.Dot (v1, v2); + var result = new SCNQuaternion (a.X, a.Y, a.Z, w); + result.Normalize (); + + return result; + } + + public static SCNQuaternion CreateQuaternion (SCNMatrix4 matrix) + { + //http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ + float w, x, y, z; + + var t = matrix.M11 + matrix.M22 + matrix.M33 + 1f; + if (t > 0) { + var s = 0.5f / (float) Math.Sqrt (t); + w = 0.25f / s; + x = (matrix.M32 - matrix.M23) * s; + y = (matrix.M13 - matrix.M31) * s; + z = (matrix.M21 - matrix.M12) * s; + } else { + /*var tr = matrix.M11 + matrix.M22 + matrix.M33; if (tr > 0) { var s = (float)Math.Sqrt(tr + 1) * 2f; @@ -208,33 +202,28 @@ public static SCNQuaternion CreateQuaternion(SCNMatrix4 matrix) z = (matrix.M21 - matrix.M12) * s; } else*/ - if (matrix.M11 > matrix.M22 && matrix.M11 > matrix.M33) - { - var s = (float)Math.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33) * 2f; // S=4*qx - w = (matrix.M32 - matrix.M23) / s; - x = 0.25f * s; - y = (matrix.M12 + matrix.M21) / s; - z = (matrix.M13 + matrix.M31) / s; - } - else if (matrix.M22 > matrix.M33) - { - var s = (float)Math.Sqrt(1f + matrix.M22 - matrix.M11 - matrix.M33) * 2f; // S=4*qy - w = (matrix.M13 - matrix.M31) / s; - x = (matrix.M12 + matrix.M21) / s; - y = 0.25f * s; - z = (matrix.M23 + matrix.M32) / s; - } - else - { - var s = (float)Math.Sqrt(1f + matrix.M33 - matrix.M11 - matrix.M22) * 2f; // S=4*qz - w = (matrix.M21 - matrix.M12) / s; - x = (matrix.M13 + matrix.M31) / s; - y = (matrix.M23 + matrix.M32) / s; - z = 0.25f * s; - } - } - - return new SCNQuaternion(x, y, z, w); - } - } -} \ No newline at end of file + if (matrix.M11 > matrix.M22 && matrix.M11 > matrix.M33) { + var s = (float) Math.Sqrt (1f + matrix.M11 - matrix.M22 - matrix.M33) * 2f; // S=4*qx + w = (matrix.M32 - matrix.M23) / s; + x = 0.25f * s; + y = (matrix.M12 + matrix.M21) / s; + z = (matrix.M13 + matrix.M31) / s; + } else if (matrix.M22 > matrix.M33) { + var s = (float) Math.Sqrt (1f + matrix.M22 - matrix.M11 - matrix.M33) * 2f; // S=4*qy + w = (matrix.M13 - matrix.M31) / s; + x = (matrix.M12 + matrix.M21) / s; + y = 0.25f * s; + z = (matrix.M23 + matrix.M32) / s; + } else { + var s = (float) Math.Sqrt (1f + matrix.M33 - matrix.M11 - matrix.M22) * 2f; // S=4*qz + w = (matrix.M21 - matrix.M12) / s; + x = (matrix.M13 + matrix.M31) / s; + y = (matrix.M23 + matrix.M32) / s; + z = 0.25f * s; + } + } + + return new SCNQuaternion (x, y, z, w); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/UIViewExtensions.cs b/ios12/XamarinShot/XamarinShot/Utils/UIViewExtensions.cs index 3817bb06b..af055f63c 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/UIViewExtensions.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/UIViewExtensions.cs @@ -1,37 +1,28 @@ - -namespace XamarinShot.Utils -{ - using System; - using UIKit; - /// <summary> - /// Convenience extension for animation on UIView. - /// </summary> - public static class UIViewExtensions - { - public static void FadeInFadeOut(this UIView view, double duration) - { - UIView.AnimateNotify(duration, 0d, UIViewAnimationOptions.CurveEaseIn, () => - { - view.Alpha = 1f; - }, (finished) => - { - if (finished) - { - view.Hidden = false; - UIView.Animate(duration, 1d, UIViewAnimationOptions.CurveEaseIn, () => - { - view.Alpha = 0f; - }, () => - { - view.Hidden = true; - }); - } - else - { - view.Hidden = true; - } - }); - } - } -} \ No newline at end of file +namespace XamarinShot.Utils { + using System; + using UIKit; + + /// <summary> + /// Convenience extension for animation on UIView. + /// </summary> + public static class UIViewExtensions { + public static void FadeInFadeOut (this UIView view, double duration) + { + UIView.AnimateNotify (duration, 0d, UIViewAnimationOptions.CurveEaseIn, () => { + view.Alpha = 1f; + }, (finished) => { + if (finished) { + view.Hidden = false; + UIView.Animate (duration, 1d, UIViewAnimationOptions.CurveEaseIn, () => { + view.Alpha = 0f; + }, () => { + view.Hidden = true; + }); + } else { + view.Hidden = true; + } + }); + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/UserDefaults.cs b/ios12/XamarinShot/XamarinShot/Utils/UserDefaults.cs index d39f75fa3..e40ee81d8 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/UserDefaults.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/UserDefaults.cs @@ -1,487 +1,374 @@ - -namespace XamarinShot.Utils -{ - using Foundation; - using MultipeerConnectivity; - using XamarinShot.Models; - using XamarinShot.Models.Enums; - using System.Collections.Generic; - using UIKit; - - public static class UserDefaults - { - public static Dictionary<string, object> ApplicationDefaults = new Dictionary<string, object> - { - { UserDefaultsKeys.Spectator, false }, - { UserDefaultsKeys.MusicVolume, 0f }, - { UserDefaultsKeys.EffectsVolume, 1f }, - { UserDefaultsKeys.AntialiasingMode, true}, - { UserDefaultsKeys.UseEncryption, true}, - { UserDefaultsKeys.GameRoomMode, false}, - { UserDefaultsKeys.AutoFocus, true}, - { UserDefaultsKeys.AllowGameBoardAutoSize, false}, - { UserDefaultsKeys.ShowReset, false}, - { UserDefaultsKeys.ShowFlags, true}, - { UserDefaultsKeys.ShowClouds, false}, - { UserDefaultsKeys.SynchronizeMusicWithWallClock, true}, - { UserDefaultsKeys.ShowRopeSimulation, true}, - { UserDefaultsKeys.ShowThermalState, true}, - { UserDefaultsKeys.ShowProjectileTrail, true}, - { UserDefaultsKeys.TrailShouldNarrow, true }, - }; - - public static Player Myself - { - get - { - Player result = null; - if (NSUserDefaults.StandardUserDefaults[UserDefaultsKeys.PeerID] is NSData data) - { - if (NSKeyedUnarchiver.GetUnarchivedObject(typeof(MCPeerID), data, out NSError error) is MCPeerID peerID) - { - result = new Player(peerID); - } - } - - if (result == null) - { - // if no playerID was previously selected, create and cache a new one. - result = new Player(UIDevice.CurrentDevice.Name); - // update inner value - Myself = result; - } - - return result; - } - - set - { - var data = NSKeyedArchiver.ArchivedDataWithRootObject(value.PeerId, true, out NSError archivedError); - NSUserDefaults.StandardUserDefaults[UserDefaultsKeys.PeerID] = NSObject.FromObject(data); - } - } - - public static float MusicVolume - { - get - { - - return NSUserDefaults.StandardUserDefaults.FloatForKey(UserDefaultsKeys.MusicVolume); - } - set - { - NSUserDefaults.StandardUserDefaults.SetFloat(value, UserDefaultsKeys.MusicVolume); - } - } - - public static float EffectsVolume - { - get - { - - return NSUserDefaults.StandardUserDefaults.FloatForKey(UserDefaultsKeys.EffectsVolume); - } - set - { - NSUserDefaults.StandardUserDefaults.SetFloat(value, UserDefaultsKeys.EffectsVolume); - } - } - - public static bool ShowARDebug - { - get - { - - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowARDebug); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowARDebug); - } - } - - public static bool ShowSceneViewStats - { - get - { - - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowSceneViewStats); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowSceneViewStats); - } - } - - /// <summary> - /// This is a wireframe overlay for looking at poly-count (f.e. LOD) - /// </summary> - public static bool ShowWireframe - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowWireframe); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowWireframe); - } - } - - /// <summary> - /// This turns shapes emissive channel red (set at level start) - /// </summary> - public static bool ShowLOD - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowLOD); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowLOD); - } - } - - /// <summary> - /// This may need to be integer for 0, 2, 4x - /// </summary> - public static bool AntialiasingMode - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.AntialiasingMode); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.AntialiasingMode); - } - } - - public static bool ShowTrackingState - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowTrackingState); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowTrackingState); - } - } - - public static GameLevel SelectedLevel - { - get - { - var levelName = NSUserDefaults.StandardUserDefaults.StringForKey(UserDefaultsKeys.SelectedLevel); - if (!string.IsNullOrEmpty(levelName)) - { - var level = GameLevel.Level(levelName); - return level ?? GameLevel.DefaultLevel; - } - else - { - return GameLevel.DefaultLevel; - } - } - set - { - NSUserDefaults.StandardUserDefaults.SetString(value.Name, UserDefaultsKeys.SelectedLevel); - } - } - - public static bool ShowPhysicsDebug - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowPhysicsDebug); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowPhysicsDebug); - } - } - - public static bool ShowNetworkDebug - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowNetworkDebug); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowNetworkDebug); - } - } - - public static bool HasOnboarded - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.HasOnboarded); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.HasOnboarded); - } - } - - public static BoardLocatingMode BoardLocatingMode - { - get - { - var value = NSUserDefaults.StandardUserDefaults.IntForKey(UserDefaultsKeys.BoardLocatingMode); - return (BoardLocatingMode)(int)value; - } - set - { - NSUserDefaults.StandardUserDefaults.SetInt((int)value, UserDefaultsKeys.BoardLocatingMode); - } - } - - public static bool GameRoomMode - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.GameRoomMode); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.GameRoomMode); - } - } - - public static bool UseEncryption - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.UseEncryption); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.UseEncryption); - } - } - - public static bool ShowSettingsInGame - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowSettingsInGame); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowSettingsInGame); - } - } - - public static bool ShowARRelocalizationHelp - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowARRelocalizationHelp); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowARRelocalizationHelp); - } - } - - public static int? TrailLength - { - get - { - var value = NSUserDefaults.StandardUserDefaults[UserDefaultsKeys.TrailLength] as NSNumber; - return value?.Int32Value; - } - set - { - if (value.HasValue) - { - NSUserDefaults.StandardUserDefaults.SetInt(value.Value, UserDefaultsKeys.TrailLength); - } - else - { - NSUserDefaults.StandardUserDefaults.RemoveObject(UserDefaultsKeys.TrailLength); - } - } - } - - public static float? TrailWidth - { - get - { - var value = NSUserDefaults.StandardUserDefaults[UserDefaultsKeys.TrailWidth] as NSNumber; - return value?.FloatValue; - } - set - { - if (value.HasValue) - { - NSUserDefaults.StandardUserDefaults[UserDefaultsKeys.TrailWidth] = new NSNumber(value.Value); - } - else - { - NSUserDefaults.StandardUserDefaults.RemoveObject(UserDefaultsKeys.TrailWidth); - } - } - } - - public static bool ShowProjectileTrail - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowProjectileTrail); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowProjectileTrail); - } - } - - public static bool UseCustomTrail - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.UseCustomTrail); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.UseCustomTrail); - } - } - - public static bool TrailShouldNarrow - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.TrailShouldNarrow); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.TrailShouldNarrow); - } - } - - public static bool ShowResetLever - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowReset); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowReset); - } - } - - public static bool ShowClouds - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowClouds); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowClouds); - } - } - - public static bool ShowFlags - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowFlags); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowFlags); - } - } - - public static bool ShowRopeSimulation - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowRopeSimulation); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowRopeSimulation); - } - } - - public static bool AutoFocus - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.AutoFocus); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.AutoFocus); - } - } - - public static bool AllowGameBoardAutoSize - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.AllowGameBoardAutoSize); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.AllowGameBoardAutoSize); - } - } - - public static bool Spectator - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.Spectator); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.Spectator); - } - } - - public static bool DisableInGameUI - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.DisableInGameUI); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.DisableInGameUI); - } - } - - public static bool SynchronizeMusicWithWallClock - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.SynchronizeMusicWithWallClock); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.SynchronizeMusicWithWallClock); - } - } - - public static bool ShowThermalState - { - get - { - return NSUserDefaults.StandardUserDefaults.BoolForKey(UserDefaultsKeys.ShowThermalState); - } - set - { - NSUserDefaults.StandardUserDefaults.SetBool(value, UserDefaultsKeys.ShowThermalState); - } - } - } -} \ No newline at end of file + +namespace XamarinShot.Utils { + using Foundation; + using MultipeerConnectivity; + using XamarinShot.Models; + using XamarinShot.Models.Enums; + using System.Collections.Generic; + using UIKit; + + public static class UserDefaults { + public static Dictionary<string, object> ApplicationDefaults = new Dictionary<string, object> + { + { UserDefaultsKeys.Spectator, false }, + { UserDefaultsKeys.MusicVolume, 0f }, + { UserDefaultsKeys.EffectsVolume, 1f }, + { UserDefaultsKeys.AntialiasingMode, true}, + { UserDefaultsKeys.UseEncryption, true}, + { UserDefaultsKeys.GameRoomMode, false}, + { UserDefaultsKeys.AutoFocus, true}, + { UserDefaultsKeys.AllowGameBoardAutoSize, false}, + { UserDefaultsKeys.ShowReset, false}, + { UserDefaultsKeys.ShowFlags, true}, + { UserDefaultsKeys.ShowClouds, false}, + { UserDefaultsKeys.SynchronizeMusicWithWallClock, true}, + { UserDefaultsKeys.ShowRopeSimulation, true}, + { UserDefaultsKeys.ShowThermalState, true}, + { UserDefaultsKeys.ShowProjectileTrail, true}, + { UserDefaultsKeys.TrailShouldNarrow, true }, + }; + + public static Player Myself { + get { + Player result = null; + if (NSUserDefaults.StandardUserDefaults [UserDefaultsKeys.PeerID] is NSData data) { + if (NSKeyedUnarchiver.GetUnarchivedObject (typeof (MCPeerID), data, out NSError error) is MCPeerID peerID) { + result = new Player (peerID); + } + } + + if (result == null) { + // if no playerID was previously selected, create and cache a new one. + result = new Player (UIDevice.CurrentDevice.Name); + // update inner value + Myself = result; + } + + return result; + } + + set { + var data = NSKeyedArchiver.ArchivedDataWithRootObject (value.PeerId, true, out NSError archivedError); + NSUserDefaults.StandardUserDefaults [UserDefaultsKeys.PeerID] = NSObject.FromObject (data); + } + } + + public static float MusicVolume { + get { + + return NSUserDefaults.StandardUserDefaults.FloatForKey (UserDefaultsKeys.MusicVolume); + } + set { + NSUserDefaults.StandardUserDefaults.SetFloat (value, UserDefaultsKeys.MusicVolume); + } + } + + public static float EffectsVolume { + get { + + return NSUserDefaults.StandardUserDefaults.FloatForKey (UserDefaultsKeys.EffectsVolume); + } + set { + NSUserDefaults.StandardUserDefaults.SetFloat (value, UserDefaultsKeys.EffectsVolume); + } + } + + public static bool ShowARDebug { + get { + + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowARDebug); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowARDebug); + } + } + + public static bool ShowSceneViewStats { + get { + + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowSceneViewStats); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowSceneViewStats); + } + } + + /// <summary> + /// This is a wireframe overlay for looking at poly-count (f.e. LOD) + /// </summary> + public static bool ShowWireframe { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowWireframe); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowWireframe); + } + } + + /// <summary> + /// This turns shapes emissive channel red (set at level start) + /// </summary> + public static bool ShowLOD { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowLOD); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowLOD); + } + } + + /// <summary> + /// This may need to be integer for 0, 2, 4x + /// </summary> + public static bool AntialiasingMode { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.AntialiasingMode); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.AntialiasingMode); + } + } + + public static bool ShowTrackingState { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowTrackingState); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowTrackingState); + } + } + + public static GameLevel SelectedLevel { + get { + var levelName = NSUserDefaults.StandardUserDefaults.StringForKey (UserDefaultsKeys.SelectedLevel); + if (!string.IsNullOrEmpty (levelName)) { + var level = GameLevel.Level (levelName); + return level ?? GameLevel.DefaultLevel; + } else { + return GameLevel.DefaultLevel; + } + } + set { + NSUserDefaults.StandardUserDefaults.SetString (value.Name, UserDefaultsKeys.SelectedLevel); + } + } + + public static bool ShowPhysicsDebug { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowPhysicsDebug); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowPhysicsDebug); + } + } + + public static bool ShowNetworkDebug { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowNetworkDebug); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowNetworkDebug); + } + } + + public static bool HasOnboarded { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.HasOnboarded); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.HasOnboarded); + } + } + + public static BoardLocatingMode BoardLocatingMode { + get { + var value = NSUserDefaults.StandardUserDefaults.IntForKey (UserDefaultsKeys.BoardLocatingMode); + return (BoardLocatingMode) (int) value; + } + set { + NSUserDefaults.StandardUserDefaults.SetInt ((int) value, UserDefaultsKeys.BoardLocatingMode); + } + } + + public static bool GameRoomMode { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.GameRoomMode); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.GameRoomMode); + } + } + + public static bool UseEncryption { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.UseEncryption); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.UseEncryption); + } + } + + public static bool ShowSettingsInGame { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowSettingsInGame); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowSettingsInGame); + } + } + + public static bool ShowARRelocalizationHelp { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowARRelocalizationHelp); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowARRelocalizationHelp); + } + } + + public static int? TrailLength { + get { + var value = NSUserDefaults.StandardUserDefaults [UserDefaultsKeys.TrailLength] as NSNumber; + return value?.Int32Value; + } + set { + if (value.HasValue) { + NSUserDefaults.StandardUserDefaults.SetInt (value.Value, UserDefaultsKeys.TrailLength); + } else { + NSUserDefaults.StandardUserDefaults.RemoveObject (UserDefaultsKeys.TrailLength); + } + } + } + + public static float? TrailWidth { + get { + var value = NSUserDefaults.StandardUserDefaults [UserDefaultsKeys.TrailWidth] as NSNumber; + return value?.FloatValue; + } + set { + if (value.HasValue) { + NSUserDefaults.StandardUserDefaults [UserDefaultsKeys.TrailWidth] = new NSNumber (value.Value); + } else { + NSUserDefaults.StandardUserDefaults.RemoveObject (UserDefaultsKeys.TrailWidth); + } + } + } + + public static bool ShowProjectileTrail { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowProjectileTrail); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowProjectileTrail); + } + } + + public static bool UseCustomTrail { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.UseCustomTrail); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.UseCustomTrail); + } + } + + public static bool TrailShouldNarrow { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.TrailShouldNarrow); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.TrailShouldNarrow); + } + } + + public static bool ShowResetLever { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowReset); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowReset); + } + } + + public static bool ShowClouds { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowClouds); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowClouds); + } + } + + public static bool ShowFlags { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowFlags); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowFlags); + } + } + + public static bool ShowRopeSimulation { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowRopeSimulation); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowRopeSimulation); + } + } + + public static bool AutoFocus { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.AutoFocus); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.AutoFocus); + } + } + + public static bool AllowGameBoardAutoSize { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.AllowGameBoardAutoSize); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.AllowGameBoardAutoSize); + } + } + + public static bool Spectator { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.Spectator); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.Spectator); + } + } + + public static bool DisableInGameUI { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.DisableInGameUI); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.DisableInGameUI); + } + } + + public static bool SynchronizeMusicWithWallClock { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.SynchronizeMusicWithWallClock); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.SynchronizeMusicWithWallClock); + } + } + + public static bool ShowThermalState { + get { + return NSUserDefaults.StandardUserDefaults.BoolForKey (UserDefaultsKeys.ShowThermalState); + } + set { + NSUserDefaults.StandardUserDefaults.SetBool (value, UserDefaultsKeys.ShowThermalState); + } + } + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/UserDefaultsKeys.cs b/ios12/XamarinShot/XamarinShot/Utils/UserDefaultsKeys.cs index b21cbfe44..7bf0c0af0 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/UserDefaultsKeys.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/UserDefaultsKeys.cs @@ -1,46 +1,44 @@ - -namespace XamarinShot.Utils -{ - public static class UserDefaultsKeys - { - // debug support - public static string ShowSceneViewStats { get; } = "ShowSceneViewStatsKey"; - public static string ShowWireframe { get; } = "ShowWireframe"; - public static string ShowTrackingState { get; } = "ShowTrackingStateKey"; - public static string ShowARDebug { get; } = "ShowARDebugKey"; - public static string ShowPhysicsDebug { get; } = "EnablePhysicsKey"; - public static string ShowNetworkDebug { get; } = "ShowNetworkDebugKey"; - public static string ShowSettingsInGame { get; } = "ShowSettingsInGame"; - public static string ShowARRelocalizationHelp { get; } = "ShowARRelocalizationHelp"; - public static string TrailWidth { get; } = "TrailWidth"; - public static string TrailLength { get; } = "TrailLength"; - public static string ShowProjectileTrail { get; } = "ShowProjectileTrail"; - public static string UseCustomTrail { get; } = "UseCustomTrail"; - public static string TrailShouldNarrow { get; } = "TrailShouldNarrow"; - public static string AllowGameBoardAutoSize { get; } = "AllowGameBoardAutoSize"; - public static string DisableInGameUI { get; } = "DisableInGameUI"; - // settings - public static string AntialiasingMode { get; } = "AntialiasingMode"; - public static string PeerID { get; } = "PeerIDDefaultsKey"; - public static string SelectedLevel { get; } = "SelectedLevel"; - public static string HasOnboarded { get; } = "HasOnboarded"; - public static string BoardLocatingMode { get; } = "BoardLocatingMode"; - public static string GameRoomMode { get; } = "GameRoomMode"; - public static string UseEncryption { get; } = "UseEncryption"; - public static string AutoFocus { get; } = "AutoFocus"; - public static string Spectator { get; } = "Spectator"; +namespace XamarinShot.Utils { + public static class UserDefaultsKeys { + // debug support + public static string ShowSceneViewStats { get; } = "ShowSceneViewStatsKey"; + public static string ShowWireframe { get; } = "ShowWireframe"; + public static string ShowTrackingState { get; } = "ShowTrackingStateKey"; + public static string ShowARDebug { get; } = "ShowARDebugKey"; + public static string ShowPhysicsDebug { get; } = "EnablePhysicsKey"; + public static string ShowNetworkDebug { get; } = "ShowNetworkDebugKey"; + public static string ShowSettingsInGame { get; } = "ShowSettingsInGame"; + public static string ShowARRelocalizationHelp { get; } = "ShowARRelocalizationHelp"; + public static string TrailWidth { get; } = "TrailWidth"; + public static string TrailLength { get; } = "TrailLength"; + public static string ShowProjectileTrail { get; } = "ShowProjectileTrail"; + public static string UseCustomTrail { get; } = "UseCustomTrail"; + public static string TrailShouldNarrow { get; } = "TrailShouldNarrow"; + public static string AllowGameBoardAutoSize { get; } = "AllowGameBoardAutoSize"; + public static string DisableInGameUI { get; } = "DisableInGameUI"; - public static string ShowReset { get; } = "ShowReset"; - public static string ShowClouds { get; } = "ShowClouds"; - public static string ShowFlags { get; } = "ShowFlags"; - public static string ShowRopeSimulation { get; } = "ShowRopeSimulation"; - public static string ShowLOD { get; } = "showLOD"; + // settings + public static string AntialiasingMode { get; } = "AntialiasingMode"; + public static string PeerID { get; } = "PeerIDDefaultsKey"; + public static string SelectedLevel { get; } = "SelectedLevel"; + public static string HasOnboarded { get; } = "HasOnboarded"; + public static string BoardLocatingMode { get; } = "BoardLocatingMode"; + public static string GameRoomMode { get; } = "GameRoomMode"; + public static string UseEncryption { get; } = "UseEncryption"; + public static string AutoFocus { get; } = "AutoFocus"; + public static string Spectator { get; } = "Spectator"; - public static string MusicVolume { get; } = "MusicVolume"; - public static string EffectsVolume { get; } = "EffectsVolume"; - public static string SynchronizeMusicWithWallClock { get; } = "MusicSyncWithClock"; + public static string ShowReset { get; } = "ShowReset"; + public static string ShowClouds { get; } = "ShowClouds"; + public static string ShowFlags { get; } = "ShowFlags"; + public static string ShowRopeSimulation { get; } = "ShowRopeSimulation"; + public static string ShowLOD { get; } = "showLOD"; - public static string ShowThermalState { get; } = "ShowThermalState"; - } -} \ No newline at end of file + public static string MusicVolume { get; } = "MusicVolume"; + public static string EffectsVolume { get; } = "EffectsVolume"; + public static string SynchronizeMusicWithWallClock { get; } = "MusicSyncWithClock"; + + public static string ShowThermalState { get; } = "ShowThermalState"; + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameAttribute.cs b/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameAttribute.cs index be9b58c54..a6aceb312 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameAttribute.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameAttribute.cs @@ -1,10 +1,8 @@ - -namespace XamarinShot.Utils -{ - public static class XamarinShotGameAttribute - { - public const string Name = "XamarinShotGameAttributeName"; - public const string Location = "LocationAttributeName"; - public const string AppIdentifier = "AppIdentifierAttributeName"; - } -} \ No newline at end of file + +namespace XamarinShot.Utils { + public static class XamarinShotGameAttribute { + public const string Name = "XamarinShotGameAttributeName"; + public const string Location = "LocationAttributeName"; + public const string AppIdentifier = "AppIdentifierAttributeName"; + } +} diff --git a/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameService.cs b/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameService.cs index 7cac03c01..9aba73d4b 100644 --- a/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameService.cs +++ b/ios12/XamarinShot/XamarinShot/Utils/XamarinShotGameService.cs @@ -1,9 +1,7 @@ - -namespace XamarinShot.Utils -{ - public static class XamarinShotGameService - { - public const string PlayerService = "xamarinshot-p"; - public const string SpectatorService = "xamarinshot-s"; - } -} \ No newline at end of file + +namespace XamarinShot.Utils { + public static class XamarinShotGameService { + public const string PlayerService = "xamarinshot-p"; + public const string SpectatorService = "xamarinshot-s"; + } +} diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/AppDelegate.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/AppDelegate.cs index 05839fcd4..480150618 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/AppDelegate.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/AppDelegate.cs @@ -1,4 +1,4 @@ -using AuthenticationServices; +using AuthenticationServices; using CoreFoundation; using Foundation; using UIKit; diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainException.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainException.cs index 59d68bf4f..169f6cb3d 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainException.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainException.cs @@ -1,4 +1,4 @@ -using System; +using System; using Security; namespace AddingTheSignInWithAppleFlowToYourApp { diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainItem.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainItem.cs index a4b2ec2f3..0de68a267 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainItem.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/KeychainItem.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/LoginViewController.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/LoginViewController.cs index afc3bbd0c..b7185e7aa 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/LoginViewController.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/LoginViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using AuthenticationServices; using CoreImage; diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Main.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Main.cs index 1febba420..c775062e4 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Main.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace AddingTheSignInWithAppleFlowToYourApp { public class Application { @@ -10,4 +10,4 @@ static void Main (string [] args) UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Properties/AssemblyInfo.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Properties/AssemblyInfo.cs index 323ddc816..185bce7ad 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Properties/AssemblyInfo.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("AddingTheSignInWithAppleFlowToYourApp")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("AddingTheSignInWithAppleFlowToYourApp")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("AddingTheSignInWithAppleFlowToYourApp")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("AddingTheSignInWithAppleFlowToYourApp")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] +[assembly: Guid ("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/ResultViewController.cs b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/ResultViewController.cs index 95a16bed7..da665363c 100644 --- a/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/ResultViewController.cs +++ b/ios13/AddingTheSignInWithAppleFlowToYourApp/AddingTheSignInWithAppleFlowToYourApp/ResultViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreFoundation; using Foundation; using UIKit; diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2MoreViewController.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2MoreViewController.cs index 7696e689b..145bb0972 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2MoreViewController.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2MoreViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2SlowDrawingViewController.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2SlowDrawingViewController.cs index f9afac558..d311945ca 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2SlowDrawingViewController.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/After2SlowDrawingViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/AlwaysDarkViewController.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/AlwaysDarkViewController.cs index b3b9fb3c2..b47a2e381 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/AlwaysDarkViewController.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/After Adoption (2)/AlwaysDarkViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/AppDelegate.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/AppDelegate.cs index 4e67d7076..3aca6b862 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/AppDelegate.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace FaceTrack -{ +namespace FaceTrack { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1MoreViewController.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1MoreViewController.cs index bd612bcb0..e6d30b05c 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1MoreViewController.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1MoreViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1SlowDrawingViewController.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1SlowDrawingViewController.cs index ca62fe262..db595ee11 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1SlowDrawingViewController.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Before Adoption (1)/Before1SlowDrawingViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Main.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Main.cs index 8681fc048..ac534281d 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Main.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace AdoptingIOSDarkMode { public class Application { diff --git a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Properties/AssemblyInfo.cs b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Properties/AssemblyInfo.cs index 0d373ad5c..862eb4da2 100644 --- a/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Properties/AssemblyInfo.cs +++ b/ios13/AdoptingIOSDarkMode/AdoptingIOSDarkMode/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("AdoptingIOSDarkMode")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("AdoptingIOSDarkMode")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("AdoptingIOSDarkMode")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("AdoptingIOSDarkMode")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] +[assembly: Guid ("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/AppDelegate.cs b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/AppDelegate.cs index 020d9ff9d..985142d7e 100644 --- a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/AppDelegate.cs +++ b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace DisablingPullingDownASheet { diff --git a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/EditViewController.cs b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/EditViewController.cs index 34363979b..06ee4922e 100644 --- a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/EditViewController.cs +++ b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/EditViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/IEditViewControllerDelegate.cs b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/IEditViewControllerDelegate.cs index 7dca38dce..a34530d77 100644 --- a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/IEditViewControllerDelegate.cs +++ b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/IEditViewControllerDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace DisablingPullingDownASheet { public interface IEditViewControllerDelegate { void EditViewControllerDidCancel (EditViewController editViewController); diff --git a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Main.cs b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Main.cs index b1ae35f3c..59326fc4d 100644 --- a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Main.cs +++ b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace DisablingPullingDownASheet { public class Application { @@ -10,4 +10,4 @@ static void Main (string [] args) UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Properties/AssemblyInfo.cs b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Properties/AssemblyInfo.cs index 7d9ab7afa..e00784720 100644 --- a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Properties/AssemblyInfo.cs +++ b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("DisablingPullingDownASheet")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("DisablingPullingDownASheet")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("DisablingPullingDownASheet")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("DisablingPullingDownASheet")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] +[assembly: Guid ("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/RootViewController.cs b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/RootViewController.cs index 2c9e3080c..779b2b289 100644 --- a/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/RootViewController.cs +++ b/ios13/DisablingPullingDownASheet/DisablingPullingDownASheet/RootViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/AppDelegate.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/AppDelegate.cs index 328cb0575..25b84786e 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/AppDelegate.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/AppDelegate.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -18,7 +18,7 @@ namespace ColorFeed { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations - + static readonly string caveat = "Change me!!"; public static string RefreshTaskId { get; } = "com.xamarin.ColorFeed.refresh"; @@ -71,7 +71,7 @@ void ScheduleAppRefresh () NSNotificationCenter.DefaultCenter.AddObserver (RefreshSuccessNotificationName, RefreshSuccess); var request = new BGAppRefreshTaskRequest (RefreshTaskId) { - EarliestBeginDate = (NSDate)DateTime.Now.AddMinutes (15) // Fetch no earlier than 15 minutes from now + EarliestBeginDate = (NSDate) DateTime.Now.AddMinutes (15) // Fetch no earlier than 15 minutes from now }; BGTaskScheduler.Shared.Submit (request, out NSError error); diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Main.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Main.cs index 262e17dd5..deb14ee2d 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Main.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace ColorFeed { public class Application { @@ -10,4 +10,4 @@ static void Main (string [] args) UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/DBManager.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/DBManager.cs index 3d279f814..00c60a9f5 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/DBManager.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/DBManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/Operations.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/Operations.cs index 5c5a5a1ae..fcf60641f 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/Operations.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Model/Operations.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Diagnostics; using System.Linq; using System.Threading; diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Color.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Color.cs index 2e4dfbe34..c38e92151 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Color.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Color.cs @@ -1,4 +1,4 @@ -using System; +using System; using SQLite; using SQLiteNetExtensions.Attributes; @@ -23,6 +23,6 @@ public Color (double red, double green, double blue) Blue = blue; } - public UIColor ToUIColor () => new UIColor ((nfloat)Red, (nfloat)Green, (nfloat)Blue, 1); + public UIColor ToUIColor () => new UIColor ((nfloat) Red, (nfloat) Green, (nfloat) Blue, 1); } } diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Post.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Post.cs index 812941975..335bbc793 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Post.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ORM/Post.cs @@ -1,4 +1,4 @@ -using System; +using System; using SQLite; using SQLiteNetExtensions.Attributes; diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Properties/AssemblyInfo.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Properties/AssemblyInfo.cs index abc8e24c7..dd299a2a4 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Properties/AssemblyInfo.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("ColorFeed")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ColorFeed")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("ColorFeed")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("ColorFeed")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] +[assembly: Guid ("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Mocks.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Mocks.cs index b894d0d9e..b68fd36ee 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Mocks.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Mocks.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -36,7 +36,7 @@ public MockDownloadTask (TimeSpan delay, DateTime startDate, Action<Post []> suc } public void Start () - { + { Task.Factory.StartNew (async () => { await Task.Delay (delay); var posts = await ServerUtils.GenerateFakePosts (startDate, DateTime.Now); diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Server.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Server.cs index be9e4af0a..108b694b4 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Server.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/SimulatedServer/Server.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -36,8 +36,7 @@ public ServerSuccessEventArgs (Post [] posts) } } - public static class ServerUtils - { + public static class ServerUtils { static Random random = new Random (DateTime.Now.Millisecond); public static Color CreateRandomColor () diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/ColorView.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/ColorView.cs index 781e7ae28..93ba53c38 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/ColorView.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/ColorView.cs @@ -8,10 +8,8 @@ using Foundation; using UIKit; -namespace ColorFeed -{ - public partial class ColorView : UIView - { +namespace ColorFeed { + public partial class ColorView : UIView { UIImageView imageView; CancellationTokenSource cancellationTokenSource; diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedEntryTableViewCell.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedEntryTableViewCell.cs index e955eee0d..6d5f2746c 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedEntryTableViewCell.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedEntryTableViewCell.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace ColorFeed -{ - public partial class FeedEntryTableViewCell : UITableViewCell - { +namespace ColorFeed { + public partial class FeedEntryTableViewCell : UITableViewCell { Post post; public Post Post { get => post; diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedTableViewController.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedTableViewController.cs index 1f670c88b..c20856e8c 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedTableViewController.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/UI/FeedTableViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -118,7 +118,7 @@ Task LoadPosts () InsertPostsIntoTable (insertedPostCount); insertedPostCount = posts.Count; }); - } + } posts = await DBManager.SharedInstance.GetPosts (); InvokeOnMainThread (() => { @@ -149,7 +149,7 @@ void InsertPostsIntoTable (Post [] posts, int delayInSeconds, CancellationToken for (int i = 0; i < totalPosts; i++) { if (cancellationToken.IsCancellationRequested) return; - + Task.Delay (delayInSeconds * 1000).Wait (); this.posts.Insert (0, posts [i]); diff --git a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ViewController.cs b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ViewController.cs index ac8dabc12..864204e6e 100644 --- a/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ViewController.cs +++ b/ios13/RefreshingAndMaintainingYourAppUsingBackgroundTasks/ColorFeed/ViewController.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using System; using UIKit; @@ -20,4 +20,4 @@ public override void DidReceiveMemoryWarning () // Release any cached data, images, etc that aren't in use. } } -} \ No newline at end of file +} diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/AppDelegate.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/AppDelegate.cs index 53db553b3..80889f86f 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/AppDelegate.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/AppDelegate.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/Main.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/Main.cs index 5acbbac16..ac50c03d3 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/Main.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace Gallery { public class Application { diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/Models.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/Models.cs index 1f46c234b..bd8aa0325 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/Models.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/Models.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -40,7 +40,7 @@ public class PhotoManager { static Lazy<PhotoManager> lazy = new Lazy<PhotoManager> (() => new PhotoManager ()); public static PhotoManager SharedInstance { get; } = lazy.Value; - PhotoManager () { } + PhotoManager () { } public PhotoSection [] Sections { get; } = { new PhotoSection { diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/Properties/AssemblyInfo.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/Properties/AssemblyInfo.cs index 6fb76e7ff..f12f1cc1e 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/Properties/AssemblyInfo.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Gallery")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Gallery")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("Gallery")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("Gallery")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] +[assembly: Guid ("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/SceneDelegate.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/SceneDelegate.cs index 2a0a985a7..43aad2fab 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/SceneDelegate.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/SceneDelegate.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryCollectionViewCell.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryCollectionViewCell.cs index b83159073..ba35fccbf 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryCollectionViewCell.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryCollectionViewCell.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryViewController.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryViewController.cs index 09eb9e056..b048bba57 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryViewController.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/GalleryViewController/GalleryViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/PhotoDetailViewController/PhotoDetailViewController.cs b/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/PhotoDetailViewController/PhotoDetailViewController.cs index ed3f35cc9..307b7adb2 100644 --- a/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/PhotoDetailViewController/PhotoDetailViewController.cs +++ b/ios13/SupportingMultipleWindowsOniPad/Gallery/View Controllers/PhotoDetailViewController/PhotoDetailViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/AppDelegate.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/AppDelegate.cs index e2ab9cac0..49ef29734 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/AppDelegate.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace Conference_Diffable { diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/NestedGroupsViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/NestedGroupsViewController.cs index b2e491c9e..f8d4f9432 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/NestedGroupsViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/NestedGroupsViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -35,7 +35,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollBehaviorViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollBehaviorViewController.cs index 6092ede3b..ecb155661 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollBehaviorViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollBehaviorViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -81,7 +81,7 @@ public UICollectionLayoutSectionOrthogonalScrollingBehavior GetOrthogonalScrolli } public static bool operator != (SectionKind left, SectionKind right) => !(left == right); - public override bool Equals (object obj) => this == (SectionKind)obj; + public override bool Equals (object obj) => this == (SectionKind) obj; public bool Equals (SectionKind other) => EnumValue == other.EnumValue; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), EnumValue); diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollingViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollingViewController.cs index b3c5c9892..02b6fbf11 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollingViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Advanced Layouts View Controllers/OrthogonalScrollingViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using Conference_Diffable.CompositionalLayout.CellsandSupplementaryViews; using Foundation; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceNewsFeedViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceNewsFeedViewController.cs index 585ccdf85..3e715a0e9 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceNewsFeedViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceNewsFeedViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Conference_Diffable.CompositionalLayout.CellsandSupplementaryViews; using Conference_Diffable.CompositionalLayout.Controllers; using Foundation; @@ -28,7 +28,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceVideoSessionsViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceVideoSessionsViewController.cs index c980cc31a..935c5ccd2 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceVideoSessionsViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/App Samples View Controllers/ConferenceVideoSessionsViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/AdaptiveSectionsViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/AdaptiveSectionsViewController.cs index d076edf34..12e4dc6b7 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/AdaptiveSectionsViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/AdaptiveSectionsViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -20,7 +20,7 @@ class SectionLayoutKind : NSObject, IEquatable<SectionLayoutKind> { public static SectionLayoutKind Grid3 { get; } = new SectionLayoutKind (2); public int EnumValue { get; private set; } - + public static SectionLayoutKind [] AllSections { get; } = { List, Grid5, Grid3 }; SectionLayoutKind (int enumValue) => EnumValue = enumValue; @@ -58,7 +58,7 @@ public int GetColumnCount (nfloat width) } public static bool operator != (SectionLayoutKind left, SectionLayoutKind right) => !(left == right); - public override bool Equals (object obj) => this == (SectionLayoutKind)obj; + public override bool Equals (object obj) => this == (SectionLayoutKind) obj; public bool Equals (SectionLayoutKind other) => EnumValue == other.EnumValue; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), EnumValue); } @@ -143,7 +143,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd if (section == SectionLayoutKind.List) { // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (ListCell.Key, indexPath) as ListCell; - + // Populate the cell with our item description. cell.Label.Text = id.ToString (); @@ -152,7 +152,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd } else { // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (TextCell.Key, indexPath) as TextCell; - + // Populate the cell with our item description. cell.Label.Text = id.ToString (); cell.ContentView.BackgroundColor = UIColorExtensions.CornflowerBlue; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/DistinctSectionsViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/DistinctSectionsViewController.cs index 14795547b..271e1aba9 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/DistinctSectionsViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/DistinctSectionsViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -20,7 +20,7 @@ class SectionLayoutKind : NSObject, IEquatable<SectionLayoutKind> { public static SectionLayoutKind Grid3 { get; } = new SectionLayoutKind (2); public int EnumValue { get; private set; } - + public static SectionLayoutKind [] AllSections { get; } = { List, Grid5, Grid3 }; SectionLayoutKind (int enumValue) => EnumValue = enumValue; @@ -56,7 +56,7 @@ public int GetColumnCount () } public static bool operator != (SectionLayoutKind left, SectionLayoutKind right) => !(left == right); - public override bool Equals (object obj) => this == (SectionLayoutKind)obj; + public override bool Equals (object obj) => this == (SectionLayoutKind) obj; public bool Equals (SectionLayoutKind other) => EnumValue == other.EnumValue; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), EnumValue); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/GridViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/GridViewController.cs index fee74c2ac..9316027f1 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/GridViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/GridViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -35,7 +35,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } @@ -96,7 +96,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd var id = (obj as NSNumber).Int32Value; // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (TextCell.Key, indexPath) as TextCell; - + // Populate the cell with our item description. cell.Label.Text = id.ToString (); cell.ContentView.BackgroundColor = UIColorExtensions.CornflowerBlue; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/InsetItemsGridViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/InsetItemsGridViewController.cs index 519b28d17..2979cf9da 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/InsetItemsGridViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/InsetItemsGridViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -37,7 +37,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } @@ -65,7 +65,7 @@ UICollectionViewLayout CreateLayout () var groupSize = NSCollectionLayoutSize.Create (NSCollectionLayoutDimension.CreateFractionalWidth (1), NSCollectionLayoutDimension.CreateFractionalWidth (.2f)); var group = NSCollectionLayoutGroup.CreateHorizontal (groupSize, item); - + var section = NSCollectionLayoutSection.Create (group); var layout = new UICollectionViewCompositionalLayout (section); @@ -99,7 +99,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd var id = (obj as NSNumber).Int32Value; // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (TextCell.Key, indexPath) as TextCell; - + // Populate the cell with our item description. cell.Label.Text = id.ToString (); cell.ContentView.BackgroundColor = UIColorExtensions.CornflowerBlue; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ItemBadgeSupplementaryViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ItemBadgeSupplementaryViewController.cs index ba9926263..b06a2f0bb 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ItemBadgeSupplementaryViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ItemBadgeSupplementaryViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -37,7 +37,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } @@ -124,7 +124,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd var model = obj as Model; // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (TextCell.Key, indexPath) as TextCell; - + // Populate the cell with our item description. cell.Label.Text = model.Title; cell.ContentView.BackgroundColor = UIColorExtensions.CornflowerBlue; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ListViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ListViewController.cs index 54d46b055..5fae8c28b 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ListViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/ListViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -35,7 +35,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/PinnedSectionHeaderFooterViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/PinnedSectionHeaderFooterViewController.cs index 58fe01aa2..9d3baf02d 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/PinnedSectionHeaderFooterViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/PinnedSectionHeaderFooterViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -93,7 +93,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd { // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (ListCell.Key, indexPath) as ListCell; - + // Populate the cell with our item description. cell.Label.Text = $"{indexPath.Section}, {indexPath.Row}"; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionDecorationViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionDecorationViewController.cs index 1d8ba37d1..2d5a24e20 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionDecorationViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionDecorationViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionHeadersFootersViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionHeadersFootersViewController.cs index 4e2349fe7..f4c26aa47 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionHeadersFootersViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/SectionHeadersFootersViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/TwoColumnViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/TwoColumnViewController.cs index 98ba4510a..ea21480d5 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/TwoColumnViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Basics View Controllers/TwoColumnViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -35,7 +35,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } @@ -100,7 +100,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd var id = (obj as NSNumber).Int32Value; // Get a cell of the desired kind. var cell = collectionView.DequeueReusableCell (TextCell.Key, indexPath) as TextCell; - + // Populate the cell with our item description. cell.Label.Text = id.ToString (); cell.ContentView.BackgroundColor = UIColorExtensions.CornflowerBlue; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/BadgeSupplementaryView.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/BadgeSupplementaryView.cs index f55d7133c..c1c37662f 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/BadgeSupplementaryView.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/BadgeSupplementaryView.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceNewsFeedCell.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceNewsFeedCell.cs index 8593513f0..ae2ddef0b 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceNewsFeedCell.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceNewsFeedCell.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Globalization; using CoreGraphics; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceVideoCell.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceVideoCell.cs index b7ccb39ab..e1636f130 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceVideoCell.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ConferenceVideoCell.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ListCell.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ListCell.cs index 2eae913e8..b1adb0511 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ListCell.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/ListCell.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/SectionBackgroundDecorationView.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/SectionBackgroundDecorationView.cs index 8b65e73d4..8bb27e1a6 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/SectionBackgroundDecorationView.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/SectionBackgroundDecorationView.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TextCell.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TextCell.cs index 6bbd51565..60497c370 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TextCell.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TextCell.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TitleSupplementaryView.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TitleSupplementaryView.cs index d695d42ad..3c3aae5a1 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TitleSupplementaryView.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Cells and Supplementary Views/TitleSupplementaryView.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceNewsController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceNewsController.cs index dd8415809..7dc0c52a2 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceNewsController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceNewsController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -34,21 +34,21 @@ public NewsFeedItem (string title, DateTime date, string body) public ConferenceNewsController () => GenerateNews (); void GenerateNews () => News = new [] { - new NewsFeedItem ("Conference 2019 Registration Now Open", new DateTime (2109, 3, 14), "\"" + - "Register by Wednesday, March 20, 2019 at 5:00PM PSD for your chance to join us and thousands\n" + + new NewsFeedItem ("Conference 2019 Registration Now Open", new DateTime (2109, 3, 14), "\"" + + "Register by Wednesday, March 20, 2019 at 5:00PM PSD for your chance to join us and thousands\n" + "of coders, creators, and crazy ones at this year's Conference 19 in San Jose, June 3-7.\""), - new NewsFeedItem ("Apply for a Conference19 Scholarship", new DateTime (2109, 3, 14), "\"" + - "Conference Scholarships reward talented studens and STEM orgination members with the opportunity\n" + + new NewsFeedItem ("Apply for a Conference19 Scholarship", new DateTime (2109, 3, 14), "\"" + + "Conference Scholarships reward talented studens and STEM orgination members with the opportunity\n" + "to attend this year's conference. Apply by Sunday, March 24, 2019 at 5:00PM PDT\""), - new NewsFeedItem ("Conference18 Video Subtitles Now in More Languages", new DateTime (2109, 8, 8), "\"" + - "All of this year's session videos are now available with Japanese and Simplified Chinese subtitles.\n" + + new NewsFeedItem ("Conference18 Video Subtitles Now in More Languages", new DateTime (2109, 8, 8), "\"" + + "All of this year's session videos are now available with Japanese and Simplified Chinese subtitles.\n" + "Watch in the Videos tab or on the Apple Developer website.\""), - new NewsFeedItem ("Lunchtime Inspiration", new DateTime (2109, 6, 8), "\"" + - "All of this year's session videos are now available with Japanese and Simplified Chinease subtitles.\n" + + new NewsFeedItem ("Lunchtime Inspiration", new DateTime (2109, 6, 8), "\"" + + "All of this year's session videos are now available with Japanese and Simplified Chinease subtitles.\n" + "Watch in the Videos tab or on the Apple Developer website.\""), - new NewsFeedItem ("Close Your Rings Challenge", new DateTime (2109, 6, 8), "\"" + - "Congratulations to all Close Your Rings Challenge participants for staying active\n" + - "throughout the week! Everyone who participated in the challenge can pick up a\n" + + new NewsFeedItem ("Close Your Rings Challenge", new DateTime (2109, 6, 8), "\"" + + "Congratulations to all Close Your Rings Challenge participants for staying active\n" + + "throughout the week! Everyone who participated in the challenge can pick up a\n" + "special reward pin outside on the Plaza until 5:00 p.m.\"") }; } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceVideoController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceVideoController.cs index b87c11643..91b158b94 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceVideoController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Compositional Layout/Controllers/ConferenceVideoController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/Cells And Supplementary Views/LabelCell.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/Cells And Supplementary Views/LabelCell.cs index 47d377b66..2ba6312bd 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/Cells And Supplementary Views/LabelCell.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/Cells And Supplementary Views/LabelCell.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/InsertionSortViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/InsertionSortViewController.cs index cf77cbb86..9db8433fb 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/InsertionSortViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/InsertionSortViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -38,9 +38,9 @@ UICollectionViewLayout CreateLayout () NSCollectionLayoutSection SectionProviderHandler (nint sectionIndex, INSCollectionLayoutEnvironment layoutEnvironment) { var contentSize = layoutEnvironment.Container.EffectiveContentSize; - var columns = (int)(contentSize.Width / nodeSize.Width); + var columns = (int) (contentSize.Width / nodeSize.Width); var rowHeight = nodeSize.Height; - + var itemSize = NSCollectionLayoutSize.Create (NSCollectionLayoutDimension.CreateFractionalWidth (1), NSCollectionLayoutDimension.CreateFractionalHeight (1)); var item = NSCollectionLayoutItem.Create (itemSize); @@ -171,8 +171,8 @@ public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerT return snapshot; } - int GetRows (CGRect bounds) => (int)(bounds.Height / nodeSize.Height); - int GetColumns (CGRect bounds) => (int)(bounds.Width / nodeSize.Width); + int GetRows (CGRect bounds) => (int) (bounds.Height / nodeSize.Height); + int GetColumns (CGRect bounds) => (int) (bounds.Width / nodeSize.Width); } } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsController.cs index 1c5e77682..9adaab620 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -41,7 +41,7 @@ public Mountain (string name, int height) } public static bool operator != (Mountain left, Mountain right) => !(left == right); - public override bool Equals (object obj) => this == (Mountain)obj; + public override bool Equals (object obj) => this == (Mountain) obj; public bool Equals (Mountain other) => Id == other.Id; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Id); diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsRawData.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsRawData.cs index 6792520e1..142d0981c 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsRawData.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsRawData.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Conference_Diffable.Diffable { public class MountainsRawData { public static string [] Mountains { get; } = { diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsViewController.cs index e262f48c2..f674af189 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/MountainsViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -37,7 +37,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/TableViewEditingViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/TableViewEditingViewController.cs index 6a709e8d0..06a92dfaa 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/TableViewEditingViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/TableViewEditingViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -57,7 +57,7 @@ public static Section GetSectionKind (nint sectionIndex) } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => EnumValue == other.EnumValue; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), EnumValue); diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WIFIController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WIFIController.cs index 0fda21c24..895ef0d6e 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WIFIController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WIFIController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -38,7 +38,7 @@ public Network (string name) } public static bool operator != (Network left, Network right) => !(left == right); - public override bool Equals (object obj) => this == (Network)obj; + public override bool Equals (object obj) => this == (Network) obj; public bool Equals (Network other) => Id == other.Id; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Id); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WiFiSettingsViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WiFiSettingsViewController.cs index 17cd92ef6..fb21356a7 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WiFiSettingsViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Diffable/WiFiSettingsViewController.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -43,7 +43,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } @@ -70,7 +70,7 @@ public Item (string title, ItemType type) public Item (WIFIController.Network network) { Title = network.Name; - Type = ItemType.AvailableNetwork; + Type = ItemType.AvailableNetwork; Network = network; Id = network.Id; } @@ -99,7 +99,7 @@ public bool IsConfig { } public static bool operator != (Item left, Item right) => !(left == right); - public override bool Equals (object obj) => this == (Item)obj; + public override bool Equals (object obj) => this == (Item) obj; public bool Equals (Item other) => Id == other.Id; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Id); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/InsertionSortArray.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/InsertionSortArray.cs index afa4b629a..6acc43e0c 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/InsertionSortArray.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/InsertionSortArray.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -22,7 +22,7 @@ public class SortNode : NSObject, IEquatable<SortNode> { public SortNode (int value, int maxValue) { Value = value; - var hue = value / (nfloat)maxValue; + var hue = value / (nfloat) maxValue; Color = UIColor.FromHSBA (hue, 1, 1, 1); Id = new NSUuid ().ToString (); @@ -43,7 +43,7 @@ public SortNode (int value, int maxValue) } public static bool operator != (SortNode left, SortNode right) => !(left == right); - public override bool Equals (object obj) => this == (SortNode)obj; + public override bool Equals (object obj) => this == (SortNode) obj; public bool Equals (SortNode other) => Id == other.Id; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Id); } @@ -56,7 +56,7 @@ public SortNode (int value, int maxValue) public InsertionSortArray (int count) { - Nodes = Enumerable.Range (0, count).Select (i => new SortNode (i, count)).ToArray (); + Nodes = Enumerable.Range (0, count).Select (i => new SortNode (i, count)).ToArray (); SortNodes (); Id = new NSUuid ().ToString (); } @@ -115,7 +115,7 @@ void PerformNextSortStep () } public static bool operator != (InsertionSortArray left, InsertionSortArray right) => !(left == right); - public override bool Equals (object obj) => this == (InsertionSortArray)obj; + public override bool Equals (object obj) => this == (InsertionSortArray) obj; public bool Equals (InsertionSortArray other) => Id == other.Id; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Id); } diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Main.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Main.cs index 4c538507e..6edfd8c40 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Main.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Main.cs @@ -1,4 +1,4 @@ -using UIKit; +using UIKit; namespace Conference_Diffable { public class Application { @@ -10,4 +10,4 @@ static void Main (string [] args) UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineItemCell.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineItemCell.cs index 0fecebe09..691e38047 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineItemCell.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineItemCell.cs @@ -1,4 +1,4 @@ -/* +/* See LICENSE folder for this sample’s licensing information. Abstract: @@ -126,7 +126,7 @@ void ConfigureChevron () ImageView.Image = image; var rtlMultiplier = rtl ? -1.0 : 1.0; var rotationTransform = Expanded ? - CGAffineTransform.MakeRotation ((nfloat)(rtlMultiplier * Math.PI / 2)) : CGAffineTransform.MakeIdentity (); + CGAffineTransform.MakeRotation ((nfloat) (rtlMultiplier * Math.PI / 2)) : CGAffineTransform.MakeIdentity (); ImageView.Transform = rotationTransform; } else { var imageName = Highlighted ? circleFill : circle; diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineViewController.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineViewController.cs index 93b7a1083..b95215ab1 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineViewController.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/OutlineViewController.cs @@ -38,7 +38,7 @@ class Section : NSObject, IEquatable<Section> { } public static bool operator != (Section left, Section right) => !(left == right); - public override bool Equals (object obj) => this == (Section)obj; + public override bool Equals (object obj) => this == (Section) obj; public bool Equals (Section other) => Value == other.Value; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Value); } @@ -77,7 +77,7 @@ public OutlineItem (string title, int indentLevel = 0, UIViewController outlineV } public static bool operator != (OutlineItem left, OutlineItem right) => !(left == right); - public override bool Equals (object obj) => this == (OutlineItem)obj; + public override bool Equals (object obj) => this == (OutlineItem) obj; public bool Equals (OutlineItem other) => Id == other.Id; public override int GetHashCode () => HashCode.Combine (base.GetHashCode (), Id); } @@ -178,7 +178,7 @@ UICollectionViewCell CellProviderHandler (UICollectionView collectionView, NSInd } UICollectionViewLayout GenerateLayout () - { + { var itemHeightDimension = NSCollectionLayoutDimension.CreateAbsolute (44); var itemSize = NSCollectionLayoutSize.Create (NSCollectionLayoutDimension.CreateFractionalWidth (1), itemHeightDimension); var item = NSCollectionLayoutItem.Create (itemSize); diff --git a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Properties/AssemblyInfo.cs b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Properties/AssemblyInfo.cs index 3840cad34..425a33f3b 100644 --- a/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Properties/AssemblyInfo.cs +++ b/ios13/UsingCollectionViewCompositionalLayoutsAndDiffableDataSources/Conference-Diffable/Properties/AssemblyInfo.cs @@ -1,26 +1,26 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Conference_Diffable")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Conference_Diffable")] -[assembly: AssemblyCopyright("Copyright © 2017")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] +[assembly: AssemblyTitle ("Conference_Diffable")] +[assembly: AssemblyDescription ("")] +[assembly: AssemblyConfiguration ("")] +[assembly: AssemblyCompany ("")] +[assembly: AssemblyProduct ("Conference_Diffable")] +[assembly: AssemblyCopyright ("Copyright © 2017")] +[assembly: AssemblyTrademark ("")] +[assembly: AssemblyCulture ("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] +[assembly: ComVisible (false)] // The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] +[assembly: Guid ("50c7b8c9-e664-45af-b88e-0c9b8b9c1be1")] // Version information for an assembly consists of the following four values: // @@ -32,5 +32,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion ("1.0.0.0")] +[assembly: AssemblyFileVersion ("1.0.0.0")] diff --git a/ios7fonts/AppDelegate.cs b/ios7fonts/AppDelegate.cs index 00a608566..c645d1009 100644 --- a/ios7fonts/AppDelegate.cs +++ b/ios7fonts/AppDelegate.cs @@ -7,11 +7,9 @@ using CoreGraphics; using CoreText; -namespace ios7fonts -{ +namespace ios7fonts { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { const string lorem = "\nLorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "; @@ -36,8 +34,8 @@ public Element MakeMultilineSample (string text, UIFontDescriptorSymbolicTraits public UIFont ResizeProportionalAndAlternative (UIFont font) { var attributes = new UIFontAttributes ( - new UIFontFeature (CTFontFeatureNumberSpacing.Selector.ProportionalNumbers), - new UIFontFeature ((CTFontFeatureCharacterAlternatives.Selector)1)); + new UIFontFeature (CTFontFeatureNumberSpacing.Selector.ProportionalNumbers), + new UIFontFeature ((CTFontFeatureCharacterAlternatives.Selector) 1)); var newDesc = font.FontDescriptor.CreateWithAttributes (attributes); return UIFont.FromDescriptor (newDesc, 40); @@ -52,7 +50,7 @@ public UIFont ResizeProportional (UIFont font) public UIFont ResizeAlternative (UIFont font) { - var attributes = new UIFontAttributes (new UIFontFeature ((CTFontFeatureCharacterAlternatives.Selector)1)); + var attributes = new UIFontAttributes (new UIFontFeature ((CTFontFeatureCharacterAlternatives.Selector) 1)); var newDesc = font.FontDescriptor.CreateWithAttributes (attributes); return UIFont.FromDescriptor (newDesc, 40); } @@ -122,14 +120,15 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) window.RootViewController = nav; window.MakeKeyAndVisible (); - UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate { + UIApplication.Notifications.ObserveContentSizeCategoryChanged (delegate + { dialog.Root = MakeFonts (); nav.PopToRootViewController (false); }); return true; } - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/AppDelegate.cs b/ios8/AdaptivePhotos/AdaptivePhotos/AppDelegate.cs index a6ecd26e7..94f1414c8 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/AppDelegate.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; using System.Reflection; -namespace AdaptivePhotos -{ +namespace AdaptivePhotos { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) @@ -25,7 +23,7 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) var masterNav = new CustomNavigationController (master); var detail = new EmptyViewController (); - controller.ViewControllers = new UIViewController[] { masterNav, detail }; + controller.ViewControllers = new UIViewController [] { masterNav, detail }; controller.PreferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible; var traitController = new TraitOverrideViewController () { @@ -39,28 +37,27 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) return true; } - public class SplitViewControllerDelegate : UISplitViewControllerDelegate - { + public class SplitViewControllerDelegate : UISplitViewControllerDelegate { public override bool CollapseSecondViewController (UISplitViewController splitViewController, - UIViewController secondaryViewController, UIViewController primaryViewController) + UIViewController secondaryViewController, UIViewController primaryViewController) { - Photo photo = ((CustomViewController)secondaryViewController).ContainedPhoto (null); + Photo photo = ((CustomViewController) secondaryViewController).ContainedPhoto (null); if (photo == null) { return true; } - if (primaryViewController.GetType () == typeof(CustomNavigationController)) { + if (primaryViewController.GetType () == typeof (CustomNavigationController)) { var viewControllers = new List<UIViewController> (); - foreach (var controller in ((UINavigationController)primaryViewController).ViewControllers) { + foreach (var controller in ((UINavigationController) primaryViewController).ViewControllers) { var type = controller.GetType (); MethodInfo method = type.GetMethod ("ContainsPhoto"); - if ((bool)method.Invoke (controller, new object[] { null })) { + if ((bool) method.Invoke (controller, new object [] { null })) { viewControllers.Add (controller); } } - ((UINavigationController)primaryViewController).ViewControllers = viewControllers.ToArray<UIViewController> (); + ((UINavigationController) primaryViewController).ViewControllers = viewControllers.ToArray<UIViewController> (); } return false; @@ -69,12 +66,12 @@ public override bool CollapseSecondViewController (UISplitViewController splitVi public override UIViewController SeparateSecondaryViewController (UISplitViewController splitViewController, UIViewController primaryViewController) { - if (primaryViewController.GetType () == typeof(CustomNavigationController)) { - foreach (var controller in ((CustomNavigationController)primaryViewController).ViewControllers) { + if (primaryViewController.GetType () == typeof (CustomNavigationController)) { + foreach (var controller in ((CustomNavigationController) primaryViewController).ViewControllers) { var type = controller.GetType (); MethodInfo method = type.GetMethod ("ContainedPhoto"); - if (method.Invoke (controller, new object[] { null }) != null) { + if (method.Invoke (controller, new object [] { null }) != null) { return null; } } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ConversationViewController.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ConversationViewController.cs index 482645ca9..640e47870 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ConversationViewController.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ConversationViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using ObjCRuntime; using UIKit; -namespace AdaptivePhotos -{ - public class ConversationViewController : CustomTableViewController - { +namespace AdaptivePhotos { + public class ConversationViewController : CustomTableViewController { readonly NSString ListTableViewControllerCellIdentifier = new NSString ("Cell"); public Conversation Conversation { get; set; } @@ -19,7 +17,7 @@ public ConversationViewController () : base (UITableViewStyle.Plain) public override void ViewDidLoad () { base.ViewDidLoad (); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), ListTableViewControllerCellIdentifier); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), ListTableViewControllerCellIdentifier); NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("showDetailTargetDidChange:"), UIViewController.ShowDetailTargetDidChangeNotification, null); } @@ -68,12 +66,12 @@ public void ShowDetailTargetDidChange (NSNotification notification) Photo PhotoForIndexPath (NSIndexPath indexPath) { - return Conversation.Photos.GetItem<Photo> ((nuint)indexPath.Item); + return Conversation.Photos.GetItem<Photo> ((nuint) indexPath.Item); } public override nint RowsInSection (UITableView tableview, nint section) { - return (nint)Conversation.Photos.Count; + return (nint) Conversation.Photos.Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/EmptyViewController.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/EmptyViewController.cs index 0de5e55fe..3672431a3 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/EmptyViewController.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/EmptyViewController.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace AdaptivePhotos -{ - public class EmptyViewController : CustomViewController - { +namespace AdaptivePhotos { + public class EmptyViewController : CustomViewController { public override void ViewDidLoad () { base.ViewDidLoad (); diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ListTableViewController.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ListTableViewController.cs index 0cdaed20f..2379aeaf6 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ListTableViewController.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ListTableViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using UIKit; using ObjCRuntime; -namespace AdaptivePhotos -{ - public class ListTableViewController : CustomTableViewController - { +namespace AdaptivePhotos { + public class ListTableViewController : CustomTableViewController { readonly NSString ListTableViewControllerCellIdentifier = new NSString ("Cell"); public User User { get; set; } @@ -21,7 +19,7 @@ public ListTableViewController (User user) : base (UITableViewStyle.Plain) public override void ViewDidLoad () { base.ViewDidLoad (); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), ListTableViewControllerCellIdentifier); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), ListTableViewControllerCellIdentifier); NSNotificationCenter.DefaultCenter.AddObserver (this, new Selector ("showDetailTargetDidChange:"), UIViewController.ShowDetailTargetDidChangeNotification, null); ClearsSelectionOnViewWillAppear = false; @@ -63,7 +61,7 @@ public void ShowDetailTargetDidChange (NSNotification notification) public override nint RowsInSection (UITableView tableview, nint section) { - return (nint)User.Conversations.Count; + return (nint) User.Conversations.Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) @@ -96,7 +94,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) controller.Title = conversation.Name; ShowViewController (controller, this); } else { - var photo = conversation.Photos.GetItem <Photo> (conversation.Photos.Count - 1); + var photo = conversation.Photos.GetItem<Photo> (conversation.Photos.Count - 1); var controller = new PhotoViewController { Photo = photo, Title = conversation.Name @@ -115,7 +113,7 @@ void ShowProfile (object sender, EventArgs e) controller.NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, CloseProfile); var navController = new UINavigationController (controller); navController.ModalPresentationStyle = UIModalPresentationStyle.Popover; - navController.PopoverPresentationController.BarButtonItem = (UIBarButtonItem)sender; + navController.PopoverPresentationController.BarButtonItem = (UIBarButtonItem) sender; navController.PopoverPresentationController.PermittedArrowDirections = UIPopoverArrowDirection.Any; PresentViewController (navController, true, null); } @@ -133,7 +131,7 @@ bool ShouldShowConversationViewForIndexPath (NSIndexPath indexPath) Conversation ConversationForIndexPath (NSIndexPath indexPath) { - return User.Conversations.GetItem<Conversation> ((nuint)indexPath.Item); + return User.Conversations.GetItem<Conversation> ((nuint) indexPath.Item); } } } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/PhotoViewController.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/PhotoViewController.cs index add0dbbdb..c57d71b6c 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/PhotoViewController.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/PhotoViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; -namespace AdaptivePhotos -{ - public class PhotoViewController : CustomViewController - { +namespace AdaptivePhotos { + public class PhotoViewController : CustomViewController { Photo photo; public Photo Photo { @@ -88,7 +86,7 @@ public override void LoadView () "overlayButton", overlayButton)); foreach (var constraint in constraints) - constraint.Priority = (int)UILayoutPriority.Required - 1; + constraint.Priority = (int) UILayoutPriority.Required - 1; View.AddConstraints (constraints.ToArray ()); } @@ -100,7 +98,7 @@ public override Photo ContainedPhoto (Photo photo) void RatingChanges (object sender, EventArgs e) { - photo.Rating = ((RatingControl)sender).Rating; + photo.Rating = ((RatingControl) sender).Rating; } void UpdatePhoto () diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ProfileViewController.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ProfileViewController.cs index ae56f1e94..16787d908 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ProfileViewController.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/ProfileViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Collections.Generic; using UIKit; -namespace AdaptivePhotos -{ - public class ProfileViewController : CustomViewController - { +namespace AdaptivePhotos { + public class ProfileViewController : CustomViewController { List<NSLayoutConstraint> constraints; User user; @@ -26,7 +24,7 @@ string PhotosText { get { nuint photosCount = 0; for (nuint i = 0; i < User.Conversations.Count; i++) - photosCount += User.Conversations.GetItem <Conversation> (i).Photos.Count; + photosCount += User.Conversations.GetItem<Conversation> (i).Photos.Count; return string.Format ("{0} photos", photosCount); } @@ -40,7 +38,7 @@ string PhotosText { UILabel PhotosLabel { get; set; } - public User User { + public User User { get { return user; } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/TraitOverrideViewController.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/TraitOverrideViewController.cs index 950b99060..28b4c376d 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/TraitOverrideViewController.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/TraitOverrideViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using CoreGraphics; using Foundation; using UIKit; -namespace AdaptivePhotos -{ - public class TraitOverrideViewController : CustomViewController - { +namespace AdaptivePhotos { + public class TraitOverrideViewController : CustomViewController { UITraitCollection forcedTraitCollection = new UITraitCollection (); UIViewController viewController; diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/UIViewController+ViewControllerShowing.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/UIViewController+ViewControllerShowing.cs index 434d40c58..98ccc2bfd 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Controller/UIViewController+ViewControllerShowing.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Controller/UIViewController+ViewControllerShowing.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using Foundation; using ObjCRuntime; using System.Reflection; -namespace AdaptivePhotos -{ - public class CustomTableViewController : UITableViewController - { +namespace AdaptivePhotos { + public class CustomTableViewController : UITableViewController { public CustomTableViewController (UITableViewStyle style) : base (style) { } @@ -20,7 +18,7 @@ public bool WillShowingViewControllerPushWithSender () if (target != null) { var type = target.GetType (); MethodInfo method = type.GetMethod ("WillShowingDetailViewControllerPushWithSender"); - return (bool)method.Invoke (target, new object[] { }); + return (bool) method.Invoke (target, new object [] { }); } else { return false; } @@ -34,7 +32,7 @@ public bool WillShowingDetailViewControllerPushWithSender () if (target != null) { var type = target.GetType (); MethodInfo method = type.GetMethod ("WillShowingDetailViewControllerPushWithSender"); - return (bool)method.Invoke (target, new object[] { }); + return (bool) method.Invoke (target, new object [] { }); } else { return false; } @@ -58,15 +56,14 @@ public Photo CurrentVisibleDetailPhotoWithSender () if (target != null) { var type = target.GetType (); MethodInfo method = type.GetMethod ("CurrentVisibleDetailPhotoWithSender"); - return (Photo)method.Invoke (target, new object[] { }); + return (Photo) method.Invoke (target, new object [] { }); } else { return null; } } } - public class CustomViewController : UIViewController - { + public class CustomViewController : UIViewController { public bool WillShowingViewControllerPushWithSender () { var selector = new Selector ("WillShowingViewControllerPushWithSender"); @@ -75,7 +72,7 @@ public bool WillShowingViewControllerPushWithSender () if (target != null) { var type = target.GetType (); MethodInfo method = type.GetMethod ("WillShowingDetailViewControllerPushWithSender"); - return (bool)method.Invoke (target, new object[] { }); + return (bool) method.Invoke (target, new object [] { }); } else { return false; } @@ -89,7 +86,7 @@ public bool WillShowingDetailViewControllerPushWithSender () if (target != null) { var type = target.GetType (); MethodInfo method = type.GetMethod ("WillShowingDetailViewControllerPushWithSender"); - return (bool)method.Invoke (target, new object[] { }); + return (bool) method.Invoke (target, new object [] { }); } else { return false; } @@ -106,8 +103,7 @@ public virtual bool ContainsPhoto (Photo photo) } } - public class CustomNavigationController : UINavigationController - { + public class CustomNavigationController : UINavigationController { public CustomNavigationController (UIViewController viewController) : base (viewController) { } @@ -119,8 +115,7 @@ public bool WillShowingDetailViewControllerPushWithSender () } } - public class CustomSplitViewController : UISplitViewController - { + public class CustomSplitViewController : UISplitViewController { [Export ("WillShowingViewControllerPushWithSender")] public bool WillShowingViewControllerPushWithSender () { @@ -134,7 +129,7 @@ public bool WillShowingDetailViewControllerPushWithSender () var target = this.ViewControllers [this.ViewControllers.Length - 1]; var type = target.GetType (); MethodInfo method = type.GetMethod ("WillShowingDetailViewControllerPushWithSender"); - return (bool)method.Invoke (target, new object[] { }); + return (bool) method.Invoke (target, new object [] { }); } else { return false; } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Main.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Main.cs index f7953abd2..1651abd7c 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Main.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace AdaptivePhotos -{ - public class Application - { +namespace AdaptivePhotos { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Model/Conversation.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Model/Conversation.cs index e924b7806..e52bfaf3e 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Model/Conversation.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Model/Conversation.cs @@ -1,26 +1,24 @@ -using System; +using System; using Foundation; -namespace AdaptivePhotos -{ - public class Conversation : NSObject - { +namespace AdaptivePhotos { + public class Conversation : NSObject { public NSArray Photos { get; private set; } public string Name { get; private set; } public static Conversation ConversationWithDictionary (NSDictionary dictionary) { - var photoValues = (NSArray)dictionary.ObjectForKey (new NSString ("photos")); + var photoValues = (NSArray) dictionary.ObjectForKey (new NSString ("photos")); var photos = new NSMutableArray (photoValues.Count); for (nuint i = 0; i < photoValues.Count; i++) { - var photo = Photo.PhotoWithDictionary (photoValues.GetItem <NSDictionary> (i)); + var photo = Photo.PhotoWithDictionary (photoValues.GetItem<NSDictionary> (i)); photos.Add (photo); } return new Conversation { - Name = (NSString)dictionary.ObjectForKey (new NSString ("name")), + Name = (NSString) dictionary.ObjectForKey (new NSString ("name")), Photos = photos }; } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Model/Photo.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Model/Photo.cs index a72a7f956..4154d636b 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Model/Photo.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Model/Photo.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; using Foundation; -namespace AdaptivePhotos -{ - public class Photo : NSObject - { +namespace AdaptivePhotos { + public class Photo : NSObject { public UIImage Image { get { return UIImage.FromBundle (ImageName + ".jpg"); @@ -21,9 +19,9 @@ public UIImage Image { public static Photo PhotoWithDictionary (NSDictionary dictionary) { return new Photo { - ImageName = (NSString)dictionary.ObjectForKey (new NSString ("imageName")), - Comment = (NSString)dictionary.ObjectForKey (new NSString ("comment")), - Rating = ((NSNumber)dictionary.ObjectForKey (new NSString ("rating"))).UInt32Value, + ImageName = (NSString) dictionary.ObjectForKey (new NSString ("imageName")), + Comment = (NSString) dictionary.ObjectForKey (new NSString ("comment")), + Rating = ((NSNumber) dictionary.ObjectForKey (new NSString ("rating"))).UInt32Value, }; } } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/Model/User.cs b/ios8/AdaptivePhotos/AdaptivePhotos/Model/User.cs index 963af80f8..929cba022 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/Model/User.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/Model/User.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; -namespace AdaptivePhotos -{ - public class User - { +namespace AdaptivePhotos { + public class User { public string Name { get; private set; } public NSArray Conversations { get; private set; } @@ -13,8 +11,8 @@ public class User public static User UserWithDictionary (NSDictionary dictionary) { - string name = (NSString)dictionary.ObjectForKey (new NSString ("name")); - var conversationDictionaries = (NSArray)dictionary.ObjectForKey (new NSString ("conversations")); + string name = (NSString) dictionary.ObjectForKey (new NSString ("name")); + var conversationDictionaries = (NSArray) dictionary.ObjectForKey (new NSString ("conversations")); var conversations = new NSMutableArray (conversationDictionaries.Count); for (nuint i = 0; i < conversationDictionaries.Count; i++) { @@ -22,7 +20,7 @@ public static User UserWithDictionary (NSDictionary dictionary) conversations.Add (conversation); } - var lastPhotoDictionary = NSDictionary.FromDictionary ((NSDictionary)dictionary.ObjectForKey (new NSString ("lastPhoto"))); + var lastPhotoDictionary = NSDictionary.FromDictionary ((NSDictionary) dictionary.ObjectForKey (new NSString ("lastPhoto"))); return new User { Name = name, diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/View/OverlayView.cs b/ios8/AdaptivePhotos/AdaptivePhotos/View/OverlayView.cs index 73d0904f3..050e5867e 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/View/OverlayView.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/View/OverlayView.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using CoreGraphics; using Foundation; using UIKit; -namespace AdaptivePhotos -{ - public class OverlayView : UIView - { +namespace AdaptivePhotos { + public class OverlayView : UIView { UILabel label; public string Text { @@ -76,7 +74,7 @@ public override void TraitCollectionDidChange (UITraitCollection previousTraitCo base.TraitCollectionDidChange (previousTraitCollection); if ((TraitCollection.VerticalSizeClass != previousTraitCollection.VerticalSizeClass) || - (TraitCollection.VerticalSizeClass != previousTraitCollection.HorizontalSizeClass)) { + (TraitCollection.VerticalSizeClass != previousTraitCollection.HorizontalSizeClass)) { InvalidateIntrinsicContentSize (); } } diff --git a/ios8/AdaptivePhotos/AdaptivePhotos/View/RatingControl.cs b/ios8/AdaptivePhotos/AdaptivePhotos/View/RatingControl.cs index c821498ce..22375a984 100644 --- a/ios8/AdaptivePhotos/AdaptivePhotos/View/RatingControl.cs +++ b/ios8/AdaptivePhotos/AdaptivePhotos/View/RatingControl.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using CoreGraphics; using Foundation; using UIKit; -namespace AdaptivePhotos -{ - public class RatingControl : UIControl - { +namespace AdaptivePhotos { + public class RatingControl : UIControl { const int ratingControlMinimumRating = 0; const int ratingControlMaximumRating = 4; @@ -78,12 +76,12 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) void UpdateImageViews () { for (nuint i = 0; i < ImageViews.Count; i++) - ImageViews.GetItem <UIImageView> (i).Highlighted = (i + ratingControlMinimumRating <= Rating); + ImageViews.GetItem<UIImageView> (i).Highlighted = (i + ratingControlMinimumRating <= Rating); } void UpdateRatingWithTouches (NSSet touches, UIEvent evt) { - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; CGPoint position = touch.LocationInView (this); UIView touchedView = HitTest (position, evt); @@ -109,7 +107,7 @@ void SetupConstraints () UIImageView lastImageView = null; for (nuint i = 0; i < ImageViews.Count; i++) { - var imageView = ImageViews.GetItem <UIImageView> (i); + var imageView = ImageViews.GetItem<UIImageView> (i); imageView.TranslatesAutoresizingMaskIntoConstraints = false; AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-4-[imageView]-4-|", diff --git a/ios8/BracketStripes/BracketStripes/AppDelegate.cs b/ios8/BracketStripes/BracketStripes/AppDelegate.cs index 8d9253810..736242153 100644 --- a/ios8/BracketStripes/BracketStripes/AppDelegate.cs +++ b/ios8/BracketStripes/BracketStripes/AppDelegate.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace BracketStripes -{ +namespace BracketStripes { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios8/BracketStripes/BracketStripes/Controllers/CameraViewController.cs b/ios8/BracketStripes/BracketStripes/Controllers/CameraViewController.cs index f6fc3312c..7aedc5178 100644 --- a/ios8/BracketStripes/BracketStripes/Controllers/CameraViewController.cs +++ b/ios8/BracketStripes/BracketStripes/Controllers/CameraViewController.cs @@ -7,10 +7,8 @@ using Foundation; using UIKit; -namespace BracketStripes -{ - public partial class CameraViewController : UIViewController - { +namespace BracketStripes { + public partial class CameraViewController : UIViewController { private AVCaptureSession captureSession; private AVCaptureDevice captureDevice; private AVCaptureDeviceFormat captureDeviceFormat; @@ -31,12 +29,12 @@ public bool UserInterfaceEnabled { } } - private List <AVCaptureBracketedStillImageSettings> ExposureBrackets { + private List<AVCaptureBracketedStillImageSettings> ExposureBrackets { get { - var brackets = new List <AVCaptureBracketedStillImageSettings> (); + var brackets = new List<AVCaptureBracketedStillImageSettings> (); nuint fixedBracketCount = 3; - var biasValues = new float[] { -2f, 0f, 2f }; + var biasValues = new float [] { -2f, 0f, 2f }; for (nuint index = 0; index < Math.Min (fixedBracketCount, maxBracketCount); index++) { float biasValue = biasValues [index]; @@ -47,9 +45,9 @@ private List <AVCaptureBracketedStillImageSettings> ExposureBrackets { } } - private List <AVCaptureBracketedStillImageSettings> DurationISOBrackets { + private List<AVCaptureBracketedStillImageSettings> DurationISOBrackets { get { - var brackets = new List <AVCaptureBracketedStillImageSettings> (); + var brackets = new List<AVCaptureBracketedStillImageSettings> (); Console.WriteLine ("Camera device ISO range: [{0:##}, {1:##}]", captureDeviceFormat.MinISO, captureDeviceFormat.MaxISO); @@ -58,13 +56,13 @@ private List <AVCaptureBracketedStillImageSettings> DurationISOBrackets { captureDeviceFormat.MinExposureDuration.Seconds, captureDeviceFormat.MaxExposureDuration.Seconds); nuint fixedBracketCount = 3; - var ISOValues = new float[] { 50f, 60f, 500f }; - var durationSecondsValues = new float[] { 0.25f, 0.05f, 0.005f }; + var ISOValues = new float [] { 50f, 60f, 500f }; + var durationSecondsValues = new float [] { 0.25f, 0.05f, 0.005f }; for (nuint index = 0; index < Math.Min (fixedBracketCount, maxBracketCount); index++) { - float ISO = (float)Clamp (ISOValues [index], captureDeviceFormat.MinISO, captureDeviceFormat.MaxISO); + float ISO = (float) Clamp (ISOValues [index], captureDeviceFormat.MinISO, captureDeviceFormat.MaxISO); double durationSeconds = Clamp (durationSecondsValues [index], - captureDeviceFormat.MinExposureDuration.Seconds, captureDeviceFormat.MaxExposureDuration.Seconds); + captureDeviceFormat.MinExposureDuration.Seconds, captureDeviceFormat.MaxExposureDuration.Seconds); var duration = CMTime.FromSeconds (durationSeconds, 483); brackets.Add (AVCaptureManualExposureBracketedStillImageSettings.Create (duration, ISO)); @@ -223,7 +221,7 @@ private void PrepareBracketsWithCompletionHandler (Action<bool, NSError> complet if (imageStripes != null) imageStripes.Dispose (); - imageStripes = new StripedImage (dimensions, (int)dimensions.Width / 12, (int)bracketSettings.Count); + imageStripes = new StripedImage (dimensions, (int) dimensions.Width / 12, (int) bracketSettings.Count); Console.WriteLine ("Warming brackets: {0}", bracketSettings.Count); AVCaptureConnection connection = stillImageOutput.ConnectionFromMediaType (AVMediaType.Video); stillImageOutput.PrepareToCaptureStillImageBracket (connection, bracketSettings.ToArray (), (success, error) => { diff --git a/ios8/BracketStripes/BracketStripes/Controllers/ImageViewController.cs b/ios8/BracketStripes/BracketStripes/Controllers/ImageViewController.cs index ebe056ce2..40b3a620b 100644 --- a/ios8/BracketStripes/BracketStripes/Controllers/ImageViewController.cs +++ b/ios8/BracketStripes/BracketStripes/Controllers/ImageViewController.cs @@ -7,10 +7,8 @@ using System.Collections.Generic; using System.Runtime.InteropServices; -namespace BracketStripes -{ - public class ImageViewController : UIViewController - { +namespace BracketStripes { + public class ImageViewController : UIViewController { public Action<ImageViewController> ImageViewControllerDidFinish { get; set; } public ZoomImageView ImageView { get; set; } diff --git a/ios8/BracketStripes/BracketStripes/Main.cs b/ios8/BracketStripes/BracketStripes/Main.cs index e44b29f56..ad641c1bc 100644 --- a/ios8/BracketStripes/BracketStripes/Main.cs +++ b/ios8/BracketStripes/BracketStripes/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace BracketStripes -{ - public class Application - { +namespace BracketStripes { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/BracketStripes/BracketStripes/Utilities/StripedImage.cs b/ios8/BracketStripes/BracketStripes/Utilities/StripedImage.cs index 32890de25..c1b95ddcf 100644 --- a/ios8/BracketStripes/BracketStripes/Utilities/StripedImage.cs +++ b/ios8/BracketStripes/BracketStripes/Utilities/StripedImage.cs @@ -9,10 +9,8 @@ using CoreVideo; using System.Diagnostics; -namespace BracketStripes -{ - public class StripedImage : NSObject - { +namespace BracketStripes { + public class StripedImage : NSObject { private CGSize imageSize; private CGSize stripeSize; private int stride; @@ -31,20 +29,20 @@ public StripedImage (CGSize size, int stripWidth, int stride) private void PrepareImage (CGSize size) { nint bitsPerComponent = 8; - nint width = (nint)size.Width; + nint width = (nint) size.Width; nint paddedWidth = (width + 15); nint bytesPerPixel = 4; nint bytesPerRow = paddedWidth * bytesPerPixel; using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) { - renderContext = new CGBitmapContext (null, (nint)size.Width, (nint)size.Height, bitsPerComponent, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst); + renderContext = new CGBitmapContext (null, (nint) size.Width, (nint) size.Height, bitsPerComponent, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedFirst); } } public void AddSampleBuffer (CMSampleBuffer sampleBuffer) { - var stopwatch = new Stopwatch(); - stopwatch.Start(); + var stopwatch = new Stopwatch (); + stopwatch.Start (); using (var image = CreateImage (sampleBuffer)) { var imageRect = new CGRect (0, 0, image.Width, image.Height); @@ -63,7 +61,7 @@ public void AddSampleBuffer (CMSampleBuffer sampleBuffer) renderContext.RestoreState (); } - stopwatch.Stop(); + stopwatch.Stop (); Console.WriteLine ("Render time for contributor {0}: {1} msec", stripeIndex, stopwatch.Elapsed); stripeIndex = (stripeIndex + 1) % stride; @@ -96,7 +94,7 @@ private CGImage CreateImage (CMSampleBuffer sampleBuffer) CMBlockBuffer blockBuffer = sampleBuffer.GetDataBuffer (); if (blockBuffer != null) { - if (subType != (int)CMVideoCodecType.JPEG) + if (subType != (int) CMVideoCodecType.JPEG) throw new Exception ("Block buffer must be JPEG encoded."); var jpegData = new NSMutableData (); @@ -114,14 +112,14 @@ private CGImage CreateImage (CMSampleBuffer sampleBuffer) } } else { - if (subType != (int)CVPixelFormatType.CV32BGRA) + if (subType != (int) CVPixelFormatType.CV32BGRA) throw new Exception ("Image buffer must be BGRA encoded."); CVImageBuffer imageBuffer = sampleBuffer.GetImageBuffer (); using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) using (var bitmapContext = new CGBitmapContext (imageBuffer.Handle, - (int)imageBuffer.DisplaySize.Width, (int)imageBuffer.DisplaySize.Height, 8, 0, colorSpace, CGImageAlphaInfo.NoneSkipFirst)) { + (int) imageBuffer.DisplaySize.Width, (int) imageBuffer.DisplaySize.Height, 8, 0, colorSpace, CGImageAlphaInfo.NoneSkipFirst)) { image = bitmapContext.ToImage (); } } diff --git a/ios8/BracketStripes/BracketStripes/Views/CapturePreviewView.cs b/ios8/BracketStripes/BracketStripes/Views/CapturePreviewView.cs index bcea9b15e..3a840f6bf 100644 --- a/ios8/BracketStripes/BracketStripes/Views/CapturePreviewView.cs +++ b/ios8/BracketStripes/BracketStripes/Views/CapturePreviewView.cs @@ -3,10 +3,8 @@ using UIKit; using AVFoundation; -namespace BracketStripes -{ - public partial class CapturePreviewView : UIView - { +namespace BracketStripes { + public partial class CapturePreviewView : UIView { private NSString capturingStillImageKeypath = new NSString ("capturingStillImage"); private UIView flashView; private AVCaptureVideoPreviewLayer previewLayer; @@ -40,7 +38,7 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio { if ((ofObject == CaptureOutput) && (keyPath == capturingStillImageKeypath)) { var ch = new NSObservedChange (change); - var value = (NSNumber)ch.NewValue; + var value = (NSNumber) ch.NewValue; AnimateVisualShutter (value.BoolValue); return; } diff --git a/ios8/BracketStripes/BracketStripes/Views/ZoomImageView.cs b/ios8/BracketStripes/BracketStripes/Views/ZoomImageView.cs index 848266006..d2e4500b7 100644 --- a/ios8/BracketStripes/BracketStripes/Views/ZoomImageView.cs +++ b/ios8/BracketStripes/BracketStripes/Views/ZoomImageView.cs @@ -6,10 +6,8 @@ using UIKit; using System.Collections.Generic; -namespace BracketStripes -{ - public class ZoomImageView : UIView, IUIScrollViewDelegate - { +namespace BracketStripes { + public class ZoomImageView : UIView, IUIScrollViewDelegate { private UIScrollView scrollView; private UIImageView imageView; @@ -93,12 +91,12 @@ private void CenterImageInScrollView () CGRect frameToCenter = imageView.Frame; if (frameToCenter.Size.Width < boundsSize.Width) - frameToCenter.X = ((int)boundsSize.Width - frameToCenter.Size.Width) / 2; + frameToCenter.X = ((int) boundsSize.Width - frameToCenter.Size.Width) / 2; else frameToCenter.X = 0; if (frameToCenter.Size.Height < boundsSize.Height) - frameToCenter.Y = ((int)boundsSize.Height - frameToCenter.Size.Height) / 2; + frameToCenter.Y = ((int) boundsSize.Height - frameToCenter.Size.Height) / 2; else frameToCenter.Y = 0; diff --git a/ios8/CSSceneKit/CSSceneKit/AppDelegate.cs b/ios8/CSSceneKit/CSSceneKit/AppDelegate.cs index 7be96c611..19a571710 100644 --- a/ios8/CSSceneKit/CSSceneKit/AppDelegate.cs +++ b/ios8/CSSceneKit/CSSceneKit/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace CSSceneKit -{ +namespace CSSceneKit { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { @@ -21,8 +19,8 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary // If not required for your application you can safely delete this method // Code to start the Xamarin Test Cloud Agent - #if ENABLE_TEST_CLOUD - #endif +#if ENABLE_TEST_CLOUD +#endif return true; } diff --git a/ios8/CSSceneKit/CSSceneKit/Main.cs b/ios8/CSSceneKit/CSSceneKit/Main.cs index 210062e75..711b2e4b6 100644 --- a/ios8/CSSceneKit/CSSceneKit/Main.cs +++ b/ios8/CSSceneKit/CSSceneKit/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace CSSceneKit -{ - public class Application - { +namespace CSSceneKit { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/CSSceneKit/CSSceneKit/ViewController.cs b/ios8/CSSceneKit/CSSceneKit/ViewController.cs index 966a0abfb..f153d1e25 100644 --- a/ios8/CSSceneKit/CSSceneKit/ViewController.cs +++ b/ios8/CSSceneKit/CSSceneKit/ViewController.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Linq; using UIKit; using SceneKit; -namespace CSSceneKit -{ - public partial class ViewController : UIViewController - { +namespace CSSceneKit { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } - int Building (float width, float length, float height, float posx, float posy, SCNScene scene, Random rnd) + int Building (float width, float length, float height, float posx, float posy, SCNScene scene, Random rnd) { var boxNode = new SCNNode () { Geometry = new SCNBox { @@ -21,12 +19,12 @@ int Building (float width, float length, float height, float posx, float posy, S Length = length, ChamferRadius = 0.02f }, - Position = new SCNVector3(posx, height/2.0f, posy) + Position = new SCNVector3 (posx, height / 2.0f, posy) }; scene.RootNode.AddChildNode (boxNode); - var buildings = new[] { "Content/building1.jpg", "Content/building2.jpg","Content/building3.jpg" }; + var buildings = new [] { "Content/building1.jpg", "Content/building2.jpg", "Content/building3.jpg" }; var material = new SCNMaterial (); material.Diffuse.Contents = UIImage.FromFile (buildings [rnd.Next (buildings.Length)]); material.Diffuse.ContentsTransform = SCNMatrix4.Scale (new SCNVector3 (width, height, 1.0f)); @@ -50,7 +48,7 @@ public override void ViewDidLoad () var rnd = new Random (); Func<int, int, bool, float> random = (min, max, clamp) => { - float num = (float)((double)rnd.Next(min, max) * rnd.NextDouble ()); + float num = (float) ((double) rnd.Next (min, max) * rnd.NextDouble ()); if (!clamp) return num; else if (num < 1.0f) @@ -60,9 +58,9 @@ public override void ViewDidLoad () }; Enumerable.Range (0, 200).Select<int, int> ((i) => Building ( - random (2,5, true), - random (2,5, true), - random (2,10, true), + random (2, 5, true), + random (2, 5, true), + random (2, 10, true), random (-20, 20, false), random (-20, 20, false), scene, @@ -70,7 +68,7 @@ public override void ViewDidLoad () )).ToArray (); //Lights! - var lightNode = new SCNNode() { + var lightNode = new SCNNode () { Light = new SCNLight (), Position = new SCNVector3 (30.0F, 20.0F, 60.0F) }; @@ -96,9 +94,9 @@ public override void ViewDidLoad () scene.RootNode.AddChildNode (targetNode); var lc = SCNLookAtConstraint.Create (targetNode); - cameraNode.Constraints = new[] { lc }; + cameraNode.Constraints = new [] { lc }; - var scnView = new SCNView(UIScreen.MainScreen.Bounds) { + var scnView = new SCNView (UIScreen.MainScreen.Bounds) { Scene = scene, AllowsCameraControl = true, ShowsStatistics = true, @@ -114,7 +112,7 @@ public override void ViewDidLoad () }; var pi2 = Math.PI / 2.0; - floorNode.Orientation = SCNQuaternion.FromAxisAngle (SCNVector3.UnitX, (float)(0.0 - pi2)); + floorNode.Orientation = SCNQuaternion.FromAxisAngle (SCNVector3.UnitX, (float) (0.0 - pi2)); scene.RootNode.AddChildNode (floorNode); diff --git a/ios8/CloudCaptions/CloudCaptions/AppDelegate.cs b/ios8/CloudCaptions/CloudCaptions/AppDelegate.cs index 9320329a5..c173c0e9c 100644 --- a/ios8/CloudCaptions/CloudCaptions/AppDelegate.cs +++ b/ios8/CloudCaptions/CloudCaptions/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,21 +6,19 @@ using UIKit; using CloudKit; -namespace CloudCaptions -{ +namespace CloudCaptions { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } - [Outlet("tableController")] + [Outlet ("tableController")] public MainViewController TableController { get; set; } public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // Override point for customization after application launch. UIUserNotificationSettings notificationSettings = UIUserNotificationSettings.GetSettingsForTypes (UIUserNotificationType.Alert, null); - app.RegisterUserNotificationSettings (notificationSettings);; + app.RegisterUserNotificationSettings (notificationSettings); ; app.RegisterForRemoteNotifications (); return true; @@ -32,7 +30,7 @@ public override void DidReceiveRemoteNotification (UIApplication application, NS return; // Sends the ID of the record save that triggered the push to the tableViewController - var recordInfo = (CKQueryNotification)CKQueryNotification.FromRemoteNotificationDictionary (userInfo); + var recordInfo = (CKQueryNotification) CKQueryNotification.FromRemoteNotificationDictionary (userInfo); TableController.LoadNewPostsWithRecordID (recordInfo.RecordId); } } diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/CKErrorInfo.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/CKErrorInfo.cs index 58a1eb7b8..b5d6b0046 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/CKErrorInfo.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/CKErrorInfo.cs @@ -1,24 +1,22 @@ -using System; +using System; using Foundation; using CloudKit; -namespace CloudCaptions -{ +namespace CloudCaptions { // TODO: https://trello.com/c/Yu3OnaUH - public class CKErrorInfo : DictionaryContainer - { + public class CKErrorInfo : DictionaryContainer { public nint? RetryAfter { get { NSObject obj; if (!base.Dictionary.TryGetValue (CKErrorFields.ErrorRetryAfterKey, out obj)) - return (nint?)null; + return (nint?) null; - return ((NSNumber)obj).NIntValue; + return ((NSNumber) obj).NIntValue; } } - public NSError this[CKRecordID key] { + public NSError this [CKRecordID key] { get { NSDictionary dict = base.GetNSDictionary (CKErrorFields.PartialErrorsByItemIdKey); if (dict == null) @@ -28,17 +26,17 @@ public NSError this[CKRecordID key] { if (!dict.TryGetValue (key, out obj)) return null; - return (NSError)obj; + return (NSError) obj; } } public CKErrorInfo (NSError error) - : this(error.UserInfo) + : this (error.UserInfo) { } public CKErrorInfo (NSDictionary dictionary) - : base(dictionary) + : base (dictionary) { } } diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/Error.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/Error.cs index e6782c400..c0468f67f 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/Error.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/Error.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace CloudCaptions -{ - public enum Error - { +namespace CloudCaptions { + public enum Error { Ignore, Retry, Success diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/ExistingImageViewController.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/ExistingImageViewController.cs index 8238bc79d..3bdf6e8d7 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/ExistingImageViewController.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/ExistingImageViewController.cs @@ -1,20 +1,17 @@ -using System; +using System; using UIKit; using CloudKit; using CoreGraphics; using Foundation; -namespace CloudCaptions -{ - [Register("ExistingImageViewController")] - public class ExistingImageViewController : UIViewController - { - class CollectionViewDelegate : UICollectionViewDelegate - { +namespace CloudCaptions { + [Register ("ExistingImageViewController")] + public class ExistingImageViewController : UIViewController { + class CollectionViewDelegate : UICollectionViewDelegate { readonly ExistingImageViewController controller; - public CollectionViewDelegate(ExistingImageViewController controller) + public CollectionViewDelegate (ExistingImageViewController controller) { this.controller = controller; } @@ -23,7 +20,7 @@ public override void Scrolled (UIScrollView scrollView) { // Gets the point at the bottom of the scroll view var contentOffset = scrollView.ContentOffset; - CGPoint bottomRowPoint = new CGPoint(contentOffset.X, contentOffset.Y + scrollView.Bounds.Size.Height); + CGPoint bottomRowPoint = new CGPoint (contentOffset.X, contentOffset.Y + scrollView.Bounds.Size.Height); // Finds number of rows left (gets height of row and adds 5 px spacing between rows) var flowLayout = (UICollectionViewFlowLayout) controller.ImageCollection.CollectionViewLayout; @@ -32,7 +29,7 @@ public override void Scrolled (UIScrollView scrollView) nfloat rowsLeft = (scrollView.ContentSize.Height - bottomRowPoint.Y) / (rowHeight + rowSpacing); // If we have less five rows left, load the next set - if ((int)rowsLeft < 5) + if ((int) rowsLeft < 5) controller.LoadImages (); } @@ -52,43 +49,43 @@ public override void ItemSelected (UICollectionView collectionView, NSIndexPath CKRecordID userSelectedRecordID = controller.ImageCollection.GetRecordId (indexPath); controller.PublicCloudDatabase.FetchRecord (userSelectedRecordID, (record, error) => { // If we get a partial failure, we should unwrap it - if(error != null && error.Code == (long)CKErrorCode.PartialFailure) { - CKErrorInfo info = new CKErrorInfo(error); - error = info[userSelectedRecordID]; + if (error != null && error.Code == (long) CKErrorCode.PartialFailure) { + CKErrorInfo info = new CKErrorInfo (error); + error = info [userSelectedRecordID]; } - Error errorResponse = controller.HandleError(error); - - switch(errorResponse) { - case Error.Success: - controller.ImageCollection.SetLoadingFlag(indexPath, false); - Image selectedImage = new Image(record); - InvokeOnMainThread(() => { - controller.MasterController.GoTo(controller, selectedImage); - }); - break; - - case Error.Retry: - Utils.Retry(()=> { - controller.lockSelectThumbnail = false; - ItemSelected(collectionView, indexPath); - }, error); - break; - - case Error.Ignore: - Console.WriteLine ("Error: {0}", error.Description); - string errorTitle = "Error"; - string errorMessage = "We couldn't fetch the full size thumbnail you tried to select, try again"; - string dismissButton = "Okay"; - UIAlertController alert = UIAlertController.Create(errorTitle, errorMessage, UIAlertControllerStyle.Alert); - alert.AddAction(UIAlertAction.Create(dismissButton, UIAlertActionStyle.Cancel, null)); - InvokeOnMainThread(()=> controller.PresentViewController(alert, true, null)); - controller.ImageCollection.SetLoadingFlag(indexPath, false); + Error errorResponse = controller.HandleError (error); + + switch (errorResponse) { + case Error.Success: + controller.ImageCollection.SetLoadingFlag (indexPath, false); + Image selectedImage = new Image (record); + InvokeOnMainThread (() => { + controller.MasterController.GoTo (controller, selectedImage); + }); + break; + + case Error.Retry: + Utils.Retry (() => { controller.lockSelectThumbnail = false; - break; + ItemSelected (collectionView, indexPath); + }, error); + break; + + case Error.Ignore: + Console.WriteLine ("Error: {0}", error.Description); + string errorTitle = "Error"; + string errorMessage = "We couldn't fetch the full size thumbnail you tried to select, try again"; + string dismissButton = "Okay"; + UIAlertController alert = UIAlertController.Create (errorTitle, errorMessage, UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create (dismissButton, UIAlertActionStyle.Cancel, null)); + InvokeOnMainThread (() => controller.PresentViewController (alert, true, null)); + controller.ImageCollection.SetLoadingFlag (indexPath, false); + controller.lockSelectThumbnail = false; + break; - default: - throw new NotImplementedException(); + default: + throw new NotImplementedException (); } }); } @@ -97,10 +94,10 @@ public override void ItemSelected (UICollectionView collectionView, NSIndexPath // This constant determines the number of images to fetch at a time const int UpdateBy = 24; - [Outlet("imageCollection")] + [Outlet ("imageCollection")] ExistingImageCollectionView ImageCollection { get; set; } - [Outlet("loadingImages")] + [Outlet ("loadingImages")] UIActivityIndicatorView loadingImages { get; set; } CKQueryCursor imageCursor; @@ -110,7 +107,7 @@ public override void ItemSelected (UICollectionView collectionView, NSIndexPath bool lockSelectThumbnail; // Only lets user select one image at a time CollectionViewDelegate collectionViewDelegate; - readonly object locker = new Object(); + readonly object locker = new Object (); CKDatabase PublicCloudDatabase { get { @@ -121,8 +118,8 @@ CKDatabase PublicCloudDatabase { // ExistingImageViewController is detailed controller. Need to store ref to master(parent) controller to perform callback public MainViewController MasterController { get; set; } - public ExistingImageViewController(IntPtr handle) - : base(handle) + public ExistingImageViewController (IntPtr handle) + : base (handle) { } @@ -131,7 +128,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - collectionViewDelegate = new CollectionViewDelegate(this); + collectionViewDelegate = new CollectionViewDelegate (this); ImageCollection.Delegate = collectionViewDelegate; isLoadingBatch = false; firstThumbnailLoaded = false; @@ -139,15 +136,15 @@ public override void ViewDidLoad () // This ensures that there are always three images per row whether it's an iPhone or an iPad (20 px subtracted to account for four 5 px spaces between thumbnails) var screenSize = UIScreen.MainScreen.Bounds.Size; - nfloat smallerDimension = NMath.Min(screenSize.Width, screenSize.Height); // Works even if iPad is rotated - UICollectionViewFlowLayout flowLayout = (UICollectionViewFlowLayout)ImageCollection.CollectionViewLayout; + nfloat smallerDimension = NMath.Min (screenSize.Width, screenSize.Height); // Works even if iPad is rotated + UICollectionViewFlowLayout flowLayout = (UICollectionViewFlowLayout) ImageCollection.CollectionViewLayout; nfloat imageWidth = (smallerDimension - 20) / 3; - flowLayout.ItemSize = new CGSize(imageWidth, imageWidth); + flowLayout.ItemSize = new CGSize (imageWidth, imageWidth); LoadImages (); } - void LoadImages() + void LoadImages () { // If we're already loading a set of images or there are no images left to load, just return lock (locker) { @@ -168,7 +165,7 @@ void LoadImages() } // We only want to download the thumbnails, not the full image - queryOp.DesiredKeys = new string[] { + queryOp.DesiredKeys = new string [] { Image.ThumbnailKey }; queryOp.ResultsLimit = UpdateBy; @@ -217,56 +214,55 @@ Error HandleError (NSError error) if (error == null) return Error.Success; - switch ((CKErrorCode)(long)error.Code) - { - case CKErrorCode.NetworkUnavailable: - case CKErrorCode.NetworkFailure: - // A reachability check might be appropriate here so we don't just keep retrying if the user has no service - case CKErrorCode.ServiceUnavailable: - case CKErrorCode.RequestRateLimited: - return Error.Retry; - - case CKErrorCode.UnknownItem: - Console.WriteLine ("If an image has never been uploaded, CKErrorCode.UnknownItem will be returned in ExistingImageViewController because it has never seen the Image record type"); - return Error.Ignore; - - case CKErrorCode.InvalidArguments: - Console.WriteLine ("If invalid arguments is returned in ExistingImageViewController with a message about not being marked indexable or sortable, go into CloudKit dashboard and set the Image record type as sortable on date created"); - return Error.Ignore; - - case CKErrorCode.IncompatibleVersion: - case CKErrorCode.BadContainer: - case CKErrorCode.MissingEntitlement: - case CKErrorCode.PermissionFailure: - case CKErrorCode.BadDatabase: - // This app uses the publicDB with default world readable permissions - case CKErrorCode.AssetFileNotFound: - case CKErrorCode.QuotaExceeded: - // We should not retry if it'll exceed our quota - case CKErrorCode.OperationCancelled: - // Nothing to do here, we intentionally cancelled - case CKErrorCode.NotAuthenticated: - case CKErrorCode.ResultsTruncated: - case CKErrorCode.ServerRecordChanged: - case CKErrorCode.AssetFileModified: - case CKErrorCode.ChangeTokenExpired: - case CKErrorCode.BatchRequestFailed: - case CKErrorCode.ZoneBusy: - case CKErrorCode.ZoneNotFound: - case CKErrorCode.LimitExceeded: - case CKErrorCode.UserDeletedZone: - // All of these errors are irrelevant for this query operation - case CKErrorCode.InternalError: - case CKErrorCode.ServerRejectedRequest: - case CKErrorCode.ConstraintViolation: - //Non-recoverable, should not retry - default: - return Error.Ignore; + switch ((CKErrorCode) (long) error.Code) { + case CKErrorCode.NetworkUnavailable: + case CKErrorCode.NetworkFailure: + // A reachability check might be appropriate here so we don't just keep retrying if the user has no service + case CKErrorCode.ServiceUnavailable: + case CKErrorCode.RequestRateLimited: + return Error.Retry; + + case CKErrorCode.UnknownItem: + Console.WriteLine ("If an image has never been uploaded, CKErrorCode.UnknownItem will be returned in ExistingImageViewController because it has never seen the Image record type"); + return Error.Ignore; + + case CKErrorCode.InvalidArguments: + Console.WriteLine ("If invalid arguments is returned in ExistingImageViewController with a message about not being marked indexable or sortable, go into CloudKit dashboard and set the Image record type as sortable on date created"); + return Error.Ignore; + + case CKErrorCode.IncompatibleVersion: + case CKErrorCode.BadContainer: + case CKErrorCode.MissingEntitlement: + case CKErrorCode.PermissionFailure: + case CKErrorCode.BadDatabase: + // This app uses the publicDB with default world readable permissions + case CKErrorCode.AssetFileNotFound: + case CKErrorCode.QuotaExceeded: + // We should not retry if it'll exceed our quota + case CKErrorCode.OperationCancelled: + // Nothing to do here, we intentionally cancelled + case CKErrorCode.NotAuthenticated: + case CKErrorCode.ResultsTruncated: + case CKErrorCode.ServerRecordChanged: + case CKErrorCode.AssetFileModified: + case CKErrorCode.ChangeTokenExpired: + case CKErrorCode.BatchRequestFailed: + case CKErrorCode.ZoneBusy: + case CKErrorCode.ZoneNotFound: + case CKErrorCode.LimitExceeded: + case CKErrorCode.UserDeletedZone: + // All of these errors are irrelevant for this query operation + case CKErrorCode.InternalError: + case CKErrorCode.ServerRejectedRequest: + case CKErrorCode.ConstraintViolation: + //Non-recoverable, should not retry + default: + return Error.Ignore; } } - [Export("cancelSelection:")] - void CancelSelection(NSObject sender) + [Export ("cancelSelection:")] + void CancelSelection (NSObject sender) { // If cancel is pressed, dismiss the selection view controller DismissViewController (true, null); diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/MainViewController.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/MainViewController.cs index e1dd72af6..4c78cbf66 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/MainViewController.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/MainViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using CloudKit; @@ -6,27 +6,25 @@ using Foundation; using CoreGraphics; -namespace CloudCaptions -{ - [Register("MainViewController")] - public class MainViewController : UITableViewController, IUIScrollViewDelegate, IUISearchBarDelegate - { - readonly NSString cellReuseIdentifier = new NSString("post"); +namespace CloudCaptions { + [Register ("MainViewController")] + public class MainViewController : UITableViewController, IUIScrollViewDelegate, IUISearchBarDelegate { + readonly NSString cellReuseIdentifier = new NSString ("post"); PostManager postManager; public MainViewController (IntPtr handle) - : base(handle) + : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); - ((AppDelegate)UIApplication.SharedApplication.Delegate).TableController = this; + ((AppDelegate) UIApplication.SharedApplication.Delegate).TableController = this; postManager = new PostManager (() => { - InvokeOnMainThread(() => { TableView.ReloadData(); }); + InvokeOnMainThread (() => { TableView.ReloadData (); }); }); postManager.LoadBatch (); @@ -40,7 +38,7 @@ public override void ViewDidLoad () NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Compose, OnNewPostClicked); } - public async void LoadNewPostsWithRecordID(CKRecordID recordID) + public async void LoadNewPostsWithRecordID (CKRecordID recordID) { // Called when AppDelegate receives a push notification // The post that triggered the push may not be indexed yet, so a fetch on predicate might not see it. @@ -48,10 +46,10 @@ public async void LoadNewPostsWithRecordID(CKRecordID recordID) CKDatabase publicDB = CKContainer.DefaultContainer.PublicCloudDatabase; try { CKRecord record = await publicDB.FetchRecordAsync (recordID); - Post postThatFiredPush = new Post(record); - postThatFiredPush.LoadImage(null, TableView.ReloadData); - postManager.LoadNewPosts(postThatFiredPush); - } catch(NSErrorException ex) { + Post postThatFiredPush = new Post (record); + postThatFiredPush.LoadImage (null, TableView.ReloadData); + postManager.LoadNewPosts (postThatFiredPush); + } catch (NSErrorException ex) { Console.WriteLine (ex.Error); } } @@ -69,28 +67,28 @@ void OnNewPostClicked (object sender, EventArgs e) UIAlertController picMethod = UIAlertController.Create (alertTitle, null, UIAlertControllerStyle.ActionSheet); picMethod.ModalPresentationStyle = UIModalPresentationStyle.Popover; UIPopoverPresentationController popPresenter = picMethod.PopoverPresentationController; - if(popPresenter != null) + if (popPresenter != null) popPresenter.BarButtonItem = NavigationItem.RightBarButtonItem; string takePhotoButton = "Take Photo"; UIAlertAction takePhoto = UIAlertAction.Create (takePhotoButton, UIAlertActionStyle.Default, action => { - var imagePicker = new UIImagePickerController(); + var imagePicker = new UIImagePickerController (); imagePicker.WeakDelegate = this; imagePicker.SourceType = UIImagePickerControllerSourceType.Camera; - PresentViewController(imagePicker, true, null); + PresentViewController (imagePicker, true, null); }); string uploadButton = "Upload Photo"; UIAlertAction uploadPhoto = UIAlertAction.Create (uploadButton, UIAlertActionStyle.Default, action => { - var imagePicker = new UIImagePickerController(); + var imagePicker = new UIImagePickerController (); imagePicker.WeakDelegate = this; imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary; - PresentViewController(imagePicker, true, null); + PresentViewController (imagePicker, true, null); }); string selectButton = "Select from CloudKit"; UIAlertAction selectExisting = UIAlertAction.Create (selectButton, UIAlertActionStyle.Default, action => { - PerformSegue("selectExisting", null); + PerformSegue ("selectExisting", null); }); UIAlertAction cancel = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, null); @@ -116,9 +114,9 @@ public override nint RowsInSection (UITableView tableview, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (PostCell)TableView.DequeueReusableCell (cellReuseIdentifier, indexPath); + var cell = (PostCell) TableView.DequeueReusableCell (cellReuseIdentifier, indexPath); cell = cell ?? new PostCell (); - Post post = postManager.PostCells[indexPath.Row]; + Post post = postManager.PostCells [indexPath.Row]; cell.DisplayInfoForPost (post); return cell; } @@ -133,11 +131,11 @@ public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath index public void Scrolled (UIScrollView scrollView) { // Checks to see if the user has scrolled five posts from the bottom and if we want to update - var tableBottom = new CGPoint(scrollView.ContentOffset.X, scrollView.ContentOffset.Y + scrollView.Bounds.Size.Height); + var tableBottom = new CGPoint (scrollView.ContentOffset.X, scrollView.ContentOffset.Y + scrollView.Bounds.Size.Height); int count = postManager.PostCells.Count; NSIndexPath index = TableView.IndexPathForRowAtPoint (tableBottom); - if( count > 0 && index != null && index.Row + 5 > count) + if (count > 0 && index != null && index.Row + 5 > count) postManager.LoadBatch (); } @@ -181,22 +179,22 @@ public void FinishedPickingMedia (UIImagePickerController picker, NSDictionary i // Dismisses imagePicker and pulls up SubmitPostViewController var imageRecord = new Image (eArg.OriginalImage); picker.DismissViewController (true, () => { - PerformSegue("newPost", imageRecord); + PerformSegue ("newPost", imageRecord); }); } #endregion - public void GoTo(ExistingImageViewController controller, Image image) + public void GoTo (ExistingImageViewController controller, Image image) { // Gets called when the user taps on an image in the collection view // Dismisses collection view and pulls up a SubmitPostViewController controller.DismissViewController (true, () => { - PerformSegue("newPost", image); + PerformSegue ("newPost", image); }); } - public void Submit(Post post) + public void Submit (Post post) { postManager.LoadNewPosts (post); } @@ -206,10 +204,10 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) base.PrepareForSegue (segue, sender); if (segue.Identifier == "selectExisting") { - ((ExistingImageViewController)segue.DestinationViewController).MasterController = this; + ((ExistingImageViewController) segue.DestinationViewController).MasterController = this; } else if (segue.Identifier == "newPost") { - var controller = ((SubmitPostViewController)segue.DestinationViewController); - controller.ImageRecord = (Image)sender; + var controller = ((SubmitPostViewController) segue.DestinationViewController); + controller.ImageRecord = (Image) sender; controller.MainController = this; } else { throw new NotImplementedException ("Unhandled segue"); diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/PostManager.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/PostManager.cs index e64eba4a8..b307ba4ed 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/PostManager.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/PostManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; @@ -7,22 +7,20 @@ using Foundation; using CoreFoundation; -namespace CloudCaptions -{ - public class PostManager - { +namespace CloudCaptions { + public class PostManager { readonly nuint updateBy = 10; Action reloadHandler; Post lastPostSeenOnServer; - string[] tagArray; + string [] tagArray; CKQueryCursor postCursor; - readonly NSOperationQueue fetchRecordQueue; // Allows for us to cancel loadBatch operation when the tag string has changed - readonly DispatchQueue updateCellArrayQueue; // Synchronous dispatch queue to synchronously add objects to postCells collection - bool isLoadingBatch; // Flags when we're loading a batch so we don't try loading a second batch while this one is running - bool haveOldestPost; // Flags when we've loaded the earliest post + readonly NSOperationQueue fetchRecordQueue; // Allows for us to cancel loadBatch operation when the tag string has changed + readonly DispatchQueue updateCellArrayQueue; // Synchronous dispatch queue to synchronously add objects to postCells collection + bool isLoadingBatch; // Flags when we're loading a batch so we don't try loading a second batch while this one is running + bool haveOldestPost; // Flags when we've loaded the earliest post readonly object locker = new object (); - readonly string[] desiredKeys; + readonly string [] desiredKeys; readonly List<Post> downloadingBatchStorage; // we use this storage to hold post during downloading from server public UIRefreshControl RefreshControl { get; set; } @@ -41,9 +39,9 @@ public PostManager (Action reloadHandler) downloadingBatchStorage = new List<Post> (); updateCellArrayQueue = new DispatchQueue ("UpdateCellQueue"); fetchRecordQueue = new NSOperationQueue (); - tagArray = new string[0]; + tagArray = new string [0]; - desiredKeys = new string[] { + desiredKeys = new string [] { Post.ImageRefKey, Post.FontKey, Post.TextKey @@ -52,7 +50,7 @@ public PostManager (Action reloadHandler) #region LoadBatch - public void LoadBatch() + public void LoadBatch () { lock (locker) { // Quickly returns if another loadNextBatch is running or we have the oldest post @@ -66,7 +64,7 @@ public void LoadBatch() fetchRecordQueue.AddOperation (queryOp); } - CKQueryOperation CreateLoadBatchOperation() + CKQueryOperation CreateLoadBatchOperation () { CKQueryOperation queryOp = null; if (postCursor != null) { @@ -89,12 +87,12 @@ CKQueryOperation CreateLoadBatchOperation() return queryOp; } - CKQuery CreatePostQuery() + CKQuery CreatePostQuery () { // Create predicate out of tags. If self.tagArray is empty we should get every post - NSPredicate[] subPredicates = new NSPredicate[tagArray.Length]; + NSPredicate [] subPredicates = new NSPredicate [tagArray.Length]; for (int i = 0; i < tagArray.Length; i++) - subPredicates [i] = Utils.CreateTagPredicate(tagArray [i]); + subPredicates [i] = Utils.CreateTagPredicate (tagArray [i]); // If our tagArray is empty, create a true predicate (as opposed to a predicate containing "Tags CONTAINS ''" NSPredicate finalPredicate = tagArray.Length == 0 @@ -108,52 +106,52 @@ CKQuery CreatePostQuery() return postQuery; } - void OnPostFetched(CKRecord record) + void OnPostFetched (CKRecord record) { // When we get a record, use it to create an Post Post fetchedPost = new Post (record); downloadingBatchStorage.Add (fetchedPost); - fetchedPost.LoadImage (new string[]{ Image.FullsizeKey }, () => { + fetchedPost.LoadImage (new string [] { Image.FullsizeKey }, () => { // Once image is loaded, tell the tableview to reload DispatchQueue.MainQueue.DispatchAsync (reloadHandler); }); } - void OnPostLoadingCompleted(CKQueryCursor cursor, NSError operationError) + void OnPostLoadingCompleted (CKQueryCursor cursor, NSError operationError) { Error error = HandleError (operationError); switch (error) { - case Error.Success: - postCursor = cursor; - haveOldestPost = cursor == null; - isLoadingBatch = false; - PostCells.AddRange (downloadingBatchStorage); - - if (lastPostSeenOnServer == null && PostCells.Count > 0) { - lastPostSeenOnServer = PostCells [0]; - DispatchQueue.MainQueue.DispatchAsync(RefreshControl.EndRefreshing); - } - - DispatchQueue.MainQueue.DispatchAsync (reloadHandler); - break; + case Error.Success: + postCursor = cursor; + haveOldestPost = cursor == null; + isLoadingBatch = false; + PostCells.AddRange (downloadingBatchStorage); + + if (lastPostSeenOnServer == null && PostCells.Count > 0) { + lastPostSeenOnServer = PostCells [0]; + DispatchQueue.MainQueue.DispatchAsync (RefreshControl.EndRefreshing); + } - case Error.Retry: - Utils.Retry (() => { - isLoadingBatch = false; - LoadBatch (); - }, operationError); - break; + DispatchQueue.MainQueue.DispatchAsync (reloadHandler); + break; - case Error.Ignore: + case Error.Retry: + Utils.Retry (() => { isLoadingBatch = false; - DispatchQueue.MainQueue.DispatchAsync (RefreshControl.EndRefreshing); - Console.WriteLine ("Error: {0}", operationError.Description); - break; + LoadBatch (); + }, operationError); + break; + + case Error.Ignore: + isLoadingBatch = false; + DispatchQueue.MainQueue.DispatchAsync (RefreshControl.EndRefreshing); + Console.WriteLine ("Error: {0}", operationError.Description); + break; - default: - break; + default: + break; } } @@ -163,7 +161,7 @@ void OnPostLoadingCompleted(CKQueryCursor cursor, NSError operationError) // Called when users pulls to refresh // This adds new items to the beginning of the table - public void LoadNewPosts(Post post = null) + public void LoadNewPosts (Post post = null) { // If we don't have any posts on our table yet, // fetch the first batch instead (we make assumptions in this method that we have other posts to compare to) @@ -194,11 +192,11 @@ public void LoadNewPosts(Post post = null) fetchRecordQueue.AddOperation (queryOp); } - bool TryLoadFirstBatch() + bool TryLoadFirstBatch () { bool haveNoPost = PostCells.Count == 0 || lastPostSeenOnServer == null; - if(haveNoPost) { + if (haveNoPost) { // We dispatch it after two seconds to give the server time to index the new post // TODO: https://trello.com/c/cWWQXKYY var dispatchTime = new DispatchTime (DispatchTime.Now, 2 * 1000000000); @@ -212,13 +210,13 @@ bool TryLoadFirstBatch() return haveNoPost; } - bool MatchesTags(Post post) + bool MatchesTags (Post post) { if (post == null) return false; var weakTags = post.PostRecord [Post.TagsKey]; - string[] postTags = NSArray.StringArrayFromHandle (weakTags.Handle); + string [] postTags = NSArray.StringArrayFromHandle (weakTags.Handle); // All tags from seach field (tagArray) must be presented inside post foreach (string tag in tagArray) { @@ -230,7 +228,7 @@ bool MatchesTags(Post post) return true; } - CKQuery CreateLoadNewPostQuery() + CKQuery CreateLoadNewPostQuery () { // Creates predicate based on tag string and most recent post from server NSPredicate predicate = CreateLoadNewPostPredicate (); @@ -241,71 +239,71 @@ CKQuery CreateLoadNewPostQuery() return postQuery; } - NSPredicate CreateLoadNewPostPredicate() + NSPredicate CreateLoadNewPostPredicate () { var len = tagArray.Length + 1; - var subPredicates = new NSPredicate[len]; - subPredicates [0] = Utils.CreateAfterPredicate(lastPostSeenOnServer.PostRecord.CreationDate); + var subPredicates = new NSPredicate [len]; + subPredicates [0] = Utils.CreateAfterPredicate (lastPostSeenOnServer.PostRecord.CreationDate); for (int i = 0; i < tagArray.Length; i++) - subPredicates [i + 1] = Utils.CreateTagPredicate(tagArray [i]); + subPredicates [i + 1] = Utils.CreateTagPredicate (tagArray [i]); // ANDs all subpredicates to make a final predicate NSPredicate finalPredicate = NSCompoundPredicate.CreateAndPredicate (subPredicates); return finalPredicate; } - void OnLoadNewPostFetchRecord(CKRecord record, List<Post> newPosts, ref Post lastRecordInOperation) + void OnLoadNewPostFetchRecord (CKRecord record, List<Post> newPosts, ref Post lastRecordInOperation) { // If the record we just fetched doesn't match recordIDs to any item in our newPosts array, let's make an Post and add it - var matchingRecord = newPosts.FindIndex (p => p.PostRecord.Id.Equals(record.Id)); + var matchingRecord = newPosts.FindIndex (p => p.PostRecord.Id.Equals (record.Id)); if (matchingRecord == -1) { Post fetchedPost = new Post (record); newPosts.Add (fetchedPost); - fetchedPost.LoadImage(new string[] { Image.FullsizeKey }, reloadHandler); + fetchedPost.LoadImage (new string [] { Image.FullsizeKey }, reloadHandler); lastRecordInOperation = fetchedPost; } else { // If we already have this record we don't have to fetch. We'll still update lastRecordInOperation because we did see it on the server - lastRecordInOperation = newPosts[matchingRecord]; + lastRecordInOperation = newPosts [matchingRecord]; } } - void OnLoadNewPostComplted(CKQueryCursor cursor, NSError operationError, List<Post> newPosts, Post lastRecordInOperation, Post retryPost) + void OnLoadNewPostComplted (CKQueryCursor cursor, NSError operationError, List<Post> newPosts, Post lastRecordInOperation, Post retryPost) { Error error = HandleError (operationError); switch (error) { - case Error.Success: - // lastRecordCreationDate is the most recent record we've seen on server, let's set our property to that for next time we get a push - lastPostSeenOnServer = lastRecordInOperation ?? lastPostSeenOnServer; - // This sorts the newPosts array in ascending order - newPosts.Sort (PostComparison); - // Takes our newPosts array and inserts the items into the table array one at a time - foreach (Post p in newPosts) { - updateCellArrayQueue.DispatchAsync (() => { - PostCells.Insert (0, p); - DispatchQueue.MainQueue.DispatchAsync (reloadHandler); - }); - } - DispatchQueue.MainQueue.DispatchAsync (RefreshControl.EndRefreshing); - break; - - case Error.Retry: - Utils.Retry(()=> LoadNewPosts(retryPost), operationError); - break; - - case Error.Ignore: - Console.WriteLine ("Error: {0}", operationError.Description); - DispatchQueue.MainQueue.DispatchAsync(RefreshControl.EndRefreshing); - break; - - default: - throw new NotImplementedException (); + case Error.Success: + // lastRecordCreationDate is the most recent record we've seen on server, let's set our property to that for next time we get a push + lastPostSeenOnServer = lastRecordInOperation ?? lastPostSeenOnServer; + // This sorts the newPosts array in ascending order + newPosts.Sort (PostComparison); + // Takes our newPosts array and inserts the items into the table array one at a time + foreach (Post p in newPosts) { + updateCellArrayQueue.DispatchAsync (() => { + PostCells.Insert (0, p); + DispatchQueue.MainQueue.DispatchAsync (reloadHandler); + }); + } + DispatchQueue.MainQueue.DispatchAsync (RefreshControl.EndRefreshing); + break; + + case Error.Retry: + Utils.Retry (() => LoadNewPosts (retryPost), operationError); + break; + + case Error.Ignore: + Console.WriteLine ("Error: {0}", operationError.Description); + DispatchQueue.MainQueue.DispatchAsync (RefreshControl.EndRefreshing); + break; + + default: + throw new NotImplementedException (); } } #endregion - public void ResetWithTagString(string tags) + public void ResetWithTagString (string tags) { // Reloads table with new tag settings // First, anything the table is updating with now is potentially invalid, cancel any current updates @@ -321,8 +319,8 @@ public void ResetWithTagString(string tags) // Sets tag array and prepares table for initial update tagArray = string.IsNullOrWhiteSpace (tags) - ? new string[0] - : tags.ToLower ().Split (new char[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries); + ? new string [0] + : tags.ToLower ().Split (new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries); postCursor = null; isLoadingBatch = false; @@ -330,10 +328,10 @@ public void ResetWithTagString(string tags) LoadBatch (); } - int PostComparison(Post first, Post second) + int PostComparison (Post first, Post second) { - var firstDate = (DateTime)first.PostRecord.CreationDate; - var secondDate = (DateTime)second.PostRecord.CreationDate; + var firstDate = (DateTime) first.PostRecord.CreationDate; + var secondDate = (DateTime) second.PostRecord.CreationDate; return firstDate.CompareTo (secondDate); } @@ -342,52 +340,52 @@ Error HandleError (NSError error) if (error == null) return Error.Success; - switch ((CKErrorCode)(long)error.Code) { - case CKErrorCode.NetworkUnavailable: - case CKErrorCode.NetworkFailure: - // A reachability check might be appropriate here so we don't just keep retrying if the user has no service - case CKErrorCode.ServiceUnavailable: - case CKErrorCode.RequestRateLimited: - return Error.Retry; - - case CKErrorCode.UnknownItem: - Console.WriteLine ("If a post has never been made, CKErrorCode.UnknownItem will be returned in PostManager because it has never seen the Post record type"); - return Error.Ignore; - - case CKErrorCode.InvalidArguments: - Console.WriteLine ("If invalid arguments is returned in PostManager with a message about not being marked indexable or sortable, go into CloudKit dashboard and set the Post record type as sortable on date created (under metadata index)"); - return Error.Ignore; - - case CKErrorCode.IncompatibleVersion: - case CKErrorCode.BadContainer: - case CKErrorCode.MissingEntitlement: - case CKErrorCode.PermissionFailure: - case CKErrorCode.BadDatabase: - // This app uses the publicDB with default world readable permissions - case CKErrorCode.AssetFileNotFound: - case CKErrorCode.PartialFailure: - // These shouldn't occur during a query operation - case CKErrorCode.QuotaExceeded: - // We should not retry if it'll exceed our quota - case CKErrorCode.OperationCancelled: - // Nothing to do here, we intentionally cancelled - case CKErrorCode.NotAuthenticated: - case CKErrorCode.ResultsTruncated: - case CKErrorCode.ServerRecordChanged: - case CKErrorCode.AssetFileModified: - case CKErrorCode.ChangeTokenExpired: - case CKErrorCode.BatchRequestFailed: - case CKErrorCode.ZoneBusy: - case CKErrorCode.ZoneNotFound: - case CKErrorCode.LimitExceeded: - case CKErrorCode.UserDeletedZone: - // All of these errors are irrelevant for this query operation - case CKErrorCode.InternalError: - case CKErrorCode.ServerRejectedRequest: - case CKErrorCode.ConstraintViolation: - //Non-recoverable, should not retry - default: - return Error.Ignore; + switch ((CKErrorCode) (long) error.Code) { + case CKErrorCode.NetworkUnavailable: + case CKErrorCode.NetworkFailure: + // A reachability check might be appropriate here so we don't just keep retrying if the user has no service + case CKErrorCode.ServiceUnavailable: + case CKErrorCode.RequestRateLimited: + return Error.Retry; + + case CKErrorCode.UnknownItem: + Console.WriteLine ("If a post has never been made, CKErrorCode.UnknownItem will be returned in PostManager because it has never seen the Post record type"); + return Error.Ignore; + + case CKErrorCode.InvalidArguments: + Console.WriteLine ("If invalid arguments is returned in PostManager with a message about not being marked indexable or sortable, go into CloudKit dashboard and set the Post record type as sortable on date created (under metadata index)"); + return Error.Ignore; + + case CKErrorCode.IncompatibleVersion: + case CKErrorCode.BadContainer: + case CKErrorCode.MissingEntitlement: + case CKErrorCode.PermissionFailure: + case CKErrorCode.BadDatabase: + // This app uses the publicDB with default world readable permissions + case CKErrorCode.AssetFileNotFound: + case CKErrorCode.PartialFailure: + // These shouldn't occur during a query operation + case CKErrorCode.QuotaExceeded: + // We should not retry if it'll exceed our quota + case CKErrorCode.OperationCancelled: + // Nothing to do here, we intentionally cancelled + case CKErrorCode.NotAuthenticated: + case CKErrorCode.ResultsTruncated: + case CKErrorCode.ServerRecordChanged: + case CKErrorCode.AssetFileModified: + case CKErrorCode.ChangeTokenExpired: + case CKErrorCode.BatchRequestFailed: + case CKErrorCode.ZoneBusy: + case CKErrorCode.ZoneNotFound: + case CKErrorCode.LimitExceeded: + case CKErrorCode.UserDeletedZone: + // All of these errors are irrelevant for this query operation + case CKErrorCode.InternalError: + case CKErrorCode.ServerRejectedRequest: + case CKErrorCode.ConstraintViolation: + //Non-recoverable, should not retry + default: + return Error.Ignore; } } } diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/SubmitPostViewController.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/SubmitPostViewController.cs index 26af33a46..687162501 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/SubmitPostViewController.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/SubmitPostViewController.cs @@ -1,17 +1,14 @@ -using System; +using System; using System.Threading.Tasks; using UIKit; using Foundation; using CloudKit; -namespace CloudCaptions -{ - [Register("SubmitPostViewController")] - public class SubmitPostViewController : UIViewController - { - class PickerViewModel : UIPickerViewModel - { +namespace CloudCaptions { + [Register ("SubmitPostViewController")] + public class SubmitPostViewController : UIViewController { + class PickerViewModel : UIPickerViewModel { SubmitPostViewController controller; public PickerViewModel (SubmitPostViewController controller) @@ -34,7 +31,7 @@ public override UIView GetView (UIPickerView picker, nint row, nint component, U { // Sets each item in pickerview as the name of each font with its typeface in its own font // (e.g. Helvetica appears in Helvetica, Courier New appears in Courier New - UILabel fontLabel = (UILabel)view ?? new UILabel (); + UILabel fontLabel = (UILabel) view ?? new UILabel (); var familyName = UIFont.FamilyNames [row]; fontLabel.Font = UIFont.FromName (familyName, 24); @@ -164,71 +161,71 @@ void PublishPost (NSObject sender) // Creates post record type and initizalizes all of its values CKRecord newRecord = new CKRecord (Post.RecordType); - newRecord [Post.FontKey] = (NSString)ImageLabel.Font.Name; + newRecord [Post.FontKey] = (NSString) ImageLabel.Font.Name; newRecord [Post.ImageRefKey] = new CKReference (ImageRecord.Record.Id, CKReferenceAction.DeleteSelf); - newRecord [Post.TextKey] = (NSString)HiddenText.Text; - string[] tags = TagField.Text.ToLower ().Split (new char[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries); + newRecord [Post.TextKey] = (NSString) HiddenText.Text; + string [] tags = TagField.Text.ToLower ().Split (new char [] { ' ' }, StringSplitOptions.RemoveEmptyEntries); newRecord [Post.TagsKey] = NSArray.FromObjects (tags); Post newPost = new Post (newRecord); newPost.ImageRecord = ImageRecord; // Only upload image record if it is not on server, otherwise just upload the new post record - CKRecord[] recordsToSave = ImageRecord.IsOnServer - ? new CKRecord[] { newRecord } - : new CKRecord[] { newRecord, ImageRecord.Record }; + CKRecord [] recordsToSave = ImageRecord.IsOnServer + ? new CKRecord [] { newRecord } + : new CKRecord [] { newRecord, ImageRecord.Record }; // TODO: https://trello.com/c/A9T8Spyp second param is null - CKModifyRecordsOperation saveOp = new CKModifyRecordsOperation (recordsToSave, new CKRecordID[0]); + CKModifyRecordsOperation saveOp = new CKModifyRecordsOperation (recordsToSave, new CKRecordID [0]); saveOp.PerRecordProgress = (CKRecord record, double progress) => { // Image record type is probably going to take the longest to upload. Reflect it's progress in the progress bar if (record.RecordType == Image.RecordType) InvokeOnMainThread (() => { - var val = (float)(progress * 0.95); + var val = (float) (progress * 0.95); ProgressBar.SetProgress (val, true); }); }; // When completed it notifies the tableView to add the post we just uploaded, displays error if it didn't work - saveOp.Completed = (CKRecord[] savedRecords, CKRecordID[] deletedRecordIDs, NSError operationError) => { + saveOp.Completed = (CKRecord [] savedRecords, CKRecordID [] deletedRecordIDs, NSError operationError) => { Error errorResponse = HandleError (operationError); switch (errorResponse) { - case Error.Success: - // Tells delegate to update so it can display our new post - InvokeOnMainThread (() => { - DismissViewController (true, null); - MainController.Submit (newPost); - }); - break; - - case Error.Retry: - CKErrorInfo errorInfo = new CKErrorInfo (operationError.UserInfo); - nint retryAfter = errorInfo.RetryAfter.HasValue ? errorInfo.RetryAfter.Value : 3; - Console.WriteLine ("Error: {0}. Recoverable, retry after {1} seconds", operationError.Description, retryAfter); - Task.Delay ((int)retryAfter * 1000).ContinueWith (_ => PublishPost (sender)); - break; - - case Error.Ignore: - Console.WriteLine ("Error saving record: {0}", operationError.Description); - - string errorTitle = "Error"; - string dismissButton = "Okay"; - string errorMessage = operationError.Code == (long)CKErrorCode.NotAuthenticated - ? "You must be logged in to iCloud in order to post" - : "Unrecoverable error with the upload, check console logs"; - - InvokeOnMainThread (() => { - UIAlertController alert = UIAlertController.Create (errorTitle, errorMessage, UIAlertControllerStyle.Alert); - alert.AddAction (UIAlertAction.Create (dismissButton, UIAlertActionStyle.Cancel, null)); - - PostButton.Enabled = true; - PresentViewController (alert, true, null); - ProgressBar.Hidden = true; - PostButton.CustomView = null; - }); - break; - - default: - throw new NotImplementedException (); + case Error.Success: + // Tells delegate to update so it can display our new post + InvokeOnMainThread (() => { + DismissViewController (true, null); + MainController.Submit (newPost); + }); + break; + + case Error.Retry: + CKErrorInfo errorInfo = new CKErrorInfo (operationError.UserInfo); + nint retryAfter = errorInfo.RetryAfter.HasValue ? errorInfo.RetryAfter.Value : 3; + Console.WriteLine ("Error: {0}. Recoverable, retry after {1} seconds", operationError.Description, retryAfter); + Task.Delay ((int) retryAfter * 1000).ContinueWith (_ => PublishPost (sender)); + break; + + case Error.Ignore: + Console.WriteLine ("Error saving record: {0}", operationError.Description); + + string errorTitle = "Error"; + string dismissButton = "Okay"; + string errorMessage = operationError.Code == (long) CKErrorCode.NotAuthenticated + ? "You must be logged in to iCloud in order to post" + : "Unrecoverable error with the upload, check console logs"; + + InvokeOnMainThread (() => { + UIAlertController alert = UIAlertController.Create (errorTitle, errorMessage, UIAlertControllerStyle.Alert); + alert.AddAction (UIAlertAction.Create (dismissButton, UIAlertActionStyle.Cancel, null)); + + PostButton.Enabled = true; + PresentViewController (alert, true, null); + ProgressBar.Hidden = true; + PostButton.CustomView = null; + }); + break; + + default: + throw new NotImplementedException (); } }; CKContainer.DefaultContainer.PublicCloudDatabase.AddOperation (saveOp); @@ -239,51 +236,51 @@ Error HandleError (NSError operationError) if (operationError == null) { return Error.Success; } - switch ((CKErrorCode)(long)operationError.Code) { - case CKErrorCode.UnknownItem: - // This error occurs if it can't find the subscription named autoUpdate. (It tries to delete one that doesn't exits or it searches for one it can't find) - // This is okay and expected behavior - return Error.Ignore; - - case CKErrorCode.NetworkUnavailable: - case CKErrorCode.NetworkFailure: - // A reachability check might be appropriate here so we don't just keep retrying if the user has no service - case CKErrorCode.ServiceUnavailable: - case CKErrorCode.RequestRateLimited: - return Error.Retry; - - case CKErrorCode.PartialFailure: - // This shouldn't happen on a query operation - case CKErrorCode.NotAuthenticated: - case CKErrorCode.BadDatabase: - case CKErrorCode.IncompatibleVersion: - case CKErrorCode.BadContainer: - case CKErrorCode.PermissionFailure: - case CKErrorCode.MissingEntitlement: - // This app uses the publicDB with default world readable permissions - case CKErrorCode.AssetFileNotFound: - case CKErrorCode.AssetFileModified: - // Users don't really have an option to delete files so this shouldn't happen - case CKErrorCode.QuotaExceeded: - // We should not retry if it'll exceed our quota - case CKErrorCode.OperationCancelled: - // Nothing to do here, we intentionally cancelled - case CKErrorCode.InvalidArguments: - case CKErrorCode.ResultsTruncated: - case CKErrorCode.ServerRecordChanged: - case CKErrorCode.ChangeTokenExpired: - case CKErrorCode.BatchRequestFailed: - case CKErrorCode.ZoneBusy: - case CKErrorCode.ZoneNotFound: - case CKErrorCode.LimitExceeded: - case CKErrorCode.UserDeletedZone: - // All of these errors are irrelevant for this save operation. We're only saving new records, not modifying old ones - case CKErrorCode.InternalError: - case CKErrorCode.ServerRejectedRequest: - case CKErrorCode.ConstraintViolation: - //Non-recoverable, should not retry - default: - return Error.Ignore; + switch ((CKErrorCode) (long) operationError.Code) { + case CKErrorCode.UnknownItem: + // This error occurs if it can't find the subscription named autoUpdate. (It tries to delete one that doesn't exits or it searches for one it can't find) + // This is okay and expected behavior + return Error.Ignore; + + case CKErrorCode.NetworkUnavailable: + case CKErrorCode.NetworkFailure: + // A reachability check might be appropriate here so we don't just keep retrying if the user has no service + case CKErrorCode.ServiceUnavailable: + case CKErrorCode.RequestRateLimited: + return Error.Retry; + + case CKErrorCode.PartialFailure: + // This shouldn't happen on a query operation + case CKErrorCode.NotAuthenticated: + case CKErrorCode.BadDatabase: + case CKErrorCode.IncompatibleVersion: + case CKErrorCode.BadContainer: + case CKErrorCode.PermissionFailure: + case CKErrorCode.MissingEntitlement: + // This app uses the publicDB with default world readable permissions + case CKErrorCode.AssetFileNotFound: + case CKErrorCode.AssetFileModified: + // Users don't really have an option to delete files so this shouldn't happen + case CKErrorCode.QuotaExceeded: + // We should not retry if it'll exceed our quota + case CKErrorCode.OperationCancelled: + // Nothing to do here, we intentionally cancelled + case CKErrorCode.InvalidArguments: + case CKErrorCode.ResultsTruncated: + case CKErrorCode.ServerRecordChanged: + case CKErrorCode.ChangeTokenExpired: + case CKErrorCode.BatchRequestFailed: + case CKErrorCode.ZoneBusy: + case CKErrorCode.ZoneNotFound: + case CKErrorCode.LimitExceeded: + case CKErrorCode.UserDeletedZone: + // All of these errors are irrelevant for this save operation. We're only saving new records, not modifying old ones + case CKErrorCode.InternalError: + case CKErrorCode.ServerRejectedRequest: + case CKErrorCode.ConstraintViolation: + //Non-recoverable, should not retry + default: + return Error.Ignore; } } diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/SubscriptionController.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/SubscriptionController.cs index f62d40b3f..4c87b030c 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/SubscriptionController.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/SubscriptionController.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; using CloudKit; using Foundation; -namespace CloudCaptions -{ - [Register("SubscriptionController")] - public class SubscriptionController : UIBarButtonItem - { +namespace CloudCaptions { + [Register ("SubscriptionController")] + public class SubscriptionController : UIBarButtonItem { const string SubscriptionID = "autoUpdate"; CKDatabase PublicDB { @@ -17,14 +15,14 @@ CKDatabase PublicDB { } } - public SubscriptionController(IntPtr handle) - : base(handle) + public SubscriptionController (IntPtr handle) + : base (handle) { } public SubscriptionController (UIView customView) - : base(customView) + : base (customView) { this.Clicked += OnToggleSubscribtion; CheckSubscription (); @@ -37,15 +35,15 @@ void OnToggleSubscribtion (object sender, EventArgs e) ToggleSubscription (); } - void ToggleSubscription() + void ToggleSubscription () { var indicator = new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray); indicator.StartAnimating (); CustomView = indicator; - if(Title == "Subscribe") + if (Title == "Subscribe") Subscribe (); - else if(Title == "Unsubscribe") + else if (Title == "Unsubscribe") Unsubscribe (); else CheckSubscription (); @@ -53,13 +51,13 @@ void ToggleSubscription() #region Subscribe - async void Subscribe() + async void Subscribe () { CKSubscription subscriptionToUpload = CreateSubscription (); try { - await PublicDB.SaveSubscriptionAsync(subscriptionToUpload); - ResetButton("Unsubscribe"); + await PublicDB.SaveSubscriptionAsync (subscriptionToUpload); + ResetButton ("Unsubscribe"); } catch (NSErrorException ex) { HandleSubscribeError (ex); } @@ -83,22 +81,22 @@ void HandleSubscribeError (NSErrorException ex) Error errorResult = HandleError (error); switch (errorResult) { - case Error.Success: - if (error.Code == (long)CKErrorCode.UnknownItem) - Console.WriteLine ("If you see this it's because you've tried to subscribe to new Post records when CloudKit hasn't seen the Post record type yet. Either manually create the record type in dashboard or upload a post"); - CheckSubscription (); - break; - - case Error.Retry: - Utils.Retry (ToggleSubscription, error); - break; - - case Error.Ignore: - Console.WriteLine ("Ignored error while saving subscription: {0}", error.Description); - break; - - default: - break; + case Error.Success: + if (error.Code == (long) CKErrorCode.UnknownItem) + Console.WriteLine ("If you see this it's because you've tried to subscribe to new Post records when CloudKit hasn't seen the Post record type yet. Either manually create the record type in dashboard or upload a post"); + CheckSubscription (); + break; + + case Error.Retry: + Utils.Retry (ToggleSubscription, error); + break; + + case Error.Ignore: + Console.WriteLine ("Ignored error while saving subscription: {0}", error.Description); + break; + + default: + break; } } @@ -106,12 +104,12 @@ void HandleSubscribeError (NSErrorException ex) #region Unsubscribe - async void Unsubscribe() + async void Unsubscribe () { try { await PublicDB.DeleteSubscriptionAsync (SubscriptionID); - CheckSubscription(); - } catch(NSErrorException ex) { + CheckSubscription (); + } catch (NSErrorException ex) { HandleUnsubscribeError (ex); } } @@ -122,16 +120,16 @@ void HandleUnsubscribeError (NSErrorException ex) var errorResult = HandleError (error); switch (errorResult) { - case Error.Retry: - Utils.Retry (ToggleSubscription, error); - break; + case Error.Retry: + Utils.Retry (ToggleSubscription, error); + break; - case Error.Ignore: - Console.WriteLine ("Ignored error while deleting subscription: {0}", error.Description); - break; + case Error.Ignore: + Console.WriteLine ("Ignored error while deleting subscription: {0}", error.Description); + break; - default: - throw new NotImplementedException (); + default: + throw new NotImplementedException (); } } @@ -139,48 +137,48 @@ void HandleUnsubscribeError (NSErrorException ex) #endregion - void OnCheckSubscriptionClicked(object sender, EventArgs e) + void OnCheckSubscriptionClicked (object sender, EventArgs e) { CheckSubscription (); } - async void CheckSubscription() + async void CheckSubscription () { try { - var subscription = await PublicDB.FetchSubscriptionAsync(SubscriptionID); + var subscription = await PublicDB.FetchSubscriptionAsync (SubscriptionID); if (subscription != null) - ResetButton("Unsubscribe"); - } catch(NSErrorException ex) { + ResetButton ("Unsubscribe"); + } catch (NSErrorException ex) { HandleCheckSubscriptionError (ex); } } - void HandleCheckSubscriptionError(NSErrorException ex) + void HandleCheckSubscriptionError (NSErrorException ex) { NSError error = ex.Error; Error errorResult = HandleError (error); switch (errorResult) { - case Error.Success: - if (ex.Error.Code == (long)CKErrorCode.UnknownItem) - ResetButton ("Subscribe"); - break; - - case Error.Retry: - Utils.Retry (CheckSubscription, error); - break; - - case Error.Ignore: - Console.WriteLine ("Ignored error while checking subscription: {0}", error.Description); - ResetButton ("?"); - break; - - default: - throw new NotImplementedException (); + case Error.Success: + if (ex.Error.Code == (long) CKErrorCode.UnknownItem) + ResetButton ("Subscribe"); + break; + + case Error.Retry: + Utils.Retry (CheckSubscription, error); + break; + + case Error.Ignore: + Console.WriteLine ("Ignored error while checking subscription: {0}", error.Description); + ResetButton ("?"); + break; + + default: + throw new NotImplementedException (); } } - void ResetButton(string title) + void ResetButton (string title) { InvokeOnMainThread (() => { Title = title; @@ -188,57 +186,56 @@ void ResetButton(string title) }); } - Error HandleError(NSError error) + Error HandleError (NSError error) { if (error == null) { return Error.Success; } - switch ((CKErrorCode)(long)error.Code) - { - // This error occurs if it can't find the subscription named autoUpdate. (It tries to delete one that doesn't exits or it searches for one it can't find) - // This is okay and expected behavior - case CKErrorCode.UnknownItem: - return Error.Success; - - case CKErrorCode.NetworkUnavailable: - case CKErrorCode.NetworkFailure: - // A reachability check might be appropriate here so we don't just keep retrying if the user has no service - case CKErrorCode.ServiceUnavailable: - case CKErrorCode.RequestRateLimited: - return Error.Retry; - - case CKErrorCode.BadDatabase: - case CKErrorCode.IncompatibleVersion: - case CKErrorCode.BadContainer: - case CKErrorCode.PermissionFailure: - case CKErrorCode.MissingEntitlement: - // This app uses the publicDB with default world readable permissions - case CKErrorCode.AssetFileNotFound: - case CKErrorCode.PartialFailure: - // These shouldn't occur during a subscription operation - case CKErrorCode.QuotaExceeded: - // We should not retry if it'll exceed our quota - case CKErrorCode.OperationCancelled: - // Nothing to do here, we intentionally cancelled - case CKErrorCode.NotAuthenticated: - // User must be logged in - case CKErrorCode.InvalidArguments: - case CKErrorCode.ResultsTruncated: - case CKErrorCode.ServerRecordChanged: - case CKErrorCode.AssetFileModified: - case CKErrorCode.ChangeTokenExpired: - case CKErrorCode.BatchRequestFailed: - case CKErrorCode.ZoneBusy: - case CKErrorCode.ZoneNotFound: - case CKErrorCode.LimitExceeded: - case CKErrorCode.UserDeletedZone: - // All of these errors are irrelevant for this subscription operation - case CKErrorCode.InternalError: - case CKErrorCode.ServerRejectedRequest: - case CKErrorCode.ConstraintViolation: - //Non-recoverable, should not retry - default: - return Error.Ignore; + switch ((CKErrorCode) (long) error.Code) { + // This error occurs if it can't find the subscription named autoUpdate. (It tries to delete one that doesn't exits or it searches for one it can't find) + // This is okay and expected behavior + case CKErrorCode.UnknownItem: + return Error.Success; + + case CKErrorCode.NetworkUnavailable: + case CKErrorCode.NetworkFailure: + // A reachability check might be appropriate here so we don't just keep retrying if the user has no service + case CKErrorCode.ServiceUnavailable: + case CKErrorCode.RequestRateLimited: + return Error.Retry; + + case CKErrorCode.BadDatabase: + case CKErrorCode.IncompatibleVersion: + case CKErrorCode.BadContainer: + case CKErrorCode.PermissionFailure: + case CKErrorCode.MissingEntitlement: + // This app uses the publicDB with default world readable permissions + case CKErrorCode.AssetFileNotFound: + case CKErrorCode.PartialFailure: + // These shouldn't occur during a subscription operation + case CKErrorCode.QuotaExceeded: + // We should not retry if it'll exceed our quota + case CKErrorCode.OperationCancelled: + // Nothing to do here, we intentionally cancelled + case CKErrorCode.NotAuthenticated: + // User must be logged in + case CKErrorCode.InvalidArguments: + case CKErrorCode.ResultsTruncated: + case CKErrorCode.ServerRecordChanged: + case CKErrorCode.AssetFileModified: + case CKErrorCode.ChangeTokenExpired: + case CKErrorCode.BatchRequestFailed: + case CKErrorCode.ZoneBusy: + case CKErrorCode.ZoneNotFound: + case CKErrorCode.LimitExceeded: + case CKErrorCode.UserDeletedZone: + // All of these errors are irrelevant for this subscription operation + case CKErrorCode.InternalError: + case CKErrorCode.ServerRejectedRequest: + case CKErrorCode.ConstraintViolation: + //Non-recoverable, should not retry + default: + return Error.Ignore; } } } diff --git a/ios8/CloudCaptions/CloudCaptions/Controllers/Utils.cs b/ios8/CloudCaptions/CloudCaptions/Controllers/Utils.cs index 006e9f49c..b7b80f179 100644 --- a/ios8/CloudCaptions/CloudCaptions/Controllers/Utils.cs +++ b/ios8/CloudCaptions/CloudCaptions/Controllers/Utils.cs @@ -1,48 +1,46 @@ -using System; +using System; using System.Threading.Tasks; using Foundation; -namespace CloudCaptions -{ - public static class Utils - { - public static void Retry(Action handler, NSError error) +namespace CloudCaptions { + public static class Utils { + public static void Retry (Action handler, NSError error) { int delayInSec = FetchRetryDelay (error); PrintLog (error, delayInSec); Retry (handler, delayInSec); } - static int FetchRetryDelay(NSError error) + static int FetchRetryDelay (NSError error) { CKErrorInfo errorInfo = new CKErrorInfo (error.UserInfo); - return (int)(errorInfo.RetryAfter.HasValue ? errorInfo.RetryAfter.Value : 3); + return (int) (errorInfo.RetryAfter.HasValue ? errorInfo.RetryAfter.Value : 3); } - static void PrintLog(NSError error, int retryDelay) + static void PrintLog (NSError error, int retryDelay) { Console.WriteLine ("Error: {0}. Recoverable, retry after {1} seconds", error.Description, retryDelay); } - static void Retry(Action action, int retryDelayInSec) + static void Retry (Action action, int retryDelayInSec) { - Task.Delay ((int)retryDelayInSec * 1000).ContinueWith (_ => action ()); + Task.Delay ((int) retryDelayInSec * 1000).ContinueWith (_ => action ()); } - public static NSPredicate CreateTagPredicate(string tags) + public static NSPredicate CreateTagPredicate (string tags) { - return NSPredicate.FromFormat ("Tags CONTAINS %@", (NSString)tags); + return NSPredicate.FromFormat ("Tags CONTAINS %@", (NSString) tags); } - public static NSPredicate CreateAfterPredicate(NSDate date) + public static NSPredicate CreateAfterPredicate (NSDate date) { return NSPredicate.FromFormat ("creationDate > %@", date); } - public static NSSortDescriptor[] CreateCreationDateDescriptor(bool ascending) + public static NSSortDescriptor [] CreateCreationDateDescriptor (bool ascending) { - return new NSSortDescriptor[] { + return new NSSortDescriptor [] { new NSSortDescriptor ("creationDate", ascending) }; } diff --git a/ios8/CloudCaptions/CloudCaptions/Main.cs b/ios8/CloudCaptions/CloudCaptions/Main.cs index 1032ec2d2..82c609c00 100644 --- a/ios8/CloudCaptions/CloudCaptions/Main.cs +++ b/ios8/CloudCaptions/CloudCaptions/Main.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace CloudCaptions -{ - public class Application - { - static void Main (string[] args) +namespace CloudCaptions { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios8/CloudCaptions/CloudCaptions/Model/Image.cs b/ios8/CloudCaptions/CloudCaptions/Model/Image.cs index d1b36cafc..3f884b6b2 100644 --- a/ios8/CloudCaptions/CloudCaptions/Model/Image.cs +++ b/ios8/CloudCaptions/CloudCaptions/Model/Image.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using UIKit; @@ -6,10 +6,8 @@ using Foundation; using CoreGraphics; -namespace CloudCaptions -{ - public class Image : NSObject - { +namespace CloudCaptions { + public class Image : NSObject { public static readonly string RecordType = "Image"; public static readonly string ThumbnailKey = "Thumb"; public static readonly string FullsizeKey = "Full"; @@ -47,7 +45,7 @@ public Image (UIImage image) } // Creates an Image from a CKRecord that has been fetched - public Image(CKRecord record, bool onServer = true) + public Image (CKRecord record, bool onServer = true) { if (record == null) throw new ArgumentNullException ("record"); @@ -68,7 +66,7 @@ void Init (CKRecord record, bool onServer) UIImage LoadImage (string key) { - var asset = (CKAsset)Record [key]; + var asset = (CKAsset) Record [key]; if (asset == null) return null; @@ -93,9 +91,9 @@ static CGImage Crop (CGImage rawImage) } } - static UIImage Resize(CGImage original, nfloat scale, UIImageOrientation orientation, CGSize newSize) + static UIImage Resize (CGImage original, nfloat scale, UIImageOrientation orientation, CGSize newSize) { - UIGraphics.BeginImageContext(newSize); + UIGraphics.BeginImageContext (newSize); var rect = new CGRect (CGPoint.Empty, newSize); UIImage.FromImage (original, scale, orientation).Draw (rect); diff --git a/ios8/CloudCaptions/CloudCaptions/Model/Post.cs b/ios8/CloudCaptions/CloudCaptions/Model/Post.cs index 54a803169..18255806f 100644 --- a/ios8/CloudCaptions/CloudCaptions/Model/Post.cs +++ b/ios8/CloudCaptions/CloudCaptions/Model/Post.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; using Foundation; -namespace CloudCaptions -{ - public class Post - { +namespace CloudCaptions { + public class Post { public static readonly string RecordType = "Post"; public static readonly string TextKey = "ImageText"; public static readonly string FontKey = "Font"; @@ -28,95 +26,95 @@ public Post (CKRecord postRecord) PostRecord = postRecord; } - public void LoadImage (string[] keys, Action updateBlock = null) + public void LoadImage (string [] keys, Action updateBlock = null) { // Fetches the imageRecord this post record references in its ImageRefKey. // Only fetches the values associated with the keys passed in to the NSArray - var imgRecordId = ((CKReference)PostRecord[ImageRefKey]).RecordId; - CKFetchRecordsOperation imageOp = new CKFetchRecordsOperation (new CKRecordID[]{ + var imgRecordId = ((CKReference) PostRecord [ImageRefKey]).RecordId; + CKFetchRecordsOperation imageOp = new CKFetchRecordsOperation (new CKRecordID []{ imgRecordId }); imageOp.DesiredKeys = keys; imageOp.Completed = (NSDictionary recordDict, NSError error) => { - if(error != null && error.Code == (long)CKErrorCode.PartialFailure) { - CKErrorInfo info = new CKErrorInfo(error); - error = info[imgRecordId]; + if (error != null && error.Code == (long) CKErrorCode.PartialFailure) { + CKErrorInfo info = new CKErrorInfo (error); + error = info [imgRecordId]; } - Error errorResponse = HandleError(error); - switch(errorResponse) { - case Error.Success: - CKRecord fetchedImageRecord = (CKRecord)recordDict[imgRecordId]; - ImageRecord = new Image(fetchedImageRecord); - if(updateBlock != null) - updateBlock(); - break; + Error errorResponse = HandleError (error); + switch (errorResponse) { + case Error.Success: + CKRecord fetchedImageRecord = (CKRecord) recordDict [imgRecordId]; + ImageRecord = new Image (fetchedImageRecord); + if (updateBlock != null) + updateBlock (); + break; - case Error.Retry: - Utils.Retry(() => LoadImage(keys, updateBlock), error); - ImageRecord = null; - break; + case Error.Retry: + Utils.Retry (() => LoadImage (keys, updateBlock), error); + ImageRecord = null; + break; - case Error.Ignore: - Console.WriteLine ("Error: {0}", error.Description); - ImageRecord = null; - break; + case Error.Ignore: + Console.WriteLine ("Error: {0}", error.Description); + ImageRecord = null; + break; - default: - throw new NotImplementedException(); + default: + throw new NotImplementedException (); } }; PublicDB.AddOperation (imageOp); } - Error HandleError(NSError error) + Error HandleError (NSError error) { if (error == null) return Error.Success; - switch ((CKErrorCode)(long)error.Code) { - case CKErrorCode.NetworkUnavailable: - case CKErrorCode.NetworkFailure: - // A reachability check might be appropriate here so we don't just keep retrying if the user has no service - case CKErrorCode.ServiceUnavailable: - case CKErrorCode.RequestRateLimited: - return Error.Retry; + switch ((CKErrorCode) (long) error.Code) { + case CKErrorCode.NetworkUnavailable: + case CKErrorCode.NetworkFailure: + // A reachability check might be appropriate here so we don't just keep retrying if the user has no service + case CKErrorCode.ServiceUnavailable: + case CKErrorCode.RequestRateLimited: + return Error.Retry; - case CKErrorCode.BadContainer: - case CKErrorCode.MissingEntitlement: - case CKErrorCode.PermissionFailure: - case CKErrorCode.BadDatabase: - // This app uses the publicDB with default world readable permissions - case CKErrorCode.UnknownItem: - case CKErrorCode.AssetFileNotFound: - // This shouldn't happen. If an Image record is deleted it should delete all Post records that reference it (CKReferenceActionDeleteSelf) - case CKErrorCode.IncompatibleVersion: - case CKErrorCode.QuotaExceeded: - //App quota will be exceeded, cancelling operation - case CKErrorCode.OperationCancelled: - // Nothing to do here, we intentionally cancelled - case CKErrorCode.NotAuthenticated: - case CKErrorCode.InvalidArguments: - case CKErrorCode.ResultsTruncated: - case CKErrorCode.ServerRecordChanged: - case CKErrorCode.AssetFileModified: - case CKErrorCode.ChangeTokenExpired: - case CKErrorCode.BatchRequestFailed: - case CKErrorCode.ZoneBusy: - case CKErrorCode.ZoneNotFound: - case CKErrorCode.LimitExceeded: - case CKErrorCode.UserDeletedZone: - // These errors are pretty irrelevant here - // We're fetching only one record by its recordID - // These errors could be hit fetching multiple records, using zones, saving records, or fetching with predicates - case CKErrorCode.InternalError: - case CKErrorCode.ServerRejectedRequest: - case CKErrorCode.ConstraintViolation: - Console.WriteLine ("Nonrecoverable error, will not retry"); - return Error.Ignore; + case CKErrorCode.BadContainer: + case CKErrorCode.MissingEntitlement: + case CKErrorCode.PermissionFailure: + case CKErrorCode.BadDatabase: + // This app uses the publicDB with default world readable permissions + case CKErrorCode.UnknownItem: + case CKErrorCode.AssetFileNotFound: + // This shouldn't happen. If an Image record is deleted it should delete all Post records that reference it (CKReferenceActionDeleteSelf) + case CKErrorCode.IncompatibleVersion: + case CKErrorCode.QuotaExceeded: + //App quota will be exceeded, cancelling operation + case CKErrorCode.OperationCancelled: + // Nothing to do here, we intentionally cancelled + case CKErrorCode.NotAuthenticated: + case CKErrorCode.InvalidArguments: + case CKErrorCode.ResultsTruncated: + case CKErrorCode.ServerRecordChanged: + case CKErrorCode.AssetFileModified: + case CKErrorCode.ChangeTokenExpired: + case CKErrorCode.BatchRequestFailed: + case CKErrorCode.ZoneBusy: + case CKErrorCode.ZoneNotFound: + case CKErrorCode.LimitExceeded: + case CKErrorCode.UserDeletedZone: + // These errors are pretty irrelevant here + // We're fetching only one record by its recordID + // These errors could be hit fetching multiple records, using zones, saving records, or fetching with predicates + case CKErrorCode.InternalError: + case CKErrorCode.ServerRejectedRequest: + case CKErrorCode.ConstraintViolation: + Console.WriteLine ("Nonrecoverable error, will not retry"); + return Error.Ignore; - default: - return Error.Ignore; + default: + return Error.Ignore; } } } diff --git a/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionView.cs b/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionView.cs index a5c4baec4..c5d6da7b0 100644 --- a/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionView.cs +++ b/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; @@ -7,23 +7,20 @@ using Foundation; using CoreFoundation; -namespace CloudCaptions -{ - [Register("ExistingImageCollectionView")] - public class ExistingImageCollectionView : UICollectionView, INSCoding - { - class CollectionViewDataSource : UICollectionViewDataSource - { +namespace CloudCaptions { + [Register ("ExistingImageCollectionView")] + public class ExistingImageCollectionView : UICollectionView, INSCoding { + class CollectionViewDataSource : UICollectionViewDataSource { readonly ExistingImageCollectionView view; - public CollectionViewDataSource(ExistingImageCollectionView view) + public CollectionViewDataSource (ExistingImageCollectionView view) { this.view = view; } public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (ExistingImageCollectionViewCell)collectionView.DequeueReusableCell (cellReuseIdentifier, indexPath); + var cell = (ExistingImageCollectionViewCell) collectionView.DequeueReusableCell (cellReuseIdentifier, indexPath); cell = cell ?? new ExistingImageCollectionViewCell (); cell.ThumbnailImage.Image = view.imageRecords [indexPath.Row].Thumbnail; @@ -39,7 +36,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio } } - static readonly NSString cellReuseIdentifier = new NSString("imageCell"); + static readonly NSString cellReuseIdentifier = new NSString ("imageCell"); List<Image> imageRecords; DispatchQueue updateArrayQueue; @@ -51,14 +48,14 @@ int Count { } } - public ExistingImageCollectionView(IntPtr handle) - : base(handle) + public ExistingImageCollectionView (IntPtr handle) + : base (handle) { Initialize (); } - public ExistingImageCollectionView(NSCoder coder) - : base(coder) + public ExistingImageCollectionView (NSCoder coder) + : base (coder) { Initialize (); } @@ -70,7 +67,7 @@ void Initialize () updateArrayQueue = new DispatchQueue ("UpdateCollectionViewQueue"); } - public void AddImageFromRecord(CKRecord toAdd) + public void AddImageFromRecord (CKRecord toAdd) { Image fetchedImage = new Image (toAdd); // Ensures that only one object will be added to the imageRecords array at a time @@ -80,7 +77,7 @@ public void AddImageFromRecord(CKRecord toAdd) }); } - public void SetLoadingFlag(NSIndexPath index, bool isLoading) + public void SetLoadingFlag (NSIndexPath index, bool isLoading) { currentLoadingIndex = isLoading ? index : null; InvokeOnMainThread (ReloadData); @@ -89,7 +86,7 @@ public void SetLoadingFlag(NSIndexPath index, bool isLoading) public CKRecordID GetRecordId (NSIndexPath index) { // returns the recordID of the item in imageRecords at the given index - Image img = imageRecords[index.Row]; + Image img = imageRecords [index.Row]; return img.Record.Id; } } diff --git a/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionViewCell.cs b/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionViewCell.cs index 4ba5bf0dd..79491d664 100644 --- a/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionViewCell.cs +++ b/ios8/CloudCaptions/CloudCaptions/View/ExistingImageCollectionViewCell.cs @@ -1,16 +1,14 @@ -using System; +using System; using UIKit; using Foundation; -namespace CloudCaptions -{ - [Register("ExistingImageCollectionViewCell")] - public class ExistingImageCollectionViewCell : UICollectionViewCell - { - [Outlet("thumbnailImage")] +namespace CloudCaptions { + [Register ("ExistingImageCollectionViewCell")] + public class ExistingImageCollectionViewCell : UICollectionViewCell { + [Outlet ("thumbnailImage")] public UIImageView ThumbnailImage { get; set; } - [Outlet("loadingIndicator")] + [Outlet ("loadingIndicator")] UIActivityIndicatorView LoadingIndicator { get; set; } UIVisualEffectView blurSubview; @@ -27,7 +25,7 @@ public ExistingImageCollectionViewCell () public void SetLoading (bool loading) { - if(loading) { + if (loading) { LoadingIndicator.StartAnimating (); UIBlurEffect blurEffect = UIBlurEffect.FromStyle (UIBlurEffectStyle.Light); @@ -35,7 +33,7 @@ public void SetLoading (bool loading) blurSubview.Frame = ThumbnailImage.Frame; ThumbnailImage.AddSubview (blurSubview); } else { - if(blurSubview != null) { + if (blurSubview != null) { blurSubview.RemoveFromSuperview (); blurSubview = null; } diff --git a/ios8/CloudCaptions/CloudCaptions/View/PostCell.cs b/ios8/CloudCaptions/CloudCaptions/View/PostCell.cs index ba622f229..76d1d2010 100644 --- a/ios8/CloudCaptions/CloudCaptions/View/PostCell.cs +++ b/ios8/CloudCaptions/CloudCaptions/View/PostCell.cs @@ -1,26 +1,24 @@ -using System; +using System; using UIKit; using Foundation; -namespace CloudCaptions -{ - [Register("PostCell")] - public class PostCell : UITableViewCell - { +namespace CloudCaptions { + [Register ("PostCell")] + public class PostCell : UITableViewCell { string fontName; - [Outlet("textLabelInCell")] + [Outlet ("textLabelInCell")] UILabel TextLabelInCell { get; set; } - [Outlet("imageViewInCell")] + [Outlet ("imageViewInCell")] UIImageView ImageViewInCell { get; set; } - [Outlet("activityIndicator")] + [Outlet ("activityIndicator")] UIActivityIndicatorView ActivityIndicator { get; set; } public PostCell (IntPtr handle) - : base(handle) + : base (handle) { } @@ -36,16 +34,16 @@ public override void LayoutSubviews () TextLabelInCell.Font = labelFont; } - public void DisplayInfoForPost(Post post) + public void DisplayInfoForPost (Post post) { // Sets how the cell appears based on the Post passed in ActivityIndicator.StartAnimating (); - if(post.ImageRecord != null) + if (post.ImageRecord != null) ImageViewInCell.Image = post.ImageRecord.FullImage; - fontName = (string)(NSString)post.PostRecord[Post.FontKey]; - TextLabelInCell.Text = (string)(NSString)post.PostRecord[Post.TextKey]; + fontName = (string) (NSString) post.PostRecord [Post.FontKey]; + TextLabelInCell.Text = (string) (NSString) post.PostRecord [Post.TextKey]; } } } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/AppDelegate.cs b/ios8/CloudKitAtlas/CloudKitAtlas/AppDelegate.cs index 8db5e988b..041003764 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/AppDelegate.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/AppDelegate.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; using Foundation; using CloudKit; -namespace CloudKitAtlas -{ +namespace CloudKitAtlas { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSample.cs index 914755836..06a37d912 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSample.cs @@ -1,21 +1,18 @@ -using System.Collections.Generic; +using System.Collections.Generic; using UIKit; using Foundation; using CoreLocation; using System.Threading.Tasks; -namespace CloudKitAtlas -{ - public enum Change - { +namespace CloudKitAtlas { + public enum Change { Modified, Deleted, Added } - public class Attribute - { + public class Attribute { public string Key { get; set; } public string Value { get; set; } public bool IsNested { get; set; } = false; @@ -46,8 +43,7 @@ public Attribute (string key, string value, UIImage image) } } - public class AttributeGroup - { + public class AttributeGroup { public string Title { get; } public List<Attribute> Attributes { get; set; } = new List<Attribute> (); @@ -64,8 +60,7 @@ public AttributeGroup (string title, IEnumerable<Attribute> attributes) } } - public class Input - { + public class Input { public string Label { get; } public virtual bool IsValid { @@ -98,8 +93,7 @@ public Input (string label, int [] toggleIndexes) } } - public class SelectionInput : Input - { + public class SelectionInput : Input { public List<Input> Items { get; set; } = new List<Input> (); public override bool IsValid { @@ -120,14 +114,12 @@ public SelectionInput (string label, Input [] items) } } - public enum TextInputType - { + public enum TextInputType { Text, Email } - public class LocationInput : Input - { + public class LocationInput : Input { public int? Longitude { get; set; } public int? Latitude { get; set; } @@ -151,8 +143,7 @@ public LocationInput (string label, bool isRequired) } } - public class ImageInput : Input - { + public class ImageInput : Input { public NSUrl Value { get; set; } public override bool IsValid { @@ -167,8 +158,7 @@ public ImageInput (string label) } } - public class BooleanInput : Input - { + public class BooleanInput : Input { public bool Value { get; set; } public override bool IsValid { @@ -190,8 +180,7 @@ public BooleanInput (string label, bool value, bool isHidden) } } - public class TextInput : Input - { + public class TextInput : Input { public TextInputType Type { get; private set; } = TextInputType.Text; public string Value { get; set; } = string.Empty; @@ -222,14 +211,12 @@ public TextInput (string label, string value, bool isRequired, TextInputType typ } } - public interface IResult - { + public interface IResult { string SummaryField { get; } List<AttributeGroup> AttributeList { get; } } - public class NoResults : IResult - { + public class NoResults : IResult { public string SummaryField { get { return null; @@ -244,8 +231,7 @@ public List<AttributeGroup> AttributeList { } } - public class Results - { + public class Results { public List<IResult> Items { get; } = new List<IResult> (); public bool AlwaysShowAsList { get; } @@ -281,8 +267,7 @@ public void Reset () } } - public abstract class CodeSample - { + public abstract class CodeSample { public string Title { get; } public string ClassName { get; } public string MethodName { get; } @@ -358,10 +343,10 @@ bool TryGet<T> (string key, out T value) { object obj; var contains = Data.TryGetValue (key, out obj); - value = contains ? (T)obj : default (T); + value = contains ? (T) obj : default (T); return contains; } public abstract Task<Results> Run (); } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleGroup.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleGroup.cs index 0cdf3823a..f6925a996 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleGroup.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleGroup.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace CloudKitAtlas -{ - public class CodeSampleGroup - { +namespace CloudKitAtlas { + public class CodeSampleGroup { public string Title { get; } public UIImage Icon { get; } public CodeSample [] CodeSamples { get; } @@ -17,4 +15,4 @@ public CodeSampleGroup (string title, UIImage icon, CodeSample [] codeSamples) } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleViewController.cs index ab76e84ef..fed78c92f 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/CodeSampleViewController.cs @@ -10,12 +10,10 @@ using static CloudKitAtlas.NullableExtensions; using System.Diagnostics.Contracts; -namespace CloudKitAtlas -{ +namespace CloudKitAtlas { public partial class CodeSampleViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource, IUIScrollViewDelegate, IUITextFieldDelegate, ICLLocationManagerDelegate, IUIImagePickerControllerDelegate, - IUINavigationControllerDelegate, IUIPickerViewDelegate, IUIPickerViewDataSource - { + IUINavigationControllerDelegate, IUIPickerViewDelegate, IUIPickerViewDataSource { CLLocationManager LocationManager { get; } = new CLLocationManager (); UIImagePickerController ImagePickerController { get; } = new UIImagePickerController (); @@ -64,7 +62,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); var codeSample = SelectedCodeSample; - if(codeSample != null) { + if (codeSample != null) { ClassName.Text = $"Class: {codeSample.ClassName}"; MethodName.Text = codeSample.MethodName; CodeSampleDescription.Text = codeSample.Description; @@ -228,7 +226,7 @@ public bool ShouldReturn (UITextField textField) void EditingChanged (object sender, EventArgs e) { - EditingEnded ((UITextField)sender); + EditingEnded ((UITextField) sender); } [Export ("textFieldDidEndEditing:")] @@ -304,7 +302,7 @@ public string GetTitle (UIPickerView pickerView, nint row, nint component) var indexPath = NSIndexPath.FromRowSection (selectedSelectionCellIndex.Value, 0); var cell = TableView.CellAt (indexPath) as SelectionFieldTableViewCell; if (cell != null) - return cell.SelectionInput.Items [(int)row].Label; + return cell.SelectionInput.Items [(int) row].Label; } return null; } @@ -316,7 +314,7 @@ public void Selected (UIPickerView pickerView, nint row, nint component) var indexPath = NSIndexPath.FromRowSection (selectedSelectionCellIndex.Value, 0); var cell = TableView.CellAt (indexPath) as SelectionFieldTableViewCell; if (cell != null) { - cell.SelectedItemLabel.Text = cell.SelectionInput.Items [(int)row].Label; + cell.SelectedItemLabel.Text = cell.SelectionInput.Items [(int) row].Label; UIView.AnimateNotify (0.4, () => { PickerHeightConstraint.Constant = 0; View.LayoutIfNeeded (); @@ -329,10 +327,10 @@ public void Selected (UIPickerView pickerView, nint row, nint component) foreach (var index in cell.SelectionInput.Items [oldValue.Value].ToggleIndexes) SelectedCodeSample.Inputs [index].IsHidden = true; } - foreach (var index in cell.SelectionInput.Items [(int)row].ToggleIndexes) + foreach (var index in cell.SelectionInput.Items [(int) row].ToggleIndexes) SelectedCodeSample.Inputs [index].IsHidden = false; - cell.SelectionInput.Value = (int)row; + cell.SelectionInput.Value = (int) row; TableView.ReloadData (); }); } @@ -351,7 +349,7 @@ public void AuthorizationChanged (CLLocationManager manager, CLAuthorizationStat int index = selectedImageCellIndex.Value; var indexPath = NSIndexPath.FromRowSection (index, 0); - var cell = (LocationFieldTableViewCell)TableView.CellAt (indexPath); + var cell = (LocationFieldTableViewCell) TableView.CellAt (indexPath); cell.LookUpButton.Enabled = status != CLAuthorizationStatus.Denied; if (status == CLAuthorizationStatus.AuthorizedWhenInUse) @@ -381,12 +379,12 @@ public void LocationsUpdated (CLLocationManager manager, CLLocation [] locations var index = selectedImageCellIndex.Value; var indexPath = NSIndexPath.FromRowSection (index, 0); - var cell = (LocationFieldTableViewCell)TableView.CellAt (indexPath); + var cell = (LocationFieldTableViewCell) TableView.CellAt (indexPath); EndLocationLookupForCell (cell); var location = locations.LastOrDefault (); - if(location != null) { + if (location != null) { cell.SetCoordinate (location.Coordinate); ValidateInputs (); } @@ -425,12 +423,12 @@ public void Canceled (UIImagePickerController picker) [Export ("imagePickerController:didFinishPickingMediaWithInfo:")] public void FinishedPickingMedia (UIImagePickerController picker, NSDictionary info) { - var selectedImage = (UIImage)info [UIImagePickerController.OriginalImage]; + var selectedImage = (UIImage) info [UIImagePickerController.OriginalImage]; var imageUrl = GetImageUrl (); if (selectedImage != null && selectedImageCellIndex.HasValue && imageUrl != null) { var index = selectedImageCellIndex.Value; var indexPath = NSIndexPath.FromRowSection (index, 0); - var cell = (ImageFieldTableViewCell)TableView.CellAt (indexPath); + var cell = (ImageFieldTableViewCell) TableView.CellAt (indexPath); var imageData = selectedImage.AsJPEG (0.8f); imageData?.Save (imageUrl, atomically: true); cell.AssetView.Image = selectedImage; @@ -524,7 +522,7 @@ void SelectOption (UITapGestureRecognizer sender) static int? Parse (string text) { int value; - return int.TryParse (text, out value) ? value : (int?)null; + return int.TryParse (text, out value) ? value : (int?) null; } } } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverAllContactUserInfosSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverAllContactUserInfosSample.cs index 10daca01a..428820140 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverAllContactUserInfosSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverAllContactUserInfosSample.cs @@ -1,12 +1,10 @@ -using System.Linq; +using System.Linq; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class DiscoverAllContactUserInfosSample : CodeSample - { +namespace CloudKitAtlas { + public class DiscoverAllContactUserInfosSample : CodeSample { public DiscoverAllContactUserInfosSample () : base (title: "DiscoverAllContactUserInfos", className: "CKContainer", @@ -20,10 +18,10 @@ public async override Task<Results> Run () var container = CKContainer.DefaultContainer; var userInfos = await container.DiscoverAllContactUserInfosAsync (); - var items = userInfos.Select (info => new CKDiscoveredUserInfoWrapper(info)).ToArray (); + var items = userInfos.Select (info => new CKDiscoveredUserInfoWrapper (info)).ToArray (); ListHeading = items.Length > 0 ? "Discovered User Infos:" : "No Discoverable Users Found"; return new Results (items, alwaysShowAsList: true); } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithEmailAddressSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithEmailAddressSample.cs index 8fb983410..ed0613f77 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithEmailAddressSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithEmailAddressSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class DiscoverUserInfoWithEmailAddressSample : CodeSample - { +namespace CloudKitAtlas { + public class DiscoverUserInfoWithEmailAddressSample : CodeSample { public DiscoverUserInfoWithEmailAddressSample () : base (title: "DiscoverUserInfo by email", className: "CKContainer", @@ -25,8 +23,8 @@ public async override Task<Results> Run () throw new InvalidProgramException (); var container = CKContainer.DefaultContainer; - CKDiscoveredUserInfo userInfo = await container.DiscoverUserInfoAsync ((string)emailAddress); + CKDiscoveredUserInfo userInfo = await container.DiscoverUserInfoAsync ((string) emailAddress); return new Results (new IResult [] { new CKDiscoveredUserInfoWrapper (userInfo) }); } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithUserRecordIdSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithUserRecordIdSample.cs index baaa1c5ae..2868b49e9 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithUserRecordIdSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/DiscoverUserInfoWithUserRecordIdSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class DiscoverUserInfoWithUserRecordIdSample : CodeSample - { +namespace CloudKitAtlas { + public class DiscoverUserInfoWithUserRecordIdSample : CodeSample { public DiscoverUserInfoWithUserRecordIdSample () : base (title: "DiscoverUserInfo by recordId", className: "CKContainer", @@ -24,8 +22,8 @@ public async override Task<Results> Run () object recordName, zoneName; if (Data.TryGetValue ("recordName", out recordName) && Data.TryGetValue ("zoneName", out zoneName)) { var container = CKContainer.DefaultContainer; - var zoneId = new CKRecordZoneID ((string)zoneName, CKContainer.OwnerDefaultName); - var userRecordID = new CKRecordID ((string)recordName, zoneId); + var zoneId = new CKRecordZoneID ((string) zoneName, CKContainer.OwnerDefaultName); + var userRecordID = new CKRecordID ((string) recordName, zoneId); CKDiscoveredUserInfo userInfo = await container.DiscoverUserInfoAsync (userRecordID); return new Results (new IResult [] { new CKDiscoveredUserInfoWrapper (userInfo) }); diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/FetchUserRecordIdSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/FetchUserRecordIdSample.cs index de0edccf2..2ecffc3bf 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/FetchUserRecordIdSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/FetchUserRecordIdSample.cs @@ -1,11 +1,9 @@ -using System.Threading.Tasks; +using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class FetchUserRecordIdSample : CodeSample - { +namespace CloudKitAtlas { + public class FetchUserRecordIdSample : CodeSample { public FetchUserRecordIdSample () : base (title: "FetchUserRecordId", className: "CKContainer", @@ -21,4 +19,4 @@ public async override Task<Results> Run () return new Results (new IResult [] { new CKRecordIdWrapper (recordId) }); } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/RequestApplicationPermissionSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/RequestApplicationPermissionSample.cs index 1cff99570..a479b3dcc 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/RequestApplicationPermissionSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Discoverability/RequestApplicationPermissionSample.cs @@ -1,12 +1,10 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class PermissionStatus : IResult - { +namespace CloudKitAtlas { + public class PermissionStatus : IResult { readonly Attribute attribute; public string SummaryField { get; } @@ -24,8 +22,7 @@ public PermissionStatus (CKApplicationPermissionStatus status) } } - public class RequestApplicationPermissionSample : CodeSample - { + public class RequestApplicationPermissionSample : CodeSample { public RequestApplicationPermissionSample () : base (title: "RequestApplicationPermission", className: "CKContainer", @@ -38,7 +35,7 @@ public async override Task<Results> Run () { var container = CKContainer.DefaultContainer; var status = await container.RequestApplicationPermissionAsync (CKApplicationPermissions.UserDiscoverability); - return new Results (new IResult [] { new PermissionStatus(status) }); + return new Results (new IResult [] { new PermissionStatus (status) }); } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Notitfications/MarkNotificationsReadSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Notitfications/MarkNotificationsReadSample.cs index 99e96c2fb..9931e3eca 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Notitfications/MarkNotificationsReadSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Notitfications/MarkNotificationsReadSample.cs @@ -1,14 +1,12 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; using UIKit; using Foundation; using CloudKit; -namespace CloudKitAtlas -{ - public class NotificationsCache - { +namespace CloudKitAtlas { + public class NotificationsCache { public Results Results { get; private set; } = new Results (null, alwaysShowAsList: true); public void AddNotification (CKNotification notification) @@ -57,8 +55,7 @@ public void MarkAsRead () } } - public class MarkNotificationsReadSample : CodeSample - { + public class MarkNotificationsReadSample : CodeSample { public NotificationsCache Cache { get; private set; } = new NotificationsCache (); public MarkNotificationsReadSample () @@ -93,4 +90,4 @@ public override Task<Results> Run () return tcs.Task; } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Query/PerformQuerySample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Query/PerformQuerySample.cs index 5fc581ef9..ac46364cf 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Query/PerformQuerySample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Query/PerformQuerySample.cs @@ -1,14 +1,12 @@ -using System.Linq; +using System.Linq; using System.Threading.Tasks; using CloudKit; using CoreLocation; using Foundation; -namespace CloudKitAtlas -{ - public class PerformQuerySample : CodeSample - { +namespace CloudKitAtlas { + public class PerformQuerySample : CodeSample { CLLocation Location { get { object locationObj; @@ -47,7 +45,7 @@ public async override Task<Results> Run () var results = new Results (alwaysShowAsList: true); var len = recordArray.Length; - if(len == 0) + if (len == 0) ListHeading = "No matching items"; else if (len == 1) ListHeading = "Found 1 matching item:"; diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/DeleteRecordSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/DeleteRecordSample.cs index b117208bc..609bc847b 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/DeleteRecordSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/DeleteRecordSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class DeleteRecordSample : CodeSample - { +namespace CloudKitAtlas { + public class DeleteRecordSample : CodeSample { public DeleteRecordSample () : base (title: "DeleteRecord", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/FetchRecordSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/FetchRecordSample.cs index 52f447f94..9013c635f 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/FetchRecordSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/FetchRecordSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class FetchRecordSample : CodeSample - { +namespace CloudKitAtlas { + public class FetchRecordSample : CodeSample { public FetchRecordSample () : base (title: "FetchRecord", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/SaveRecordSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/SaveRecordSample.cs index 3b39179a9..6c1d5f4a5 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/SaveRecordSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Records/SaveRecordSample.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; using CoreLocation; using Foundation; -namespace CloudKitAtlas -{ - public class SaveRecordSample : CodeSample - { +namespace CloudKitAtlas { + public class SaveRecordSample : CodeSample { public SaveRecordSample () : base (title: "SaveRecord", className: "CKDatabase", @@ -36,7 +34,7 @@ public async override Task<Results> Run () var recordType = "Items"; CKRecord record; - if (string.IsNullOrWhiteSpace(zoneName)) { + if (string.IsNullOrWhiteSpace (zoneName)) { record = string.IsNullOrWhiteSpace (recordName) ? new CKRecord (recordType) : new CKRecord (recordType, new CKRecordID (recordName)); @@ -49,10 +47,10 @@ record = string.IsNullOrWhiteSpace (recordName) string name; if (TryGetString ("name", out name)) - record ["name"] = (NSString)name; + record ["name"] = (NSString) name; CLLocation location; - if (TryGetLocation("location", out location)) + if (TryGetLocation ("location", out location)) record ["location"] = location; NSUrl url; diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/DeleteSubscriptionSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/DeleteSubscriptionSample.cs index ff521a0be..e77c2c3a3 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/DeleteSubscriptionSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/DeleteSubscriptionSample.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Collections.Generic; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - class SubscriptionIDResult : IResult - { +namespace CloudKitAtlas { + class SubscriptionIDResult : IResult { readonly string subscriptionId; public string SummaryField { get; set; } @@ -22,14 +20,13 @@ public List<AttributeGroup> AttributeList { } } - public SubscriptionIDResult (string subscriptionId) + public SubscriptionIDResult (string subscriptionId) { this.subscriptionId = subscriptionId; } } - public class DeleteSubscriptionSample : CodeSample - { + public class DeleteSubscriptionSample : CodeSample { public DeleteSubscriptionSample () : base (title: "DeleteSubscription", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchAllSubscriptionsSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchAllSubscriptionsSample.cs index ef2279015..6e3ac31b8 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchAllSubscriptionsSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchAllSubscriptionsSample.cs @@ -1,12 +1,10 @@ -using System.Linq; +using System.Linq; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class FetchAllSubscriptionsSample : CodeSample - { +namespace CloudKitAtlas { + public class FetchAllSubscriptionsSample : CodeSample { public FetchAllSubscriptionsSample () : base (title: "FetchAllSubscriptions", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchSubscriptionSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchSubscriptionSample.cs index 92e5354bc..bde62424e 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchSubscriptionSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/FetchSubscriptionSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class FetchSubscriptionSample : CodeSample - { +namespace CloudKitAtlas { + public class FetchSubscriptionSample : CodeSample { public FetchSubscriptionSample () : base (title: "FetchSubscription", className: "CkDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/SaveSubscriptionSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/SaveSubscriptionSample.cs index 302bdf3b0..745562a18 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/SaveSubscriptionSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Subscriptions/SaveSubscriptionSample.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; using Foundation; -namespace CloudKitAtlas -{ - public class SaveSubscriptionSample : CodeSample - { +namespace CloudKitAtlas { + public class SaveSubscriptionSample : CodeSample { public override string Error { get { string subscriptionType, zoneName; @@ -67,7 +65,7 @@ public async override Task<Results> Run () NotificationInfo = notificationInfo }; } else { - var subscriptionOptions = (CKSubscriptionOptions)0; + var subscriptionOptions = (CKSubscriptionOptions) 0; bool firesOnRecordCreation; if (TryGetBool ("FiresOnRecordCreation", out firesOnRecordCreation) && firesOnRecordCreation) @@ -87,7 +85,7 @@ public async override Task<Results> Run () string beginsWithText; NSPredicate predicate = TryGetString ("name BEGINSWITH", out beginsWithText) - ? NSPredicate.FromFormat ("name BEGINSWITH %@", (NSString)beginsWithText) + ? NSPredicate.FromFormat ("name BEGINSWITH %@", (NSString) beginsWithText) : NSPredicate.FromValue (true); notificationInfo.AlertBody = $"Changed {recordType} satisfying {predicate.PredicateFormat}"; diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Sync/FetchRecordChangesSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Sync/FetchRecordChangesSample.cs index 563257a20..b7308750e 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Sync/FetchRecordChangesSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Sync/FetchRecordChangesSample.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - class ChangedRecords - { +namespace CloudKitAtlas { + class ChangedRecords { public Results Results { get; } = new Results (alwaysShowAsList: true); readonly Dictionary<CKRecordID, CKRecord> recordsByID = new Dictionary<CKRecordID, CKRecord> (); @@ -56,7 +54,7 @@ public void MarkRecordAsDeleted (CKRecordID recordID) void RemoveDeletedRecords () { foreach (var index in Results.Deleted.OrderByDescending (i => i)) { - var record = ((CKRecordWrapper)Results.Items [index]).Record; + var record = ((CKRecordWrapper) Results.Items [index]).Record; Results.Items.RemoveAt (index); recordsByID.Remove (record.Id); } @@ -84,8 +82,7 @@ public void Reset () } } - public class FetchRecordChangesSample : CodeSample - { + public class FetchRecordChangesSample : CodeSample { readonly Dictionary<CKRecordZoneID, ChangedRecords> recordCache = new Dictionary<CKRecordZoneID, ChangedRecords> (); public FetchRecordChangesSample () diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/DeleteRecordZoneSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/DeleteRecordZoneSample.cs index d407dcdcd..fe0147846 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/DeleteRecordZoneSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/DeleteRecordZoneSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class DeleteRecordZoneSample : CodeSample - { +namespace CloudKitAtlas { + public class DeleteRecordZoneSample : CodeSample { public DeleteRecordZoneSample () : base (title: "DeleteRecordZone", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchAllRecordZonesSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchAllRecordZonesSample.cs index 95c7ba41d..835d87327 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchAllRecordZonesSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchAllRecordZonesSample.cs @@ -1,12 +1,10 @@ -using System.Linq; +using System.Linq; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class FetchAllRecordZonesSample : CodeSample - { +namespace CloudKitAtlas { + public class FetchAllRecordZonesSample : CodeSample { public FetchAllRecordZonesSample () : base (title: "FetchAllRecordZones", className: "CKDatabase", @@ -33,4 +31,4 @@ public async override Task<Results> Run () return results; } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchRecordZoneSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchRecordZoneSample.cs index 9a5c3011f..35f904ed2 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchRecordZoneSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/FetchRecordZoneSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class FetchRecordZoneSample : CodeSample - { +namespace CloudKitAtlas { + public class FetchRecordZoneSample : CodeSample { public FetchRecordZoneSample () : base (title: "FetchRecordZone", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/SaveRecordZoneSample.cs b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/SaveRecordZoneSample.cs index 345f69cdd..1edc8509c 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/SaveRecordZoneSample.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/CodeSamples/Zones/SaveRecordZoneSample.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Threading.Tasks; using CloudKit; -namespace CloudKitAtlas -{ - public class SaveRecordZoneSample : CodeSample - { +namespace CloudKitAtlas { + public class SaveRecordZoneSample : CodeSample { public SaveRecordZoneSample () : base (title: "SaveRecordZone", className: "CKDatabase", diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Form/BooleanFieldTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Form/BooleanFieldTableViewCell.cs index d08fb8ad8..3bb7eb8f6 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Form/BooleanFieldTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Form/BooleanFieldTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class BooleanFieldTableViewCell : FormFieldTableViewCell - { +namespace CloudKitAtlas { + public partial class BooleanFieldTableViewCell : FormFieldTableViewCell { [Outlet] public UISwitch BooleanField { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Form/FormFieldTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Form/FormFieldTableViewCell.cs index 8c46e6d10..f5c014edd 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Form/FormFieldTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Form/FormFieldTableViewCell.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using Foundation; -namespace CloudKitAtlas -{ - [Register("FormFieldTableViewCell")] - public class FormFieldTableViewCell : UITableViewCell - { +namespace CloudKitAtlas { + [Register ("FormFieldTableViewCell")] + public class FormFieldTableViewCell : UITableViewCell { [Outlet] public UILabel FieldLabel { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Form/ImageFieldTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Form/ImageFieldTableViewCell.cs index 41c66eac7..13fd9713c 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Form/ImageFieldTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Form/ImageFieldTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class ImageFieldTableViewCell : FormFieldTableViewCell - { +namespace CloudKitAtlas { + public partial class ImageFieldTableViewCell : FormFieldTableViewCell { public ImageInput ImageInput { get; set; } [Outlet] diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Form/LocationFieldTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Form/LocationFieldTableViewCell.cs index 7e18ff716..46893a33f 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Form/LocationFieldTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Form/LocationFieldTableViewCell.cs @@ -4,10 +4,8 @@ using Foundation; using CoreLocation; -namespace CloudKitAtlas -{ - public partial class LocationFieldTableViewCell : FormFieldTableViewCell - { +namespace CloudKitAtlas { + public partial class LocationFieldTableViewCell : FormFieldTableViewCell { [Outlet] public UIButton LookUpButton { get; set; } @@ -41,8 +39,8 @@ public void SetCoordinate (CLLocationCoordinate2D coordinate) var latitude = coordinate.Latitude; var longitude = coordinate.Longitude; - LocationInput.Latitude = (int)latitude; - LocationInput.Longitude = (int)longitude; + LocationInput.Latitude = (int) latitude; + LocationInput.Longitude = (int) longitude; LatitudeField.Text = LocationInput.Latitude.ToString (); LongitudeField.Text = LocationInput.Longitude.ToString (); diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Form/SelectionFieldTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Form/SelectionFieldTableViewCell.cs index e76f7eec7..9cfc9e2c7 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Form/SelectionFieldTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Form/SelectionFieldTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class SelectionFieldTableViewCell : FormFieldTableViewCell - { +namespace CloudKitAtlas { + public partial class SelectionFieldTableViewCell : FormFieldTableViewCell { [Outlet] public UILabel SelectedItemLabel { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Form/TextFieldTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Form/TextFieldTableViewCell.cs index 0bbc5a387..8d6ca4ff8 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Form/TextFieldTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Form/TextFieldTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class TextFieldTableViewCell : FormFieldTableViewCell - { +namespace CloudKitAtlas { + public partial class TextFieldTableViewCell : FormFieldTableViewCell { [Outlet] public UITextField TextField { get; set; } @@ -21,7 +19,7 @@ public TextFieldTableViewCell (IntPtr handle) public TextFieldTableViewCell (NSCoder coder) : base (coder) { - + } } } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Loading/LoadingViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Loading/LoadingViewController.cs index c315efd80..ad51f666a 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Loading/LoadingViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Loading/LoadingViewController.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class LoadingViewController : UIViewController - { +namespace CloudKitAtlas { + public partial class LoadingViewController : UIViewController { [Outlet] public UIActivityIndicatorView ActivityIndicator { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Main.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Main.cs index f3908bd84..150b54c0b 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Main.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace CloudKitAtlas -{ - public class Application - { +namespace CloudKitAtlas { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewCell.cs index b6741c1ad..026d83acb 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class MainMenuTableViewCell : UITableViewCell - { +namespace CloudKitAtlas { + public partial class MainMenuTableViewCell : UITableViewCell { [Outlet] public UIImageView MenuIcon { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewController.cs index 229336ee2..c7f220379 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/MainMenuTableViewController.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class MainMenuTableViewController : UITableViewController - { +namespace CloudKitAtlas { + public partial class MainMenuTableViewController : UITableViewController { public CodeSampleGroup [] CodeSampleGroups { get; set; } = new CodeSampleGroup [0]; public MainMenuTableViewController (IntPtr handle) @@ -96,7 +94,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var codeSampleGroup = CodeSampleGroups [indexPath.Row]; - var cell = (MainMenuTableViewCell)tableView.DequeueReusableCell ("MainMenuItem", indexPath); + var cell = (MainMenuTableViewCell) tableView.DequeueReusableCell ("MainMenuItem", indexPath); cell.MenuLabel.Text = codeSampleGroup.Title; cell.MenuIcon.Image = codeSampleGroup.Icon; @@ -106,7 +104,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var notificationSample = codeSampleGroup.CodeSamples [0] as MarkNotificationsReadSample; if (notificationSample != null && UIApplication.SharedApplication.IsRegisteredForRemoteNotifications) { if (notificationSample.Cache.AddedIndices.Count > 0) { - cell.BadgeLabel.Superview.Layer.CornerRadius = cell.BadgeLabel.Font.PointSize * (nfloat)1.2 / 2; + cell.BadgeLabel.Superview.Layer.CornerRadius = cell.BadgeLabel.Font.PointSize * (nfloat) 1.2 / 2; cell.BadgeLabel.Text = notificationSample.Cache.AddedIndices.Count.ToString (); cell.BadgeLabel.Superview.Hidden = false; cell.BadgeLabel.Hidden = false; @@ -138,11 +136,11 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (indexPath != null) { var selectedCodeSampleGroup = CodeSampleGroups [indexPath.Row]; if (segue.Identifier == "ShowSubmenu") { - var submenuViewController = (SubmenuTableViewController)segue.DestinationViewController; + var submenuViewController = (SubmenuTableViewController) segue.DestinationViewController; submenuViewController.CodeSamples = selectedCodeSampleGroup.CodeSamples; submenuViewController.GroupTitle = selectedCodeSampleGroup.Title; } else if (segue.Identifier == "ShowCodeSampleFromMenu" && selectedCodeSampleGroup.CodeSamples.Length > 0) { - var codeSampleViewController = (CodeSampleViewController)segue.DestinationViewController; + var codeSampleViewController = (CodeSampleViewController) segue.DestinationViewController; codeSampleViewController.SelectedCodeSample = selectedCodeSampleGroup.CodeSamples [0]; codeSampleViewController.GroupTitle = selectedCodeSampleGroup.Title; } @@ -151,4 +149,4 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) #endregion } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewCell.cs index 39b4383ce..5108e23ec 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class SubmenuTableViewCell : UITableViewCell - { +namespace CloudKitAtlas { + public partial class SubmenuTableViewCell : UITableViewCell { [Outlet] public UILabel SubmenuLabel { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewController.cs index 68bb0af48..96b62d66d 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Menu/SubmenuTableViewController.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class SubmenuTableViewController : UITableViewController - { +namespace CloudKitAtlas { + public partial class SubmenuTableViewController : UITableViewController { public string GroupTitle { get; set; } public CodeSample [] CodeSamples { get; set; } @@ -47,7 +45,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var codeSample = CodeSamples [indexPath.Row]; - var cell = (SubmenuTableViewCell)tableView.DequeueReusableCell ("SubmenuItem", indexPath); + var cell = (SubmenuTableViewCell) tableView.DequeueReusableCell ("SubmenuItem", indexPath); cell.SubmenuLabel.Text = codeSample.Title; return cell; @@ -60,7 +58,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == "ShowCodeSampleFromSubmenu") { - var codeSampleViewController = (CodeSampleViewController)segue.DestinationViewController; + var codeSampleViewController = (CodeSampleViewController) segue.DestinationViewController; var selectedCell = sender as SubmenuTableViewCell; if (selectedCell != null) { var indexPath = TableView.IndexPathForCell (selectedCell); diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/MainNavigationItem.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/MainNavigationItem.cs index ea2c73361..e98eeac27 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/MainNavigationItem.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/MainNavigationItem.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class MainNavigationItem : UINavigationItem - { +namespace CloudKitAtlas { + public partial class MainNavigationItem : UINavigationItem { public MainNavigationItem (IntPtr handle) : base (handle) { diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationBar.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationBar.cs index 300e59bfd..c1f4559cf 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationBar.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationBar.cs @@ -7,10 +7,8 @@ using static UIKit.NSLayoutAttribute; using static UIKit.NSLayoutRelation; -namespace CloudKitAtlas -{ - public partial class NavigationBar : UINavigationBar - { +namespace CloudKitAtlas { + public partial class NavigationBar : UINavigationBar { NotificationBar NotificationBar { get; set; } public NavigationBar (IntPtr handle) diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationController.cs index ff7e5ea04..111a1a077 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NavigationController.cs @@ -4,10 +4,8 @@ using Foundation; using CoreFoundation; -namespace CloudKitAtlas -{ - public partial class NavigationController : UINavigationController - { +namespace CloudKitAtlas { + public partial class NavigationController : UINavigationController { public NavigationController (IntPtr handle) : base (handle) { diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NotificationBar.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NotificationBar.cs index 957f6b709..9a84460bb 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NotificationBar.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Navigation/NotificationBar.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using CloudKit; @@ -8,10 +8,8 @@ using static UIKit.NSLayoutRelation; using System.Linq; -namespace CloudKitAtlas -{ - public class NotificationBar : UIView - { +namespace CloudKitAtlas { + public class NotificationBar : UIView { NSLayoutConstraint heightConstraint; UILabel label; UIButton button; diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeKeyTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeKeyTableViewCell.cs index 411dd2a96..51b7f6dac 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeKeyTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeKeyTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class AttributeKeyTableViewCell : UITableViewCell - { +namespace CloudKitAtlas { + public partial class AttributeKeyTableViewCell : UITableViewCell { [Outlet] public UILabel AttributeKey { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeTableViewCell.cs index cecac192c..d2bd1aa1d 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/AttributeTableViewCell.cs @@ -3,15 +3,13 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class AttributeTableViewCell : UITableViewCell - { +namespace CloudKitAtlas { + public partial class AttributeTableViewCell : UITableViewCell { [Outlet] public UILabel AttributeKey { get; set; } [Outlet] - public UILabel AttributeValue { get; set;} + public UILabel AttributeValue { get; set; } public AttributeTableViewCell (IntPtr handle) : base (handle) diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ErrorViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ErrorViewController.cs index 1707192ca..1b7e888ad 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ErrorViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ErrorViewController.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class ErrorViewController : ResultOrErrorViewController - { +namespace CloudKitAtlas { + public partial class ErrorViewController : ResultOrErrorViewController { [Outlet] public UILabel ErrorCode { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ImageTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ImageTableViewCell.cs index 5ee4f4c12..397a25aa2 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ImageTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ImageTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class ImageTableViewCell : NestedAttributeTableViewCell - { +namespace CloudKitAtlas { + public partial class ImageTableViewCell : NestedAttributeTableViewCell { [Outlet] public UIImageView AssetImage { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/NestedAttributeTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/NestedAttributeTableViewCell.cs index 47a546a02..f1864d5e3 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/NestedAttributeTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/NestedAttributeTableViewCell.cs @@ -1,11 +1,9 @@ using System; using Foundation; -namespace CloudKitAtlas -{ +namespace CloudKitAtlas { // TODO: why do we need this class? - public partial class NestedAttributeTableViewCell : AttributeTableViewCell - { + public partial class NestedAttributeTableViewCell : AttributeTableViewCell { public NestedAttributeTableViewCell (IntPtr handle) : base (handle) { @@ -15,7 +13,7 @@ public NestedAttributeTableViewCell (IntPtr handle) public NestedAttributeTableViewCell (NSCoder coder) : base (coder) { - + } } } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultOrErrorViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultOrErrorViewController.cs index d8e76fab9..092ab868b 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultOrErrorViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultOrErrorViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public class ResultOrErrorViewController : UIViewController - { +namespace CloudKitAtlas { + public class ResultOrErrorViewController : UIViewController { protected UIBarButtonItem DoneButton { get; set; } protected bool IsDrilldown { get; set; } = false; diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultTableViewCell.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultTableViewCell.cs index 8619c6ad3..43241f727 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultTableViewCell.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultTableViewCell.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class ResultTableViewCell : UITableViewCell - { +namespace CloudKitAtlas { + public partial class ResultTableViewCell : UITableViewCell { [Outlet] public UILabel ResultLabel { get; set; } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultsViewController.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultsViewController.cs index 3f21675ce..9a8fb1088 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultsViewController.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Results/ResultsViewController.cs @@ -8,10 +8,8 @@ using ObjCRuntime; using CoreFoundation; -namespace CloudKitAtlas -{ - public partial class ResultsViewController : ResultOrErrorViewController, IUITableViewDelegate, IUITableViewDataSource, IUIScrollViewDelegate - { +namespace CloudKitAtlas { + public partial class ResultsViewController : ResultOrErrorViewController, IUITableViewDelegate, IUITableViewDataSource, IUIScrollViewDelegate { [Outlet] public TableView TableView { get; set; } @@ -91,13 +89,13 @@ public nint RowsInSection (UITableView tableView, nint section) { return (Results.Items.Count == 0 || Results.ShowAsList) ? Results.Items.Count - : Results.Items [0].AttributeList [(int)section].Attributes.Count; + : Results.Items [0].AttributeList [(int) section].Attributes.Count; } public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { if (Results.ShowAsList) { - var resultCell = (ResultTableViewCell)tableView.DequeueReusableCell ("ResultCell", indexPath); + var resultCell = (ResultTableViewCell) tableView.DequeueReusableCell ("ResultCell", indexPath); var result = Results.Items [indexPath.Row]; resultCell.ResultLabel.Text = result.SummaryField ?? string.Empty; resultCell.ChangeLabelWidthConstraint.Constant = 15; @@ -116,13 +114,13 @@ public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) var attribute = Results.Items [0].AttributeList [indexPath.Section].Attributes [indexPath.Row]; var value = attribute.Value; if (value == null) { - var attribCell = (AttributeKeyTableViewCell)tableView.DequeueReusableCell ("AttributeKeyCell", indexPath); + var attribCell = (AttributeKeyTableViewCell) tableView.DequeueReusableCell ("AttributeKeyCell", indexPath); attribCell.AttributeKey.Text = attribute.Key; return attribCell; } if (attribute.Image != null) { - var imgCell = (ImageTableViewCell)tableView.DequeueReusableCell ("ImageCell", indexPath); + var imgCell = (ImageTableViewCell) tableView.DequeueReusableCell ("ImageCell", indexPath); imgCell.AttributeKey.Text = attribute.Key; imgCell.AttributeValue.Text = string.IsNullOrWhiteSpace (value) ? "-" : value; imgCell.AssetImage.Image = attribute.Image; @@ -130,7 +128,7 @@ public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) } var cellIdentifier = attribute.IsNested ? "NestedAttributeCell" : "AttributeCell"; - var cell = (AttributeTableViewCell)tableView.DequeueReusableCell (cellIdentifier, indexPath); + var cell = (AttributeTableViewCell) tableView.DequeueReusableCell (cellIdentifier, indexPath); cell.AttributeKey.Text = attribute.Key; cell.AttributeValue.Text = string.IsNullOrWhiteSpace (value) ? "-" : value; @@ -148,7 +146,7 @@ public string TitleForHeader (UITableView tableView, nint section) return codeSample.ListHeading; var result = Results.Items [0]; - return result.AttributeList [(int)section].Title; + return result.AttributeList [(int) section].Title; } [Export ("tableView:heightForRowAtIndexPath:")] @@ -234,7 +232,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) resultsViewController.Results = new Results (new IResult [] { result }); resultsViewController.CodeSample = CodeSample; resultsViewController.IsDrilldown = true; - + TableView.DeselectRow (indexPath, false); } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Table/TableView.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Table/TableView.cs index a3b4da11b..2ad87fe76 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Table/TableView.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Table/TableView.cs @@ -3,10 +3,8 @@ using UIKit; using Foundation; -namespace CloudKitAtlas -{ - public partial class TableView : UITableView - { +namespace CloudKitAtlas { + public partial class TableView : UITableView { public TableView (IntPtr handle) : base (handle) { diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKDiscoveredUserInfoWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKDiscoveredUserInfoWrapper.cs index 598408ad3..e5411ad55 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKDiscoveredUserInfoWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKDiscoveredUserInfoWrapper.cs @@ -1,12 +1,10 @@ -using System.Collections.Generic; +using System.Collections.Generic; using CloudKit; using Contacts; -namespace CloudKitAtlas -{ - public class CKDiscoveredUserInfoWrapper : IResult - { +namespace CloudKitAtlas { + public class CKDiscoveredUserInfoWrapper : IResult { readonly CKDiscoveredUserInfo userInfo; public CKDiscoveredUserInfoWrapper (CKDiscoveredUserInfo userInfo) diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKFetchRecordChangesOperationFactory.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKFetchRecordChangesOperationFactory.cs index d625ca8e2..58ca2646d 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKFetchRecordChangesOperationFactory.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKFetchRecordChangesOperationFactory.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Runtime.InteropServices; using CloudKit; using ObjCRuntime; -namespace CloudKitAtlas -{ +namespace CloudKitAtlas { // TODO: This is a workaround for https://bugzilla.xamarin.com/show_bug.cgi?id=42163 // CKFetchRecordChangesOperation doesn't accept null for CKServerChangeToken – this is bug // We have to create CKFetchRecordChangesOperation w/o using ctor // This is a factory class to workaround this issue - public static class CKFetchRecordChangesOperationFactory - { + public static class CKFetchRecordChangesOperationFactory { [DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")] public static extern IntPtr IntPtr_objc_msgSend (IntPtr receiver, IntPtr selector); diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKNotificationWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKNotificationWrapper.cs index df2827215..11ede44e5 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKNotificationWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKNotificationWrapper.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Collections.Generic; using CloudKit; -namespace CloudKitAtlas -{ - public class CKNotificationWrapper : IResult - { +namespace CloudKitAtlas { + public class CKNotificationWrapper : IResult { readonly CKNotification notification; public CKNotificationWrapper (CKNotification notification) diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordIdWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordIdWrapper.cs index 2f1b435ee..6eab3b52f 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordIdWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordIdWrapper.cs @@ -1,10 +1,8 @@ -using System.Collections.Generic; +using System.Collections.Generic; using CloudKit; -namespace CloudKitAtlas -{ - public class CKRecordIdWrapper : IResult - { +namespace CloudKitAtlas { + public class CKRecordIdWrapper : IResult { readonly CKRecordID record; public CKRecordIdWrapper (CKRecordID record) @@ -34,4 +32,4 @@ public string SummaryField { } } } -} \ No newline at end of file +} diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordWrapper.cs index c1fbf8eea..c9900adab 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordWrapper.cs @@ -1,14 +1,12 @@ -using System.Collections.Generic; +using System.Collections.Generic; using Foundation; using UIKit; using CloudKit; using CoreLocation; -namespace CloudKitAtlas -{ - public class CKRecordWrapper : IResult - { +namespace CloudKitAtlas { + public class CKRecordWrapper : IResult { public CKRecord Record { get; } public CKRecordWrapper (CKRecord record) diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneIdWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneIdWrapper.cs index 9f2fd0bbd..fd2efd3e5 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneIdWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneIdWrapper.cs @@ -1,11 +1,9 @@ -using System.Collections.Generic; +using System.Collections.Generic; using CloudKit; -namespace CloudKitAtlas -{ - public class CKRecordZoneIdWrapper : IResult - { +namespace CloudKitAtlas { + public class CKRecordZoneIdWrapper : IResult { readonly CKRecordZoneID zoneId; public string SummaryField { diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneWrapper.cs index fd7440413..43d95d616 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKRecordZoneWrapper.cs @@ -1,11 +1,9 @@ -using System.Collections.Generic; +using System.Collections.Generic; using CloudKit; -namespace CloudKitAtlas -{ - public class CKRecordZoneWrapper : IResult - { +namespace CloudKitAtlas { + public class CKRecordZoneWrapper : IResult { readonly CKRecordZone zone; public string SummaryField { diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKSubscriptionWrapper.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKSubscriptionWrapper.cs index d2242b9ed..14ee5c857 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKSubscriptionWrapper.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/CKSubscriptionWrapper.cs @@ -1,13 +1,11 @@ -using System.Collections.Generic; +using System.Collections.Generic; using CloudKit; using static CloudKit.CKSubscriptionType; using static CloudKit.CKSubscriptionOptions; -namespace CloudKitAtlas -{ - public class CKSubscriptionWrapper : IResult - { +namespace CloudKitAtlas { + public class CKSubscriptionWrapper : IResult { readonly CKSubscription subscription; public string SummaryField { diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/NullableExtensions.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/NullableExtensions.cs index d7454fa0e..86abc1b30 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/NullableExtensions.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/NullableExtensions.cs @@ -1,10 +1,8 @@ -using System; +using System; -namespace CloudKitAtlas -{ - public static class NullableExtensions - { - public static T GetValueOrDefault<T> (this T? value, T defaultValue = default(T)) where T : struct +namespace CloudKitAtlas { + public static class NullableExtensions { + public static T GetValueOrDefault<T> (this T? value, T defaultValue = default (T)) where T : struct { return ValueOrDefault (value, defaultValue); } diff --git a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/SegueArg.cs b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/SegueArg.cs index 6f8c98589..038233b1a 100644 --- a/ios8/CloudKitAtlas/CloudKitAtlas/Utils/SegueArg.cs +++ b/ios8/CloudKitAtlas/CloudKitAtlas/Utils/SegueArg.cs @@ -1,9 +1,7 @@ -using Foundation; +using Foundation; -namespace CloudKitAtlas -{ - public class SegueArg : NSObject - { +namespace CloudKitAtlas { + public class SegueArg : NSObject { public CodeSample Sample { get; set; } } } diff --git a/ios8/DocPicker/DocPicker/AppDelegate.cs b/ios8/DocPicker/DocPicker/AppDelegate.cs index 7a2bb8292..fab693780 100644 --- a/ios8/DocPicker/DocPicker/AppDelegate.cs +++ b/ios8/DocPicker/DocPicker/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -7,16 +7,14 @@ using ObjCRuntime; using System.IO; -namespace DocPicker -{ +namespace DocPicker { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { #region Static Properties - public const string TestFilename = "test.txt"; + public const string TestFilename = "test.txt"; #endregion #region Computed Properties @@ -34,11 +32,12 @@ public partial class AppDelegate : UIApplicationDelegate /// <summary> /// Starts a query to look for the sample Test File. /// </summary> - private void FindDocument () { + private void FindDocument () + { Console.WriteLine ("Finding Document..."); // Create a new query and set it's scope - Query = new NSMetadataQuery(); + Query = new NSMetadataQuery (); Query.SearchScopes = new NSObject [] { NSMetadataQuery.UbiquitousDocumentsScope, NSMetadataQuery.UbiquitousDataScope, @@ -47,14 +46,14 @@ private void FindDocument () { // Build a predicate to locate the file by name and attach it to the query var pred = NSPredicate.FromFormat ("%K == %@" - , new NSObject[] { + , new NSObject [] { NSMetadataQuery.ItemFSNameKey , new NSString(TestFilename)}); Query.Predicate = pred; // Register a notification for when the query returns NSNotificationCenter.DefaultCenter.AddObserver (this - , new Selector("queryDidFinishGathering:") + , new Selector ("queryDidFinishGathering:") , NSMetadataQuery.DidFinishGatheringNotification , Query); @@ -67,14 +66,15 @@ private void FindDocument () { /// Callback for when the query finishs gathering documents. /// </summary> /// <param name="notification">Notification.</param> - [Export("queryDidFinishGathering:")] - public void DidFinishGathering (NSNotification notification) { + [Export ("queryDidFinishGathering:")] + public void DidFinishGathering (NSNotification notification) + { Console.WriteLine ("Finish Gathering Documents."); // Access the query and stop it from running - var query = (NSMetadataQuery)notification.Object; - query.DisableUpdates(); - query.StopQuery(); + var query = (NSMetadataQuery) notification.Object; + query.DisableUpdates (); + query.StopQuery (); // Release the notification NSNotificationCenter.DefaultCenter.RemoveObserver (this @@ -82,15 +82,16 @@ public void DidFinishGathering (NSNotification notification) { , query); // Load the document that the query returned - LoadDocument(query); + LoadDocument (query); } /// <summary> /// Loads the document. /// </summary> /// <param name="query">Query.</param> - private void LoadDocument (NSMetadataQuery query) { - Console.WriteLine ("Loading Document..."); + private void LoadDocument (NSMetadataQuery query) + { + Console.WriteLine ("Loading Document..."); // Take action based on the returned record count switch (query.ResultCount) { @@ -101,8 +102,8 @@ private void LoadDocument (NSMetadataQuery query) { case 1: // Gain access to the url and create a new document from // that instance - NSMetadataItem item = (NSMetadataItem)query.ResultAtIndex (0); - var url = (NSUrl)item.ValueForAttribute (NSMetadataQuery.ItemURLKey); + NSMetadataItem item = (NSMetadataItem) query.ResultAtIndex (0); + var url = (NSUrl) item.ValueForAttribute (NSMetadataQuery.ItemURLKey); // Load the document OpenDocument (url); @@ -120,13 +121,14 @@ private void LoadDocument (NSMetadataQuery query) { /// Opens the document. /// </summary> /// <param name="url">URL.</param> - public void OpenDocument(NSUrl url) { + public void OpenDocument (NSUrl url) + { Console.WriteLine ("Attempting to open: {0}", url); Document = new GenericTextDocument (url); // Open the document - Document.Open ( (success) => { + Document.Open ((success) => { if (success) { Console.WriteLine ("Document Opened"); } else @@ -140,10 +142,11 @@ public void OpenDocument(NSUrl url) { /// <summary> /// Creates the new document. /// </summary> - public void CreateNewDocument() { + public void CreateNewDocument () + { // Create path to new file // var docsFolder = Environment.GetFolderPath (Environment.SpecialFolder.Personal); - var docsFolder = Path.Combine(iCloudUrl.Path, "Documents"); + var docsFolder = Path.Combine (iCloudUrl.Path, "Documents"); var docPath = Path.Combine (docsFolder, TestFilename); var ubiq = new NSUrl (docPath, false); @@ -172,7 +175,8 @@ public void CreateNewDocument() { /// Saves the document. /// </summary> /// <returns><c>true</c>, if document was saved, <c>false</c> otherwise.</returns> - public bool SaveDocument() { + public bool SaveDocument () + { bool successful = false; // Save document to path @@ -183,7 +187,7 @@ public bool SaveDocument() { successful = true; } else { Console.WriteLine ("Unable to Save Document"); - successful=false; + successful = false; } }); @@ -202,36 +206,33 @@ public override void FinishedLaunching (UIApplication application) // Start a new thread to check and see if the user has iCloud // enabled. - new Thread(new ThreadStart(() => { + new Thread (new ThreadStart (() => { // Inform caller that we are checking for iCloud CheckingForiCloud = true; // Checks to see if the user of this device has iCloud // enabled - var uburl = NSFileManager.DefaultManager.GetUrlForUbiquityContainer(null); + var uburl = NSFileManager.DefaultManager.GetUrlForUbiquityContainer (null); // Connected to iCloud? - if (uburl == null) - { + if (uburl == null) { // No, inform caller HasiCloud = false; - iCloudUrl =null; - Console.WriteLine("Unable to connect to iCloud"); - InvokeOnMainThread(()=>{ + iCloudUrl = null; + Console.WriteLine ("Unable to connect to iCloud"); + InvokeOnMainThread (() => { var okAlertController = UIAlertController.Create ("iCloud Not Available", "Developer, please check your Entitlements.plist, Bundle ID and Provisioning Profiles.", UIAlertControllerStyle.Alert); okAlertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); Window.RootViewController.PresentViewController (okAlertController, true, null); }); - } - else - { + } else { // Yes, inform caller and save location the the Application Container HasiCloud = true; iCloudUrl = uburl; - Console.WriteLine("Connected to iCloud"); + Console.WriteLine ("Connected to iCloud"); // If we have made the connection with iCloud, start looking for documents - InvokeOnMainThread(()=>{ + InvokeOnMainThread (() => { // Search for the default document FindDocument (); }); @@ -240,16 +241,16 @@ public override void FinishedLaunching (UIApplication application) // Inform caller that we are no longer looking for iCloud CheckingForiCloud = false; - })).Start(); - + })).Start (); + } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. @@ -258,7 +259,7 @@ public override void DidEnterBackground (UIApplication application) // Trap all errors try { // Values to include in the bookmark packet - var resources = new string[] { + var resources = new string [] { NSUrl.FileSecurityKey, NSUrl.ContentModificationDateKey, NSUrl.FileResourceIdentifierKey, @@ -275,13 +276,12 @@ public override void DidEnterBackground (UIApplication application) // Yes, report it Console.WriteLine ("Error Creating Bookmark: {0}", err.LocalizedDescription); } - } - catch (Exception e) { + } catch (Exception e) { // Report error Console.WriteLine ("Error: {0}", e.Message); } } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { @@ -302,15 +302,14 @@ public override void WillEnterForeground (UIApplication application) // Load document from bookmark OpenDocument (srcUrl); } - } - catch (Exception e) { + } catch (Exception e) { // Report error Console.WriteLine ("Error: {0}", e.Message); } } } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { @@ -321,14 +320,15 @@ public override void WillTerminate (UIApplication application) /// <summary> /// Document loaded delegate. /// </summary> - public delegate void DocumentLoadedDelegate(GenericTextDocument document); + public delegate void DocumentLoadedDelegate (GenericTextDocument document); public event DocumentLoadedDelegate DocumentLoaded; /// <summary> /// Raises the document loaded event. /// </summary> /// <param name="document">Document.</param> - internal void RaiseDocumentLoaded(GenericTextDocument document) { + internal void RaiseDocumentLoaded (GenericTextDocument document) + { // Inform caller if (this.DocumentLoaded != null) { this.DocumentLoaded (document); diff --git a/ios8/DocPicker/DocPicker/Classes/GenericTextDocument.cs b/ios8/DocPicker/DocPicker/Classes/GenericTextDocument.cs index f1323d5e1..40768bfd2 100644 --- a/ios8/DocPicker/DocPicker/Classes/GenericTextDocument.cs +++ b/ios8/DocPicker/DocPicker/Classes/GenericTextDocument.cs @@ -2,13 +2,11 @@ using Foundation; using UIKit; -namespace DocPicker -{ +namespace DocPicker { /// <summary> /// The file representation is a simple text file with .txt extension. /// </summary> - public class GenericTextDocument : UIDocument - { + public class GenericTextDocument : UIDocument { #region Private Variable Storage private NSString _dataModel; #endregion @@ -20,7 +18,7 @@ public class GenericTextDocument : UIDocument /// <value>The document contents.</value> public string Contents { get { return _dataModel.ToString (); } - set { _dataModel = new NSString(value); } + set { _dataModel = new NSString (value); } } #endregion @@ -62,7 +60,7 @@ public override bool LoadFromContents (NSObject contents, string typeName, out N // Were any contents passed to the document? if (contents != null) { - _dataModel = NSString.FromData( (NSData)contents, NSStringEncoding.UTF8 ); + _dataModel = NSString.FromData ((NSData) contents, NSStringEncoding.UTF8); } // Inform caller that the document has been modified @@ -86,7 +84,7 @@ public override NSObject ContentsForType (string typeName, out NSError outError) outError = null; // Convert the contents to a NSData object and return it - NSData docData = _dataModel.Encode(NSStringEncoding.UTF8); + NSData docData = _dataModel.Encode (NSStringEncoding.UTF8); return docData; } #endregion @@ -95,13 +93,14 @@ public override NSObject ContentsForType (string typeName, out NSError outError) /// <summary> /// Document modified delegate. /// </summary> - public delegate void DocumentModifiedDelegate(GenericTextDocument document); + public delegate void DocumentModifiedDelegate (GenericTextDocument document); public event DocumentModifiedDelegate DocumentModified; /// <summary> /// Raises the document modified event. /// </summary> - internal void RaiseDocumentModified(GenericTextDocument document) { + internal void RaiseDocumentModified (GenericTextDocument document) + { // Inform caller if (this.DocumentModified != null) { this.DocumentModified (document); diff --git a/ios8/DocPicker/DocPicker/DocPickerViewController.cs b/ios8/DocPicker/DocPicker/DocPickerViewController.cs index 531af2176..f672fec59 100644 --- a/ios8/DocPicker/DocPicker/DocPickerViewController.cs +++ b/ios8/DocPicker/DocPicker/DocPickerViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; using MobileCoreServices; -namespace DocPicker -{ - public partial class DocPickerViewController : UIViewController - { +namespace DocPicker { + public partial class DocPickerViewController : UIViewController { #region Private Variables private nfloat _documentTextHeight = 0; #endregion @@ -23,7 +21,7 @@ static bool UserInterfaceIdiomIsPhone { /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -40,7 +38,8 @@ public DocPickerViewController (IntPtr handle) : base (handle) /// <returns><c>true</c>, if file was moved, <c>false</c> otherwise.</returns> /// <param name="fromURL">From UR.</param> /// <param name="toURL">To UR.</param> - private bool MoveFile(string fromURL, string toURL) { + private bool MoveFile (string fromURL, string toURL) + { bool successful = true; // Get source options @@ -52,7 +51,7 @@ private bool MoveFile(string fromURL, string toURL) { var dstIntent = NSFileAccessIntent.CreateReadingIntent (dstURL, NSFileCoordinatorReadingOptions.ForUploading); // Create an array - var intents = new NSFileAccessIntent[] { + var intents = new NSFileAccessIntent [] { srcIntent, dstIntent }; @@ -62,9 +61,9 @@ private bool MoveFile(string fromURL, string toURL) { var fileCoordinator = new NSFileCoordinator (); fileCoordinator.CoordinateAccess (intents, queue, (err) => { // Was there an error? - if (err!=null) { + if (err != null) { // Yes, inform caller - Console.WriteLine("Error: {0}",err.LocalizedDescription); + Console.WriteLine ("Error: {0}", err.LocalizedDescription); successful = false; } }); @@ -80,17 +79,18 @@ private bool MoveFile(string fromURL, string toURL) { /// Adjust the size of the <c>DocumentText</c> text editor to account for the keyboard being displayed /// </summary> /// <param name="height">The new text area height</param> - private void MoveDocumentText(nfloat height) { + private void MoveDocumentText (nfloat height) + { // Animate size change - UIView.BeginAnimations("keyboard"); - UIView.SetAnimationDuration(0.3f); + UIView.BeginAnimations ("keyboard"); + UIView.SetAnimationDuration (0.3f); // Adjust frame to move the text away from the keyboard DocumentText.Frame = new CGRect (0, DocumentText.Frame.Y, DocumentText.Frame.Width, height); // Start animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } #endregion @@ -103,7 +103,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -128,18 +128,20 @@ public override void ViewDidLoad () document.DocumentModified += (doc) => { // Display the updated contents of the document DocumentText.Text = doc.Contents; - Console.WriteLine("Document contents have been updated"); + Console.WriteLine ("Document contents have been updated"); }; }; // Wireup events for the text editor - DocumentText.ShouldBeginEditing= delegate(UITextView field){ + DocumentText.ShouldBeginEditing = delegate (UITextView field) + { //Placeholder - MoveDocumentText(_documentTextHeight-170f); + MoveDocumentText (_documentTextHeight - 170f); return true; }; - DocumentText.ShouldEndEditing= delegate (UITextView field){ - MoveDocumentText(_documentTextHeight); + DocumentText.ShouldEndEditing = delegate (UITextView field) + { + MoveDocumentText (_documentTextHeight); ThisApp.Document.Contents = DocumentText.Text; return true; }; @@ -147,17 +149,17 @@ public override void ViewDidLoad () // Wireup the Save button SaveButton.Clicked += (sender, e) => { // Close the keyboard - DocumentText.ResignFirstResponder(); + DocumentText.ResignFirstResponder (); // Save the changes to the document - ThisApp.SaveDocument(); + ThisApp.SaveDocument (); }; // Wireup the Action buttom ActionButton.Clicked += (s, e) => { // Allow the Document picker to select a range of document types - var allowedUTIs = new string[] { + var allowedUTIs = new string [] { UTType.UTF8PlainText, UTType.PlainText, UTType.RTF, @@ -169,7 +171,7 @@ public override void ViewDidLoad () // Display the picker //var picker = new UIDocumentPickerViewController (allowedUTIs, UIDocumentPickerMode.Open); - var pickerMenu = new UIDocumentMenuViewController(allowedUTIs, UIDocumentPickerMode.Open); + var pickerMenu = new UIDocumentMenuViewController (allowedUTIs, UIDocumentPickerMode.Open); pickerMenu.DidPickDocumentPicker += (sender, args) => { // Wireup Document Picker @@ -177,41 +179,41 @@ public override void ViewDidLoad () // IMPORTANT! You must lock the security scope before you can // access this file - var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource(); + var securityEnabled = pArgs.Url.StartAccessingSecurityScopedResource (); // Open the document - ThisApp.OpenDocument(pArgs.Url); + ThisApp.OpenDocument (pArgs.Url); // TODO: This should work but doesn't // Apple's WWDC 2014 sample project does this but it blows // up in Xamarin - NSFileCoordinator fileCoordinator = new NSFileCoordinator(); - NSError err; - fileCoordinator.CoordinateRead (pArgs.Url, 0, out err, (NSUrl newUrl) => { - NSData data = NSData.FromUrl(newUrl); - Console.WriteLine("Data: {0}",data); - }); + NSFileCoordinator fileCoordinator = new NSFileCoordinator (); + NSError err; + fileCoordinator.CoordinateRead (pArgs.Url, 0, out err, (NSUrl newUrl) => { + NSData data = NSData.FromUrl (newUrl); + Console.WriteLine ("Data: {0}", data); + }); // IMPORTANT! You must release the security lock established // above. - pArgs.Url.StopAccessingSecurityScopedResource(); + pArgs.Url.StopAccessingSecurityScopedResource (); }; // Display the document picker - PresentViewController(args.DocumentPicker,true,null); + PresentViewController (args.DocumentPicker, true, null); }; pickerMenu.ModalPresentationStyle = UIModalPresentationStyle.Popover; - PresentViewController(pickerMenu,true,null); + PresentViewController (pickerMenu, true, null); UIPopoverPresentationController presentationPopover = pickerMenu.PopoverPresentationController; - if (presentationPopover!=null) { + if (presentationPopover != null) { presentationPopover.SourceView = this.View; presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Down; // Get UIBarButtonItem's frame // there is no built in way to get a UIBarButtonItem frame so you need to hack your own // This is because UIBarButtonItem inherits from UIBarItem and UIBarItem inherits from NSObject - var buttonView = (UIView)((UIBarButtonItem)s).ValueForKey(new NSString("view")); + var buttonView = (UIView) ((UIBarButtonItem) s).ValueForKey (new NSString ("view")); presentationPopover.SourceRect = buttonView.Frame; } }; diff --git a/ios8/DocPicker/DocPicker/Main.cs b/ios8/DocPicker/DocPicker/Main.cs index c65d5cc6b..31f86bfaa 100644 --- a/ios8/DocPicker/DocPicker/Main.cs +++ b/ios8/DocPicker/DocPicker/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace DocPicker -{ - public class Application - { +namespace DocPicker { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/DynamicLaunchScreen/DynamicLaunchScreen/AppDelegate.cs b/ios8/DynamicLaunchScreen/DynamicLaunchScreen/AppDelegate.cs index afdcf6f68..fd1b3ec78 100644 --- a/ios8/DynamicLaunchScreen/DynamicLaunchScreen/AppDelegate.cs +++ b/ios8/DynamicLaunchScreen/DynamicLaunchScreen/AppDelegate.cs @@ -1,43 +1,41 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace DynamicLaunchScreen -{ +namespace DynamicLaunchScreen { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/ios8/DynamicLaunchScreen/DynamicLaunchScreen/DynamicLaunchScreenViewController.cs b/ios8/DynamicLaunchScreen/DynamicLaunchScreen/DynamicLaunchScreenViewController.cs index f3905e750..0f14e83b2 100644 --- a/ios8/DynamicLaunchScreen/DynamicLaunchScreen/DynamicLaunchScreenViewController.cs +++ b/ios8/DynamicLaunchScreen/DynamicLaunchScreen/DynamicLaunchScreenViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace DynamicLaunchScreen -{ - public partial class DynamicLaunchScreenViewController : UIViewController - { +namespace DynamicLaunchScreen { + public partial class DynamicLaunchScreenViewController : UIViewController { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } @@ -20,7 +18,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -29,7 +27,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/ios8/DynamicLaunchScreen/DynamicLaunchScreen/Main.cs b/ios8/DynamicLaunchScreen/DynamicLaunchScreen/Main.cs index b1e22b0a2..96380a3f8 100644 --- a/ios8/DynamicLaunchScreen/DynamicLaunchScreen/Main.cs +++ b/ios8/DynamicLaunchScreen/DynamicLaunchScreen/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace DynamicLaunchScreen -{ - public class Application - { +namespace DynamicLaunchScreen { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/ExtensionsDemo/EvolveCountdownWidget/EvolveCountdownViewController.cs b/ios8/ExtensionsDemo/EvolveCountdownWidget/EvolveCountdownViewController.cs index f08a364b0..d629bfe7b 100644 --- a/ios8/ExtensionsDemo/EvolveCountdownWidget/EvolveCountdownViewController.cs +++ b/ios8/ExtensionsDemo/EvolveCountdownWidget/EvolveCountdownViewController.cs @@ -31,7 +31,7 @@ public void WidgetPerformUpdate (Action<NCUpdateResult> completionHandler) completionHandler (NCUpdateResult.NewData); } - void UpdateTitle() + void UpdateTitle () { var evolveStartDate = new DateTime (2014, 10, 6); var numDays = (evolveStartDate - DateTime.Now).Days; diff --git a/ios8/ExtensionsDemo/ExtensionsDemo/AppDelegate.cs b/ios8/ExtensionsDemo/ExtensionsDemo/AppDelegate.cs index 7db026008..5c3437395 100644 --- a/ios8/ExtensionsDemo/ExtensionsDemo/AppDelegate.cs +++ b/ios8/ExtensionsDemo/ExtensionsDemo/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace ExtensionsDemo { diff --git a/ios8/ExtensionsDemo/ExtensionsDemo/ExtensionsDemoViewController.cs b/ios8/ExtensionsDemo/ExtensionsDemo/ExtensionsDemoViewController.cs index 4998bc76b..0ee90f284 100644 --- a/ios8/ExtensionsDemo/ExtensionsDemo/ExtensionsDemoViewController.cs +++ b/ios8/ExtensionsDemo/ExtensionsDemo/ExtensionsDemoViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; diff --git a/ios8/ExtensionsDemo/ExtensionsDemo/Main.cs b/ios8/ExtensionsDemo/ExtensionsDemo/Main.cs index 2354b293e..c1bca0365 100644 --- a/ios8/ExtensionsDemo/ExtensionsDemo/Main.cs +++ b/ios8/ExtensionsDemo/ExtensionsDemo/Main.cs @@ -1,9 +1,9 @@ -using UIKit; +using UIKit; namespace ExtensionsDemo { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/Fit/Fit/Age, Height, and Weight/ProfileViewController.cs b/ios8/Fit/Fit/Age, Height, and Weight/ProfileViewController.cs index d26b2d894..c5e7159f3 100644 --- a/ios8/Fit/Fit/Age, Height, and Weight/ProfileViewController.cs +++ b/ios8/Fit/Fit/Age, Height, and Weight/ProfileViewController.cs @@ -4,17 +4,15 @@ using HealthKit; using UIKit; -namespace Fit -{ - public partial class ProfileViewController : UITableViewController, IHealthStore - { +namespace Fit { + public partial class ProfileViewController : UITableViewController, IHealthStore { NSNumberFormatter numberFormatter; public HKHealthStore HealthStore { get; set; } NSSet DataTypesToWrite { get { - return NSSet.MakeNSObjectSet <HKObjectType> (new HKObjectType[] { + return NSSet.MakeNSObjectSet<HKObjectType> (new HKObjectType [] { HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.DietaryEnergyConsumed), HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.ActiveEnergyBurned), HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.Height), @@ -25,7 +23,7 @@ NSSet DataTypesToWrite { NSSet DataTypesToRead { get { - return NSSet.MakeNSObjectSet <HKObjectType> (new HKObjectType[] { + return NSSet.MakeNSObjectSet<HKObjectType> (new HKObjectType [] { HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.DietaryEnergyConsumed), HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.ActiveEnergyBurned), HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.Height), @@ -78,7 +76,7 @@ void UpdateUsersAge () var now = NSDate.Now; NSDateComponents ageComponents = NSCalendar.CurrentCalendar.Components (NSCalendarUnit.Year, dateOfBirth, now, - NSCalendarOptions.WrapCalendarComponents); + NSCalendarOptions.WrapCalendarComponents); nint usersAge = ageComponents.Year; @@ -103,7 +101,8 @@ void UpdateUsersHeight () usersHeight = mostRecentQuantity.GetDoubleValue (heightUnit); } - InvokeOnMainThread (delegate { + InvokeOnMainThread (delegate + { heightValueLabel.Text = numberFormatter.StringFromNumber (new NSNumber (usersHeight)); }); }); @@ -127,32 +126,33 @@ void UpdateUsersWeight () usersWeight = mostRecentQuantity.GetDoubleValue (weightUnit); } - InvokeOnMainThread (delegate { + InvokeOnMainThread (delegate + { weightValueLabel.Text = numberFormatter.StringFromNumber (new NSNumber (usersWeight)); }); } ); } - void FetchMostRecentData (HKQuantityType quantityType, Action <HKQuantity, NSError> completion) + void FetchMostRecentData (HKQuantityType quantityType, Action<HKQuantity, NSError> completion) { var timeSortDescriptor = new NSSortDescriptor (HKSample.SortIdentifierEndDate, false); - var query = new HKSampleQuery (quantityType, null, 1, new NSSortDescriptor[] { timeSortDescriptor }, - (HKSampleQuery resultQuery, HKSample[] results, NSError error) => { - if (completion != null && error != null) { - completion (null, error); - return; - } - - HKQuantity quantity = null; - if (results.Length != 0) { - var quantitySample = (HKQuantitySample)results [results.Length - 1]; - quantity = quantitySample.Quantity; - } - - if (completion != null) - completion (quantity, error); - }); + var query = new HKSampleQuery (quantityType, null, 1, new NSSortDescriptor [] { timeSortDescriptor }, + (HKSampleQuery resultQuery, HKSample [] results, NSError error) => { + if (completion != null && error != null) { + completion (null, error); + return; + } + + HKQuantity quantity = null; + if (results.Length != 0) { + var quantitySample = (HKQuantitySample) results [results.Length - 1]; + quantity = quantitySample.Quantity; + } + + if (completion != null) + completion (quantity, error); + }); HealthStore.ExecuteQuery (query); } @@ -218,7 +218,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) var textField = alertController.TextFields [0]; double value; Double.TryParse (textField.Text, out value); - if(valueChangedHandler != null) + if (valueChangedHandler != null) valueChangedHandler (value); TableView.DeselectRow (indexPath, true); }); diff --git a/ios8/Fit/Fit/AppDelegate.cs b/ios8/Fit/Fit/AppDelegate.cs index 73f734d13..642ce6775 100644 --- a/ios8/Fit/Fit/AppDelegate.cs +++ b/ios8/Fit/Fit/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,14 +6,12 @@ using UIKit; using HealthKit; -namespace Fit -{ +namespace Fit { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) @@ -50,7 +48,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary void SetupHealthStoreForTabBarControllers () { - var tabBarController = (UITabBarController)Window.RootViewController; + var tabBarController = (UITabBarController) Window.RootViewController; foreach (UINavigationController navigationController in tabBarController.ViewControllers) { IHealthStore controller = navigationController.TopViewController as IHealthStore; if (controller != null) diff --git a/ios8/Fit/Fit/Energy/EnergyViewController.cs b/ios8/Fit/Fit/Energy/EnergyViewController.cs index a070d6a71..0db6b0582 100644 --- a/ios8/Fit/Fit/Energy/EnergyViewController.cs +++ b/ios8/Fit/Fit/Energy/EnergyViewController.cs @@ -4,10 +4,8 @@ using ObjCRuntime; using UIKit; -namespace Fit -{ - public partial class EnergyViewController : UITableViewController, IHealthStore - { +namespace Fit { + public partial class EnergyViewController : UITableViewController, IHealthStore { double simulatedBurntEnergy; double consumedEnergy; double netEnergy; @@ -28,7 +26,7 @@ NSEnergyFormatter EnergyFormatter { } } - public HKHealthStore HealthStore { get; set; } + public HKHealthStore HealthStore { get; set; } public double SimulatedBurntEnergy { get { @@ -79,7 +77,8 @@ void RefreshStatistics (object sender, EventArgs args) { RefreshControl.BeginRefreshing (); FetchMostRecentData ((totalJoulesConsumed, error) => { - InvokeOnMainThread (delegate { + InvokeOnMainThread (delegate + { SimulatedBurntEnergy = new Random ().Next (0, 300000); ConsumedEnergy = totalJoulesConsumed; NetEnergy = consumedEnergy - simulatedBurntEnergy; @@ -88,28 +87,28 @@ void RefreshStatistics (object sender, EventArgs args) }); } - void FetchMostRecentData (Action <double, NSError> completionHandler) + void FetchMostRecentData (Action<double, NSError> completionHandler) { var calendar = NSCalendar.CurrentCalendar; var startDate = DateTime.Now.Date; var endDate = startDate.AddDays (1); var sampleType = HKQuantityType.GetQuantityType (HKQuantityTypeIdentifierKey.DietaryEnergyConsumed); - var predicate = HKQuery.GetPredicateForSamples ((NSDate)startDate, (NSDate)endDate, HKQueryOptions.StrictStartDate); + var predicate = HKQuery.GetPredicateForSamples ((NSDate) startDate, (NSDate) endDate, HKQueryOptions.StrictStartDate); var query = new HKStatisticsQuery (sampleType, predicate, HKStatisticsOptions.CumulativeSum, - (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => { + (HKStatisticsQuery resultQuery, HKStatistics results, NSError error) => { - if (error != null && completionHandler != null) - completionHandler (0.0f, error); + if (error != null && completionHandler != null) + completionHandler (0.0f, error); - var totalCalories = results.SumQuantity (); - if (totalCalories == null) - totalCalories = HKQuantity.FromQuantity (HKUnit.Joule, 0.0); + var totalCalories = results.SumQuantity (); + if (totalCalories == null) + totalCalories = HKQuantity.FromQuantity (HKUnit.Joule, 0.0); - if (completionHandler != null) - completionHandler (totalCalories.GetDoubleValue (HKUnit.Joule), error); - }); + if (completionHandler != null) + completionHandler (totalCalories.GetDoubleValue (HKUnit.Joule), error); + }); HealthStore.ExecuteQuery (query); } diff --git a/ios8/Fit/Fit/IHealthStore.cs b/ios8/Fit/Fit/IHealthStore.cs index 9ab8ca737..9b1fffa5b 100644 --- a/ios8/Fit/Fit/IHealthStore.cs +++ b/ios8/Fit/Fit/IHealthStore.cs @@ -1,10 +1,8 @@ -using System; +using System; using HealthKit; -namespace Fit -{ - public interface IHealthStore - { +namespace Fit { + public interface IHealthStore { HKHealthStore HealthStore { get; set; } } } diff --git a/ios8/Fit/Fit/Journal/FoodItem.cs b/ios8/Fit/Fit/Journal/FoodItem.cs index f4399dee4..ecafb9814 100644 --- a/ios8/Fit/Fit/Journal/FoodItem.cs +++ b/ios8/Fit/Fit/Journal/FoodItem.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; -namespace Fit -{ - public class FoodItem : NSObject - { +namespace Fit { + public class FoodItem : NSObject { public string Name { get; private set; } public double Joules { get; private set; } @@ -29,8 +27,8 @@ public FoodItem () public override bool Equals (object obj) { - if (obj.GetType () == typeof(FoodItem)) - return ((FoodItem)obj).Joules == Joules && ((FoodItem)obj).Name == Name; + if (obj.GetType () == typeof (FoodItem)) + return ((FoodItem) obj).Joules == Joules && ((FoodItem) obj).Name == Name; return false; } diff --git a/ios8/Fit/Fit/Journal/FoodPickerViewController.cs b/ios8/Fit/Fit/Journal/FoodPickerViewController.cs index 75809089c..95f9f1023 100644 --- a/ios8/Fit/Fit/Journal/FoodPickerViewController.cs +++ b/ios8/Fit/Fit/Journal/FoodPickerViewController.cs @@ -2,10 +2,8 @@ using Foundation; using UIKit; -namespace Fit -{ - public partial class FoodPickerViewController : UITableViewController - { +namespace Fit { + public partial class FoodPickerViewController : UITableViewController { readonly NSString CellIdentifier = new NSString ("cell"); NSEnergyFormatter energyFormatter; @@ -35,7 +33,7 @@ public FoodPickerViewController (IntPtr handle) : base (handle) public override void ViewDidLoad () { base.ViewDidLoad (); - FoodItems = NSArray.FromObjects (new object[] { + FoodItems = NSArray.FromObjects (new object [] { FoodItem.Create ("Wheat Bagel", 240000.0), FoodItem.Create ("Bran with Raisins", 190000.0), FoodItem.Create ("Regular Instant Coffee", 1000.0), @@ -51,13 +49,13 @@ public override void ViewDidLoad () public override nint RowsInSection (UITableView tableview, nint section) { - return (nint)FoodItems.Count; + return (nint) FoodItems.Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = TableView.DequeueReusableCell (CellIdentifier, indexPath); - var foodItem = FoodItems.GetItem<FoodItem> ((nuint)indexPath.Row); + var foodItem = FoodItems.GetItem<FoodItem> ((nuint) indexPath.Row); cell.TextLabel.Text = foodItem.Name; cell.DetailTextLabel.Text = EnergyFormatter.StringFromJoules (foodItem.Joules); @@ -67,8 +65,8 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { NSIndexPath indexPathForSelectedRow = TableView.IndexPathForSelectedRow; - SelectedFoodItem = FoodItems.GetItem<FoodItem> ((nuint)indexPathForSelectedRow.Row); - ((JournalViewController)NavigationController.ViewControllers [NavigationController.ViewControllers.Length - 2]). + SelectedFoodItem = FoodItems.GetItem<FoodItem> ((nuint) indexPathForSelectedRow.Row); + ((JournalViewController) NavigationController.ViewControllers [NavigationController.ViewControllers.Length - 2]). AddFoodItem (SelectedFoodItem); NavigationController.PopViewController (true); } diff --git a/ios8/Fit/Fit/Journal/JournalViewController.cs b/ios8/Fit/Fit/Journal/JournalViewController.cs index fbd349600..f56f95cd3 100644 --- a/ios8/Fit/Fit/Journal/JournalViewController.cs +++ b/ios8/Fit/Fit/Journal/JournalViewController.cs @@ -4,10 +4,8 @@ using HealthKit; using ObjCRuntime; -namespace Fit -{ - public partial class JournalViewController : UITableViewController, IHealthStore - { +namespace Fit { + public partial class JournalViewController : UITableViewController, IHealthStore { readonly NSString CellReuseIdentifier = new NSString ("cell"); NSEnergyFormatter energyFormatter; @@ -39,7 +37,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); FoodItems = new NSMutableArray (); - if(HealthStore != null) + if (HealthStore != null) UpdateJournal (null, null); UIApplication.Notifications.ObserveDidBecomeActive (UpdateJournal); } @@ -49,12 +47,12 @@ void UpdateJournal (object sender, EventArgs args) var calendar = NSCalendar.CurrentCalendar; var startDate = DateTime.Now.Date; - var endDate = startDate.AddDays(1); + var endDate = startDate.AddDays (1); var sampleType = HKSampleType.GetQuantityType (HKQuantityTypeIdentifierKey.DietaryEnergyConsumed); - var predicate = HKQuery.GetPredicateForSamples ((NSDate)startDate, (NSDate)endDate, HKQueryOptions.None); + var predicate = HKQuery.GetPredicateForSamples ((NSDate) startDate, (NSDate) endDate, HKQueryOptions.None); - var query = new HKSampleQuery (sampleType, predicate, 0, new NSSortDescriptor[0], (resultQuery, results, error) => { + var query = new HKSampleQuery (sampleType, predicate, 0, new NSSortDescriptor [0], (resultQuery, results, error) => { if (error != null) { Console.WriteLine ("An error occured fetching the user's tracked food. " + "In your app, try to handle this gracefully. The error was: {0}.", error.LocalizedDescription); @@ -65,7 +63,7 @@ void UpdateJournal (object sender, EventArgs args) FoodItems.RemoveAllObjects (); foreach (HKQuantitySample sample in results) { - var foodName = (NSString)sample.Metadata.Dictionary [HKMetadataKey.FoodType]; + var foodName = (NSString) sample.Metadata.Dictionary [HKMetadataKey.FoodType]; double joules = sample.Quantity.GetDoubleValue (HKUnit.Joule); var foodItem = FoodItem.Create (foodName, joules); @@ -94,7 +92,7 @@ public void AddFoodItem (FoodItem item) FoodItems.Insert (item, 0); var indexPathForInsertedFoodItem = NSIndexPath.FromRowSection (0, 0); InvokeOnMainThread (() => { - TableView.InsertRows (new NSIndexPath[] { indexPathForInsertedFoodItem }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new NSIndexPath [] { indexPathForInsertedFoodItem }, UITableViewRowAnimation.Automatic); }); } else { Console.WriteLine ("An error occured saving the food {0}. In your app, try to handle this gracefully. " + @@ -105,13 +103,13 @@ public void AddFoodItem (FoodItem item) public override nint RowsInSection (UITableView tableview, nint section) { - return (nint)FoodItems.Count; + return (nint) FoodItems.Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = TableView.DequeueReusableCell (CellReuseIdentifier, indexPath); - var foodItem = FoodItems.GetItem<FoodItem> ((nuint)indexPath.Row); + var foodItem = FoodItems.GetItem<FoodItem> ((nuint) indexPath.Row); cell.TextLabel.Text = foodItem.Name; cell.DetailTextLabel.Text = EnergyFormatter.StringFromValue (foodItem.Joules, NSEnergyFormatterUnit.Joule); return cell; diff --git a/ios8/Fit/Fit/Main.cs b/ios8/Fit/Fit/Main.cs index 2ccd11d9f..b416c70e7 100644 --- a/ios8/Fit/Fit/Main.cs +++ b/ios8/Fit/Fit/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace Fit -{ - public class Application - { +namespace Fit { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/Footprint/Footprint/AppDelegate.cs b/ios8/Footprint/Footprint/AppDelegate.cs index e7caf4a3a..059515430 100644 --- a/ios8/Footprint/Footprint/AppDelegate.cs +++ b/ios8/Footprint/Footprint/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace Footprint -{ +namespace Footprint { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication app, NSDictionary options) diff --git a/ios8/Footprint/Footprint/Main.cs b/ios8/Footprint/Footprint/Main.cs index 740e6dba2..96160d52d 100644 --- a/ios8/Footprint/Footprint/Main.cs +++ b/ios8/Footprint/Footprint/Main.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace Footprint -{ - public class Application - { - static void Main (string[] args) +namespace Footprint { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios8/Footprint/Footprint/MainViewController.cs b/ios8/Footprint/Footprint/MainViewController.cs index f2a06d36c..06fd1376e 100644 --- a/ios8/Footprint/Footprint/MainViewController.cs +++ b/ios8/Footprint/Footprint/MainViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; @@ -6,11 +6,9 @@ using CoreGraphics; using CoreLocation; -namespace Footprint -{ +namespace Footprint { [Register ("MainViewController")] - public class MainViewController : UIViewController - { + public class MainViewController : UIViewController { [Outlet ("imageView")] UIImageView ImageView { get; set; } @@ -105,18 +103,18 @@ void StartTrackingLocation () void OnAuthorizationChanged (object sender, CLAuthorizationChangedEventArgs e) { switch (e.Status) { - case CLAuthorizationStatus.AuthorizedAlways: - case CLAuthorizationStatus.AuthorizedWhenInUse: - Console.WriteLine ("Got authorization, start tracking location"); - StartTrackingLocation (); - break; - - case CLAuthorizationStatus.NotDetermined: - locationManager.RequestWhenInUseAuthorization (); - break; - - default: - break; + case CLAuthorizationStatus.AuthorizedAlways: + case CLAuthorizationStatus.AuthorizedWhenInUse: + Console.WriteLine ("Got authorization, start tracking location"); + StartTrackingLocation (); + break; + + case CLAuthorizationStatus.NotDetermined: + locationManager.RequestWhenInUseAuthorization (); + break; + + default: + break; } } @@ -142,7 +140,7 @@ void UpdateViewWithLocation (CLLocation location) var scaledPoint = new CGPoint (x, y); // Calculate and set the size of the radius - nfloat radiusFrameSize = (nfloat)location.HorizontalAccuracy * coordinateConverter.PixelsPerMeter * 2; + nfloat radiusFrameSize = (nfloat) location.HorizontalAccuracy * coordinateConverter.PixelsPerMeter * 2; RadiusView.Frame = new CGRect (0, 0, radiusFrameSize, radiusFrameSize); // Move the pin and radius to the user's location diff --git a/ios8/Footprint/Footprint/Math/CoordinateConverter.cs b/ios8/Footprint/Footprint/Math/CoordinateConverter.cs index 2626935fe..89f03b99b 100644 --- a/ios8/Footprint/Footprint/Math/CoordinateConverter.cs +++ b/ios8/Footprint/Footprint/Math/CoordinateConverter.cs @@ -1,12 +1,10 @@ -using System; +using System; using MapKit; using CoreGraphics; using CoreLocation; -namespace Footprint -{ - public class CoordinateConverter - { +namespace Footprint { + public class CoordinateConverter { // We pick one of the anchors on the floorplan as an origin point that we will compute distance relative to. MKMapPoint fromAnchorMKPoint; CGPoint fromAnchorFloorplanPoint; @@ -47,7 +45,7 @@ void Init (Tuple<GeoAnchor, GeoAnchor> anchors) // So that we can use MapKit's helper function to compute distance. // this helper function takes into account the curvature of the earth. - var distanceBetweenPointsMeters = (nfloat)MKGeometry.MetersBetweenMapPoints (fromAnchorMKPoint, toAnchorMKPoint); + var distanceBetweenPointsMeters = (nfloat) MKGeometry.MetersBetweenMapPoints (fromAnchorMKPoint, toAnchorMKPoint); var dx = anchors.Item1.Pixel.X - anchors.Item2.Pixel.X; var dy = anchors.Item1.Pixel.Y - anchors.Item2.Pixel.Y; @@ -101,11 +99,11 @@ public CGPoint Convert (CLLocationCoordinate2D coordinate) static EastSouthDistance FetchRect (MKMapPoint fromAnchorMKPoint, MKMapPoint toPoint) { double latitude = MKMapPoint.ToCoordinate (fromAnchorMKPoint).Latitude; - nfloat metersPerMapPoint = (nfloat)MKGeometry.MetersPerMapPointAtLatitude (latitude); + nfloat metersPerMapPoint = (nfloat) MKGeometry.MetersPerMapPointAtLatitude (latitude); var eastSouthDistance = new EastSouthDistance { - East = (nfloat)(toPoint.X - fromAnchorMKPoint.X) * metersPerMapPoint, - South = (nfloat)(toPoint.Y - fromAnchorMKPoint.Y) * metersPerMapPoint + East = (nfloat) (toPoint.X - fromAnchorMKPoint.X) * metersPerMapPoint, + South = (nfloat) (toPoint.Y - fromAnchorMKPoint.Y) * metersPerMapPoint }; return eastSouthDistance; } diff --git a/ios8/Footprint/Footprint/Math/EastSouthDistance.cs b/ios8/Footprint/Footprint/Math/EastSouthDistance.cs index d3e40c81a..2765df63e 100644 --- a/ios8/Footprint/Footprint/Math/EastSouthDistance.cs +++ b/ios8/Footprint/Footprint/Math/EastSouthDistance.cs @@ -1,14 +1,12 @@ -using System; +using System; using CoreLocation; -namespace Footprint -{ +namespace Footprint { // Struct that contains a point in meters (east and south) with respect to an origin point (in geographic space) // We use East & South because when drawing on an image, origin (0,0) is on the top-left. // So +eastMeters corresponds to +x and +southMeters corresponds to +y - public struct EastSouthDistance - { + public struct EastSouthDistance { public nfloat East { get; set; } public nfloat South { get; set; } diff --git a/ios8/Footprint/Footprint/Math/GeoAnchor.cs b/ios8/Footprint/Footprint/Math/GeoAnchor.cs index 9d99bbf2f..2c9653129 100644 --- a/ios8/Footprint/Footprint/Math/GeoAnchor.cs +++ b/ios8/Footprint/Footprint/Math/GeoAnchor.cs @@ -1,11 +1,9 @@ -using System; +using System; using CoreLocation; using CoreGraphics; -namespace Footprint -{ - public struct GeoAnchor - { +namespace Footprint { + public struct GeoAnchor { public CLLocationCoordinate2D LatitudeLongitude { get; set; } public CGPoint Pixel { get; set; } diff --git a/ios8/HelloGoodbye/HelloGoodbye/AppDelegate.cs b/ios8/HelloGoodbye/HelloGoodbye/AppDelegate.cs index 1d32445c6..afa367772 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/AppDelegate.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace HelloGoodbye -{ +namespace HelloGoodbye { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; StartViewController startViewController; UINavigationController navigationController; diff --git a/ios8/HelloGoodbye/HelloGoodbye/LocalizationHelper.cs b/ios8/HelloGoodbye/HelloGoodbye/LocalizationHelper.cs index a240f7af6..7a2800602 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/LocalizationHelper.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/LocalizationHelper.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; -namespace HelloGoodbye -{ - public static class LocalizationHelper - { - public static string LocalizedString(this string key, string comment) +namespace HelloGoodbye { + public static class LocalizationHelper { + public static string LocalizedString (this string key, string comment) { return NSBundle.MainBundle.LocalizedString (key, comment); } diff --git a/ios8/HelloGoodbye/HelloGoodbye/Main.cs b/ios8/HelloGoodbye/HelloGoodbye/Main.cs index c9184ea3a..3da67dfaf 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Main.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Main.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace HelloGoodbye -{ - public class Application - { - static void Main (string[] args) +namespace HelloGoodbye { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios8/HelloGoodbye/HelloGoodbye/Model/Person.cs b/ios8/HelloGoodbye/HelloGoodbye/Model/Person.cs index 29aac7391..fee6edb15 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Model/Person.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Model/Person.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace HelloGoodbye -{ - public class Person - { +namespace HelloGoodbye { + public class Person { const string PhotoKey = "photo"; const string AgeKey = "age"; const string HobbiesKey = "hobbies"; @@ -17,13 +15,13 @@ public class Person public string Hobbies { get; set; } public string ElevatorPitch { get; set; } - public static Person PersonFromDictionary(NSDictionary dict) + public static Person PersonFromDictionary (NSDictionary dict) { Person person = new Person { - Photo = UIImage.FromBundle((string)(NSString)dict[PhotoKey]), - Age = ((NSNumber)dict[AgeKey]).Int32Value, - Hobbies = (string)(NSString)dict[HobbiesKey], - ElevatorPitch = (string)(NSString)dict[ElevatorPitchKey], + Photo = UIImage.FromBundle ((string) (NSString) dict [PhotoKey]), + Age = ((NSNumber) dict [AgeKey]).Int32Value, + Hobbies = (string) (NSString) dict [HobbiesKey], + ElevatorPitch = (string) (NSString) dict [ElevatorPitchKey], }; return person; diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/AgeSlider.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/AgeSlider.cs index 41f1e8b7c..3191a8bb8 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/AgeSlider.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/AgeSlider.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using UIKit; using Foundation; -namespace HelloGoodbye -{ - public class AgeSlider : UISlider - { +namespace HelloGoodbye { + public class AgeSlider : UISlider { public override string AccessibilityValue { get { NSNumber number = NSNumber.FromFloat (Value); @@ -19,7 +17,7 @@ public override string AccessibilityValue { } } - public AgeSlider() + public AgeSlider () { TintColor = StyleUtilities.ForegroundColor; MinValue = 18; diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/PreviewLabel.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/PreviewLabel.cs index bb1f19765..386488e0a 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/PreviewLabel.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/Controls/PreviewLabel.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Drawing; using UIKit; -namespace HelloGoodbye -{ - public class PreviewLabel : UILabel - { +namespace HelloGoodbye { + public class PreviewLabel : UILabel { public event EventHandler ActivatePreviewLabel; public override UIAccessibilityTrait AccessibilityTraits { @@ -20,7 +18,7 @@ public override UIAccessibilityTrait AccessibilityTraits { public PreviewLabel () { - Text = "Preview".LocalizedString("Name of the card preview tab"); + Text = "Preview".LocalizedString ("Name of the card preview tab"); Font = StyleUtilities.LargeFont; TextColor = StyleUtilities.PreviewTabLabelColor; } diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/MatchesViewController.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/MatchesViewController.cs index 7f3f17b81..135580656 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/MatchesViewController.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/MatchesViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; @@ -6,10 +6,8 @@ using CoreGraphics; using ObjCRuntime; -namespace HelloGoodbye -{ - public class MatchesViewController : PhotoBackgroundViewController - { +namespace HelloGoodbye { + public class MatchesViewController : PhotoBackgroundViewController { const float HelloGoodbyeVerticalMargin = 5f; const float SwipeAnimationDuration = 0.5f; const float ZoomAnimationDuration = 0.3f; @@ -19,7 +17,7 @@ public class MatchesViewController : PhotoBackgroundViewController UIView swipeInstructionsView; UIView allMatchesViewedExplanatoryView; - NSLayoutConstraint[] cardViewVerticalConstraints; + NSLayoutConstraint [] cardViewVerticalConstraints; List<Person> matches; int currentMatchIndex; @@ -46,7 +44,7 @@ public MatchesViewController () matches.Add (match); } - Title = "Matches".LocalizedString("Title of the matches page"); + Title = "Matches".LocalizedString ("Title of the matches page"); BackgroundImage = UIImage.FromBundle ("dessert.jpg"); } @@ -69,14 +67,14 @@ public override void ViewDidLoad () // Define the vertical positioning of the card // These constraints will be removed when the card animates off screen - cardViewVerticalConstraints = new NSLayoutConstraint[] { + cardViewVerticalConstraints = new NSLayoutConstraint [] { NSLayoutConstraint.Create (cardView, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, dummyView, NSLayoutAttribute.CenterY, 1f, 0f), NSLayoutConstraint.Create (cardView, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, swipeInstructionsView, NSLayoutAttribute.Bottom, 1f, HelloGoodbyeVerticalMargin) }; constraints.AddRange (cardViewVerticalConstraints); // Ensure that the card is centered horizontally within the container view, and doesn't exceed its width - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (cardView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.CenterX, 1f, 0f), NSLayoutConstraint.Create (cardView, NSLayoutAttribute.Left, NSLayoutRelation.GreaterThanOrEqual, containerView, NSLayoutAttribute.Left, 1f, 0f), NSLayoutConstraint.Create (cardView, NSLayoutAttribute.Right, NSLayoutRelation.LessThanOrEqual, containerView, NSLayoutAttribute.Right, 1f, 0f), @@ -84,18 +82,18 @@ public override void ViewDidLoad () // When the matches run out, we'll show this message allMatchesViewedExplanatoryView = AddAllMatchesViewExplanatoryViewToContainerView (containerView, constraints); - containerView.AddConstraints (constraints.ToArray()); + containerView.AddConstraints (constraints.ToArray ()); } - UIView AddDummyViewToContainerView(UIView containerView, INativeObject topItem, INativeObject bottomItem, List<NSLayoutConstraint> constraints) + UIView AddDummyViewToContainerView (UIView containerView, INativeObject topItem, INativeObject bottomItem, List<NSLayoutConstraint> constraints) { - UIView dummyView = new UIView{ + UIView dummyView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false }; containerView.AddSubview (dummyView); // The horizontal layout of the dummy view does not matter, but for completeness, we give it a width of 0 and center it horizontally. - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (dummyView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0f, 0f), NSLayoutConstraint.Create (dummyView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.CenterX, 1f, 0f), NSLayoutConstraint.Create (dummyView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, topItem, NSLayoutAttribute.Bottom, 1f, 0f), @@ -105,7 +103,7 @@ UIView AddDummyViewToContainerView(UIView containerView, INativeObject topItem, return dummyView; } - CardView AddCardViewToView(UIView containerView) + CardView AddCardViewToView (UIView containerView) { CardView cv = new CardView (); cv.Update (CurrentMatch); @@ -113,7 +111,7 @@ CardView AddCardViewToView(UIView containerView) this.cardView = cv; containerView.AddSubview (cv); - UISwipeGestureRecognizer swipeUpRecognizer = new UISwipeGestureRecognizer(HandleSwipeUp); + UISwipeGestureRecognizer swipeUpRecognizer = new UISwipeGestureRecognizer (HandleSwipeUp); swipeUpRecognizer.Direction = UISwipeGestureRecognizerDirection.Up; cv.AddGestureRecognizer (swipeUpRecognizer); @@ -127,26 +125,26 @@ CardView AddCardViewToView(UIView containerView) string sayGoodbyeName = "Say goodbye".LocalizedString ("Accessibility action to say goodbye"); goodbyeAction = new UIAccessibilityCustomAction (sayGoodbyeName, probe: SayGoodbye); - UIView[] elements = NSArray.FromArray<UIView> ((NSArray)cv.GetAccessibilityElements ()); + UIView [] elements = NSArray.FromArray<UIView> ((NSArray) cv.GetAccessibilityElements ()); foreach (UIView element in elements) - element.AccessibilityCustomActions = new UIAccessibilityCustomAction[] { helloAction, goodbyeAction }; + element.AccessibilityCustomActions = new UIAccessibilityCustomAction [] { helloAction, goodbyeAction }; return cv; } - void HandleSwipeUp(UISwipeGestureRecognizer gestureRecognizer) + void HandleSwipeUp (UISwipeGestureRecognizer gestureRecognizer) { if (gestureRecognizer.State == UIGestureRecognizerState.Recognized) SayHello (helloAction); } - void HandleSwipeDown(UISwipeGestureRecognizer gestureRecognizer) + void HandleSwipeDown (UISwipeGestureRecognizer gestureRecognizer) { if (gestureRecognizer.State == UIGestureRecognizerState.Recognized) SayGoodbye (goodbyeAction); } - UIView AddAllMatchesViewExplanatoryViewToContainerView(UIView containerView, List<NSLayoutConstraint> constraints) + UIView AddAllMatchesViewExplanatoryViewToContainerView (UIView containerView, List<NSLayoutConstraint> constraints) { UIView overlayView = AddOverlayViewToContainerView (containerView); @@ -172,19 +170,19 @@ UIView AddAllMatchesViewExplanatoryViewToContainerView(UIView containerView, Lis return overlayView; } - bool SayHello(UIAccessibilityCustomAction customAction) + bool SayHello (UIAccessibilityCustomAction customAction) { AnimateCardsForHello (true); return true; } - bool SayGoodbye(UIAccessibilityCustomAction customAction) + bool SayGoodbye (UIAccessibilityCustomAction customAction) { AnimateCardsForHello (false); return true; } - void AnimateCardsForHello(bool forHello) + void AnimateCardsForHello (bool forHello) { AnimateCardOffScreenToTop (forHello, () => { currentMatchIndex++; @@ -218,7 +216,7 @@ void AnimateCardsForHello(bool forHello) }); } - void FadeCardIntoView() + void FadeCardIntoView () { cardView.Alpha = 0f; UIView.Animate (FadeAnimationDuration, () => { @@ -226,15 +224,15 @@ void FadeCardIntoView() }); } - void ZoomCardIntoView() + void ZoomCardIntoView () { - cardView.Transform = CGAffineTransform.MakeScale(0f, 0f); + cardView.Transform = CGAffineTransform.MakeScale (0f, 0f); UIView.Animate (ZoomAnimationDuration, () => { cardView.Transform = CGAffineTransform.MakeIdentity (); }); } - void AnimateCardOffScreenToTop(bool toTop, Action completion) + void AnimateCardOffScreenToTop (bool toTop, Action completion) { NSLayoutConstraint offScreenConstraint = null; if (toTop) @@ -259,7 +257,7 @@ void AnimateCardOffScreenToTop(bool toTop, Action completion) }); } - UIView AddSwipeInstructionsToContainerView(UIView containerView, List<NSLayoutConstraint>constraints) + UIView AddSwipeInstructionsToContainerView (UIView containerView, List<NSLayoutConstraint> constraints) { UIView overlayView = AddOverlayViewToContainerView (containerView); @@ -270,8 +268,8 @@ UIView AddSwipeInstructionsToContainerView(UIView containerView, List<NSLayoutCo swipeInstructionsLabel.AccessibilityLabel = "Swipe up to say \"Hello!\"\nSwipe down to say \"Goodbye\"".LocalizedString ("Accessibility instructions for the Matches page"); float overlayMargin = StyleUtilities.OverlayMargin; - NSLayoutConstraint topMarginConstraint = NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, overlayMargin); - float priority = (int)UILayoutPriority.Required - 1; + NSLayoutConstraint topMarginConstraint = NSLayoutConstraint.Create (overlayView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, overlayMargin); + float priority = (int) UILayoutPriority.Required - 1; topMarginConstraint.Priority = priority; constraints.Add (topMarginConstraint); @@ -287,14 +285,14 @@ UIView AddSwipeInstructionsToContainerView(UIView containerView, List<NSLayoutCo return overlayView; } - UIView AddOverlayViewToContainerView(UIView containerView) + UIView AddOverlayViewToContainerView (UIView containerView) { UIView overlayView = new UIView { BackgroundColor = StyleUtilities.OverlayColor, TranslatesAutoresizingMaskIntoConstraints = false, }; overlayView.Layer.CornerRadius = StyleUtilities.OverlayCornerRadius; - containerView.AddSubview(overlayView); + containerView.AddSubview (overlayView); return overlayView; } diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/PhotoBackgroundViewController.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/PhotoBackgroundViewController.cs index 5e6a8f547..f79863cc1 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/PhotoBackgroundViewController.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/PhotoBackgroundViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using UIKit; using CoreGraphics; -namespace HelloGoodbye -{ - public class PhotoBackgroundViewController : UIViewController - { +namespace HelloGoodbye { + public class PhotoBackgroundViewController : UIViewController { UIImageView backgroundView; UIView containerView; @@ -22,7 +20,7 @@ public UIImage BackgroundImage { backgroundImage = value; - if(backgroundView != null) + if (backgroundView != null) backgroundView.Image = backgroundImage; } } diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/CardView.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/CardView.cs index e222bc9aa..84321a660 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/CardView.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/CardView.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using System.Collections.Generic; @@ -6,10 +6,8 @@ using Foundation; using CoreGraphics; -namespace HelloGoodbye -{ - public class CardView : UIView, IUIAccessibilityContainer - { +namespace HelloGoodbye { + public class CardView : UIView, IUIAccessibilityContainer { const float PhotoWidth = 80; const float BorderWidth = 5; const float HorizontalPadding = 20; @@ -42,7 +40,7 @@ public CardView () AddAllConstraints (); } - void AddProfileViews() + void AddProfileViews () { photo = new UIImageView { IsAccessibilityElement = true, @@ -52,8 +50,8 @@ void AddProfileViews() AddSubview (photo); ageTitleLabel = StyleUtilities.CreateStandardLabel (); - ageTitleLabel.Text = "Age".LocalizedString("Age of the user"); - AddSubview(ageTitleLabel); + ageTitleLabel.Text = "Age".LocalizedString ("Age of the user"); + AddSubview (ageTitleLabel); ageValueLabel = StyleUtilities.CreateDetailLabel (); AddSubview (ageValueLabel); @@ -83,12 +81,12 @@ void AddProfileViews() )); } - void AddAllConstraints() + void AddAllConstraints () { var constraints = new List<NSLayoutConstraint> (); // Fill the card with the background view (leaving a border around it) - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (backgroundView, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, this, NSLayoutAttribute.Leading, 1f, BorderWidth), NSLayoutConstraint.Create (backgroundView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1f, BorderWidth), NSLayoutConstraint.Create (this, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, backgroundView, NSLayoutAttribute.Trailing, 1f, BorderWidth), @@ -98,7 +96,7 @@ void AddAllConstraints() // Position the photo // The constant for the aspect ratio constraint will be updated once a photo is set photoAspectRatioConstraint = NSLayoutConstraint.Create (photo, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0f, 0f); - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (photo, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, this, NSLayoutAttribute.Leading, 1f, HorizontalPadding), NSLayoutConstraint.Create (photo, NSLayoutAttribute.Top, NSLayoutRelation.Equal, this, NSLayoutAttribute.Top, 1f, VerticalPadding), NSLayoutConstraint.Create (photo, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0f, PhotoWidth), @@ -107,7 +105,7 @@ void AddAllConstraints() }); // Position the age to the right of the photo, with some spacing - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (ageTitleLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, photo, NSLayoutAttribute.Trailing, 1f, InterItemHorizontalSpacing), NSLayoutConstraint.Create (ageTitleLabel, NSLayoutAttribute.Top, NSLayoutRelation.Equal, photo, NSLayoutAttribute.Top, 1f, 0f), NSLayoutConstraint.Create (ageValueLabel, NSLayoutAttribute.Top, NSLayoutRelation.Equal, ageTitleLabel, NSLayoutAttribute.Bottom, 1f, TitleValueSpacing), @@ -126,7 +124,7 @@ void AddAllConstraints() }); // Position the elevator pitch below the age and the hobbies - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (elevatorPitchTitleLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, ageTitleLabel, NSLayoutAttribute.Leading, 1f, 0f), NSLayoutConstraint.Create (elevatorPitchTitleLabel, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, ageValueLabel, NSLayoutAttribute.Bottom, 1f, InterItemVerticalSpacing), NSLayoutConstraint.Create (elevatorPitchTitleLabel, NSLayoutAttribute.Top, NSLayoutRelation.GreaterThanOrEqual, hobbiesValueLabel, NSLayoutAttribute.Bottom, 1f, InterItemVerticalSpacing), @@ -139,7 +137,7 @@ void AddAllConstraints() AddConstraints (constraints.ToArray ()); } - public void Update(Person person) + public void Update (Person person) { if (person == null) throw new ArgumentNullException ("person"); @@ -152,7 +150,7 @@ public void Update(Person person) elevatorPitchValueLabel.Text = person.ElevatorPitch; } - void UpdatePhotoConstraint() + void UpdatePhotoConstraint () { CGSize size = photo.Image.Size; nfloat ratio = size.Height / size.Width; diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/ProfileViewController.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/ProfileViewController.cs index 01bb8a0f7..1bba70841 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/ProfileViewController.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/Profile/ProfileViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using System.Collections.Generic; @@ -6,10 +6,8 @@ using Foundation; using CoreText; -namespace HelloGoodbye -{ - public class ProfileViewController : PhotoBackgroundViewController - { +namespace HelloGoodbye { + public class ProfileViewController : PhotoBackgroundViewController { const float LabelControlMinimumSpacing = 20; const float MinimumVerticalSpacingBetweenRows = 20; const float PreviewTabMinimumWidth = 80; @@ -41,12 +39,12 @@ nfloat CardHeight { public ProfileViewController () { - Title = @"Profile".LocalizedString("Title of the profile page"); + Title = @"Profile".LocalizedString ("Title of the profile page"); BackgroundImage = UIImage.FromBundle ("girl-bg.jpg"); // Create the model. If we had a backing service, this model would pull data from the user's account settings. person = new Person { - Photo = UIImage.FromBundle("girl.jpg"), + Photo = UIImage.FromBundle ("girl.jpg"), Age = 37, Hobbies = "Music, swing dance, wine", ElevatorPitch = "I can keep a steady beat.", @@ -61,12 +59,12 @@ public override void ViewDidLoad () var constraints = new List<NSLayoutConstraint> (); UIView overlayView = AddOverlayViewToView (containerView, constraints); - UIView[] ageControls = AddAgeControlsToView (overlayView, constraints); + UIView [] ageControls = AddAgeControlsToView (overlayView, constraints); hobbiesField = AddTextFieldWithName ("Hobbies".LocalizedString ("The user's hobbies"), person.Hobbies, overlayView, ageControls, constraints); - elevatorPitchField = AddTextFieldWithName ("Elevator Pitch".LocalizedString ("The user's elevator pitch for finding a partner"), person.ElevatorPitch, overlayView, new UIView[] { hobbiesField }, constraints); + elevatorPitchField = AddTextFieldWithName ("Elevator Pitch".LocalizedString ("The user's elevator pitch for finding a partner"), person.ElevatorPitch, overlayView, new UIView [] { hobbiesField }, constraints); AddCardAndPreviewTab (constraints); - containerView.AddConstraints (constraints.ToArray()); + containerView.AddConstraints (constraints.ToArray ()); } UIView AddOverlayViewToView (UIView containerView, List<NSLayoutConstraint> constraints) @@ -81,8 +79,8 @@ UIView AddOverlayViewToView (UIView containerView, List<NSLayoutConstraint> cons // Cover the view controller with the overlay, leaving a margin on all sides float margin = StyleUtilities.OverlayMargin; - constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, margin)); - constraints.Add(NSLayoutConstraint.Create(overlayView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, BottomLayoutGuide, NSLayoutAttribute.Bottom, 1f, -margin)); + constraints.Add (NSLayoutConstraint.Create (overlayView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, TopLayoutGuide, NSLayoutAttribute.Bottom, 1f, margin)); + constraints.Add (NSLayoutConstraint.Create (overlayView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, BottomLayoutGuide, NSLayoutAttribute.Bottom, 1f, -margin)); constraints.Add (NSLayoutConstraint.Create (overlayView, NSLayoutAttribute.Left, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.Left, 1f, margin)); constraints.Add (NSLayoutConstraint.Create (overlayView, NSLayoutAttribute.Right, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.Right, 1f, -margin)); return overlayView; @@ -102,8 +100,8 @@ UITextField AddTextFieldWithName (string name, string text, UIView overlayView, Font = StyleUtilities.StandardFont, TextColor = StyleUtilities.DetailOnOverlayColor, Text = text, - AttributedPlaceholder = new NSAttributedString("Type here...".LocalizedString("Placeholder for profile text fields"), attributes), - TranslatesAutoresizingMaskIntoConstraints = false + AttributedPlaceholder = new NSAttributedString ("Type here...".LocalizedString ("Placeholder for profile text fields"), attributes), + TranslatesAutoresizingMaskIntoConstraints = false }; overlayView.AddSubview (valueField); @@ -122,7 +120,7 @@ UITextField AddTextFieldWithName (string name, string text, UIView overlayView, return valueField; } - UIView[] AddAgeControlsToView(UIView overlayView, List<NSLayoutConstraint> constraints) + UIView [] AddAgeControlsToView (UIView overlayView, List<NSLayoutConstraint> constraints) { UILabel ageTitleLabel = StyleUtilities.CreateStandardLabel (); ageTitleLabel.Text = "Your age".LocalizedString ("The user's age"); @@ -139,7 +137,7 @@ UIView[] AddAgeControlsToView(UIView overlayView, List<NSLayoutConstraint> const ageValueLabel = AddAgeValueLabelToView (overlayView); UpdateAgeValueLabelFromSlider (ageSlider); -// // Position the age title and value side by side, within the overlay view + // // Position the age title and value side by side, within the overlay view constraints.Add (NSLayoutConstraint.Create (ageTitleLabel, NSLayoutAttribute.Top, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Top, 1f, StyleUtilities.ContentVerticalMargin)); constraints.Add (NSLayoutConstraint.Create (ageTitleLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Leading, 1f, StyleUtilities.ContentHorizontalMargin)); constraints.Add (NSLayoutConstraint.Create (ageSlider, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, ageTitleLabel, NSLayoutAttribute.Trailing, 1f, LabelControlMinimumSpacing)); @@ -148,10 +146,10 @@ UIView[] AddAgeControlsToView(UIView overlayView, List<NSLayoutConstraint> const constraints.Add (NSLayoutConstraint.Create (ageValueLabel, NSLayoutAttribute.FirstBaseline, NSLayoutRelation.Equal, ageTitleLabel, NSLayoutAttribute.FirstBaseline, 1f, 0f)); constraints.Add (NSLayoutConstraint.Create (ageValueLabel, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, overlayView, NSLayoutAttribute.Trailing, 1f, -1 * StyleUtilities.ContentHorizontalMargin)); - return new UIView[]{ ageTitleLabel, ageSlider, ageValueLabel }; + return new UIView [] { ageTitleLabel, ageSlider, ageValueLabel }; } - UILabel AddAgeValueLabelToView(UIView overlayView) + UILabel AddAgeValueLabelToView (UIView overlayView) { UILabel ageValueLabel = StyleUtilities.CreateStandardLabel (); ageValueLabel.IsAccessibilityElement = false; @@ -160,13 +158,13 @@ UILabel AddAgeValueLabelToView(UIView overlayView) return ageValueLabel; } - void UpdateAgeValueLabelFromSlider(AgeSlider ageSlider) + void UpdateAgeValueLabelFromSlider (AgeSlider ageSlider) { NSNumber number = NSNumber.FromFloat (ageSlider.Value); ageValueLabel.Text = NSNumberFormatter.LocalizedStringFromNumbernumberStyle (number, NSNumberFormatterStyle.Decimal); } - void AddCardAndPreviewTab(List<NSLayoutConstraint> constraints) + void AddCardAndPreviewTab (List<NSLayoutConstraint> constraints) { previewTab = AddPreviewTab (); previewTab.TranslatesAutoresizingMaskIntoConstraints = false; @@ -180,9 +178,9 @@ void AddCardAndPreviewTab(List<NSLayoutConstraint> constraints) // Pin the tab to the bottom center of the screen cardRevealConstraint = NSLayoutConstraint.Create (previewTab, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1f, 0f); constraints.Add (cardRevealConstraint); - constraints.Add(NSLayoutConstraint.Create(previewTab, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1f, 0f)); + constraints.Add (NSLayoutConstraint.Create (previewTab, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1f, 0f)); // Center the preview label within the tab - constraints.Add(NSLayoutConstraint.Create (previewLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, previewTab, NSLayoutAttribute.Leading, 1f, PreviewTabHorizontalPadding)); + constraints.Add (NSLayoutConstraint.Create (previewLabel, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, previewTab, NSLayoutAttribute.Leading, 1f, PreviewTabHorizontalPadding)); constraints.Add (NSLayoutConstraint.Create (previewLabel, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, previewTab, NSLayoutAttribute.Trailing, 1f, -PreviewTabHorizontalPadding)); constraints.Add (NSLayoutConstraint.Create (previewLabel, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, previewTab, NSLayoutAttribute.CenterY, 1f, 0f)); @@ -194,19 +192,19 @@ void AddCardAndPreviewTab(List<NSLayoutConstraint> constraints) constraints.Add (NSLayoutConstraint.Create (cardView, NSLayoutAttribute.Width, NSLayoutRelation.LessThanOrEqual, View, NSLayoutAttribute.Width, 1f, 0f)); } - UIImageView AddPreviewTab() + UIImageView AddPreviewTab () { UIImage previewTabBackgroundImage = CreatePreviewTabBackgroundImage (); - UIImageView previewTab = new UIImageView(previewTabBackgroundImage); + UIImageView previewTab = new UIImageView (previewTabBackgroundImage); previewTab.UserInteractionEnabled = true; - View.AddSubview(previewTab); + View.AddSubview (previewTab); - UIPanGestureRecognizer revealGestureRecognizer = new UIPanGestureRecognizer(DidSlidePreviewTab); - previewTab.AddGestureRecognizer(revealGestureRecognizer); + UIPanGestureRecognizer revealGestureRecognizer = new UIPanGestureRecognizer (DidSlidePreviewTab); + previewTab.AddGestureRecognizer (revealGestureRecognizer); return previewTab; } - UIImage CreatePreviewTabBackgroundImage() + UIImage CreatePreviewTabBackgroundImage () { // The preview tab should be flat on the bottom, and have rounded corners on top. var size = new SizeF (PreviewTabMinimumWidth, PreviewTabHeight); @@ -227,44 +225,44 @@ UIImage CreatePreviewTabBackgroundImage() return previewTabBackgroundImage; } - void DidSlidePreviewTab(UIPanGestureRecognizer gestureRecognizer) + void DidSlidePreviewTab (UIPanGestureRecognizer gestureRecognizer) { switch (gestureRecognizer.State) { - case UIGestureRecognizerState.Began: - cardWasRevealedBeforePan = IsCardRevealed; - break; - - case UIGestureRecognizerState.Changed: - nfloat cardHeight = CardHeight; - nfloat cardRevealConstant = gestureRecognizer.TranslationInView (View).Y; - if (cardWasRevealedBeforePan) { - cardRevealConstant += -1 * cardHeight; - } - // Never let the card tab move off screen - cardRevealConstant = NMath.Min (0, cardRevealConstant); - // Never let the card have a gap below it - cardRevealConstant = NMath.Max (-1 * cardHeight, cardRevealConstant); - cardRevealConstraint.Constant = cardRevealConstant; - break; - - case UIGestureRecognizerState.Ended: + case UIGestureRecognizerState.Began: + cardWasRevealedBeforePan = IsCardRevealed; + break; + + case UIGestureRecognizerState.Changed: + nfloat cardHeight = CardHeight; + nfloat cardRevealConstant = gestureRecognizer.TranslationInView (View).Y; + if (cardWasRevealedBeforePan) { + cardRevealConstant += -1 * cardHeight; + } + // Never let the card tab move off screen + cardRevealConstant = NMath.Min (0, cardRevealConstant); + // Never let the card have a gap below it + cardRevealConstant = NMath.Max (-1 * cardHeight, cardRevealConstant); + cardRevealConstraint.Constant = cardRevealConstant; + break; + + case UIGestureRecognizerState.Ended: // Card was closer to the bottom of the screen - if (cardRevealConstraint.Constant > (-0.5 * CardHeight)) - DismissCard (); - else - RevealCard (); - break; - - case UIGestureRecognizerState.Cancelled: - if (cardWasRevealedBeforePan) - RevealCard (); - else - DismissCard (); - break; + if (cardRevealConstraint.Constant > (-0.5 * CardHeight)) + DismissCard (); + else + RevealCard (); + break; + + case UIGestureRecognizerState.Cancelled: + if (cardWasRevealedBeforePan) + RevealCard (); + else + DismissCard (); + break; } } - void RevealCard() + void RevealCard () { View.LayoutIfNeeded (); @@ -272,11 +270,11 @@ void RevealCard() cardRevealConstraint.Constant = -1 * CardHeight; View.LayoutIfNeeded (); }, () => { - UIAccessibility.PostNotification(UIAccessibilityPostNotification.LayoutChanged, null); + UIAccessibility.PostNotification (UIAccessibilityPostNotification.LayoutChanged, null); }); } - void DismissCard() + void DismissCard () { View.LayoutIfNeeded (); @@ -288,11 +286,11 @@ void DismissCard() }); } - PreviewLabel AddPreviewLabel() + PreviewLabel AddPreviewLabel () { - PreviewLabel previewLabel = new PreviewLabel(); + PreviewLabel previewLabel = new PreviewLabel (); previewLabel.ActivatePreviewLabel += DidActivatePreviewLabel; - View.AddSubview(previewLabel); + View.AddSubview (previewLabel); return previewLabel; } @@ -305,9 +303,9 @@ void DidActivatePreviewLabel (object sender, EventArgs e) RevealCard (); } - CardView AddCardView() + CardView AddCardView () { - cardView = new CardView(); + cardView = new CardView (); cardView.Update (person); View.AddSubview (cardView); @@ -316,9 +314,9 @@ CardView AddCardView() void OnAgeUpdate (object sender, EventArgs e) { - var ageSlider = (AgeSlider)sender; + var ageSlider = (AgeSlider) sender; // Turn the value into a valid age - int age = (int)Math.Round(ageSlider.Value); + int age = (int) Math.Round (ageSlider.Value); ageSlider.Value = age; // Display the updated age next to the slider @@ -333,15 +331,15 @@ void OnAgeUpdate (object sender, EventArgs e) #region UITextFieldDelegate - [Export("textFieldDidBeginEditing:")] - public void TextFieldDidBeginEditing(UITextField textField) + [Export ("textFieldDidBeginEditing:")] + public void TextFieldDidBeginEditing (UITextField textField) { // Add a Done button so that the user can dismiss the keyboard easily NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done, DoneButtonPressed); } - [Export("textFieldDidEndEditing:")] - public void TextFieldDidEndEditing(UITextField textField) + [Export ("textFieldDidEndEditing:")] + public void TextFieldDidEndEditing (UITextField textField) { // Remove the Done button NavigationItem.RightBarButtonItem = null; @@ -353,11 +351,11 @@ public void TextFieldDidEndEditing(UITextField textField) person.ElevatorPitch = textField.Text; // Update the card view with the new data - cardView.Update(person); + cardView.Update (person); } #endregion - void DoneButtonPressed(object sender, EventArgs args) + void DoneButtonPressed (object sender, EventArgs args) { // End editing on whichever text field is first responder hobbiesField.ResignFirstResponder (); diff --git a/ios8/HelloGoodbye/HelloGoodbye/Screens/StartScreen/StartViewController.cs b/ios8/HelloGoodbye/HelloGoodbye/Screens/StartScreen/StartViewController.cs index 20c2a0222..d9e872054 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/Screens/StartScreen/StartViewController.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/Screens/StartScreen/StartViewController.cs @@ -1,20 +1,18 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using Foundation; using ObjCRuntime; -namespace HelloGoodbye -{ - public class StartViewController : PhotoBackgroundViewController - { +namespace HelloGoodbye { + public class StartViewController : PhotoBackgroundViewController { const float ButtonToButtonVerticalSpacing = 10; const float LogoPadding = 30; public StartViewController () { - Title = "HelloGoodbye".LocalizedString("Title of the start page"); + Title = "HelloGoodbye".LocalizedString ("Title of the start page"); BackgroundImage = UIImage.FromBundle ("couple.jpg"); } @@ -43,7 +41,7 @@ public override void ViewDidLoad () containerView.AddSubview (profileButton); containerView.AddSubview (matchesButton); - var constraints = new List<NSLayoutConstraint>(); + var constraints = new List<NSLayoutConstraint> (); // Use dummy views space the top of the view, the logo, the buttons, and the bottom of the view evenly apart UIView topDummyView = AddDummyViewToContainerView (containerView, TopLayoutGuide, logoOverlayView, constraints); @@ -53,7 +51,7 @@ public override void ViewDidLoad () constraints.Add (NSLayoutConstraint.Create (middleDummyView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, bottomDummyView, NSLayoutAttribute.Height, 1f, 0f)); // Position the logo - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create (logoOverlayView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, topDummyView, NSLayoutAttribute.Bottom, 1f, 0f), NSLayoutConstraint.Create (logoOverlayView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.CenterX, 1f, 0f), NSLayoutConstraint.Create (logoOverlayView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, middleDummyView, NSLayoutAttribute.Top, 1f, 0f), @@ -77,10 +75,10 @@ public override void ViewDidLoad () constraints.Add (NSLayoutConstraint.Create (matchesButton, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, logoOverlayView, NSLayoutAttribute.Leading, 1f, 0f)); constraints.Add (NSLayoutConstraint.Create (matchesButton, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, logoOverlayView, NSLayoutAttribute.Trailing, 1f, 0f)); - containerView.AddConstraints (constraints.ToArray()); + containerView.AddConstraints (constraints.ToArray ()); } - UIView AddDummyViewToContainerView(UIView containerView, INativeObject topItem, INativeObject bottomItem, List<NSLayoutConstraint> constraints) + UIView AddDummyViewToContainerView (UIView containerView, INativeObject topItem, INativeObject bottomItem, List<NSLayoutConstraint> constraints) { UIView dummyView = new UIView { TranslatesAutoresizingMaskIntoConstraints = false @@ -89,7 +87,7 @@ UIView AddDummyViewToContainerView(UIView containerView, INativeObject topItem, containerView.AddSubview (dummyView); // The horizontal layout of the dummy view does not matter, but for completeness, we give it a width of 0 and center it horizontally. - constraints.AddRange (new NSLayoutConstraint[] { + constraints.AddRange (new NSLayoutConstraint [] { NSLayoutConstraint.Create(dummyView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 0f, 0f), NSLayoutConstraint.Create(dummyView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, containerView, NSLayoutAttribute.CenterX, 1f, 0f), NSLayoutConstraint.Create(dummyView, NSLayoutAttribute.Top, NSLayoutRelation.Equal, topItem, NSLayoutAttribute.Bottom, 1f, 0f), @@ -99,7 +97,7 @@ UIView AddDummyViewToContainerView(UIView containerView, INativeObject topItem, return dummyView; } - UIButton CreateButton(string titleKey, string titleComment, EventHandler handler) + UIButton CreateButton (string titleKey, string titleComment, EventHandler handler) { UIButton button = StyleUtilities.CreateOverlayRoundedRectButton (); button.SetTitle (titleKey.LocalizedString (titleComment), UIControlState.Normal); diff --git a/ios8/HelloGoodbye/HelloGoodbye/StyleUtilities.cs b/ios8/HelloGoodbye/HelloGoodbye/StyleUtilities.cs index 43f035192..37a5cfe29 100644 --- a/ios8/HelloGoodbye/HelloGoodbye/StyleUtilities.cs +++ b/ios8/HelloGoodbye/HelloGoodbye/StyleUtilities.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Drawing; using UIKit; -namespace HelloGoodbye -{ - public static class StyleUtilities - { +namespace HelloGoodbye { + public static class StyleUtilities { const float kOverlayCornerRadius = 10; const float kButtonVerticalContentInset = 10; const float kButtonHorizontalContentInset = 10; @@ -23,7 +21,7 @@ public static UIColor ForegroundColor { public static UIColor OverlayColor { get { return UIAccessibility.IsReduceTransparencyEnabled ? UIColor.White - : UIColor.FromWhiteAlpha (white:1f, alpha: 0.8f); + : UIColor.FromWhiteAlpha (white: 1f, alpha: 0.8f); } } @@ -42,7 +40,7 @@ public static UIColor CardBackgroundColor { public static UIColor DetailColor { get { return UIAccessibility.DarkerSystemColosEnabled ? UIColor.Black - : UIColor.Gray; + : UIColor.Gray; } } @@ -106,7 +104,7 @@ public static UIFont LargeFont { } } - public static UILabel CreateStandardLabel() + public static UILabel CreateStandardLabel () { UILabel label = new UILabel { TextColor = ForegroundColor, @@ -117,14 +115,14 @@ public static UILabel CreateStandardLabel() return label; } - public static UILabel CreateDetailLabel() + public static UILabel CreateDetailLabel () { - UILabel label = CreateStandardLabel(); + UILabel label = CreateStandardLabel (); label.TextColor = DetailColor; return label; } - public static UIButton CreateOverlayRoundedRectButton() + public static UIButton CreateOverlayRoundedRectButton () { UIButton button = new UIButton (UIButtonType.Custom); button.TranslatesAutoresizingMaskIntoConstraints = false; @@ -135,10 +133,10 @@ public static UIButton CreateOverlayRoundedRectButton() return button; } - static UIImage CreateOverlayRoundedRectImage() + static UIImage CreateOverlayRoundedRectImage () { UIImage roundedRectImage = null; - SizeF imageSize = new SizeF(2 * kOverlayCornerRadius, 2 * kOverlayCornerRadius); + SizeF imageSize = new SizeF (2 * kOverlayCornerRadius, 2 * kOverlayCornerRadius); UIGraphics.BeginImageContextWithOptions (imageSize, false, UIScreen.MainScreen.Scale); var rect = new RectangleF (PointF.Empty, imageSize); diff --git a/ios8/ImageInverter/ImageInverter/AppDelegate.cs b/ios8/ImageInverter/ImageInverter/AppDelegate.cs index 854201fb4..fec9762e7 100644 --- a/ios8/ImageInverter/ImageInverter/AppDelegate.cs +++ b/ios8/ImageInverter/ImageInverter/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace ImageInverter -{ +namespace ImageInverter { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication app, NSDictionary options) diff --git a/ios8/ImageInverter/ImageInverter/ImageShareViewController.cs b/ios8/ImageInverter/ImageInverter/ImageShareViewController.cs index 72f37ebc0..cb9992d11 100644 --- a/ios8/ImageInverter/ImageInverter/ImageShareViewController.cs +++ b/ios8/ImageInverter/ImageInverter/ImageShareViewController.cs @@ -4,15 +4,13 @@ using UIKit; using MobileCoreServices; -namespace ImageInverter -{ +namespace ImageInverter { [Register ("ImageShareViewController")] - public class ImageShareViewController : UIViewController - { - [Outlet("imageView")] + public class ImageShareViewController : UIViewController { + [Outlet ("imageView")] public UIImageView ImageView { get; set; } - [Outlet("shareItem")] + [Outlet ("shareItem")] public UIBarButtonItem ShareItem { get; set; } public ImageShareViewController (IntPtr handle) @@ -21,13 +19,13 @@ public ImageShareViewController (IntPtr handle) } [Export ("initWithCoder:")] - public ImageShareViewController(NSCoder coder) + public ImageShareViewController (NSCoder coder) : base (coder) { } - [Action("share:")] - void OnShareClicked(UIBarButtonItem button) + [Action ("share:")] + void OnShareClicked (UIBarButtonItem button) { var activityViewController = new UIActivityViewController (new [] { ImageView.Image @@ -45,13 +43,13 @@ void OnShareClicked(UIBarButtonItem button) NSExtensionItem extensionItem = returnedItems [0]; NSItemProvider imageItemProvider = extensionItem.Attachments [0]; - if (!imageItemProvider.HasItemConformingTo(UTType.Image)) + if (!imageItemProvider.HasItemConformingTo (UTType.Image)) return; imageItemProvider.LoadItem (UTType.Image, null, (item, loadError) => { if (item != null && loadError == null) InvokeOnMainThread (() => { - ImageView.Image = (UIImage)item; + ImageView.Image = (UIImage) item; }); }); }); @@ -59,4 +57,4 @@ void OnShareClicked(UIBarButtonItem button) PresentViewController (activityViewController, true, null); } } -} \ No newline at end of file +} diff --git a/ios8/ImageInverter/ImageInverter/Main.cs b/ios8/ImageInverter/ImageInverter/Main.cs index fe8da1d26..9718727ce 100644 --- a/ios8/ImageInverter/ImageInverter/Main.cs +++ b/ios8/ImageInverter/ImageInverter/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace ImageInverter -{ - public class Application - { +namespace ImageInverter { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/ImageInverter/ImageInverterExt/AppDelegate.cs b/ios8/ImageInverter/ImageInverterExt/AppDelegate.cs index 373f682b7..9d755f0f8 100644 --- a/ios8/ImageInverter/ImageInverterExt/AppDelegate.cs +++ b/ios8/ImageInverter/ImageInverterExt/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace ImageInverterExt -{ +namespace ImageInverterExt { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios8/ImageInverter/ImageInverterExt/ImageInverterViewController.cs b/ios8/ImageInverter/ImageInverterExt/ImageInverterViewController.cs index 7adc8d989..df9b538ad 100644 --- a/ios8/ImageInverter/ImageInverterExt/ImageInverterViewController.cs +++ b/ios8/ImageInverter/ImageInverterExt/ImageInverterViewController.cs @@ -6,10 +6,8 @@ using MobileCoreServices; using CoreGraphics; -namespace ImageInverterExt -{ - public partial class ImageInverterViewController : UIViewController - { +namespace ImageInverterExt { + public partial class ImageInverterViewController : UIViewController { public ImageInverterViewController (IntPtr handle) : base (handle) { @@ -31,12 +29,12 @@ public override void ViewDidLoad () // Verify that we have a valid NSExtensionItem NSExtensionItem imageItem = ExtensionContext.InputItems [0]; - if(imageItem == null) + if (imageItem == null) return; // Verify that we have a valid NSItemProvider NSItemProvider imageItemProvider = imageItem.Attachments [0]; - if(imageItemProvider == null) + if (imageItemProvider == null) return; // Look for an image inside the NSItemProvider @@ -48,8 +46,8 @@ public override void ViewDidLoad () // This is true when you call extension from Photo's ActivityViewController var url = image as NSUrl; - if(url != null) { - img = UIImage.LoadFromData(NSData.FromUrl(url)); + if (url != null) { + img = UIImage.LoadFromData (NSData.FromUrl (url)); InitWithImage (img); return; } @@ -57,7 +55,7 @@ public override void ViewDidLoad () // This is true when you call extension from Main App img = image as UIImage; if (img != null) { - InitWithImage(img); + InitWithImage (img); return; } }); @@ -68,7 +66,7 @@ void InitWithImage (UIImage image) // Invert the image, enable the Done button InvokeOnMainThread (() => { // Invert the image - UIImage invertedImage = Invert(image); + UIImage invertedImage = Invert (image); // Set the inverted image in the UIImageView ImageView.Image = invertedImage; @@ -76,15 +74,15 @@ void InitWithImage (UIImage image) }); } - static UIImage Invert(UIImage originalImage) + static UIImage Invert (UIImage originalImage) { // Invert the image by applying an affine transformation UIGraphics.BeginImageContext (originalImage.Size); // Apply an affine transformation to the original image to generate a vertically flipped image CGContext context = UIGraphics.GetCurrentContext (); - var affineTransformationInvert = new CGAffineTransform(1, 0, 0, -1, 0, originalImage.Size.Height); - context.ConcatCTM(affineTransformationInvert); + var affineTransformationInvert = new CGAffineTransform (1, 0, 0, -1, 0, originalImage.Size.Height); + context.ConcatCTM (affineTransformationInvert); originalImage.Draw (PointF.Empty); UIImage invertedImage = UIGraphics.GetImageFromCurrentImageContext (); @@ -96,7 +94,7 @@ static UIImage Invert(UIImage originalImage) partial void OnCancelClicked (UIButton sender) { // Cancel the request - ExtensionContext.CancelRequest(new NSError((NSString)"ImageInverterErrorDomain", 0)); + ExtensionContext.CancelRequest (new NSError ((NSString) "ImageInverterErrorDomain", 0)); } partial void OnDoneClicked (UIBarButtonItem sender) @@ -108,7 +106,7 @@ partial void OnDoneClicked (UIBarButtonItem sender) new NSItemProvider (ImageView.Image, UTType.Image) } }; - ExtensionContext.CompleteRequest(new [] { + ExtensionContext.CompleteRequest (new [] { extensionItem }, null); } diff --git a/ios8/IntroToHealthKit/HKWork/AppDelegate.cs b/ios8/IntroToHealthKit/HKWork/AppDelegate.cs index 496606170..c07ed83fb 100644 --- a/ios8/IntroToHealthKit/HKWork/AppDelegate.cs +++ b/ios8/IntroToHealthKit/HKWork/AppDelegate.cs @@ -7,18 +7,16 @@ using HealthKit; -namespace HKWork -{ +namespace HKWork { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { private HKHealthStore healthKitStore = new HKHealthStore (); public override UIWindow Window { get; set; } - + public override void OnActivated (UIApplication application) { ValidateAuthorization (); @@ -33,8 +31,8 @@ private void ValidateAuthorization () //We aren't reading any data for this sample var typesToRead = new NSSet (); healthKitStore.RequestAuthorizationToShare ( - typesToWrite, - typesToRead, + typesToWrite, + typesToRead, ReactToHealthCarePermissions); } diff --git a/ios8/IntroToHealthKit/HKWork/HKWorkViewController.cs b/ios8/IntroToHealthKit/HKWork/HKWorkViewController.cs index 911ea99a3..acfcdf9b9 100644 --- a/ios8/IntroToHealthKit/HKWork/HKWorkViewController.cs +++ b/ios8/IntroToHealthKit/HKWork/HKWorkViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; using HealthKit; -namespace HKWork -{ - public partial class HKWorkViewController : UIViewController - { +namespace HKWork { + public partial class HKWorkViewController : UIViewController { public HKWorkViewController (IntPtr handle) : base (handle) { HeartRateModel.Instance.EnabledChanged += OnEnabledChanged; @@ -20,7 +18,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -62,10 +60,10 @@ partial void StoreData_TouchUpInside (UIButton sender) var s = heartRate.Text; ushort result = 0; if (UInt16.TryParse (s, out result)) { - var quantity = HeartRateModel.Instance.HeartRateInBeatsPerMinute(result); - HeartRateModel.Instance.StoreHeartRate(quantity); + var quantity = HeartRateModel.Instance.HeartRateInBeatsPerMinute (result); + HeartRateModel.Instance.StoreHeartRate (quantity); } - heartRate.ResignFirstResponder(); + heartRate.ResignFirstResponder (); } #endregion diff --git a/ios8/IntroToHealthKit/HKWork/HeartRateModel.cs b/ios8/IntroToHealthKit/HKWork/HeartRateModel.cs index 5cce320d3..4b991d096 100644 --- a/ios8/IntroToHealthKit/HKWork/HeartRateModel.cs +++ b/ios8/IntroToHealthKit/HKWork/HeartRateModel.cs @@ -2,10 +2,8 @@ using HealthKit; using Foundation; -namespace HKWork -{ - public class GenericEventArgs<T> : EventArgs - { +namespace HKWork { + public class GenericEventArgs<T> : EventArgs { public T Value { get; protected set; } public DateTime Time { get; protected set; } @@ -17,10 +15,9 @@ public GenericEventArgs (T value) } } - public delegate void GenericEventHandler<T> (object sender,GenericEventArgs<T> args); + public delegate void GenericEventHandler<T> (object sender, GenericEventArgs<T> args); - public sealed class HeartRateModel : NSObject - { + public sealed class HeartRateModel : NSObject { //Thread-safe singleton: Overkill for the sample app, but proper design private static volatile HeartRateModel singleton; private static object syncRoot = new Object (); @@ -50,7 +47,7 @@ public static HeartRateModel Instance { public event GenericEventHandler<String> ErrorMessageChanged; public event GenericEventHandler<Double> HeartRateStored; - public bool Enabled { + public bool Enabled { get { return enabled; } set { if (enabled != value) { diff --git a/ios8/IntroToHealthKit/HKWork/Main.cs b/ios8/IntroToHealthKit/HKWork/Main.cs index 1d1b2294c..01d9a573e 100644 --- a/ios8/IntroToHealthKit/HKWork/Main.cs +++ b/ios8/IntroToHealthKit/HKWork/Main.cs @@ -5,13 +5,11 @@ using Foundation; using UIKit; -namespace HKWork -{ - public class Application - { +namespace HKWork { + public class Application { //Sample application that stores heart-rate data in Health Kit //Note: Must be used with a Health Kit enabled Provisioning Profile - static void Main (string[] args) + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/ios8/KannadaKeyboard/KannadaKeyboard/KeyboardViewController.cs b/ios8/KannadaKeyboard/KannadaKeyboard/KeyboardViewController.cs index 8c03660a3..6a647484d 100644 --- a/ios8/KannadaKeyboard/KannadaKeyboard/KeyboardViewController.cs +++ b/ios8/KannadaKeyboard/KannadaKeyboard/KeyboardViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; -namespace KannadaKeyboard -{ - public partial class KeyboardViewController : UIInputViewController - { +namespace KannadaKeyboard { + public partial class KeyboardViewController : UIInputViewController { public KeyboardViewController (IntPtr handle) : base (handle) { } @@ -16,17 +14,17 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - var nib = UINib.FromName ("KeyboardView", null); + var nib = UINib.FromName ("KeyboardView", null); var objects = nib.Instantiate (this, null); View = objects [0] as UIView; - Shift.TouchUpInside += ( sender, e) => { + Shift.TouchUpInside += (sender, e) => { UpdateShiftText (!isShiftPressed); UpdateKeyboardLayout (); }; } - void SetKeyTitle (UIView row, string[] titles) + void SetKeyTitle (UIView row, string [] titles) { int i = 0; foreach (UIButton item in row) { @@ -81,9 +79,9 @@ partial void KeyPress (NSObject sender) static void Anumate (UIButton button) { - UIView.Animate (0.2, () => { + UIView.Animate (0.2, () => { button.Transform = CGAffineTransform.Scale (CGAffineTransform.MakeIdentity (), 2f, 2f); - }, () => { + }, () => { button.Transform = CGAffineTransform.Scale (CGAffineTransform.MakeIdentity (), 1f, 1f); }); } @@ -115,15 +113,15 @@ void SetRemainging () bool isShiftPressed; - string[] shiftRow1 = { "#", "್ರ", "ರ್", "ಜ್ಞ", "ತ್ರ", "ಕ್ಷ", "ಶ್ರ", "(", ")", "ಃ", "ಋ" }; - string[] shiftRow2 = { "ಔ", "ಐ", "ಆ", "ಈ", "ಊ", "ಭ", "ಙ", "ಘ", "ಧ", "ಝ", "ಢ" }; - string[] shiftRow3 = { "ಓ", "ಏ", "ಅ", "ಇ", "ಉ", "ಫ", "ಱ", "ಖ", "ಥ", "ಛ", "ಠ" }; - string[] shiftRow4 = { "", "ಎ", "ಣ", "ಞ", "ೢ", "ಳ", "ಶ", "ಷ", "ಒ", "ೣ", "" }; + string [] shiftRow1 = { "#", "್ರ", "ರ್", "ಜ್ಞ", "ತ್ರ", "ಕ್ಷ", "ಶ್ರ", "(", ")", "ಃ", "ಋ" }; + string [] shiftRow2 = { "ಔ", "ಐ", "ಆ", "ಈ", "ಊ", "ಭ", "ಙ", "ಘ", "ಧ", "ಝ", "ಢ" }; + string [] shiftRow3 = { "ಓ", "ಏ", "ಅ", "ಇ", "ಉ", "ಫ", "ಱ", "ಖ", "ಥ", "ಛ", "ಠ" }; + string [] shiftRow4 = { "", "ಎ", "ಣ", "ಞ", "ೢ", "ಳ", "ಶ", "ಷ", "ಒ", "ೣ", "" }; - string[] normalRow1 = { "೧", "೨", "೩", "೪", "೫", "೬", "೭", "೮", "೯", "೦", "-" }; - string[] normalRow2 = { "ೌ", "ೈ", "ಾ", "ೀ", "ೂ", "ಬ", "ಹ", "ಗ", "ದ", "ಜ", "ಡ" }; - string[] normalRow3 = { "ೋ", "ೇ", "್", "ಿ", "ು", "ಪ", "ರ", "ಕ", "ತ", "ಚ", "ಟ" }; - string[] normalRow4 = { "s", "ೆ", "ಂ", "ಮ", "ನ", "ವ", "ಲ", "ಸ", "ಯ", "ೃ", "b" }; + string [] normalRow1 = { "೧", "೨", "೩", "೪", "೫", "೬", "೭", "೮", "೯", "೦", "-" }; + string [] normalRow2 = { "ೌ", "ೈ", "ಾ", "ೀ", "ೂ", "ಬ", "ಹ", "ಗ", "ದ", "ಜ", "ಡ" }; + string [] normalRow3 = { "ೋ", "ೇ", "್", "ಿ", "ು", "ಪ", "ರ", "ಕ", "ತ", "ಚ", "ಟ" }; + string [] normalRow4 = { "s", "ೆ", "ಂ", "ಮ", "ನ", "ವ", "ಲ", "ಸ", "ಯ", "ೃ", "b" }; } diff --git a/ios8/KannadaKeyboard/KannadaKeyboardCompanion/AppDelegate.cs b/ios8/KannadaKeyboard/KannadaKeyboardCompanion/AppDelegate.cs index 1dc4fe8a4..316cfeef9 100644 --- a/ios8/KannadaKeyboard/KannadaKeyboardCompanion/AppDelegate.cs +++ b/ios8/KannadaKeyboard/KannadaKeyboardCompanion/AppDelegate.cs @@ -1,12 +1,10 @@ -using Foundation; +using Foundation; using MonoTouch.Dialog; using UIKit; -namespace KannadaKeyboardCompanion -{ +namespace KannadaKeyboardCompanion { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -22,7 +20,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary new UIViewElement("Instruction", web.View, false) } }; - + var dv = new DialogViewController (root) { Autorotate = true }; @@ -33,7 +31,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary window.RootViewController = navigation; window.MakeKeyAndVisible (); - + return true; } } diff --git a/ios8/KannadaKeyboard/KannadaKeyboardCompanion/Main.cs b/ios8/KannadaKeyboard/KannadaKeyboardCompanion/Main.cs index 6b58f0f7d..9ff74893f 100644 --- a/ios8/KannadaKeyboard/KannadaKeyboardCompanion/Main.cs +++ b/ios8/KannadaKeyboard/KannadaKeyboardCompanion/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace KannadaKeyboardCompanion -{ - public class Application - { +namespace KannadaKeyboardCompanion { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/KannadaKeyboard/KannadaKeyboardCompanion/WebElement.cs b/ios8/KannadaKeyboard/KannadaKeyboardCompanion/WebElement.cs index 5181c546e..4bbc2d26f 100644 --- a/ios8/KannadaKeyboard/KannadaKeyboardCompanion/WebElement.cs +++ b/ios8/KannadaKeyboard/KannadaKeyboardCompanion/WebElement.cs @@ -1,10 +1,8 @@ -using Foundation; +using Foundation; using UIKit; -namespace KannadaKeyboardCompanion -{ - public partial class WebElement : UIViewController - { +namespace KannadaKeyboardCompanion { + public partial class WebElement : UIViewController { public string HtmlFile { get; set; } public WebElement () : base ("WebElement", null) diff --git a/ios8/KeychainTouchID/KeychainTouchID/AppDelegate.cs b/ios8/KeychainTouchID/KeychainTouchID/AppDelegate.cs index 84b468b60..29cd603fb 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/AppDelegate.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace KeychainTouchID -{ +namespace KeychainTouchID { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/ios8/KeychainTouchID/KeychainTouchID/BasicTestViewController.cs b/ios8/KeychainTouchID/KeychainTouchID/BasicTestViewController.cs index 41ffdae08..8c0f2a9f6 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/BasicTestViewController.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/BasicTestViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Collections.Generic; using CoreFoundation; using Foundation; using UIKit; -namespace KeychainTouchID -{ +namespace KeychainTouchID { [Register ("BasicTestViewController")] - public class BasicTestViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource - { + public class BasicTestViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource { public List<Test> Tests { get; set; } public BasicTestViewController (IntPtr handle) : base (handle) @@ -32,7 +30,7 @@ public int NumberOfSections (UITableView tableView) [Export ("tableView:numberOfRowsInSection:")] public nint RowsInSection (UITableView tableview, nint section) { - return (nint)Tests.Count; + return (nint) Tests.Count; } [Export ("tableView:titleForHeaderInSection:")] diff --git a/ios8/KeychainTouchID/KeychainTouchID/KeychainTestsViewController.cs b/ios8/KeychainTouchID/KeychainTouchID/KeychainTestsViewController.cs index 970d861b1..1a58eb48b 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/KeychainTestsViewController.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/KeychainTestsViewController.cs @@ -7,10 +7,8 @@ using UIKit; using System.Text; -namespace KeychainTouchID -{ - public partial class KeychainTestsViewController : BasicTestViewController - { +namespace KeychainTouchID { + public partial class KeychainTestsViewController : BasicTestViewController { public KeychainTestsViewController (IntPtr handle) : base (handle) { } @@ -38,7 +36,7 @@ public override void ViewWillAppear (bool animated) public override void ViewDidLayoutSubviews () { - var height = (nfloat)Math.Min (View.Bounds.Size.Height, tableView.ContentSize.Height); + var height = (nfloat) Math.Min (View.Bounds.Size.Height, tableView.ContentSize.Height); dynamicViewHeight.Constant = height; View.LayoutIfNeeded (); } diff --git a/ios8/KeychainTouchID/KeychainTouchID/LocalAuthenticationTestsViewController.cs b/ios8/KeychainTouchID/KeychainTouchID/LocalAuthenticationTestsViewController.cs index 1aab513b0..0e4f15bb2 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/LocalAuthenticationTestsViewController.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/LocalAuthenticationTestsViewController.cs @@ -4,10 +4,8 @@ using LocalAuthentication; using UIKit; -namespace KeychainTouchID -{ - public partial class LocalAuthenticationTestsViewController : BasicTestViewController - { +namespace KeychainTouchID { + public partial class LocalAuthenticationTestsViewController : BasicTestViewController { public LocalAuthenticationTestsViewController (IntPtr handle) : base (handle) { } @@ -34,7 +32,7 @@ public override void ViewWillAppear (bool animated) public override void ViewDidLayoutSubviews () { - var height = (nfloat)Math.Min (View.Bounds.Size.Height, tableView.ContentSize.Height); + var height = (nfloat) Math.Min (View.Bounds.Size.Height, tableView.ContentSize.Height); dynamicViewHeight.Constant = height; View.LayoutIfNeeded (); } diff --git a/ios8/KeychainTouchID/KeychainTouchID/Main.cs b/ios8/KeychainTouchID/KeychainTouchID/Main.cs index 77dc196df..20d37d865 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/Main.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace KeychainTouchID -{ - public class Application - { +namespace KeychainTouchID { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/KeychainTouchID/KeychainTouchID/SecStatusCodeExtensions.cs b/ios8/KeychainTouchID/KeychainTouchID/SecStatusCodeExtensions.cs index 36e0761db..7d9e56686 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/SecStatusCodeExtensions.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/SecStatusCodeExtensions.cs @@ -1,11 +1,9 @@ -using System; +using System; using Security; -namespace KeychainTouchID -{ - public static class Extensions - { - public static string GetDescription(this SecStatusCode code) +namespace KeychainTouchID { + public static class Extensions { + public static string GetDescription (this SecStatusCode code) { string description = string.Empty; switch (code) { diff --git a/ios8/KeychainTouchID/KeychainTouchID/Test.cs b/ios8/KeychainTouchID/KeychainTouchID/Test.cs index 5bd9ea84b..727c2a445 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/Test.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/Test.cs @@ -3,10 +3,8 @@ using UIKit; using System.Collections.Generic; -namespace KeychainTouchID -{ - public class Test - { +namespace KeychainTouchID { + public class Test { public string Name { get; set; } public string Details { get; set; } diff --git a/ios8/KeychainTouchID/KeychainTouchID/Text.cs b/ios8/KeychainTouchID/KeychainTouchID/Text.cs index 3d5682bc7..ce46a2730 100644 --- a/ios8/KeychainTouchID/KeychainTouchID/Text.cs +++ b/ios8/KeychainTouchID/KeychainTouchID/Text.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace KeychainTouchID -{ - public static class Text - { +namespace KeychainTouchID { + public static class Text { public static string SELECT_TEST = "Select test"; public static string TOUCH_ID_IS_AVAILABLE = "Touch ID is available"; public static string TOUCH_ID_IS_NOT_AVAILABLE = "Touch ID is not available"; diff --git a/ios8/Lister/Common/CheckBoxLayer.cs b/ios8/Lister/Common/CheckBoxLayer.cs index 30eebf7e9..a1eb90863 100644 --- a/ios8/Lister/Common/CheckBoxLayer.cs +++ b/ios8/Lister/Common/CheckBoxLayer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Drawing; @@ -6,11 +6,9 @@ using Foundation; using CoreGraphics; -namespace Common -{ - public class CheckBoxLayer : CALayer - { - static readonly string[] keys = new string[] { +namespace Common { + public class CheckBoxLayer : CALayer { + static readonly string [] keys = new string [] { "tintColor", "checked", "strokeFactor", @@ -18,21 +16,21 @@ public class CheckBoxLayer : CALayer "markInsetFactor" }; - static readonly nfloat[] components = new nfloat[] { + static readonly nfloat [] components = new nfloat [] { 0.5f, 0.5f, 0.5f }; - [Outlet("strokeFactor")] + [Outlet ("strokeFactor")] public float StrokeFactor { get; set; } - [Outlet("insetFactor")] + [Outlet ("insetFactor")] public float InsetFactor { get; set; } - [Outlet("markInsetFactor")] + [Outlet ("markInsetFactor")] public float MarkInsetFactor { get; set; } CGColor tintColor; - [Outlet("tintColor")] + [Outlet ("tintColor")] public CGColor TintColor { get { return tintColor; @@ -44,7 +42,7 @@ public CGColor TintColor { } bool isChecked; - [Outlet("checked")] + [Outlet ("checked")] public bool Checked { get { return isChecked; @@ -86,7 +84,7 @@ public override void DrawInContext (CGContext context) // Create the outer border for the check box. nfloat outerDimension = size - 2 * checkBoxInset; - var checkBoxRect = new CGRect(checkBoxInset, checkBoxInset, outerDimension, outerDimension); + var checkBoxRect = new CGRect (checkBoxInset, checkBoxInset, outerDimension, outerDimension); checkBoxRect = transform.TransformRect (checkBoxRect); // Make the desired width of the outer box. @@ -103,7 +101,7 @@ public override void DrawInContext (CGContext context) nfloat markInset = MarkInsetFactor * size; nfloat markDimension = size - 2 * markInset; - var markRect = new CGRect(markInset, markInset, markDimension, markDimension); + var markRect = new CGRect (markInset, markInset, markDimension, markDimension); markRect = transform.TransformRect (markRect); context.SetFillColor (TintColor); @@ -112,7 +110,7 @@ public override void DrawInContext (CGContext context) } [Export ("needsDisplayForKey:")] - public new static bool NeedsDisplayForKey(string key) + public new static bool NeedsDisplayForKey (string key) { if (keys.Contains (key)) return true; diff --git a/ios8/Lister/Common/Colors/AppColors.cs b/ios8/Lister/Common/Colors/AppColors.cs index fbc7090cb..f206df15d 100644 --- a/ios8/Lister/Common/Colors/AppColors.cs +++ b/ios8/Lister/Common/Colors/AppColors.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace Common -{ - public static class AppColors - { +namespace Common { + public static class AppColors { public static readonly UIColor GrayColor = UIColor.DarkGray; public static readonly UIColor BlueColor = UIColor.FromRGBA (0.42f, 0.7f, 0.88f, 1); public static readonly UIColor BreenColor = UIColor.FromRGBA (0.71f, 0.84f, 0.31f, 1); @@ -12,29 +10,29 @@ public static class AppColors public static readonly UIColor OrangeColor = UIColor.FromRGBA (0.96f, 0.63f, 0.20f, 1); public static readonly UIColor RedColor = UIColor.FromRGBA (0.96f, 0.42f, 0.42f, 1); - public static UIColor ColorFrom(ListColor colorType) + public static UIColor ColorFrom (ListColor colorType) { switch (colorType) { - case ListColor.Gray: - return GrayColor; + case ListColor.Gray: + return GrayColor; - case ListColor.Blue: - return BlueColor; + case ListColor.Blue: + return BlueColor; - case ListColor.Green: - return BreenColor; + case ListColor.Green: + return BreenColor; - case ListColor.Yellow: - return YellowColor; + case ListColor.Yellow: + return YellowColor; - case ListColor.Orange: - return OrangeColor; + case ListColor.Orange: + return OrangeColor; - case ListColor.Red: - return RedColor; + case ListColor.Red: + return RedColor; - default: - throw new NotImplementedException (); + default: + throw new NotImplementedException (); } } } diff --git a/ios8/Lister/Common/Colors/ListColor.cs b/ios8/Lister/Common/Colors/ListColor.cs index 22592c9bf..38413891e 100644 --- a/ios8/Lister/Common/Colors/ListColor.cs +++ b/ios8/Lister/Common/Colors/ListColor.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace Common -{ - public enum ListColor - { +namespace Common { + public enum ListColor { Gray = 0, Blue, Green, diff --git a/ios8/Lister/Common/Configuration/AppConfig.cs b/ios8/Lister/Common/Configuration/AppConfig.cs index d46f0c0b4..b3f3461b6 100644 --- a/ios8/Lister/Common/Configuration/AppConfig.cs +++ b/ios8/Lister/Common/Configuration/AppConfig.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.IO; using Foundation; using System.Linq; -namespace Common -{ - public class AppConfig : NSObject - { +namespace Common { + public class AppConfig : NSObject { const string FirstLaunchUserDefaultsKey = "FirstLaunchUserDefaultsKey"; const string StorageOptionUserDefaultsKey = "StorageOptionUserDefaultsKey"; const string StoredUbiquityIdentityTokenKey = "UbiquityIdentityTokenKey"; @@ -16,7 +14,7 @@ public class AppConfig : NSObject public event EventHandler StorageOptionChanged; - static readonly AppConfig sharedAppConfiguration = new AppConfig(); + static readonly AppConfig sharedAppConfiguration = new AppConfig (); public static AppConfig SharedAppConfiguration { get { return sharedAppConfiguration; @@ -27,14 +25,14 @@ public static AppConfig SharedAppConfiguration { public StorageType StorageOption { get { if (!storageOption.HasValue) - storageOption = (StorageType)(int)NSUserDefaults.StandardUserDefaults.IntForKey (StorageOptionUserDefaultsKey); + storageOption = (StorageType) (int) NSUserDefaults.StandardUserDefaults.IntForKey (StorageOptionUserDefaultsKey); return storageOption.Value; } set { if (!storageOption.HasValue || value != storageOption.Value) { storageOption = value; - NSUserDefaults.StandardUserDefaults.SetInt ((int)value, StorageOptionUserDefaultsKey); + NSUserDefaults.StandardUserDefaults.SetInt ((int) value, StorageOptionUserDefaultsKey); var handler = StorageOptionChanged; if (handler != null) @@ -54,7 +52,7 @@ public StorageState StorageState { get { return new StorageState { StorageOption = StorageOption, - AccountDidChange = HasUbiquityIdentityChanged(), + AccountDidChange = HasUbiquityIdentityChanged (), CloudAvailable = IsCloudAvailable }; } @@ -78,7 +76,7 @@ public string DefaultListerDraftName { } } - public void RunHandlerOnFirstLaunch(Action firstLaunchHandler) + public void RunHandlerOnFirstLaunch (Action firstLaunchHandler) { NSUserDefaults defaults = NSUserDefaults.StandardUserDefaults; @@ -87,15 +85,15 @@ public void RunHandlerOnFirstLaunch(Action firstLaunchHandler) { (NSString)StorageOptionUserDefaultsKey, NSObject.FromObject(StorageType.NotSet) } }); - if (defaults.BoolForKey(FirstLaunchUserDefaultsKey)) { + if (defaults.BoolForKey (FirstLaunchUserDefaultsKey)) { defaults.SetBool (false, FirstLaunchUserDefaultsKey); - firstLaunchHandler(); + firstLaunchHandler (); } } #region Identity - bool HasUbiquityIdentityChanged() + bool HasUbiquityIdentityChanged () { if (StorageOption != StorageType.Cloud) return false; @@ -107,7 +105,7 @@ bool HasUbiquityIdentityChanged() bool currentTokenNullStoredNonNull = currentToken == null && storedToken != null; bool storedTokenNullCurrentNonNull = storedToken == null && currentToken != null; bool currentNotEqualStored = currentToken != null && storedToken != null - && !currentToken.Equals (storedToken); + && !currentToken.Equals (storedToken); if (currentTokenNullStoredNonNull || storedTokenNullCurrentNonNull || currentNotEqualStored) { StoreUbiquityIdentityToken (); @@ -117,7 +115,7 @@ bool HasUbiquityIdentityChanged() return hasChanged; } - public void StoreUbiquityIdentityToken() + public void StoreUbiquityIdentityToken () { NSUserDefaults defaults = NSUserDefaults.StandardUserDefaults; var token = NSFileManager.DefaultManager.UbiquityIdentityToken; @@ -134,12 +132,12 @@ public void StoreUbiquityIdentityToken() defaults.Synchronize (); } - NSObject FetchStoredUbiquityIdentityToken() + NSObject FetchStoredUbiquityIdentityToken () { NSObject storedToken = null; // Determine if the iCloud account associated with this device has changed since the last time the user launched the app. - var tokenArchive = (NSData)NSUserDefaults.StandardUserDefaults[StoredUbiquityIdentityTokenKey]; + var tokenArchive = (NSData) NSUserDefaults.StandardUserDefaults [StoredUbiquityIdentityTokenKey]; if (tokenArchive != null) storedToken = NSKeyedUnarchiver.UnarchiveObject (tokenArchive); diff --git a/ios8/Lister/Common/Configuration/StorageState.cs b/ios8/Lister/Common/Configuration/StorageState.cs index 5fb67635b..9a01e00a1 100644 --- a/ios8/Lister/Common/Configuration/StorageState.cs +++ b/ios8/Lister/Common/Configuration/StorageState.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace Common -{ - public struct StorageState - { +namespace Common { + public struct StorageState { public StorageType StorageOption { get; set; } public bool AccountDidChange { get; set; } public bool CloudAvailable { get; set; } diff --git a/ios8/Lister/Common/Configuration/StorageType.cs b/ios8/Lister/Common/Configuration/StorageType.cs index 5a76d79b0..0c65a958a 100644 --- a/ios8/Lister/Common/Configuration/StorageType.cs +++ b/ios8/Lister/Common/Configuration/StorageType.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace Common -{ - public enum StorageType - { +namespace Common { + public enum StorageType { NotSet = 0, Cloud, Local diff --git a/ios8/Lister/Common/List.cs b/ios8/Lister/Common/List.cs index 851e5c694..9a18d2216 100644 --- a/ios8/Lister/Common/List.cs +++ b/ios8/Lister/Common/List.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using UIKit; using Foundation; -namespace Common -{ - [Register("List")] - public class List : NSObject, ICloneable, INSCoding - { +namespace Common { + [Register ("List")] + public class List : NSObject, ICloneable, INSCoding { const string ListEncodingItemsKey = "items"; const string ListEncodingColorKey = "color"; @@ -28,7 +26,7 @@ public int Count { } } - public ListItem this[int index] { + public ListItem this [int index] { get { return items [index]; } @@ -39,40 +37,40 @@ public List () items = new List<ListItem> (); } - public List(IEnumerable<ListItem> items, ListColor color) - : this() + public List (IEnumerable<ListItem> items, ListColor color) + : this () { this.items.AddRange (items); Color = color; } - [Export("initWithCoder:")] - public List(NSCoder coder) - : this() + [Export ("initWithCoder:")] + public List (NSCoder coder) + : this () { - NSArray array = (NSArray)coder.DecodeObject (ListEncodingItemsKey); + NSArray array = (NSArray) coder.DecodeObject (ListEncodingItemsKey); for (nuint i = 0; i < array.Count; i++) items.Add (array.GetItem<ListItem> (i)); - Color = (ListColor)coder.DecodeInt (ListEncodingColorKey); + Color = (ListColor) coder.DecodeInt (ListEncodingColorKey); } [Export ("encodeWithCoder:")] public void EncodeTo (NSCoder coder) { - NSArray array = NSArray.FromNSObjects (items.ToArray()); + NSArray array = NSArray.FromNSObjects (items.ToArray ()); coder.Encode (array, ListEncodingItemsKey); - coder.Encode((int)Color, ListEncodingColorKey); + coder.Encode ((int) Color, ListEncodingColorKey); } - public int IndexOfItem(ListItem item) + public int IndexOfItem (ListItem item) { return items.IndexOf (item); } /// Use this function to ensure that all inserted items are complete. /// All inserted items must be incomplete when inserted. - public bool CanInsertIncompleteItems(IEnumerable<ListItem> incompleteItems, int index) + public bool CanInsertIncompleteItems (IEnumerable<ListItem> incompleteItems, int index) { bool anyCompleteItem = incompleteItems.Any (item => item.IsComplete); @@ -86,7 +84,7 @@ public bool CanInsertIncompleteItems(IEnumerable<ListItem> incompleteItems, int /// e.g. if items are [complete(0), incomplete(1), incomplete(2), completed(3)], they will be inserted /// into to sections of the items array. [incomplete(1), incomplete(2)] will be inserted at index 0 of the /// list. [complete(0), completed(3)] will be inserted at the index of the list. - public NSIndexSet InsertItems(IEnumerable<ListItem> items) + public NSIndexSet InsertItems (IEnumerable<ListItem> items) { int initialCount = Count; @@ -110,12 +108,12 @@ public NSIndexSet InsertItems(IEnumerable<ListItem> items) return insertedIndexes; } - public void InsertItem(ListItem item, int index) + public void InsertItem (ListItem item, int index) { items.Insert (index, item); } - public int InsertItem(ListItem item) + public int InsertItem (ListItem item) { if (item.IsComplete) { items.Add (item); @@ -126,7 +124,7 @@ public int InsertItem(ListItem item) } } - public bool CanMoveItem(ListItem item, int index, bool inclusive) + public bool CanMoveItem (ListItem item, int index, bool inclusive) { int fromIndex = items.IndexOf (item); @@ -141,7 +139,7 @@ public bool CanMoveItem(ListItem item, int index, bool inclusive) return index >= 0 && index < IndexOfFirstCompletedItem (); } - public ListOperationInfo MoveItem(ListItem item, int toIndex) + public ListOperationInfo MoveItem (ListItem item, int toIndex) { int fromIndex = items.IndexOf (item); @@ -165,14 +163,14 @@ public ListOperationInfo MoveItem(ListItem item, int toIndex) return moveInfo; } - public void RemoveItems(IEnumerable<ListItem> items) + public void RemoveItems (IEnumerable<ListItem> items) { foreach (var item in items) this.items.Remove (item); } // Toggles an item's completion state and moves the item to the appropriate index. The normalized from/to indexes are returned in the ListOperationInfo struct. - public ListOperationInfo ToggleItem(ListItem item, int preferredDestinationIndex) + public ListOperationInfo ToggleItem (ListItem item, int preferredDestinationIndex) { int fromIndex = items.IndexOf (item); @@ -186,7 +184,7 @@ public ListOperationInfo ToggleItem(ListItem item, int preferredDestinationIndex int toIndex = preferredDestinationIndex; if (toIndex == -1) - toIndex = item.IsComplete ? Count : IndexOfFirstCompletedItem(); + toIndex = item.IsComplete ? Count : IndexOfFirstCompletedItem (); items.Insert (toIndex, item); @@ -199,19 +197,19 @@ public ListOperationInfo ToggleItem(ListItem item, int preferredDestinationIndex } // Set all of the items to be a specific completion state. - public void UpdateAllItemsToCompletionState(bool completeStatus) + public void UpdateAllItemsToCompletionState (bool completeStatus) { foreach (ListItem item in items) item.IsComplete = completeStatus; } - public int IndexOfFirstCompletedItem() + public int IndexOfFirstCompletedItem () { int index = items.FindIndex (item => item.IsComplete); return index == -1 ? items.Count : index; } - public ListItem[] CopyAllItems() + public ListItem [] CopyAllItems () { return items.ToArray (); } diff --git a/ios8/Lister/Common/ListItem.cs b/ios8/Lister/Common/ListItem.cs index 3803bbddb..f0cf6fa99 100644 --- a/ios8/Lister/Common/ListItem.cs +++ b/ios8/Lister/Common/ListItem.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; -namespace Common -{ - [Register("ListItem")] - public class ListItem: NSObject, ICloneable, INSCoding - { +namespace Common { + [Register ("ListItem")] + public class ListItem : NSObject, ICloneable, INSCoding { const string ListItemEncodingTextKey = "text"; const string ListItemEncodingCompletedKey = "completed"; const string ListItemEncodingUUIDKey = "uuid"; @@ -22,29 +20,29 @@ public ListItem (string text, bool isComplete, Guid uid) UID = uid; } - public ListItem(string text) - : this(text, false, Guid.NewGuid()) + public ListItem (string text) + : this (text, false, Guid.NewGuid ()) { } - [Export("initWithCoder:")] - public ListItem(NSCoder coder) + [Export ("initWithCoder:")] + public ListItem (NSCoder coder) { - Text = (string)(NSString)coder.DecodeObject (ListItemEncodingTextKey); - NSUuid uid = (NSUuid)coder.DecodeObject (ListItemEncodingUUIDKey); - UID = new Guid (uid.GetBytes()); + Text = (string) (NSString) coder.DecodeObject (ListItemEncodingTextKey); + NSUuid uid = (NSUuid) coder.DecodeObject (ListItemEncodingUUIDKey); + UID = new Guid (uid.GetBytes ()); IsComplete = coder.DecodeBool (ListItemEncodingCompletedKey); } [Export ("encodeWithCoder:")] public void EncodeTo (NSCoder coder) { - coder.Encode ((NSString)Text, ListItemEncodingTextKey); - coder.Encode (new NSUuid(UID.ToByteArray ()), ListItemEncodingUUIDKey); + coder.Encode ((NSString) Text, ListItemEncodingTextKey); + coder.Encode (new NSUuid (UID.ToByteArray ()), ListItemEncodingUUIDKey); coder.Encode (IsComplete, ListItemEncodingCompletedKey); } - public void RefreshIdentity() + public void RefreshIdentity () { UID = Guid.Empty; } diff --git a/ios8/Lister/Common/ListOperationInfo.cs b/ios8/Lister/Common/ListOperationInfo.cs index 89040d5fb..bf4f8c25b 100644 --- a/ios8/Lister/Common/ListOperationInfo.cs +++ b/ios8/Lister/Common/ListOperationInfo.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace Common -{ - public struct ListOperationInfo - { +namespace Common { + public struct ListOperationInfo { public int FromIndex { get; set; } public int ToIndex { get; set; } } diff --git a/ios8/Lister/Common/Properties/AssemblyInfo.cs b/ios8/Lister/Common/Properties/AssemblyInfo.cs index 456fb09d5..79fc8286b 100644 --- a/ios8/Lister/Common/Properties/AssemblyInfo.cs +++ b/ios8/Lister/Common/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/ios8/Lister/Common/Utils/ComparisionComparer.cs b/ios8/Lister/Common/Utils/ComparisionComparer.cs index d563e194e..4a44b0329 100644 --- a/ios8/Lister/Common/Utils/ComparisionComparer.cs +++ b/ios8/Lister/Common/Utils/ComparisionComparer.cs @@ -1,10 +1,8 @@ -using System; +using System; using System.Collections.Generic; -namespace Common -{ - public class ComparisionComparer<T> : Comparer<T> - { +namespace Common { + public class ComparisionComparer<T> : Comparer<T> { readonly Comparison<T> comparision; public ComparisionComparer (Comparison<T> comparision) diff --git a/ios8/Lister/Lister/AppDelegate.cs b/ios8/Lister/Lister/AppDelegate.cs index 356912241..c4a54a03f 100644 --- a/ios8/Lister/Lister/AppDelegate.cs +++ b/ios8/Lister/Lister/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -8,11 +8,9 @@ using Common; using ListerKit; -namespace Lister -{ +namespace Lister { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate - { + public partial class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate { const string MainStoryboardName = "Main"; const string MainStoryboardEmptyViewControllerIdentifier = "emptyViewController"; @@ -20,13 +18,13 @@ public partial class AppDelegate : UIApplicationDelegate, IUISplitViewController UISplitViewController SplitViewController { get { - return (UISplitViewController)Window.RootViewController; + return (UISplitViewController) Window.RootViewController; } } UINavigationController PrimaryViewController { get { - return (UINavigationController)SplitViewController.ViewControllers [0]; + return (UINavigationController) SplitViewController.ViewControllers [0]; } } @@ -35,11 +33,11 @@ public override bool FinishedLaunching (UIApplication app, NSDictionary options) Console.WriteLine (IntPtr.Size); Console.WriteLine ("FinishedLaunching"); - AppConfig.SharedAppConfiguration.RunHandlerOnFirstLaunch(()=> { - ListCoordinator.SharedListCoordinator.CopyInitialDocuments(); + AppConfig.SharedAppConfiguration.RunHandlerOnFirstLaunch (() => { + ListCoordinator.SharedListCoordinator.CopyInitialDocuments (); }); - var splitViewController = (UISplitViewController)Window.RootViewController; + var splitViewController = (UISplitViewController) Window.RootViewController; splitViewController.PreferredDisplayMode = UISplitViewControllerDisplayMode.AllVisible; splitViewController.WeakDelegate = this; @@ -76,10 +74,10 @@ public bool CollapseSecondViewController (UISplitViewController splitViewControl [Export ("splitViewController:separateSecondaryViewControllerFromPrimaryViewController:")] public UIViewController SeparateSecondaryViewController (UISplitViewController splitViewController, UIViewController primaryViewController) { - if (PrimaryViewController.TopViewController == PrimaryViewController.ViewControllers[0]) { + if (PrimaryViewController.TopViewController == PrimaryViewController.ViewControllers [0]) { // If no list is on the stack, fill the detail area with an empty controller. UIStoryboard storyboard = UIStoryboard.FromName (MainStoryboardName, null); - UIViewController emptyViewController = (UIViewController)storyboard.InstantiateViewController (MainStoryboardEmptyViewControllerIdentifier); + UIViewController emptyViewController = (UIViewController) storyboard.InstantiateViewController (MainStoryboardEmptyViewControllerIdentifier); return emptyViewController; } diff --git a/ios8/Lister/Lister/Main.cs b/ios8/Lister/Lister/Main.cs index ae6f86a9d..be4d40c40 100644 --- a/ios8/Lister/Lister/Main.cs +++ b/ios8/Lister/Lister/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace Lister -{ - public class Application - { +namespace Lister { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/Lister/Lister/Model/IListInfoProvider.cs b/ios8/Lister/Lister/Model/IListInfoProvider.cs index 423a1c1c3..38e4d18ea 100644 --- a/ios8/Lister/Lister/Model/IListInfoProvider.cs +++ b/ios8/Lister/Lister/Model/IListInfoProvider.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; -namespace Lister -{ - public interface IListInfoProvider - { +namespace Lister { + public interface IListInfoProvider { NSUrl Url { get; set; } } } diff --git a/ios8/Lister/Lister/Model/ListInfo.cs b/ios8/Lister/Lister/Model/ListInfo.cs index 33ad99200..0277958ad 100644 --- a/ios8/Lister/Lister/Model/ListInfo.cs +++ b/ios8/Lister/Lister/Model/ListInfo.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -7,10 +7,8 @@ using ListerKit; using System.Threading.Tasks; -namespace Lister -{ - public class ListInfo : IEquatable<ListInfo> - { +namespace Lister { + public class ListInfo : IEquatable<ListInfo> { public ListColor? Color { get; set; } public NSUrl Url { get; private set; } @@ -23,13 +21,13 @@ public bool IsLoaded { } } - public ListInfo(NSUrl url) + public ListInfo (NSUrl url) { Url = url; Name = string.Empty; } - public Task FetchInfoAsync() + public Task FetchInfoAsync () { var tcs = new TaskCompletionSource<object> (); @@ -41,7 +39,7 @@ public Task FetchInfoAsync() return tcs.Task; } - async void FetchInfo(TaskCompletionSource<object> tcs) + async void FetchInfo (TaskCompletionSource<object> tcs) { ListDocument document = new ListDocument (Url); @@ -51,13 +49,13 @@ async void FetchInfo(TaskCompletionSource<object> tcs) Name = document.LocalizedName; tcs.SetResult (null); - document.Close(null); + document.Close (null); } else { tcs.SetException (new InvalidOperationException ("Your attempt to open the document failed.")); } } - public void CreateAndSaveWithCompletionHandler(UIOperationHandler completionHandler) + public void CreateAndSaveWithCompletionHandler (UIOperationHandler completionHandler) { List list = new List (); list.Color = Color.Value; @@ -75,8 +73,8 @@ public override bool Equals (object obj) if (obj == null || GetType () != obj.GetType ()) return false; - ListInfo listInfo = (ListInfo)obj; - return (Url == null && listInfo.Url == null) || Url.Equals(listInfo.Url); + ListInfo listInfo = (ListInfo) obj; + return (Url == null && listInfo.Url == null) || Url.Equals (listInfo.Url); } public bool Equals (ListInfo other) @@ -84,7 +82,7 @@ public bool Equals (ListInfo other) if (other == null || GetType () != other.GetType ()) return false; - return (Url == null && other.Url == null) || Url.Equals(other.Url); + return (Url == null && other.Url == null) || Url.Equals (other.Url); } public override int GetHashCode () diff --git a/ios8/Lister/Lister/ViewControllers/DocumentsViewController.cs b/ios8/Lister/Lister/ViewControllers/DocumentsViewController.cs index 07ceadd57..671b2dde6 100644 --- a/ios8/Lister/Lister/ViewControllers/DocumentsViewController.cs +++ b/ios8/Lister/Lister/ViewControllers/DocumentsViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Collections.Generic; using System.Threading; @@ -9,11 +9,9 @@ using Common; using ListerKit; -namespace Lister -{ - [Register("DocumentsViewController")] - public class DocumentsViewController : UITableViewController - { +namespace Lister { + [Register ("DocumentsViewController")] + public class DocumentsViewController : UITableViewController { // User defaults keys. const string StorageOptionUserDefaultsKey = "StorageOptionKey"; const string StorageOptionUserDefaultsLocal = "StorageOptionLocal"; @@ -22,15 +20,15 @@ public class DocumentsViewController : UITableViewController // Segue identifiers. const string ListDocumentSegueIdentifier = "showListDocument"; const string NewListDocumentSegueIdentifier = "newListDocument"; - readonly NSString ListDocumentCellIdentifier = new NSString("listDocumentCell"); + readonly NSString ListDocumentCellIdentifier = new NSString ("listDocumentCell"); NSObject sizeChangedToken, finishGatheringToken, updateToken; - List<ListInfo> listInfos = new List<ListInfo>(); + List<ListInfo> listInfos = new List<ListInfo> (); NSMetadataQuery documentMetadataQuery; - public DocumentsViewController(IntPtr handle) - : base(handle) + public DocumentsViewController (IntPtr handle) + : base (handle) { } @@ -57,9 +55,9 @@ public override void ViewWillAppear (bool animated) SetupTextAttributes (); - NavigationController.NavigationBar.TintColor = AppColors.ColorFrom(ListColor.Gray); - NavigationController.Toolbar.TintColor = AppColors.ColorFrom(ListColor.Gray); - TableView.TintColor = AppColors.ColorFrom(ListColor.Gray); + NavigationController.NavigationBar.TintColor = AppColors.ColorFrom (ListColor.Gray); + NavigationController.Toolbar.TintColor = AppColors.ColorFrom (ListColor.Gray); + TableView.TintColor = AppColors.ColorFrom (ListColor.Gray); } public override void ViewDidAppear (bool animated) @@ -89,24 +87,24 @@ protected override void Dispose (bool disposing) #region Setup - void SelectListWithListInfo(ListInfo listInfo) + void SelectListWithListInfo (ListInfo listInfo) { UISplitViewController splitViewController = SplitViewController; Action<ListViewController> ConfigureListViewController = listViewController => { - listViewController.ConfigureWith(listInfo); + listViewController.ConfigureWith (listInfo); listViewController.MasterController = this; }; if (splitViewController.Collapsed) { - ListViewController listViewController = (ListViewController)Storyboard.InstantiateViewController ("listViewController"); - ConfigureListViewController(listViewController); + ListViewController listViewController = (ListViewController) Storyboard.InstantiateViewController ("listViewController"); + ConfigureListViewController (listViewController); ShowViewController (listViewController, this); } else { - UINavigationController navigationController = (UINavigationController)Storyboard.InstantiateViewController ("listViewNavigationController"); - ListViewController listViewController = (ListViewController)navigationController.TopViewController; - ConfigureListViewController(listViewController); - SplitViewController.ViewControllers = new UIViewController[] { + UINavigationController navigationController = (UINavigationController) Storyboard.InstantiateViewController ("listViewNavigationController"); + ListViewController listViewController = (ListViewController) navigationController.TopViewController; + ConfigureListViewController (listViewController); + SplitViewController.ViewControllers = new UIViewController [] { SplitViewController.ViewControllers [0], new UIViewController () }; @@ -114,7 +112,7 @@ void SelectListWithListInfo(ListInfo listInfo) } } - void SetupUserStoragePreferences() + void SetupUserStoragePreferences () { StorageState storageState = AppConfig.SharedAppConfiguration.StorageState; @@ -142,14 +140,14 @@ public override nint RowsInSection (UITableView tableview, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { ListInfo listInfo = listInfos [indexPath.Row]; - ListCell cell = (ListCell)tableView.DequeueReusableCell(ListDocumentCellIdentifier, indexPath); + ListCell cell = (ListCell) tableView.DequeueReusableCell (ListDocumentCellIdentifier, indexPath); Configure (cell, listInfo); return cell; } - async void Configure(ListCell cell, ListInfo listInfo) + async void Configure (ListCell cell, ListInfo listInfo) { // Show an empty string as the text since it may need to load. cell.Label.Text = string.Empty; @@ -169,7 +167,7 @@ async void Configure(ListCell cell, ListInfo listInfo) public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - ListInfo listInfo = listInfos[indexPath.Row]; + ListInfo listInfo = listInfos [indexPath.Row]; SelectListWithListInfo (listInfo); } @@ -199,16 +197,16 @@ public void ListViewControllerDidDeleteList (ListViewController listViewControll public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == NewListDocumentSegueIdentifier) { - var newListController = (NewDocumentController)segue.DestinationViewController; + var newListController = (NewDocumentController) segue.DestinationViewController; newListController.MasterController = this; } } public void OnNewListInfo (ListInfo listInfo) { - InsertListInfo(listInfo, index => { - NSIndexPath indexPathForInsertedRow = NSIndexPath.FromRowSection(index, 0); - TableView.InsertRows(new NSIndexPath[] {indexPathForInsertedRow }, UITableViewRowAnimation.Automatic); + InsertListInfo (listInfo, index => { + NSIndexPath indexPathForInsertedRow = NSIndexPath.FromRowSection (index, 0); + TableView.InsertRows (new NSIndexPath [] { indexPathForInsertedRow }, UITableViewRowAnimation.Automatic); }); } @@ -216,17 +214,17 @@ public void OnNewListInfo (ListInfo listInfo) #region Convenience - void DeleteListAtUrl(NSUrl url) + void DeleteListAtUrl (NSUrl url) { // Asynchonously delete the document. - ThreadPool.QueueUserWorkItem(_=> { - ListCoordinator.SharedListCoordinator.DeleteFileAtURL(url); + ThreadPool.QueueUserWorkItem (_ => { + ListCoordinator.SharedListCoordinator.DeleteFileAtURL (url); }); // Update the document list and remove the row from the table view. RemoveListInfo (url, index => { - NSIndexPath indexPathForRemoval = NSIndexPath.FromRowSection(index, 0); - TableView.DeleteRows(new NSIndexPath[] { indexPathForRemoval }, UITableViewRowAnimation.Automatic); + NSIndexPath indexPathForRemoval = NSIndexPath.FromRowSection (index, 0); + TableView.DeleteRows (new NSIndexPath [] { indexPathForRemoval }, UITableViewRowAnimation.Automatic); }); } @@ -234,9 +232,9 @@ void DeleteListAtUrl(NSUrl url) #region List Management - void StartQuery() + void StartQuery () { - if(documentMetadataQuery != null) + if (documentMetadataQuery != null) documentMetadataQuery.StopQuery (); if (AppConfig.SharedAppConfiguration.StorageOption == StorageType.Cloud) @@ -245,7 +243,7 @@ void StartQuery() StartLocalQuery (); } - void StartLocalQuery() + void StartLocalQuery () { NSUrl docDir = ListCoordinator.SharedListCoordinator.DocumentsDirectory; @@ -253,23 +251,23 @@ void StartLocalQuery() // Fetch the list documents from container documents directory. NSError error; - NSUrl[] localDocuments = defaultManager.GetDirectoryContent (docDir, null, - NSDirectoryEnumerationOptions.SkipsPackageDescendants, out error); + NSUrl [] localDocuments = defaultManager.GetDirectoryContent (docDir, null, + NSDirectoryEnumerationOptions.SkipsPackageDescendants, out error); ProcessURLs (localDocuments); } - void ProcessURLs(NSUrl[] results) + void ProcessURLs (NSUrl [] results) { listInfos.Clear (); Array.Sort (results, (lhs, rhs) => { - return lhs.LastPathComponent.CompareTo(rhs.LastPathComponent); + return lhs.LastPathComponent.CompareTo (rhs.LastPathComponent); }); foreach (NSUrl url in results) { string ext = Path.GetExtension (url.AbsoluteString); - ext = ext.Remove(0, 1); // remove lead dot ".list" become "list" + ext = ext.Remove (0, 1); // remove lead dot ".list" become "list" if (ext == AppConfig.ListerFileExtension) InsertListInfoWithProvider (url, null); } @@ -277,18 +275,18 @@ void ProcessURLs(NSUrl[] results) TableView.ReloadData (); } - void ProcessMetadataItems() + void ProcessMetadataItems () { listInfos.Clear (); - NSMetadataItem[] results = documentMetadataQuery.Results; + NSMetadataItem [] results = documentMetadataQuery.Results; // This is debug output, just to show when ProcessMetadataItems is called foreach (var item in results) PrintMetadataItem (item); Array.Sort (results, (left, right) => { - string lName = (string)(NSString)left.ValueForAttribute (NSMetadataQuery.ItemFSNameKey); - string rName = (string)(NSString)right.ValueForAttribute (NSMetadataQuery.ItemFSNameKey); + string lName = (string) (NSString) left.ValueForAttribute (NSMetadataQuery.ItemFSNameKey); + string rName = (string) (NSString) right.ValueForAttribute (NSMetadataQuery.ItemFSNameKey); return lName.CompareTo (rName); }); @@ -296,13 +294,13 @@ void ProcessMetadataItems() InsertListInfoWithProvider (item, null); listInfos.Sort ((left, right) => { - return left.Url.LastPathComponent.CompareTo(right.Url.LastPathComponent); + return left.Url.LastPathComponent.CompareTo (right.Url.LastPathComponent); }); TableView.ReloadData (); } - void PrintMetadataItem(NSMetadataItem item) + void PrintMetadataItem (NSMetadataItem item) { Console.WriteLine ("path={0}, display={1}, url={2}, name={3}, downloaded={4}, downloading={5}, uploaded={6}, uploading={7}, createData={8}, updateDate={9},", item.Path, item.DisplayName, item.Url, item.FileSystemName, item.UbiquitousItemIsUploaded, @@ -310,16 +308,16 @@ void PrintMetadataItem(NSMetadataItem item) item.FileSystemCreationDate, item.FileSystemContentChangeDate); } - void StartMetadataQuery() + void StartMetadataQuery () { if (documentMetadataQuery == null) { NSMetadataQuery metadataQuery = new NSMetadataQuery { - SearchScopes = new NSObject[] { + SearchScopes = new NSObject [] { NSMetadataQuery.UbiquitousDocumentsScope }, Predicate = NSPredicate.FromFormat ("(%K.pathExtension = %@)", NSMetadataQuery.ItemFSNameKey, - (NSString)AppConfig.ListerFileExtension) + (NSString) AppConfig.ListerFileExtension) }; documentMetadataQuery = metadataQuery; @@ -334,35 +332,35 @@ void StartMetadataQuery() documentMetadataQuery.StartQuery (); } - void HandleMetadataQueryUpdates(NSNotification notification) + void HandleMetadataQueryUpdates (NSNotification notification) { documentMetadataQuery.DisableUpdates (); ProcessMetadataItems (); documentMetadataQuery.EnableUpdates (); } - void InsertListInfo(ListInfo listInfo, Action<int> completionHandler) + void InsertListInfo (ListInfo listInfo, Action<int> completionHandler) { - ComparisionComparer<ListInfo> comparer = new ComparisionComparer<ListInfo>((left, right) => { - return left.Name.CompareTo(right.Name); + ComparisionComparer<ListInfo> comparer = new ComparisionComparer<ListInfo> ((left, right) => { + return left.Name.CompareTo (right.Name); }); // read more about return value http://msdn.microsoft.com/en-us/library/ftfdbfx6(v=vs.110).aspx - int index = listInfos.BinarySearch(listInfo, comparer); + int index = listInfos.BinarySearch (listInfo, comparer); index = index >= 0 ? index : ~index; listInfos.Insert (index, listInfo); if (completionHandler != null) - completionHandler(index); + completionHandler (index); } - void RemoveListInfo(NSUrl url, Action<int> completionHandler) + void RemoveListInfo (NSUrl url, Action<int> completionHandler) { ListInfo listInfo = new ListInfo (url); RemoveListInfo (listInfo, completionHandler); } - void RemoveListInfo(ListInfo listInfo, Action<int> completionHandler) + void RemoveListInfo (ListInfo listInfo, Action<int> completionHandler) { int index = listInfos.IndexOf (listInfo); if (index < 0) @@ -371,17 +369,17 @@ void RemoveListInfo(ListInfo listInfo, Action<int> completionHandler) listInfos.RemoveAt (index); if (completionHandler != null) - completionHandler(index); + completionHandler (index); } // ListInfo objects may originate from local URLs or NSMetadataItems representing document in the cloud. - void InsertListInfoWithProvider(NSMetadataItem item, Action<int> completionHandler) + void InsertListInfoWithProvider (NSMetadataItem item, Action<int> completionHandler) { - InsertListInfoWithProvider ((NSUrl)item.ValueForAttribute (NSMetadataQuery.ItemURLKey), completionHandler); + InsertListInfoWithProvider ((NSUrl) item.ValueForAttribute (NSMetadataQuery.ItemURLKey), completionHandler); } // ListInfo objects may originate from local URLs or NSMetadataItems representing document in the cloud. - void InsertListInfoWithProvider(NSUrl provider, Action<int> completionHandler) + void InsertListInfoWithProvider (NSUrl provider, Action<int> completionHandler) { ListInfo listInfo = new ListInfo (provider); InsertListInfo (listInfo, completionHandler); @@ -391,27 +389,27 @@ void InsertListInfoWithProvider(NSUrl provider, Action<int> completionHandler) #region Notifications - public void UpdateDocumentColor(NSUrl documentUrl, ListColor newColor) + public void UpdateDocumentColor (NSUrl documentUrl, ListColor newColor) { ListInfo listInfo = new ListInfo (documentUrl); - int index = listInfos.IndexOf(listInfo); + int index = listInfos.IndexOf (listInfo); if (index != -1) { - listInfo = listInfos[index]; + listInfo = listInfos [index]; listInfo.Color = newColor; NSIndexPath indexPath = NSIndexPath.FromRowSection (index, 0); - ListCell cell = (ListCell)TableView.CellAt (indexPath); + ListCell cell = (ListCell) TableView.CellAt (indexPath); cell.ListColorView.BackgroundColor = AppColors.ColorFrom (newColor); } } - void HandleContentSizeCategoryDidChangeNotification(object sender, UIContentSizeCategoryChangedEventArgs arg) + void HandleContentSizeCategoryDidChangeNotification (object sender, UIContentSizeCategoryChangedEventArgs arg) { View.SetNeedsLayout (); } - void OnStorageChoiceChanged(object sender, EventArgs arg) + void OnStorageChoiceChanged (object sender, EventArgs arg) { StartQuery (); } @@ -420,7 +418,7 @@ void OnStorageChoiceChanged(object sender, EventArgs arg) #region User Storage Preference Related Alerts - void NotifyUserOfAccountChange() + void NotifyUserOfAccountChange () { string title = "iCloud Sign Out"; string message = "You have signed out of the iCloud account previously used to store documents. Sign back in to access those documents."; @@ -432,7 +430,7 @@ void NotifyUserOfAccountChange() PresentViewController (signedOutController, true, null); } - void PromptUserForStorageOption() + void PromptUserForStorageOption () { string title = "Choose Storage Option"; string message = "Do you want to store documents in iCloud or only on this device?"; @@ -448,14 +446,14 @@ void PromptUserForStorageOption() UIAlertAction cloudOption = UIAlertAction.Create (cloudActionTitle, UIAlertActionStyle.Default, action => { AppConfig.SharedAppConfiguration.StorageOption = StorageType.Cloud; - AppConfig.SharedAppConfiguration.StoreUbiquityIdentityToken(); + AppConfig.SharedAppConfiguration.StoreUbiquityIdentityToken (); }); storageController.AddAction (cloudOption); PresentViewController (storageController, true, null); } - void NeedCloudAlert() + void NeedCloudAlert () { var title = "iCloud needed"; var message = "For this sample you need enable iCloud Drive and restart app"; diff --git a/ios8/Lister/Lister/ViewControllers/ListViewController.cs b/ios8/Lister/Lister/ViewControllers/ListViewController.cs index e62a825e0..b644370fd 100644 --- a/ios8/Lister/Lister/ViewControllers/ListViewController.cs +++ b/ios8/Lister/Lister/ViewControllers/ListViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -9,23 +9,21 @@ using System.Drawing; using CoreGraphics; -namespace Lister -{ - [Register("ListViewController")] - public class ListViewController : UITableViewController, IUITextFieldDelegate - { +namespace Lister { + [Register ("ListViewController")] + public class ListViewController : UITableViewController, IUITextFieldDelegate { const string EmptyViewControllerStoryboardIdentifier = "emptyViewController"; // Notification User Info Keys - public static readonly NSString ListDidUpdateColorUserInfoKey = new NSString("ListDidUpdateColorUserInfoKey"); - public static readonly NSString ListDidUpdateURLUserInfoKey = new NSString("ListDidUPdateURLUserInfoKey"); + public static readonly NSString ListDidUpdateColorUserInfoKey = new NSString ("ListDidUpdateColorUserInfoKey"); + public static readonly NSString ListDidUpdateURLUserInfoKey = new NSString ("ListDidUPdateURLUserInfoKey"); // UITableViewCell Identifiers - static readonly NSString ListItemCellIdentifier = new NSString("listItemCell"); - static readonly NSString ListColorCellIdentifier = new NSString("listColorCell"); + static readonly NSString ListItemCellIdentifier = new NSString ("listItemCell"); + static readonly NSString ListColorCellIdentifier = new NSString ("listColorCell"); ListDocument document; - UIBarButtonItem[] listToolbarItems; + UIBarButtonItem [] listToolbarItems; public NSUrl DocumentURL { get { @@ -51,12 +49,12 @@ UIStringAttributes TextAttributes { set { textAttributes = value; - if(IsViewLoaded) + if (IsViewLoaded) UpdateInterfaceWithTextAttributes (); } } - public ListViewController(IntPtr handle) + public ListViewController (IntPtr handle) : base (handle) { string title = "Delete List"; @@ -64,7 +62,7 @@ public ListViewController(IntPtr handle) UIBarButtonItem flexibleSpace = new UIBarButtonItem (UIBarButtonSystemItem.FixedSpace); - listToolbarItems = new UIBarButtonItem[] { + listToolbarItems = new UIBarButtonItem [] { flexibleSpace, deleteList, flexibleSpace @@ -113,11 +111,11 @@ public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); - if(document != null) + if (document != null) document.Close (null); // Unsibscribe from UIDocument.StateChangedNotification - if(docStateChangeToken != null) + if (docStateChangeToken != null) docStateChangeToken.Dispose (); // Hide the toolbar so the list can't be edited. @@ -128,7 +126,7 @@ public override void ViewWillDisappear (bool animated) #region Setup - public async void ConfigureWith(ListInfo listInfo) + public async void ConfigureWith (ListInfo listInfo) { await listInfo.FetchInfoAsync (); @@ -137,14 +135,14 @@ public async void ConfigureWith(ListInfo listInfo) document.Close (null); } - document = new ListDocument(listInfo.Url); + document = new ListDocument (listInfo.Url); document.DocumentDeleted += OnListDocumentWasDeleted; NavigationItem.Title = listInfo.Name; TextAttributes = new UIStringAttributes { Font = UIFont.PreferredHeadline, - ForegroundColor = AppColors.ColorFrom(listInfo.Color.Value) + ForegroundColor = AppColors.ColorFrom (listInfo.Color.Value) }; } @@ -152,7 +150,7 @@ public async void ConfigureWith(ListInfo listInfo) #region Notifications - void HandleDocumentStateChangedNotification(NSNotification notification) + void HandleDocumentStateChangedNotification (NSNotification notification) { UIDocumentState state = document.DocumentState; @@ -160,7 +158,7 @@ void HandleDocumentStateChangedNotification(NSNotification notification) ResolveConflicts (); InvokeOnMainThread (() => { - TableView.ReloadData(); + TableView.ReloadData (); }); } @@ -177,7 +175,7 @@ public override void SetEditing (bool editing, bool animated) // Reload the first row to switch from "Add Item" to "Change Color" NSIndexPath indexPath = NSIndexPath.FromRowSection (0, 0); - TableView.ReloadRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); // If moving out of edit mode, notify observers about the list color and trigger a save. if (!editing) { @@ -207,21 +205,21 @@ public override nint RowsInSection (UITableView tableview, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { if (Editing && indexPath.Row == 0) { - var colorCell = (ListColorCell)tableView.DequeueReusableCell (ListColorCellIdentifier, indexPath); + var colorCell = (ListColorCell) tableView.DequeueReusableCell (ListColorCellIdentifier, indexPath); colorCell.Configure (); colorCell.ViewController = this; return colorCell; } else { - var itemCell = (ListItemCell)tableView.DequeueReusableCell (ListItemCellIdentifier, indexPath); + var itemCell = (ListItemCell) tableView.DequeueReusableCell (ListItemCellIdentifier, indexPath); ConfigureListItemCell (itemCell, indexPath.Row); return itemCell; } } - void ConfigureListItemCell(ListItemCell itemCell, int row) + void ConfigureListItemCell (ListItemCell itemCell, int row) { itemCell.TextField.Font = UIFont.PreferredBody; itemCell.TextField.WeakDelegate = this; @@ -231,7 +229,7 @@ void ConfigureListItemCell(ListItemCell itemCell, int row) itemCell.TextField.Placeholder = "Add Item"; itemCell.CheckBox.Hidden = true; } else { - ListItem item = List[row - 1]; + ListItem item = List [row - 1]; itemCell.Completed = item.IsComplete; itemCell.TextField.Text = item.Text; @@ -255,10 +253,10 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE if (editingStyle != UITableViewCellEditingStyle.Delete) return; - ListItem item = List[indexPath.Row - 1]; - List.RemoveItems (new ListItem[]{ item }); + ListItem item = List [indexPath.Row - 1]; + List.RemoveItems (new ListItem [] { item }); - TableView.DeleteRows (new NSIndexPath[]{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); TriggerNewDataForWidget (); @@ -268,7 +266,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE public override void MoveRow (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) { - ListItem item = List[sourceIndexPath.Row - 1]; + ListItem item = List [sourceIndexPath.Row - 1]; List.MoveItem (item, destinationIndexPath.Row - 1); // Notify the document of a change. @@ -293,13 +291,13 @@ public override void DidEndEditing (UITableView tableView, NSIndexPath indexPath public override NSIndexPath CustomizeMoveTarget (UITableView tableView, NSIndexPath sourceIndexPath, NSIndexPath proposedIndexPath) { - ListItem item = List[sourceIndexPath.Row - 1]; + ListItem item = List [sourceIndexPath.Row - 1]; int row; if (proposedIndexPath.Row == 0) { - row = item.IsComplete ? List.IndexOfFirstCompletedItem() + 1 : 1; + row = item.IsComplete ? List.IndexOfFirstCompletedItem () + 1 : 1; return NSIndexPath.FromRowSection (row, 0); - } else if (List.CanMoveItem(item, proposedIndexPath.Row - 1, false)) { + } else if (List.CanMoveItem (item, proposedIndexPath.Row - 1, false)) { return proposedIndexPath; } else if (item.IsComplete) { row = List.IndexOfFirstCompletedItem () + 1; @@ -321,7 +319,7 @@ public void EditingEnded (UITextField textField) if (indexPath.Row > 0) { // Edit the item in place. - ListItem item = List[indexPath.Row - 1]; + ListItem item = List [indexPath.Row - 1]; // If the contents of the text field at the end of editing is the same as it started, don't trigger an update. if (item.Text != textField.Text) { @@ -338,14 +336,14 @@ public void EditingEnded (UITextField textField) int insertedIndex = List.InsertItem (item); // Update the edit row to show the check box. - ListItemCell itemCell = (ListItemCell)TableView.CellAt (indexPath); + ListItemCell itemCell = (ListItemCell) TableView.CellAt (indexPath); itemCell.CheckBox.Hidden = false; // Insert a new add item row into the table view. TableView.BeginUpdates (); NSIndexPath targetIndexPath = NSIndexPath.FromRowSection (insertedIndex, 0); - TableView.InsertRows (new NSIndexPath[] { targetIndexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new NSIndexPath [] { targetIndexPath }, UITableViewRowAnimation.Automatic); TableView.EndUpdates (); @@ -359,10 +357,10 @@ public void EditingEnded (UITextField textField) [Export ("textFieldShouldReturn:")] public bool ShouldReturn (UITextField textField) { - NSIndexPath indexPath = IndexPathForView(textField); + NSIndexPath indexPath = IndexPathForView (textField); // An item must have text to dismiss the keyboard. - if (!string.IsNullOrEmpty(textField.Text) || indexPath.Row == 0) { + if (!string.IsNullOrEmpty (textField.Text) || indexPath.Row == 0) { textField.ResignFirstResponder (); return true; } @@ -381,35 +379,35 @@ public void OnListColorCellDidChangeSelectedColor (ListColor color) ForegroundColor = AppColors.ColorFrom (List.Color) }; - NSIndexPath[] indexPaths = TableView.IndexPathsForVisibleRows; + NSIndexPath [] indexPaths = TableView.IndexPathsForVisibleRows; TableView.ReloadRows (indexPaths, UITableViewRowAnimation.None); } #region IBActions - void DeleteList(object sender, EventArgs e) + void DeleteList (object sender, EventArgs e) { if (SplitViewController.Collapsed) { NavigationController.PopViewController (true); } else { - UIViewController emptyViewController = (UIViewController)Storyboard.InstantiateViewController (EmptyViewControllerStoryboardIdentifier); + UIViewController emptyViewController = (UIViewController) Storyboard.InstantiateViewController (EmptyViewControllerStoryboardIdentifier); SplitViewController.ShowDetailViewController (emptyViewController, null); } MasterController.ListViewControllerDidDeleteList (this); } - [Export("checkBoxTapped:")] - public void CheckBoxTapped(CheckBox sender) + [Export ("checkBoxTapped:")] + public void CheckBoxTapped (CheckBox sender) { NSIndexPath indexPath = IndexPathForView (sender); if (indexPath.Row >= 1 && indexPath.Row <= List.Count) { - ListItem item = List[indexPath.Row - 1]; + ListItem item = List [indexPath.Row - 1]; ListOperationInfo info = List.ToggleItem (item, -1); if (info.FromIndex == info.ToIndex) { - TableView.ReloadRows(new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); } else { // Animate the row up or down depending on whether it was complete/incomplete. NSIndexPath target = NSIndexPath.FromRowSection (info.ToIndex + 1, 0); @@ -417,7 +415,7 @@ public void CheckBoxTapped(CheckBox sender) TableView.BeginUpdates (); TableView.MoveRow (indexPath, target); TableView.EndUpdates (); - TableView.ReloadRows (new NSIndexPath[] { target }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new NSIndexPath [] { target }, UITableViewRowAnimation.Automatic); } TriggerNewDataForWidget (); @@ -431,17 +429,17 @@ public void CheckBoxTapped(CheckBox sender) void OnListDocumentWasDeleted (object sender, EventArgs e) { - var document = (ListDocument)sender; + var document = (ListDocument) sender; document.DocumentDeleted -= OnListDocumentWasDeleted; InvokeOnMainThread (() => { - DismissViewController(true, null); + DismissViewController (true, null); }); } #region Convenience - void TriggerNewDataForWidget() + void TriggerNewDataForWidget () { string todayDocumentName = AppConfig.SharedAppConfiguration.TodayDocumentName; @@ -451,11 +449,11 @@ void TriggerNewDataForWidget() // You can use hardcoded value for widget bundle identifier // But it is a good idea to move this value to some kind of setting // Info.plist works for this purpose - var widgetBundleId = (string)(NSString)NSBundle.MainBundle.ObjectForInfoDictionary ("WidgetBundleIdentifier"); + var widgetBundleId = (string) (NSString) NSBundle.MainBundle.ObjectForInfoDictionary ("WidgetBundleIdentifier"); NCWidgetController.GetWidgetController ().SetHasContent (true, widgetBundleId); } - void UpdateInterfaceWithTextAttributes() + void UpdateInterfaceWithTextAttributes () { NavigationController.NavigationBar.TitleTextAttributes = TextAttributes; @@ -465,19 +463,19 @@ void UpdateInterfaceWithTextAttributes() TableView.TintColor = color; } - void ResolveConflicts() + void ResolveConflicts () { // Any automatic merging logic or presentation of conflict resolution UI should go here. // For this sample, just pick the current version and mark the conflict versions as resolved. NSError error = null; NSFileVersion.RemoveOtherVersions (DocumentURL, out error); - NSFileVersion[] conflictVersions = NSFileVersion.GetUnresolvedConflictVersions (DocumentURL); + NSFileVersion [] conflictVersions = NSFileVersion.GetUnresolvedConflictVersions (DocumentURL); foreach (NSFileVersion fileVersion in conflictVersions) fileVersion.Resolved = true; } - NSIndexPath IndexPathForView(UIView view) + NSIndexPath IndexPathForView (UIView view) { CGPoint viewOrigin = view.Bounds.Location; CGPoint viewLocation = TableView.ConvertPointFromView (viewOrigin, view); diff --git a/ios8/Lister/Lister/ViewControllers/NewDocumentController.cs b/ios8/Lister/Lister/ViewControllers/NewDocumentController.cs index b4c0f09e9..64293bb62 100644 --- a/ios8/Lister/Lister/ViewControllers/NewDocumentController.cs +++ b/ios8/Lister/Lister/ViewControllers/NewDocumentController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -6,43 +6,41 @@ using Common; using ListerKit; -namespace Lister -{ - [Register("NewDocumentController")] - public class NewDocumentController : UIViewController, IUITextFieldDelegate - { - [Outlet("grayButton")] +namespace Lister { + [Register ("NewDocumentController")] + public class NewDocumentController : UIViewController, IUITextFieldDelegate { + [Outlet ("grayButton")] UIButton GrayButton { get; set; } - [Outlet("blueButton")] + [Outlet ("blueButton")] UIButton BlueButton { get; set; } - [Outlet("greenButton")] + [Outlet ("greenButton")] UIButton GreenButton { get; set; } - [Outlet("yellowButton")] + [Outlet ("yellowButton")] UIButton YellowButton { get; set; } - [Outlet("orangeButton")] + [Outlet ("orangeButton")] UIButton OrangeButton { get; set; } - [Outlet("redButton")] + [Outlet ("redButton")] UIButton RedButton { get; set; } - [Outlet("saveButton")] + [Outlet ("saveButton")] UIBarButtonItem SaveButton { get; set; } - [Outlet("toolbar")] + [Outlet ("toolbar")] UIToolbar Toolbar { get; set; } - [Outlet("titleLabel")] + [Outlet ("titleLabel")] UILabel TitleLabel { get; set; } UIButton selectedButton; NSUrl FileUrl { get { - return string.IsNullOrWhiteSpace(selectedTitle) + return string.IsNullOrWhiteSpace (selectedTitle) ? null : ListCoordinator.SharedListCoordinator.DocumentURLForName (selectedTitle); } @@ -73,7 +71,7 @@ public void EditingEnded (UITextField textField) [Export ("textFieldShouldReturn:")] public bool ShouldReturn (UITextField textField) { - textField.ResignFirstResponder(); + textField.ResignFirstResponder (); return true; } @@ -81,46 +79,47 @@ public bool ShouldReturn (UITextField textField) #region IBActions - [Export("pickColor:")] - public void PickColor(UIButton sender) + [Export ("pickColor:")] + public void PickColor (UIButton sender) { // Use the button's tag to determine the color. - selectedColor = (ListColor)(int)sender.Tag; + selectedColor = (ListColor) (int) sender.Tag; // Clear out the previously selected button's border. - if(selectedButton != null) + if (selectedButton != null) selectedButton.Layer.BorderWidth = 0; sender.Layer.BorderWidth = 5f; sender.Layer.BorderColor = UIColor.LightGray.CGColor; selectedButton = sender; - TitleLabel.TextColor = AppColors.ColorFrom(selectedColor); - Toolbar.TintColor = AppColors.ColorFrom(selectedColor); + TitleLabel.TextColor = AppColors.ColorFrom (selectedColor); + Toolbar.TintColor = AppColors.ColorFrom (selectedColor); } - [Export("saveAction:")] - public void SaveAction(NSObject sender) + [Export ("saveAction:")] + public void SaveAction (NSObject sender) { - ListInfo listInfo = new ListInfo(FileUrl); + ListInfo listInfo = new ListInfo (FileUrl); listInfo.Color = selectedColor; listInfo.Name = selectedTitle; listInfo.CreateAndSaveWithCompletionHandler (success => { if (success) { - MasterController.OnNewListInfo(listInfo); + MasterController.OnNewListInfo (listInfo); } else { // In your app, you should handle this error gracefully. Console.WriteLine ("Unable to create new document at URL: {0}", FileUrl.AbsoluteString); - throw new InvalidProgramException(); + throw new InvalidProgramException (); } - DismissViewController(true, null); + DismissViewController (true, null); }); } - [Export("cancelAction:")] - public void CancelAction(NSObject sender) { - DismissViewController(true, null); + [Export ("cancelAction:")] + public void CancelAction (NSObject sender) + { + DismissViewController (true, null); } #endregion diff --git a/ios8/Lister/Lister/Views/ListCell.cs b/ios8/Lister/Lister/Views/ListCell.cs index d068c89fe..f34f9e3a3 100644 --- a/ios8/Lister/Lister/Views/ListCell.cs +++ b/ios8/Lister/Lister/Views/ListCell.cs @@ -1,21 +1,19 @@ -using System; +using System; using UIKit; using Foundation; -namespace Lister -{ - [Register("ListCell")] - public class ListCell : UITableViewCell - { - [Outlet("label")] +namespace Lister { + [Register ("ListCell")] + public class ListCell : UITableViewCell { + [Outlet ("label")] public UILabel Label { get; set; } - [Outlet("listColorView")] + [Outlet ("listColorView")] public UIView ListColorView { get; set; } - public ListCell(IntPtr handle) - : base(handle) + public ListCell (IntPtr handle) + : base (handle) { } diff --git a/ios8/Lister/Lister/Views/ListColorCell.cs b/ios8/Lister/Lister/Views/ListColorCell.cs index 596a74d8a..fd8c03343 100644 --- a/ios8/Lister/Lister/Views/ListColorCell.cs +++ b/ios8/Lister/Lister/Views/ListColorCell.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using UIKit; @@ -7,27 +7,25 @@ using Common; using CoreGraphics; -namespace Lister -{ - [Register("ListColorCell")] - public class ListColorCell : UITableViewCell - { - [Outlet("gray")] +namespace Lister { + [Register ("ListColorCell")] + public class ListColorCell : UITableViewCell { + [Outlet ("gray")] UIView Gray { get; set; } - [Outlet("blue")] + [Outlet ("blue")] UIView Blue { get; set; } - [Outlet("green")] + [Outlet ("green")] UIView Green { get; set; } - [Outlet("yellow")] + [Outlet ("yellow")] UIView Yellow { get; set; } - [Outlet("orange")] + [Outlet ("orange")] UIView Orange { get; set; } - [Outlet("red")] + [Outlet ("red")] UIView Red { get; set; } public ListViewController ViewController { get; set; } @@ -35,11 +33,11 @@ public class ListColorCell : UITableViewCell public ListColor SelectedColor { get; private set; } public ListColorCell (IntPtr handle) - : base(handle) + : base (handle) { } - public void Configure() + public void Configure () { UITapGestureRecognizer colorTapGestureRecognizer = new UITapGestureRecognizer (ColorTap); colorTapGestureRecognizer.NumberOfTapsRequired = 1; @@ -48,7 +46,7 @@ public void Configure() AddGestureRecognizer (colorTapGestureRecognizer); } - void ColorTap(UITapGestureRecognizer tapGestureRecognizer) + void ColorTap (UITapGestureRecognizer tapGestureRecognizer) { if (tapGestureRecognizer.State != UIGestureRecognizerState.Ended) return; @@ -57,7 +55,7 @@ void ColorTap(UITapGestureRecognizer tapGestureRecognizer) UIView view = ContentView.HitTest (tapLocation, null); // If the user tapped on a color (identified by its tag), notify the delegate. - ListColor color = (ListColor)(int)view.Tag; + ListColor color = (ListColor) (int) view.Tag; SelectedColor = color; ViewController.OnListColorCellDidChangeSelectedColor (SelectedColor); } diff --git a/ios8/Lister/Lister/Views/ListItemCell.cs b/ios8/Lister/Lister/Views/ListItemCell.cs index 1f57ed8b7..25cec6693 100644 --- a/ios8/Lister/Lister/Views/ListItemCell.cs +++ b/ios8/Lister/Lister/Views/ListItemCell.cs @@ -1,19 +1,17 @@ -using System; +using System; using UIKit; using Foundation; using ListerKit; -namespace Lister -{ - [Register("ListItemCell")] - public class ListItemCell : UITableViewCell - { - [Outlet("checkBox")] +namespace Lister { + [Register ("ListItemCell")] + public class ListItemCell : UITableViewCell { + [Outlet ("checkBox")] public CheckBox CheckBox { get; set; } - [Outlet("textField")] + [Outlet ("textField")] public UITextField TextField { get; set; } bool complete; @@ -30,8 +28,8 @@ public bool Completed { } } - public ListItemCell(IntPtr handle) - : base(handle) + public ListItemCell (IntPtr handle) + : base (handle) { } diff --git a/ios8/Lister/ListerKit/CheckBox.cs b/ios8/Lister/ListerKit/CheckBox.cs index 16a1fa09a..17b51332a 100644 --- a/ios8/Lister/ListerKit/CheckBox.cs +++ b/ios8/Lister/ListerKit/CheckBox.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -6,25 +6,23 @@ using Common; -namespace ListerKit -{ - [Register("CheckBox")] - public class CheckBox : UIControl - { - [Export("layerClass")] +namespace ListerKit { + [Register ("CheckBox")] + public class CheckBox : UIControl { + [Export ("layerClass")] public static Class LayerClass { get { - return new Class(typeof(CheckBoxLayer)); + return new Class (typeof (CheckBoxLayer)); } } CheckBoxLayer CheckBoxLayer { get { - return (CheckBoxLayer)Layer; + return (CheckBoxLayer) Layer; } } - [Outlet("checked")] + [Outlet ("checked")] public bool Checked { get { return CheckBoxLayer.Checked; @@ -63,7 +61,7 @@ public float MarkInsetFactor { } public CheckBox (IntPtr handle) - : base(handle) + : base (handle) { } diff --git a/ios8/Lister/ListerKit/ListCoordinator.cs b/ios8/Lister/ListerKit/ListCoordinator.cs index ea4452a97..0ba2dafef 100644 --- a/ios8/Lister/ListerKit/ListCoordinator.cs +++ b/ios8/Lister/ListerKit/ListCoordinator.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Threading; using System.IO; using Foundation; using Common; -namespace ListerKit -{ - public class ListCoordinator : NSObject - { +namespace ListerKit { + public class ListCoordinator : NSObject { public event EventHandler StorageChoiceChanged; static readonly ListCoordinator sharedListCoordinator; @@ -26,9 +24,9 @@ public NSUrl TodayDocumentURL { } } - static ListCoordinator() + static ListCoordinator () { - sharedListCoordinator = new ListCoordinator(); + sharedListCoordinator = new ListCoordinator (); sharedListCoordinator.DocumentsDirectory = GetFirstDocumentDirectoryUrlForUserDomain (); } @@ -37,7 +35,7 @@ static ListCoordinator() AppConfig.SharedAppConfiguration.StorageOptionChanged += UpdateDocumentStorageContainerURL; } - static NSUrl GetFirstDocumentDirectoryUrlForUserDomain() + static NSUrl GetFirstDocumentDirectoryUrlForUserDomain () { var defaultManager = NSFileManager.DefaultManager; return defaultManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User) [0]; @@ -45,7 +43,7 @@ static NSUrl GetFirstDocumentDirectoryUrlForUserDomain() #region Convenience - void CopyFileToDocumentsDirectory(NSUrl fromUrl) + void CopyFileToDocumentsDirectory (NSUrl fromUrl) { NSUrl toURL = DocumentsDirectory.Append (fromUrl.LastPathComponent, false); @@ -54,8 +52,8 @@ void CopyFileToDocumentsDirectory(NSUrl fromUrl) NSFileCoordinator fileCoordinator = new NSFileCoordinator (); fileCoordinator.CoordinateWriteWrite (fromUrl, NSFileCoordinatorWritingOptions.ForMoving, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out error, (src, dst) => { - NSFileManager fileManager = new NSFileManager(); - success = fileManager.Copy(src, dst, out error); + NSFileManager fileManager = new NSFileManager (); + success = fileManager.Copy (src, dst, out error); if (success) { var attributes = new NSFileAttributes { @@ -72,7 +70,7 @@ void CopyFileToDocumentsDirectory(NSUrl fromUrl) toURL.AbsoluteString, error.Description); } - public void DeleteFileAtURL(NSUrl fileURL) + public void DeleteFileAtURL (NSUrl fileURL) { var fileCoordinator = new NSFileCoordinator (); NSError error; @@ -80,13 +78,13 @@ public void DeleteFileAtURL(NSUrl fileURL) fileCoordinator.CoordinateWrite (fileURL, NSFileCoordinatorWritingOptions.ForDeleting, out error, writingURL => { - NSFileManager fileManager = new NSFileManager(); - success = fileManager.Remove(writingURL, out error); - }); + NSFileManager fileManager = new NSFileManager (); + success = fileManager.Remove (writingURL, out error); + }); - // In your app, handle this gracefully. + // In your app, handle this gracefully. if (!success) { - string msg = string.Format("Couldn't delete file at URL {0}. Error: {1}.", fileURL.AbsoluteString, error.Description); + string msg = string.Format ("Couldn't delete file at URL {0}. Error: {1}.", fileURL.AbsoluteString, error.Description); throw new InvalidProgramException (msg); } } @@ -95,16 +93,16 @@ public void DeleteFileAtURL(NSUrl fileURL) #region Document Management - public void CopyInitialDocuments() + public void CopyInitialDocuments () { var bundle = NSBundle.MainBundle; - NSUrl[] defaultListPaths = bundle.GetUrlsForResourcesWithExtension(AppConfig.ListerFileExtension, string.Empty); + NSUrl [] defaultListPaths = bundle.GetUrlsForResourcesWithExtension (AppConfig.ListerFileExtension, string.Empty); foreach (var p in defaultListPaths) CopyFileToDocumentsDirectory (p); } - void UpdateDocumentStorageContainerURL(object sender, EventArgs e) + void UpdateDocumentStorageContainerURL (object sender, EventArgs e) { NSUrl oldDocumentsDirectory = DocumentsDirectory; @@ -119,48 +117,48 @@ void UpdateDocumentStorageContainerURL(object sender, EventArgs e) // The call to GetUrlForUbiquityContainer should be on a background thread. // You can pass null to retrieve the URL for the first container in the list // For more information visit https://developer.apple.com/library/ios/documentation/General/Conceptual/iCloudDesignGuide/Chapters/iCloudFundametals.html#//apple_ref/doc/uid/TP40012094-CH6-SW1 - NSUrl cloudDirectory = fileManager.GetUrlForUbiquityContainer(null); + NSUrl cloudDirectory = fileManager.GetUrlForUbiquityContainer (null); - InvokeOnMainThread(()=> { - DocumentsDirectory = cloudDirectory.Append("Documents", true); + InvokeOnMainThread (() => { + DocumentsDirectory = cloudDirectory.Append ("Documents", true); NSError error; - NSUrl[] localDocuments = fileManager.GetDirectoryContent(oldDocumentsDirectory, + NSUrl [] localDocuments = fileManager.GetDirectoryContent (oldDocumentsDirectory, null, NSDirectoryEnumerationOptions.SkipsPackageDescendants, out error); foreach (NSUrl url in localDocuments) { - string ext = Path.GetExtension(url.AbsoluteString).Replace(".", string.Empty); + string ext = Path.GetExtension (url.AbsoluteString).Replace (".", string.Empty); if (ext == AppConfig.ListerFileExtension) - MakeItemUbiquitousAtURL(url); + MakeItemUbiquitousAtURL (url); } - RaiseStorageChoiceChanged(); + RaiseStorageChoiceChanged (); }); }); } } - void RaiseStorageChoiceChanged() + void RaiseStorageChoiceChanged () { var handler = StorageChoiceChanged; if (handler != null) handler (this, EventArgs.Empty); } - void MakeItemUbiquitousAtURL(NSUrl sourceURL) + void MakeItemUbiquitousAtURL (NSUrl sourceURL) { string destinationFileName = sourceURL.LastPathComponent; NSUrl destinationURL = DocumentsDirectory.Append (destinationFileName, false); // Upload the file to iCloud on a background queue. ThreadPool.QueueUserWorkItem (_ => { - NSFileManager fileManager = new NSFileManager(); + NSFileManager fileManager = new NSFileManager (); NSError error; - bool success = fileManager.SetUbiquitous(true, sourceURL, destinationURL, out error); + bool success = fileManager.SetUbiquitous (true, sourceURL, destinationURL, out error); // If the move wasn't successful, try removing the item locally since the document may already exist in the cloud. if (!success) - fileManager.Remove(sourceURL, out error); + fileManager.Remove (sourceURL, out error); }); } @@ -168,14 +166,14 @@ void MakeItemUbiquitousAtURL(NSUrl sourceURL) #region Document Name Helper Methods - public NSUrl DocumentURLForName(string name) + public NSUrl DocumentURLForName (string name) { var url = DocumentsDirectory.Append (name, false); url = url.AppendPathExtension (AppConfig.ListerFileExtension); return url; } - public bool IsValidDocumentName(string name) + public bool IsValidDocumentName (string name) { if (string.IsNullOrWhiteSpace (name)) return false; diff --git a/ios8/Lister/ListerKit/ListDocument.cs b/ios8/Lister/ListerKit/ListDocument.cs index cc207557b..35e2383a5 100644 --- a/ios8/Lister/ListerKit/ListDocument.cs +++ b/ios8/Lister/ListerKit/ListDocument.cs @@ -1,20 +1,18 @@ -using System; +using System; using UIKit; using Foundation; using Common; -namespace ListerKit -{ - public class ListDocument : UIDocument - { +namespace ListerKit { + public class ListDocument : UIDocument { public event EventHandler DocumentDeleted; public List List { get; set; } public ListDocument (NSUrl url) - : base(url) + : base (url) { List = new List (); } @@ -23,13 +21,13 @@ public override bool LoadFromContents (NSObject contents, string typeName, out N { outError = null; - List deserializedList = (List)NSKeyedUnarchiver.UnarchiveObject ((NSData)contents); - if (deserializedList!= null) { + List deserializedList = (List) NSKeyedUnarchiver.UnarchiveObject ((NSData) contents); + if (deserializedList != null) { List = deserializedList; return true; } - outError = new NSError (NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadCorruptFile, new NSDictionary ( + outError = new NSError (NSError.CocoaErrorDomain, (int) NSCocoaError.FileReadCorruptFile, new NSDictionary ( NSError.LocalizedDescriptionKey, "Could not read file", NSError.LocalizedFailureReasonErrorKey, "File was in an invalid format" )); @@ -45,7 +43,7 @@ public override NSObject ContentsForType (string typeName, out NSError outError) if (serializedList != null) return serializedList; - outError = new NSError (NSError.CocoaErrorDomain, (int)NSCocoaError.FileReadUnknown, new NSDictionary ( + outError = new NSError (NSError.CocoaErrorDomain, (int) NSCocoaError.FileReadUnknown, new NSDictionary ( NSError.LocalizedDescriptionKey, "Could not save file", NSError.LocalizedFailureReasonErrorKey, "An unexpected error occured" )); diff --git a/ios8/Lister/ListerKit/Properties/AssemblyInfo.cs b/ios8/Lister/ListerKit/Properties/AssemblyInfo.cs index f3f445571..ca20941a2 100644 --- a/ios8/Lister/ListerKit/Properties/AssemblyInfo.cs +++ b/ios8/Lister/ListerKit/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/ios8/Lister/ListerToday/CheckBoxCell.cs b/ios8/Lister/ListerToday/CheckBoxCell.cs index 8c811c5b5..cf08590c6 100644 --- a/ios8/Lister/ListerToday/CheckBoxCell.cs +++ b/ios8/Lister/ListerToday/CheckBoxCell.cs @@ -1,23 +1,21 @@ -using System; +using System; using UIKit; using Foundation; using ListerKit; -namespace ListerToday -{ - [Register("CheckBoxCell")] - public class CheckBoxCell : UITableViewCell - { - [Outlet("label")] +namespace ListerToday { + [Register ("CheckBoxCell")] + public class CheckBoxCell : UITableViewCell { + [Outlet ("label")] public UILabel Label { get; private set; } - [Outlet("checkBox")] + [Outlet ("checkBox")] public CheckBox CheckBox { get; private set; } public CheckBoxCell (IntPtr handle) - : base(handle) + : base (handle) { } diff --git a/ios8/Lister/ListerToday/TodayViewController.cs b/ios8/Lister/ListerToday/TodayViewController.cs index 01c13e6b4..0a017a2b5 100644 --- a/ios8/Lister/ListerToday/TodayViewController.cs +++ b/ios8/Lister/ListerToday/TodayViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Drawing; using NotificationCenter; @@ -10,19 +10,17 @@ using System.Collections.Generic; using CoreGraphics; -namespace ListerToday -{ - [Register("TodayViewController")] - public class TodayViewController : UITableViewController, INCWidgetProviding - { +namespace ListerToday { + [Register ("TodayViewController")] + public class TodayViewController : UITableViewController, INCWidgetProviding { const float TodayRowHeight = 44; const int TodayBaseRowCount = 5; - static readonly NSString ContentCellIdentifier = new NSString("todayViewCell"); - static readonly NSString MessageCellIdentifier = new NSString("messageCell"); + static readonly NSString ContentCellIdentifier = new NSString ("todayViewCell"); + static readonly NSString MessageCellIdentifier = new NSString ("messageCell"); ListDocument document; - List empty = new List(); + List empty = new List (); List List { get { return document != null ? document.List : empty; @@ -92,7 +90,7 @@ public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); - if(finishGatheringToken != null) + if (finishGatheringToken != null) finishGatheringToken.Dispose (); if (IsTodayAvailable) @@ -118,15 +116,15 @@ public UIEdgeInsets GetWidgetMarginInsets (UIEdgeInsets defaultMarginInsets) #region Query Management - void StartQuery() + void StartQuery () { if (documentMetadataQuery == null) { documentMetadataQuery = new NSMetadataQuery (); - documentMetadataQuery.SearchScopes = new NSObject[]{ NSMetadataQuery.UbiquitousDocumentsScope }; + documentMetadataQuery.SearchScopes = new NSObject [] { NSMetadataQuery.UbiquitousDocumentsScope }; string todayListName = AppConfig.SharedAppConfiguration.TodayDocumentNameAndExtension; documentMetadataQuery.Predicate = NSPredicate.FromFormat ("(%K = %@)", NSMetadataQuery.ItemFSNameKey, - (NSString)todayListName); + (NSString) todayListName); NSNotificationCenter notificationCenter = NSNotificationCenter.DefaultCenter; // TODO: subscribtion https://trello.com/c/1RyX6cJL @@ -137,21 +135,21 @@ void StartQuery() documentMetadataQuery.StartQuery (); } - void HandleMetadataQueryUpdates(NSNotification notification) + void HandleMetadataQueryUpdates (NSNotification notification) { documentMetadataQuery.DisableUpdates (); ProcessMetadataItems (); - documentMetadataQuery.EnableUpdates(); + documentMetadataQuery.EnableUpdates (); } - async void ProcessMetadataItems() + async void ProcessMetadataItems () { Console.WriteLine ("ProcessMetadataItems"); - NSMetadataItem[] metadataItems = documentMetadataQuery.Results; + NSMetadataItem [] metadataItems = documentMetadataQuery.Results; // We only expect a single result to be returned by our NSMetadataQuery since we query for a specific file. if (metadataItems.Length == 1) { - var url = (NSUrl)metadataItems [0].ValueForAttribute (NSMetadataQuery.ItemURLKey); + var url = (NSUrl) metadataItems [0].ValueForAttribute (NSMetadataQuery.ItemURLKey); if (document != null) document.Close (null); @@ -163,8 +161,8 @@ async void ProcessMetadataItems() return; } - ResetContentSize(); - TableView.ReloadData(); + ResetContentSize (); + TableView.ReloadData (); } } @@ -177,7 +175,7 @@ public override nint RowsInSection (UITableView tableview, nint section) if (!IsTodayAvailable) return 1; - return ShowingAll ? List.Count : Math.Min(List.Count, TodayBaseRowCount + 1); + return ShowingAll ? List.Count : Math.Min (List.Count, TodayBaseRowCount + 1); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) @@ -192,7 +190,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde int itemCount = List.Count; if (itemCount > 0) { - ListItem item = List[indexPath.Row]; + ListItem item = List [indexPath.Row]; if (ShowingAll && indexPath.Row == TodayBaseRowCount && itemCount != TodayBaseRowCount + 1) { UITableViewCell cell = tableView.DequeueReusableCell (MessageCellIdentifier, indexPath); @@ -200,14 +198,14 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde return cell; } else { - var cell = (CheckBoxCell)tableView.DequeueReusableCell (ContentCellIdentifier, indexPath); + var cell = (CheckBoxCell) tableView.DequeueReusableCell (ContentCellIdentifier, indexPath); ConfigureListItemCell (cell, List.Color, item); return cell; } } - var msgCell = tableView.DequeueReusableCell(MessageCellIdentifier, indexPath); + var msgCell = tableView.DequeueReusableCell (MessageCellIdentifier, indexPath); msgCell.TextLabel.Text = IsTodayAvailable ? "No items in today's list" : string.Empty; return msgCell; @@ -218,9 +216,9 @@ public override void WillDisplay (UITableView tableView, UITableViewCell cell, N cell.Layer.BackgroundColor = UIColor.Clear.CGColor; } - void ConfigureListItemCell(CheckBoxCell itemCell, ListColor color, ListItem item) + void ConfigureListItemCell (CheckBoxCell itemCell, ListColor color, ListItem item) { - itemCell.CheckBox.TintColor = AppColors.ColorFrom(color); + itemCell.CheckBox.TintColor = AppColors.ColorFrom (color); itemCell.CheckBox.Checked = item.IsComplete; itemCell.Label.Text = item.Text; @@ -244,12 +242,12 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) TableView.BeginUpdates (); NSIndexPath indexPathForRemoval = NSIndexPath.FromRowSection (TodayBaseRowCount, 0); - TableView.DeleteRows (new NSIndexPath[] { indexPathForRemoval }, UITableViewRowAnimation.Fade); + TableView.DeleteRows (new NSIndexPath [] { indexPathForRemoval }, UITableViewRowAnimation.Fade); int count = Math.Max (List.Count - TodayBaseRowCount, 0); - NSIndexPath[] inserted = new NSIndexPath[count]; + NSIndexPath [] inserted = new NSIndexPath [count]; for (int i = 0; i < count; i++) - inserted[i] = NSIndexPath.FromRowSection (i + TodayBaseRowCount, 0); + inserted [i] = NSIndexPath.FromRowSection (i + TodayBaseRowCount, 0); TableView.InsertRows (inserted, UITableViewRowAnimation.Fade); TableView.EndUpdates (); @@ -266,15 +264,15 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) #region IBActions - [Export("checkBoxTapped:")] - public void CheckBoxTapped(CheckBox sender) + [Export ("checkBoxTapped:")] + public void CheckBoxTapped (CheckBox sender) { NSIndexPath indexPath = IndexPathForView (sender); - ListItem item = List[indexPath.Row]; + ListItem item = List [indexPath.Row]; ListOperationInfo info = List.ToggleItem (item, -1); if (info.FromIndex == info.ToIndex) { - TableView.ReloadRows (new NSIndexPath[]{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); } else { int itemCount = List.Count; @@ -284,8 +282,8 @@ public void CheckBoxTapped(CheckBox sender) NSIndexPath targetIndexPath = NSIndexPath.FromRowSection (TodayBaseRowCount - 1, 0); TableView.BeginUpdates (); - TableView.DeleteRows (new NSIndexPath[] { indexPath }, UITableViewRowAnimation.Automatic); - TableView.InsertRows (new NSIndexPath[]{ targetIndexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new NSIndexPath [] { indexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new NSIndexPath [] { targetIndexPath }, UITableViewRowAnimation.Automatic); TableView.EndUpdates (); } else { // Need to animate the row up or down depending on its completion state. @@ -294,7 +292,7 @@ public void CheckBoxTapped(CheckBox sender) TableView.BeginUpdates (); TableView.MoveRow (indexPath, targetIndexPath); TableView.EndUpdates (); - TableView.ReloadRows (new NSIndexPath[] { targetIndexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new NSIndexPath [] { targetIndexPath }, UITableViewRowAnimation.Automatic); } } @@ -306,14 +304,14 @@ public void CheckBoxTapped(CheckBox sender) #region Convenience - void ResetContentSize() + void ResetContentSize () { CGSize preferredSize = PreferredContentSize; preferredSize.Height = PreferredViewHeight; PreferredContentSize = preferredSize; } - NSIndexPath IndexPathForView(UIView view) + NSIndexPath IndexPathForView (UIView view) { CGPoint viewOrigin = view.Bounds.Location; CGPoint viewLocation = TableView.ConvertPointFromView (viewOrigin, view); diff --git a/ios8/LookInside/LookInside/AppDelegate.cs b/ios8/LookInside/LookInside/AppDelegate.cs index 0939bcbf6..78869c0b3 100644 --- a/ios8/LookInside/LookInside/AppDelegate.cs +++ b/ios8/LookInside/LookInside/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace LookInside -{ +namespace LookInside { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { UIWindow window; RootViewController rootViewController; UINavigationController navigationViewController; diff --git a/ios8/LookInside/LookInside/Main.cs b/ios8/LookInside/LookInside/Main.cs index 83a05dda9..89b9a16e0 100644 --- a/ios8/LookInside/LookInside/Main.cs +++ b/ios8/LookInside/LookInside/Main.cs @@ -1,14 +1,12 @@ -using System; +using System; using Foundation; using UIKit; -namespace LookInside -{ - public class Application - { +namespace LookInside { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/LookInside/LookInside/OverlayVibrantLabel.cs b/ios8/LookInside/LookInside/OverlayVibrantLabel.cs index 48a1fffe7..d4c1d532d 100644 --- a/ios8/LookInside/LookInside/OverlayVibrantLabel.cs +++ b/ios8/LookInside/LookInside/OverlayVibrantLabel.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace LookInside -{ - public class OverlayVibrantLabel : UILabel - { +namespace LookInside { + public class OverlayVibrantLabel : UILabel { public OverlayVibrantLabel () { TranslatesAutoresizingMaskIntoConstraints = false; diff --git a/ios8/LookInside/LookInside/OverlayViewController.cs b/ios8/LookInside/LookInside/OverlayViewController.cs index 426012407..3198bd55b 100644 --- a/ios8/LookInside/LookInside/OverlayViewController.cs +++ b/ios8/LookInside/LookInside/OverlayViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using UIKit; @@ -6,10 +6,8 @@ using Foundation; using CoreGraphics; -namespace LookInside -{ - public class OverlayViewController : UIViewController - { +namespace LookInside { + public class OverlayViewController : UIViewController { CIImage baseCIImage; UIVisualEffectView backgroundView; @@ -44,7 +42,7 @@ public PhotoCollectionViewCell PhotoView { } } - public OverlayViewController() + public OverlayViewController () { ModalPresentationStyle = UIModalPresentationStyle.Custom; Setup (); @@ -54,7 +52,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - foregroundContentView = new UIVisualEffectView(UIVibrancyEffect.FromBlurEffect(blurEffect)); + foregroundContentView = new UIVisualEffectView (UIVibrancyEffect.FromBlurEffect (blurEffect)); backgroundView = new UIVisualEffectView (blurEffect); foregroundContentScrollView = new UIScrollView (); @@ -68,18 +66,18 @@ public override void ViewWillAppear (bool animated) UpdateLabels (); } - void ConfigureCIObjects() + void ConfigureCIObjects () { baseCIImage = CIImage.FromCGImage (PhotoView.Image.CGImage); } - void OnSliderChanged(object sender, EventArgs e) + void OnSliderChanged (object sender, EventArgs e) { UpdateLabels (); ApplyFilters (); } - void UpdateLabels() + void UpdateLabels () { // Update labels hueLabel.Text = string.Format ("Hue: {0}", hueSlider.Value); @@ -87,7 +85,7 @@ void UpdateLabels() brightnessLabel.Text = string.Format ("Brightness: {0}", brightnessSlider.Value); } - void ApplyFilters() + void ApplyFilters () { float hue = hueSlider.Value; float saturation = saturationSlider.Value; @@ -96,14 +94,14 @@ void ApplyFilters() // Apply effects to image CIImage result = null; - using(var colorControlsFilter = new CIColorControls ()) { + using (var colorControlsFilter = new CIColorControls ()) { colorControlsFilter.Image = baseCIImage; colorControlsFilter.Saturation = saturation; colorControlsFilter.Brightness = brightness; result = colorControlsFilter.OutputImage; } - using(var hueAdjustFilter = new CIHueAdjust ()) { + using (var hueAdjustFilter = new CIHueAdjust ()) { hueAdjustFilter.Image = result; hueAdjustFilter.Angle = hue; result = hueAdjustFilter.OutputImage; @@ -122,7 +120,7 @@ void ApplyFilters() result.Dispose (); } - void OnSaveClicked(object sender, EventArgs e) + void OnSaveClicked (object sender, EventArgs e) { PhotoView.Image.Dispose (); PhotoView.Image = imageView.Image; @@ -130,7 +128,7 @@ void OnSaveClicked(object sender, EventArgs e) }); } - UISlider ConfiguredOverlaySlider() + UISlider ConfiguredOverlaySlider () { UISlider slider = new UISlider (); slider.TranslatesAutoresizingMaskIntoConstraints = false; @@ -139,7 +137,7 @@ UISlider ConfiguredOverlaySlider() return slider; } - void Setup() + void Setup () { imageView = new UIImageView (); imageView.ContentMode = UIViewContentMode.ScaleAspectFit; @@ -147,7 +145,7 @@ void Setup() blurEffect = UIBlurEffect.FromStyle (UIBlurEffectStyle.ExtraLight); } - void ConfigureViews() + void ConfigureViews () { View.BackgroundColor = UIColor.Clear; @@ -192,53 +190,53 @@ void ConfigureViews() foregroundContentScrollView.AddSubview (imageView); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[backgroundView]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "backgroundView", backgroundView)); - View.AddConstraints (NSLayoutConstraint.FromVisualFormat("V:|[backgroundView]|", - (NSLayoutFormatOptions)0, + View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|[backgroundView]|", + (NSLayoutFormatOptions) 0, "backgroundView", backgroundView)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[foregroundContentScrollView]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "foregroundContentScrollView", foregroundContentScrollView)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|[foregroundContentScrollView]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "foregroundContentScrollView", foregroundContentScrollView)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[foregroundContentView]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "foregroundContentView", foregroundContentView)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|[foregroundContentView]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "foregroundContentView", foregroundContentView)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[hueLabel]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "hueLabel", hueLabel)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[hueSlider]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "hueSlider", hueSlider)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[saturationLabel]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "saturationLabel", saturationLabel)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[saturationSlider]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "saturationSlider", saturationSlider)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[brightnessLabel]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "brightnessLabel", brightnessLabel)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[brightnessSlider]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "brightnessSlider", brightnessSlider)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[saveButton]-|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "saveButton", saveButton)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[imageView(==foregroundContentScrollView)]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "imageView", imageView, "foregroundContentScrollView", foregroundContentScrollView)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-(>=30)-[hueLabel]-[hueSlider]-[saturationLabel]-[saturationSlider]-[brightnessLabel]-[brightnessSlider]-[saveButton]-(>=10)-[imageView(==200)]|", - (NSLayoutFormatOptions)0, + (NSLayoutFormatOptions) 0, "hueLabel", hueLabel, "hueSlider", hueSlider, "saturationLabel", saturationLabel, @@ -249,7 +247,7 @@ void ConfigureViews() "imageView", imageView)); } - void PrepareForReuse() + void PrepareForReuse () { imageView.Image = PhotoView.Image; diff --git a/ios8/LookInside/LookInside/PhotoCollectionViewCell.cs b/ios8/LookInside/LookInside/PhotoCollectionViewCell.cs index 1a7cb38c1..0118999d0 100644 --- a/ios8/LookInside/LookInside/PhotoCollectionViewCell.cs +++ b/ios8/LookInside/LookInside/PhotoCollectionViewCell.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace LookInside -{ - public class PhotoCollectionViewCell : UICollectionViewCell - { +namespace LookInside { + public class PhotoCollectionViewCell : UICollectionViewCell { UIImageView imageView; public UIImage Image { get { @@ -21,7 +19,7 @@ public UIImage Image { } public PhotoCollectionViewCell (IntPtr handle) - : base(handle) + : base (handle) { imageView = new UIImageView (); imageView.ContentMode = UIViewContentMode.ScaleAspectFill; diff --git a/ios8/LookInside/LookInside/PresentationControllers/CoolPresentationController.cs b/ios8/LookInside/LookInside/PresentationControllers/CoolPresentationController.cs index 0c68adfe2..e24d70b0c 100644 --- a/ios8/LookInside/LookInside/PresentationControllers/CoolPresentationController.cs +++ b/ios8/LookInside/LookInside/PresentationControllers/CoolPresentationController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace LookInside -{ - public class CoolPresentationController : UIPresentationController - { +namespace LookInside { + public class CoolPresentationController : UIPresentationController { UIImageView bigFlowerImageView; UIImageView carlImageView; @@ -31,7 +29,7 @@ public override CGRect FrameOfPresentedViewInContainerView { ? 300 : containerBounds.Size.Height - 2 * jaguarPrintImageH.Size.Height; presentedViewFrame.Size = new CGSize (w, h); - var location = (CGPoint)containerBounds.Size; + var location = (CGPoint) containerBounds.Size; location.X /= 2; location.Y /= 2; location.X -= presentedViewFrame.Size.Width / 2; @@ -43,11 +41,11 @@ public override CGRect FrameOfPresentedViewInContainerView { } public CoolPresentationController (UIViewController presentedViewController, - UIViewController presentingViewController) - : base(presentedViewController, presentingViewController) + UIViewController presentingViewController) + : base (presentedViewController, presentingViewController) { dimmingView = new UIView { - BackgroundColor = UIColor.Purple.ColorWithAlpha(0.4f) + BackgroundColor = UIColor.Purple.ColorWithAlpha (0.4f) }; bigFlowerImageView = new UIImageView (UIImage.FromBundle ("BigFlower")); @@ -80,7 +78,7 @@ public override void PresentationTransitionWillBegin () MoveJaguarPrintToPresentedPosition (false); UIView.Animate (1, () => { - MoveJaguarPrintToPresentedPosition(true); + MoveJaguarPrintToPresentedPosition (true); }); } @@ -112,7 +110,7 @@ public override void DismissalTransitionWillBegin () { base.DismissalTransitionWillBegin (); - PresentedViewController.GetTransitionCoordinator().AnimateAlongsideTransition(context => { + PresentedViewController.GetTransitionCoordinator ().AnimateAlongsideTransition (context => { dimmingView.Alpha = 0; }, null); } @@ -123,7 +121,7 @@ public override void DismissalTransitionDidEnd (bool completed) Dispose (); } - void AddViewsToDimmingView() + void AddViewsToDimmingView () { if (TraitCollection.HorizontalSizeClass == UIUserInterfaceSizeClass.Regular && TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Regular) { @@ -136,7 +134,7 @@ void AddViewsToDimmingView() ContainerView.AddSubview (dimmingView); } - void MoveJaguarPrintToPresentedPosition(bool presentedPosition) + void MoveJaguarPrintToPresentedPosition (bool presentedPosition) { CGSize horizontalJaguarSize = jaguarPrintImageH.Size; CGSize verticalJaguarSize = jaguarPrintImageV.Size; @@ -159,7 +157,7 @@ void MoveJaguarPrintToPresentedPosition(bool presentedPosition) CGRect frameToAlignAround = presentedPosition ? frameOfView : containerFrame; - topFrame.Y = frameToAlignAround.GetMinY() - horizontalJaguarSize.Height; + topFrame.Y = frameToAlignAround.GetMinY () - horizontalJaguarSize.Height; bottomFrame.Y = frameToAlignAround.GetMaxY (); leftFrame.X = frameToAlignAround.GetMinX () - verticalJaguarSize.Width; rightFrame.X = frameToAlignAround.GetMaxX (); @@ -175,13 +173,13 @@ protected override void Dispose (bool disposing) bigFlowerImageView.Dispose (); bigFlowerImageView = null; - carlImageView.Dispose(); + carlImageView.Dispose (); carlImageView = null; - jaguarPrintImageH.Dispose(); + jaguarPrintImageH.Dispose (); jaguarPrintImageH = null; - jaguarPrintImageV.Dispose(); + jaguarPrintImageV.Dispose (); jaguarPrintImageV = null; topJaguarPrintImageView.Dispose (); diff --git a/ios8/LookInside/LookInside/PresentationControllers/OverlayPresentationController.cs b/ios8/LookInside/LookInside/PresentationControllers/OverlayPresentationController.cs index eb8ed0f12..6caf0947c 100644 --- a/ios8/LookInside/LookInside/PresentationControllers/OverlayPresentationController.cs +++ b/ios8/LookInside/LookInside/PresentationControllers/OverlayPresentationController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace LookInside -{ - public class OverlayPresentationController : UIPresentationController - { +namespace LookInside { + public class OverlayPresentationController : UIPresentationController { UIView dimmingView; UITapGestureRecognizer tap; @@ -36,8 +34,8 @@ public override CGRect FrameOfPresentedViewInContainerView { } public OverlayPresentationController (UIViewController presentedViewController, - UIViewController presentingViewController) - : base(presentedViewController, presentingViewController) + UIViewController presentingViewController) + : base (presentedViewController, presentingViewController) { PrepareDimmingView (); } @@ -59,11 +57,10 @@ public override void DismissalTransitionWillBegin () SetAplhaOnTransitionBegin (0); } - void SetAplhaOnTransitionBegin(float alpha) + void SetAplhaOnTransitionBegin (float alpha) { var transitionCoordinator = PresentedViewController.GetTransitionCoordinator (); - if(transitionCoordinator == null) - { + if (transitionCoordinator == null) { dimmingView.Alpha = alpha; return; } @@ -83,7 +80,7 @@ public override CGSize GetSizeForChildContentContainer (IUIContentContainer cont if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone) return parentContainerSize; else - return new CGSize(parentContainerSize.Width / 3, parentContainerSize.Height); + return new CGSize (parentContainerSize.Width / 3, parentContainerSize.Height); } public override void ContainerViewWillLayoutSubviews () @@ -94,7 +91,7 @@ public override void ContainerViewWillLayoutSubviews () PresentedView.Frame = FrameOfPresentedViewInContainerView; } - void PrepareDimmingView() + void PrepareDimmingView () { dimmingView = new UIView (); dimmingView.BackgroundColor = UIColor.FromWhiteAlpha (0, 0.4f); @@ -104,7 +101,7 @@ void PrepareDimmingView() dimmingView.AddGestureRecognizer (tap); } - void DimmingViewTapped(UIGestureRecognizer gesture) + void DimmingViewTapped (UIGestureRecognizer gesture) { if (gesture.State == UIGestureRecognizerState.Recognized) PresentingViewController.DismissViewController (true, null); diff --git a/ios8/LookInside/LookInside/RootViewController.cs b/ios8/LookInside/LookInside/RootViewController.cs index bb072a89d..bde1fa58d 100644 --- a/ios8/LookInside/LookInside/RootViewController.cs +++ b/ios8/LookInside/LookInside/RootViewController.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Globalization; using UIKit; using Foundation; using CoreGraphics; -namespace LookInside -{ - public class RootViewController : UICollectionViewController, IUICollectionViewDataSource - { +namespace LookInside { + public class RootViewController : UICollectionViewController, IUICollectionViewDataSource { static readonly nint kNumberOfViews = 37; static readonly nfloat kViewsWide = 5; static readonly nfloat kViewMargin = 2; - static readonly NSString kCellReuseIdentifier = new NSString("CellReuseIdentifier"); + static readonly NSString kCellReuseIdentifier = new NSString ("CellReuseIdentifier"); CoolTransitioningDelegate coolTransitioningDelegate; OverlayTransitioningDelegate overlayTransitioningDelegate; @@ -30,7 +28,7 @@ private set { } public RootViewController () - : base(new UICollectionViewFlowLayout()) + : base (new UICollectionViewFlowLayout ()) { ConfigureTitleBar (); } @@ -39,9 +37,9 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - CollectionView.RegisterClassForCell(typeof(PhotoCollectionViewCell), kCellReuseIdentifier); + CollectionView.RegisterClassForCell (typeof (PhotoCollectionViewCell), kCellReuseIdentifier); CollectionView.BackgroundColor = null; - var layout = (UICollectionViewFlowLayout)Layout; + var layout = (UICollectionViewFlowLayout) Layout; layout.MinimumInteritemSpacing = kViewMargin; layout.MinimumLineSpacing = kViewMargin; @@ -61,7 +59,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (PhotoCollectionViewCell)collectionView.DequeueReusableCell (kCellReuseIdentifier, indexPath); + var cell = (PhotoCollectionViewCell) collectionView.DequeueReusableCell (kCellReuseIdentifier, indexPath); string photoName = indexPath.Item.ToString (CultureInfo.InvariantCulture); UIImage photo = UIImage.FromBundle (photoName); @@ -80,7 +78,7 @@ public override void ItemSelected (UICollectionView collectionView, NSIndexPath overlay.TransitioningDelegate = coolTransitioningDelegate; else overlay.TransitioningDelegate = overlayTransitioningDelegate; - overlay.PhotoView = (PhotoCollectionViewCell)CollectionView.CellForItem (indexPath); + overlay.PhotoView = (PhotoCollectionViewCell) CollectionView.CellForItem (indexPath); PresentViewController (overlay, true, null); } @@ -92,11 +90,11 @@ public override void ViewWillTransitionToSize (CGSize toSize, IUIViewControllerT nfloat itemWidth = toSize.Width / kViewsWide; itemWidth -= kViewMargin; - ((UICollectionViewFlowLayout)CollectionView.CollectionViewLayout).ItemSize = new CGSize(itemWidth, itemWidth); + ((UICollectionViewFlowLayout) CollectionView.CollectionViewLayout).ItemSize = new CGSize (itemWidth, itemWidth); Layout.InvalidateLayout (); } - void ConfigureTitleBar() + void ConfigureTitleBar () { Title = "LookInside Photos"; EdgesForExtendedLayout = UIRectEdge.Left | UIRectEdge.Bottom | UIRectEdge.Right; diff --git a/ios8/LookInside/LookInside/Transitioner/CoolAnimatedTransitioning.cs b/ios8/LookInside/LookInside/Transitioner/CoolAnimatedTransitioning.cs index ef9140c02..21d81c2e7 100644 --- a/ios8/LookInside/LookInside/Transitioner/CoolAnimatedTransitioning.cs +++ b/ios8/LookInside/LookInside/Transitioner/CoolAnimatedTransitioning.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace LookInside -{ - public class CoolAnimatedTransitioning : UIViewControllerAnimatedTransitioning - { +namespace LookInside { + public class CoolAnimatedTransitioning : UIViewControllerAnimatedTransitioning { public bool IsPresentation { get; set; } public CoolAnimatedTransitioning () @@ -29,13 +27,13 @@ public async override void AnimateTransition (IUIViewControllerContextTransition if (IsPresentation) containerView.AddSubview (toView); - UIViewController animatingVC = IsPresentation? toVC : fromVC; + UIViewController animatingVC = IsPresentation ? toVC : fromVC; UIView animatingView = animatingVC.View; animatingView.Frame = transitionContext.GetFinalFrameForViewController (animatingVC); CGAffineTransform presentedTransform = CGAffineTransform.MakeIdentity (); - CGAffineTransform dismissedTransform = CGAffineTransform.MakeScale (0.001f, 0.001f) * CGAffineTransform.MakeRotation (8 * (float)Math.PI); + CGAffineTransform dismissedTransform = CGAffineTransform.MakeScale (0.001f, 0.001f) * CGAffineTransform.MakeRotation (8 * (float) Math.PI); animatingView.Transform = IsPresentation ? dismissedTransform : presentedTransform; diff --git a/ios8/LookInside/LookInside/Transitioner/CoolTransitioningDelegate.cs b/ios8/LookInside/LookInside/Transitioner/CoolTransitioningDelegate.cs index 5eccd6e95..521c46941 100644 --- a/ios8/LookInside/LookInside/Transitioner/CoolTransitioningDelegate.cs +++ b/ios8/LookInside/LookInside/Transitioner/CoolTransitioningDelegate.cs @@ -4,10 +4,8 @@ using UIKit; using Foundation; -namespace LookInside -{ - public class CoolTransitioningDelegate : UIViewControllerTransitioningDelegate - { +namespace LookInside { + public class CoolTransitioningDelegate : UIViewControllerTransitioningDelegate { UIPresentationController presentationController; CoolAnimatedTransitioning present, dismiss; diff --git a/ios8/LookInside/LookInside/Transitioner/OverlayAnimatedTransitioning.cs b/ios8/LookInside/LookInside/Transitioner/OverlayAnimatedTransitioning.cs index c7c01ddfd..325367c75 100644 --- a/ios8/LookInside/LookInside/Transitioner/OverlayAnimatedTransitioning.cs +++ b/ios8/LookInside/LookInside/Transitioner/OverlayAnimatedTransitioning.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; -namespace LookInside -{ - public class OverlayAnimatedTransitioning : UIViewControllerAnimatedTransitioning - { +namespace LookInside { + public class OverlayAnimatedTransitioning : UIViewControllerAnimatedTransitioning { public bool IsPresentation { get; set; } public OverlayAnimatedTransitioning () @@ -41,7 +39,7 @@ public async override void AnimateTransition (IUIViewControllerContextTransition animatingView.Frame = initialFrame; UIViewAnimationOptions opt = UIViewAnimationOptions.AllowUserInteraction - | UIViewAnimationOptions.BeginFromCurrentState; + | UIViewAnimationOptions.BeginFromCurrentState; await UIView.AnimateNotifyAsync (TransitionDuration (transitionContext), 0, 300, 5, opt, () => { animatingView.Frame = finalFrame; }); diff --git a/ios8/LookInside/LookInside/Transitioner/OverlayTransitioningDelegate.cs b/ios8/LookInside/LookInside/Transitioner/OverlayTransitioningDelegate.cs index 9ed8fb262..83ecb1a16 100644 --- a/ios8/LookInside/LookInside/Transitioner/OverlayTransitioningDelegate.cs +++ b/ios8/LookInside/LookInside/Transitioner/OverlayTransitioningDelegate.cs @@ -4,10 +4,8 @@ using UIKit; using Foundation; -namespace LookInside -{ - public class OverlayTransitioningDelegate : UIViewControllerTransitioningDelegate - { +namespace LookInside { + public class OverlayTransitioningDelegate : UIViewControllerTransitioningDelegate { UIPresentationController presentationController; OverlayAnimatedTransitioning present, dismiss; diff --git a/ios8/MetalBasic3D/MetalBasic3D/AppDelegate.cs b/ios8/MetalBasic3D/MetalBasic3D/AppDelegate.cs index f09ab23e2..eb387a658 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/AppDelegate.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace MetalBasic3D -{ +namespace MetalBasic3D { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { @@ -45,7 +43,7 @@ public override void WillTerminate (UIApplication application) public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { - GameViewController controller = (GameViewController)Window.RootViewController; + GameViewController controller = (GameViewController) Window.RootViewController; if (controller == null) { Console.WriteLine ("ERROR: Failed creating a view controller!"); @@ -55,7 +53,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary var renderer = new Renderer (); controller.Delegate = renderer; - GameView renderView = (GameView)controller.View; + GameView renderView = (GameView) controller.View; if (renderView == null) { Console.WriteLine ("ERROR: Failed creating a renderer view!"); diff --git a/ios8/MetalBasic3D/MetalBasic3D/GameView.cs b/ios8/MetalBasic3D/MetalBasic3D/GameView.cs index 06f78cc26..bc8b4416a 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/GameView.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/GameView.cs @@ -9,23 +9,21 @@ using ObjCRuntime; using UIKit; -namespace MetalBasic3D -{ +namespace MetalBasic3D { [Register ("GameView")] - public class GameView : UIView - { + public class GameView : UIView { [Export ("layerClass")] public static Class LayerClass () { - return new Class (typeof(CAMetalLayer)); + return new Class (typeof (CAMetalLayer)); } bool layerSizeDidUpdate; IMTLTexture depthTex; - #pragma warning disable 649 +#pragma warning disable 649 IMTLTexture stencilTex; - #pragma warning restore 649 +#pragma warning restore 649 IMTLTexture msaaTex; CAMetalLayer metalLayer; @@ -56,7 +54,7 @@ public GameView (IntPtr handle) : base (handle) Opaque = true; BackgroundColor = UIColor.Clear; - metalLayer = (CAMetalLayer)Layer; + metalLayer = (CAMetalLayer) Layer; ContentScaleFactor = UIScreen.MainScreen.Scale; metalLayer.PresentsWithTransaction = false; metalLayer.DrawsAsynchronously = true; diff --git a/ios8/MetalBasic3D/MetalBasic3D/GameViewController.cs b/ios8/MetalBasic3D/MetalBasic3D/GameViewController.cs index 44f0c5d36..a2da8a7bb 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/GameViewController.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/GameViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.InteropServices; using System.Threading; @@ -9,11 +9,9 @@ using Metal; using UIKit; -namespace MetalBasic3D -{ +namespace MetalBasic3D { [Register ("GameViewController")] - public class GameViewController : UIViewController - { + public class GameViewController : UIViewController { CADisplayLink timer; double timeSinceLastDrawPreviousTime; bool lastDrawOccurred; @@ -76,7 +74,7 @@ public void Gameloop () timeSinceLastDrawPreviousTime = currentTime; } - ((GameView)View).Display (); + ((GameView) View).Display (); Delegate.RenderViewControllerUpdate (this); } diff --git a/ios8/MetalBasic3D/MetalBasic3D/IGameView.cs b/ios8/MetalBasic3D/MetalBasic3D/IGameView.cs index 1b3d73cb2..2b0829f98 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/IGameView.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/IGameView.cs @@ -1,9 +1,7 @@ -using System; +using System; -namespace MetalBasic3D -{ - public interface IGameView - { +namespace MetalBasic3D { + public interface IGameView { void Reshape (GameView view); void Render (GameView view); diff --git a/ios8/MetalBasic3D/MetalBasic3D/IGameViewController.cs b/ios8/MetalBasic3D/MetalBasic3D/IGameViewController.cs index a3a627393..1d89c64d4 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/IGameViewController.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/IGameViewController.cs @@ -1,9 +1,7 @@ using System; -namespace MetalBasic3D -{ - public interface IGameViewController - { +namespace MetalBasic3D { + public interface IGameViewController { void RenderViewControllerUpdate (GameViewController gameViewController); void RenderViewController (GameViewController gameViewController, bool value); diff --git a/ios8/MetalBasic3D/MetalBasic3D/Main.cs b/ios8/MetalBasic3D/MetalBasic3D/Main.cs index 1a8e14432..3f71c8035 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/Main.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MetalBasic3D -{ - public class Application - { +namespace MetalBasic3D { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/MetalBasic3D/MetalBasic3D/Renderer.cs b/ios8/MetalBasic3D/MetalBasic3D/Renderer.cs index 1230f8ad0..224715732 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/Renderer.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/Renderer.cs @@ -1,4 +1,4 @@ -using System; +using System; using Metal; using OpenTK; using System.Threading; @@ -6,10 +6,8 @@ using System.Runtime.InteropServices; using CoreAnimation; -namespace MetalBasic3D -{ - public class Renderer : IGameViewController, IGameView - { +namespace MetalBasic3D { + public class Renderer : IGameViewController, IGameView { const int max_inflight_buffers = 3; const int max_bytes_per_frame = 1024 * 1024; @@ -29,7 +27,7 @@ public class Renderer : IGameViewController, IGameView const float height = 1f; const float depth = 1f; - float[] cubeVertexData = new float [216] { + float [] cubeVertexData = new float [216] { width, -height, depth, 0.0f, -1.0f, 0.0f, -width, -height, depth, 0.0f, -1.0f, 0.0f, -width, -height, -depth, 0.0f, -1.0f, 0.0f, @@ -83,7 +81,7 @@ public class Renderer : IGameViewController, IGameView IMTLLibrary defaultLibrary; Semaphore inflightSemaphore; - IMTLBuffer[] dynamicConstantBuffer; + IMTLBuffer [] dynamicConstantBuffer; // render stage IMTLRenderPipelineState pipelineState; @@ -94,7 +92,7 @@ public class Renderer : IGameViewController, IGameView Matrix4 projectionMatrix; Matrix4 viewMatrix; - Uniforms[] constantBuffer; + Uniforms [] constantBuffer; int multiplier; public IMTLDevice Device { get; private set; } @@ -121,7 +119,7 @@ public Renderer () constantDataBufferIndex = 0; inflightSemaphore = new Semaphore (max_inflight_buffers, max_inflight_buffers); - constantBuffer = new Uniforms[2]; + constantBuffer = new Uniforms [2]; constantBuffer [0].ambientColor = box1AmbientColor; constantBuffer [0].diffuseColor = box1DiffuseColor; @@ -158,7 +156,7 @@ public void RenderViewControllerUpdate (GameViewController gameViewController) constantBuffer [1].ambientColor.Y += multiplier * 0.01f; } - rotation += (float)gameViewController.TimeSinceLastDraw; + rotation += (float) gameViewController.TimeSinceLastDraw; } public void RenderViewController (GameViewController gameViewController, bool value) @@ -169,7 +167,7 @@ public void RenderViewController (GameViewController gameViewController, bool va public void Reshape (GameView view) { - var aspect = (float)(view.Bounds.Size.Width / view.Bounds.Size.Height); + var aspect = (float) (view.Bounds.Size.Width / view.Bounds.Size.Height); projectionMatrix = CreateMatrixFromPerspective (FOVY, aspect, 0.1f, 100.0f); viewMatrix = LookAt (eye, center, up); } @@ -191,7 +189,7 @@ public void Render (GameView view) renderEncoder.SetDepthStencilState (depthState); RenderBox (renderEncoder, view, 0, "Box1"); - RenderBox (renderEncoder, view, (nuint)Marshal.SizeOf<Uniforms> (), "Box2"); + RenderBox (renderEncoder, view, (nuint) Marshal.SizeOf<Uniforms> (), "Box2"); renderEncoder.EndEncoding (); commandBuffer.AddCompletedHandler ((IMTLCommandBuffer buffer) => { @@ -211,7 +209,7 @@ public void Configure (GameView view) view.StencilPixelFormat = stencilPixelFormat; view.SampleCount = sampleCount; - dynamicConstantBuffer = new IMTLBuffer[max_inflight_buffers]; + dynamicConstantBuffer = new IMTLBuffer [max_inflight_buffers]; // allocate one region of memory for the constant buffer for (int i = 0; i < max_inflight_buffers; i++) { @@ -257,8 +255,8 @@ public void Configure (GameView view) void PrepareToDraw () { - int rawsize = 2 * Marshal.SizeOf <Uniforms> (); - byte[] rawdata = new byte[rawsize]; + int rawsize = 2 * Marshal.SizeOf<Uniforms> (); + byte [] rawdata = new byte [rawsize]; GCHandle pinnedArray = GCHandle.Alloc (constantBuffer, GCHandleType.Pinned); IntPtr ptr = pinnedArray.AddrOfPinnedObject (); @@ -284,7 +282,7 @@ void RenderBox (IMTLRenderCommandEncoder renderEncoder, GameView view, nuint off Matrix4 CreateMatrixFromPerspective (float fovY, float aspect, float near, float far) { - float yscale = 1.0f / (float)Math.Tan (fovY * 0.5f); + float yscale = 1.0f / (float) Math.Tan (fovY * 0.5f); float xscale = yscale / aspect; float zScale = far / (far - near); @@ -311,8 +309,8 @@ Matrix4 CreateMatrixFromTranslation (float x, float y, float z) Matrix4 CreateMatrixFromRotation (float radians, float x, float y, float z) { Vector3 v = Vector3.Normalize (new Vector3 (x, y, z)); - var cos = (float)Math.Cos (radians); - var sin = (float)Math.Sin (radians); + var cos = (float) Math.Cos (radians); + var sin = (float) Math.Sin (radians); float cosp = 1.0f - cos; var m = new Matrix4 { diff --git a/ios8/MetalBasic3D/MetalBasic3D/Uniforms.cs b/ios8/MetalBasic3D/MetalBasic3D/Uniforms.cs index 555398190..a2e73f967 100644 --- a/ios8/MetalBasic3D/MetalBasic3D/Uniforms.cs +++ b/ios8/MetalBasic3D/MetalBasic3D/Uniforms.cs @@ -3,10 +3,8 @@ using OpenTK; using System.Threading; -namespace MetalBasic3D -{ - struct Uniforms - { +namespace MetalBasic3D { + struct Uniforms { public Matrix4 modelviewProjectionMatrix; public Matrix4 normalMatrix; public Vector4 ambientColor; diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/AppDelegate.cs b/ios8/MetalImageProcessing/MetalImageProcessing/AppDelegate.cs index 8a7d72577..5161e321e 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/AppDelegate.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/AppDelegate.cs @@ -1,17 +1,15 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MetalImageProcessing -{ +namespace MetalImageProcessing { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/ImageView.cs b/ios8/MetalImageProcessing/MetalImageProcessing/ImageView.cs index 854108aa3..06bef607c 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/ImageView.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/ImageView.cs @@ -9,14 +9,12 @@ using Metal; using CoreGraphics; -namespace MetalImageProcessing -{ - public partial class ImageView : UIView - { +namespace MetalImageProcessing { + public partial class ImageView : UIView { [Export ("layerClass")] public static Class LayerClass () { - return new Class (typeof(CAMetalLayer)); + return new Class (typeof (CAMetalLayer)); } IMTLDevice device; @@ -51,7 +49,7 @@ public ImageView (IntPtr handle) : base (handle) Opaque = true; BackgroundColor = UIColor.Clear; - metalLayer = (CAMetalLayer)Layer; + metalLayer = (CAMetalLayer) Layer; device = MTLDevice.SystemDefault; @@ -135,29 +133,29 @@ void SetupRenderPassDescriptorForTexture (IMTLTexture texture) } if (DepthPixelFormat != MTLPixelFormat.Invalid && (depthTex == null || NeedUpdate (texture, depthTex))) { - var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (DepthPixelFormat, texture.Width, texture.Height, false); - desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; - desc.SampleCount = SampleCount; - depthTex = device.CreateTexture (desc); - - MTLRenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.DepthAttachment; - depthAttachment.Texture = depthTex; - depthAttachment.LoadAction = MTLLoadAction.Clear; - depthAttachment.StoreAction = MTLStoreAction.DontCare; - depthAttachment.ClearDepth = 1.0; + var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (DepthPixelFormat, texture.Width, texture.Height, false); + desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; + desc.SampleCount = SampleCount; + depthTex = device.CreateTexture (desc); + + MTLRenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.DepthAttachment; + depthAttachment.Texture = depthTex; + depthAttachment.LoadAction = MTLLoadAction.Clear; + depthAttachment.StoreAction = MTLStoreAction.DontCare; + depthAttachment.ClearDepth = 1.0; } if (StencilPixelFormat != MTLPixelFormat.Invalid && (stencilTex == null || NeedUpdate (texture, stencilTex))) { - var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (StencilPixelFormat, texture.Width, texture.Height, false); - desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; - desc.SampleCount = SampleCount; - stencilTex = device.CreateTexture (desc); - - MTLRenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.StencilAttachment; - stencilAttachment.Texture = stencilTex; - stencilAttachment.LoadAction = MTLLoadAction.Clear; - stencilAttachment.StoreAction = MTLStoreAction.DontCare; - stencilAttachment.ClearStencil = 0; + var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (StencilPixelFormat, texture.Width, texture.Height, false); + desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; + desc.SampleCount = SampleCount; + stencilTex = device.CreateTexture (desc); + + MTLRenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.StencilAttachment; + stencilAttachment.Texture = stencilTex; + stencilAttachment.LoadAction = MTLLoadAction.Clear; + stencilAttachment.StoreAction = MTLStoreAction.DontCare; + stencilAttachment.ClearStencil = 0; } } diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/ImageViewController.cs b/ios8/MetalImageProcessing/MetalImageProcessing/ImageViewController.cs index ee5bb3e76..d5f51ec52 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/ImageViewController.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/ImageViewController.cs @@ -6,17 +6,15 @@ using UIKit; using CoreAnimation; -namespace MetalImageProcessing -{ - public partial class ImageViewController : UIViewController - { +namespace MetalImageProcessing { + public partial class ImageViewController : UIViewController { CADisplayLink timer; double timeSinceLastDrawPreviousTime; bool gameLoopPaused; bool firstDrawOccurred; - #pragma warning disable 414 +#pragma warning disable 414 double timeSinceLastDraw; - #pragma warning restore 414 +#pragma warning restore 414 Renderer renderer; @@ -64,7 +62,7 @@ public void Gameloop () timeSinceLastDrawPreviousTime = currentTime; } - ((ImageView)View).Display (); + ((ImageView) View).Display (); } public override void ViewDidLoad () @@ -72,7 +70,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); renderer = new Renderer (); - var renderView = (ImageView)View; + var renderView = (ImageView) View; renderView.Renderer = renderer; // load all renderer assets before starting game loop diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/Main.cs b/ios8/MetalImageProcessing/MetalImageProcessing/Main.cs index 896e310ec..9bd422dbb 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/Main.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MetalImageProcessing -{ - public class Application - { +namespace MetalImageProcessing { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/MathUtils.cs b/ios8/MetalImageProcessing/MetalImageProcessing/MathUtils.cs index 7a22fd887..52a839cba 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/MathUtils.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/MathUtils.cs @@ -1,10 +1,8 @@ -using System; +using System; using OpenTK; -namespace MetalImageProcessing -{ - public static class MathUtils - { +namespace MetalImageProcessing { + public static class MathUtils { public static Matrix4 SwapColumnsAndRows (this Matrix4 matrix) { return new Matrix4 (matrix.Column0, matrix.Column1, matrix.Column2, matrix.Column3); @@ -12,7 +10,7 @@ public static Matrix4 SwapColumnsAndRows (this Matrix4 matrix) public static Matrix4 Scale (float x, float y, float z) { - return new Matrix4 (x, 0f, 0f, 0f, 0f, y, 0f, 0f, 0f, 0f, z, 0f, 0f, 0f, 0f, 1f); + return new Matrix4 (x, 0f, 0f, 0f, 0f, y, 0f, 0f, 0f, 0f, z, 0f, 0f, 0f, 0f, 1f); } public static Matrix4 Translate (Vector3 t) @@ -37,8 +35,8 @@ public static float RadiansOverPi (float degrees) public static Matrix4 Rotate (float angle, Vector3 r) { float a = RadiansOverPi (angle); - float c = (float)Math.Cos (a); - float s = (float)Math.Sin (a); + float c = (float) Math.Cos (a); + float s = (float) Math.Sin (a); float k = 1.0f - c; r.Normalize (); @@ -95,7 +93,7 @@ public static Matrix4 Perspective (float width, float height, float near, float public static Matrix4 PerspectiveFov (float fovy, float aspect, float near, float far) { float angle = Radians (0.5f * fovy); - float yScale = 1f / (float)Math.Tan (angle); + float yScale = 1f / (float) Math.Tan (angle); float xScale = yScale / aspect; float zScale = far / (far - near); @@ -212,8 +210,8 @@ public static Matrix4 Ortho2dOc (Vector3 origin, Vector3 size) public static Matrix4 Frustrum (float fovH, float fovV, float near, float far) { - float width = 1f / (float)Math.Tan (Radians (0.5f * fovH)); - float height = 1f / (float)Math.Tan (Radians (0.5f * fovV)); + float width = 1f / (float) Math.Tan (Radians (0.5f * fovH)); + float height = 1f / (float) Math.Tan (Radians (0.5f * fovV)); float sDepth = far / (far - near); Vector4 P = Vector4.Zero; @@ -276,7 +274,7 @@ public static Matrix4 FrustrumOc (float left, float right, float bottom, float t public static float Radians (float degrees) { - return 1.0f / 180.0f * (float)Math.PI * degrees; + return 1.0f / 180.0f * (float) Math.PI * degrees; } public static Matrix4 MakeResultMatrix (Vector4 column0, Vector4 column1, Vector4 column2, Vector4 column3) diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/Quad.cs b/ios8/MetalImageProcessing/MetalImageProcessing/Quad.cs index a32eb0691..400729ca4 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/Quad.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/Quad.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Runtime.InteropServices; using CoreGraphics; using Foundation; using Metal; using OpenTK; -namespace MetalImageProcessing -{ - public class Quad : NSObject - { +namespace MetalImageProcessing { + public class Quad : NSObject { // textured Quad IMTLBuffer vertexBuffer; IMTLBuffer texCoordBuffer; @@ -19,7 +17,7 @@ public class Quad : NSObject // Dimensions CGRect bounds; - readonly Vector4[] quadVertices = new Vector4 [] { + readonly Vector4 [] quadVertices = new Vector4 [] { new Vector4 (-1f, -1f, 0f, 1f), new Vector4 (1f, -1f, 0f, 1f), new Vector4 (-1f, 1f, 0f, 1f), @@ -29,7 +27,7 @@ public class Quad : NSObject new Vector4 (1f, 1f, 0f, 1f) }; - readonly Vector2[] quadTexCoords = new Vector2 [] { + readonly Vector2 [] quadTexCoords = new Vector2 [] { new Vector2 (0f, 0f), new Vector2 (1f, 0f), new Vector2 (0f, 1f), @@ -45,7 +43,7 @@ public class Quad : NSObject public CGSize Size { get; set; } - public nfloat Aspect { get; set; } + public nfloat Aspect { get; set; } public CGRect Bounds { get { @@ -93,11 +91,11 @@ void UpdateBounds () { Aspect = bounds.Size.Width / bounds.Size.Height; - float aspect = 1.0f / (float)Aspect; + float aspect = 1.0f / (float) Aspect; Vector2 localScale = Vector2.Zero; - localScale.X = (float)(aspect * Size.Width / Bounds.Size.Width); - localScale.Y = (float)(Size.Height / Bounds.Size.Height); + localScale.X = (float) (aspect * Size.Width / Bounds.Size.Width); + localScale.Y = (float) (Size.Height / Bounds.Size.Height); // Did the scaling factor change bool newScale = (scale.X != localScale.X) || (scale.Y != localScale.Y); @@ -108,10 +106,10 @@ void UpdateBounds () // Update the scaling factor scale = localScale; - var vertices = new Vector4[quadVertices.Length]; + var vertices = new Vector4 [quadVertices.Length]; IntPtr contentPtr = vertexBuffer.Contents; for (int i = 0; i < vertices.Length; i++) { - vertices [i] = (Vector4)Marshal.PtrToStructure (contentPtr, typeof(Vector4)); + vertices [i] = (Vector4) Marshal.PtrToStructure (contentPtr, typeof (Vector4)); contentPtr += Marshal.SizeOf<Vector4> (); } @@ -135,8 +133,8 @@ void UpdateBounds () vertices [5].X = scale.X; vertices [5].Y = scale.Y; - int rawsize = quadVertices.Length * Marshal.SizeOf <Vector4> (); - var rawdata = new byte[rawsize]; + int rawsize = quadVertices.Length * Marshal.SizeOf<Vector4> (); + var rawdata = new byte [rawsize]; GCHandle pinnedTransform = GCHandle.Alloc (vertices, GCHandleType.Pinned); IntPtr ptr = pinnedTransform.AddrOfPinnedObject (); Marshal.Copy (ptr, rawdata, 0, rawsize); diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/Renderer.cs b/ios8/MetalImageProcessing/MetalImageProcessing/Renderer.cs index 5692d0351..d14d79329 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/Renderer.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/Renderer.cs @@ -8,10 +8,8 @@ using OpenTK; using UIKit; -namespace MetalImageProcessing -{ - public class Renderer - { +namespace MetalImageProcessing { + public class Renderer { const float interfaceOrientationLandscapeAngle = 35.0f; const float interfaceOrientationPortraitAngle = 50.0f; const float prespectiveNear = 0.1f; @@ -25,7 +23,7 @@ public class Renderer Quad mpQuad; // Interface Orientation - UIInterfaceOrientation mnOrientation; + UIInterfaceOrientation mnOrientation; Semaphore inflightSemaphore; // Renderer globals @@ -43,10 +41,10 @@ public class Renderer IMTLTexture outTexture; IMTLRenderPipelineState pipelineState; - #pragma warning disable 649 +#pragma warning disable 649 // Dimensions CGSize size; - #pragma warning restore 649 +#pragma warning restore 649 // Viewing matrix is derived from an eye point, a reference point // indicating the center of the scene, and an up vector. @@ -170,22 +168,22 @@ public void Configure (ImageView renderView) // we need to set the framebuffer only property of the layer to NO so we // can perform compute on the drawable's texture - var metalLayer = (CAMetalLayer)renderView.Layer; + var metalLayer = (CAMetalLayer) renderView.Layer; metalLayer.FramebufferOnly = false; - if(!PreparePipelineState ()) + if (!PreparePipelineState ()) throw new ApplicationException ("ERROR: Failed creating a depth stencil state descriptor!"); - if(!PrepareTexturedQuad ("Default", "jpg")) + if (!PrepareTexturedQuad ("Default", "jpg")) throw new ApplicationException ("ERROR: Failed creating a textured quad!"); - if(!PrepareCompute ()) + if (!PrepareCompute ()) throw new ApplicationException ("ERROR: Failed creating a compute stage!"); - if(!PrepareDepthStencilState ()) + if (!PrepareDepthStencilState ()) throw new ApplicationException ("ERROR: Failed creating a depth stencil state!"); - if(!PrepareTransformBuffer ()) + if (!PrepareTransformBuffer ()) throw new ApplicationException ("ERROR: Failed creating a transform buffer!"); // Default orientation is unknown @@ -200,13 +198,13 @@ bool PreparePipelineState () // get the fragment function from the library IMTLFunction fragmentProgram = shaderLibrary.CreateFunction ("texturedQuadFragment"); - if(fragmentProgram == null) + if (fragmentProgram == null) Console.WriteLine ("ERROR: Couldn't load fragment function from default library"); // get the vertex function from the library IMTLFunction vertexProgram = shaderLibrary.CreateFunction ("texturedQuadVertex"); - if(vertexProgram == null) + if (vertexProgram == null) Console.WriteLine ("ERROR: Couldn't load vertex function from default library"); // create a pipeline state for the quad @@ -218,12 +216,12 @@ bool PreparePipelineState () FragmentFunction = fragmentProgram }; - quadPipelineStateDescriptor.ColorAttachments[0].PixelFormat = MTLPixelFormat.BGRA8Unorm; + quadPipelineStateDescriptor.ColorAttachments [0].PixelFormat = MTLPixelFormat.BGRA8Unorm; NSError error; pipelineState = device.CreateRenderPipelineState (quadPipelineStateDescriptor, out error); - if(pipelineState == null) { + if (pipelineState == null) { Console.WriteLine ("ERROR: Failed acquiring pipeline state descriptor: %@", error.Description); return false; } @@ -237,7 +235,7 @@ bool PrepareTexturedQuad (string texStr, string extStr) bool isAcquired = mpInTexture.Finalize (device); mpInTexture.MetalTexture.Label = texStr; - if(!isAcquired) { + if (!isAcquired) { Console.WriteLine ("ERROR: Failed creating an input 2d texture!"); return false; } @@ -258,42 +256,42 @@ bool PrepareCompute () // Create a compute kernel function IMTLFunction function = shaderLibrary.CreateFunction ("grayscale"); - if(function == null) { + if (function == null) { Console.WriteLine ("ERROR: Failed creating a new function!"); return false; } // Create a compute kernel kernel = device.CreateComputePipelineState (function, out error); - if(kernel == null) { + if (kernel == null) { Console.WriteLine ("ERROR: Failed creating a compute kernel: %@", error.Description); return false; } - MTLTextureDescriptor texDesc = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.RGBA8Unorm, (nuint)size.Width, (nuint)size.Height, false); - if(texDesc == null) { + MTLTextureDescriptor texDesc = MTLTextureDescriptor.CreateTexture2DDescriptor (MTLPixelFormat.RGBA8Unorm, (nuint) size.Width, (nuint) size.Height, false); + if (texDesc == null) { Console.WriteLine ("ERROR: Failed creating a texture 2d descriptor with RGBA unnormalized pixel format!"); return false; } outTexture = device.CreateTexture (texDesc); - if(outTexture == null) { + if (outTexture == null) { Console.WriteLine ("ERROR: Failed creating an output 2d texture!"); return false; } // Set the compute kernel's workgroup size and count workgroupSize = new MTLSize (1, 1, 1); - localCount = new MTLSize ((nint)size.Width, (nint)size.Height, 1); + localCount = new MTLSize ((nint) size.Width, (nint) size.Height, 1); return true; } bool PrepareTransformBuffer () { // allocate regions of memory for the constant buffer - transformBuffer = device.CreateBuffer ((nuint)Marshal.SizeOf<Matrix4> (), MTLResourceOptions.CpuCacheModeDefault); + transformBuffer = device.CreateBuffer ((nuint) Marshal.SizeOf<Matrix4> (), MTLResourceOptions.CpuCacheModeDefault); - if(transformBuffer == null) + if (transformBuffer == null) return false; transformBuffer.Label = "TransformBuffer"; @@ -343,8 +341,7 @@ float GetActualAngle (UIInterfaceOrientation orientation, CGRect bounds) // through the camera position and the bottom of your screen. float dangle = 0.0f; - switch(mnOrientation) - { + switch (mnOrientation) { case UIInterfaceOrientation.LandscapeLeft: case UIInterfaceOrientation.LandscapeRight: dangle = interfaceOrientationLandscapeAngle; @@ -365,9 +362,9 @@ void CreateMatrix (float angle) float near = prespectiveNear; float far = prespectiveFar; float rangle = MathUtils.Radians (angle); - float length = near * (float)Math.Tan (rangle); + float length = near * (float) Math.Tan (rangle); - float right = length / (float)mpQuad.Aspect; + float right = length / (float) mpQuad.Aspect; float left = -right; float top = length; float bottom = -top; @@ -385,8 +382,8 @@ void CreateMatrix (float angle) void UpdateBuffer () { // Update the buffer associated with the linear _transformation matrix - int rawsize = Marshal.SizeOf <Matrix4> (); - var rawdata = new byte[rawsize]; + int rawsize = Marshal.SizeOf<Matrix4> (); + var rawdata = new byte [rawsize]; GCHandle pinnedTransform = GCHandle.Alloc (transform, GCHandleType.Pinned); IntPtr ptr = pinnedTransform.AddrOfPinnedObject (); diff --git a/ios8/MetalImageProcessing/MetalImageProcessing/Texture.cs b/ios8/MetalImageProcessing/MetalImageProcessing/Texture.cs index 7feb3d59c..4e1e8d29d 100644 --- a/ios8/MetalImageProcessing/MetalImageProcessing/Texture.cs +++ b/ios8/MetalImageProcessing/MetalImageProcessing/Texture.cs @@ -7,13 +7,11 @@ using OpenTK; using UIKit; -namespace MetalImageProcessing -{ - public class Texture : NSObject - { +namespace MetalImageProcessing { + public class Texture : NSObject { public nint Height { get; private set; } - public nint Width { get; private set; } + public nint Width { get; private set; } public IMTLTexture MetalTexture { get; private set; } @@ -47,17 +45,17 @@ public bool Finalize (IMTLDevice device) Width = image.CGImage.Width; Height = image.CGImage.Height; - nuint width = (nuint)Width; - nuint height = (nuint)Height; + nuint width = (nuint) Width; + nuint height = (nuint) Height; nuint rowBytes = width * 4; var context = new CGBitmapContext (IntPtr.Zero, - (int)width, - (int)height, - 8, - (int)rowBytes, - colorSpace, - CGImageAlphaInfo.PremultipliedLast); + (int) width, + (int) height, + 8, + (int) rowBytes, + colorSpace, + CGImageAlphaInfo.PremultipliedLast); if (context == null) return false; @@ -90,8 +88,8 @@ public bool Finalize (IMTLDevice device) var region = new MTLRegion (); region.Origin.X = 0; region.Origin.Y = 0; - region.Size.Width = (nint)width; - region.Size.Height = (nint)height; + region.Size.Width = (nint) width; + region.Size.Height = (nint) height; MetalTexture.ReplaceRegion (region, 0, pixels, rowBytes); } diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/AppDelegate.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/AppDelegate.cs index ab27445fb..8d7e49202 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/AppDelegate.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/AppDelegate.cs @@ -1,17 +1,15 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MetalTexturedQuad -{ +namespace MetalTexturedQuad { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageView.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageView.cs index e73217443..27dadacf5 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageView.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageView.cs @@ -9,14 +9,12 @@ using Metal; using CoreGraphics; -namespace MetalTexturedQuad -{ - public partial class ImageView : UIView - { +namespace MetalTexturedQuad { + public partial class ImageView : UIView { [Export ("layerClass")] public static Class LayerClass () { - return new Class (typeof(CAMetalLayer)); + return new Class (typeof (CAMetalLayer)); } IMTLDevice device; @@ -51,7 +49,7 @@ public ImageView (IntPtr handle) : base (handle) Opaque = true; BackgroundColor = UIColor.Clear; - metalLayer = (CAMetalLayer)Layer; + metalLayer = (CAMetalLayer) Layer; device = MTLDevice.SystemDefault; @@ -135,29 +133,29 @@ void SetupRenderPassDescriptorForTexture (IMTLTexture texture) } if (DepthPixelFormat != MTLPixelFormat.Invalid && (depthTex == null || NeedUpdate (texture, depthTex))) { - var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (DepthPixelFormat, texture.Width, texture.Height, false); - desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; - desc.SampleCount = SampleCount; - depthTex = device.CreateTexture (desc); - - MTLRenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.DepthAttachment; - depthAttachment.Texture = depthTex; - depthAttachment.LoadAction = MTLLoadAction.Clear; - depthAttachment.StoreAction = MTLStoreAction.DontCare; - depthAttachment.ClearDepth = 1.0; + var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (DepthPixelFormat, texture.Width, texture.Height, false); + desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; + desc.SampleCount = SampleCount; + depthTex = device.CreateTexture (desc); + + MTLRenderPassDepthAttachmentDescriptor depthAttachment = renderPassDescriptor.DepthAttachment; + depthAttachment.Texture = depthTex; + depthAttachment.LoadAction = MTLLoadAction.Clear; + depthAttachment.StoreAction = MTLStoreAction.DontCare; + depthAttachment.ClearDepth = 1.0; } if (StencilPixelFormat != MTLPixelFormat.Invalid && (stencilTex == null || NeedUpdate (texture, stencilTex))) { - var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (StencilPixelFormat, texture.Width, texture.Height, false); - desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; - desc.SampleCount = SampleCount; - stencilTex = device.CreateTexture (desc); - - MTLRenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.StencilAttachment; - stencilAttachment.Texture = stencilTex; - stencilAttachment.LoadAction = MTLLoadAction.Clear; - stencilAttachment.StoreAction = MTLStoreAction.DontCare; - stencilAttachment.ClearStencil = 0; + var desc = MTLTextureDescriptor.CreateTexture2DDescriptor (StencilPixelFormat, texture.Width, texture.Height, false); + desc.TextureType = (SampleCount > 1) ? MTLTextureType.k2DMultisample : MTLTextureType.k2D; + desc.SampleCount = SampleCount; + stencilTex = device.CreateTexture (desc); + + MTLRenderPassStencilAttachmentDescriptor stencilAttachment = renderPassDescriptor.StencilAttachment; + stencilAttachment.Texture = stencilTex; + stencilAttachment.LoadAction = MTLLoadAction.Clear; + stencilAttachment.StoreAction = MTLStoreAction.DontCare; + stencilAttachment.ClearStencil = 0; } } diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageViewController.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageViewController.cs index 412225073..9b348f3e3 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageViewController.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/ImageViewController.cs @@ -6,17 +6,15 @@ using UIKit; using CoreAnimation; -namespace MetalTexturedQuad -{ - public partial class ImageViewController : UIViewController - { +namespace MetalTexturedQuad { + public partial class ImageViewController : UIViewController { CADisplayLink timer; double timeSinceLastDrawPreviousTime; bool gameLoopPaused; bool firstDrawOccurred; - #pragma warning disable 414 +#pragma warning disable 414 double timeSinceLastDraw; - #pragma warning restore 414 +#pragma warning restore 414 Renderer renderer; @@ -64,7 +62,7 @@ public void Gameloop () timeSinceLastDrawPreviousTime = currentTime; } - ((ImageView)View).Display (); + ((ImageView) View).Display (); } public override void ViewDidLoad () @@ -72,7 +70,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); renderer = new Renderer (); - var renderView = (ImageView)View; + var renderView = (ImageView) View; renderView.Renderer = renderer; // load all renderer assets before starting game loop diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/Main.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/Main.cs index 8bc904bb6..259aa6498 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/Main.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MetalTexturedQuad -{ - public class Application - { +namespace MetalTexturedQuad { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/MathUtils.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/MathUtils.cs index 10f47a1e2..c53b2389e 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/MathUtils.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/MathUtils.cs @@ -1,10 +1,8 @@ -using System; +using System; using OpenTK; -namespace MetalTexturedQuad -{ - public static class MathUtils - { +namespace MetalTexturedQuad { + public static class MathUtils { public static Matrix4 SwapColumnsAndRows (this Matrix4 matrix) { return new Matrix4 (matrix.Column0, matrix.Column1, matrix.Column2, matrix.Column3); @@ -12,7 +10,7 @@ public static Matrix4 SwapColumnsAndRows (this Matrix4 matrix) public static Matrix4 Scale (float x, float y, float z) { - return new Matrix4 (x, 0f, 0f, 0f, 0f, y, 0f, 0f, 0f, 0f, z, 0f, 0f, 0f, 0f, 1f); + return new Matrix4 (x, 0f, 0f, 0f, 0f, y, 0f, 0f, 0f, 0f, z, 0f, 0f, 0f, 0f, 1f); } public static Matrix4 Translate (Vector3 t) @@ -37,8 +35,8 @@ public static float RadiansOverPi (float degrees) public static Matrix4 Rotate (float angle, Vector3 r) { float a = RadiansOverPi (angle); - float c = (float)Math.Cos (a); - float s = (float)Math.Sin (a); + float c = (float) Math.Cos (a); + float s = (float) Math.Sin (a); float k = 1.0f - c; r.Normalize (); @@ -95,7 +93,7 @@ public static Matrix4 Perspective (float width, float height, float near, float public static Matrix4 PerspectiveFov (float fovy, float aspect, float near, float far) { float angle = Radians (0.5f * fovy); - float yScale = 1f / (float)Math.Tan (angle); + float yScale = 1f / (float) Math.Tan (angle); float xScale = yScale / aspect; float zScale = far / (far - near); @@ -212,8 +210,8 @@ public static Matrix4 Ortho2dOc (Vector3 origin, Vector3 size) public static Matrix4 Frustrum (float fovH, float fovV, float near, float far) { - float width = 1f / (float)Math.Tan (Radians (0.5f * fovH)); - float height = 1f / (float)Math.Tan (Radians (0.5f * fovV)); + float width = 1f / (float) Math.Tan (Radians (0.5f * fovH)); + float height = 1f / (float) Math.Tan (Radians (0.5f * fovV)); float sDepth = far / (far - near); Vector4 P = Vector4.Zero; @@ -276,7 +274,7 @@ public static Matrix4 FrustrumOc (float left, float right, float bottom, float t public static float Radians (float degrees) { - return 1.0f / 180.0f * (float)Math.PI * degrees; + return 1.0f / 180.0f * (float) Math.PI * degrees; } public static Matrix4 MakeResultMatrix (Vector4 column0, Vector4 column1, Vector4 column2, Vector4 column3) diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/Quad.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/Quad.cs index 0181327b4..02c506b3c 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/Quad.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/Quad.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Runtime.InteropServices; using CoreGraphics; using Foundation; using Metal; using OpenTK; -namespace MetalTexturedQuad -{ - public class Quad : NSObject - { +namespace MetalTexturedQuad { + public class Quad : NSObject { // textured Quad IMTLBuffer vertexBuffer; IMTLBuffer texCoordBuffer; @@ -19,7 +17,7 @@ public class Quad : NSObject // Dimensions CGRect bounds; - readonly Vector4[] quadVertices = new Vector4 [] { + readonly Vector4 [] quadVertices = new Vector4 [] { new Vector4 (-1f, -1f, 0f, 1f), new Vector4 (1f, -1f, 0f, 1f), new Vector4 (-1f, 1f, 0f, 1f), @@ -29,7 +27,7 @@ public class Quad : NSObject new Vector4 (1f, 1f, 0f, 1f) }; - readonly Vector2[] quadTexCoords = new Vector2 [] { + readonly Vector2 [] quadTexCoords = new Vector2 [] { new Vector2 (0f, 0f), new Vector2 (1f, 0f), new Vector2 (0f, 1f), @@ -45,7 +43,7 @@ public class Quad : NSObject public CGSize Size { get; set; } - public nfloat Aspect { get; set; } + public nfloat Aspect { get; set; } public CGRect Bounds { get { @@ -92,11 +90,11 @@ void UpdateBounds () { Aspect = bounds.Size.Width / bounds.Size.Height; - float aspect = 1.0f / (float)Aspect; + float aspect = 1.0f / (float) Aspect; Vector2 localScale = Vector2.Zero; - localScale.X = (float)(aspect * Size.Width / Bounds.Size.Width); - localScale.Y = (float)(Size.Height / Bounds.Size.Height); + localScale.X = (float) (aspect * Size.Width / Bounds.Size.Width); + localScale.Y = (float) (Size.Height / Bounds.Size.Height); // Did the scaling factor change bool newScale = (scale.X != localScale.X) || (scale.Y != localScale.Y); @@ -107,10 +105,10 @@ void UpdateBounds () // Update the scaling factor scale = localScale; - var vertices = new Vector4[quadVertices.Length]; + var vertices = new Vector4 [quadVertices.Length]; IntPtr contentPtr = vertexBuffer.Contents; for (int i = 0; i < vertices.Length; i++) { - vertices [i] = (Vector4)Marshal.PtrToStructure (contentPtr, typeof(Vector4)); + vertices [i] = (Vector4) Marshal.PtrToStructure (contentPtr, typeof (Vector4)); contentPtr += Marshal.SizeOf<Vector4> (); } @@ -134,8 +132,8 @@ void UpdateBounds () vertices [5].X = scale.X; vertices [5].Y = scale.Y; - int rawsize = quadVertices.Length * Marshal.SizeOf <Vector4> (); - var rawdata = new byte[rawsize]; + int rawsize = quadVertices.Length * Marshal.SizeOf<Vector4> (); + var rawdata = new byte [rawsize]; GCHandle pinnedTransform = GCHandle.Alloc (vertices, GCHandleType.Pinned); IntPtr ptr = pinnedTransform.AddrOfPinnedObject (); Marshal.Copy (ptr, rawdata, 0, rawsize); diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/Renderer.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/Renderer.cs index c459d5366..fac2290f3 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/Renderer.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/Renderer.cs @@ -8,10 +8,8 @@ using OpenTK; using UIKit; -namespace MetalTexturedQuad -{ - public class Renderer - { +namespace MetalTexturedQuad { + public class Renderer { const float interfaceOrientationLandscapeAngle = 35.0f; const float interfaceOrientationPortraitAngle = 50.0f; const float prespectiveNear = 0.1f; @@ -37,10 +35,10 @@ public class Renderer Texture mpInTexture; IMTLRenderPipelineState pipelineState; - #pragma warning disable 649 +#pragma warning disable 649 // Dimensions CGSize size; - #pragma warning restore 649 +#pragma warning restore 649 // Viewing matrix is derived from an eye point, a reference point // indicating the center of the scene, and an up vector. @@ -149,7 +147,7 @@ public void Configure (ImageView renderView) // we need to set the framebuffer only property of the layer to NO so we // can perform compute on the drawable's texture - var metalLayer = (CAMetalLayer)renderView.Layer; + var metalLayer = (CAMetalLayer) renderView.Layer; metalLayer.FramebufferOnly = false; if (!PreparePipelineState ()) @@ -231,7 +229,7 @@ bool PrepareTexturedQuad (string texStr, string extStr) bool PrepareTransformBuffer () { // allocate regions of memory for the constant buffer - transformBuffer = device.CreateBuffer ((nuint)Marshal.SizeOf<Matrix4> (), MTLResourceOptions.CpuCacheModeDefault); + transformBuffer = device.CreateBuffer ((nuint) Marshal.SizeOf<Matrix4> (), MTLResourceOptions.CpuCacheModeDefault); if (transformBuffer == null) return false; @@ -304,9 +302,9 @@ void CreateMatrix (float angle) float near = prespectiveNear; float far = prespectiveFar; float rangle = MathUtils.Radians (angle); - float length = near * (float)Math.Tan (rangle); + float length = near * (float) Math.Tan (rangle); - float right = length / (float)mpQuad.Aspect; + float right = length / (float) mpQuad.Aspect; float left = -right; float top = length; float bottom = -top; @@ -324,8 +322,8 @@ void CreateMatrix (float angle) void UpdateBuffer () { // Update the buffer associated with the linear _transformation matrix - int rawsize = Marshal.SizeOf <Matrix4> (); - var rawdata = new byte[rawsize]; + int rawsize = Marshal.SizeOf<Matrix4> (); + var rawdata = new byte [rawsize]; GCHandle pinnedTransform = GCHandle.Alloc (transform, GCHandleType.Pinned); IntPtr ptr = pinnedTransform.AddrOfPinnedObject (); diff --git a/ios8/MetalTexturedQuad/MetalTexturedQuad/Texture.cs b/ios8/MetalTexturedQuad/MetalTexturedQuad/Texture.cs index afcf1f207..a347c68fd 100644 --- a/ios8/MetalTexturedQuad/MetalTexturedQuad/Texture.cs +++ b/ios8/MetalTexturedQuad/MetalTexturedQuad/Texture.cs @@ -7,16 +7,14 @@ using OpenTK; using UIKit; -namespace MetalTexturedQuad -{ - public class Texture : NSObject - { +namespace MetalTexturedQuad { + public class Texture : NSObject { string path; bool flip; public nint Height { get; private set; } - public nint Width { get; private set; } + public nint Width { get; private set; } public IMTLTexture MetalTexture { get; private set; } @@ -46,17 +44,17 @@ public bool Finalize (IMTLDevice device) Width = image.CGImage.Width; Height = image.CGImage.Height; - nuint width = (nuint)Width; - nuint height = (nuint)Height; + nuint width = (nuint) Width; + nuint height = (nuint) Height; nuint rowBytes = width * 4; var context = new CGBitmapContext (IntPtr.Zero, - (int)width, - (int)height, - 8, - (int)rowBytes, - colorSpace, - CGImageAlphaInfo.PremultipliedLast); + (int) width, + (int) height, + 8, + (int) rowBytes, + colorSpace, + CGImageAlphaInfo.PremultipliedLast); if (context == null) return false; @@ -89,8 +87,8 @@ public bool Finalize (IMTLDevice device) var region = new MTLRegion (); region.Origin.X = 0; region.Origin.Y = 0; - region.Size.Width = (nint)width; - region.Size.Height = (nint)height; + region.Size.Width = (nint) width; + region.Size.Height = (nint) height; MetalTexture.ReplaceRegion (region, 0, pixels, rowBytes); } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/AppDelegate.cs b/ios8/MonkeyBrowser/MonkeyBrowse/AppDelegate.cs index c3cd1aa28..db75118d7 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/AppDelegate.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/AppDelegate.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace MonkeyBrowse -{ +namespace MonkeyBrowse { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { #region Public Constants public NSString UserActivityTab1 = new NSString ("com.xamarin.monkeybrowser.tab1"); public NSString UserActivityTab2 = new NSString ("com.xamarin.monkeybrowser.tab2"); @@ -21,9 +19,9 @@ public partial class AppDelegate : UIApplicationDelegate #endregion #region Computed Properties - public override UIWindow Window { get; set;} + public override UIWindow Window { get; set; } public FirstViewController Tab1 { get; set; } - public SecondViewController Tab2 { get; set;} + public SecondViewController Tab2 { get; set; } public ThirdViewController Tab3 { get; set; } public FourthViewController Tab4 { get; set; } #endregion @@ -75,7 +73,7 @@ public override bool ContinueUserActivity (UIApplication application, NSUserActi { // Report Activity - Console.WriteLine ("Continuing User Activity: {0}", userActivity.ToString()); + Console.WriteLine ("Continuing User Activity: {0}", userActivity.ToString ()); // Get input and output streams from the Activity userActivity.GetContinuationStreams ((NSInputStream arg1, NSOutputStream arg2, NSError arg3) => { @@ -88,22 +86,22 @@ public override bool ContinueUserActivity (UIApplication application, NSUserActi case "com.xamarin.monkeybrowser.tab1": // Preform handoff Tab1.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab1}); + completionHandler (new NSObject [] { Tab1 }); break; case "com.xamarin.monkeybrowser.tab2": // Preform handoff Tab2.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab2}); + completionHandler (new NSObject [] { Tab2 }); break; case "com.xamarin.monkeybrowser.tab3": // Preform handoff Tab3.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab3}); + completionHandler (new NSObject [] { Tab3 }); break; case "com.xamarin.monkeybrowser.tab4": // Preform handoff Tab4.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab4}); + completionHandler (new NSObject [] { Tab4 }); break; } @@ -127,19 +125,19 @@ public override void DidFailToContinueUserActivitiy (UIApplication application, public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/Classes/AlertView.cs b/ios8/MonkeyBrowser/MonkeyBrowse/Classes/AlertView.cs index 7cf9e4422..c888de6a4 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/Classes/AlertView.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/Classes/AlertView.cs @@ -3,55 +3,56 @@ using UIKit; using System.CodeDom.Compiler; -namespace MonoTouch.UIKit -{ - public class AlertView - { +namespace MonoTouch.UIKit { + public class AlertView { #region Static Methods - public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) { + public static UIAlertController PresentOKAlert (string title, string description, UIViewController controller) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Configure the alert - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {})); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (action) => { })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentOKCancelAlert(string title, string description, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentOKCancelAlert (string title, string description, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentTextInputAlert(string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) { + public static UIAlertController PresentTextInputAlert (string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); UITextField field = null; // Add and configure text field @@ -70,23 +71,23 @@ public static UIAlertController PresentTextInputAlert(string title, string descr }); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false,""); + if (action != null) { + action (false, ""); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null && field !=null) { - action(true, field.Text); + if (action != null && field != null) { + action (true, field.Text); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -94,8 +95,8 @@ public static UIAlertController PresentTextInputAlert(string title, string descr #endregion #region Delegates - public delegate void AlertOKCancelDelegate(bool OK); - public delegate void AlertTextInputDelegate(bool OK, string text); + public delegate void AlertOKCancelDelegate (bool OK); + public delegate void AlertTextInputDelegate (bool OK, string text); #endregion } } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/Classes/UserActivityDelegate.cs b/ios8/MonkeyBrowser/MonkeyBrowse/Classes/UserActivityDelegate.cs index 67fac2525..88faf11e9 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/Classes/UserActivityDelegate.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/Classes/UserActivityDelegate.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace MonkeyBrowse -{ - public class UserActivityDelegate : NSUserActivityDelegate - { +namespace MonkeyBrowse { + public class UserActivityDelegate : NSUserActivityDelegate { #region Constructors public UserActivityDelegate () { @@ -30,6 +28,6 @@ public override void UserActivityWillSave (NSUserActivity userActivity) Console.WriteLine ("User Activity will be Saved: {0}", userActivity.Title); } #endregion - } + } } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/FirstViewController.cs b/ios8/MonkeyBrowser/MonkeyBrowse/FirstViewController.cs index 9514a9e81..06e5786b1 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/FirstViewController.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/FirstViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace MonkeyBrowse -{ - public partial class FirstViewController : UIViewController - { +namespace MonkeyBrowse { + public partial class FirstViewController : UIViewController { #region Computed Properties /// <summary> /// Gets a value indicating whether this <see cref="MonkeyBrowse.FirstViewController"/> user interface idiom is phone. @@ -21,7 +19,7 @@ public bool UserInterfaceIdiomIsPhone { /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> @@ -38,7 +36,7 @@ public AppDelegate ThisApp { /// <param name="handle">Handle.</param> public FirstViewController (IntPtr handle) : base (handle) { - + } #endregion @@ -47,7 +45,8 @@ public FirstViewController (IntPtr handle) : base (handle) /// Navigates the Webview to the given URL string. /// </summary> /// <param name="url">URL.</param> - private void NavigateToURL(string url) { + private void NavigateToURL (string url) + { // Properly formatted? if (!url.StartsWith ("http://")) { @@ -56,16 +55,16 @@ private void NavigateToURL(string url) { } // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Invalidate existing Activity if (UserActivity != null) { - UserActivity.Invalidate(); + UserActivity.Invalidate (); UserActivity = null; } // Create a new user Activity to support this tab - UserActivity = new NSUserActivity (ThisApp.UserActivityTab1){ + UserActivity = new NSUserActivity (ThisApp.UserActivityTab1) { Title = "Weather Tab", SupportsContinuationStreams = true }; @@ -87,44 +86,48 @@ private void NavigateToURL(string url) { /// Shows the busy indicator /// </summary> /// <param name="reason">Reason.</param> - private void ShowBusy(string reason) { + private void ShowBusy (string reason) + { // Display reason BusyText.Text = reason; //Define Animation - UIView.BeginAnimations("Show"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Show"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0.5f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } /// <summary> /// Hides the busy. /// </summary> - private void HideBusy() { + private void HideBusy () + { //Define Animation - UIView.BeginAnimations("Hide"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Hide"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } #endregion #region Public Methods - public void PreparingToHandoff() { + public void PreparingToHandoff () + { // Inform caller ShowBusy ("Continuing Activity..."); } - public void PerformHandoff(NSUserActivity activity) { + public void PerformHandoff (NSUserActivity activity) + { // Hide busy indicator HideBusy (); @@ -136,7 +139,7 @@ public void PerformHandoff(NSUserActivity activity) { URL.Text = url; // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Save activity UserActivity = activity; @@ -162,28 +165,29 @@ public override void ViewDidLoad () // Wireup Webview notifications WebView.LoadStarted += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - ShowBusy(string .Format("Loading {0}...",URL.Text)); + ShowBusy (string.Format ("Loading {0}...", URL.Text)); }; WebView.LoadFinished += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - HideBusy(); + HideBusy (); }; // Configure URL entry field URL.Placeholder = "(enter url)"; // Wire-up URL field - URL.ShouldReturn = delegate (UITextField field){ + URL.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); - NavigateToURL(field.Text); + NavigateToURL (field.Text); return true; }; // Wire-up the Go Button GoButton.Clicked += (sender, e) => { - NavigateToURL(URL.Text); + NavigateToURL (URL.Text); }; } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/FourthViewController.cs b/ios8/MonkeyBrowser/MonkeyBrowse/FourthViewController.cs index de6a03900..97420aa84 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/FourthViewController.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/FourthViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace MonkeyBrowse -{ - public partial class FourthViewController : UIViewController - { +namespace MonkeyBrowse { + public partial class FourthViewController : UIViewController { #region Computed Properties /// <summary> /// Gets a value indicating whether this <see cref="MonkeyBrowse.FirstViewController"/> user interface idiom is phone. @@ -21,7 +19,7 @@ public bool UserInterfaceIdiomIsPhone { /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> @@ -42,7 +40,8 @@ public FourthViewController (IntPtr handle) : base (handle) /// Navigates the Webview to the given URL string. /// </summary> /// <param name="url">URL.</param> - private void NavigateToURL(string url) { + private void NavigateToURL (string url) + { // Properly formatted? if (!url.StartsWith ("http://")) { @@ -51,11 +50,11 @@ private void NavigateToURL(string url) { } // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Invalidate existing Activity if (UserActivity != null) { - UserActivity.Invalidate(); + UserActivity.Invalidate (); UserActivity = null; } @@ -79,44 +78,48 @@ private void NavigateToURL(string url) { /// Shows the busy indicator /// </summary> /// <param name="reason">Reason.</param> - private void ShowBusy(string reason) { + private void ShowBusy (string reason) + { // Display reason BusyText.Text = reason; //Define Animation - UIView.BeginAnimations("Show"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Show"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0.5f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } /// <summary> /// Hides the busy. /// </summary> - private void HideBusy() { + private void HideBusy () + { //Define Animation - UIView.BeginAnimations("Hide"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Hide"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } #endregion #region Public Methods - public void PreparingToHandoff() { + public void PreparingToHandoff () + { // Inform caller ShowBusy ("Continuing Activity..."); } - public void PerformHandoff(NSUserActivity activity) { + public void PerformHandoff (NSUserActivity activity) + { // Hide busy indicator HideBusy (); @@ -128,7 +131,7 @@ public void PerformHandoff(NSUserActivity activity) { URL.Text = url; // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Save activity UserActivity = activity; @@ -154,28 +157,29 @@ public override void ViewDidLoad () // Wireup Webview notifications WebView.LoadStarted += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - ShowBusy(string .Format("Loading {0}...",URL.Text)); + ShowBusy (string.Format ("Loading {0}...", URL.Text)); }; WebView.LoadFinished += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - HideBusy(); + HideBusy (); }; // Configure URL entry field URL.Placeholder = "(enter url)"; // Wire-up URL field - URL.ShouldReturn = delegate (UITextField field){ + URL.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); - NavigateToURL(field.Text); + NavigateToURL (field.Text); return true; }; // Wire-up the Go Button GoButton.Clicked += (sender, e) => { - NavigateToURL(URL.Text); + NavigateToURL (URL.Text); }; } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/Main.cs b/ios8/MonkeyBrowser/MonkeyBrowse/Main.cs index 84b77fc44..5f82e6b8f 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/Main.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace MonkeyBrowse -{ - public class Application - { +namespace MonkeyBrowse { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/SecondViewController.cs b/ios8/MonkeyBrowser/MonkeyBrowse/SecondViewController.cs index aa9ce54c2..ed1df7c4d 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/SecondViewController.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/SecondViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; -namespace MonkeyBrowse -{ - public partial class SecondViewController : UIViewController - { +namespace MonkeyBrowse { + public partial class SecondViewController : UIViewController { #region Computed Properties /// <summary> /// Gets a value indicating whether this <see cref="MonkeyBrowse.FirstViewController"/> user interface idiom is phone. @@ -22,7 +20,7 @@ public bool UserInterfaceIdiomIsPhone { /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> @@ -43,7 +41,8 @@ public SecondViewController (IntPtr handle) : base (handle) /// Navigates the Webview to the given URL string. /// </summary> /// <param name="url">URL.</param> - private void NavigateToURL(string url) { + private void NavigateToURL (string url) + { // Properly formatted? if (!url.StartsWith ("http://")) { @@ -52,11 +51,11 @@ private void NavigateToURL(string url) { } // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Invalidate existing Activity if (UserActivity != null) { - UserActivity.Invalidate(); + UserActivity.Invalidate (); UserActivity = null; } @@ -80,44 +79,48 @@ private void NavigateToURL(string url) { /// Shows the busy indicator /// </summary> /// <param name="reason">Reason.</param> - private void ShowBusy(string reason) { + private void ShowBusy (string reason) + { // Display reason BusyText.Text = reason; //Define Animation - UIView.BeginAnimations("Show"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Show"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0.5f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } /// <summary> /// Hides the busy. /// </summary> - private void HideBusy() { + private void HideBusy () + { //Define Animation - UIView.BeginAnimations("Hide"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Hide"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } #endregion #region Public Methods - public void PreparingToHandoff() { + public void PreparingToHandoff () + { // Inform caller ShowBusy ("Continuing Activity..."); } - public void PerformHandoff(NSUserActivity activity) { + public void PerformHandoff (NSUserActivity activity) + { // Hide busy indicator HideBusy (); @@ -129,7 +132,7 @@ public void PerformHandoff(NSUserActivity activity) { URL.Text = url; // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Save activity UserActivity = activity; @@ -155,28 +158,29 @@ public override void ViewDidLoad () // Wireup Webview notifications WebView.LoadStarted += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - ShowBusy(string .Format("Loading {0}...",URL.Text)); + ShowBusy (string.Format ("Loading {0}...", URL.Text)); }; WebView.LoadFinished += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - HideBusy(); + HideBusy (); }; // Configure URL entry field URL.Placeholder = "(enter url)"; // Wire-up URL field - URL.ShouldReturn = delegate (UITextField field){ + URL.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); - NavigateToURL(field.Text); + NavigateToURL (field.Text); return true; }; // Wire-up the Go Button GoButton.Clicked += (sender, e) => { - NavigateToURL(URL.Text); + NavigateToURL (URL.Text); }; } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/TabBarViewController.cs b/ios8/MonkeyBrowser/MonkeyBrowse/TabBarViewController.cs index 0bea5e1e0..cb3d6f4cf 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/TabBarViewController.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/TabBarViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace MonkeyBrowse -{ - partial class TabBarViewController : UITabBarController - { +namespace MonkeyBrowse { + partial class TabBarViewController : UITabBarController { public TabBarViewController (IntPtr handle) : base (handle) { } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/ThirdViewController.cs b/ios8/MonkeyBrowser/MonkeyBrowse/ThirdViewController.cs index 9ddbfe0c9..0802da31c 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/ThirdViewController.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/ThirdViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace MonkeyBrowse -{ - public partial class ThirdViewController : UIViewController - { +namespace MonkeyBrowse { + public partial class ThirdViewController : UIViewController { #region Computed Properties /// <summary> /// Gets a value indicating whether this <see cref="MonkeyBrowse.FirstViewController"/> user interface idiom is phone. @@ -21,7 +19,7 @@ public bool UserInterfaceIdiomIsPhone { /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> @@ -42,7 +40,8 @@ public ThirdViewController (IntPtr handle) : base (handle) /// Navigates the Webview to the given URL string. /// </summary> /// <param name="url">URL.</param> - private void NavigateToURL(string url) { + private void NavigateToURL (string url) + { // Properly formatted? if (!url.StartsWith ("http://")) { @@ -51,11 +50,11 @@ private void NavigateToURL(string url) { } // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Invalidate existing Activity if (UserActivity != null) { - UserActivity.Invalidate(); + UserActivity.Invalidate (); UserActivity = null; } @@ -79,44 +78,48 @@ private void NavigateToURL(string url) { /// Shows the busy indicator /// </summary> /// <param name="reason">Reason.</param> - private void ShowBusy(string reason) { + private void ShowBusy (string reason) + { // Display reason BusyText.Text = reason; //Define Animation - UIView.BeginAnimations("Show"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Show"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0.5f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } /// <summary> /// Hides the busy. /// </summary> - private void HideBusy() { + private void HideBusy () + { //Define Animation - UIView.BeginAnimations("Hide"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Hide"); + UIView.SetAnimationDuration (1.0f); Handoff.Alpha = 0f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } #endregion #region Public Methods - public void PreparingToHandoff() { + public void PreparingToHandoff () + { // Inform caller ShowBusy ("Continuing Activity..."); } - public void PerformHandoff(NSUserActivity activity) { + public void PerformHandoff (NSUserActivity activity) + { // Hide busy indicator HideBusy (); @@ -128,7 +131,7 @@ public void PerformHandoff(NSUserActivity activity) { URL.Text = url; // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(url))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (url))); // Save activity UserActivity = activity; @@ -154,28 +157,29 @@ public override void ViewDidLoad () // Wireup Webview notifications WebView.LoadStarted += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - ShowBusy(string .Format("Loading {0}...",URL.Text)); + ShowBusy (string.Format ("Loading {0}...", URL.Text)); }; WebView.LoadFinished += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - HideBusy(); + HideBusy (); }; // Configure URL entry field URL.Placeholder = "(enter url)"; // Wire-up URL field - URL.ShouldReturn = delegate (UITextField field){ + URL.ShouldReturn = delegate (UITextField field) + { field.ResignFirstResponder (); - NavigateToURL(field.Text); + NavigateToURL (field.Text); return true; }; // Wire-up the Go Button GoButton.Clicked += (sender, e) => { - NavigateToURL(URL.Text); + NavigateToURL (URL.Text); }; } diff --git a/ios8/MonkeyBrowser/MonkeyBrowse/temp.cs b/ios8/MonkeyBrowser/MonkeyBrowse/temp.cs index 469d0ceb6..8b8793594 100644 --- a/ios8/MonkeyBrowser/MonkeyBrowse/temp.cs +++ b/ios8/MonkeyBrowser/MonkeyBrowse/temp.cs @@ -1,8 +1,8 @@ -public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler) +public override bool ContinueUserActivity (UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler) { // Report Activity - Console.WriteLine ("Continuing User Activity: {0}", userActivity.ToString()); + Console.WriteLine ("Continuing User Activity: {0}", userActivity.ToString ()); // Get input and output streams from the Activity userActivity.GetContinuationStreams ((NSInputStream arg1, NSOutputStream arg2, NSError arg3) => { @@ -15,25 +15,25 @@ case "com.xamarin.monkeybrowser.tab1": // Preform handoff Tab1.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab1}); + completionHandler (new NSObject [] { Tab1 }); break; case "com.xamarin.monkeybrowser.tab2": // Preform handoff Tab2.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab2}); + completionHandler (new NSObject [] { Tab2 }); break; case "com.xamarin.monkeybrowser.tab3": // Preform handoff Tab3.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab3}); + completionHandler (new NSObject [] { Tab3 }); break; case "com.xamarin.monkeybrowser.tab4": // Preform handoff Tab4.PerformHandoff (userActivity); - completionHandler (new NSObject[]{Tab4}); + completionHandler (new NSObject [] { Tab4 }); break; } // Inform system we handled this return true; -} \ No newline at end of file +} diff --git a/ios8/MotionActivityDemo/MotionActivityDemo/ActivityDataManager.cs b/ios8/MotionActivityDemo/MotionActivityDemo/ActivityDataManager.cs index 7181afe88..1d3b1dba4 100644 --- a/ios8/MotionActivityDemo/MotionActivityDemo/ActivityDataManager.cs +++ b/ios8/MotionActivityDemo/MotionActivityDemo/ActivityDataManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using System.Collections.Generic; using CoreMotion; @@ -7,10 +7,8 @@ using System.Threading.Tasks; using System.Linq; -namespace MotionActivityDemo -{ - public enum ActivityType - { +namespace MotionActivityDemo { + public enum ActivityType { Walking, Running, Driving, @@ -19,8 +17,7 @@ public enum ActivityType None } - public class ActivityDataManager : NSObject - { + public class ActivityDataManager : NSObject { public double WalkingDuration; public double RunningDuration; public double VehicularDuration; @@ -31,7 +28,7 @@ public class ActivityDataManager : NSObject public List<SignificantActivity> SignificantActivities { get { - SignificantActivity[] copy = new SignificantActivity[significantActivities.Count]; + SignificantActivity [] copy = new SignificantActivity [significantActivities.Count]; significantActivities.CopyTo (copy); return copy.ToList (); } @@ -69,13 +66,13 @@ public async Task QueryAsync (MotionActivityQuery query) await queryHistoricalDataAsync (query.StartDate, query.EndDate); } - async Task additionalProcessingOnAsync (CMMotionActivity[] activities) + async Task additionalProcessingOnAsync (CMMotionActivity [] activities) { computeTotalDurations (activities); SignificantActivities = (await aggregateSignificantActivitiesAsync (activities)).ToList (); } - void computeTotalDurations (CMMotionActivity[] activities) + void computeTotalDurations (CMMotionActivity [] activities) { WalkingDuration = 0; RunningDuration = 0; @@ -101,7 +98,7 @@ void computeTotalDurations (CMMotionActivity[] activities) } } - async Task<List<SignificantActivity>> aggregateSignificantActivitiesAsync (CMMotionActivity[] activities) + async Task<List<SignificantActivity>> aggregateSignificantActivitiesAsync (CMMotionActivity [] activities) { List<CMMotionActivity> filteredActivities = new List<CMMotionActivity> (); @@ -153,8 +150,8 @@ async Task<List<SignificantActivity>> aggregateSignificantActivitiesAsync (CMMot CMMotionActivity activity = filteredActivities [i]; if ((prevActivity.Walking && activity.Walking) || - (prevActivity.Running && activity.Running) || - (prevActivity.Automotive && activity.Automotive)) { + (prevActivity.Running && activity.Running) || + (prevActivity.Automotive && activity.Automotive)) { filteredActivities.RemoveAt (i); } else { ++i; @@ -171,7 +168,7 @@ async Task<List<SignificantActivity>> aggregateSignificantActivitiesAsync (CMMot if (!activity.Walking && !activity.Running && !activity.Automotive) continue; - var significantActivity = new SignificantActivity (ActivityDataManager.ActivityToType (activity), (DateTime)activity.StartDate, (DateTime)nextActivity.StartDate); + var significantActivity = new SignificantActivity (ActivityDataManager.ActivityToType (activity), (DateTime) activity.StartDate, (DateTime) nextActivity.StartDate); try { var pedometerData = await pedometer.QueryPedometerDataAsync (significantActivity.StartDate, significantActivity.EndDate); @@ -232,7 +229,7 @@ public static string ActivityTypeToString (ActivityType type) public static bool CheckAvailability () { if (available != null) - return (bool)available; + return (bool) available; available = true; if (CMMotionActivityManager.IsActivityAvailable == false) { @@ -245,7 +242,7 @@ public static bool CheckAvailability () available = false; } - return (bool)available; + return (bool) available; } void initMotionActivity () @@ -310,8 +307,7 @@ public void StopMotionUpdates () #endregion } - public class SignificantActivity : NSObject - { + public class SignificantActivity : NSObject { public NSDate StartDate; public NSDate EndDate; public int StepCounts; @@ -320,8 +316,8 @@ public class SignificantActivity : NSObject public SignificantActivity (ActivityType type, DateTime startDate, DateTime endDate) { ActivityType = type; - StartDate = (NSDate)startDate; - EndDate = (NSDate)endDate; + StartDate = (NSDate) startDate; + EndDate = (NSDate) endDate; StepCounts = 0; } } diff --git a/ios8/MotionActivityDemo/MotionActivityDemo/AppDelegate.cs b/ios8/MotionActivityDemo/MotionActivityDemo/AppDelegate.cs index 05e110c92..3def215c5 100644 --- a/ios8/MotionActivityDemo/MotionActivityDemo/AppDelegate.cs +++ b/ios8/MotionActivityDemo/MotionActivityDemo/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MotionActivityDemo -{ +namespace MotionActivityDemo { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; diff --git a/ios8/MotionActivityDemo/MotionActivityDemo/DetailViewController.cs b/ios8/MotionActivityDemo/MotionActivityDemo/DetailViewController.cs index c919d65f7..f15c4b334 100644 --- a/ios8/MotionActivityDemo/MotionActivityDemo/DetailViewController.cs +++ b/ios8/MotionActivityDemo/MotionActivityDemo/DetailViewController.cs @@ -6,10 +6,8 @@ using UIKit; using System.Threading.Tasks; -namespace MotionActivityDemo -{ - public partial class DetailViewController : UITableViewController - { +namespace MotionActivityDemo { + public partial class DetailViewController : UITableViewController { ActivityDataManager activityDataManager; NSDateFormatter dateFormatter; string currentActivity; @@ -80,13 +78,13 @@ public override nint RowsInSection (UITableView tableview, nint section) if (section == 1) return 1; if (section == 2) - return (nint)activityDataManager.SignificantActivities.Count; + return (nint) activityDataManager.SignificantActivities.Count; return 0; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = tableView.DequeueReusableCell ((NSString)"Cell", indexPath); + var cell = tableView.DequeueReusableCell ((NSString) "Cell", indexPath); if (indexPath.Section == 0) { if (indexPath.Row == 0) { @@ -138,7 +136,7 @@ public override string TitleForHeader (UITableView tableView, nint section) static string formatTimeInterval (double interval) { - return String.Format ("{0}h {1}m", (int)interval / 3600, (int)(interval / 60) % 60); + return String.Format ("{0}h {1}m", (int) interval / 3600, (int) (interval / 60) % 60); } } } diff --git a/ios8/MotionActivityDemo/MotionActivityDemo/Main.cs b/ios8/MotionActivityDemo/MotionActivityDemo/Main.cs index e8c30417b..17579e243 100644 --- a/ios8/MotionActivityDemo/MotionActivityDemo/Main.cs +++ b/ios8/MotionActivityDemo/MotionActivityDemo/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace MotionActivityDemo -{ - public class Application - { +namespace MotionActivityDemo { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/MotionActivityDemo/MotionActivityDemo/MasterViewController.cs b/ios8/MotionActivityDemo/MotionActivityDemo/MasterViewController.cs index edc6aff52..38dbd9b7c 100644 --- a/ios8/MotionActivityDemo/MotionActivityDemo/MasterViewController.cs +++ b/ios8/MotionActivityDemo/MotionActivityDemo/MasterViewController.cs @@ -8,16 +8,14 @@ using CoreFoundation; using System.Threading.Tasks; -namespace MotionActivityDemo -{ - public partial class MasterViewController : UITableViewController - { +namespace MotionActivityDemo { + public partial class MasterViewController : UITableViewController { ActivityDataManager dataManager; List<MotionActivityQuery> motionActivityQueries; - #pragma warning disable 414 +#pragma warning disable 414 NSObject observer; - #pragma warning disable 414 +#pragma warning disable 414 public MasterViewController (IntPtr handle) : base (handle) { @@ -72,9 +70,9 @@ public override nint RowsInSection (UITableView tableview, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - UITableViewCell cell = tableView.DequeueReusableCell ((NSString)"Cell", indexPath); + UITableViewCell cell = tableView.DequeueReusableCell ((NSString) "Cell", indexPath); - MotionActivityQuery query = motionActivityQueries[indexPath.Row]; + MotionActivityQuery query = motionActivityQueries [indexPath.Row]; cell.TextLabel.Text = query.ShortDescription; return cell; } diff --git a/ios8/MotionActivityDemo/MotionActivityDemo/MotionActivityQuery.cs b/ios8/MotionActivityDemo/MotionActivityDemo/MotionActivityQuery.cs index 7c69e6acc..2665636eb 100644 --- a/ios8/MotionActivityDemo/MotionActivityDemo/MotionActivityQuery.cs +++ b/ios8/MotionActivityDemo/MotionActivityDemo/MotionActivityQuery.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; -namespace MotionActivityDemo -{ - public class MotionActivityQuery : NSObject - { +namespace MotionActivityDemo { + public class MotionActivityQuery : NSObject { public NSDate StartDate; public NSDate EndDate; public bool IsToday; @@ -20,7 +18,7 @@ public static MotionActivityQuery FromDate (NSDate date, int offset) { NSCalendar currentCalendar = NSCalendar.CurrentCalendar; NSDateComponents timeComponents = currentCalendar.Components ( - NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, date); + NSCalendarUnit.Year | NSCalendarUnit.Month | NSCalendarUnit.Day, date); timeComponents.Hour = 0; timeComponents.Day = timeComponents.Day + offset; diff --git a/ios8/NewBox/NBox/DocumentPickerViewController.cs b/ios8/NewBox/NBox/DocumentPickerViewController.cs index 55b6927bd..84ffce754 100644 --- a/ios8/NewBox/NBox/DocumentPickerViewController.cs +++ b/ios8/NewBox/NBox/DocumentPickerViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; using System.Text; -namespace NBox -{ - public partial class DocumentPickerViewController : UIDocumentPickerExtensionViewController - { +namespace NBox { + public partial class DocumentPickerViewController : UIDocumentPickerExtensionViewController { public DocumentPickerViewController (IntPtr handle) : base (handle) { Console.WriteLine (IntPtr.Size); @@ -37,10 +35,10 @@ public override void PrepareForPresentation (UIDocumentPickerMode mode) SetupMoveExportButton (mode); } - void FillMovedImportedList() + void FillMovedImportedList () { NSError error; - string[] files = NSFileManager.DefaultManager.GetDirectoryContent (DocumentStorageUrl.Path, out error); + string [] files = NSFileManager.DefaultManager.GetDirectoryContent (DocumentStorageUrl.Path, out error); if (error != null) { Console.WriteLine ("GetDirectoryContent error: {0}", error); return; @@ -56,7 +54,7 @@ void FillMovedImportedList() MovedImportedList.Text = sb.ToString (); } - void SetupMoveExportButton(UIDocumentPickerMode mode) + void SetupMoveExportButton (UIDocumentPickerMode mode) { switch (mode) { case UIDocumentPickerMode.Import: @@ -74,13 +72,13 @@ void SetupMoveExportButton(UIDocumentPickerMode mode) } } - void HideMoveExportButton() + void HideMoveExportButton () { MoveExportBtn.Hidden = true; MoveExportBtn.Enabled = false; } - void ShowMoveExportButton(string title) + void ShowMoveExportButton (string title) { MoveExportBtn.Hidden = false; MoveExportBtn.Enabled = true; @@ -100,7 +98,7 @@ partial void OpenDocument (NSObject sender) DismissGrantingAccess (documentURL); } - partial void OnExportMoveClicked(NSObject sender) + partial void OnExportMoveClicked (NSObject sender) { Console.WriteLine ("DocumentPickerViewController MoveExportClicked"); @@ -110,11 +108,11 @@ partial void OnExportMoveClicked(NSObject sender) // After the copy is complete, call DismissGrantingAccess method, and provide the URL to the new copy NSError error; - var destinationUrl = DocumentStorageUrl.Append(OriginalUrl.LastPathComponent, false); - NSFileManager.DefaultManager.Copy(OriginalUrl.Path, destinationUrl.Path, out error); + var destinationUrl = DocumentStorageUrl.Append (OriginalUrl.LastPathComponent, false); + NSFileManager.DefaultManager.Copy (OriginalUrl.Path, destinationUrl.Path, out error); // Provide here a destination Url - DismissGrantingAccess(destinationUrl); + DismissGrantingAccess (destinationUrl); } } } diff --git a/ios8/NewBox/NBoxFileProvider/FileProvider.cs b/ios8/NewBox/NBoxFileProvider/FileProvider.cs index 24da9d16c..0a9ffc4c0 100644 --- a/ios8/NewBox/NBoxFileProvider/FileProvider.cs +++ b/ios8/NewBox/NBoxFileProvider/FileProvider.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.IO; using Foundation; using UIKit; -namespace NBoxFileProvider -{ +namespace NBoxFileProvider { [Register ("FileProvider")] - public class FileProvider : NSFileProviderExtension - { + public class FileProvider : NSFileProviderExtension { public FileProvider () { Console.WriteLine ("FileProvider ctor"); @@ -46,11 +44,11 @@ public override void StartProvidingItemAtUrl (NSUrl url, Action<NSError> complet // The system then passes the error back to the original coordinated read. string str = "These are the contents of the file"; - NSData fileData = ((NSString)str).Encode (NSStringEncoding.UTF8); + NSData fileData = ((NSString) str).Encode (NSStringEncoding.UTF8); NSError error = null; fileData.Save (url, NSDataWritingOptions.Atomic, out error); - if(error != null) + if (error != null) Console.WriteLine ("FileProvider atomic save error {0}", error); completionHandler (error); diff --git a/ios8/NewBox/NewBox/AppDelegate.cs b/ios8/NewBox/NewBox/AppDelegate.cs index 659655803..134d9ab94 100644 --- a/ios8/NewBox/NewBox/AppDelegate.cs +++ b/ios8/NewBox/NewBox/AppDelegate.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace NewBox -{ +namespace NewBox { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; diff --git a/ios8/NewBox/NewBox/Main.cs b/ios8/NewBox/NewBox/Main.cs index 55b827d12..12292d534 100644 --- a/ios8/NewBox/NewBox/Main.cs +++ b/ios8/NewBox/NewBox/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace NewBox -{ - public class Application - { +namespace NewBox { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/NewBox/NewBox/MainViewController.cs b/ios8/NewBox/NewBox/MainViewController.cs index 024beefdb..0d5058949 100644 --- a/ios8/NewBox/NewBox/MainViewController.cs +++ b/ios8/NewBox/NewBox/MainViewController.cs @@ -1,19 +1,17 @@ -using System; +using System; using UIKit; using Foundation; using MobileCoreServices; -namespace NewBox -{ +namespace NewBox { [Register ("MainViewController")] - public class MainViewController : UIViewController - { + public class MainViewController : UIViewController { NSUrl documentURL; - string[] allowedUTIs; + string [] allowedUTIs; - public MainViewController(IntPtr handle) - : base(handle) + public MainViewController (IntPtr handle) + : base (handle) { } @@ -23,7 +21,7 @@ public override async void ViewDidLoad () // For demo we put all available UTI types #region Init UTIs - allowedUTIs = new string[] { + allowedUTIs = new string [] { UTType.AliasFile, UTType.AliasRecord, UTType.AppleICNS, @@ -170,8 +168,8 @@ public override async void ViewDidLoad () #region Document picker's actions - [Export("importFromDocPicker:")] - public void ImportFromDocPicker(UIButton sender) + [Export ("importFromDocPicker:")] + public void ImportFromDocPicker (UIButton sender) { UIDocumentPickerViewController vc = new UIDocumentPickerViewController (allowedUTIs, UIDocumentPickerMode.Import); vc.WasCancelled += OnPickerCancel; @@ -189,8 +187,8 @@ void DidPickDocumentForImport (object sender, UIDocumentPickedEventArgs e) PrintFileContent (temporaryFileUrl); } - [Export("exportToDocPicker:")] - public void ExportToDocPicker(UIButton sender) + [Export ("exportToDocPicker:")] + public void ExportToDocPicker (UIButton sender) { if (TryShowFileNotExistsError ()) return; @@ -211,8 +209,8 @@ void DidPickDocumentForExport (object sender, UIDocumentPickedEventArgs e) Console.WriteLine ("{0} exported to new location outside your app’s sandbox {1}", documentURL, url); } - [Export("openDocPicker:")] - public void OpenDocPicker(UIButton sender) + [Export ("openDocPicker:")] + public void OpenDocPicker (UIButton sender) { UIDocumentPickerViewController vc = new UIDocumentPickerViewController (allowedUTIs, UIDocumentPickerMode.Open); vc.WasCancelled += OnPickerCancel; @@ -230,8 +228,8 @@ void DidPickDocumentForOpen (object sender, UIDocumentPickedEventArgs e) PrintOutsideFileContent (securityScopedUrl); } - [Export("moveToDocPicker:")] - private void MoveToDocPicker(UIButton sender) + [Export ("moveToDocPicker:")] + private void MoveToDocPicker (UIButton sender) { if (TryShowFileNotExistsError ()) return; @@ -252,7 +250,7 @@ void DidPickDocumentForMove (object sender, UIDocumentPickedEventArgs e) PrintOutsideFileContent (securityScopedUrl); } - void PrintOutsideFileContent(NSUrl securityScopedUrl) + void PrintOutsideFileContent (NSUrl securityScopedUrl) { if (!securityScopedUrl.StartAccessingSecurityScopedResource ()) return; @@ -262,13 +260,13 @@ void PrintOutsideFileContent(NSUrl securityScopedUrl) securityScopedUrl.StopAccessingSecurityScopedResource (); } - void PrintFileContent(NSUrl url) + void PrintFileContent (NSUrl url) { NSData data = null; NSError error = null; NSFileCoordinator fileCoordinator = new NSFileCoordinator (); - fileCoordinator.CoordinateRead (url, (NSFileCoordinatorReadingOptions)0, out error, newUrl => { - data = NSData.FromUrl(newUrl); + fileCoordinator.CoordinateRead (url, (NSFileCoordinatorReadingOptions) 0, out error, newUrl => { + data = NSData.FromUrl (newUrl); }); if (error != null) { @@ -283,22 +281,22 @@ void PrintFileContent(NSUrl url) #region Documnet menu's actions - [Export("importFromDocMenu:")] - public void ImportFromDocMenu(UIButton sender) + [Export ("importFromDocMenu:")] + public void ImportFromDocMenu (UIButton sender) { UIDocumentMenuViewController vc = new UIDocumentMenuViewController (allowedUTIs, UIDocumentPickerMode.Import); SetupDelegateThenPresent (vc, sender); } - [Export("openDocMenu:")] - public void OpenDocMenu(UIButton sender) + [Export ("openDocMenu:")] + public void OpenDocMenu (UIButton sender) { UIDocumentMenuViewController vc = new UIDocumentMenuViewController (allowedUTIs, UIDocumentPickerMode.Open); SetupDelegateThenPresent (vc, sender); } - [Export("exportToDocMenu:")] - public void ExportToDocMenu(UIButton sender) + [Export ("exportToDocMenu:")] + public void ExportToDocMenu (UIButton sender) { if (TryShowFileNotExistsError ()) return; @@ -307,8 +305,8 @@ public void ExportToDocMenu(UIButton sender) SetupDelegateThenPresent (vc, sender); } - [Export("moveToDocMenu:")] - public void MoveToDocMenu(UIButton sender) + [Export ("moveToDocMenu:")] + public void MoveToDocMenu (UIButton sender) { if (TryShowFileNotExistsError ()) return; @@ -317,7 +315,7 @@ public void MoveToDocMenu(UIButton sender) SetupDelegateThenPresent (vc, sender); } - void SetupDelegateThenPresent(UIDocumentMenuViewController vc, UIButton button) + void SetupDelegateThenPresent (UIDocumentMenuViewController vc, UIButton button) { vc.WasCancelled += OnPickerSelectionCancel; vc.DidPickDocumentPicker += OnPickerPicked; @@ -343,7 +341,7 @@ void SetupDelegateThenPresent(UIDocumentMenuViewController vc, UIButton button) void OnPickerSelectionCancel (object sender, EventArgs e) { - var menu = (UIDocumentMenuViewController)sender; + var menu = (UIDocumentMenuViewController) sender; Unsibscribe (menu); Console.WriteLine ("Picker selection was canceled"); @@ -351,27 +349,27 @@ void OnPickerSelectionCancel (object sender, EventArgs e) void OnPickerPicked (object sender, UIDocumentMenuDocumentPickedEventArgs e) { - var menu = (UIDocumentMenuViewController)sender; + var menu = (UIDocumentMenuViewController) sender; Unsibscribe (menu); var documentPicker = e.DocumentPicker; documentPicker.WasCancelled += OnPickerCancel; switch (documentPicker.DocumentPickerMode) { - case UIDocumentPickerMode.Import: - documentPicker.DidPickDocument += DidPickDocumentForImport; - break; + case UIDocumentPickerMode.Import: + documentPicker.DidPickDocument += DidPickDocumentForImport; + break; - case UIDocumentPickerMode.Open: - documentPicker.DidPickDocument += DidPickDocumentForOpen; - break; + case UIDocumentPickerMode.Open: + documentPicker.DidPickDocument += DidPickDocumentForOpen; + break; - case UIDocumentPickerMode.ExportToService: - documentPicker.DidPickDocument += DidPickDocumentForExport; - break; + case UIDocumentPickerMode.ExportToService: + documentPicker.DidPickDocument += DidPickDocumentForExport; + break; - case UIDocumentPickerMode.MoveToService: - documentPicker.DidPickDocument += DidPickDocumentForMove; - break; + case UIDocumentPickerMode.MoveToService: + documentPicker.DidPickDocument += DidPickDocumentForMove; + break; } PresentViewController (documentPicker, true, null); @@ -384,7 +382,7 @@ void OnPickerCancel (object sender, EventArgs e) Console.WriteLine ("Cancel pick document"); } - bool TryShowFileNotExistsError() + bool TryShowFileNotExistsError () { if (NSFileManager.DefaultManager.FileExists (documentURL.Path)) return false; @@ -395,10 +393,10 @@ bool TryShowFileNotExistsError() return true; } - void Unsibscribe(UIDocumentMenuViewController menu) + void Unsibscribe (UIDocumentMenuViewController menu) { menu.WasCancelled -= OnPickerSelectionCancel; menu.DidPickDocumentPicker -= OnPickerPicked; } } -} \ No newline at end of file +} diff --git a/ios8/NewBox/NewBox/ResourceHelper.cs b/ios8/NewBox/NewBox/ResourceHelper.cs index 2f47ac96a..47a762ec2 100644 --- a/ios8/NewBox/NewBox/ResourceHelper.cs +++ b/ios8/NewBox/NewBox/ResourceHelper.cs @@ -1,17 +1,15 @@ -using System; +using System; using System.Threading; using System.Threading.Tasks; using Foundation; using System.IO; -namespace NewBox -{ - public static class ResourceHelper - { - public static Task<NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) +namespace NewBox { + public static class ResourceHelper { + public static Task<NSUrl> CopyToDocumentsDirectoryAsync (NSUrl fromUrl) { - var tcs = new TaskCompletionSource<NSUrl>(); + var tcs = new TaskCompletionSource<NSUrl> (); NSUrl localDocDir = GetDocumentDirectoryUrl (); NSUrl toURL = localDocDir.Append (fromUrl.LastPathComponent, false); @@ -22,8 +20,8 @@ public static Task<NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) ThreadPool.QueueUserWorkItem (_ => { fileCoordinator.CoordinateReadWrite (fromUrl, 0, toURL, NSFileCoordinatorWritingOptions.ForReplacing, out coordinationError, (src, dst) => { - NSFileManager fileManager = new NSFileManager(); - success = fileManager.Copy(src, dst, out copyError); + NSFileManager fileManager = new NSFileManager (); + success = fileManager.Copy (src, dst, out copyError); if (success) { var attributes = new NSFileAttributes { @@ -39,13 +37,13 @@ public static Task<NSUrl> CopyToDocumentsDirectoryAsync(NSUrl fromUrl) Console.WriteLine ("Couldn't copy file: {0} to: {1}. Error: {2}.", fromUrl.AbsoluteString, toURL.AbsoluteString, (coordinationError ?? copyError).Description); - tcs.SetResult(toURL); + tcs.SetResult (toURL); }); return tcs.Task; } - static NSUrl GetDocumentDirectoryUrl() + static NSUrl GetDocumentDirectoryUrl () { var defaultManager = NSFileManager.DefaultManager; return defaultManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User) [0]; diff --git a/ios8/PhotoFilter/PhotoFilter/AppDelegate.cs b/ios8/PhotoFilter/PhotoFilter/AppDelegate.cs index 182052be7..b4ffff859 100644 --- a/ios8/PhotoFilter/PhotoFilter/AppDelegate.cs +++ b/ios8/PhotoFilter/PhotoFilter/AppDelegate.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using Foundation; -namespace PhotoFilter -{ +namespace PhotoFilter { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -25,4 +23,4 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return true; } } -} \ No newline at end of file +} diff --git a/ios8/PhotoFilter/PhotoFilter/Main.cs b/ios8/PhotoFilter/PhotoFilter/Main.cs index 8b967c344..ea1c12a54 100644 --- a/ios8/PhotoFilter/PhotoFilter/Main.cs +++ b/ios8/PhotoFilter/PhotoFilter/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace PhotoFilter -{ - public class Application - { +namespace PhotoFilter { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/PhotoFilter/PhotoFilter/ViewController.cs b/ios8/PhotoFilter/PhotoFilter/ViewController.cs index cdc93e351..6860252aa 100644 --- a/ios8/PhotoFilter/PhotoFilter/ViewController.cs +++ b/ios8/PhotoFilter/PhotoFilter/ViewController.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace PhotoFilter -{ - public class ViewController : UIViewController - { +namespace PhotoFilter { + public class ViewController : UIViewController { UILabel note; public override void ViewDidLoad () @@ -23,7 +21,7 @@ public override void ViewDidLoad () View.BackgroundColor = UIColor.White; View.AddConstraint (NSLayoutConstraint.Create (note, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterY, 1, 0)); - View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-[note]-|", (NSLayoutFormatOptions)0, "note", note)); + View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-[note]-|", (NSLayoutFormatOptions) 0, "note", note)); } } -} \ No newline at end of file +} diff --git a/ios8/PhotoFilter/PhotoFilterExtension/AVReaderWriter.cs b/ios8/PhotoFilter/PhotoFilterExtension/AVReaderWriter.cs index 279a0cd4d..0a9d85184 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/AVReaderWriter.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/AVReaderWriter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading; using System.IO; using System.Drawing; @@ -12,10 +12,8 @@ using CoreFoundation; using CoreGraphics; -namespace PhotoFilterExtension -{ - public class AVReaderWriter - { +namespace PhotoFilterExtension { + public class AVReaderWriter { readonly IVideoTransformer transformer; readonly AVAsset asset; @@ -48,17 +46,17 @@ public void WriteToUrl (NSUrl localOutputURL, Action<NSError> completion) completionProc = completion; // Dispatch the setup work with cancellationTokenSrc, to ensure this work can be cancelled - asset.LoadValuesTaskAsync (new string[] { "tracks", "duration" }).ContinueWith (_ => { + asset.LoadValuesTaskAsync (new string [] { "tracks", "duration" }).ContinueWith (_ => { // Since we are doing these things asynchronously, the user may have already cancelled on the main thread. // In that case, simply return from this block cancellationTokenSrc.Token.ThrowIfCancellationRequested (); NSError localError = null; - if(asset.StatusOfValue ("tracks", out localError) != AVKeyValueStatus.Loaded) + if (asset.StatusOfValue ("tracks", out localError) != AVKeyValueStatus.Loaded) throw new NSErrorException (localError); - if(asset.StatusOfValue ("duration", out localError) != AVKeyValueStatus.Loaded) + if (asset.StatusOfValue ("duration", out localError) != AVKeyValueStatus.Loaded) throw new NSErrorException (localError); var timeRange = new CMTimeRange { @@ -75,16 +73,16 @@ public void WriteToUrl (NSUrl localOutputURL, Action<NSError> completion) StartReadingAndWriting (timeRange); }, cancellationTokenSrc.Token).ContinueWith (prevTask => { switch (prevTask.Status) { - case TaskStatus.Canceled: - ReadingAndWritingDidFinish (false, null); - break; + case TaskStatus.Canceled: + ReadingAndWritingDidFinish (false, null); + break; - case TaskStatus.Faulted: - ReadingAndWritingDidFinish (false, ((NSErrorException)prevTask.Exception.InnerException).Error); - break; + case TaskStatus.Faulted: + ReadingAndWritingDidFinish (false, ((NSErrorException) prevTask.Exception.InnerException).Error); + break; - default: - break; + default: + break; } }); } @@ -118,17 +116,17 @@ void SetupAssetReaderWriterForAudio (AVAssetTrack audioTrack) // Decompress to Linear PCM with the asset reader // To read the media data from a specific asset track in the format in which it was stored, pass null to the settings parameter. - AVAssetReaderOutput output = AVAssetReaderTrackOutput.Create (audioTrack, (AudioSettings)null); + AVAssetReaderOutput output = AVAssetReaderTrackOutput.Create (audioTrack, (AudioSettings) null); if (assetReader.CanAddOutput (output)) assetReader.AddOutput (output); - AVAssetWriterInput input = AVAssetWriterInput.Create (audioTrack.MediaType, (AudioSettings)null); + AVAssetWriterInput input = AVAssetWriterInput.Create (audioTrack.MediaType, (AudioSettings) null); if (assetWriter.CanAddInput (input)) assetWriter.AddInput (input); // Create and save an instance of ReadWriteSampleBufferChannel, // which will coordinate the work of reading and writing sample buffers - audioSampleBufferChannel = new AudioChannel(output, input); + audioSampleBufferChannel = new AudioChannel (output, input); } void SetupAssetReaserWriterForVideo (AVAssetTrack videoTrack) @@ -145,7 +143,7 @@ void SetupAssetReaserWriterForVideo (AVAssetTrack videoTrack) assetReader.AddOutput (output); // Get the format description of the track, to fill in attributes of the video stream that we don't want to change - var formatDescription = (CMVideoFormatDescription)videoTrack.FormatDescriptions.FirstOrDefault (); + var formatDescription = (CMVideoFormatDescription) videoTrack.FormatDescriptions.FirstOrDefault (); // Grab track dimensions from format description CGSize trackDimensions = formatDescription != null ? formatDescription.GetPresentationDimensions (false, false) @@ -154,16 +152,16 @@ void SetupAssetReaserWriterForVideo (AVAssetTrack videoTrack) // Grab clean aperture, pixel aspect ratio from format description AVVideoCodecSettings compressionSettings = null; if (formatDescription != null) { - var cleanApertureDescr = (NSDictionary)formatDescription.GetExtension (CVImageBuffer.CleanApertureKey); - var pixelAspectRatioDescr = (NSDictionary)formatDescription.GetExtension (CVImageBuffer.PixelAspectRatioKey); + var cleanApertureDescr = (NSDictionary) formatDescription.GetExtension (CVImageBuffer.CleanApertureKey); + var pixelAspectRatioDescr = (NSDictionary) formatDescription.GetExtension (CVImageBuffer.PixelAspectRatioKey); compressionSettings = CreateCodecSettingsFor (cleanApertureDescr, pixelAspectRatioDescr); } // Compress to H.264 with the asset writer var videoSettings = new AVVideoSettingsCompressed { Codec = AVVideoCodec.H264, - Width = (int)trackDimensions.Width, - Height = (int)trackDimensions.Height, + Width = (int) trackDimensions.Width, + Height = (int) trackDimensions.Height, CodecSettings = compressionSettings }; AVAssetWriterInput input = new AVAssetWriterInput (videoTrack.MediaType, videoSettings); diff --git a/ios8/PhotoFilter/PhotoFilterExtension/FilterInfo.cs b/ios8/PhotoFilter/PhotoFilterExtension/FilterInfo.cs index 0a0e5199f..eeb5f75c0 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/FilterInfo.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/FilterInfo.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using Foundation; -namespace PhotoFilterExtension -{ - public class FilterInfo - { +namespace PhotoFilterExtension { + public class FilterInfo { const string filterNameKey = "filterName"; const string displayNameKey = "displayName"; const string previewImageKey = "previewImage"; @@ -28,9 +26,9 @@ public FilterInfo (NSDictionary storage) public void FillFrom (NSDictionary storage) { - FilterName = (NSString)storage [filterNameKey]; - DisplayName = (NSString)storage [displayNameKey]; - PreviewImage = (NSString)storage [previewImageKey]; + FilterName = (NSString) storage [filterNameKey]; + DisplayName = (NSString) storage [displayNameKey]; + PreviewImage = (NSString) storage [previewImageKey]; } } } diff --git a/ios8/PhotoFilter/PhotoFilterExtension/IVideoTransformer.cs b/ios8/PhotoFilter/PhotoFilterExtension/IVideoTransformer.cs index 81020ae47..e32ccc9e7 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/IVideoTransformer.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/IVideoTransformer.cs @@ -1,10 +1,8 @@ -using System; +using System; using CoreVideo; -namespace PhotoFilterExtension -{ - public interface IVideoTransformer - { +namespace PhotoFilterExtension { + public interface IVideoTransformer { void AdjustPixelBuffer (CVPixelBuffer inputBuffer, CVPixelBuffer outputBuffer); } } diff --git a/ios8/PhotoFilter/PhotoFilterExtension/PhotoEditingViewController.cs b/ios8/PhotoFilter/PhotoFilterExtension/PhotoEditingViewController.cs index 6f2db8cf5..7ead5dfa7 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/PhotoEditingViewController.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/PhotoEditingViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Drawing; using System.Collections.Generic; @@ -15,10 +15,8 @@ using CoreMedia; using System.Threading.Tasks; -namespace PhotoFilterExtension -{ - public partial class PhotoEditingViewController : UIViewController, IPHContentEditingController, IUICollectionViewDelegate, IUICollectionViewDataSource, IVideoTransformer - { +namespace PhotoFilterExtension { + public partial class PhotoEditingViewController : UIViewController, IPHContentEditingController, IUICollectionViewDelegate, IUICollectionViewDataSource, IVideoTransformer { const string kFilterInfoFilterNameKey = "filterName"; const string kFilterInfoDisplayNameKey = "displayName"; const string kFilterInfoPreviewImageKey = "previewImage"; @@ -27,7 +25,7 @@ public partial class PhotoEditingViewController : UIViewController, IPHContentEd PHContentEditingInput contentEditingInput; - FilterInfo[] availableFilterInfos; + FilterInfo [] availableFilterInfos; string selectedFilterName; string initialFilterName; @@ -71,8 +69,8 @@ public override void ViewDidLoad () effectView.TranslatesAutoresizingMaskIntoConstraints = false; View.InsertSubviewAbove (effectView, BackgroundImageView); - View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|[effectView]|", (NSLayoutFormatOptions)0, "effectView", effectView)); - View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[effectView]|", (NSLayoutFormatOptions)0, "effectView", effectView)); + View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|[effectView]|", (NSLayoutFormatOptions) 0, "effectView", effectView)); + View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|[effectView]|", (NSLayoutFormatOptions) 0, "effectView", effectView)); } void FetchAvailableFilters () @@ -82,7 +80,7 @@ void FetchAvailableFilters () var rawFiltersData = NSArray.FromFile (plist); nuint count = rawFiltersData.Count; - availableFilterInfos = new FilterInfo[count]; + availableFilterInfos = new FilterInfo [count]; for (nuint i = 0; i < count; i++) availableFilterInfos [i] = new FilterInfo (rawFiltersData.GetItem<NSDictionary> (i)); @@ -122,16 +120,16 @@ public void StartContentEditing (PHContentEditingInput input, UIImage placeholde // Load input image switch (contentEditingInput.MediaType) { - case PHAssetMediaType.Image: - inputImage = contentEditingInput.DisplaySizeImage; - break; + case PHAssetMediaType.Image: + inputImage = contentEditingInput.DisplaySizeImage; + break; - case PHAssetMediaType.Video: - inputImage = ImageFor (contentEditingInput.AvAsset, 0); - break; + case PHAssetMediaType.Video: + inputImage = ImageFor (contentEditingInput.AvAsset, 0); + break; - default: - break; + default: + break; } // Load adjustment data, if any @@ -147,14 +145,14 @@ public void StartContentEditing (PHContentEditingInput input, UIImage placeholde BackgroundImageView.Image = placeholderImage; } - static string FetchAdjustmentFilterName(PHContentEditingInput contentEditingInput) + static string FetchAdjustmentFilterName (PHContentEditingInput contentEditingInput) { string filterName = null; try { PHAdjustmentData adjustmentData = contentEditingInput.AdjustmentData; if (adjustmentData != null) - filterName = (NSString)NSKeyedUnarchiver.UnarchiveObject (adjustmentData.Data); + filterName = (NSString) NSKeyedUnarchiver.UnarchiveObject (adjustmentData.Data); } catch (Exception exception) { Console.WriteLine ("Exception decoding adjustment data: {0}", exception); } @@ -169,24 +167,24 @@ public void FinishContentEditing (Action<PHContentEditingOutput> completionHandl Task assetWork = null; switch (contentEditingInput.MediaType) { - case PHAssetMediaType.Image: - assetWork = FinishPhotoEditing (completionHandler); - break; + case PHAssetMediaType.Image: + assetWork = FinishPhotoEditing (completionHandler); + break; - case PHAssetMediaType.Video: - assetWork = FinishVideoEditing (completionHandler); - break; + case PHAssetMediaType.Video: + assetWork = FinishVideoEditing (completionHandler); + break; - default: - throw new NotImplementedException (); + default: + throw new NotImplementedException (); } assetWork.ContinueWith (_ => { - InvokeOnMainThread(()=> { + InvokeOnMainThread (() => { initialFilterName = null; - TryDisposeContentInputImage(); - TryDisposeContentInput(); + TryDisposeContentInputImage (); + TryDisposeContentInput (); inputImage.Dispose (); inputImage = null; @@ -202,13 +200,13 @@ public void FinishContentEditing (Action<PHContentEditingOutput> completionHandl }); } - PHAdjustmentData CreateAdjustmentData() + PHAdjustmentData CreateAdjustmentData () { - NSData archivedData = NSKeyedArchiver.ArchivedDataWithRootObject ((NSString)selectedFilterName); + NSData archivedData = NSKeyedArchiver.ArchivedDataWithRootObject ((NSString) selectedFilterName); return new PHAdjustmentData (BundleId, "1.0", archivedData); } - Task FinishPhotoEditing(Action<PHContentEditingOutput> completionHandler) + Task FinishPhotoEditing (Action<PHContentEditingOutput> completionHandler) { PHContentEditingOutput contentEditingOutput = CreateOutput (); @@ -236,7 +234,7 @@ Task FinishPhotoEditing(Action<PHContentEditingOutput> completionHandler) } } - Task FinishVideoEditing(Action<PHContentEditingOutput> completionHandler) + Task FinishVideoEditing (Action<PHContentEditingOutput> completionHandler) { PHContentEditingOutput contentEditingOutput = CreateOutput (); AVReaderWriter avReaderWriter = new AVReaderWriter (contentEditingInput.AvAsset, this); @@ -246,16 +244,16 @@ Task FinishVideoEditing(Action<PHContentEditingOutput> completionHandler) avReaderWriter.WriteToUrl (contentEditingOutput.RenderedContentUrl, error => { bool success = error == null; PHContentEditingOutput output = success ? contentEditingOutput : null; - if(!success) + if (!success) Console.WriteLine ("An error occured: {0}", error); completionHandler (output); - tcs.SetResult(null); // inform that we may safely clean up any data + tcs.SetResult (null); // inform that we may safely clean up any data }); return tcs.Task; } - PHContentEditingOutput CreateOutput() + PHContentEditingOutput CreateOutput () { PHContentEditingOutput contentEditingOutput = new PHContentEditingOutput (contentEditingInput); contentEditingOutput.AdjustmentData = CreateAdjustmentData (); @@ -348,12 +346,12 @@ public UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPat { var filterInfo = availableFilterInfos [indexPath.Item]; - var cell = (UICollectionViewCell)collectionView.DequeueReusableCell (PhotoFilterReuseId, indexPath); + var cell = (UICollectionViewCell) collectionView.DequeueReusableCell (PhotoFilterReuseId, indexPath); - var imageView = (UIImageView)cell.ViewWithTag (999); + var imageView = (UIImageView) cell.ViewWithTag (999); imageView.Image = UIImage.FromBundle (filterInfo.PreviewImage); - UILabel label = (UILabel)cell.ViewWithTag (998); + UILabel label = (UILabel) cell.ViewWithTag (998); label.Text = filterInfo.DisplayName; UpdateSelectionForCell (cell); @@ -384,11 +382,11 @@ void UpdateSelectionForCell (UICollectionViewCell cell) bool isSelected = cell.Selected; - UIImageView imageView = (UIImageView)cell.ViewWithTag (999); + UIImageView imageView = (UIImageView) cell.ViewWithTag (999); imageView.Layer.BorderColor = View.TintColor.CGColor; imageView.Layer.BorderWidth = isSelected ? 2 : 0; - UILabel label = (UILabel)cell.ViewWithTag (998); + UILabel label = (UILabel) cell.ViewWithTag (998); label.TextColor = isSelected ? View.TintColor : UIColor.White; } @@ -400,24 +398,24 @@ void UpdateSelectionForCell (UICollectionViewCell cell) CIImageOrientation Convert (UIImageOrientation imageOrientation) { switch (imageOrientation) { - case UIImageOrientation.Up: - return CIImageOrientation.TopLeft; - case UIImageOrientation.Down: - return CIImageOrientation.BottomRight; - case UIImageOrientation.Left: - return CIImageOrientation.LeftBottom; - case UIImageOrientation.Right: - return CIImageOrientation.RightTop; - case UIImageOrientation.UpMirrored: - return CIImageOrientation.TopRight; - case UIImageOrientation.DownMirrored: - return CIImageOrientation.BottomLeft; - case UIImageOrientation.LeftMirrored: - return CIImageOrientation.LeftTop; - case UIImageOrientation.RightMirrored: - return CIImageOrientation.RightBottom; - default: - throw new NotImplementedException (); + case UIImageOrientation.Up: + return CIImageOrientation.TopLeft; + case UIImageOrientation.Down: + return CIImageOrientation.BottomRight; + case UIImageOrientation.Left: + return CIImageOrientation.LeftBottom; + case UIImageOrientation.Right: + return CIImageOrientation.RightTop; + case UIImageOrientation.UpMirrored: + return CIImageOrientation.TopRight; + case UIImageOrientation.DownMirrored: + return CIImageOrientation.BottomLeft; + case UIImageOrientation.LeftMirrored: + return CIImageOrientation.LeftTop; + case UIImageOrientation.RightMirrored: + return CIImageOrientation.RightBottom; + default: + throw new NotImplementedException (); } } @@ -428,14 +426,14 @@ UIImage ImageFor (AVAsset avAsset, double time) CMTime actualTime; NSError error = null; - var requestedTime = new CMTime ((long)time, 100); + var requestedTime = new CMTime ((long) time, 100); using (CGImage posterImage = imageGenerator.CopyCGImageAtTime (requestedTime, out actualTime, out error)) return UIImage.FromImage (posterImage); } #endregion - void TryDisposeFilterInput() + void TryDisposeFilterInput () { if (ciFilter == null) return; @@ -447,7 +445,7 @@ void TryDisposeFilterInput() ciFilter.Image = null; } - void TryDisposeFilter() + void TryDisposeFilter () { if (ciFilter == null) return; @@ -456,7 +454,7 @@ void TryDisposeFilter() ciFilter = null; } - void TryDisposeFilterPreviewImg() + void TryDisposeFilterPreviewImg () { if (FilterPreviewView == null) return; @@ -468,7 +466,7 @@ void TryDisposeFilterPreviewImg() FilterPreviewView.Image = null; } - void TryDisposeContentInputImage() + void TryDisposeContentInputImage () { if (contentEditingInput == null) return; @@ -479,7 +477,7 @@ void TryDisposeContentInputImage() contentEditingInput.DisplaySizeImage.Dispose (); } - void TryDisposeContentInput() + void TryDisposeContentInput () { if (contentEditingInput == null) return; diff --git a/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/AudioChannel.cs b/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/AudioChannel.cs index 1e6a756b5..f701736c4 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/AudioChannel.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/AudioChannel.cs @@ -1,13 +1,11 @@ -using System; +using System; using AVFoundation; using CoreMedia; -namespace PhotoFilterExtension -{ - public class AudioChannel : ReadWriteSampleBufferChannel - { +namespace PhotoFilterExtension { + public class AudioChannel : ReadWriteSampleBufferChannel { public AudioChannel (AVAssetReaderOutput readerOutput, AVAssetWriterInput writerInput) - : base(readerOutput, writerInput) + : base (readerOutput, writerInput) { } diff --git a/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/ReadWriteSampleBufferChannel.cs b/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/ReadWriteSampleBufferChannel.cs index 499d12604..f6f4271f0 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/ReadWriteSampleBufferChannel.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/ReadWriteSampleBufferChannel.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Threading.Tasks; using AVFoundation; @@ -7,10 +7,8 @@ using Foundation; using CoreMedia; -namespace PhotoFilterExtension -{ - public abstract class ReadWriteSampleBufferChannel - { +namespace PhotoFilterExtension { + public abstract class ReadWriteSampleBufferChannel { readonly AVAssetReaderOutput readerOutput; protected AVAssetReaderOutput ReaderOutput { get { @@ -63,7 +61,7 @@ public Task StartAsync () void AdjustMediaData () { writerInput.RequestMediaData (serializationQueue, () => { - if(finished) + if (finished) return; bool shouldContinue = true; @@ -77,12 +75,12 @@ void AdjustMediaData () } } - if(!shouldContinue) + if (!shouldContinue) CompleteTask (); }); } - protected abstract bool Append(CMSampleBuffer sampleBuffer); + protected abstract bool Append (CMSampleBuffer sampleBuffer); public void Cancel () { diff --git a/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/VideoChannel.cs b/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/VideoChannel.cs index fb8c9d579..978ae1e5a 100644 --- a/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/VideoChannel.cs +++ b/ios8/PhotoFilter/PhotoFilterExtension/ReadWriteChannel/VideoChannel.cs @@ -1,17 +1,15 @@ -using System; +using System; using AVFoundation; using CoreVideo; using CoreMedia; -namespace PhotoFilterExtension -{ - public class VideoChannel : ReadWriteSampleBufferChannel - { +namespace PhotoFilterExtension { + public class VideoChannel : ReadWriteSampleBufferChannel { readonly IVideoTransformer transformer; readonly AVAssetWriterInputPixelBufferAdaptor adaptor; public VideoChannel (AVAssetReaderOutput readerOutput, AVAssetWriterInput writerInput, IVideoTransformer transformer) - : base(readerOutput, writerInput) + : base (readerOutput, writerInput) { if (transformer == null) throw new ArgumentNullException ("transformer"); @@ -31,7 +29,7 @@ protected override bool Append (CMSampleBuffer sampleBuffer) using (CVPixelBuffer writerBuffer = adaptor.PixelBufferPool.CreatePixelBuffer ()) { // Grab the pixel buffer from the sample buffer, if possible using (CVImageBuffer imageBuffer = sampleBuffer.GetImageBuffer ()) { - var pixelBuffer = (CVPixelBuffer)imageBuffer; + var pixelBuffer = (CVPixelBuffer) imageBuffer; if (pixelBuffer != null) transformer.AdjustPixelBuffer (pixelBuffer, writerBuffer); } diff --git a/ios8/PhotoHandoff/PhotoHandoff/AppDelegate.cs b/ios8/PhotoHandoff/PhotoHandoff/AppDelegate.cs index dfef67c46..09fd9d896 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/AppDelegate.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/AppDelegate.cs @@ -1,28 +1,26 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace PhotoHandoff -{ +namespace PhotoHandoff { [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { DataSource dataSource; public override UIWindow Window { get; set; } UINavigationController NavigationController { get { - return (UINavigationController)Window.RootViewController; + return (UINavigationController) Window.RootViewController; } } CollectionViewController PrimaryViewController { get { - return (CollectionViewController)NavigationController.ViewControllers[0]; + return (CollectionViewController) NavigationController.ViewControllers [0]; } } @@ -62,7 +60,7 @@ public override bool ContinueUserActivity (UIApplication application, NSUserActi var vc = PrimaryViewController; vc.HandleUserActivity (userActivity); - completionHandler(new NSObject[]{ NavigationController, vc}); + completionHandler (new NSObject [] { NavigationController, vc }); return true; } diff --git a/ios8/PhotoHandoff/PhotoHandoff/CollectionView/Cell.cs b/ios8/PhotoHandoff/PhotoHandoff/CollectionView/Cell.cs index d4ed2eb2f..83cdbd57d 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/CollectionView/Cell.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/CollectionView/Cell.cs @@ -1,23 +1,21 @@ -using System; +using System; using UIKit; using Foundation; -namespace PhotoHandoff -{ - [Register("Cell")] - public class Cell : UICollectionViewCell - { +namespace PhotoHandoff { + [Register ("Cell")] + public class Cell : UICollectionViewCell { UIColor labelColor; - [Outlet("image")] + [Outlet ("image")] public UIImageView Image { get; set; } - [Outlet("label")] + [Outlet ("label")] public UILabel Label { get; set; } public Cell (IntPtr handle) - : base(handle) + : base (handle) { SelectedBackgroundView = new CustomCellBackground (); } diff --git a/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CollectionViewController.cs b/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CollectionViewController.cs index 31dd6a441..f43166423 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CollectionViewController.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CollectionViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -6,23 +6,21 @@ using System.Globalization; using CoreFoundation; -namespace PhotoHandoff -{ - [Register("CollectionViewController")] - public class CollectionViewController : UICollectionViewController, INSUserActivityDelegate - { +namespace PhotoHandoff { + [Register ("CollectionViewController")] + public class CollectionViewController : UICollectionViewController, INSUserActivityDelegate { const string DetailedViewControllerID = "DetailView"; // view controller storyboard id const string DetailSegueName = "showDetail"; // segue ID to navigate to the detail view controller const string DetailViewControllerKey = "DetailViewControllerKey"; - readonly NSString CellID = new NSString("cellID"); // UICollectionViewCell id + readonly NSString CellID = new NSString ("cellID"); // UICollectionViewCell id DetailViewController detailViewController; public DataSource DataSource { get; set; } public CollectionViewController (IntPtr handle) - : base(handle) + : base (handle) { } public override void ViewDidAppear (bool animated) @@ -78,7 +76,7 @@ public void UserActivityWasContinued (NSUserActivity userActivity) }); } - void SaveActivity() + void SaveActivity () { if (UserActivity == null) { UserActivity = new NSUserActivity (NSBundle.MainBundle.BundleIdentifier) { @@ -93,15 +91,15 @@ void SaveActivity() PresentedViewController.UserActivity = UserActivity; } - void InstantiateAndPushDetailViewController(bool animated) + void InstantiateAndPushDetailViewController (bool animated) { // we use our bundle identifier to define the user activity - detailViewController = (DetailViewController)Storyboard.InstantiateViewController ("DetailViewController"); + detailViewController = (DetailViewController) Storyboard.InstantiateViewController ("DetailViewController"); detailViewController.DataSource = DataSource; NavigationController.PushViewController (detailViewController, animated); } - public bool HandleUserActivity(NSUserActivity userActivity) + public bool HandleUserActivity (NSUserActivity userActivity) { var userInfo = new UserInfo (userActivity.UserInfo); bool rc = HandleActivityUserInfo (userInfo); @@ -110,7 +108,7 @@ public bool HandleUserActivity(NSUserActivity userActivity) return rc; } - bool HandleActivityUserInfo(UserInfo userInfo) + bool HandleActivityUserInfo (UserInfo userInfo) { string imageIdentifier = userInfo.ImageId; if (string.IsNullOrEmpty (imageIdentifier)) { @@ -139,7 +137,7 @@ void ClearActivityContinuationInProgress () UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; } - public void PrepareForActivity() + public void PrepareForActivity () { if (detailViewController == null) InstantiateAndPushDetailViewController (true); @@ -152,7 +150,7 @@ public void PrepareForActivity() public void HandleActivityFailure () { // pop the current view controller since something failed - if (detailViewController != null && string.IsNullOrEmpty(detailViewController.ImageIdentifier)) + if (detailViewController != null && string.IsNullOrEmpty (detailViewController.ImageIdentifier)) NavigationController.PopToRootViewController (true); ClearActivityContinuationInProgress (); @@ -169,7 +167,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (Cell)collectionView.DequeueReusableCell (CellID, indexPath); + var cell = (Cell) collectionView.DequeueReusableCell (CellID, indexPath); string imageIdentifier = DataSource.IdentifierForIndexPath (indexPath); string text = DataSource.GetTitleForIdentifier (imageIdentifier); @@ -190,7 +188,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) NSIndexPath selectedIndexPath = CollectionView.GetIndexPathsForSelectedItems () [0]; string imageIdentifier = DataSource.IdentifierForIndexPath (selectedIndexPath); - detailViewController = (DetailViewController)segue.DestinationViewController; + detailViewController = (DetailViewController) segue.DestinationViewController; detailViewController.ImageIdentifier = imageIdentifier; detailViewController.DataSource = DataSource; SaveActivity (); // create our new NSUserActivity handled us @@ -207,7 +205,7 @@ public override void EncodeRestorableState (NSCoder coder) public override void DecodeRestorableState (NSCoder coder) { base.DecodeRestorableState (coder); - detailViewController = (DetailViewController)coder.DecodeObject (DetailViewControllerKey); + detailViewController = (DetailViewController) coder.DecodeObject (DetailViewControllerKey); } public override void ApplicationFinishedRestoringState () @@ -218,4 +216,4 @@ public override void ApplicationFinishedRestoringState () SaveActivity (); } } -} \ No newline at end of file +} diff --git a/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CustomCellBackground.cs b/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CustomCellBackground.cs index 86ea533be..c12bce068 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CustomCellBackground.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/CollectionView/CustomCellBackground.cs @@ -1,16 +1,14 @@ -using System; +using System; using UIKit; using Foundation; -namespace PhotoHandoff -{ - public class CustomCellBackground : UIView - { +namespace PhotoHandoff { + public class CustomCellBackground : UIView { public CustomCellBackground () { BackgroundColor = UIColor.LightGray; Layer.CornerRadius = 5; } } -} \ No newline at end of file +} diff --git a/ios8/PhotoHandoff/PhotoHandoff/DataSource.cs b/ios8/PhotoHandoff/PhotoHandoff/DataSource.cs index 712994e4f..087c93b25 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/DataSource.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/DataSource.cs @@ -1,23 +1,20 @@ -using System; +using System; using System.Globalization; using UIKit; using Foundation; -namespace PhotoHandoff -{ - public class DataSource : UIStateRestoring - { - class TitleStorage : DictionaryContainer - { - public TitleStorage(NSDictionary dictionary) - : base(dictionary) +namespace PhotoHandoff { + public class DataSource : UIStateRestoring { + class TitleStorage : DictionaryContainer { + public TitleStorage (NSDictionary dictionary) + : base (dictionary) { } - public string GetTitle(string identifier) + public string GetTitle (string identifier) { - return (string)(NSString)Dictionary [identifier]; + return (string) (NSString) Dictionary [identifier]; } } @@ -30,34 +27,34 @@ public DataSource () nameStorage = new TitleStorage (dict); } - public nint NumberOfItemsInSection(nint section) + public nint NumberOfItemsInSection (nint section) { return 32; } - public string IdentifierForIndexPath(NSIndexPath indexPath) + public string IdentifierForIndexPath (NSIndexPath indexPath) { return indexPath.Row.ToString (CultureInfo.InvariantCulture); } - public string GetTitleForIdentifier(string identifier) + public string GetTitleForIdentifier (string identifier) { string title = string.IsNullOrEmpty (identifier) ? "Image" : nameStorage.GetTitle (identifier); return title; } - public UIImage ThumbnailForIdentifier(string identifier) + public UIImage ThumbnailForIdentifier (string identifier) { - if (string.IsNullOrEmpty(identifier)) + if (string.IsNullOrEmpty (identifier)) return null; string pathToImage = FetchPath (identifier, "JPG"); return new UIImage (pathToImage); } - public UIImage ImageForIdentifier(string identifier) + public UIImage ImageForIdentifier (string identifier) { - if (string.IsNullOrEmpty(identifier)) + if (string.IsNullOrEmpty (identifier)) return null; string imageName = string.Format ("{0}_full", identifier); @@ -66,9 +63,9 @@ public UIImage ImageForIdentifier(string identifier) return image; } - static string FetchPath(string fileName, string ext) + static string FetchPath (string fileName, string ext) { return NSBundle.MainBundle.PathForResource (fileName, ext); } } -} \ No newline at end of file +} diff --git a/ios8/PhotoHandoff/PhotoHandoff/DetailViewController.cs b/ios8/PhotoHandoff/PhotoHandoff/DetailViewController.cs index 1c5996e74..84b02b01b 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/DetailViewController.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/DetailViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -9,11 +9,9 @@ using ObjCRuntime; using System.Runtime.InteropServices; -namespace PhotoHandoff -{ - [Register("DetailViewController")] - public class DetailViewController : UIViewController, IUIScrollViewDelegate, IUIPopoverPresentationControllerDelegate, IUIStateRestoring - { +namespace PhotoHandoff { + [Register ("DetailViewController")] + public class DetailViewController : UIViewController, IUIScrollViewDelegate, IUIPopoverPresentationControllerDelegate, IUIStateRestoring { const int BlurButtonTag = 1; const int SepiaButtonTag = 2; @@ -23,34 +21,34 @@ public class DetailViewController : UIViewController, IUIScrollViewDelegate, IUI const string kFilterButtonKey = "kFilterButtonKey"; const string kActivityViewControllerKey = "kActivityViewControllerKey"; - [Outlet("imageView")] + [Outlet ("imageView")] UIImageView ImageView { get; set; } UIImage image; bool filtering; bool needsFilter; - Dictionary<string, ImageFilter> filters = new Dictionary<string, ImageFilter>(); + Dictionary<string, ImageFilter> filters = new Dictionary<string, ImageFilter> (); - [Outlet("scrollView")] + [Outlet ("scrollView")] UIScrollView ScrollView { get; set; } - [Outlet("constraintLeft")] + [Outlet ("constraintLeft")] NSLayoutConstraint ConstraintLeft { get; set; } - [Outlet("constraintRight")] + [Outlet ("constraintRight")] NSLayoutConstraint ConstraintRight { get; set; } - [Outlet("constraintTop")] + [Outlet ("constraintTop")] NSLayoutConstraint ConstraintTop { get; set; } - [Outlet("constraintBottom")] + [Outlet ("constraintBottom")] NSLayoutConstraint ConstraintBottom { get; set; } - [Outlet("blurButton")] + [Outlet ("blurButton")] UIBarButtonItem BlurButton { get; set; } - [Outlet("sepiaButton")] + [Outlet ("sepiaButton")] UIBarButtonItem SepiaButton { get; set; } nfloat lastZoomScale; @@ -65,7 +63,7 @@ public class DetailViewController : UIViewController, IUIScrollViewDelegate, IUI public DataSource DataSource { get; set; } public DetailViewController (IntPtr handle) - : base(handle) + : base (handle) { } @@ -98,7 +96,7 @@ protected override void Dispose (bool disposing) base.Dispose (disposing); } - void CleanupFilters() + void CleanupFilters () { foreach (var item in filters) item.Value.DirtyChanged -= OnDirtyChanged; @@ -117,8 +115,8 @@ void UpdateImage (bool coalesce, bool animate) if (image == null) return; - var blurFilter = (BlurFilter)GetFilter (BlurFilter.Key); - var modifyFilter = (ModifyFilter)GetFilter (ModifyFilter.Key); + var blurFilter = (BlurFilter) GetFilter (BlurFilter.Key); + var modifyFilter = (ModifyFilter) GetFilter (ModifyFilter.Key); bool dirty = blurFilter != null ? blurFilter.Dirty : false; dirty |= modifyFilter != null ? modifyFilter.Dirty : false; filtering = true; @@ -127,39 +125,39 @@ void UpdateImage (bool coalesce, bool animate) Action runFilters = () => { var filterInput = new CIImage (image.CGImage); - CIImage filteredCIImage = Apply(blurFilter, filterInput, dirty); + CIImage filteredCIImage = Apply (blurFilter, filterInput, dirty); filterInput = filteredCIImage ?? new CIImage (image.CGImage); - filteredCIImage = Apply(modifyFilter, filterInput, dirty) ?? filteredCIImage; + filteredCIImage = Apply (modifyFilter, filterInput, dirty) ?? filteredCIImage; CGImage cgFilteredImage = null; if (filteredCIImage != null) { - CIContext context = CIContext.FromOptions (new CIContextOptions{ UseSoftwareRenderer = false }); + CIContext context = CIContext.FromOptions (new CIContextOptions { UseSoftwareRenderer = false }); cgFilteredImage = context.CreateCGImage (filteredCIImage, filteredCIImage.Extent); } if (coalesce) - InvokeOnMainThread (() => Apply(cgFilteredImage, image, dirty)); + InvokeOnMainThread (() => Apply (cgFilteredImage, image, dirty)); else - Apply(cgFilteredImage, image, dirty); + Apply (cgFilteredImage, image, dirty); }; if (coalesce) - Task.Delay (250).ContinueWith (_ => runFilters()); + Task.Delay (250).ContinueWith (_ => runFilters ()); else runFilters (); blurFilter.Dirty = modifyFilter.Dirty = false; } - ImageFilter GetFilter(string key) + ImageFilter GetFilter (string key) { ImageFilter filter; filters.TryGetValue (key, out filter); return filter; } - void Apply(CGImage filteredImage, UIImage defaultImage, bool dirty) + void Apply (CGImage filteredImage, UIImage defaultImage, bool dirty) { if (filteredImage != null) { ImageView.Image = new UIImage (filteredImage); @@ -181,7 +179,7 @@ void Apply(CGImage filteredImage, UIImage defaultImage, bool dirty) UpdateZoom (); } - void TryStartIndicatorForFilter() + void TryStartIndicatorForFilter () { if (currentFilterViewController == null) return; @@ -189,7 +187,7 @@ void TryStartIndicatorForFilter() currentFilterViewController.ActivityIndicator.StartAnimating (); } - void TryStopIndicatorForFilter() + void TryStopIndicatorForFilter () { if (currentFilterViewController == null) return; @@ -197,7 +195,7 @@ void TryStopIndicatorForFilter() currentFilterViewController.ActivityIndicator.StopAnimating (); } - bool TryInit(bool animate) + bool TryInit (bool animate) { if (image != null) return true; // already initialized @@ -213,7 +211,7 @@ bool TryInit(bool animate) return true; } - void SetTitleImage(string title, UIImage img, bool animate) + void SetTitleImage (string title, UIImage img, bool animate) { if (animate) { ImageView.Alpha = 0; @@ -228,7 +226,7 @@ void SetTitleImage(string title, UIImage img, bool animate) } } - CIImage Apply(BlurFilter blurFilter, CIImage input, bool dirty) + CIImage Apply (BlurFilter blurFilter, CIImage input, bool dirty) { if (blurFilter == null || !blurFilter.Active || !dirty) return null; @@ -240,7 +238,7 @@ CIImage Apply(BlurFilter blurFilter, CIImage input, bool dirty) return filter.OutputImage; } - CIImage Apply(ModifyFilter modifyFilter, CIImage input, bool dirty) + CIImage Apply (ModifyFilter modifyFilter, CIImage input, bool dirty) { if (modifyFilter == null || !modifyFilter.Active || !dirty) return null; @@ -257,9 +255,9 @@ public void DismissFromUserActivity (Action completionHandler) { InvokeOnMainThread (() => { if (currentFilterViewController != null) - currentFilterViewController.DismissViewController(false, completionHandler); - else if(completionHandler != null) - completionHandler(); + currentFilterViewController.DismissViewController (false, completionHandler); + else if (completionHandler != null) + completionHandler (); }); } @@ -315,7 +313,7 @@ void UpdateZoom () var img = ImageView.Image; var imgSize = img != null ? img.Size : CGSize.Empty; - nfloat minZoom = NMath.Min(scrollSize.Width / imgSize.Width, scrollSize.Height / imgSize.Height); + nfloat minZoom = NMath.Min (scrollSize.Width / imgSize.Width, scrollSize.Height / imgSize.Height); minZoom = NMath.Min (1, minZoom); @@ -341,27 +339,27 @@ public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrie #region Filtering - void OnDirtyChanged(object sender, EventArgs e) + void OnDirtyChanged (object sender, EventArgs e) { - var filter = (ImageFilter)sender; + var filter = (ImageFilter) sender; - if(filter.Dirty) + if (filter.Dirty) UpdateImage (true, false); } - ImageFilter CreateImageFilter(string key) + ImageFilter CreateImageFilter (string key) { ImageFilter filter; if (!filters.TryGetValue (key, out filter)) { filter = CreateFilter (key, true); Subscribe (filter); - filters[key] = filter; + filters [key] = filter; } return filter; } - static ImageFilter CreateFilter(string key, bool setDefaults) + static ImageFilter CreateFilter (string key, bool setDefaults) { ImageFilter filter = null; if (key == BlurFilter.Key) @@ -373,7 +371,7 @@ static ImageFilter CreateFilter(string key, bool setDefaults) UIApplication.RegisterObjectForStateRestoration (filter, key); filter.Dirty = false; - filter.RestorationType = typeof(DetailViewController); + filter.RestorationType = typeof (DetailViewController); return filter; } @@ -393,14 +391,14 @@ void DidDismissPopover (UIPopoverPresentationController popoverPresentationContr // We are notified when our FilterViewController is // being dismissed on its own - public void WasDismissed() + public void WasDismissed () { currentFilterViewController = null; } - void CreateAndPresentFilterVC(UIBarButtonItem sender, ImageFilter filter, string identifier) + void CreateAndPresentFilterVC (UIBarButtonItem sender, ImageFilter filter, string identifier) { - currentFilterViewController = (FilterViewController)Storyboard.InstantiateViewController (identifier); + currentFilterViewController = (FilterViewController) Storyboard.InstantiateViewController (identifier); currentFilterViewController.Filter = filter; currentFilterViewController.ModalPresentationStyle = UIModalPresentationStyle.Popover; currentFilterViewController.PopoverPresentationController.BarButtonItem = sender; @@ -415,10 +413,10 @@ void CreateAndPresentFilterVC(UIBarButtonItem sender, ImageFilter filter, string PresentViewController (currentFilterViewController, true, () => UpdateImage (false, false)); } - [Export("presentFilter:")] - void PresentFilter(NSObject sender) + [Export ("presentFilter:")] + void PresentFilter (NSObject sender) { - var button = (UIBarButtonItem)sender; + var button = (UIBarButtonItem) sender; string key = null, identifier = null; if (button.Tag == BlurButtonTag) { @@ -436,17 +434,17 @@ void PresentFilter(NSObject sender) ImageFilter filter = CreateImageFilter (key); // check for activity view controller is open, dismiss it - TryDismiss (activityViewController, ()=> { + TryDismiss (activityViewController, () => { activityViewController = null; - TryDismiss(currentFilterViewController, () => CreateAndPresentFilterVC (button, filter, identifier)); + TryDismiss (currentFilterViewController, () => CreateAndPresentFilterVC (button, filter, identifier)); }); } - void TryDismiss(UIViewController controller, Action completionHandler) + void TryDismiss (UIViewController controller, Action completionHandler) { if (controller != null) controller.DismissViewController (false, completionHandler); - else if(completionHandler != null) + else if (completionHandler != null) completionHandler (); } @@ -467,16 +465,16 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) return; ImageFilter filter = CreateImageFilter (key); - var filterViewController = (FilterViewController)segue.DestinationViewController; + var filterViewController = (FilterViewController) segue.DestinationViewController; filterViewController.Filter = filter; } - void CleanupActivity() + void CleanupActivity () { activityViewController = null; } - void SetupActivityCompletion() + void SetupActivityCompletion () { if (activityViewController == null) return; @@ -484,21 +482,21 @@ void SetupActivityCompletion() activityViewController.SetCompletionHandler ((aType, completed, items, aError) => CleanupActivity ()); } - [Export("share:")] - void Share(NSObject sender) + [Export ("share:")] + void Share (NSObject sender) { if (ImageView.Image == null) return; - var items = new NSObject[] { + var items = new NSObject [] { ImageView.Image }; activityViewController = new UIActivityViewController (items, null) { ModalPresentationStyle = UIModalPresentationStyle.Popover, RestorationIdentifier = "Activity" }; - if(activityViewController.PopoverPresentationController != null) - activityViewController.PopoverPresentationController.BarButtonItem = (UIBarButtonItem)sender; + if (activityViewController.PopoverPresentationController != null) + activityViewController.PopoverPresentationController.BarButtonItem = (UIBarButtonItem) sender; SetupActivityCompletion (); TryDismiss (currentFilterViewController, () => { @@ -515,7 +513,7 @@ void Share(NSObject sender) #region UIStateRestoration [Export ("objectWithRestorationIdentifierPath:coder:")] - static UIStateRestoring Restore (string[] identifierComponents, NSCoder coder) + static UIStateRestoring Restore (string [] identifierComponents, NSCoder coder) { string key = identifierComponents [identifierComponents.Length - 1]; return CreateFilter (key, false); @@ -525,12 +523,12 @@ public override void EncodeRestorableState (NSCoder coder) { base.EncodeRestorableState (coder); // TODO: https://trello.com/c/TydBAJP0 - coder.Encode ((NSString)ImageIdentifier, kImageIdentifierKey); + coder.Encode ((NSString) ImageIdentifier, kImageIdentifierKey); coder.Encode (DataSource, kDataSourceKey); coder.Encode (filters.Convert (), kImageFiltersKey); if (!string.IsNullOrEmpty (currentlyPresentedFilterTitle)) - coder.Encode ((NSString)currentlyPresentedFilterTitle, kFilterButtonKey); + coder.Encode ((NSString) currentlyPresentedFilterTitle, kFilterButtonKey); coder.Encode (activityViewController, kActivityViewControllerKey); } @@ -540,19 +538,19 @@ public override void DecodeRestorableState (NSCoder coder) base.DecodeRestorableState (coder); // TODO: https://trello.com/c/TydBAJP0 - ImageIdentifier = (NSString)coder.DecodeObject (kImageIdentifierKey); - DataSource = (DataSource)coder.DecodeObject (kDataSourceKey); + ImageIdentifier = (NSString) coder.DecodeObject (kImageIdentifierKey); + DataSource = (DataSource) coder.DecodeObject (kDataSourceKey); NSObject nDict; if (coder.TryDecodeObject (kImageFiltersKey, out nDict)) - filters = ((NSDictionary)nDict).Convert<ImageFilter> (); + filters = ((NSDictionary) nDict).Convert<ImageFilter> (); // TODO: https://trello.com/c/TydBAJP0 - currentlyPresentedFilterTitle = (NSString)coder.DecodeObject (kFilterButtonKey); + currentlyPresentedFilterTitle = (NSString) coder.DecodeObject (kFilterButtonKey); NSObject avc; if (coder.TryDecodeObject (kActivityViewControllerKey, out avc)) - activityViewController = (UIActivityViewController)avc; + activityViewController = (UIActivityViewController) avc; SetupActivityCompletion (); } @@ -566,31 +564,31 @@ public override void ApplicationFinishedRestoringState () TryPresentFilterButton (); } - void CenterImageView() + void CenterImageView () { CGSize size = View.Bounds.Size; CGPoint imageCenter = ImageView.Center; - var center = new CGPoint(size.Width / 2, size.Height / 2); + var center = new CGPoint (size.Width / 2, size.Height / 2); ImageView.Center = center; ImageView.Bounds = View.Bounds; UpdateImage (false, false); } - void SubscribeToFilters() + void SubscribeToFilters () { foreach (var kvp in filters) Subscribe (kvp.Value); } - void Subscribe(ImageFilter subject) + void Subscribe (ImageFilter subject) { subject.DirtyChanged += OnDirtyChanged; } - void TryPresentFilterButton() + void TryPresentFilterButton () { if (UIDevice.CurrentDevice.UserInterfaceIdiom != UIUserInterfaceIdiom.Pad - || string.IsNullOrEmpty (currentlyPresentedFilterTitle)) + || string.IsNullOrEmpty (currentlyPresentedFilterTitle)) return; UIBarButtonItem button = GetCurrentFilterButton (); @@ -598,7 +596,7 @@ void TryPresentFilterButton() InvokeOnMainThread (() => PresentFilter (button)); } - UIBarButtonItem GetCurrentFilterButton() + UIBarButtonItem GetCurrentFilterButton () { if (currentlyPresentedFilterTitle == "blur") return BlurButton; @@ -636,17 +634,17 @@ public override void UpdateUserActivityState (NSUserActivity activity) activity.AddUserInfoEntries (info.Dictionary); } - UserInfo GetFilterValues() + UserInfo GetFilterValues () { var info = new UserInfo (); // obtain the filter values and save them ImageFilter filter; - if(filters.TryGetValue (BlurFilter.Key, out filter)) - info.BlurRadius = ((BlurFilter)filter).BlurRadius; + if (filters.TryGetValue (BlurFilter.Key, out filter)) + info.BlurRadius = ((BlurFilter) filter).BlurRadius; if (filters.TryGetValue (ModifyFilter.Key, out filter)) - info.Intensity = ((ModifyFilter)filter).Intensity; + info.Intensity = ((ModifyFilter) filter).Intensity; return info; } @@ -668,14 +666,14 @@ public void RestoreActivityForImageIdentifier (UserInfo userInfo) // setup our filters (if not already allocated) and assign their values float blurFilterValue = userInfo.BlurRadius; - var blurFilter = (BlurFilter)CreateImageFilter (BlurFilter.Key); + var blurFilter = (BlurFilter) CreateImageFilter (BlurFilter.Key); blurFilter.BlurRadius = blurFilterValue; // the blur has changed from the activity on the other device blurFilter.Dirty = blurFilterValue > 0 ? true : blurFilter.Dirty; var sepiaFilterValue = userInfo.Intensity; - var sepiaFilter = (ModifyFilter)CreateImageFilter (ModifyFilter.Key); + var sepiaFilter = (ModifyFilter) CreateImageFilter (ModifyFilter.Key); sepiaFilter.Intensity = sepiaFilterValue; // the sepia has changed from the activity on the other device sepiaFilter.Dirty = sepiaFilterValue > 0 ? true : sepiaFilter.Dirty; @@ -694,11 +692,11 @@ public void RestoreActivityForImageIdentifier (UserInfo userInfo) activityViewController.DismissViewController (false, null); } - void SetActivityViewControllerCompletionHandler(UserInfo info) + void SetActivityViewControllerCompletionHandler (UserInfo info) { activityViewController.SetCompletionHandler ((activityType, completed, returnedItems, error) => { - CleanupActivity(); - RestoreActivityForImageIdentifier(info); + CleanupActivity (); + RestoreActivityForImageIdentifier (info); }); } diff --git a/ios8/PhotoHandoff/PhotoHandoff/Filtering/BlurFilter.cs b/ios8/PhotoHandoff/PhotoHandoff/Filtering/BlurFilter.cs index 5fc4405cd..4d6826caa 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/Filtering/BlurFilter.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/Filtering/BlurFilter.cs @@ -1,17 +1,15 @@ -using System; +using System; using Foundation; -namespace PhotoHandoff -{ - public class BlurFilter : ImageFilter - { +namespace PhotoHandoff { + public class BlurFilter : ImageFilter { const string BlurRadiusKey = "kImageFilterBlurRadiusKey"; internal const string Key = "BlurFilter"; public float BlurRadius { get; set; } public BlurFilter (bool active) - : base(active) + : base (active) { } @@ -28,4 +26,4 @@ public override void DecodeRestorableState (NSCoder coder) BlurRadius = coder.DecodeFloat (BlurRadiusKey); } } -} \ No newline at end of file +} diff --git a/ios8/PhotoHandoff/PhotoHandoff/Filtering/FilterViewController.cs b/ios8/PhotoHandoff/PhotoHandoff/Filtering/FilterViewController.cs index dafeb6f3b..e0d5ae780 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/Filtering/FilterViewController.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/Filtering/FilterViewController.cs @@ -1,25 +1,23 @@ -using System; +using System; using UIKit; using Foundation; -namespace PhotoHandoff -{ - [Register("FilterViewController")] - public class FilterViewController : UIViewController - { +namespace PhotoHandoff { + [Register ("FilterViewController")] + public class FilterViewController : UIViewController { const string ImageFilterKey = "kImageFilterKey"; - [Outlet("slider")] + [Outlet ("slider")] UISlider Slider { get; set; } - [Outlet("activeSwitch")] + [Outlet ("activeSwitch")] UISwitch ActiveSwitch { get; set; } - [Outlet("navigationBar")] + [Outlet ("navigationBar")] UINavigationBar NavigationBar { get; set; } - [Outlet("activityIndicator")] + [Outlet ("activityIndicator")] public UIActivityIndicatorView ActivityIndicator { get; set; } public ImageFilter Filter { get; set; } @@ -34,12 +32,12 @@ ModifyFilter ModifyFilter { get { return Filter as ModifyFilter; } - } + } public DetailViewController MasterViewController { get; set; } - public FilterViewController(IntPtr handle) - : base(handle) + public FilterViewController (IntPtr handle) + : base (handle) { } @@ -60,19 +58,19 @@ public override void ViewWillAppear (bool animated) Update (); } - [Export("dismiss:")] - void Dismiss(NSObject sender) + [Export ("dismiss:")] + void Dismiss (NSObject sender) { // inform our MasterViewController we are going away - Action completionHandler = MasterViewController != null ? MasterViewController.WasDismissed : (Action)null; + Action completionHandler = MasterViewController != null ? MasterViewController.WasDismissed : (Action) null; PresentingViewController.DismissViewController (true, completionHandler); } #region Filtering // blue slider value has changed - [Export("setBlurValue:")] - void SetBlurValue(NSObject sender) + [Export ("setBlurValue:")] + void SetBlurValue (NSObject sender) { if (BlurFilter == null || Slider == null) return; @@ -82,8 +80,8 @@ void SetBlurValue(NSObject sender) } // sepia intensity slider value has changed - [Export("setIntensity:")] - void SetIntensity(NSObject sender) + [Export ("setIntensity:")] + void SetIntensity (NSObject sender) { if (ModifyFilter == null && Slider == null) return; @@ -93,8 +91,8 @@ void SetIntensity(NSObject sender) } // active or on/off switch has changed - [Export("setActiveValue:")] - void SetActiveValue(NSObject sender) + [Export ("setActiveValue:")] + void SetActiveValue (NSObject sender) { Filter.Active = ActiveSwitch.On; Filter.Dirty = true; @@ -134,7 +132,7 @@ public override void DecodeRestorableState (NSCoder coder) { base.DecodeRestorableState (coder); if (coder.ContainsKey (ImageFilterKey)) - Filter = (ImageFilter)coder.DecodeObject (ImageFilterKey); + Filter = (ImageFilter) coder.DecodeObject (ImageFilterKey); } public override void ApplicationFinishedRestoringState () @@ -145,4 +143,4 @@ public override void ApplicationFinishedRestoringState () #endregion } -} \ No newline at end of file +} diff --git a/ios8/PhotoHandoff/PhotoHandoff/Filtering/ImageFilter.cs b/ios8/PhotoHandoff/PhotoHandoff/Filtering/ImageFilter.cs index 5e7c6102b..ac8b602da 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/Filtering/ImageFilter.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/Filtering/ImageFilter.cs @@ -1,13 +1,11 @@ -using System; +using System; using Foundation; using UIKit; using ObjCRuntime; -namespace PhotoHandoff -{ - public class ImageFilter : UIStateRestoring - { +namespace PhotoHandoff { + public class ImageFilter : UIStateRestoring { const string ActiveKey = "kImageFilterActiveKey"; public event EventHandler DirtyChanged; diff --git a/ios8/PhotoHandoff/PhotoHandoff/Filtering/ModifyFilter.cs b/ios8/PhotoHandoff/PhotoHandoff/Filtering/ModifyFilter.cs index 789777686..531be6992 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/Filtering/ModifyFilter.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/Filtering/ModifyFilter.cs @@ -1,17 +1,15 @@ -using System; +using System; using Foundation; -namespace PhotoHandoff -{ - public class ModifyFilter : ImageFilter - { +namespace PhotoHandoff { + public class ModifyFilter : ImageFilter { const string IntensityKey = "kImageFilterIntensityKey"; internal const string Key = "ModifyFilter"; public float Intensity { get; set; } public ModifyFilter (bool active) - : base(active) + : base (active) { } diff --git a/ios8/PhotoHandoff/PhotoHandoff/Main.cs b/ios8/PhotoHandoff/PhotoHandoff/Main.cs index f7dddc88b..7c1ad194b 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/Main.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace PhotoHandoff -{ - public class Application - { +namespace PhotoHandoff { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/PhotoHandoff/PhotoHandoff/UserInfo.cs b/ios8/PhotoHandoff/PhotoHandoff/UserInfo.cs index e915dd518..9207b02f8 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/UserInfo.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/UserInfo.cs @@ -1,29 +1,27 @@ -using System; +using System; using Foundation; -namespace PhotoHandoff -{ - public class UserInfo : DictionaryContainer - { +namespace PhotoHandoff { + public class UserInfo : DictionaryContainer { const string BlurKey = "activityImageBlurKey"; const string SepiaKey = "activityImageSepiaKey"; const string ImageKey = "imageIdentifier"; public float BlurRadius { get { - return GetFloatValue ((NSString)BlurKey).Value; + return GetFloatValue ((NSString) BlurKey).Value; } set { - SetNumberValue ((NSString)BlurKey, value); + SetNumberValue ((NSString) BlurKey, value); } } public float Intensity { get { - return GetFloatValue ((NSString)SepiaKey).Value; + return GetFloatValue ((NSString) SepiaKey).Value; } set { - SetNumberValue ((NSString)SepiaKey, value); + SetNumberValue ((NSString) SepiaKey, value); } } @@ -32,18 +30,18 @@ public string ImageId { return base.GetStringValue (ImageKey); } set { - SetStringValue ((NSString)ImageKey, value); + SetStringValue ((NSString) ImageKey, value); } } - public UserInfo() + public UserInfo () { } - public UserInfo(NSDictionary dictionary) + public UserInfo (NSDictionary dictionary) { - var mDict = (NSMutableDictionary)Dictionary; + var mDict = (NSMutableDictionary) Dictionary; foreach (var item in dictionary) mDict.Add (item.Key, item.Value); } diff --git a/ios8/PhotoHandoff/PhotoHandoff/Utils.cs b/ios8/PhotoHandoff/PhotoHandoff/Utils.cs index 4c032edcd..2cfcfe81e 100644 --- a/ios8/PhotoHandoff/PhotoHandoff/Utils.cs +++ b/ios8/PhotoHandoff/PhotoHandoff/Utils.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using System.Collections.Generic; -namespace PhotoHandoff -{ - public static class Utils - { - public static NSDictionary Convert<T>(this Dictionary<string, T> dict) where T : NSObject +namespace PhotoHandoff { + public static class Utils { + public static NSDictionary Convert<T> (this Dictionary<string, T> dict) where T : NSObject { if (dict == null) throw new ArgumentNullException ("dict"); @@ -14,23 +12,23 @@ public static NSDictionary Convert<T>(this Dictionary<string, T> dict) where T : var nativeDict = new NSMutableDictionary (); foreach (var item in dict) - nativeDict.Add ((NSString)item.Key, item.Value); + nativeDict.Add ((NSString) item.Key, item.Value); return nativeDict; } - public static Dictionary<string, T> Convert<T>(this NSDictionary nativeDict) where T : NSObject + public static Dictionary<string, T> Convert<T> (this NSDictionary nativeDict) where T : NSObject { var dict = new Dictionary<string, T> (); foreach (var item in nativeDict) - dict.Add ((NSString)item.Key, (T)item.Value); + dict.Add ((NSString) item.Key, (T) item.Value); return dict; } // https://trello.com/c/TydBAJP0 - public static bool TryDecodeObject(this NSCoder coder, string key, out NSObject obj) + public static bool TryDecodeObject (this NSCoder coder, string key, out NSObject obj) { obj = null; diff --git a/ios8/SceneKitVehicle/SceneKitVehicle/AppDelegate.cs b/ios8/SceneKitVehicle/SceneKitVehicle/AppDelegate.cs index f239beec7..39c1ec3f7 100644 --- a/ios8/SceneKitVehicle/SceneKitVehicle/AppDelegate.cs +++ b/ios8/SceneKitVehicle/SceneKitVehicle/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace SceneKitVehicle -{ +namespace SceneKitVehicle { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios8/SceneKitVehicle/SceneKitVehicle/GameView.cs b/ios8/SceneKitVehicle/SceneKitVehicle/GameView.cs index b94c92e8e..25f3d6a8a 100644 --- a/ios8/SceneKitVehicle/SceneKitVehicle/GameView.cs +++ b/ios8/SceneKitVehicle/SceneKitVehicle/GameView.cs @@ -10,10 +10,8 @@ using System.Linq; using System.Diagnostics; -namespace SceneKitVehicle -{ - public partial class GameView : SCNView - { +namespace SceneKitVehicle { + public partial class GameView : SCNView { public int TouchesCount { get; set; } public bool InCarView { get; set; } @@ -52,7 +50,7 @@ public void ChangePointOfView () public override void TouchesBegan (NSSet touches, UIEvent evt) { - var touch = (UITouch)touches.AnyObject; + var touch = (UITouch) touches.AnyObject; SKScene scene = OverlayScene; CGPoint p = touch.LocationInView (this); @@ -66,7 +64,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) } NSSet allTouches = evt.AllTouches; - TouchesCount = (int)allTouches.Count; + TouchesCount = (int) allTouches.Count; } public override void TouchesEnded (NSSet touches, UIEvent evt) diff --git a/ios8/SceneKitVehicle/SceneKitVehicle/GameViewController.cs b/ios8/SceneKitVehicle/SceneKitVehicle/GameViewController.cs index c2eb82afa..85e4bdc52 100644 --- a/ios8/SceneKitVehicle/SceneKitVehicle/GameViewController.cs +++ b/ios8/SceneKitVehicle/SceneKitVehicle/GameViewController.cs @@ -7,10 +7,8 @@ using UIKit; using CoreGraphics; -namespace SceneKitVehicle -{ - public partial class GameViewController : UIViewController - { +namespace SceneKitVehicle { + public partial class GameViewController : UIViewController { private SCNNode spotLightNode; private SCNNode cameraNode; private SCNNode vehicleNode; @@ -48,7 +46,7 @@ public override void ViewDidLoad () { UIApplication.SharedApplication.SetStatusBarHidden (true, true); - var scnView = (SCNView)View; + var scnView = (SCNView) View; scnView.BackgroundColor = UIColor.Black; scnView.Scene = SetupScene (); scnView.Scene.PhysicsWorld.Speed = 4f; @@ -88,14 +86,14 @@ public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations () public void AccelerometerDidChange (CMAcceleration acceleration) { float filteringFactor = 0.5f; - accelerometer.X = (float)acceleration.X * filteringFactor + accelerometer.X * (1f - filteringFactor); - accelerometer.Y = (float)acceleration.Y * filteringFactor + accelerometer.Y * (1f - filteringFactor); - accelerometer.Z = (float)acceleration.Z * filteringFactor + accelerometer.Z * (1f - filteringFactor); + accelerometer.X = (float) acceleration.X * filteringFactor + accelerometer.X * (1f - filteringFactor); + accelerometer.Y = (float) acceleration.Y * filteringFactor + accelerometer.Y * (1f - filteringFactor); + accelerometer.Z = (float) acceleration.Z * filteringFactor + accelerometer.Z * (1f - filteringFactor); if (accelerometer.X > 0) { - orientation = (float)(accelerometer.Y * 1.3f); + orientation = (float) (accelerometer.Y * 1.3f); } else { - orientation = (float)(-accelerometer.Y * 1.3f); + orientation = (float) (-accelerometer.Y * 1.3f); } } @@ -189,25 +187,25 @@ public virtual void DidSimulatePhysics (ISCNSceneRenderer renderer, double timeI if (scnView.InCarView) { var frontPosition = scnView.PointOfView.PresentationNode.ConvertPositionToNode (new SCNVector3 (0f, 0f, -30f), null); spotLightNode.Position = new SCNVector3 (frontPosition.X, 80f, frontPosition.Z); - spotLightNode.Rotation = new SCNVector4 (1f, 0f, 0f, -(float)Math.PI / 2f); + spotLightNode.Rotation = new SCNVector4 (1f, 0f, 0f, -(float) Math.PI / 2f); } else { spotLightNode.Position = new SCNVector3 (carPos.X, 80f, carPos.Z + 30f); - spotLightNode.Rotation = new SCNVector4 (1f, 0f, 0f, -(float)(Math.PI / 2.8)); + spotLightNode.Rotation = new SCNVector4 (1f, 0f, 0f, -(float) (Math.PI / 2.8)); } - var overlayScene = (OverlayScene)scnView.OverlayScene; - overlayScene.SpeedNeedle.ZRotation = -(vehicle.SpeedInKilometersPerHour * (float)Math.PI / maxSpeed); + var overlayScene = (OverlayScene) scnView.OverlayScene; + overlayScene.SpeedNeedle.ZRotation = -(vehicle.SpeedInKilometersPerHour * (float) Math.PI / maxSpeed); } private void HandleDoubleTap (UITapGestureRecognizer gesture) { - var scnView = (SCNView)View; + var scnView = (SCNView) View; scnView.Scene = SetupScene (); scnView.Scene.PhysicsWorld.Speed = 4f; scnView.PointOfView = cameraNode; - ((GameView)scnView).TouchesCount = 0; + ((GameView) scnView).TouchesCount = 0; } private void ReorientCarIfNeeded () @@ -261,7 +259,7 @@ private void AddTrainToScene (SCNScene scene, SCNVector3 position) { var max = SCNVector3.Zero; var min = SCNVector3.Zero; - var trainScene = SCNScene.FromFile ("train_flat", ResourceManager.ResourceFolder, (NSDictionary)null); + var trainScene = SCNScene.FromFile ("train_flat", ResourceManager.ResourceFolder, (NSDictionary) null); foreach (var node in trainScene.RootNode.ChildNodes) { if (node.Geometry != null) { @@ -284,7 +282,7 @@ private void AddTrainToScene (SCNScene scene, SCNVector3 position) ChamferRadius = 0f }; - body.PhysicsShape = SCNPhysicsShape.Create (boxShape, (NSDictionary)null); + body.PhysicsShape = SCNPhysicsShape.Create (boxShape, (NSDictionary) null); node.Pivot = SCNMatrix4.CreateTranslation (0f, -min.Y, 0f); node.PhysicsBody = body; scene.RootNode.AddChildNode (node); @@ -375,12 +373,12 @@ private void SetupSceneElements (SCNScene scene) wall = wall.Clone (); wall.Position = new SCNVector3 (202f, 50f, 0f); - wall.Rotation = new SCNVector4 (0f, 1f, 0f, (float)Math.PI / 2f); + wall.Rotation = new SCNVector4 (0f, 1f, 0f, (float) Math.PI / 2f); scene.RootNode.AddChildNode (wall); wall = wall.Clone (); wall.Position = new SCNVector3 (-202f, 50f, 0f); - wall.Rotation = new SCNVector4 (0f, 1f, 0f, -(float)Math.PI / 2f); + wall.Rotation = new SCNVector4 (0f, 1f, 0f, -(float) Math.PI / 2f); scene.RootNode.AddChildNode (wall); var planeGeometry = new SCNPlane { @@ -391,7 +389,7 @@ private void SetupSceneElements (SCNScene scene) var backWall = SCNNode.FromGeometry (planeGeometry); backWall.Geometry.FirstMaterial = wall.Geometry.FirstMaterial; backWall.Position = new SCNVector3 (0f, 50f, 200f); - backWall.Rotation = new SCNVector4 (0f, 1f, 0f, (float)Math.PI); + backWall.Rotation = new SCNVector4 (0f, 1f, 0f, (float) Math.PI); backWall.CastsShadow = false; backWall.PhysicsBody = SCNPhysicsBody.CreateStaticBody (); scene.RootNode.AddChildNode (backWall); @@ -403,7 +401,7 @@ private void SetupSceneElements (SCNScene scene) var ceilNode = SCNNode.FromGeometry (planeGeometry); ceilNode.Position = new SCNVector3 (0f, 100f, 0f); - ceilNode.Rotation = new SCNVector4 (1f, 0f, 0f, (float)Math.PI / 2f); + ceilNode.Rotation = new SCNVector4 (1f, 0f, 0f, (float) Math.PI / 2f); ceilNode.Geometry.FirstMaterial.DoubleSided = false; ceilNode.CastsShadow = false; ceilNode.Geometry.FirstMaterial.LocksAmbientWithDiffuse = true; @@ -428,7 +426,7 @@ private void SetupSceneElements (SCNScene scene) var block = SCNNode.Create (); block.Position = new SCNVector3 (20f, 10f, -16f); - block.Rotation = new SCNVector4 (0f, 1f, 0f, (float)-Math.PI / 4f); + block.Rotation = new SCNVector4 (0f, 1f, 0f, (float) -Math.PI / 4f); block.Geometry = blockBox; var frontMat = SCNMaterial.Create (); @@ -441,13 +439,13 @@ private void SetupSceneElements (SCNScene scene) backMat.Diffuse.Contents = ResourceManager.GetResourcePath ("book_back.jpg"); backMat.Diffuse.MipFilter = SCNFilterMode.Linear; - block.Geometry.Materials = new SCNMaterial[] { frontMat, backMat }; + block.Geometry.Materials = new SCNMaterial [] { frontMat, backMat }; block.PhysicsBody = SCNPhysicsBody.CreateDynamicBody (); scene.RootNode.AddChildNode (block); var rug = SCNNode.Create (); rug.Position = new SCNVector3 (0f, 0.01f, 0f); - rug.Rotation = new SCNVector4 (1f, 0f, 0f, (float)Math.PI / 2f); + rug.Rotation = new SCNVector4 (1f, 0f, 0f, (float) Math.PI / 2f); var path = UIBezierPath.FromRoundedRect (new CGRect (-50f, -30f, 100f, 50f), 2.5f); path.Flatness = 0.1f; rug.Geometry = SCNShape.Create (path, 0.05f); @@ -469,11 +467,11 @@ private void SetupSceneElements (SCNScene scene) private SCNNode SetupVehicle (SCNScene scene) { - var carScene = SCNScene.FromFile ("rc_car", ResourceManager.ResourceFolder, (NSDictionary)null); + var carScene = SCNScene.FromFile ("rc_car", ResourceManager.ResourceFolder, (NSDictionary) null); var chassisNode = carScene.RootNode.FindChildNode ("rccarBody", false); chassisNode.Position = new SCNVector3 (0f, 10f, 30f); - chassisNode.Rotation = new SCNVector4 (0f, 1f, 0f, (float)Math.PI); + chassisNode.Rotation = new SCNVector4 (0f, 1f, 0f, (float) Math.PI); var body = SCNPhysicsBody.CreateDynamicBody (); body.AllowsResting = false; @@ -486,7 +484,7 @@ private SCNNode SetupVehicle (SCNScene scene) var frontCameraNode = SCNNode.Create (); frontCameraNode.Position = new SCNVector3 (0f, 3.5f, 2.5f); - frontCameraNode.Rotation = new SCNVector4 (0f, 1f, 0f, (float)Math.PI); + frontCameraNode.Rotation = new SCNVector4 (0f, 1f, 0f, (float) Math.PI); frontCameraNode.Camera = SCNCamera.Create (); frontCameraNode.Camera.XFov = 75f; frontCameraNode.Camera.ZFar = 500f; @@ -524,7 +522,7 @@ private SCNNode SetupVehicle (SCNScene scene) wheel3.ConnectionPosition = SCNVector3.Subtract (wheel3Node.ConvertPositionToNode (SCNVector3.Zero, chassisNode), new SCNVector3 (wheelHalfWidth, 0f, 0f)); var vehicle = SCNPhysicsVehicle.Create (chassisNode.PhysicsBody, - new SCNPhysicsVehicleWheel[] { wheel0, wheel1, wheel2, wheel3 }); + new SCNPhysicsVehicleWheel [] { wheel0, wheel1, wheel2, wheel3 }); scene.PhysicsWorld.AddBehavior (vehicle); this.vehicle = vehicle; @@ -543,7 +541,7 @@ private SCNScene SetupScene () cameraNode.Camera = SCNCamera.Create (); cameraNode.Camera.ZFar = 500f; cameraNode.Position = new SCNVector3 (0f, 60f, 50f); - cameraNode.Rotation = new SCNVector4 (1f, 0f, 0f, -(float)Math.PI / 4f * 0.75f); + cameraNode.Rotation = new SCNVector4 (1f, 0f, 0f, -(float) Math.PI / 4f * 0.75f); scene.RootNode.AddChildNode (cameraNode); return scene; @@ -560,7 +558,7 @@ private void SetupInvironment (SCNScene scene) var lightNode = new SCNNode { Position = new SCNVector3 (0f, 80f, 30f), - Rotation = new SCNVector4 (1f, 0f, 0f, (float)(-Math.PI / 2.8)) + Rotation = new SCNVector4 (1f, 0f, 0f, (float) (-Math.PI / 2.8)) }; lightNode.Light = new SCNLight { @@ -587,7 +585,7 @@ private void SetupInvironment (SCNScene scene) floor.Geometry.FirstMaterial.LocksAmbientWithDiffuse = true; if (IsHighEndDevice) - ((SCNFloor)floor.Geometry).ReflectionFalloffEnd = 10f; + ((SCNFloor) floor.Geometry).ReflectionFalloffEnd = 10f; var staticBody = SCNPhysicsBody.CreateStaticBody (); floor.PhysicsBody = staticBody; diff --git a/ios8/SceneKitVehicle/SceneKitVehicle/Main.cs b/ios8/SceneKitVehicle/SceneKitVehicle/Main.cs index 7678b4f0c..83e825093 100644 --- a/ios8/SceneKitVehicle/SceneKitVehicle/Main.cs +++ b/ios8/SceneKitVehicle/SceneKitVehicle/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace SceneKitVehicle -{ - public class Application - { +namespace SceneKitVehicle { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/SceneKitVehicle/SceneKitVehicle/OverlayScene.cs b/ios8/SceneKitVehicle/SceneKitVehicle/OverlayScene.cs index ce1bb650a..0ead5a6a8 100644 --- a/ios8/SceneKitVehicle/SceneKitVehicle/OverlayScene.cs +++ b/ios8/SceneKitVehicle/SceneKitVehicle/OverlayScene.cs @@ -7,10 +7,8 @@ using UIKit; using CoreGraphics; -namespace SceneKitVehicle -{ - public class OverlayScene : SKScene - { +namespace SceneKitVehicle { + public class OverlayScene : SKScene { public SKNode SpeedNeedle { get; set; } public OverlayScene (CGSize size) : base (size) @@ -33,7 +31,7 @@ public OverlayScene (CGSize size) : base (size) needle.AnchorPoint = new CGPoint (0.5f, 0f); needle.XScale = 0.7f; needle.YScale = 0.7f; - needle.ZRotation = (float)Math.PI / 2f; + needle.ZRotation = (float) Math.PI / 2f; needleHandle.AddChild (needle); myImage.AddChild (needleHandle); diff --git a/ios8/SceneKitVehicle/SceneKitVehicle/ResourceManager.cs b/ios8/SceneKitVehicle/SceneKitVehicle/ResourceManager.cs index 5e449ddde..2d44318bd 100644 --- a/ios8/SceneKitVehicle/SceneKitVehicle/ResourceManager.cs +++ b/ios8/SceneKitVehicle/SceneKitVehicle/ResourceManager.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; -namespace SceneKitVehicle -{ - public static class ResourceManager - { +namespace SceneKitVehicle { + public static class ResourceManager { public static string ResourceFolder { get { return "Models.scnassets"; @@ -16,7 +14,7 @@ public static NSString GetResourcePath (string fileName) if (string.IsNullOrEmpty (fileName)) throw new ArgumentException ("File name can't be null or empty string"); - return (NSString)String.Format ("{0}/{1}", ResourceFolder, fileName); + return (NSString) String.Format ("{0}/{1}", ResourceFolder, fileName); } } } diff --git a/ios8/Share/Share/AppDelegate.cs b/ios8/Share/Share/AppDelegate.cs index 5b93234c0..b902fdf85 100644 --- a/ios8/Share/Share/AppDelegate.cs +++ b/ios8/Share/Share/AppDelegate.cs @@ -1,21 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Share -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace Share { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } - } -} \ No newline at end of file + return true; + } + } +} diff --git a/ios8/Share/Share/Main.cs b/ios8/Share/Share/Main.cs index 38fc3f8ea..b22e8f1cb 100644 --- a/ios8/Share/Share/Main.cs +++ b/ios8/Share/Share/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Share -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace Share { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios8/Share/Share/ViewController.cs b/ios8/Share/Share/ViewController.cs index 5e215156b..37b638bf3 100644 --- a/ios8/Share/Share/ViewController.cs +++ b/ios8/Share/Share/ViewController.cs @@ -1,25 +1,23 @@ -using System; +using System; using UIKit; -namespace Share -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } +namespace Share { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } - public override void ViewDidLoad() - { - base.ViewDidLoad(); - // Perform any additional setup after loading the view, typically from a nib. - } + public override void ViewDidLoad () + { + base.ViewDidLoad (); + // Perform any additional setup after loading the view, typically from a nib. + } - public override void DidReceiveMemoryWarning() - { - base.DidReceiveMemoryWarning(); - // Release any cached data, images, etc that aren't in use. - } - } + public override void DidReceiveMemoryWarning () + { + base.DidReceiveMemoryWarning (); + // Release any cached data, images, etc that aren't in use. + } + } } diff --git a/ios8/Share/ShareExtension/ShareViewController.cs b/ios8/Share/ShareExtension/ShareViewController.cs index 983f5c3bc..7e84a360d 100644 --- a/ios8/Share/ShareExtension/ShareViewController.cs +++ b/ios8/Share/ShareExtension/ShareViewController.cs @@ -1,54 +1,50 @@ -using CoreFoundation; +using CoreFoundation; using Foundation; using Social; using System; using UIKit; -namespace ShareExtension -{ - public partial class ShareViewController : SLComposeServiceViewController - { - protected ShareViewController(IntPtr handle) : base(handle) { } - - public override void DidReceiveMemoryWarning() - { - // Releases the view if it doesn't have a superview. - base.DidReceiveMemoryWarning(); - - // Release any cached data, images, etc that aren't in use. - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - // Do any additional setup after loading the view. - } - - public override bool IsContentValid() - { - // Do validation of contentText and/or NSExtensionContext attachments here - return true; - } - - public override void DidSelectPost() - { - // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments. - var alert = UIAlertController.Create("Share extension", $"This is the step where you should post the ContentText value: '{ContentText}' to your targeted service.", UIAlertControllerStyle.Alert); - PresentViewController(alert, true, () => - { - DispatchQueue.MainQueue.DispatchAfter(new DispatchTime(DispatchTime.Now, 5000000000), () => - { - // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context. - ExtensionContext.CompleteRequest(new NSExtensionItem[0], null); - }); - }); - } - - public override SLComposeSheetConfigurationItem[] GetConfigurationItems() - { - // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here. - return new SLComposeSheetConfigurationItem[0]; - } - } -} \ No newline at end of file +namespace ShareExtension { + public partial class ShareViewController : SLComposeServiceViewController { + protected ShareViewController (IntPtr handle) : base (handle) { } + + public override void DidReceiveMemoryWarning () + { + // Releases the view if it doesn't have a superview. + base.DidReceiveMemoryWarning (); + + // Release any cached data, images, etc that aren't in use. + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + // Do any additional setup after loading the view. + } + + public override bool IsContentValid () + { + // Do validation of contentText and/or NSExtensionContext attachments here + return true; + } + + public override void DidSelectPost () + { + // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments. + var alert = UIAlertController.Create ("Share extension", $"This is the step where you should post the ContentText value: '{ContentText}' to your targeted service.", UIAlertControllerStyle.Alert); + PresentViewController (alert, true, () => { + DispatchQueue.MainQueue.DispatchAfter (new DispatchTime (DispatchTime.Now, 5000000000), () => { + // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context. + ExtensionContext.CompleteRequest (new NSExtensionItem [0], null); + }); + }); + } + + public override SLComposeSheetConfigurationItem [] GetConfigurationItems () + { + // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here. + return new SLComposeSheetConfigurationItem [0]; + } + } +} diff --git a/ios8/SingleWordKeyboard/KeyboardExtension/KeyboardViewController.cs b/ios8/SingleWordKeyboard/KeyboardExtension/KeyboardViewController.cs index 3cf6b2807..d24ca2f50 100644 --- a/ios8/SingleWordKeyboard/KeyboardExtension/KeyboardViewController.cs +++ b/ios8/SingleWordKeyboard/KeyboardExtension/KeyboardViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using ObjCRuntime; using Foundation; using UIKit; -namespace KeyboardExtension -{ - public partial class KeyboardViewController : UIInputViewController - { +namespace KeyboardExtension { + public partial class KeyboardViewController : UIInputViewController { const string SingleWord = "SingleWord"; UIButton nextKeyboardButton; @@ -27,7 +25,7 @@ public override void ViewDidLoad () SetupNextKeyboardButton (); } - void SetupNextKeyboardButton() + void SetupNextKeyboardButton () { nextKeyboardButton = new UIButton (UIButtonType.System); diff --git a/ios8/SingleWordKeyboard/SingleWordKeyboard/AppDelegate.cs b/ios8/SingleWordKeyboard/SingleWordKeyboard/AppDelegate.cs index 185602d92..84b116eac 100644 --- a/ios8/SingleWordKeyboard/SingleWordKeyboard/AppDelegate.cs +++ b/ios8/SingleWordKeyboard/SingleWordKeyboard/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace SingleWordKeyboard -{ +namespace SingleWordKeyboard { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios8/SingleWordKeyboard/SingleWordKeyboard/Main.cs b/ios8/SingleWordKeyboard/SingleWordKeyboard/Main.cs index 491c9aa3b..5c4be8729 100644 --- a/ios8/SingleWordKeyboard/SingleWordKeyboard/Main.cs +++ b/ios8/SingleWordKeyboard/SingleWordKeyboard/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace SingleWordKeyboard -{ - public class Application - { +namespace SingleWordKeyboard { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/SingleWordKeyboard/SingleWordKeyboard/SingleWordKeyboardViewController.cs b/ios8/SingleWordKeyboard/SingleWordKeyboard/SingleWordKeyboardViewController.cs index 4653fa641..c4340b128 100644 --- a/ios8/SingleWordKeyboard/SingleWordKeyboard/SingleWordKeyboardViewController.cs +++ b/ios8/SingleWordKeyboard/SingleWordKeyboard/SingleWordKeyboardViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace SingleWordKeyboard -{ - public partial class SingleWordKeyboardViewController : UIViewController - { +namespace SingleWordKeyboard { + public partial class SingleWordKeyboardViewController : UIViewController { public SingleWordKeyboardViewController (IntPtr handle) : base (handle) { diff --git a/ios8/TableSearch/TableSearch/AppDelegate.cs b/ios8/TableSearch/TableSearch/AppDelegate.cs index 46dc6f5a6..09f939e8f 100644 --- a/ios8/TableSearch/TableSearch/AppDelegate.cs +++ b/ios8/TableSearch/TableSearch/AppDelegate.cs @@ -1,31 +1,29 @@ -using Foundation; +using Foundation; using UIKit; -namespace TableSearch -{ - // The UIApplicationDelegate for the application. This class is responsible for launching the - // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public override UIWindow Window { get; set; } +namespace TableSearch { + // The UIApplicationDelegate for the application. This class is responsible for launching the + // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Override point for customization after application launch. - // If not required for your application you can safely delete this method + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Override point for customization after application launch. + // If not required for your application you can safely delete this method - return true; - } + return true; + } - public override bool ShouldSaveApplicationState(UIApplication application, NSCoder coder) - { - return true; - } + public override bool ShouldSaveApplicationState (UIApplication application, NSCoder coder) + { + return true; + } - public override bool ShouldRestoreApplicationState(UIApplication application, NSCoder coder) - { - return true; - } - } -} \ No newline at end of file + public override bool ShouldRestoreApplicationState (UIApplication application, NSCoder coder) + { + return true; + } + } +} diff --git a/ios8/TableSearch/TableSearch/Controllers/BaseTableViewController.cs b/ios8/TableSearch/TableSearch/Controllers/BaseTableViewController.cs index d96160d46..c47b1355e 100644 --- a/ios8/TableSearch/TableSearch/Controllers/BaseTableViewController.cs +++ b/ios8/TableSearch/TableSearch/Controllers/BaseTableViewController.cs @@ -2,38 +2,35 @@ using System.Collections.Generic; using UIKit; -namespace TableSearch -{ - /// <summary> - /// Base or common view controller to share a common UITableViewCell prototype between subclasses. - /// </summary> - public class BaseTableViewController : UITableViewController - { - protected const string TableViewCellIdentifier = "cellID"; - private const string CellNibName = "TableCell"; +namespace TableSearch { + /// <summary> + /// Base or common view controller to share a common UITableViewCell prototype between subclasses. + /// </summary> + public class BaseTableViewController : UITableViewController { + protected const string TableViewCellIdentifier = "cellID"; + private const string CellNibName = "TableCell"; - public BaseTableViewController(IntPtr handle) : base(handle) { } + public BaseTableViewController (IntPtr handle) : base (handle) { } - public BaseTableViewController() { } + public BaseTableViewController () { } - public List<Product> FilteredProducts { get; set; } = new List<Product>(); + public List<Product> FilteredProducts { get; set; } = new List<Product> (); - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - using (var nib = UINib.FromName(CellNibName, null)) - { - // Required if our subclasses are to use `dequeueReusableCellWithIdentifier(_:forIndexPath:)`. - base.TableView.RegisterNibForCellReuse(nib, TableViewCellIdentifier); - } - } + using (var nib = UINib.FromName (CellNibName, null)) { + // Required if our subclasses are to use `dequeueReusableCellWithIdentifier(_:forIndexPath:)`. + base.TableView.RegisterNibForCellReuse (nib, TableViewCellIdentifier); + } + } - protected void ConfigureCell(UITableViewCell cell, Product product) - { - cell.TextLabel.Text = product.Title; - // Build the price and year string. - cell.DetailTextLabel.Text = $"{product.IntroPrice.ToString("C")} | {product.YearIntroduced}"; - } - } -} \ No newline at end of file + protected void ConfigureCell (UITableViewCell cell, Product product) + { + cell.TextLabel.Text = product.Title; + // Build the price and year string. + cell.DetailTextLabel.Text = $"{product.IntroPrice.ToString ("C")} | {product.YearIntroduced}"; + } + } +} diff --git a/ios8/TableSearch/TableSearch/Controllers/DetailViewController.cs b/ios8/TableSearch/TableSearch/Controllers/DetailViewController.cs index d1fa21b1c..f21fbb0e2 100644 --- a/ios8/TableSearch/TableSearch/Controllers/DetailViewController.cs +++ b/ios8/TableSearch/TableSearch/Controllers/DetailViewController.cs @@ -2,83 +2,76 @@ using System; using UIKit; -namespace TableSearch -{ - /// <summary> - /// The detail view controller navigated to from our main and results table. - /// </summary> - public partial class DetailViewController : UIViewController - { - // Constants for Storyboard/ViewControllers. - private const string StoryboardName = "Main"; - private const string ViewControllerIdentifier = "DetailViewController"; - - // Constants for state restoration. - private const string RestoreProductKey = "restoreProduct"; - - public DetailViewController(IntPtr handle) : base(handle) { } - - public Product Product { get; set; } - - public static UIViewController Create(Product product) - { - var storyboard = UIStoryboard.FromName(DetailViewController.StoryboardName, null); - - var viewController = storyboard.InstantiateViewController(DetailViewController.ViewControllerIdentifier); - if (viewController is DetailViewController detailViewController) - { - detailViewController.Product = product; - } - - return viewController; - } - - public override void ViewWillAppear(bool animated) - { - base.ViewWillAppear(animated); - - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { - base.NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Never; - } - - base.Title = Product.Title; - this.yearsLabel.Text = this.Product.YearIntroduced.ToString(); - - /* Here you can use 'NSNumberFormatter' as a Swift developer or string format as a C# developer */ - - //var numberFormatter = new NSNumberFormatter(); - //numberFormatter.NumberStyle = NSNumberFormatterStyle.Currency; - //numberFormatter.FormatterBehavior = NSNumberFormatterBehavior.Default; - //var priceString = numberFormatter.StringFromNumber(new NSNumber(Product.IntroPrice)); - this.priceLabel.Text = this.Product.IntroPrice.ToString("C"); - } - - #region UIStateRestoration - - public override void EncodeRestorableState(NSCoder coder) - { - base.EncodeRestorableState(coder); - - // Encode the product. - coder.Encode(Product, DetailViewController.RestoreProductKey); - } - - public override void DecodeRestorableState(NSCoder coder) - { - base.DecodeRestorableState(coder); - - // Restore the product. - if (coder.DecodeObject(DetailViewController.RestoreProductKey) is Product decodedProduct) - { - Product = decodedProduct; - } - else - { - throw new Exception("A product did not exist. In your app, handle this gracefully."); - } - } - - #endregion - } -} \ No newline at end of file +namespace TableSearch { + /// <summary> + /// The detail view controller navigated to from our main and results table. + /// </summary> + public partial class DetailViewController : UIViewController { + // Constants for Storyboard/ViewControllers. + private const string StoryboardName = "Main"; + private const string ViewControllerIdentifier = "DetailViewController"; + + // Constants for state restoration. + private const string RestoreProductKey = "restoreProduct"; + + public DetailViewController (IntPtr handle) : base (handle) { } + + public Product Product { get; set; } + + public static UIViewController Create (Product product) + { + var storyboard = UIStoryboard.FromName (DetailViewController.StoryboardName, null); + + var viewController = storyboard.InstantiateViewController (DetailViewController.ViewControllerIdentifier); + if (viewController is DetailViewController detailViewController) { + detailViewController.Product = product; + } + + return viewController; + } + + public override void ViewWillAppear (bool animated) + { + base.ViewWillAppear (animated); + + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { + base.NavigationItem.LargeTitleDisplayMode = UINavigationItemLargeTitleDisplayMode.Never; + } + + base.Title = Product.Title; + this.yearsLabel.Text = this.Product.YearIntroduced.ToString (); + + /* Here you can use 'NSNumberFormatter' as a Swift developer or string format as a C# developer */ + + //var numberFormatter = new NSNumberFormatter(); + //numberFormatter.NumberStyle = NSNumberFormatterStyle.Currency; + //numberFormatter.FormatterBehavior = NSNumberFormatterBehavior.Default; + //var priceString = numberFormatter.StringFromNumber(new NSNumber(Product.IntroPrice)); + this.priceLabel.Text = this.Product.IntroPrice.ToString ("C"); + } + + #region UIStateRestoration + + public override void EncodeRestorableState (NSCoder coder) + { + base.EncodeRestorableState (coder); + + // Encode the product. + coder.Encode (Product, DetailViewController.RestoreProductKey); + } + + public override void DecodeRestorableState (NSCoder coder) + { + base.DecodeRestorableState (coder); + + // Restore the product. + if (coder.DecodeObject (DetailViewController.RestoreProductKey) is Product decodedProduct) { + Product = decodedProduct; + } else { + throw new Exception ("A product did not exist. In your app, handle this gracefully."); + } + } + + #endregion + } +} diff --git a/ios8/TableSearch/TableSearch/Controllers/MainTableViewController.cs b/ios8/TableSearch/TableSearch/Controllers/MainTableViewController.cs index cb325f87a..9428b69a8 100644 --- a/ios8/TableSearch/TableSearch/Controllers/MainTableViewController.cs +++ b/ios8/TableSearch/TableSearch/Controllers/MainTableViewController.cs @@ -4,386 +4,369 @@ using System.Linq; using UIKit; -namespace TableSearch -{ - /// <summary> - /// The application's primary table view controller showing a list of products. - /// </summary> - public partial class MainTableViewController : BaseTableViewController, - IUISearchBarDelegate, - IUISearchControllerDelegate, - IUISearchResultsUpdating - { - // Data model for the table view. - private readonly List<Product> products = new List<Product> - { - new Product ("iPhone", 2007, 599), - new Product ("iPod", 2001, 399), - new Product ("iPod touch", 2007, 210), - new Product ("iPad", 2010, 499), - new Product ("iPad mini", 2012, 659), - new Product ("iMac", 1997, 1299), - new Product ("Mac Pro", 2006, 2499), - new Product ("MacBook Air", 2008, 1799), - new Product ("MacBook Pro", 2006, 1499), - }; - - /* +namespace TableSearch { + /// <summary> + /// The application's primary table view controller showing a list of products. + /// </summary> + public partial class MainTableViewController : BaseTableViewController, + IUISearchBarDelegate, + IUISearchControllerDelegate, + IUISearchResultsUpdating { + // Data model for the table view. + private readonly List<Product> products = new List<Product> + { + new Product ("iPhone", 2007, 599), + new Product ("iPod", 2001, 399), + new Product ("iPod touch", 2007, 210), + new Product ("iPad", 2010, 499), + new Product ("iPad mini", 2012, 659), + new Product ("iMac", 1997, 1299), + new Product ("Mac Pro", 2006, 2499), + new Product ("MacBook Air", 2008, 1799), + new Product ("MacBook Pro", 2006, 1499), + }; + + /* * They are implicitly unwrapped optionals because they are used in many other places throughout this view controller. */ - // Search controller to help us with filtering. - private UISearchController searchController; + // Search controller to help us with filtering. + private UISearchController searchController; - // Secondary search results table view. - private ResultsTableController resultsTableController; + // Secondary search results table view. + private ResultsTableController resultsTableController; - // Restoration state for UISearchController - private readonly SearchControllerRestorableState restoredState = new SearchControllerRestorableState(); + // Restoration state for UISearchController + private readonly SearchControllerRestorableState restoredState = new SearchControllerRestorableState (); - public MainTableViewController(IntPtr handle) : base(handle) { } + public MainTableViewController (IntPtr handle) : base (handle) { } - public override void ViewDidLoad() - { - base.ViewDidLoad(); + public override void ViewDidLoad () + { + base.ViewDidLoad (); - this.resultsTableController = new ResultsTableController(); - this.resultsTableController.TableView.Delegate = this; + this.resultsTableController = new ResultsTableController (); + this.resultsTableController.TableView.Delegate = this; - this.searchController = new UISearchController(this.resultsTableController) { SearchResultsUpdater = this }; - this.searchController.SearchBar.AutocapitalizationType = UITextAutocapitalizationType.None; + this.searchController = new UISearchController (this.resultsTableController) { SearchResultsUpdater = this }; + this.searchController.SearchBar.AutocapitalizationType = UITextAutocapitalizationType.None; - if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0)) - { - // For iOS 11 and later, place the search bar in the navigation bar. - base.NavigationItem.SearchController = this.searchController; + if (UIDevice.CurrentDevice.CheckSystemVersion (11, 0)) { + // For iOS 11 and later, place the search bar in the navigation bar. + base.NavigationItem.SearchController = this.searchController; - // Make the search bar always visible. - base.NavigationItem.HidesSearchBarWhenScrolling = false; - } - else - { - // For iOS 10 and earlier, place the search controller's search bar in the table view's header. - base.TableView.TableHeaderView = this.searchController.SearchBar; - } + // Make the search bar always visible. + base.NavigationItem.HidesSearchBarWhenScrolling = false; + } else { + // For iOS 10 and earlier, place the search controller's search bar in the table view's header. + base.TableView.TableHeaderView = this.searchController.SearchBar; + } - this.searchController.Delegate = this; - this.searchController.DimsBackgroundDuringPresentation = false; // The default is true. - this.searchController.SearchBar.Delegate = this;// Monitor when the search button is tapped. + this.searchController.Delegate = this; + this.searchController.DimsBackgroundDuringPresentation = false; // The default is true. + this.searchController.SearchBar.Delegate = this;// Monitor when the search button is tapped. - /* + /* * Search presents a view controller by applying normal view controller presentation semantics. * This means that the presentation moves up the view controller hierarchy until it finds the root * view controller or one that defines a presentation context. */ - /* + /* * Specify that this view controller determines how the search controller is presented. * The search controller should be presented modally and match the physical size of this view controller. */ - this.DefinesPresentationContext = true; - } + this.DefinesPresentationContext = true; + } - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); - // Restore the searchController's active state. - if (this.restoredState.WasActive) - { - this.searchController.Active = this.restoredState.WasActive; - this.restoredState.WasActive = false; + // Restore the searchController's active state. + if (this.restoredState.WasActive) { + this.searchController.Active = this.restoredState.WasActive; + this.restoredState.WasActive = false; - if (this.restoredState.WasFirstResponder) - { - this.searchController.SearchBar.BecomeFirstResponder(); - this.restoredState.WasFirstResponder = false; - } - } - } + if (this.restoredState.WasFirstResponder) { + this.searchController.SearchBar.BecomeFirstResponder (); + this.restoredState.WasFirstResponder = false; + } + } + } - #region UITableViewDelegate + #region UITableViewDelegate - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - // Check to see which table view cell was selected. - var selectedProduct = tableView == base.TableView ? this.products[indexPath.Row] : - resultsTableController.FilteredProducts[indexPath.Row]; + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + // Check to see which table view cell was selected. + var selectedProduct = tableView == base.TableView ? this.products [indexPath.Row] : + resultsTableController.FilteredProducts [indexPath.Row]; - // Set up the detail view controller to show. - var detailViewController = DetailViewController.Create(selectedProduct); - base.NavigationController?.PushViewController(detailViewController, true); + // Set up the detail view controller to show. + var detailViewController = DetailViewController.Create (selectedProduct); + base.NavigationController?.PushViewController (detailViewController, true); - tableView.DeselectRow(indexPath, false); - } + tableView.DeselectRow (indexPath, false); + } - #endregion + #endregion - #region UITableViewDataSource + #region UITableViewDataSource - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.products.Count; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.products.Count; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(BaseTableViewController.TableViewCellIdentifier, indexPath); - base.ConfigureCell(cell, products[indexPath.Row]); + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (BaseTableViewController.TableViewCellIdentifier, indexPath); + base.ConfigureCell (cell, products [indexPath.Row]); - return cell; - } + return cell; + } - #endregion + #endregion - #region IUISearchBarDelegate + #region IUISearchBarDelegate - [Export("searchBarSearchButtonClicked:")] - public void SearchButtonClicked(UISearchBar searchBar) - { - searchBar.ResignFirstResponder(); - } + [Export ("searchBarSearchButtonClicked:")] + public void SearchButtonClicked (UISearchBar searchBar) + { + searchBar.ResignFirstResponder (); + } - #endregion + #endregion - #region IUISearchControllerDelegate + #region IUISearchControllerDelegate - // Use these delegate functions for additional control over the search controller. + // Use these delegate functions for additional control over the search controller. - [Export("presentSearchController:")] - public void PresentSearchController(UISearchController searchController) - { - Console.WriteLine("UISearchControllerDelegate invoked method: 'PresentSearchController'."); - } + [Export ("presentSearchController:")] + public void PresentSearchController (UISearchController searchController) + { + Console.WriteLine ("UISearchControllerDelegate invoked method: 'PresentSearchController'."); + } - [Export("willPresentSearchController:")] - public void WillPresentSearchController(UISearchController searchController) - { - Console.WriteLine("UISearchControllerDelegate invoked method: 'WillPresentSearchController'."); - } + [Export ("willPresentSearchController:")] + public void WillPresentSearchController (UISearchController searchController) + { + Console.WriteLine ("UISearchControllerDelegate invoked method: 'WillPresentSearchController'."); + } - [Export("didPresentSearchController:")] - public void DidPresentSearchController(UISearchController searchController) - { - Console.WriteLine("UISearchControllerDelegate invoked method: 'DidPresentSearchController'."); - } + [Export ("didPresentSearchController:")] + public void DidPresentSearchController (UISearchController searchController) + { + Console.WriteLine ("UISearchControllerDelegate invoked method: 'DidPresentSearchController'."); + } - [Export("didDismissSearchController:")] - public void DidDismissSearchController(UISearchController searchController) - { - Console.WriteLine("UISearchControllerDelegate invoked method: 'DidDismissSearchController'."); - } + [Export ("didDismissSearchController:")] + public void DidDismissSearchController (UISearchController searchController) + { + Console.WriteLine ("UISearchControllerDelegate invoked method: 'DidDismissSearchController'."); + } - [Export("willDismissSearchController:")] - public void WillDismissSearchController(UISearchController searchController) - { - Console.WriteLine("UISearchControllerDelegate invoked method: 'WillDismissSearchController'."); - } + [Export ("willDismissSearchController:")] + public void WillDismissSearchController (UISearchController searchController) + { + Console.WriteLine ("UISearchControllerDelegate invoked method: 'WillDismissSearchController'."); + } - #endregion - - #region IUISearchResultsUpdating + #endregion - public void UpdateSearchResultsForSearchController(UISearchController searchController) - { - // Strip out all the leading and trailing spaces. - var searchItems = searchController.SearchBar.Text.Trim().Split(' '); - - /* here you can choose the way how to do search */ + #region IUISearchResultsUpdating - var filteredResults = this.PerformSearch_Swift(searchItems); - //var filteredResults = this.PerformSearch_CSharp(searchItems); + public void UpdateSearchResultsForSearchController (UISearchController searchController) + { + // Strip out all the leading and trailing spaces. + var searchItems = searchController.SearchBar.Text.Trim ().Split (' '); - // Apply the filtered results to the search results table. - if (searchController.SearchResultsController is ResultsTableController resultsController) - { - resultsController.FilteredProducts = filteredResults; - resultsController.TableView.ReloadData(); - } - } + /* here you can choose the way how to do search */ - private NSCompoundPredicate FindMatches(string searchString) - { - /* + var filteredResults = this.PerformSearch_Swift (searchItems); + //var filteredResults = this.PerformSearch_CSharp(searchItems); + + // Apply the filtered results to the search results table. + if (searchController.SearchResultsController is ResultsTableController resultsController) { + resultsController.FilteredProducts = filteredResults; + resultsController.TableView.ReloadData (); + } + } + + private NSCompoundPredicate FindMatches (string searchString) + { + /* * Each searchString creates an OR predicate for: name, yearIntroduced, introPrice. * Example if searchItems contains "Gladiolus 51.99 2001": * - name CONTAINS[c] "gladiolus" * - name CONTAINS[c] "gladiolus", yearIntroduced ==[c] 2001, introPrice ==[c] 51.99 * - name CONTAINS[c] "ginger", yearIntroduced ==[c] 2007, introPrice ==[c] 49.98 */ - var searchItemsPredicate = new List<NSPredicate>(); + var searchItemsPredicate = new List<NSPredicate> (); - /* + /* * Below we use NSExpression represent expressions in our predicates. * NSPredicate is made up of smaller, atomic parts: * two NSExpressions (a left-hand value and a right-hand value). */ - // Name field matching. - var titleExpression = NSExpression.FromKeyPath(ExpressionKeys.Title); - var searchStringExpression = NSExpression.FromConstant(new NSString(searchString)); - - var titleSearchComparisonPredicate = new NSComparisonPredicate(titleExpression, - searchStringExpression, - NSComparisonPredicateModifier.Direct, - NSPredicateOperatorType.Contains, - NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive); - - searchItemsPredicate.Add(titleSearchComparisonPredicate); - - var numberFormatter = new NSNumberFormatter - { - NumberStyle = NSNumberFormatterStyle.None, - FormatterBehavior = NSNumberFormatterBehavior.Default - }; - - // The `searchString` may fail to convert to a number. - var targetNumber = numberFormatter.NumberFromString(searchString); - if (targetNumber != null) - { - // Use `targetNumberExpression` in both the following predicates. - var targetNumberExpression = NSExpression.FromConstant(targetNumber); - - // The `yearIntroduced` field matching. - var yearIntroducedExpression = NSExpression.FromKeyPath(ExpressionKeys.YearIntroduced); - var yearIntroducedPredicate = new NSComparisonPredicate(yearIntroducedExpression, - targetNumberExpression, - NSComparisonPredicateModifier.Direct, - NSPredicateOperatorType.EqualTo, - NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive); - - searchItemsPredicate.Add(yearIntroducedPredicate); - - // The `price` field matching. - var priceExpression = NSExpression.FromKeyPath(ExpressionKeys.IntroPrice); - var finalPredicate = new NSComparisonPredicate(priceExpression, - targetNumberExpression, - NSComparisonPredicateModifier.Direct, - NSPredicateOperatorType.EqualTo, - NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive); - - searchItemsPredicate.Add(finalPredicate); - } - - return NSCompoundPredicate.CreateOrPredicate(searchItemsPredicate.ToArray()); - } - - private List<Product> PerformSearch_Swift(string[] searchItems) - { - // Update the filtered array based on the search text. - var searchResults = this.products; - - // Build all the "AND" expressions for each value in searchString. - var andMatchPredicates = searchItems.Select(searchItem => FindMatches(searchItem)).ToArray(); - - // Match up the fields of the Product object. - var finalCompoundPredicate = NSCompoundPredicate.CreateAndPredicate(andMatchPredicates); - var filteredResults = searchResults.Where(searchResult => finalCompoundPredicate.EvaluateWithObject(searchResult)); - - return filteredResults.ToList(); - } - - private List<Product> PerformSearch_CSharp(string[] searchItems) - { - var results = new List<Product>(); - // Update the filtered array based on the search text. - var localProducts = this.products; - - foreach (var searchItem in searchItems) - { - int.TryParse(searchItem, out int @int); - double.TryParse(searchItem, out double @double); - results.AddRange(localProducts.Where(product => product.Title.Contains(searchItem, StringComparison.OrdinalIgnoreCase) || - product.IntroPrice == @double || - product.YearIntroduced == @int)); - } - - return results.Distinct().ToList(); - } - - #endregion - - #region UIStateRestoration - - public override void EncodeRestorableState(NSCoder coder) - { - base.EncodeRestorableState(coder); - - // Encode the view state so it can be restored later. - - // Encode the title. - coder.Encode(new NSString(base.NavigationItem.Title), RestorationKeys.ViewControllerTitle); - - // Encode the search controller's active state. - coder.Encode(this.searchController.Active, RestorationKeys.SearchControllerIsActive); - - // Encode the first responser status. - coder.Encode(this.searchController.SearchBar.IsFirstResponder, RestorationKeys.SearchBarIsFirstResponder); - - // Encode the search bar text. - coder.Encode(new NSString(this.searchController.SearchBar.Text), RestorationKeys.SearchBarText); - } - - public override void DecodeRestorableState(NSCoder coder) - { - base.DecodeRestorableState(coder); - - // Restore the title. - if (coder.DecodeObject(RestorationKeys.ViewControllerTitle) is NSString decodedTitle) - { - base.NavigationItem.Title = decodedTitle; - } - else - { - throw new Exception("A title did not exist. In your app, handle this gracefully."); - } - - /* + // Name field matching. + var titleExpression = NSExpression.FromKeyPath (ExpressionKeys.Title); + var searchStringExpression = NSExpression.FromConstant (new NSString (searchString)); + + var titleSearchComparisonPredicate = new NSComparisonPredicate (titleExpression, + searchStringExpression, + NSComparisonPredicateModifier.Direct, + NSPredicateOperatorType.Contains, + NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive); + + searchItemsPredicate.Add (titleSearchComparisonPredicate); + + var numberFormatter = new NSNumberFormatter { + NumberStyle = NSNumberFormatterStyle.None, + FormatterBehavior = NSNumberFormatterBehavior.Default + }; + + // The `searchString` may fail to convert to a number. + var targetNumber = numberFormatter.NumberFromString (searchString); + if (targetNumber != null) { + // Use `targetNumberExpression` in both the following predicates. + var targetNumberExpression = NSExpression.FromConstant (targetNumber); + + // The `yearIntroduced` field matching. + var yearIntroducedExpression = NSExpression.FromKeyPath (ExpressionKeys.YearIntroduced); + var yearIntroducedPredicate = new NSComparisonPredicate (yearIntroducedExpression, + targetNumberExpression, + NSComparisonPredicateModifier.Direct, + NSPredicateOperatorType.EqualTo, + NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive); + + searchItemsPredicate.Add (yearIntroducedPredicate); + + // The `price` field matching. + var priceExpression = NSExpression.FromKeyPath (ExpressionKeys.IntroPrice); + var finalPredicate = new NSComparisonPredicate (priceExpression, + targetNumberExpression, + NSComparisonPredicateModifier.Direct, + NSPredicateOperatorType.EqualTo, + NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive); + + searchItemsPredicate.Add (finalPredicate); + } + + return NSCompoundPredicate.CreateOrPredicate (searchItemsPredicate.ToArray ()); + } + + private List<Product> PerformSearch_Swift (string [] searchItems) + { + // Update the filtered array based on the search text. + var searchResults = this.products; + + // Build all the "AND" expressions for each value in searchString. + var andMatchPredicates = searchItems.Select (searchItem => FindMatches (searchItem)).ToArray (); + + // Match up the fields of the Product object. + var finalCompoundPredicate = NSCompoundPredicate.CreateAndPredicate (andMatchPredicates); + var filteredResults = searchResults.Where (searchResult => finalCompoundPredicate.EvaluateWithObject (searchResult)); + + return filteredResults.ToList (); + } + + private List<Product> PerformSearch_CSharp (string [] searchItems) + { + var results = new List<Product> (); + // Update the filtered array based on the search text. + var localProducts = this.products; + + foreach (var searchItem in searchItems) { + int.TryParse (searchItem, out int @int); + double.TryParse (searchItem, out double @double); + results.AddRange (localProducts.Where (product => product.Title.Contains (searchItem, StringComparison.OrdinalIgnoreCase) || + product.IntroPrice == @double || + product.YearIntroduced == @int)); + } + + return results.Distinct ().ToList (); + } + + #endregion + + #region UIStateRestoration + + public override void EncodeRestorableState (NSCoder coder) + { + base.EncodeRestorableState (coder); + + // Encode the view state so it can be restored later. + + // Encode the title. + coder.Encode (new NSString (base.NavigationItem.Title), RestorationKeys.ViewControllerTitle); + + // Encode the search controller's active state. + coder.Encode (this.searchController.Active, RestorationKeys.SearchControllerIsActive); + + // Encode the first responser status. + coder.Encode (this.searchController.SearchBar.IsFirstResponder, RestorationKeys.SearchBarIsFirstResponder); + + // Encode the search bar text. + coder.Encode (new NSString (this.searchController.SearchBar.Text), RestorationKeys.SearchBarText); + } + + public override void DecodeRestorableState (NSCoder coder) + { + base.DecodeRestorableState (coder); + + // Restore the title. + if (coder.DecodeObject (RestorationKeys.ViewControllerTitle) is NSString decodedTitle) { + base.NavigationItem.Title = decodedTitle; + } else { + throw new Exception ("A title did not exist. In your app, handle this gracefully."); + } + + /* * Restore the active state: * We can't make the searchController active here since it's not part of the view * hierarchy yet, instead we do it in viewWillAppear. */ - this.restoredState.WasActive = coder.DecodeBool(RestorationKeys.SearchControllerIsActive); + this.restoredState.WasActive = coder.DecodeBool (RestorationKeys.SearchControllerIsActive); - /* + /* * Restore the first responder status: * Like above, we can't make the searchController first responder here since it's not part of the view * hierarchy yet, instead we do it in viewWillAppear. */ - this.restoredState.WasFirstResponder = coder.DecodeBool(RestorationKeys.SearchBarIsFirstResponder); - - // Restore the text in the search field. - this.searchController.SearchBar.Text = coder.DecodeObject(RestorationKeys.SearchBarText) as NSString; - } - - #endregion - - private class SearchControllerRestorableState - { - public bool WasActive { get; set; } - public bool WasFirstResponder { get; set; } - } - - /// <summary> - /// State restoration values. - /// </summary> - private static class RestorationKeys - { - public const string ViewControllerTitle = "viewControllerTitle"; - public const string SearchControllerIsActive = "searchControllerIsActive"; - public const string SearchBarText = "searchBarText"; - public const string SearchBarIsFirstResponder = "searchBarIsFirstResponder"; - } - - /// <summary> - /// NSPredicate expression keys. - /// </summary> - private static class ExpressionKeys - { - public const string Title = "title"; - public const string YearIntroduced = "yearIntroduced"; - public const string IntroPrice = "introPrice"; - } - } -} \ No newline at end of file + this.restoredState.WasFirstResponder = coder.DecodeBool (RestorationKeys.SearchBarIsFirstResponder); + + // Restore the text in the search field. + this.searchController.SearchBar.Text = coder.DecodeObject (RestorationKeys.SearchBarText) as NSString; + } + + #endregion + + private class SearchControllerRestorableState { + public bool WasActive { get; set; } + public bool WasFirstResponder { get; set; } + } + + /// <summary> + /// State restoration values. + /// </summary> + private static class RestorationKeys { + public const string ViewControllerTitle = "viewControllerTitle"; + public const string SearchControllerIsActive = "searchControllerIsActive"; + public const string SearchBarText = "searchBarText"; + public const string SearchBarIsFirstResponder = "searchBarIsFirstResponder"; + } + + /// <summary> + /// NSPredicate expression keys. + /// </summary> + private static class ExpressionKeys { + public const string Title = "title"; + public const string YearIntroduced = "yearIntroduced"; + public const string IntroPrice = "introPrice"; + } + } +} diff --git a/ios8/TableSearch/TableSearch/Controllers/ResultsTableController.cs b/ios8/TableSearch/TableSearch/Controllers/ResultsTableController.cs index 57fc48886..2daad1d19 100644 --- a/ios8/TableSearch/TableSearch/Controllers/ResultsTableController.cs +++ b/ios8/TableSearch/TableSearch/Controllers/ResultsTableController.cs @@ -2,29 +2,27 @@ using System; using UIKit; -namespace TableSearch -{ - /// <summary> - /// The table view controller responsible for displaying the filtered products as the user types in the search field. - /// </summary> - public class ResultsTableController : BaseTableViewController - { - public ResultsTableController(IntPtr handle) : base(handle) { } +namespace TableSearch { + /// <summary> + /// The table view controller responsible for displaying the filtered products as the user types in the search field. + /// </summary> + public class ResultsTableController : BaseTableViewController { + public ResultsTableController (IntPtr handle) : base (handle) { } - public ResultsTableController() { } + public ResultsTableController () { } - public override nint RowsInSection(UITableView tableView, nint section) - { - return base.FilteredProducts.Count; - } + public override nint RowsInSection (UITableView tableView, nint section) + { + return base.FilteredProducts.Count; + } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell(BaseTableViewController.TableViewCellIdentifier, indexPath); - var product = base.FilteredProducts[indexPath.Row]; - base.ConfigureCell(cell, product); + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell (BaseTableViewController.TableViewCellIdentifier, indexPath); + var product = base.FilteredProducts [indexPath.Row]; + base.ConfigureCell (cell, product); - return cell; - } - } -} \ No newline at end of file + return cell; + } + } +} diff --git a/ios8/TableSearch/TableSearch/Main.cs b/ios8/TableSearch/TableSearch/Main.cs index 2c2dbba41..9f879ed34 100644 --- a/ios8/TableSearch/TableSearch/Main.cs +++ b/ios8/TableSearch/TableSearch/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace TableSearch -{ - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace TableSearch { + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/ios8/TableSearch/TableSearch/Product.cs b/ios8/TableSearch/TableSearch/Product.cs index ebdaec084..003d73a03 100644 --- a/ios8/TableSearch/TableSearch/Product.cs +++ b/ios8/TableSearch/TableSearch/Product.cs @@ -1,54 +1,49 @@ -using Foundation; +using Foundation; using System; -namespace TableSearch -{ - /// <summary> - /// The data model object describing the product displayed in both main and results tables. - /// </summary> - public class Product : NSObject, INSCoding - { - public Product(string title, int year, double price) - { - this.Title = title; - this.YearIntroduced = year; - this.IntroPrice = price; - } +namespace TableSearch { + /// <summary> + /// The data model object describing the product displayed in both main and results tables. + /// </summary> + public class Product : NSObject, INSCoding { + public Product (string title, int year, double price) + { + this.Title = title; + this.YearIntroduced = year; + this.IntroPrice = price; + } - [Export("initWithCoder:")] - public Product(NSCoder coder) - { - if(coder.DecodeObject(nameof(Title)) is NSString decodedTitle) - { - this.Title = decodedTitle; - this.YearIntroduced = coder.DecodeInt(nameof(this.YearIntroduced)); - this.IntroPrice = coder.DecodeDouble(nameof(this.IntroPrice)); - } - else - { - throw new Exception("A title did not exist. In your app, handle this gracefully."); - } - } + [Export ("initWithCoder:")] + public Product (NSCoder coder) + { + if (coder.DecodeObject (nameof (Title)) is NSString decodedTitle) { + this.Title = decodedTitle; + this.YearIntroduced = coder.DecodeInt (nameof (this.YearIntroduced)); + this.IntroPrice = coder.DecodeDouble (nameof (this.IntroPrice)); + } else { + throw new Exception ("A title did not exist. In your app, handle this gracefully."); + } + } - [Export("title")] - public string Title { get; private set; } + [Export ("title")] + public string Title { get; private set; } - [Export("yearIntroduced")] - public int YearIntroduced { get; private set; } + [Export ("yearIntroduced")] + public int YearIntroduced { get; private set; } - [Export("introPrice")] - public double IntroPrice { get; private set; } + [Export ("introPrice")] + public double IntroPrice { get; private set; } - public void EncodeTo(NSCoder encoder) - { - encoder.Encode(new NSString(this.Title), nameof(this.Title)); - encoder.Encode(this.YearIntroduced, nameof(this.YearIntroduced)); - encoder.Encode(this.IntroPrice, nameof(this.IntroPrice)); - } + public void EncodeTo (NSCoder encoder) + { + encoder.Encode (new NSString (this.Title), nameof (this.Title)); + encoder.Encode (this.YearIntroduced, nameof (this.YearIntroduced)); + encoder.Encode (this.IntroPrice, nameof (this.IntroPrice)); + } - public override int GetHashCode() - { - return this.Title.GetHashCode(); - } - } -} \ No newline at end of file + public override int GetHashCode () + { + return this.Title.GetHashCode (); + } + } +} diff --git a/ios8/ToastModern/ToastModern/AppDelegate.cs b/ios8/ToastModern/ToastModern/AppDelegate.cs index 9cafe14b4..d061d3e15 100644 --- a/ios8/ToastModern/ToastModern/AppDelegate.cs +++ b/ios8/ToastModern/ToastModern/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace ToastModern -{ +namespace ToastModern { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations UIWindow window; diff --git a/ios8/ToastModern/ToastModern/Camera.cs b/ios8/ToastModern/ToastModern/Camera.cs index b2ae5529f..0010d15f5 100644 --- a/ios8/ToastModern/ToastModern/Camera.cs +++ b/ios8/ToastModern/ToastModern/Camera.cs @@ -1,14 +1,12 @@ -using System; +using System; using AVFoundation; using CoreAnimation; using CoreGraphics; using Foundation; using UIKit; -namespace ToastModern -{ - public class Camera : Layer - { +namespace ToastModern { + public class Camera : Layer { AVCaptureVideoPreviewLayer CameraLayer { get { AVCaptureDevice defaultDevice = AVCaptureDevice.DefaultDeviceWithMediaType (AVMediaType.Video); @@ -45,7 +43,7 @@ public Camera (Layer parent) : base (parent) Layer.AddSublayer (preview); preview.Position = new CGPoint (160, 309); preview.Bounds = new CGRect (preview.Bounds.Location.X, preview.Bounds.Location.Y, 320, 320f * 16 / 9); - preview.Transform = CATransform3D.MakeRotation ((nfloat)Math.PI, 0f, 1f, 0f); + preview.Transform = CATransform3D.MakeRotation ((nfloat) Math.PI, 0f, 1f, 0f); var previewMask = new CALayer (); Layer.AddSublayer (previewMask); diff --git a/ios8/ToastModern/ToastModern/KeyboardTyping.cs b/ios8/ToastModern/ToastModern/KeyboardTyping.cs index 44b08c7cc..85b23a1e4 100644 --- a/ios8/ToastModern/ToastModern/KeyboardTyping.cs +++ b/ios8/ToastModern/ToastModern/KeyboardTyping.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace ToastModern -{ - public class KeyboardTyping : Layer - { +namespace ToastModern { + public class KeyboardTyping : Layer { public int KeyboardTypingFrame { get; private set; } public override bool Hidden { @@ -17,7 +15,7 @@ public override bool Hidden { if (value) { UIView.PerformWithoutAnimation (() => { for (int i = 0; i < Subviews.Length; i++) { - var frame = (Layer)Subviews [i]; + var frame = (Layer) Subviews [i]; frame.Hidden = i != 0; } }); diff --git a/ios8/ToastModern/ToastModern/Layer.cs b/ios8/ToastModern/ToastModern/Layer.cs index 906b023ab..a4cfaf29f 100644 --- a/ios8/ToastModern/ToastModern/Layer.cs +++ b/ios8/ToastModern/ToastModern/Layer.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; using CoreGraphics; using Foundation; -namespace ToastModern -{ - public class Layer : UIImageView - { +namespace ToastModern { + public class Layer : UIImageView { public Action<NSSet> OnTouchDown; public Action<NSSet> OnTouchMove; public Action<NSSet> OnTouchUp; @@ -93,7 +91,7 @@ public void LoadImage (string filename) public static CGColor CreateColor (int red, int green, int blue, int alpha) { CGColorSpace colorSpace = CGColorSpace.CreateDeviceRGB (); - var color = new CGColor (colorSpace, new nfloat[] { red / 255f, green / 255f, blue / 255f, alpha / 255f }); + var color = new CGColor (colorSpace, new nfloat [] { red / 255f, green / 255f, blue / 255f, alpha / 255f }); colorSpace.Dispose (); return color; } diff --git a/ios8/ToastModern/ToastModern/List.cs b/ios8/ToastModern/ToastModern/List.cs index 3952e4bff..1cbc5f209 100644 --- a/ios8/ToastModern/ToastModern/List.cs +++ b/ios8/ToastModern/ToastModern/List.cs @@ -1,14 +1,12 @@ -using System; +using System; using CoreGraphics; using Foundation; using ObjCRuntime; using UIKit; using System.Timers; -namespace ToastModern -{ - public class List : Layer - { +namespace ToastModern { + public class List : Layer { double lastTime; bool isInertiaing; double velocity; @@ -41,11 +39,11 @@ public void Tick () if (isSpringing) { spring.Tick (); UIView.PerformWithoutAnimation (() => { - Y = (nfloat)spring.Position; + Y = (nfloat) spring.Position; }); } else if (isInertiaing) { UIView.PerformWithoutAnimation (() => { - Y += (nfloat)(velocity / 60); + Y += (nfloat) (velocity / 60); }); velocity *= 0.98; @@ -81,7 +79,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) public override void TouchesMoved (NSSet touches, UIEvent evt) { InvokeOnMainThread (() => { - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; UIView.PerformWithoutAnimation (() => { if (Y < min || Y > max) Y += 0.5f * (touch.LocationInView (Screen.GlobalScreen).Y - touch.PreviousLocationInView (Screen.GlobalScreen).Y); @@ -99,7 +97,7 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) public override void TouchesEnded (NSSet touches, UIEvent evt) { - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; double dy = touch.LocationInView (Screen.GlobalScreen).Y - touch.PreviousLocationInView (Screen.GlobalScreen).Y; double dt = touch.Timestamp - lastTime; diff --git a/ios8/ToastModern/ToastModern/Main.cs b/ios8/ToastModern/ToastModern/Main.cs index 73d251a1c..08dd4df4a 100644 --- a/ios8/ToastModern/ToastModern/Main.cs +++ b/ios8/ToastModern/ToastModern/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace ToastModern -{ - public class Application - { +namespace ToastModern { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/ToastModern/ToastModern/Map.cs b/ios8/ToastModern/ToastModern/Map.cs index bed76d1f5..102db2399 100644 --- a/ios8/ToastModern/ToastModern/Map.cs +++ b/ios8/ToastModern/ToastModern/Map.cs @@ -5,10 +5,8 @@ using ObjCRuntime; using System.Timers; -namespace ToastModern -{ - public class Map : Layer - { +namespace ToastModern { + public class Map : Layer { double lastTime; bool isInertiaing; CGPoint velocity; @@ -44,7 +42,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) public override void TouchesMoved (NSSet touches, UIEvent evt) { - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; UIView.PerformWithoutAnimation (() => { X = X + touch.LocationInView (Screen.GlobalScreen).X - touch.PreviousLocationInView (Screen.GlobalScreen).X; @@ -53,8 +51,8 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) }); CGPoint newVelocity = CGPoint.Empty; - newVelocity.X = touch.LocationInView (Screen.GlobalScreen).X - (nfloat)(touch.PreviousLocationInView (Screen.GlobalScreen).X / (touch.Timestamp - lastTime)); - newVelocity.Y = touch.LocationInView (Screen.GlobalScreen).Y - (nfloat)(touch.PreviousLocationInView (Screen.GlobalScreen).Y / (touch.Timestamp - lastTime)); + newVelocity.X = touch.LocationInView (Screen.GlobalScreen).X - (nfloat) (touch.PreviousLocationInView (Screen.GlobalScreen).X / (touch.Timestamp - lastTime)); + newVelocity.Y = touch.LocationInView (Screen.GlobalScreen).Y - (nfloat) (touch.PreviousLocationInView (Screen.GlobalScreen).Y / (touch.Timestamp - lastTime)); velocity.X = 0.25f * velocity.X + 0.75f * newVelocity.X; velocity.Y = 0.25f * velocity.Y + 0.75f * newVelocity.Y; @@ -63,11 +61,11 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) public override void TouchesEnded (NSSet touches, UIEvent evt) { - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; CGPoint newVelocity = CGPoint.Empty; - newVelocity.X = touch.LocationInView (Screen.GlobalScreen).X - (nfloat)(touch.PreviousLocationInView (Screen.GlobalScreen).X / (touch.Timestamp - lastTime)); - newVelocity.Y = touch.LocationInView (Screen.GlobalScreen).Y - (nfloat)(touch.PreviousLocationInView (Screen.GlobalScreen).Y / (touch.Timestamp - lastTime)); + newVelocity.X = touch.LocationInView (Screen.GlobalScreen).X - (nfloat) (touch.PreviousLocationInView (Screen.GlobalScreen).X / (touch.Timestamp - lastTime)); + newVelocity.Y = touch.LocationInView (Screen.GlobalScreen).Y - (nfloat) (touch.PreviousLocationInView (Screen.GlobalScreen).Y / (touch.Timestamp - lastTime)); velocity.X = 0.25f * velocity.X + 0.75f * newVelocity.X; velocity.Y = 0.25f * velocity.Y + 0.75f * newVelocity.Y; diff --git a/ios8/ToastModern/ToastModern/Screen.cs b/ios8/ToastModern/ToastModern/Screen.cs index e92525342..dd145dbc2 100644 --- a/ios8/ToastModern/ToastModern/Screen.cs +++ b/ios8/ToastModern/ToastModern/Screen.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace ToastModern -{ - public class Screen : Layer - { +namespace ToastModern { + public class Screen : Layer { public static Screen GlobalScreen { get; set; } public Screen (UIWindow window) : base (window) diff --git a/ios8/ToastModern/ToastModern/Share.cs b/ios8/ToastModern/ToastModern/Share.cs index ab40ca7ca..24535c3d2 100644 --- a/ios8/ToastModern/ToastModern/Share.cs +++ b/ios8/ToastModern/ToastModern/Share.cs @@ -1,11 +1,9 @@ -using System; +using System; using CoreGraphics; using UIKit; -namespace ToastModern -{ - public class Share : Layer - { +namespace ToastModern { + public class Share : Layer { public Share (Layer parent) : base (parent) { Layer screen = Screen.GlobalScreen; @@ -53,7 +51,7 @@ public Share (Layer parent) : base (parent) OnTouchUp = (touches) => { // get position of touch - UITouch touch = (UITouch)touches.AnyObject; + UITouch touch = (UITouch) touches.AnyObject; CGPoint touchPos = touch.LocationInView (screen); if (touchPos.X < 100 && touchPos.Y > screen.Height - 100) { @@ -73,7 +71,7 @@ public Share (Layer parent) : base (parent) postNavBar.Y = 0; keyboard.Y = screen.Height - keyboard.Height; }, () => { - var firstKeyboardTypingFrame = (Layer)keyboardTyping.Subviews [0]; + var firstKeyboardTypingFrame = (Layer) keyboardTyping.Subviews [0]; UIView.PerformWithoutAnimation (() => { keyboardTyping.Hidden = false; diff --git a/ios8/ToastModern/ToastModern/Spring.cs b/ios8/ToastModern/ToastModern/Spring.cs index 10330c815..20ee2ba3b 100644 --- a/ios8/ToastModern/ToastModern/Spring.cs +++ b/ios8/ToastModern/ToastModern/Spring.cs @@ -1,10 +1,8 @@ -using System; +using System; using Foundation; -namespace ToastModern -{ - public class Spring : NSObject - { +namespace ToastModern { + public class Spring : NSObject { public double Position { get; set; } public double Damping { get; set; } diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/AlertViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/AlertViewController.cs index c6b24c0d5..e183a29e4 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/AlertViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/AlertViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - partial class AlertViewController : UIViewController - { +namespace UIKitEnhancements { + partial class AlertViewController : UIViewController { public AlertViewController (IntPtr handle) : base (handle) { } @@ -14,77 +12,77 @@ public AlertViewController (IntPtr handle) : base (handle) partial void OKAlert_TouchUpInside (UIButton sender) { // Present alert - var okAlertController = UIAlertController.Create("OK Alert","This is a sample alert with an OK button.", UIAlertControllerStyle.Alert); + var okAlertController = UIAlertController.Create ("OK Alert", "This is a sample alert with an OK button.", UIAlertControllerStyle.Alert); - okAlertController.AddAction(UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); + okAlertController.AddAction (UIAlertAction.Create ("Ok", UIAlertActionStyle.Default, null)); - PresentViewController(okAlertController, true, null); + PresentViewController (okAlertController, true, null); } partial void OKCancelAlert_TouchUpInside (UIButton sender) { - var okCancelAlertController = UIAlertController.Create("OK / Cancel Alert", "This is a sample alert with an OK / Cancel Button", UIAlertControllerStyle.Alert); + var okCancelAlertController = UIAlertController.Create ("OK / Cancel Alert", "This is a sample alert with an OK / Cancel Button", UIAlertControllerStyle.Alert); - okCancelAlertController.AddAction(UIAlertAction.Create("Okay", UIAlertActionStyle.Default, alert => Console.WriteLine ("Okay was clicked"))); + okCancelAlertController.AddAction (UIAlertAction.Create ("Okay", UIAlertActionStyle.Default, alert => Console.WriteLine ("Okay was clicked"))); - okCancelAlertController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine ("Cancel was clicked"))); + okCancelAlertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alert => Console.WriteLine ("Cancel was clicked"))); - PresentViewController(okCancelAlertController, true, null); + PresentViewController (okCancelAlertController, true, null); } partial void TextInputAlert_TouchUpInside (UIButton sender) { - var textInputAlertController = UIAlertController.Create("Text Input Alert", "Hey, input some text", UIAlertControllerStyle.Alert); + var textInputAlertController = UIAlertController.Create ("Text Input Alert", "Hey, input some text", UIAlertControllerStyle.Alert); - textInputAlertController.AddTextField(textField => { + textInputAlertController.AddTextField (textField => { }); - + var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, alertAction => Console.WriteLine ("Cancel was Pressed")); - var okayAction = UIAlertAction.Create ("Okay", UIAlertActionStyle.Default, alertAction => Console.WriteLine ("The user entered '{0}'", textInputAlertController.TextFields[0].Text)); + var okayAction = UIAlertAction.Create ("Okay", UIAlertActionStyle.Default, alertAction => Console.WriteLine ("The user entered '{0}'", textInputAlertController.TextFields [0].Text)); + + textInputAlertController.AddAction (cancelAction); + textInputAlertController.AddAction (okayAction); - textInputAlertController.AddAction(cancelAction); - textInputAlertController.AddAction(okayAction); + PresentViewController (textInputAlertController, true, null); - PresentViewController(textInputAlertController, true, null); - } partial void ActionSheet_TouchUpInside (UIButton sender) { // Create a new Alert Controller - UIAlertController alert = UIAlertController.Create("Action Sheet", "Select an item from below", UIAlertControllerStyle.ActionSheet); + UIAlertController alert = UIAlertController.Create ("Action Sheet", "Select an item from below", UIAlertControllerStyle.ActionSheet); // Add items - alert.AddAction(UIAlertAction.Create("Item One",UIAlertActionStyle.Default,(action) => { - Console.WriteLine("Item One pressed."); + alert.AddAction (UIAlertAction.Create ("Item One", UIAlertActionStyle.Default, (action) => { + Console.WriteLine ("Item One pressed."); })); - alert.AddAction(UIAlertAction.Create("Item Two",UIAlertActionStyle.Default,(action) => { - Console.WriteLine("Item Two pressed."); + alert.AddAction (UIAlertAction.Create ("Item Two", UIAlertActionStyle.Default, (action) => { + Console.WriteLine ("Item Two pressed."); })); - alert.AddAction(UIAlertAction.Create("Item Three",UIAlertActionStyle.Default,(action) => { - Console.WriteLine("Item Three pressed."); + alert.AddAction (UIAlertAction.Create ("Item Three", UIAlertActionStyle.Default, (action) => { + Console.WriteLine ("Item Three pressed."); })); - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(action) => { - Console.WriteLine("Cancel button pressed."); + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (action) => { + Console.WriteLine ("Cancel button pressed."); })); // Required for iPad - You must specify a source for the Action Sheet since it is // displayed as a popover UIPopoverPresentationController presentationPopover = alert.PopoverPresentationController; - if (presentationPopover!=null) { + if (presentationPopover != null) { presentationPopover.SourceView = this.View; presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up; presentationPopover.SourceRect = ActionSheet.Frame; } // Display the alert - this.PresentViewController(alert,true,null); + this.PresentViewController (alert, true, null); } } } diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/AppDelegate.cs b/ios8/UIKitEnhancements/UIKitEnhancements/AppDelegate.cs index d892970d0..46566723b 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/AppDelegate.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/AppDelegate.cs @@ -5,16 +5,14 @@ using Foundation; using UIKit; -namespace UIKitEnhancements -{ +namespace UIKitEnhancements { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { #region Computed Properties - public override UIWindow Window { get; set;} + public override UIWindow Window { get; set; } public DetailsViewController iPadViewController { get; set; } #endregion @@ -22,7 +20,7 @@ public partial class AppDelegate : UIApplicationDelegate public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Create a Accept action - UIMutableUserNotificationAction acceptAction = new UIMutableUserNotificationAction (){ + UIMutableUserNotificationAction acceptAction = new UIMutableUserNotificationAction () { Identifier = "ACCEPT_ID", Title = "Accept", ActivationMode = UIUserNotificationActivationMode.Background, @@ -40,7 +38,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary }; // Create a Trash action - UIMutableUserNotificationAction trashAction = new UIMutableUserNotificationAction (){ + UIMutableUserNotificationAction trashAction = new UIMutableUserNotificationAction () { Identifier = "TRASH_ID", Title = "Trash", ActivationMode = UIUserNotificationActivationMode.Background, @@ -51,17 +49,17 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary // Create MonkeyMessage Category UIMutableUserNotificationCategory monkeyMessageCategory = new UIMutableUserNotificationCategory (); monkeyMessageCategory.Identifier = "MONKEYMESSAGE_ID"; - monkeyMessageCategory.SetActions (new UIUserNotificationAction[]{ acceptAction, replyAction, trashAction }, UIUserNotificationActionContext.Default); - monkeyMessageCategory.SetActions (new UIUserNotificationAction[]{ acceptAction, trashAction }, UIUserNotificationActionContext.Minimal); + monkeyMessageCategory.SetActions (new UIUserNotificationAction [] { acceptAction, replyAction, trashAction }, UIUserNotificationActionContext.Default); + monkeyMessageCategory.SetActions (new UIUserNotificationAction [] { acceptAction, trashAction }, UIUserNotificationActionContext.Minimal); // Create a category group - NSSet categories = new NSSet(monkeyMessageCategory); + NSSet categories = new NSSet (monkeyMessageCategory); // Set the requested notification types UIUserNotificationType type = UIUserNotificationType.Alert | UIUserNotificationType.Badge; // Create the setting for the given types - UIUserNotificationSettings settings = UIUserNotificationSettings.GetSettingsForTypes(type, categories); + UIUserNotificationSettings settings = UIUserNotificationSettings.GetSettingsForTypes (type, categories); // Register the settings UIApplication.SharedApplication.RegisterUserNotificationSettings (settings); @@ -79,7 +77,7 @@ public override void DidRegisterUserNotificationSettings (UIApplication applicat public override void HandleAction (UIApplication application, string actionIdentifier, UILocalNotification localNotification, Action completionHandler) { // Take action based on the notification and the action selected - Console.WriteLine ("User selected Action '{0}' for Notification: {1}",actionIdentifier,localNotification.AlertBody); + Console.WriteLine ("User selected Action '{0}' for Notification: {1}", actionIdentifier, localNotification.AlertBody); } @@ -88,19 +86,19 @@ public override void HandleAction (UIApplication application, string actionIdent public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/AlertView.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/AlertView.cs index 7cf9e4422..c888de6a4 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/AlertView.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/AlertView.cs @@ -3,55 +3,56 @@ using UIKit; using System.CodeDom.Compiler; -namespace MonoTouch.UIKit -{ - public class AlertView - { +namespace MonoTouch.UIKit { + public class AlertView { #region Static Methods - public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) { + public static UIAlertController PresentOKAlert (string title, string description, UIViewController controller) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Configure the alert - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {})); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (action) => { })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentOKCancelAlert(string title, string description, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentOKCancelAlert (string title, string description, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentTextInputAlert(string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) { + public static UIAlertController PresentTextInputAlert (string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); UITextField field = null; // Add and configure text field @@ -70,23 +71,23 @@ public static UIAlertController PresentTextInputAlert(string title, string descr }); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false,""); + if (action != null) { + action (false, ""); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null && field !=null) { - action(true, field.Text); + if (action != null && field != null) { + action (true, field.Text); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -94,8 +95,8 @@ public static UIAlertController PresentTextInputAlert(string title, string descr #endregion #region Delegates - public delegate void AlertOKCancelDelegate(bool OK); - public delegate void AlertTextInputDelegate(bool OK, string text); + public delegate void AlertOKCancelDelegate (bool OK); + public delegate void AlertTextInputDelegate (bool OK, string text); #endregion } } diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/ImageButton.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/ImageButton.cs index d12a9b0c0..2ac8bde62 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/ImageButton.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/ImageButton.cs @@ -5,18 +5,16 @@ using CoreGraphics; using System.ComponentModel; -namespace UIKitEnhancements -{ +namespace UIKitEnhancements { /// <summary> /// Creates a "touchable" image view that can be used as a button. /// </summary> - public class ImageButton : UIImageView - { + public class ImageButton : UIImageView { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="UIKitEnhancements.ImageButton"/> class. /// </summary> - public ImageButton () : base() + public ImageButton () : base () { } @@ -24,7 +22,7 @@ public ImageButton () : base() /// Initializes a new instance of the <see cref="UIKitEnhancements.ImageButton"/> class. /// </summary> /// <param name="coder">Coder.</param> - public ImageButton (NSCoder coder) : base(coder) + public ImageButton (NSCoder coder) : base (coder) { } @@ -32,7 +30,7 @@ public ImageButton (NSCoder coder) : base(coder) /// Initializes a new instance of the <see cref="UIKitEnhancements.ImageButton"/> class. /// </summary> /// <param name="flag">Flag.</param> - public ImageButton (NSObjectFlag flag) : base(flag) + public ImageButton (NSObjectFlag flag) : base (flag) { } @@ -40,7 +38,7 @@ public ImageButton (NSObjectFlag flag) : base(flag) /// Initializes a new instance of the <see cref="UIKitEnhancements.ImageButton"/> class. /// </summary> /// <param name="bounds">Bounds.</param> - public ImageButton (CGRect bounds) : base(bounds) + public ImageButton (CGRect bounds) : base (bounds) { } @@ -48,7 +46,7 @@ public ImageButton (CGRect bounds) : base(bounds) /// Initializes a new instance of the <see cref="UIKitEnhancements.ImageButton"/> class. /// </summary> /// <param name="ptr">Ptr.</param> - public ImageButton (IntPtr ptr) : base(ptr) + public ImageButton (IntPtr ptr) : base (ptr) { } @@ -56,7 +54,8 @@ public ImageButton (IntPtr ptr) : base(ptr) /// Initializes a new instance of the <see cref="UIKitEnhancements.ImageButton"/> class. /// </summary> /// <param name="image">Image.</param> - public ImageButton(UIImage image): base(image){ + public ImageButton (UIImage image) : base (image) + { } #endregion @@ -75,7 +74,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) base.TouchesBegan (touches, evt); } - #endregion + #endregion #region Events /// <summary> @@ -87,11 +86,12 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) /// <summary> /// Raises the touched event /// </summary> - private void RaiseTouched(){ + private void RaiseTouched () + { if (this.Touched != null) this.Touched (this); } - #endregion + #endregion } } diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/MenuItem.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/MenuItem.cs index e051cb3c4..281010fad 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/MenuItem.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/MenuItem.cs @@ -1,12 +1,10 @@ using System; -namespace UIKitEnhancements -{ +namespace UIKitEnhancements { /// <summary> /// Holds information about a give item on a table-based menu /// </summary> - public class MenuItem - { + public class MenuItem { #region Computed Properties /// <summary> /// Gets or sets the title. @@ -18,19 +16,19 @@ public class MenuItem /// Gets or sets the subtitle. /// </summary> /// <value>The subtitle.</value> - public string Subtitle{ get; set; } + public string Subtitle { get; set; } /// <summary> /// Gets or sets the segue. /// </summary> /// <value>The segue.</value> - public string Segue{ get; set; } + public string Segue { get; set; } /// <summary> /// Gets or sets the URL. /// </summary> /// <value>The UR.</value> - public string URL{ get; set; } + public string URL { get; set; } #endregion #region Constructors @@ -51,7 +49,8 @@ public MenuItem () /// </summary> /// <param name="title">Title.</param> /// <param name="subtitle">Subtitle.</param> - public MenuItem(string title, string subtitle, string segue) { + public MenuItem (string title, string subtitle, string segue) + { // Initialize Title = title; @@ -67,7 +66,8 @@ public MenuItem(string title, string subtitle, string segue) { /// <param name="subtitle">Subtitle.</param> /// <param name="segue">Segue.</param> /// <param name="url">URL.</param> - public MenuItem(string title, string subtitle, string segue, string url) { + public MenuItem (string title, string subtitle, string segue, string url) + { // Initialize Title = title; diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsTableSource.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsTableSource.cs index 59e6759ac..7ff483a1d 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsTableSource.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsTableSource.cs @@ -5,13 +5,11 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - public class SearchResultsTableSource :UITableViewSource - { +namespace UIKitEnhancements { + public class SearchResultsTableSource : UITableViewSource { #region Private Variables private MainMenuTableViewController _controller; - private List<MenuItem> _items = new List<MenuItem>(); + private List<MenuItem> _items = new List<MenuItem> (); #endregion #region Computed Properties @@ -20,23 +18,20 @@ public class SearchResultsTableSource :UITableViewSource /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> /// Gets or sets the <see cref="UIKitEnhancements.MenuItem"/> at the specified index. /// </summary> /// <param name="index">Index.</param> - public MenuItem this[int index] - { - get - { - return _items[index]; + public MenuItem this [int index] { + get { + return _items [index]; } - set - { - _items[index] = value; + set { + _items [index] = value; } } @@ -61,7 +56,8 @@ public SearchResultsTableSource (MainMenuTableViewController controller) /// <summary> /// Loads the data. /// </summary> - public void Search(string searchText) { + public void Search (string searchText) + { // Clear existing items _items.Clear (); @@ -170,9 +166,8 @@ public override string TitleForFooter (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { //Decant reusable cell - UITableViewCell searchCell = tableView.DequeueReusableCell("SEARCH"); - if (searchCell == null ) - { + UITableViewCell searchCell = tableView.DequeueReusableCell ("SEARCH"); + if (searchCell == null) { //Not found, assemble new cell searchCell = new UITableViewCell (UITableViewCellStyle.Default, "SEARCH"); } @@ -195,7 +190,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { // Note item accessory being displayed and // open it's details and services view - _controller.MenuItem = _items[indexPath.Row]; + _controller.MenuItem = _items [indexPath.Row]; // Performing a segue? if (_controller.MenuItem.Segue != "") { @@ -205,7 +200,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) _controller.PerformSegue (_controller.MenuItem.Segue, _controller); } else { // Yes, invoke segue against the iPad default view - ThisApp.iPadViewController.MenuItem = _items[indexPath.Row]; + ThisApp.iPadViewController.MenuItem = _items [indexPath.Row]; ThisApp.iPadViewController.PerformSegue (_controller.MenuItem.Segue, ThisApp.iPadViewController); } } diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsUpdator.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsUpdator.cs index 3f9c871e4..9a9cceda2 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsUpdator.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Classes/SearchResultsUpdator.cs @@ -5,10 +5,8 @@ using System.Collections.Generic; using CoreGraphics; -namespace UIKitEnhancements -{ - public class SearchResultsUpdator : UISearchResultsUpdating - { +namespace UIKitEnhancements { + public class SearchResultsUpdator : UISearchResultsUpdating { #region Constructors public SearchResultsUpdator () { @@ -28,14 +26,15 @@ public override void UpdateSearchResultsForSearchController (UISearchController /// <summary> /// Update search results delegate. /// </summary> - public delegate void UpdateSearchResultsDelegate(string searchText); + public delegate void UpdateSearchResultsDelegate (string searchText); public event UpdateSearchResultsDelegate UpdateSearchResults; /// <summary> /// Raises the update search results event. /// </summary> /// <param name="searchText">Search text.</param> - private void RaiseUpdateSearchResults(string searchText) { + private void RaiseUpdateSearchResults (string searchText) + { // Inform caller if (this.UpdateSearchResults != null) this.UpdateSearchResults (searchText); diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/DetailsViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/DetailsViewController.cs index 5a1a9dd1c..bd0a1d8f2 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/DetailsViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/DetailsViewController.cs @@ -3,17 +3,15 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - public partial class DetailsViewController : UINavigationController - { +namespace UIKitEnhancements { + public partial class DetailsViewController : UINavigationController { #region Computed Properties /// <summary> /// Returns the delegate of the current running application /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> @@ -49,7 +47,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) // Dismiss previous view before displaying the next view // in the sequence. - if (ViewControllers.Length>0) { + if (ViewControllers.Length > 0) { // Pop everything off the stack back to the Home view PopToRootViewController (false); } @@ -60,7 +58,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) var webView = segue.DestinationViewController as WebViewController; webView.URL = MenuItem.URL; break; - } + } } #endregion diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Main.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Main.cs index 5c1b79d99..a2fb25f0c 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Main.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Main.cs @@ -5,12 +5,10 @@ using Foundation; using UIKit; -namespace UIKitEnhancements -{ - public class Application - { +namespace UIKitEnhancements { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableCell.cs b/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableCell.cs index 6d85f9605..b72bc370c 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableCell.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableCell.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - public partial class MainMenuTableCell : UITableViewCell - { +namespace UIKitEnhancements { + public partial class MainMenuTableCell : UITableViewCell { #region Static Properties public static readonly NSString Key = new NSString ("MainMenuTableCell"); #endregion @@ -26,7 +24,8 @@ public MainMenuTableCell (IntPtr handle) : base (handle) /// Displays the menu item. /// </summary> /// <param name="item">Item.</param> - public void DisplayMenuItem(MenuItem item) { + public void DisplayMenuItem (MenuItem item) + { // Update GUI Title.Text = item.Title; diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableSource.cs b/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableSource.cs index 45e61e729..dc51bff2d 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableSource.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableSource.cs @@ -5,14 +5,12 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - public class MainMenuTableSource :UITableViewSource - { +namespace UIKitEnhancements { + public class MainMenuTableSource : UITableViewSource { #region Private Variables private MainMenuTableViewController _controller; - private List<MenuItem> _items = new List<MenuItem>(); - #endregion + private List<MenuItem> _items = new List<MenuItem> (); + #endregion #region Computed Properties /// <summary> @@ -20,23 +18,20 @@ public class MainMenuTableSource :UITableViewSource /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> /// Gets or sets the <see cref="UIKitEnhancements.MenuItem"/> at the specified index. /// </summary> /// <param name="index">Index.</param> - public MenuItem this[int index] - { - get - { - return _items[index]; + public MenuItem this [int index] { + get { + return _items [index]; } - set - { - _items[index] = value; + set { + _items [index] = value; } } @@ -66,19 +61,20 @@ public MainMenuTableSource (MainMenuTableViewController controller) /// <summary> /// Loads the data. /// </summary> - public void LoadData() { + public void LoadData () + { // Clear existing items _items.Clear (); // Setup list of data items _items.Add (new MenuItem ("Alert Controller", "Replaces Action Sheet & Alert View", "AlertSegue")); - _items.Add (new MenuItem ("Collection View Changes", "New Collection View Features","WebSegue","http://blog.xamarin.com/new-collection-view-features-in-ios-8/")); - _items.Add (new MenuItem ("Navigation Controller", "New Navigation Controller Options","NavBarSegue")); - _items.Add (new MenuItem ("Notifications", "Required Notification Settings","NotificationSegue")); - _items.Add (new MenuItem ("Popover Presentation Controller", "Handles Presentation in a Popover","PopoverSegue")); - _items.Add (new MenuItem ("Split View Controller", "Now Supported on iPhone","WebSegue","https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UISplitViewController_class/index.html#//apple_ref/occ/cl/UISplitViewController")); - _items.Add (new MenuItem ("Visual Effects", "Adding Visual Effects in iOS 8","WebSegue","http://blog.xamarin.com/adding-view-effects-in-ios-8/")); + _items.Add (new MenuItem ("Collection View Changes", "New Collection View Features", "WebSegue", "http://blog.xamarin.com/new-collection-view-features-in-ios-8/")); + _items.Add (new MenuItem ("Navigation Controller", "New Navigation Controller Options", "NavBarSegue")); + _items.Add (new MenuItem ("Notifications", "Required Notification Settings", "NotificationSegue")); + _items.Add (new MenuItem ("Popover Presentation Controller", "Handles Presentation in a Popover", "PopoverSegue")); + _items.Add (new MenuItem ("Split View Controller", "Now Supported on iPhone", "WebSegue", "https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UISplitViewController_class/index.html#//apple_ref/occ/cl/UISplitViewController")); + _items.Add (new MenuItem ("Visual Effects", "Adding Visual Effects in iOS 8", "WebSegue", "http://blog.xamarin.com/adding-view-effects-in-ios-8/")); } #endregion @@ -192,7 +188,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { // Note item accessory being displayed and // open it's details and services view - _controller.MenuItem = _items[indexPath.Row]; + _controller.MenuItem = _items [indexPath.Row]; // Performing a segue? if (_controller.MenuItem.Segue != "") { @@ -202,7 +198,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) _controller.PerformSegue (_controller.MenuItem.Segue, _controller); } else { // Yes, invoke segue against the iPad default view - ThisApp.iPadViewController.MenuItem = _items[indexPath.Row]; + ThisApp.iPadViewController.MenuItem = _items [indexPath.Row]; ThisApp.iPadViewController.PerformSegue (_controller.MenuItem.Segue, ThisApp.iPadViewController); } } @@ -210,4 +206,4 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) } #endregion } -} \ No newline at end of file +} diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableViewController.cs index 9d1e696ed..ea03c621a 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/MainMenuTableViewController.cs @@ -1,21 +1,19 @@ - using System; - using Foundation; - using UIKit; - using System.CodeDom.Compiler; - using System.Collections.Generic; - using CoreGraphics; - -namespace UIKitEnhancements -{ - public partial class MainMenuTableViewController : UITableViewController - { +using System; +using Foundation; +using UIKit; +using System.CodeDom.Compiler; +using System.Collections.Generic; +using CoreGraphics; + +namespace UIKitEnhancements { + public partial class MainMenuTableViewController : UITableViewController { #region Computed Properties /// <summary> /// Returns the delegate of the current running application /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } /// <summary> @@ -23,7 +21,7 @@ public AppDelegate ThisApp { /// </summary> /// <value>The data source.</value> public MainMenuTableSource DataSource { - get { return (MainMenuTableSource)TableView.Source; } + get { return (MainMenuTableSource) TableView.Source; } } /// <summary> @@ -36,7 +34,7 @@ public MainMenuTableSource DataSource { /// Gets or sets the search controller. /// </summary> /// <value>The search controller.</value> - public UISearchController SearchController { get; set;} + public UISearchController SearchController { get; set; } #endregion #region Constructors @@ -49,7 +47,8 @@ public MainMenuTableViewController (IntPtr handle) : base (handle) /// <summary> /// Reloads the data. /// </summary> - public void ReloadData() { + public void ReloadData () + { // Ask the table to redisplay its information DataSource.LoadData (); @@ -77,8 +76,8 @@ public override void ViewDidLoad () var searchUpdater = new SearchResultsUpdator (); searchUpdater.UpdateSearchResults += (searchText) => { // Preform search and reload search table - searchSource.Search(searchText); - searchResultsController.TableView.ReloadData(); + searchSource.Search (searchText); + searchResultsController.TableView.ReloadData (); }; // Create a new search controller @@ -106,7 +105,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) var webView = segue.DestinationViewController as WebViewController; webView.URL = MenuItem.URL; break; - } + } } #endregion diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/MainSplitViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/MainSplitViewController.cs index c3edfe645..7d5d0bfac 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/MainSplitViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/MainSplitViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - partial class MainSplitViewController : UISplitViewController - { +namespace UIKitEnhancements { + partial class MainSplitViewController : UISplitViewController { #region Constructors public MainSplitViewController (IntPtr handle) : base (handle) { diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/NavBarViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/NavBarViewController.cs index 5f6a8aba0..686e3ad39 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/NavBarViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/NavBarViewController.cs @@ -3,12 +3,10 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - partial class NavBarViewController : UIViewController - { +namespace UIKitEnhancements { + partial class NavBarViewController : UIViewController { #region Constructors - public NavBarViewController(IntPtr handle) : base (handle) + public NavBarViewController (IntPtr handle) : base (handle) { } #endregion @@ -24,7 +22,7 @@ public override void ViewWillAppear (bool animated) // Wireup segment controller NavBarMode.ValueChanged += (sender, e) => { // Take action based on the selected mode - switch(NavBarMode.SelectedSegment) { + switch (NavBarMode.SelectedSegment) { case 0: this.NavigationController.HidesBarsOnTap = true; this.NavigationController.HidesBarsOnSwipe = false; diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/NotificationViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/NotificationViewController.cs index 9b4358c47..9cabad26e 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/NotificationViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/NotificationViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - partial class NotificationViewController : UIViewController - { +namespace UIKitEnhancements { + partial class NotificationViewController : UIViewController { #region Constructors public NotificationViewController (IntPtr handle) : base (handle) { @@ -24,17 +22,17 @@ public override void ViewDidLoad () // Wireup button SendButton.TouchUpInside += (sender, e) => { // Create a new local notification - UILocalNotification notification = new UILocalNotification(){ + UILocalNotification notification = new UILocalNotification () { AlertBody = "Go Bananas - You've got Monkey Mail!", AlertAction = null, ApplicationIconBadgeNumber = 1, Category = "MONKEYMESSAGE_ID", - FireDate = NSDate.FromTimeIntervalSinceNow(15) // Fire message in 15 seconds + FireDate = NSDate.FromTimeIntervalSinceNow (15) // Fire message in 15 seconds }; // Schedule the notification - UIApplication.SharedApplication.ScheduleLocalNotification(notification); - Console.WriteLine("Notification scheduled..."); + UIApplication.SharedApplication.ScheduleLocalNotification (notification); + Console.WriteLine ("Notification scheduled..."); }; // Enable the button if the application has been allowed to send notifications diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/PopoverViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/PopoverViewController.cs index 5086da878..00f546582 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/PopoverViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/PopoverViewController.cs @@ -6,10 +6,8 @@ using UIKit; using CoreGraphics; -namespace UIKitEnhancements -{ - public partial class PopoverViewController : UIViewController - { +namespace UIKitEnhancements { + public partial class PopoverViewController : UIViewController { #region Constructors public PopoverViewController (IntPtr handle) : base (handle) { @@ -24,36 +22,36 @@ public override void ViewDidLoad () // Wireup Show button ShowButton.TouchUpInside += (sender, e) => { // Create a UIImage view to show in the popover - UIImageView monkeyIcon = new UIImageView(new CGRect(0,0,256,256)); - monkeyIcon.Image = UIImage.FromFile("MonkeyIcon.png"); + UIImageView monkeyIcon = new UIImageView (new CGRect (0, 0, 256, 256)); + monkeyIcon.Image = UIImage.FromFile ("MonkeyIcon.png"); monkeyIcon.UserInteractionEnabled = true; // Create a view controller to act as the popover - UIViewController popover = new UIViewController(); + UIViewController popover = new UIViewController (); popover.View = monkeyIcon; popover.ModalPresentationStyle = UIModalPresentationStyle.Popover; // Grab Image - var image = UIImage.FromFile("298-circlex.png"); + var image = UIImage.FromFile ("298-circlex.png"); // Add a close button - var closeButton = new ImageButton(new CGRect(popover.View.Frame.Size.Width,20,image.Size.Width,image.Size.Height)); + var closeButton = new ImageButton (new CGRect (popover.View.Frame.Size.Width, 20, image.Size.Width, image.Size.Height)); closeButton.UserInteractionEnabled = true; closeButton.Image = image; - monkeyIcon.AddSubview(closeButton); + monkeyIcon.AddSubview (closeButton); // Wireup the close button closeButton.Touched += (button) => { - popover.DismissViewController(true,null); + popover.DismissViewController (true, null); }; // Present the popover - PresentViewController(popover,true,null); + PresentViewController (popover, true, null); // Configure the popover for the iPad, the popover displays as a modal view on the // iPhone UIPopoverPresentationController presentationPopover = popover.PopoverPresentationController; - if (presentationPopover!=null) { + if (presentationPopover != null) { presentationPopover.SourceView = this.View; presentationPopover.PermittedArrowDirections = UIPopoverArrowDirection.Up; presentationPopover.SourceRect = ShowButton.Frame; diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/Temp.cs b/ios8/UIKitEnhancements/UIKitEnhancements/Temp.cs index b1a86eef8..e6fd90d7c 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/Temp.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/Temp.cs @@ -1,5 +1,5 @@ -// Create a Accept action -UIMutableUserNotificationAction acceptAction = new UIMutableUserNotificationAction (){ +// Create a Accept action +UIMutableUserNotificationAction acceptAction = new UIMutableUserNotificationAction () { Identifier = "ACCEPT_ID", Title = "Accept", ActivationMode = UIUserNotificationActivationMode.Background, @@ -17,10 +17,10 @@ }; // Create a Trash action -UIMutableUserNotificationAction trashAction = new UIMutableUserNotificationAction (){ +UIMutableUserNotificationAction trashAction = new UIMutableUserNotificationAction () { Identifier = "TRASH_ID", Title = "Trash", ActivationMode = UIUserNotificationActivationMode.Background, Destructive = true, AuthenticationRequired = true -}; \ No newline at end of file +}; diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/UIKitEnhancementsViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/UIKitEnhancementsViewController.cs index 687ce7c39..c0ebfd66c 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/UIKitEnhancementsViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/UIKitEnhancementsViewController.cs @@ -4,10 +4,8 @@ using Foundation; using UIKit; -namespace UIKitEnhancements -{ - public partial class UIKitEnhancementsViewController : UIViewController - { +namespace UIKitEnhancements { + public partial class UIKitEnhancementsViewController : UIViewController { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } @@ -20,7 +18,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -29,7 +27,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/ios8/UIKitEnhancements/UIKitEnhancements/WebViewController.cs b/ios8/UIKitEnhancements/UIKitEnhancements/WebViewController.cs index 6b1a9cb33..6ecdddb49 100644 --- a/ios8/UIKitEnhancements/UIKitEnhancements/WebViewController.cs +++ b/ios8/UIKitEnhancements/UIKitEnhancements/WebViewController.cs @@ -3,10 +3,8 @@ using UIKit; using System.CodeDom.Compiler; -namespace UIKitEnhancements -{ - partial class WebViewController : UIViewController - { +namespace UIKitEnhancements { + partial class WebViewController : UIViewController { #region Computed Properties public string URL { get; set; } #endregion @@ -21,31 +19,33 @@ public WebViewController (IntPtr handle) : base (handle) /// <summary> /// Shows the busy indicator /// </summary> - private void ShowBusy() { + private void ShowBusy () + { //Define Animation - UIView.BeginAnimations("Show"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Show"); + UIView.SetAnimationDuration (1.0f); Loading.Alpha = 0.5f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } /// <summary> /// Hides the busy. /// </summary> - private void HideBusy() { + private void HideBusy () + { //Define Animation - UIView.BeginAnimations("Hide"); - UIView.SetAnimationDuration(1.0f); + UIView.BeginAnimations ("Hide"); + UIView.SetAnimationDuration (1.0f); Loading.Alpha = 0f; //Execute Animation - UIView.CommitAnimations(); + UIView.CommitAnimations (); } #endregion @@ -58,17 +58,17 @@ public override void ViewWillAppear (bool animated) Loading.Alpha = 0.0f; // Display the give webpage - WebView.LoadRequest(new NSUrlRequest(NSUrl.FromString(URL))); + WebView.LoadRequest (new NSUrlRequest (NSUrl.FromString (URL))); // Wireup Webview notifications WebView.LoadStarted += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; - ShowBusy(); + ShowBusy (); }; WebView.LoadFinished += (sender, e) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; - HideBusy(); + HideBusy (); }; } #endregion diff --git a/ios8/VideoTimeLine/VideoTimeLine/AppDelegate.cs b/ios8/VideoTimeLine/VideoTimeLine/AppDelegate.cs index 8c304abab..af782f82f 100644 --- a/ios8/VideoTimeLine/VideoTimeLine/AppDelegate.cs +++ b/ios8/VideoTimeLine/VideoTimeLine/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace VideoTimeLine { @@ -14,4 +14,4 @@ public override UIWindow Window { // Main.storyboard is automagically loaded since it is specified // in the Info.plist -> <key>UIMainStoryboardFile~ipad</key> } -} \ No newline at end of file +} diff --git a/ios8/VideoTimeLine/VideoTimeLine/EAGLLayer.cs b/ios8/VideoTimeLine/VideoTimeLine/EAGLLayer.cs index fb786bd40..819398d1c 100644 --- a/ios8/VideoTimeLine/VideoTimeLine/EAGLLayer.cs +++ b/ios8/VideoTimeLine/VideoTimeLine/EAGLLayer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using AVFoundation; @@ -10,10 +10,8 @@ using OpenTK.Graphics.ES20; using UIKit; -namespace VideoTimeLine -{ - public class EAGLLayer : CAEAGLLayer - { +namespace VideoTimeLine { + public class EAGLLayer : CAEAGLLayer { public enum UniformIndex { Y = 0, UV, @@ -29,14 +27,14 @@ public enum AttributeIndex { } // BT.601, which is the standard for SDTV. - static float[] colorConversion601 = { + static float [] colorConversion601 = { 1.164f, 1.164f, 1.164f, 0.0f, -0.392f, 2.017f, 1.596f, -0.813f, 0.0f }; // BT.709, which is the standard for HDTV. - static float[] colorConversion709 = { + static float [] colorConversion709 = { 1.164f, 1.164f, 1.164f, 0.0f, -0.213f, 2.112f, 1.793f, -0.533f, 0.0f @@ -52,8 +50,8 @@ public enum AttributeIndex { uint frameBufferHandle; uint colorBufferHandle; - float[] preferredConversion; - int[] uniforms = new int[(int)UniformIndex.NumUniforms]; + float [] preferredConversion; + int [] uniforms = new int [(int) UniformIndex.NumUniforms]; static string fragmentShaderSource; @@ -91,8 +89,8 @@ public EAGLLayer () { Opaque = true; DrawableProperties = NSDictionary.FromObjectsAndKeys ( - new object[] { NSNumber.FromBoolean (false), EAGLColorFormat.RGBA8 }, - new object[] { EAGLDrawableProperty.RetainedBacking, EAGLDrawableProperty.ColorFormat } + new object [] { NSNumber.FromBoolean (false), EAGLColorFormat.RGBA8 }, + new object [] { EAGLDrawableProperty.RetainedBacking, EAGLDrawableProperty.ColorFormat } ); context = new EAGLContext (EAGLRenderingAPI.OpenGLES2); @@ -138,10 +136,10 @@ public void SetupGL () GL.UseProgram (Program); // 0 and 1 are the texture IDs of lumaTexture and chromaTexture respectively. - GL.Uniform1 (uniforms [(int)UniformIndex.Y], 0); - GL.Uniform1 (uniforms [(int)UniformIndex.UV], 1); - GL.Uniform1 (uniforms [(int)UniformIndex.RotationAngle], 0); - GL.UniformMatrix3 (uniforms [(int)UniformIndex.ColorConversionMatrix], 1, false, preferredConversion); + GL.Uniform1 (uniforms [(int) UniformIndex.Y], 0); + GL.Uniform1 (uniforms [(int) UniformIndex.UV], 1); + GL.Uniform1 (uniforms [(int) UniformIndex.RotationAngle], 0); + GL.UniformMatrix3 (uniforms [(int) UniformIndex.ColorConversionMatrix], 1, false, preferredConversion); if (videoTextureCache != null) return; @@ -157,8 +155,8 @@ public void DisplayPixelBuffer (CVPixelBuffer pixelBuffer) CVReturn error; if (pixelBuffer != null) { - int frameWidth = (int)pixelBuffer.Width; - int frameHeight = (int)pixelBuffer.Height; + int frameWidth = (int) pixelBuffer.Width; + int frameHeight = (int) pixelBuffer.Height; if (videoTextureCache == null) { Console.WriteLine ("No video texture cache"); @@ -167,7 +165,7 @@ public void DisplayPixelBuffer (CVPixelBuffer pixelBuffer) CleanUpTextures (); CVAttachmentMode attachmentMode; - var colorAttachments = pixelBuffer.GetAttachment <NSString> (CVImageBuffer.YCbCrMatrixKey, out attachmentMode); + var colorAttachments = pixelBuffer.GetAttachment<NSString> (CVImageBuffer.YCbCrMatrixKey, out attachmentMode); if (colorAttachments == CVImageBuffer.YCbCrMatrix_ITU_R_601_4) preferredConversion = colorConversion601; @@ -182,10 +180,10 @@ public void DisplayPixelBuffer (CVPixelBuffer pixelBuffer) Console.WriteLine ("Error at CVOpenGLESTextureCach.TextureFromImage"); GL.BindTexture (lumaTexture.Target, lumaTexture.Name); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); GL.ActiveTexture (TextureUnit.Texture1); chromaTexture = videoTextureCache.TextureFromImage (pixelBuffer, true, All.RgExt, frameWidth / 2, frameHeight / 2, @@ -195,10 +193,10 @@ public void DisplayPixelBuffer (CVPixelBuffer pixelBuffer) Console.WriteLine ("Error at CVOpenGLESTextureCach.TextureFromImage"); GL.BindTexture (chromaTexture.Target, chromaTexture.Name); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge); - GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int) All.Linear); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int) All.ClampToEdge); + GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int) All.ClampToEdge); GL.BindFramebuffer (FramebufferTarget.Framebuffer, frameBufferHandle); GL.Viewport (0, 0, backingWidth, backingHeight); @@ -208,8 +206,8 @@ public void DisplayPixelBuffer (CVPixelBuffer pixelBuffer) GL.Clear (ClearBufferMask.ColorBufferBit); GL.UseProgram (Program); - GL.Uniform1 (uniforms [(int)UniformIndex.RotationAngle], 0f); - GL.UniformMatrix3 (uniforms [(int)UniformIndex.ColorConversionMatrix], 1, false, preferredConversion); + GL.Uniform1 (uniforms [(int) UniformIndex.RotationAngle], 0f); + GL.UniformMatrix3 (uniforms [(int) UniformIndex.ColorConversionMatrix], 1, false, preferredConversion); CGRect vertexSamplingRect = AVUtilities.WithAspectRatio (Bounds, PresentationRect); @@ -224,30 +222,30 @@ public void DisplayPixelBuffer (CVPixelBuffer pixelBuffer) normalizedSamplingSize.Height = cropScaleAmount.Width / cropScaleAmount.Height; } - float[] quadVertexData = { + float [] quadVertexData = { -1f * (float)normalizedSamplingSize.Width, -1f * (float)normalizedSamplingSize.Height, (float)normalizedSamplingSize.Width, -1f * (float)normalizedSamplingSize.Height, -1f * (float)normalizedSamplingSize.Width, (float)normalizedSamplingSize.Height, (float)normalizedSamplingSize.Width, (float)normalizedSamplingSize.Height, }; - GL.VertexAttribPointer ((int)AttributeIndex.Vertex, 2, VertexAttribPointerType.Float, false, 0, quadVertexData); - GL.EnableVertexAttribArray ((int)AttributeIndex.Vertex); + GL.VertexAttribPointer ((int) AttributeIndex.Vertex, 2, VertexAttribPointerType.Float, false, 0, quadVertexData); + GL.EnableVertexAttribArray ((int) AttributeIndex.Vertex); var textureSamplingRect = new CGRect (0, 0, 1, 1); - float[] quadTextureData = { + float [] quadTextureData = { (float)textureSamplingRect.GetMinX (), (float)textureSamplingRect.GetMaxY (), (float)textureSamplingRect.GetMaxX (), (float)textureSamplingRect.GetMaxY (), (float)textureSamplingRect.GetMinX (), (float)textureSamplingRect.GetMinY (), (float)textureSamplingRect.GetMaxX (), (float)textureSamplingRect.GetMinY () }; - GL.VertexAttribPointer ((int)AttributeIndex.TextureCoordinates, 2, VertexAttribPointerType.Float, false, 0, quadTextureData); - GL.EnableVertexAttribArray ((int)AttributeIndex.TextureCoordinates); + GL.VertexAttribPointer ((int) AttributeIndex.TextureCoordinates, 2, VertexAttribPointerType.Float, false, 0, quadTextureData); + GL.EnableVertexAttribArray ((int) AttributeIndex.TextureCoordinates); GL.DrawArrays (BeginMode.TriangleStrip, 0, 4); GL.BindRenderbuffer (RenderbufferTarget.Renderbuffer, colorBufferHandle); - context.PresentRenderBuffer ((int)RenderbufferTarget.Renderbuffer); + context.PresentRenderBuffer ((int) RenderbufferTarget.Renderbuffer); } void CleanUpTextures () @@ -267,11 +265,11 @@ void SetupBuffers () { GL.Disable (EnableCap.DepthTest); - GL.EnableVertexAttribArray ((int)AttributeIndex.Vertex); - GL.VertexAttribPointer ((int)AttributeIndex.Vertex, 2, VertexAttribPointerType.Float, false, 2 * sizeof(float), 0); + GL.EnableVertexAttribArray ((int) AttributeIndex.Vertex); + GL.VertexAttribPointer ((int) AttributeIndex.Vertex, 2, VertexAttribPointerType.Float, false, 2 * sizeof (float), 0); - GL.EnableVertexAttribArray ((int)AttributeIndex.TextureCoordinates); - GL.VertexAttribPointer ((int)AttributeIndex.TextureCoordinates, 2, VertexAttribPointerType.Float, false, 2 * sizeof(float), 0); + GL.EnableVertexAttribArray ((int) AttributeIndex.TextureCoordinates); + GL.VertexAttribPointer ((int) AttributeIndex.TextureCoordinates, 2, VertexAttribPointerType.Float, false, 2 * sizeof (float), 0); GL.GenFramebuffers (1, out frameBufferHandle); GL.BindFramebuffer (FramebufferTarget.Framebuffer, frameBufferHandle); @@ -279,9 +277,9 @@ void SetupBuffers () GL.GenRenderbuffers (1, out colorBufferHandle); GL.BindRenderbuffer (RenderbufferTarget.Renderbuffer, colorBufferHandle); - context.RenderBufferStorage ((int)RenderbufferTarget.Renderbuffer, this); - GL.GetRenderbufferParameter (RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out backingWidth); - GL.GetRenderbufferParameter (RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out backingHeight); + context.RenderBufferStorage ((int) RenderbufferTarget.Renderbuffer, this); + GL.GetRenderbufferParameter (RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferWidth, out backingWidth); + GL.GetRenderbufferParameter (RenderbufferTarget.Renderbuffer, RenderbufferParameterName.RenderbufferHeight, out backingHeight); GL.FramebufferRenderbuffer (FramebufferTarget.Framebuffer, FramebufferSlot.ColorAttachment0, RenderbufferTarget.Renderbuffer, colorBufferHandle); @@ -309,8 +307,8 @@ bool LoadShaders () GL.AttachShader (Program, vertShader); GL.AttachShader (Program, fragShader); - GL.BindAttribLocation (Program, (int)AttributeIndex.Vertex, "position"); - GL.BindAttribLocation (Program, (int)AttributeIndex.TextureCoordinates, "texCoord"); + GL.BindAttribLocation (Program, (int) AttributeIndex.Vertex, "position"); + GL.BindAttribLocation (Program, (int) AttributeIndex.TextureCoordinates, "texCoord"); GL.LinkProgram (Program); #if DEBUG @@ -351,7 +349,7 @@ bool CompileShader (ShaderType shaderType, out int shader) Console.WriteLine ("Failed to load {0}", shaderType); return false; } - + shader = GL.CreateShader (shaderType); GL.ShaderSource (shader, source); GL.CompileShader (shader); @@ -381,7 +379,7 @@ void DrawTextInCorner (CVPixelBuffer pixelBuffer) AffineTransform.xx * -1f, AffineTransform.xy * -1f, AffineTransform.yx * -1f, AffineTransform.yy * -1f, AffineTransform.x0, AffineTransform.y0 - ); + ); } textLayer.Frame = new CGRect (Bounds.Size.Width - textLayerWidth, 0f, textLayerWidth, textLayerHeight); @@ -391,4 +389,4 @@ void DrawTextInCorner (CVPixelBuffer pixelBuffer) AddSublayer (textLayer); } } -} \ No newline at end of file +} diff --git a/ios8/VideoTimeLine/VideoTimeLine/Main.cs b/ios8/VideoTimeLine/VideoTimeLine/Main.cs index ebfb2369e..ebb48edf9 100644 --- a/ios8/VideoTimeLine/VideoTimeLine/Main.cs +++ b/ios8/VideoTimeLine/VideoTimeLine/Main.cs @@ -1,15 +1,15 @@ -using UIKit; +using UIKit; namespace VideoTimeLine { - + public class Application { - + // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/ios8/VideoTimeLine/VideoTimeLine/ViewController.cs b/ios8/VideoTimeLine/VideoTimeLine/ViewController.cs index e8a02763d..2f3dd6049 100644 --- a/ios8/VideoTimeLine/VideoTimeLine/ViewController.cs +++ b/ios8/VideoTimeLine/VideoTimeLine/ViewController.cs @@ -14,10 +14,8 @@ using UIKit; using VideoToolbox; -namespace VideoTimeLine -{ - public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUIPopoverControllerDelegate, IUINavigationControllerDelegate - { +namespace VideoTimeLine { + public partial class ViewController : UIViewController, IUIImagePickerControllerDelegate, IUIPopoverControllerDelegate, IUINavigationControllerDelegate { DispatchQueue backgroundQueue; List<CVPixelBuffer> outputFrames; @@ -42,7 +40,7 @@ public ViewController (IntPtr handle) : base (handle) public override void ViewDidLoad () { base.ViewDidLoad (); - + backgroundQueue = new DispatchQueue ("com.videotimeline.backgroundqueue", false); displayLink = CADisplayLink.Create (DisplayLinkCallback); displayLink.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Default); @@ -91,7 +89,7 @@ partial void ChooseVideoTapped (UIBarButtonItem sender) var videoPicker = new UIImagePickerController { ModalPresentationStyle = UIModalPresentationStyle.CurrentContext, SourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum, - MediaTypes = new string[] { UTType.Movie } + MediaTypes = new string [] { UTType.Movie } }; videoPicker.FinishedPickingMedia += (object s, UIImagePickerMediaPickedEventArgs e) => { displayLink.Paused = true; @@ -187,10 +185,10 @@ void ReadSampleBuffers (AVAsset asset) if (error != null) Console.WriteLine ("Error creating Asset Reader: {0}", error.Description); - AVAssetTrack[] videoTracks = asset.TracksWithMediaType (AVMediaType.Video); + AVAssetTrack [] videoTracks = asset.TracksWithMediaType (AVMediaType.Video); AVAssetTrack videoTrack = videoTracks [0]; CreateDecompressionSession (videoTrack); - var videoTrackOutput = AVAssetReaderTrackOutput.Create (videoTrack, (AVVideoSettingsUncompressed)null); + var videoTrackOutput = AVAssetReaderTrackOutput.Create (videoTrack, (AVVideoSettingsUncompressed) null); if (assetReader.CanAddOutput (videoTrackOutput)) assetReader.AddOutput (videoTrackOutput); @@ -212,14 +210,14 @@ void ReadSampleBuffers (AVAsset asset) } else if (assetReader.Status == AVAssetReaderStatus.Failed) { Console.WriteLine ("Asset Reader failed with error: {0}", assetReader.Error.Description); } else if (assetReader.Status == AVAssetReaderStatus.Completed) { - Console.WriteLine("Reached the end of the video."); + Console.WriteLine ("Reached the end of the video."); ChangeStatus (); ReadSampleBuffers (asset); } } } void ChangeStatus () - { + { InvokeOnMainThread (() => { displayLink.Paused = true; playButton.Title = "Play"; @@ -229,8 +227,8 @@ void ChangeStatus () void CreateDecompressionSession (AVAssetTrack videoTrack) { - CMFormatDescription[] formatDescriptions = videoTrack.FormatDescriptions; - var formatDescription = (CMVideoFormatDescription)formatDescriptions [0]; + CMFormatDescription [] formatDescriptions = videoTrack.FormatDescriptions; + var formatDescription = (CMVideoFormatDescription) formatDescriptions [0]; videoPreferredTransform = videoTrack.PreferredTransform; decompressionSession = VTDecompressionSession.Create (DidDecompress, formatDescription); } @@ -238,8 +236,8 @@ void CreateDecompressionSession (AVAssetTrack videoTrack) void DidDecompress (IntPtr sourceFrame, VTStatus status, VTDecodeInfoFlags flags, CVImageBuffer buffer, CMTime presentationTimeStamp, CMTime presentationDuration) { if (status != VTStatus.Ok) { - Console.WriteLine ("Error decompresssing frame at time: {0:#.###} error: {1} infoFlags: {2}", - (float)presentationTimeStamp.Value / presentationTimeStamp.TimeScale, (int)status, flags); + Console.WriteLine ("Error decompresssing frame at time: {0:#.###} error: {1} infoFlags: {2}", + (float) presentationTimeStamp.Value / presentationTimeStamp.TimeScale, (int) status, flags); return; } @@ -277,4 +275,4 @@ void DidDecompress (IntPtr sourceFrame, VTStatus status, VTDecodeInfoFlags flags } } } -} \ No newline at end of file +} diff --git a/ios9/ApplicationShortcuts/ApplicationShortcuts/AppDelegate.cs b/ios9/ApplicationShortcuts/ApplicationShortcuts/AppDelegate.cs index 0dbf44632..0a42d6c63 100644 --- a/ios9/ApplicationShortcuts/ApplicationShortcuts/AppDelegate.cs +++ b/ios9/ApplicationShortcuts/ApplicationShortcuts/AppDelegate.cs @@ -1,21 +1,18 @@ -using System; +using System; using System.Linq; using Foundation; using UIKit; -namespace ApplicationShortcuts -{ - enum ShortcutIdentifierType - { +namespace ApplicationShortcuts { + enum ShortcutIdentifierType { First, Second, Third, Fourth, } - static class ShortcutIdentifierTypeExtensions - { + static class ShortcutIdentifierTypeExtensions { public static string GetTypeName (this ShortcutIdentifierType self) { return string.Format ("{0} {1}", NSBundle.MainBundle.BundleIdentifier, self); @@ -23,24 +20,22 @@ public static string GetTypeName (this ShortcutIdentifierType self) } [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - public static readonly NSString ApplicationShortcutUserInfoIconKey = (NSString)"applicationShortcutUserInfoIconKey"; + public class AppDelegate : UIApplicationDelegate { + public static readonly NSString ApplicationShortcutUserInfoIconKey = (NSString) "applicationShortcutUserInfoIconKey"; - class ShortcutIdentifier - { + class ShortcutIdentifier { public ShortcutIdentifierType Type { get; private set; } ShortcutIdentifier () { } - public static ShortcutIdentifier Create(string fullType) + public static ShortcutIdentifier Create (string fullType) { if (string.IsNullOrWhiteSpace (fullType)) return null; - string last = fullType.Split (new []{ '.' }, StringSplitOptions.RemoveEmptyEntries).Last (); + string last = fullType.Split (new [] { '.' }, StringSplitOptions.RemoveEmptyEntries).Last (); ShortcutIdentifierType type; bool isParsed = Enum.TryParse<ShortcutIdentifierType> (last, out type); @@ -53,7 +48,7 @@ public static ShortcutIdentifier Create(string fullType) // Saved shortcut item used as a result of an app launch, used later when app is activated. UIApplicationShortcutItem launchedShortcutItem; - bool HandleShortCutItem(UIApplicationShortcutItem shortcutItem) + bool HandleShortCutItem (UIApplicationShortcutItem shortcutItem) { // Verify that the provided `shortcutItem`'s `type` is one handled by the application. var shortcutIdentifier = ShortcutIdentifier.Create (shortcutItem.Type); @@ -89,7 +84,7 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary var shouldPerformAdditionalDelegateHandling = true; // If a shortcut was launched, display its information and take the appropriate action - if(launchOptions != null) { + if (launchOptions != null) { var shortcutItem = launchOptions [UIApplication.LaunchOptionsShortcutItemKey] as UIApplicationShortcutItem; if (shortcutItem != null) { launchedShortcutItem = shortcutItem; @@ -107,26 +102,26 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary return shouldPerformAdditionalDelegateHandling; } - static UIMutableApplicationShortcutItem CreatePlayShortcut() + static UIMutableApplicationShortcutItem CreatePlayShortcut () { string type = ShortcutIdentifierType.Third.GetTypeName (); var icon = CreateIcon (UIApplicationShortcutIconType.Play); - var userInfo = CreateUserInfo(UIApplicationShortcutIconType.Play); + var userInfo = CreateUserInfo (UIApplicationShortcutIconType.Play); return new UIMutableApplicationShortcutItem (type, "Play", "Will Play an item", icon, userInfo); } static UIMutableApplicationShortcutItem CreatePauseShortcut () { var type = ShortcutIdentifierType.Fourth.GetTypeName (); - var icon = CreateIcon(UIApplicationShortcutIconType.Pause); + var icon = CreateIcon (UIApplicationShortcutIconType.Pause); var userInfo = CreateUserInfo (UIApplicationShortcutIconType.Pause); return new UIMutableApplicationShortcutItem (type, "Pause", "Will Pause an item", icon, userInfo); } - static NSDictionary<NSString, NSObject> CreateUserInfo(UIApplicationShortcutIconType type) + static NSDictionary<NSString, NSObject> CreateUserInfo (UIApplicationShortcutIconType type) { int rawValue = Convert.ToInt32 (type); - return new NSDictionary<NSString, NSObject>(ApplicationShortcutUserInfoIconKey, new NSNumber (rawValue)); + return new NSDictionary<NSString, NSObject> (ApplicationShortcutUserInfoIconKey, new NSNumber (rawValue)); } static UIApplicationShortcutIcon CreateIcon (UIApplicationShortcutIconType type) @@ -144,4 +139,4 @@ public override void PerformActionForShortcutItem (UIApplication application, UI completionHandler (handledShortCutItem); } } -} \ No newline at end of file +} diff --git a/ios9/ApplicationShortcuts/ApplicationShortcuts/Main.cs b/ios9/ApplicationShortcuts/ApplicationShortcuts/Main.cs index daf8c5451..730280752 100644 --- a/ios9/ApplicationShortcuts/ApplicationShortcuts/Main.cs +++ b/ios9/ApplicationShortcuts/ApplicationShortcuts/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace ApplicationShortcuts -{ - public class Application - { +namespace ApplicationShortcuts { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutDetailViewController.cs b/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutDetailViewController.cs index fdee7ce08..a0d8028ee 100644 --- a/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutDetailViewController.cs +++ b/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutDetailViewController.cs @@ -3,11 +3,9 @@ using Foundation; using UIKit; -namespace ApplicationShortcuts -{ - public partial class ShortcutDetailViewController : UITableViewController, IUITextFieldDelegate, IUIPickerViewDataSource, IUIPickerViewDelegate - { - static readonly string[] pickerItems = { "Compose", "Play", "Pause", "Add", "Location", "Search", "Share" }; +namespace ApplicationShortcuts { + public partial class ShortcutDetailViewController : UITableViewController, IUITextFieldDelegate, IUIPickerViewDataSource, IUIPickerViewDelegate { + static readonly string [] pickerItems = { "Compose", "Play", "Pause", "Add", "Location", "Search", "Share" }; [Outlet ("titleTextField")] public UITextField TitleTextField { get; set; } @@ -61,7 +59,7 @@ public override void ViewDidLoad () UIApplicationShortcutIconType iconType = IconTypeForSelectedRow (row); // The `iconType` returned may not align to the `iconRawValue` so use the `iconType`'s `rawValue`. - PickerView.Select ((int)iconType, 0, false); + PickerView.Select ((int) iconType, 0, false); textFieldObserverToken = UITextField.Notifications.ObserveTextFieldTextDidChange ((s, e) => { // You cannot dismiss the view controller without a valid shortcut title. @@ -72,8 +70,8 @@ public override void ViewDidLoad () // Constructs a UIApplicationShortcutIconType based on the integer result from our picker. static UIApplicationShortcutIconType IconTypeForSelectedRow (int row) { - var value = (UIApplicationShortcutIconType)row; - bool isDefined = Enum.IsDefined (typeof(UIApplicationShortcutIconType), value); + var value = (UIApplicationShortcutIconType) row; + bool isDefined = Enum.IsDefined (typeof (UIApplicationShortcutIconType), value); return isDefined ? value : UIApplicationShortcutIconType.Compose; } @@ -103,7 +101,7 @@ public nint GetRowsInComponent (UIPickerView pickerView, nint component) [Export ("pickerView:titleForRow:forComponent:")] public string GetTitle (UIPickerView pickerView, nint row, nint component) { - return pickerItems [(int)row]; + return pickerItems [(int) row]; } #endregion @@ -118,7 +116,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (segue.Identifier == "ShortcutDetailUpdated") { // In the updated case, create a shortcut item to represent the final state of the view controller. - UIApplicationShortcutIconType iconType = IconTypeForSelectedRow ((int)PickerView.SelectedRowInComponent (0)); + UIApplicationShortcutIconType iconType = IconTypeForSelectedRow ((int) PickerView.SelectedRowInComponent (0)); var icon = UIApplicationShortcutIcon.FromType (iconType); var userInfo = new NSDictionary<NSString, NSObject> (AppDelegate.ApplicationShortcutUserInfoIconKey, new NSNumber (PickerView.SelectedRowInComponent (0))); @@ -137,4 +135,4 @@ protected override void Dispose (bool disposing) base.Dispose (disposing); } } -} \ No newline at end of file +} diff --git a/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutsTableViewController.cs b/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutsTableViewController.cs index 21b169a2f..f6978a919 100644 --- a/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutsTableViewController.cs +++ b/ios9/ApplicationShortcuts/ApplicationShortcuts/ShortcutsTableViewController.cs @@ -4,10 +4,8 @@ using UIKit; using Foundation; -namespace ApplicationShortcuts -{ - public partial class ShortcutsTableViewController : UITableViewController - { +namespace ApplicationShortcuts { + public partial class ShortcutsTableViewController : UITableViewController { // Pre-defined shortcuts; retrieved from the Info.plist, lazily. List<UIApplicationShortcutItem> staticShortcuts; @@ -27,9 +25,9 @@ List<UIApplicationShortcutItem> StaticShortcuts { if (array == null) return staticShortcuts; - Dictionary<string, NSObject>[] shortcuts = ParseShortcuts (array); + Dictionary<string, NSObject> [] shortcuts = ParseShortcuts (array); - foreach (var shortcut in shortcuts) { + foreach (var shortcut in shortcuts) { // The `UIApplicationShortcutItemType` and `UIApplicationShortcutItemTitle` keys are required to successfully create a `UIApplicationShortcutItem`. NSObject rawShortcutType; NSObject rawShortcutTitle; @@ -56,12 +54,12 @@ List<UIApplicationShortcutItem> StaticShortcuts { } // Shortcuts defined by the application and modifiable based on application state. - UIApplicationShortcutItem[] dynamicShortcuts; + UIApplicationShortcutItem [] dynamicShortcuts; - UIApplicationShortcutItem[] DynamicShortcuts { + UIApplicationShortcutItem [] DynamicShortcuts { get { if (dynamicShortcuts == null) - dynamicShortcuts = UIApplication.SharedApplication.ShortcutItems ?? new UIApplicationShortcutItem[0]; + dynamicShortcuts = UIApplication.SharedApplication.ShortcutItems ?? new UIApplicationShortcutItem [0]; return dynamicShortcuts; } @@ -72,15 +70,15 @@ public ShortcutsTableViewController (IntPtr handle) : base (handle) { } - static Dictionary<string, NSObject>[] ParseShortcuts (NSArray items) + static Dictionary<string, NSObject> [] ParseShortcuts (NSArray items) { - var count = (int)items.Count; - var result = new Dictionary<string, NSObject>[count]; + var count = (int) items.Count; + var result = new Dictionary<string, NSObject> [count]; for (int i = 0; i < count; i++) { - var nDict = items.GetItem<NSDictionary> ((nuint)i); + var nDict = items.GetItem<NSDictionary> ((nuint) i); var dict = result [i] = new Dictionary<string, NSObject> (); foreach (var kvp in nDict) - dict [(NSString)kvp.Key] = kvp.Value; + dict [(NSString) kvp.Key] = kvp.Value; } return result; @@ -180,7 +178,7 @@ void Done (UIStoryboardSegue sender) // Update the application's `shortcutItems`. UIApplication.SharedApplication.ShortcutItems = DynamicShortcuts; - TableView.ReloadRows (new []{ selected }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new [] { selected }, UITableViewRowAnimation.Automatic); } // Unwind segue action called when the user taps 'Cancel' after navigating to the detail controller. @@ -191,4 +189,4 @@ void cancel (UIStoryboardSegue sender) #endregion } -} \ No newline at end of file +} diff --git a/ios9/AstroLayout/AstroLayout/AppDelegate.cs b/ios9/AstroLayout/AstroLayout/AppDelegate.cs index 50e0d55a0..37527e3a2 100644 --- a/ios9/AstroLayout/AstroLayout/AppDelegate.cs +++ b/ios9/AstroLayout/AstroLayout/AppDelegate.cs @@ -4,7 +4,7 @@ namespace AstroLayout { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { - - public override UIWindow Window { get; set; } - } -} \ No newline at end of file + + public override UIWindow Window { get; set; } + } +} diff --git a/ios9/AstroLayout/AstroLayout/AstroViewController.cs b/ios9/AstroLayout/AstroLayout/AstroViewController.cs index 8fbb66f92..ffd853a89 100644 --- a/ios9/AstroLayout/AstroLayout/AstroViewController.cs +++ b/ios9/AstroLayout/AstroLayout/AstroViewController.cs @@ -6,11 +6,11 @@ using UIKit; namespace AstroLayout { - [Register ("AstroViewController")] - public class AstroViewController : UIViewController { - - NSLayoutConstraint[] regularConstraints; - NSLayoutConstraint[] compactConstraints; + [Register ("AstroViewController")] + public class AstroViewController : UIViewController { + + NSLayoutConstraint [] regularConstraints; + NSLayoutConstraint [] compactConstraints; List<NSLayoutConstraint> sharedConstraints; UIImageView mercury; @@ -50,13 +50,13 @@ public AstroViewController (NSCoder coder) : base (coder) } public override void ViewDidLoad () - { + { View.BackgroundColor = UIColor.Black; CreatePlanetViews (); CreateConstraints (); SetUpGestures (); - } + } public override void TraitCollectionDidChange (UITraitCollection previousTraitCollection) { @@ -73,26 +73,26 @@ public override void TraitCollectionDidChange (UITraitCollection previousTraitCo } } - void CreateConstraints () - { + void CreateConstraints () + { PlanetSizes (); CreateCompactConstraints (); CreateRegularConstraints (); NSLayoutConstraint.ActivateConstraints (regularConstraints); NSLayoutConstraint.ActivateConstraints (sharedConstraints.ToArray ()); - } + } - void SetLayoutIdentifierForArray (NSString identifier, NSArray constraintsArray) + void SetLayoutIdentifierForArray (NSString identifier, NSArray constraintsArray) { for (nuint i = 0; i < constraintsArray.Count; i++) { var constraint = constraintsArray.GetItem<NSLayoutConstraint> (i); constraint.SetIdentifier (identifier); } - } + } - void CreatePlanetViews () - { + void CreatePlanetViews () + { mercury = CreatePlanet ("Mercury"); venus = CreatePlanet ("Venus"); earth = CreatePlanet ("Earth"); @@ -101,7 +101,7 @@ void CreatePlanetViews () saturn = CreatePlanet ("Saturn"); uranus = CreatePlanet ("Uranus"); neptune = CreatePlanet ("Neptune"); - } + } UIImageView CreatePlanet (string planetName) { @@ -115,14 +115,14 @@ UIImageView CreatePlanet (string planetName) return planet; } - void PlanetSizes () - { + void PlanetSizes () + { NSLayoutConstraint mercuryHeight = mercury.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, .38f); NSLayoutConstraint mercuryWidth = mercury.WidthAnchor.ConstraintEqualTo (mercury.HeightAnchor, 1f); NSLayoutConstraint venusHeight = venus.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, .95f); NSLayoutConstraint venusWidth = venus.WidthAnchor.ConstraintEqualTo (venus.HeightAnchor, 1f); - + NSLayoutConstraint marsHeight = mars.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, .53f); NSLayoutConstraint marsWidth = mars.WidthAnchor.ConstraintEqualTo (mars.HeightAnchor, 1f); @@ -134,12 +134,12 @@ void PlanetSizes () NSLayoutConstraint uranusHeight = uranus.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, 4f); NSLayoutConstraint uranusWidth = uranus.WidthAnchor.ConstraintEqualTo (uranus.HeightAnchor, 1f); - + NSLayoutConstraint neptuneHeight = neptune.HeightAnchor.ConstraintEqualTo (earth.HeightAnchor, 3.88f); NSLayoutConstraint neptuneWidth = neptune.HeightAnchor.ConstraintEqualTo (neptune.HeightAnchor, 1f); - + NSLayoutConstraint earthWidth = earth.WidthAnchor.ConstraintEqualTo (earth.HeightAnchor); - + mercuryHeight.SetIdentifier ("mercuryHeight"); mercuryHeight.SetIdentifier ("mercuryHeight"); mercuryWidth.SetIdentifier ("mercuryWidth"); @@ -164,12 +164,12 @@ void PlanetSizes () }); } - void CreateCompactConstraints() - { + void CreateCompactConstraints () + { if (compactConstraints?.Length > 0) return; - - mercuryCenter = CreateCenterXConstraint (mercury, "mercuryCenterX"); + + mercuryCenter = CreateCenterXConstraint (mercury, "mercuryCenterX"); venusCenter = CreateCenterXConstraint (venus, "venusCenterX"); earthCenter = CreateCenterXConstraint (earth, "earthCenterX"); marsCenter = CreateCenterXConstraint (mars, "marsCenterX"); @@ -181,8 +181,8 @@ void CreateCompactConstraints() compactConstraints = new [] { mercuryCenter, venusCenter, earthCenter, marsCenter, jupiterCenter, saturnCenter, uranusCenter, neptuneCenter }; - } - + } + NSLayoutConstraint CreateCenterXConstraint (UIView planetToCenter, string identifierName) { NSLayoutConstraint newConstraint = planetToCenter.CenterXAnchor.ConstraintEqualTo (View.CenterXAnchor); @@ -190,12 +190,12 @@ NSLayoutConstraint CreateCenterXConstraint (UIView planetToCenter, string identi return newConstraint; } - void CreateRegularConstraints () - { + void CreateRegularConstraints () + { if (regularConstraints?.Length > 0 && sharedConstraints?.Count > 0) - return; - - UILayoutGuide leadingMercuryGuide = NewLayoutGuide ("leadingMercuryGuide"); + return; + + UILayoutGuide leadingMercuryGuide = NewLayoutGuide ("leadingMercuryGuide"); UILayoutGuide leadingVenusGuide = NewLayoutGuide ("leadingVenusGuide"); UILayoutGuide leadingEarthGuide = NewLayoutGuide ("leadingEarthGuide"); UILayoutGuide leadingMarsGuide = NewLayoutGuide ("leadingMarsGuide"); @@ -212,16 +212,16 @@ void CreateRegularConstraints () UILayoutGuide trailingSaturnGuide = NewLayoutGuide ("trailingSaturnGuide"); UILayoutGuide trailingUranusGuide = NewLayoutGuide ("trailingUranusGuide"); UILayoutGuide trailingNeptuneGuide = NewLayoutGuide ("trailingNeptuneGuide"); - + IUILayoutSupport topLayoutGuide = TopLayoutGuide; - var planetsAndGuides = NSDictionary.FromObjectsAndKeys (new object[] { + var planetsAndGuides = NSDictionary.FromObjectsAndKeys (new object [] { mercury, venus, earth, mars, jupiter, saturn, uranus, neptune, leadingMercuryGuide, leadingVenusGuide, leadingEarthGuide, leadingMarsGuide, leadingJupiterGuide, leadingSaturnGuide, leadingUranusGuide, leadingNeptuneGuide, trailingMercuryGuide, trailingVenusGuide, trailingEarthGuide, trailingMarsGuide, trailingJupiterGuide, trailingSaturnGuide, trailingUranusGuide, trailingNeptuneGuide, topLayoutGuide - }, new object[] { + }, new object [] { "mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune", "leadingMercuryGuide", "leadingVenusGuide", "leadingEarthGuide", "leadingMarsGuide", "leadingJupiterGuide", "leadingSaturnGuide", "leadingUranusGuide", "leadingNeptuneGuide", @@ -233,9 +233,9 @@ void CreateRegularConstraints () "[leadingVenusGuide]-[leadingEarthGuide]-[leadingMarsGuide]-" + "[leadingJupiterGuide][leadingSaturnGuide][leadingUranusGuide]-" + "[leadingNeptuneGuide]-20-|", NSLayoutFormatOptions.DirectionLeadingToTrailing, null, planetsAndGuides); - + sharedConstraints = new List<NSLayoutConstraint> (topToBottom); - SetLayoutIdentifierForArray ((NSString)"topToBottom", NSArray.FromObjects (topToBottom)); + SetLayoutIdentifierForArray ((NSString) "topToBottom", NSArray.FromObjects (topToBottom)); NewHorizontalArray ("|[leadingMercuryGuide][mercury][trailingMercuryGuide]|", "hMercury", planetsAndGuides); NewHorizontalArray ("|[leadingVenusGuide][venus][trailingVenusGuide]|", "hVenus", planetsAndGuides); @@ -245,7 +245,7 @@ void CreateRegularConstraints () NewHorizontalArray ("|[leadingSaturnGuide][saturn][trailingSaturnGuide]|", "hSaturn", planetsAndGuides); NewHorizontalArray ("|[leadingUranusGuide][uranus][trailingUranusGuide]|", "hUranus", planetsAndGuides); NewHorizontalArray ("|[leadingNeptuneGuide][neptune][trailingNeptuneGuide]|", "hNeptune", planetsAndGuides); - + sharedConstraints.Add (GuideHeightToPlanet (leadingMercuryGuide, mercury, "guideHeightToMercury")); sharedConstraints.Add (GuideHeightToPlanet (leadingVenusGuide, venus, "guideHeightToVenus")); sharedConstraints.Add (GuideHeightToPlanet (leadingEarthGuide, earth, "guideHeightToEarth")); @@ -263,7 +263,7 @@ void CreateRegularConstraints () saturnLeadingToTrailing = leadingSaturnGuide.WidthAnchor.ConstraintEqualTo (trailingSaturnGuide.WidthAnchor, 1f); uranusLeadingToTrailing = leadingUranusGuide.WidthAnchor.ConstraintEqualTo (trailingUranusGuide.WidthAnchor, 2.7f); neptuneLeadingToTrailing = leadingNeptuneGuide.WidthAnchor.ConstraintEqualTo (trailingNeptuneGuide.WidthAnchor, 10f); - + mercuryLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorMercury"); venusLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorVenus"); earthLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorEarth"); @@ -272,7 +272,7 @@ void CreateRegularConstraints () saturnLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorSaturn"); uranusLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorUranus"); neptuneLeadingToTrailing.SetIdentifier ("leadingTrailingAnchorNeptune"); - + regularConstraints = new [] { mercuryLeadingToTrailing, venusLeadingToTrailing, earthLeadingToTrailing, marsLeadingToTrailing, saturnLeadingToTrailing, jupiterLeadingToTrailing, uranusLeadingToTrailing, neptuneLeadingToTrailing @@ -283,7 +283,7 @@ void NewHorizontalArray (string layoutString, string arrayID, NSDictionary plane { var horizontalConstraintsArray = NSLayoutConstraint.FromVisualFormat (layoutString, NSLayoutFormatOptions.AlignAllCenterY, null, planetsAndGuides); sharedConstraints.AddRange (horizontalConstraintsArray); - SetLayoutIdentifierForArray ((NSString)arrayID, NSArray.FromObjects (horizontalConstraintsArray)); + SetLayoutIdentifierForArray ((NSString) arrayID, NSArray.FromObjects (horizontalConstraintsArray)); } NSLayoutConstraint GuideHeightToPlanet (UILayoutGuide layoutGuide, UIView planet, string identifier) @@ -303,8 +303,8 @@ UILayoutGuide NewLayoutGuide (string identifierName) return newGuide; } - void ChangeLayout (UIGestureRecognizer tapGesture) - { + void ChangeLayout (UIGestureRecognizer tapGesture) + { if (tapGesture.State != UIGestureRecognizerState.Ended) return; @@ -323,10 +323,10 @@ void ChangeLayout (UIGestureRecognizer tapGesture) View.LayoutIfNeeded (); }); } - } + } - void KeyframeBasedLayoutChange (UIGestureRecognizer twoFingerDoubleTap) - { + void KeyframeBasedLayoutChange (UIGestureRecognizer twoFingerDoubleTap) + { if (twoFingerDoubleTap.State != UIGestureRecognizerState.Ended) return; @@ -335,16 +335,16 @@ void KeyframeBasedLayoutChange (UIGestureRecognizer twoFingerDoubleTap) if (regularConstraint.Active) { UIView.AnimateKeyframes (1.5, 0.0, UIViewKeyframeAnimationOptions.CalculationModeLinear, AnimateToCompact, finished => { - }); + }); } else if (compactConstraint.Active) { UIView.AnimateKeyframes (1.5, 0.0, UIViewKeyframeAnimationOptions.CalculationModeLinear, AnimateToRegular, finished => { - }); + }); } - } + } - void AnimateToRegular () - { + void AnimateToRegular () + { UIView.AddKeyframeWithRelativeStartTime (0.0, 1.0, () => { NSLayoutConstraint.DeactivateConstraints (new [] { mercuryCenter }); NSLayoutConstraint.ActivateConstraints (new [] { mercuryLeadingToTrailing }); @@ -368,10 +368,10 @@ void AnimateToRegular () NSLayoutConstraint.ActivateConstraints (new [] { marsLeadingToTrailing, jupiterLeadingToTrailing, saturnLeadingToTrailing }); View.LayoutIfNeeded (); }); - } + } - void AnimateToCompact () - { + void AnimateToCompact () + { UIView.AddKeyframeWithRelativeStartTime (0.0, 1.0, () => { NSLayoutConstraint.DeactivateConstraints (new [] { marsLeadingToTrailing, jupiterLeadingToTrailing, saturnLeadingToTrailing }); NSLayoutConstraint.ActivateConstraints (new [] { marsCenter, jupiterCenter, saturnCenter }); @@ -395,10 +395,10 @@ void AnimateToCompact () NSLayoutConstraint.ActivateConstraints (new [] { mercuryCenter }); View.LayoutIfNeeded (); }); - } + } - void SetUpGestures () - { + void SetUpGestures () + { UITapGestureRecognizer doubleTap = null; doubleTap = new UITapGestureRecognizer (() => ChangeLayout (doubleTap)) { NumberOfTapsRequired = 2, @@ -412,6 +412,6 @@ void SetUpGestures () NumberOfTouchesRequired = 2 }; View.AddGestureRecognizer (twoFingerDoubleTap); - } - } -} \ No newline at end of file + } + } +} diff --git a/ios9/AstroLayout/AstroLayout/main.cs b/ios9/AstroLayout/AstroLayout/main.cs index 55fde2f02..b6ebd916d 100644 --- a/ios9/AstroLayout/AstroLayout/main.cs +++ b/ios9/AstroLayout/AstroLayout/main.cs @@ -4,7 +4,7 @@ namespace AstroLayout { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/CollectionView/CollectionView/AppDelegate.cs b/ios9/CollectionView/CollectionView/AppDelegate.cs index 48aa9bb03..11560cc11 100644 --- a/ios9/CollectionView/CollectionView/AppDelegate.cs +++ b/ios9/CollectionView/CollectionView/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace CollectionView { diff --git a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionDelegate.cs b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionDelegate.cs index 7cf441583..e83bbcead 100644 --- a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionDelegate.cs +++ b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace CollectionView { @@ -13,7 +13,7 @@ namespace CollectionView { /// </remarks> public class WaterfallCollectionDelegate : UICollectionViewDelegate { #region Computed Properties - public WaterfallCollectionView CollectionView { get; set;} + public WaterfallCollectionView CollectionView { get; set; } #endregion #region Constructors diff --git a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionLayout.cs b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionLayout.cs index 057f380a5..407d4b486 100644 --- a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionLayout.cs +++ b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionLayout.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using CoreGraphics; @@ -15,7 +15,7 @@ namespace CollectionView { /// Ported from http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/ to /// Xamarin.iOS by Kevin Mullins. /// </remarks> - [Register("WaterfallCollectionLayout")] + [Register ("WaterfallCollectionLayout")] public class WaterfallCollectionLayout : UICollectionViewLayout { #region Variables int columnCount = 2; @@ -26,8 +26,8 @@ public class WaterfallCollectionLayout : UICollectionViewLayout { nfloat footerHeight = 0f; UIEdgeInsets sectionInset = new UIEdgeInsets (0f, 0f, 0f, 0f); WaterfallCollectionRenderDirection itemRenderDirection = WaterfallCollectionRenderDirection.ShortestFirst; - Dictionary<nint,UICollectionViewLayoutAttributes> headersAttributes = new Dictionary<nint, UICollectionViewLayoutAttributes> (); - Dictionary<nint,UICollectionViewLayoutAttributes> footersAttributes = new Dictionary<nint, UICollectionViewLayoutAttributes> (); + Dictionary<nint, UICollectionViewLayoutAttributes> headersAttributes = new Dictionary<nint, UICollectionViewLayoutAttributes> (); + Dictionary<nint, UICollectionViewLayoutAttributes> footersAttributes = new Dictionary<nint, UICollectionViewLayoutAttributes> (); List<CGRect> unionRects = new List<CGRect> (); List<nfloat> columnHeights = new List<nfloat> (); List<UICollectionViewLayoutAttributes> allItemAttributes = new List<UICollectionViewLayoutAttributes> (); @@ -35,7 +35,7 @@ public class WaterfallCollectionLayout : UICollectionViewLayout { #endregion #region Computed Properties - [Export("ColumnCount")] + [Export ("ColumnCount")] public int ColumnCount { get { return columnCount; } set { @@ -47,7 +47,7 @@ public int ColumnCount { } } - [Export("MinimumColumnSpacing")] + [Export ("MinimumColumnSpacing")] public nfloat MinimumColumnSpacing { get { return minimumColumnSpacing; } set { @@ -59,7 +59,7 @@ public nfloat MinimumColumnSpacing { } } - [Export("MinimumInterItemSpacing")] + [Export ("MinimumInterItemSpacing")] public nfloat MinimumInterItemSpacing { get { return minimumInterItemSpacing; } set { @@ -71,7 +71,7 @@ public nfloat MinimumInterItemSpacing { } } - [Export("HeaderHeight")] + [Export ("HeaderHeight")] public nfloat HeaderHeight { get { return headerHeight; } set { @@ -83,7 +83,7 @@ public nfloat HeaderHeight { } } - [Export("FooterHeight")] + [Export ("FooterHeight")] public nfloat FooterHeight { get { return footerHeight; } set { @@ -95,7 +95,7 @@ public nfloat FooterHeight { } } - [Export("SectionInset")] + [Export ("SectionInset")] public UIEdgeInsets SectionInset { get { return sectionInset; } set { @@ -107,7 +107,7 @@ public UIEdgeInsets SectionInset { } } - [Export("ItemRenderDirection")] + [Export ("ItemRenderDirection")] public WaterfallCollectionRenderDirection ItemRenderDirection { get { return itemRenderDirection; } set { @@ -125,10 +125,10 @@ public WaterfallCollectionLayout () { } - public WaterfallCollectionLayout(NSCoder coder) : base(coder) + public WaterfallCollectionLayout (NSCoder coder) : base (coder) { } - #endregion + #endregion #region Override Methods public override void PrepareLayout () @@ -150,7 +150,7 @@ public override void PrepareLayout () // Initialize column heights for (int n = 0; n < ColumnCount; n++) - columnHeights.Add ((nfloat)0); + columnHeights.Add ((nfloat) 0); // Process all sections nfloat top = 0f; @@ -161,10 +161,10 @@ public override void PrepareLayout () // Calculate widths var width = CollectionView.Bounds.Width - SectionInset.Left - SectionInset.Right; - var itemWidth = (nfloat)Math.Floor ((width - ((ColumnCount - 1) * MinimumColumnSpacing)) / ColumnCount); + var itemWidth = (nfloat) Math.Floor ((width - ((ColumnCount - 1) * MinimumColumnSpacing)) / ColumnCount); // Calculate section header - var heightHeader = (HeightForHeader == null) ? HeaderHeight : + var heightHeader = (HeightForHeader == null) ? HeaderHeight : HeightForHeader (CollectionView, this, section); if (heightHeader > 0) { @@ -187,13 +187,13 @@ public override void PrepareLayout () for (nint n = 0; n < itemCount; n++) { var indexPath = NSIndexPath.FromRowSection (n, section); columnIndex = NextColumnIndexForItem (n); - var xOffset = SectionInset.Left + (itemWidth + MinimumColumnSpacing) * (nfloat)columnIndex; + var xOffset = SectionInset.Left + (itemWidth + MinimumColumnSpacing) * (nfloat) columnIndex; var yOffset = columnHeights [columnIndex]; var itemSize = (SizeForItem == null) ? new CGSize (0, 0) : SizeForItem (CollectionView, this, indexPath); nfloat itemHeight = 0.0f; if (itemSize.Height > 0.0f && itemSize.Width > 0.0f) - itemHeight = (nfloat)Math.Floor (itemSize.Height * itemWidth / itemSize.Width); + itemHeight = (nfloat) Math.Floor (itemSize.Height * itemWidth / itemSize.Width); attributes = UICollectionViewLayoutAttributes.CreateForCell (indexPath); attributes.Frame = new CGRect (xOffset, yOffset, itemWidth, itemHeight); @@ -225,7 +225,7 @@ public override void PrepareLayout () int attrs = allItemAttributes.Count; while (i < attrs) { var rect1 = allItemAttributes [i].Frame; - i = (int)Math.Min (i + unionSize, attrs) - 1; + i = (int) Math.Min (i + unionSize, attrs) - 1; var rect2 = allItemAttributes [i].Frame; unionRects.Add (CGRect.Union (rect1, rect2)); i++; @@ -252,7 +252,7 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForItem (NSInde return null; var list = sectionItemAttributes [indexPath.Section]; - return list [(int)indexPath.Item]; + return list [(int) indexPath.Item]; } public override UICollectionViewLayoutAttributes LayoutAttributesForSupplementaryView (NSString kind, NSIndexPath indexPath) @@ -271,7 +271,7 @@ public override UICollectionViewLayoutAttributes LayoutAttributesForSupplementar return attributes; } - public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect (CGRect rect) + public override UICollectionViewLayoutAttributes [] LayoutAttributesForElementsInRect (CGRect rect) { int begin = 0; int end = unionRects.Count; @@ -280,11 +280,11 @@ public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsIn for (int i = 0; i < end; i++) if (rect.IntersectsWith (unionRects [i])) - begin = i * (int)unionSize; + begin = i * (int) unionSize; for (int i = end - 1; i >= 0; i--) { if (rect.IntersectsWith (unionRects [i])) { - end = Math.Min ((i + 1) * (int)unionSize, allItemAttributes.Count); + end = Math.Min ((i + 1) * (int) unionSize, allItemAttributes.Count); break; } } @@ -307,7 +307,7 @@ public override bool ShouldInvalidateLayoutForBoundsChange (CGRect newBounds) #endregion #region Methods - int ShortestColumnIndex() + int ShortestColumnIndex () { int index = 0; nfloat shortestHeight = nfloat.MaxValue; @@ -355,7 +355,7 @@ int NextColumnIndexForItem (nint item) index = ColumnCount; break; case WaterfallCollectionRenderDirection.RightToLeft: - index = (ColumnCount - 1) - ((int)item / ColumnCount); + index = (ColumnCount - 1) - ((int) item / ColumnCount); break; } @@ -364,9 +364,9 @@ int NextColumnIndexForItem (nint item) #endregion #region Events - public delegate CGSize WaterfallCollectionSizeDelegate(UICollectionView collectionView, WaterfallCollectionLayout layout, NSIndexPath indexPath); - public delegate nfloat WaterfallCollectionFloatDelegate(UICollectionView collectionView, WaterfallCollectionLayout layout, nint section); - public delegate UIEdgeInsets WaterfallCollectionEdgeInsetsDelegate(UICollectionView collectionView, WaterfallCollectionLayout layout, nint section); + public delegate CGSize WaterfallCollectionSizeDelegate (UICollectionView collectionView, WaterfallCollectionLayout layout, NSIndexPath indexPath); + public delegate nfloat WaterfallCollectionFloatDelegate (UICollectionView collectionView, WaterfallCollectionLayout layout, nint section); + public delegate UIEdgeInsets WaterfallCollectionEdgeInsetsDelegate (UICollectionView collectionView, WaterfallCollectionLayout layout, nint section); public event WaterfallCollectionSizeDelegate SizeForItem; public event WaterfallCollectionFloatDelegate HeightForHeader; diff --git a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionRenderDirection.cs b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionRenderDirection.cs index 8a92834f1..a5dd1b30d 100644 --- a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionRenderDirection.cs +++ b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionRenderDirection.cs @@ -1,4 +1,4 @@ -namespace CollectionView { +namespace CollectionView { /// <summary> /// Waterfall collection render direction. /// </summary> diff --git a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionSource.cs b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionSource.cs index d6650befd..e9588b41f 100644 --- a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionSource.cs +++ b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionSource.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; @@ -16,7 +16,7 @@ namespace CollectionView { /// </remarks> public class WaterfallCollectionSource : UICollectionViewDataSource { #region Private Variables - Random rnd = new Random(); + Random rnd = new Random (); #endregion #region Computed Properties @@ -58,7 +58,7 @@ public override UICollectionViewCell GetCell (UICollectionView collectionView, N { // Get a reusable cell and set it's title from the item var cell = collectionView.DequeueReusableCell ("Cell", indexPath) as TextCollectionViewCell; - cell.Title = Numbers [(int)indexPath.Item].ToString(); + cell.Title = Numbers [(int) indexPath.Item].ToString (); return cell; } @@ -72,9 +72,9 @@ public override bool CanMoveItem (UICollectionView collectionView, NSIndexPath i public override void MoveItem (UICollectionView collectionView, NSIndexPath sourceIndexPath, NSIndexPath destinationIndexPath) { // Reorder our list of items - var item = Numbers [(int)sourceIndexPath.Item]; - Numbers.RemoveAt ((int)sourceIndexPath.Item); - Numbers.Insert ((int)destinationIndexPath.Item, item); + var item = Numbers [(int) sourceIndexPath.Item]; + Numbers.RemoveAt ((int) sourceIndexPath.Item); + Numbers.Insert ((int) destinationIndexPath.Item, item); } #endregion } diff --git a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionView.cs b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionView.cs index c8e8c478d..3e1ef1fab 100644 --- a/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionView.cs +++ b/ios9/CollectionView/CollectionView/CollectionLayouts/WaterfallCollectionView.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using Foundation; @@ -13,12 +13,12 @@ namespace CollectionView { /// Ported from http://nshint.io/blog/2015/07/16/uicollectionviews-now-have-easy-reordering/ to /// Xamarin.iOS by Kevin Mullins. /// </remarks> - [Register("WaterfallCollectionView")] + [Register ("WaterfallCollectionView")] public class WaterfallCollectionView : UICollectionView { #region Computed Properties public WaterfallCollectionSource Source { get { - return (WaterfallCollectionSource)DataSource; + return (WaterfallCollectionSource) DataSource; } } #endregion diff --git a/ios9/CollectionView/CollectionView/FirstViewController.cs b/ios9/CollectionView/CollectionView/FirstViewController.cs index 9f8ecc7bd..e24341749 100644 --- a/ios9/CollectionView/CollectionView/FirstViewController.cs +++ b/ios9/CollectionView/CollectionView/FirstViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; diff --git a/ios9/CollectionView/CollectionView/Main.cs b/ios9/CollectionView/CollectionView/Main.cs index f85c93a66..3a8d98a23 100644 --- a/ios9/CollectionView/CollectionView/Main.cs +++ b/ios9/CollectionView/CollectionView/Main.cs @@ -1,9 +1,9 @@ -using UIKit; +using UIKit; namespace CollectionView { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/CollectionView/CollectionView/SecondViewController.cs b/ios9/CollectionView/CollectionView/SecondViewController.cs index c21894d90..2eb605a7e 100644 --- a/ios9/CollectionView/CollectionView/SecondViewController.cs +++ b/ios9/CollectionView/CollectionView/SecondViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; diff --git a/ios9/CollectionView/CollectionView/ThirdViewController.cs b/ios9/CollectionView/CollectionView/ThirdViewController.cs index e98227c95..0ad9a906a 100644 --- a/ios9/CollectionView/CollectionView/ThirdViewController.cs +++ b/ios9/CollectionView/CollectionView/ThirdViewController.cs @@ -49,7 +49,7 @@ public override void ViewDidLoad () }); // Add the custom recognizer to the collection view - CollectionView.AddGestureRecognizer(longPressGesture); + CollectionView.AddGestureRecognizer (longPressGesture); } public override void AwakeFromNib () @@ -61,7 +61,7 @@ public override void AwakeFromNib () // Wireup events waterfallLayout.SizeForItem += (collectionView, layout, indexPath) => { var collection = collectionView as WaterfallCollectionView; - return new CGSize ((View.Bounds.Width - 40) / 3, collection.Source.Heights [(int)indexPath.Item]); + return new CGSize ((View.Bounds.Width - 40) / 3, collection.Source.Heights [(int) indexPath.Item]); }; // Attach the custom layout to the collection diff --git a/ios9/Emporium/Common/AppConfiguration.cs b/ios9/Emporium/Common/AppConfiguration.cs index e8e484c4e..8b7d15d02 100644 --- a/ios9/Emporium/Common/AppConfiguration.cs +++ b/ios9/Emporium/Common/AppConfiguration.cs @@ -1,7 +1,6 @@ using Foundation; -namespace Emporium -{ +namespace Emporium { /// <summary> /// The value of the EmporiumBundlePrefix setting is /// written to the Info.plist file of every project of the @@ -14,19 +13,16 @@ namespace Emporium /// an interpolated string to insert the user-defined value of EmporiumBundlePrefix /// into several static string constants below. /// </summary> - public static class AppConfiguration - { - public static class Bundle - { + public static class AppConfiguration { + public static class Bundle { public static string Prefix { get { - return (NSString)NSBundle.MainBundle.ObjectForInfoDictionary ("EmporiumBundlePrefix"); + return (NSString) NSBundle.MainBundle.ObjectForInfoDictionary ("EmporiumBundlePrefix"); } } } - public static class UserActivity - { + public static class UserActivity { public static string Payment { get { return string.Format ("{0}.payment", Bundle.Prefix); @@ -34,8 +30,7 @@ public static string Payment { } } - public static class Merchant - { + public static class Merchant { public static string Identififer { get { return string.Format ("merchant.{0}", Bundle.Prefix); @@ -43,4 +38,4 @@ public static string Identififer { } } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/Common/Product.cs b/ios9/Emporium/Common/Product.cs index 9aa5d6e8b..48388a34a 100644 --- a/ios9/Emporium/Common/Product.cs +++ b/ios9/Emporium/Common/Product.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; -namespace Emporium -{ - public class Product : NSObject - { +namespace Emporium { + public class Product : NSObject { public string Name { get; set; } new public string Description { get; set; } public string Price { get; set; } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/Common/ProductContainer.cs b/ios9/Emporium/Common/ProductContainer.cs index b818265f8..8dababf9b 100644 --- a/ios9/Emporium/Common/ProductContainer.cs +++ b/ios9/Emporium/Common/ProductContainer.cs @@ -1,12 +1,10 @@ -using Foundation; +using Foundation; -namespace Emporium -{ - public class ProductContainer : DictionaryContainer - { - static readonly NSString NameKey = (NSString)"name"; - static readonly NSString DescriptionKey = (NSString)"description"; - static readonly NSString PriceKey = (NSString)"price"; +namespace Emporium { + public class ProductContainer : DictionaryContainer { + static readonly NSString NameKey = (NSString) "name"; + static readonly NSString DescriptionKey = (NSString) "description"; + static readonly NSString PriceKey = (NSString) "price"; public string Name { get { diff --git a/ios9/Emporium/Common/Properties/AssemblyInfo.cs b/ios9/Emporium/Common/Properties/AssemblyInfo.cs index 456fb09d5..79fc8286b 100644 --- a/ios9/Emporium/Common/Properties/AssemblyInfo.cs +++ b/ios9/Emporium/Common/Properties/AssemblyInfo.cs @@ -1,4 +1,4 @@ -using System.Reflection; +using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. diff --git a/ios9/Emporium/Emporium/AppDelegate.cs b/ios9/Emporium/Emporium/AppDelegate.cs index 1cbeba501..65e57006c 100644 --- a/ios9/Emporium/Emporium/AppDelegate.cs +++ b/ios9/Emporium/Emporium/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace Emporium -{ +namespace Emporium { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } UINavigationController RootViewController { @@ -27,7 +25,7 @@ public override bool ContinueUserActivity (UIApplication application, NSUserActi Product product = productContainer.Product; // Firstly, we'll create a product detail page. We can instantiate it from our storyboard... - var viewController = (ProductTableViewController)RootViewController?.Storyboard?.InstantiateViewController ("ProductTableViewController"); + var viewController = (ProductTableViewController) RootViewController?.Storyboard?.InstantiateViewController ("ProductTableViewController"); // Manually set the product we want to display. if (viewController != null) { @@ -46,4 +44,4 @@ public override bool ContinueUserActivity (UIApplication application, NSUserActi return true; } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/Emporium/CatalogCollectionViewController.cs b/ios9/Emporium/Emporium/CatalogCollectionViewController.cs index 68056f459..651b816e0 100644 --- a/ios9/Emporium/Emporium/CatalogCollectionViewController.cs +++ b/ios9/Emporium/Emporium/CatalogCollectionViewController.cs @@ -1,29 +1,27 @@ -using System; +using System; using UIKit; using Foundation; -namespace Emporium -{ +namespace Emporium { [Register ("CatalogCollectionViewController")] - public class CatalogCollectionViewController : UICollectionViewController - { - static readonly NSString reuseIdentifier = (NSString)"ProductCell"; - static readonly NSString segueIdentifier = (NSString)"ProductDetailSegue"; + public class CatalogCollectionViewController : UICollectionViewController { + static readonly NSString reuseIdentifier = (NSString) "ProductCell"; + static readonly NSString segueIdentifier = (NSString) "ProductDetailSegue"; - Product[] products; + Product [] products; - Product[] Products { + Product [] Products { get { if (products == null) { // Populate the products array from a plist. NSUrl productsURL = NSBundle.MainBundle.GetUrlForResource ("ProductsList", "plist"); var productArr = NSArray.FromFile (productsURL.Path); - products = new Product[(int)productArr.Count]; + products = new Product [(int) productArr.Count]; for (nuint i = 0; i < productArr.Count; i++) { var container = new ProductContainer (productArr.GetItem<NSDictionary> (i)); - products [(int)i] = container.Product; + products [(int) i] = container.Product; } } @@ -43,7 +41,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (indexPaths == null || indexPaths.Length == 0) return; - var viewController = (ProductTableViewController)segue.DestinationViewController; + var viewController = (ProductTableViewController) segue.DestinationViewController; viewController.Product = products [indexPaths [0].Row]; } else { base.PrepareForSegue (segue, sender); @@ -59,7 +57,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (ProductCell)collectionView.DequeueReusableCell (reuseIdentifier, indexPath); + var cell = (ProductCell) collectionView.DequeueReusableCell (reuseIdentifier, indexPath); ConfigureCell (cell, Products [indexPath.Row]); return cell; @@ -79,4 +77,4 @@ static void ConfigureCell (ProductCell cell, Product product) cell.SubtitleLabel.Text = product.Description; } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/Emporium/ConfirmationViewController.cs b/ios9/Emporium/Emporium/ConfirmationViewController.cs index 2a926e52d..d107f26f6 100644 --- a/ios9/Emporium/Emporium/ConfirmationViewController.cs +++ b/ios9/Emporium/Emporium/ConfirmationViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using Foundation; -namespace Emporium -{ +namespace Emporium { [Register ("ConfirmationViewController")] - public class ConfirmationViewController : UIViewController - { + public class ConfirmationViewController : UIViewController { public string TransactionIdentifier { get; set; } [Outlet ("confirmationLabel")] @@ -24,4 +22,4 @@ public override void ViewWillAppear (bool animated) confirmationLabel.Text = TransactionIdentifier; } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/Emporium/Main.cs b/ios9/Emporium/Emporium/Main.cs index bd9371e6a..568baf468 100644 --- a/ios9/Emporium/Emporium/Main.cs +++ b/ios9/Emporium/Emporium/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace Emporium -{ - public class Application - { +namespace Emporium { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/Emporium/Emporium/ProductCell.cs b/ios9/Emporium/Emporium/ProductCell.cs index 2e00755fa..8b7f6cf8e 100644 --- a/ios9/Emporium/Emporium/ProductCell.cs +++ b/ios9/Emporium/Emporium/ProductCell.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; using Foundation; -namespace Emporium -{ +namespace Emporium { [Register ("ProductCell")] - public class ProductCell : UICollectionViewCell - { + public class ProductCell : UICollectionViewCell { [Outlet ("imageView")] public UIImageView ImageView { get; set; } @@ -25,4 +23,4 @@ public ProductCell (IntPtr handle) { } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/Emporium/ProductTableViewController.cs b/ios9/Emporium/Emporium/ProductTableViewController.cs index b995d80ca..0ec3bc28e 100644 --- a/ios9/Emporium/Emporium/ProductTableViewController.cs +++ b/ios9/Emporium/Emporium/ProductTableViewController.cs @@ -1,18 +1,16 @@ -using System; +using System; using UIKit; using Foundation; using PassKit; using System.Collections.Generic; -namespace Emporium -{ +namespace Emporium { [Register ("ProductTableViewController")] - public class ProductTableViewController : UITableViewController, IPKPaymentAuthorizationViewControllerDelegate - { - static readonly NSString confirmationSegue = (NSString)"ConfirmationSegue"; + public class ProductTableViewController : UITableViewController, IPKPaymentAuthorizationViewControllerDelegate { + static readonly NSString confirmationSegue = (NSString) "ConfirmationSegue"; - readonly NSString[] supportedNetworks = { + readonly NSString [] supportedNetworks = { PKPaymentNetwork.Amex, PKPaymentNetwork.Discover, PKPaymentNetwork.MasterCard, @@ -46,7 +44,7 @@ public ProductTableViewController (IntPtr handle) public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == confirmationSegue) { - var viewController = (ConfirmationViewController)segue.DestinationViewController; + var viewController = (ConfirmationViewController) segue.DestinationViewController; viewController.TransactionIdentifier = paymentToken.TransactionIdentifier; } else { base.PrepareForSegue (segue, sender); @@ -122,7 +120,7 @@ public void ApplyPayButtonClicked () } - PKPaymentSummaryItem[] MakeSummaryItems (bool requiresInternationalSurcharge) + PKPaymentSummaryItem [] MakeSummaryItems (bool requiresInternationalSurcharge) { var items = new List<PKPaymentSummaryItem> (); @@ -179,7 +177,7 @@ void DidSelectShippingContact (PKPaymentAuthorizationViewController controller, var address = contact.PostalAddress; var requiresInternationalSurcharge = address.Country != "United States"; - PKPaymentSummaryItem[] summaryItems = MakeSummaryItems (requiresInternationalSurcharge); + PKPaymentSummaryItem [] summaryItems = MakeSummaryItems (requiresInternationalSurcharge); completion (PKPaymentAuthorizationStatus.Success, new [] { shipping }, summaryItems); } @@ -218,4 +216,4 @@ void ShowAuthorizationAlert () PresentViewController (alert, true, null); } } -} \ No newline at end of file +} diff --git a/ios9/Emporium/EmporiumWatchKitExtension/InterfaceController.cs b/ios9/Emporium/EmporiumWatchKitExtension/InterfaceController.cs index ccf5f1f3c..ded7fe29a 100644 --- a/ios9/Emporium/EmporiumWatchKitExtension/InterfaceController.cs +++ b/ios9/Emporium/EmporiumWatchKitExtension/InterfaceController.cs @@ -1,14 +1,12 @@ -using System; +using System; using WatchKit; using Foundation; using Emporium; -namespace EmporiumWatchKitExtension -{ - public partial class InterfaceController : WKInterfaceController - { +namespace EmporiumWatchKitExtension { + public partial class InterfaceController : WKInterfaceController { [Outlet ("statusLabel")] public WKInterfaceLabel StatusLabel { get; set; } @@ -39,4 +37,4 @@ void MakePaymentPressed () StatusLabel.SetText ("Use handoff to pay!"); } } -} \ No newline at end of file +} diff --git a/ios9/FilterDemoApp/AUv3Host/AppDelegate.cs b/ios9/FilterDemoApp/AUv3Host/AppDelegate.cs index 7d046ce75..e335d1f36 100644 --- a/ios9/FilterDemoApp/AUv3Host/AppDelegate.cs +++ b/ios9/FilterDemoApp/AUv3Host/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace AUv3Host { diff --git a/ios9/FilterDemoApp/AUv3Host/Main.cs b/ios9/FilterDemoApp/AUv3Host/Main.cs index 045c6b556..5b69f5b44 100644 --- a/ios9/FilterDemoApp/AUv3Host/Main.cs +++ b/ios9/FilterDemoApp/AUv3Host/Main.cs @@ -1,9 +1,9 @@ -using UIKit; +using UIKit; namespace AUv3Host { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/FilterDemoApp/AUv3Host/ViewController.cs b/ios9/FilterDemoApp/AUv3Host/ViewController.cs index 859fbc275..81ecaed53 100644 --- a/ios9/FilterDemoApp/AUv3Host/ViewController.cs +++ b/ios9/FilterDemoApp/AUv3Host/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using AVFoundation; using Foundation; diff --git a/ios9/FilterDemoApp/FilterDemoApp/AppDelegate.cs b/ios9/FilterDemoApp/FilterDemoApp/AppDelegate.cs index 4db6d9f54..f7f9b430a 100644 --- a/ios9/FilterDemoApp/FilterDemoApp/AppDelegate.cs +++ b/ios9/FilterDemoApp/FilterDemoApp/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace FilterDemoApp { diff --git a/ios9/FilterDemoApp/FilterDemoApp/Main.cs b/ios9/FilterDemoApp/FilterDemoApp/Main.cs index ef98d8d99..86e671f0a 100644 --- a/ios9/FilterDemoApp/FilterDemoApp/Main.cs +++ b/ios9/FilterDemoApp/FilterDemoApp/Main.cs @@ -1,9 +1,10 @@ -using UIKit; +using UIKit; namespace FilterDemoApp { public class Application { // This is the main entry point of the application. - static void Main (string[] args) { + static void Main (string [] args) + { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); diff --git a/ios9/FilterDemoApp/FilterDemoApp/ViewController.cs b/ios9/FilterDemoApp/FilterDemoApp/ViewController.cs index e04f62098..21b00b302 100644 --- a/ios9/FilterDemoApp/FilterDemoApp/ViewController.cs +++ b/ios9/FilterDemoApp/FilterDemoApp/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using AudioUnit; using CoreFoundation; @@ -25,13 +25,13 @@ public override void ViewDidLoad () var componentDescription = new AudioComponentDescription { ComponentType = AudioComponentType.Effect, ComponentSubType = 0x666c7472, - ComponentManufacturer = (AudioComponentManufacturerType)0x44656d6f, + ComponentManufacturer = (AudioComponentManufacturerType) 0x44656d6f, ComponentFlags = 0, ComponentFlagsMask = 0 }; AUAudioUnit.RegisterSubclass ( - new Class (typeof(AUv3FilterDemo)), + new Class (typeof (AUv3FilterDemo)), componentDescription, "Local FilterDemo", int.MaxValue @@ -106,8 +106,8 @@ void ConnectParametersToControls () var audioUnit = playEngine.AudioUnit as AUv3FilterDemo; filterDemoViewController.AudioUnit = audioUnit; - cutoffParameter = (AUParameter)parameterTree.ValueForKey ((NSString)"cutoff"); - resonanceParameter = (AUParameter)parameterTree.ValueForKey ((NSString)"resonance"); + cutoffParameter = (AUParameter) parameterTree.ValueForKey ((NSString) "cutoff"); + resonanceParameter = (AUParameter) parameterTree.ValueForKey ((NSString) "resonance"); parameterTree.CreateTokenByAddingParameterObserver ((address, value) => DispatchQueue.MainQueue.DispatchAsync (() => { if (address == cutoffParameter.Address) diff --git a/ios9/FilterDemoApp/Framework/AUv3FilterDemo.cs b/ios9/FilterDemoApp/Framework/AUv3FilterDemo.cs index 7bb99cac9..bfe0266eb 100644 --- a/ios9/FilterDemoApp/Framework/AUv3FilterDemo.cs +++ b/ios9/FilterDemoApp/Framework/AUv3FilterDemo.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using AudioToolbox; @@ -46,7 +46,7 @@ public AUv3FilterDemo (AudioComponentDescription description, AudioComponentInst { var defaultFormat = new AVAudioFormat (44100.0, 2); - Kernel.Init ((int)defaultFormat.ChannelCount, defaultFormat.SampleRate); + Kernel.Init ((int) defaultFormat.ChannelCount, defaultFormat.SampleRate); AUParameter cutoffParam = AUParameterTree.CreateParameter ( "cutoff", "Cutoff", 0, 12, 2000, @@ -62,8 +62,8 @@ public AUv3FilterDemo (AudioComponentDescription description, AudioComponentInst cutoffParam.Value = 400f; resonanceParam.Value = -5.0f; - Kernel.SetParameter ((ulong)FilterParam.Cutoff, cutoffParam.Value); - Kernel.SetParameter ((ulong)FilterParam.Resonance, resonanceParam.Value); + Kernel.SetParameter ((ulong) FilterParam.Cutoff, cutoffParam.Value); + Kernel.SetParameter ((ulong) FilterParam.Resonance, resonanceParam.Value); ParameterTree = AUParameterTree.CreateTree ( new [] { @@ -83,14 +83,14 @@ public AUv3FilterDemo (AudioComponentDescription description, AudioComponentInst var filterKernel = Kernel; ParameterTree.ImplementorValueObserver = (param, value) => filterKernel.SetParameter (param.Address, value); - ParameterTree.ImplementorValueProvider = param => filterKernel.GetParameter ((nuint)param.Address); + ParameterTree.ImplementorValueProvider = param => filterKernel.GetParameter ((nuint) param.Address); ParameterTree.ImplementorStringFromValueCallback = (AUParameter param, ref float? value) => { switch (param.Address) { - case (ulong)FilterParam.Cutoff: - case (ulong)FilterParam.Resonance: - return (NSString)param.Value.ToString (); + case (ulong) FilterParam.Cutoff: + case (ulong) FilterParam.Resonance: + return (NSString) param.Value.ToString (); default: - return (NSString)"?"; + return (NSString) "?"; } }; @@ -104,21 +104,21 @@ public override bool AllocateRenderResources (out NSError outError) if (outputBus.Format.ChannelCount != inputBus.Bus.Format.ChannelCount) { if (outError != null) - outError = NSError.FromDomain (NSError.OsStatusErrorDomain, (int)AudioUnitStatus.FailedInitialization); + outError = NSError.FromDomain (NSError.OsStatusErrorDomain, (int) AudioUnitStatus.FailedInitialization); return false; } inputBus.AllocateRenderResources (MaximumFramesToRender); - Kernel.Init ((int)outputBus.Format.ChannelCount, outputBus.Format.SampleRate); + Kernel.Init ((int) outputBus.Format.ChannelCount, outputBus.Format.SampleRate); Kernel.Reset (); - var scheduleParameter = ScheduleParameterBlock; + var scheduleParameter = ScheduleParameterBlock; var rampTime = 0.02 * outputBus.Format.SampleRate; ParameterTree.ImplementorValueObserver = (param, val) => - scheduleParameter (AUEventSampleTime.Immediate, (uint)rampTime, param.Address, val); + scheduleParameter (AUEventSampleTime.Immediate, (uint) rampTime, param.Address, val); return true; } @@ -135,20 +135,20 @@ public override void DeallocateRenderResources () public AudioUnitStatus InternalRenderBlockProc (ref AudioUnitRenderActionFlags actionFlags, ref AudioTimeStamp timestamp, uint frameCount, nint outputBusNumber, AudioBuffers outputData, AURenderEventEnumerator realtimeEventListHead, AURenderPullInputBlock pullInputBlock) { - var transportStateFlags = (AUHostTransportStateFlags)0; + var transportStateFlags = (AUHostTransportStateFlags) 0; double currentSamplePosition = 0; double cycleStartBeatPosition = 0; double cycleEndBeatPosition = 0; var callBack = TransportStateBlock; - if(callBack != null) + if (callBack != null) callBack (ref transportStateFlags, ref currentSamplePosition, ref cycleStartBeatPosition, ref cycleEndBeatPosition); var state = Kernel; var input = inputBus; - var pullFlags = (AudioUnitRenderActionFlags)0; + var pullFlags = (AudioUnitRenderActionFlags) 0; AudioUnitStatus err = input.PullInput (ref pullFlags, timestamp, frameCount, 0, pullInputBlock); if (err != AudioUnitStatus.NoError) return err; @@ -161,12 +161,12 @@ public AudioUnitStatus InternalRenderBlockProc (ref AudioUnitRenderActionFlags a } state.SetBuffers (inAudioBufferList, outputData); - state.ProcessWithEvents (timestamp, (int)frameCount, realtimeEventListHead); + state.ProcessWithEvents (timestamp, (int) frameCount, realtimeEventListHead); return AudioUnitStatus.NoError; } - public double[] GetMagnitudes (double[] frequencies) + public double [] GetMagnitudes (double [] frequencies) { var coefficients = new FilterDSPKernel.BiquadCoefficients (); coefficients.CalculateLopassParams (Kernel.CutoffRamper.Goal, Kernel.ResonanceRamper.Goal); diff --git a/ios9/FilterDemoApp/Framework/BufferedAudioBus.cs b/ios9/FilterDemoApp/Framework/BufferedAudioBus.cs index c72693222..5d08ed592 100644 --- a/ios9/FilterDemoApp/Framework/BufferedAudioBus.cs +++ b/ios9/FilterDemoApp/Framework/BufferedAudioBus.cs @@ -1,4 +1,4 @@ -using AudioToolbox; +using AudioToolbox; using AudioUnit; using AVFoundation; using Foundation; diff --git a/ios9/FilterDemoApp/Framework/BufferedInputBus.cs b/ios9/FilterDemoApp/Framework/BufferedInputBus.cs index 1c3518c49..f75ed125c 100644 --- a/ios9/FilterDemoApp/Framework/BufferedInputBus.cs +++ b/ios9/FilterDemoApp/Framework/BufferedInputBus.cs @@ -1,4 +1,4 @@ -using AudioUnit; +using AudioUnit; using AudioToolbox; namespace FilterDemoFramework { @@ -15,14 +15,14 @@ public AudioUnitStatus PullInput (ref AudioUnitRenderActionFlags actionFlags, Au void PrepareInputBufferList () { - uint byteSize = MaxFrames * sizeof(float); + uint byteSize = MaxFrames * sizeof (float); MutableAudioBufferList = new AudioBuffers (OriginalAudioBufferList.Count); for (int i = 0; i < OriginalAudioBufferList.Count; ++i) { - MutableAudioBufferList[i] = new AudioBuffer { + MutableAudioBufferList [i] = new AudioBuffer { Data = OriginalAudioBufferList [i].Data, - DataByteSize = (int)byteSize, + DataByteSize = (int) byteSize, NumberChannels = OriginalAudioBufferList [i].NumberChannels }; } diff --git a/ios9/FilterDemoApp/Framework/DSPKernel.cs b/ios9/FilterDemoApp/Framework/DSPKernel.cs index 1b1eb60c3..2537c241c 100644 --- a/ios9/FilterDemoApp/Framework/DSPKernel.cs +++ b/ios9/FilterDemoApp/Framework/DSPKernel.cs @@ -1,4 +1,4 @@ -using System; +using System; using AudioToolbox; using AudioUnit; @@ -12,17 +12,17 @@ void HandleOneEvent (AURenderEvent theEvent) case AURenderEventType.ParameterRamp: AUParameterEvent paramEvent = theEvent.Parameter; - StartRamp (paramEvent.ParameterAddress, paramEvent.Value, (int)paramEvent.RampDurationSampleFrames); + StartRamp (paramEvent.ParameterAddress, paramEvent.Value, (int) paramEvent.RampDurationSampleFrames); break; case AURenderEventType.Midi: throw new NotImplementedException (); } } -// There are two APIs for getting all of the events. -// - The "raw" pointers from the linked list -// - The EnumeratorCurrentEvents wrapper -//#define USE_RAW_EVENT_ENUMERATION + // There are two APIs for getting all of the events. + // - The "raw" pointers from the linked list + // - The EnumeratorCurrentEvents wrapper + //#define USE_RAW_EVENT_ENUMERATION #if USE_RAW_EVENT_ENUMERATION unsafe void PerformAllSimultaneousEvents (nint now, AURenderEvent** theEvent) { @@ -59,7 +59,7 @@ public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, #else public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, AURenderEventEnumerator events) { - var now = (nint)timestamp.SampleTime; + var now = (nint) timestamp.SampleTime; int framesRemaining = frameCount; while (framesRemaining > 0) { if (events.IsAtEnd) { @@ -68,7 +68,7 @@ public unsafe void ProcessWithEvents (AudioTimeStamp timestamp, int frameCount, return; } - var framesThisSegment = (int)(events.Current.Head.EventSampleTime - now); + var framesThisSegment = (int) (events.Current.Head.EventSampleTime - now); if (framesThisSegment > 0) { int bufferOffset = frameCount - framesRemaining; diff --git a/ios9/FilterDemoApp/Framework/FilterDSPKernel.cs b/ios9/FilterDemoApp/Framework/FilterDSPKernel.cs index 5c32a4698..5489acaca 100644 --- a/ios9/FilterDemoApp/Framework/FilterDSPKernel.cs +++ b/ios9/FilterDemoApp/Framework/FilterDSPKernel.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using AudioToolbox; @@ -9,7 +9,7 @@ public enum FilterParam { } public static class Extensions { - public static float ConvertBadValuesToZero (this float x) + public static float ConvertBadValuesToZero (this float x) { var absx = Math.Abs (x); return (absx > 1e-15 && absx < 1e15) ? x : 0f; @@ -63,11 +63,11 @@ public class BiquadCoefficients { public void CalculateLopassParams (float frequency, float resonance) { - var r = (float)Math.Pow (10, 0.05 * -resonance); + var r = (float) Math.Pow (10, 0.05 * -resonance); - float k = 0.5f * r * (float)Math.Sin (Math.PI * frequency); + float k = 0.5f * r * (float) Math.Sin (Math.PI * frequency); float c1 = (1.0f - k) / (1.0f + k); - float c2 = (1.0f + c1) * (float)Math.Cos (Math.PI * frequency); + float c2 = (1.0f + c1) * (float) Math.Cos (Math.PI * frequency); float c3 = (1.0f + c1 - c2) * 0.25f; B0 = c3; @@ -99,7 +99,7 @@ public double GetMagnitude (double inFreq) public ParameterRamper CutoffRamper = new ParameterRamper (400f / 44100f); public ParameterRamper ResonanceRamper = new ParameterRamper (20f); - FilterState[] channelStates; + FilterState [] channelStates; readonly BiquadCoefficients coeffs = new BiquadCoefficients (); float sampleRate = 44100f; @@ -115,7 +115,7 @@ public void Init (int channelCount, double inSampleRate) .Select (i => new FilterState ()) .ToArray (); - sampleRate = (float)inSampleRate; + sampleRate = (float) inSampleRate; nyquist = 0.5f * sampleRate; inverseNyquist = 1f / nyquist; } @@ -126,13 +126,13 @@ public void Reset () state.Clear (); } - public void SetParameter (ulong address, float value) + public void SetParameter (ulong address, float value) { switch (address) { - case (ulong)FilterParam.Cutoff: + case (ulong) FilterParam.Cutoff: CutoffRamper.Set ((value * inverseNyquist).Clamp (0f, 0.99f)); break; - case (ulong)FilterParam.Resonance: + case (ulong) FilterParam.Resonance: ResonanceRamper.Set (value.Clamp (-20f, 20f)); break; } @@ -141,9 +141,9 @@ public void SetParameter (ulong address, float value) public float GetParameter (nuint address) { switch (address) { - case (ulong)FilterParam.Cutoff: + case (ulong) FilterParam.Cutoff: return CutoffRamper.Goal * nyquist; - case (ulong)FilterParam.Resonance: + case (ulong) FilterParam.Resonance: return ResonanceRamper.Goal; default: return 0.0f; @@ -153,10 +153,10 @@ public float GetParameter (nuint address) public override void StartRamp (ulong address, float value, int duration) { switch (address) { - case (ulong)FilterParam.Cutoff: + case (ulong) FilterParam.Cutoff: CutoffRamper.StartRamp ((value * inverseNyquist).Clamp (0f, 0.99f), duration); break; - case (ulong)FilterParam.Resonance: + case (ulong) FilterParam.Resonance: ResonanceRamper.StartRamp (value.Clamp (-20f, 20f), duration); break; } @@ -183,8 +183,8 @@ public override void Process (int frameCount, int bufferOffset) FilterState state = channelStates [channel]; unsafe { - float * In = (float *)inBufferList [channel].Data + frameOffset; - float * Out = (float *)outBufferList [channel].Data + frameOffset; + float* In = (float*) inBufferList [channel].Data + frameOffset; + float* Out = (float*) outBufferList [channel].Data + frameOffset; float x0 = *In; float y0 = (coeffs.B0 * x0) + (coeffs.B1 * state.X1) + (coeffs.B2 * state.X2) - diff --git a/ios9/FilterDemoApp/Framework/FilterDemoViewController.cs b/ios9/FilterDemoApp/Framework/FilterDemoViewController.cs index cf2415d35..412c5df69 100644 --- a/ios9/FilterDemoApp/Framework/FilterDemoViewController.cs +++ b/ios9/FilterDemoApp/Framework/FilterDemoViewController.cs @@ -8,8 +8,8 @@ namespace FilterDemoFramework { public partial class FilterDemoViewController : AUViewController, IFilterViewDelegate, IAUAudioUnitFactory { - static readonly NSString cutoffKey = (NSString)"cutoff"; - static readonly NSString resonanceKey = (NSString)"resonance"; + static readonly NSString cutoffKey = (NSString) "cutoff"; + static readonly NSString resonanceKey = (NSString) "resonance"; AUParameter cutoffParameter; AUParameter resonanceParameter; @@ -29,8 +29,8 @@ public AUv3FilterDemo AudioUnit { } } - [Export("initWithCoder:")] - public FilterDemoViewController (NSCoder coder) : base(coder) + [Export ("initWithCoder:")] + public FilterDemoViewController (NSCoder coder) : base (coder) { } @@ -88,7 +88,7 @@ public AUAudioUnit CreateAudioUnit (AudioComponentDescription desc, out NSError return AudioUnit; } - [Export("beginRequestWithExtensionContext:")] + [Export ("beginRequestWithExtensionContext:")] public void BeginRequestWithExtensionContext (NSExtensionContext context) { } @@ -98,14 +98,14 @@ void ConnectViewWithAU () var au = AudioUnit; if (au == null) return; - + var paramTree = au.ParameterTree; if (paramTree == null) return; - cutoffParameter = (AUParameter)paramTree.ValueForKey (cutoffKey); - resonanceParameter = (AUParameter)paramTree.ValueForKey (resonanceKey); - + cutoffParameter = (AUParameter) paramTree.ValueForKey (cutoffKey); + resonanceParameter = (AUParameter) paramTree.ValueForKey (resonanceKey); + parameterObserverToken = paramTree.CreateTokenByAddingParameterObserver ((address, value) => DispatchQueue.MainQueue.DispatchAsync (() => { if (address == cutoffParameter.Address) { diff --git a/ios9/FilterDemoApp/Framework/FilterView.cs b/ios9/FilterDemoApp/Framework/FilterView.cs index 243faed45..1dd8148b6 100644 --- a/ios9/FilterDemoApp/Framework/FilterView.cs +++ b/ios9/FilterDemoApp/Framework/FilterView.cs @@ -27,15 +27,15 @@ public partial class FilterView : UIView { CAShapeLayer curveLayer; List<double> frequencies; - readonly List <CATextLayer> dbLabels = new List <CATextLayer> (); - readonly List <CATextLayer> frequencyLabels = new List<CATextLayer> (); - readonly List <CALayer> dbLines = new List <CALayer> (); - readonly List <CALayer> freqLines = new List<CALayer> (); - readonly List <CALayer> controls = new List<CALayer> (); + readonly List<CATextLayer> dbLabels = new List<CATextLayer> (); + readonly List<CATextLayer> frequencyLabels = new List<CATextLayer> (); + readonly List<CALayer> dbLines = new List<CALayer> (); + readonly List<CALayer> freqLines = new List<CALayer> (); + readonly List<CALayer> controls = new List<CALayer> (); readonly CALayer containerLayer = new CALayer (); readonly CALayer graphLayer = new CALayer (); - public IFilterViewDelegate Delegate { get; set;} + public IFilterViewDelegate Delegate { get; set; } float resonance; public float Resonance { @@ -158,16 +158,16 @@ public double [] GetFrequencyData () var width = graphLayer.Bounds.Width; var rightEdge = width + leftMargin; - var pixelRatio = (int)Math.Ceiling (width / maxNumberOfResponseFrequencies); + var pixelRatio = (int) Math.Ceiling (width / maxNumberOfResponseFrequencies); nfloat location = leftMargin; var locationsCount = maxNumberOfResponseFrequencies; if (pixelRatio <= 1) { pixelRatio = 1; - locationsCount = (int)width; + locationsCount = (int) width; } - frequencies = new List <double> (); + frequencies = new List<double> (); for (int i = 0; i < locationsCount; i++) { if (location > rightEdge) @@ -178,7 +178,7 @@ public double [] GetFrequencyData () if (frequencyTmp > DefaultMaxHertz) frequencyTmp = DefaultMaxHertz; - location += (nfloat)pixelRatio; + location += (nfloat) pixelRatio; frequencies.Add (frequencyTmp); } @@ -202,7 +202,7 @@ public void SetMagnitudes (double [] magnitudeData) float lastDbPos = 0f; float location = leftMargin; var frequencyCount = frequencies?.Count ?? 0; - var pixelRatio = (int)(Math.Ceiling (width / frequencyCount)); + var pixelRatio = (int) (Math.Ceiling (width / frequencyCount)); for (int i = 0; i < frequencyCount; i++) { var dbValue = 20 * Math.Log10 (magnitudeData [i]); @@ -213,7 +213,7 @@ public void SetMagnitudes (double [] magnitudeData) else if (dbValue > defaultGain) dbPos = GetLocationForDbValue (defaultGain); else - dbPos = GetLocationForDbValue ((float)dbValue); + dbPos = GetLocationForDbValue ((float) dbValue); if (Math.Abs (lastDbPos - dbPos) >= 0.1) bezierPath.AddLineToPoint (location, dbPos); @@ -222,7 +222,7 @@ public void SetMagnitudes (double [] magnitudeData) location += pixelRatio; if (location > width + graphLayer.Frame.X) { - location = (float)width + (float)graphLayer.Frame.X; + location = (float) width + (float) graphLayer.Frame.X; break; } } @@ -242,7 +242,7 @@ public float GetLocationForDbValue (float value) { var step = graphLayer.Frame.Height / (defaultGain * 2); var location = (value + defaultGain) * step; - return (float)(graphLayer.Frame.Height - location + bottomMargin); + return (float) (graphLayer.Frame.Height - location + bottomMargin); } float GetLocationForFrequencyValue (float value) @@ -250,13 +250,13 @@ float GetLocationForFrequencyValue (float value) var pixelIncrement = graphLayer.Frame.Width / gridLineCount; var number = value / DefaultMinHertz; var location = GetLogValue (number, logBase) * pixelIncrement; - return (float)Math.Floor (location + graphLayer.Frame.X) + 0.5f; + return (float) Math.Floor (location + graphLayer.Frame.X) + 0.5f; } float GetDbValue (nfloat location) { var step = graphLayer.Frame.Height / (defaultGain * 2); - return (float)(-(((location - bottomMargin) / step) - defaultGain)); + return (float) (-(((location - bottomMargin) / step) - defaultGain)); } void CreateDbLabelsAndLines () @@ -300,7 +300,7 @@ void CreateFrequencyLabelsAndLines () var scale = Layer.ContentsScale; for (int index = 0; index <= gridLineCount; index++) { - value = GetValue ((float)index); + value = GetValue ((float) index); var labelLayer = new CATextLayer { ForegroundColor = UIColor.FromWhiteAlpha (0.1f, 1f).CGColor, @@ -438,9 +438,9 @@ public void LayoutSublayersOfLayer (CALayer layer) containerLayer.Bounds = layer.Bounds; graphLayer.Bounds = new CGRect ( - leftMargin, - bottomMargin, - layer.Bounds.Width - leftMargin - rightMargin, + leftMargin, + bottomMargin, + layer.Bounds.Width - leftMargin - rightMargin, layer.Bounds.Height - bottomMargin - 10); UpdateDbLayers (); @@ -483,7 +483,7 @@ void UpdateFrequenciesAndResonance () var lastResonance = GetDbValue (editPoint.Y); if (Math.Abs (lastResonance - Resonance) > float.Epsilon) { Resonance = lastResonance; - if(del != null) + if (del != null) del.ResonanceChanged (this, Resonance); } } @@ -492,7 +492,7 @@ public override void TouchesBegan (NSSet touches, UIEvent evt) { base.TouchesBegan (touches, evt); - var pointOfTouch = ((UITouch)touches.FirstOrDefault ()).LocationInView (this); + var pointOfTouch = ((UITouch) touches.FirstOrDefault ()).LocationInView (this); pointOfTouch.Y += bottomMargin; if (graphLayer.Contains (pointOfTouch)) { @@ -521,14 +521,14 @@ float GetFrequencyValue (nfloat location) return GetValue (index); } - static float GetValue (nfloat gridIndex) + static float GetValue (nfloat gridIndex) { - return (float)(DefaultMinHertz * Math.Pow (logBase, gridIndex)); + return (float) (DefaultMinHertz * Math.Pow (logBase, gridIndex)); } static float GetLogValue (float number, float baseNum) { - return (float)(Math.Log (number) / Math.Log (baseNum)); + return (float) (Math.Log (number) / Math.Log (baseNum)); } static string GetString (float value) @@ -538,9 +538,9 @@ static string GetString (float value) if (value >= 1000) temp /= 1000; - temp = (float)Math.Floor (temp * 100 / 100); + temp = (float) Math.Floor (temp * 100 / 100); - bool tooSmall = Math.Abs ((float)Math.Floor (temp) - temp) < float.Epsilon; + bool tooSmall = Math.Abs ((float) Math.Floor (temp) - temp) < float.Epsilon; return tooSmall ? temp.ToString ("F1") : temp.ToString ("0.#"); } } diff --git a/ios9/FilterDemoApp/Framework/IFilterViewDelegate.cs b/ios9/FilterDemoApp/Framework/IFilterViewDelegate.cs index ba6000810..7abebc02a 100644 --- a/ios9/FilterDemoApp/Framework/IFilterViewDelegate.cs +++ b/ios9/FilterDemoApp/Framework/IFilterViewDelegate.cs @@ -1,5 +1,5 @@ -namespace FilterDemoFramework { - public interface IFilterViewDelegate { +namespace FilterDemoFramework { + public interface IFilterViewDelegate { void ResonanceChanged (FilterView filterView, float resonance); void FrequencyChanged (FilterView filterView, float frequency); diff --git a/ios9/FilterDemoApp/Framework/ParameterRamper.cs b/ios9/FilterDemoApp/Framework/ParameterRamper.cs index 0d60c142d..7a8cec8b2 100644 --- a/ios9/FilterDemoApp/Framework/ParameterRamper.cs +++ b/ios9/FilterDemoApp/Framework/ParameterRamper.cs @@ -1,4 +1,4 @@ -namespace FilterDemoFramework { +namespace FilterDemoFramework { public class ParameterRamper { float inverseSlope; int samplesRemaining; diff --git a/ios9/FilterDemoApp/Framework/SimplePlayEngine.cs b/ios9/FilterDemoApp/Framework/SimplePlayEngine.cs index 5de275dfe..6f85f0991 100644 --- a/ios9/FilterDemoApp/Framework/SimplePlayEngine.cs +++ b/ios9/FilterDemoApp/Framework/SimplePlayEngine.cs @@ -1,4 +1,4 @@ -using System; +using System; using AudioUnit; using AVFoundation; @@ -17,15 +17,15 @@ public class SimplePlayEngine { Action componentsFoundCallback; readonly DispatchQueue availableEffectsAccessQueue = new DispatchQueue ("SimplePlayEngine.availableEffectsAccessQueue", false); - AVAudioUnitComponent[] availableEffects = new AVAudioUnitComponent[0]; + AVAudioUnitComponent [] availableEffects = new AVAudioUnitComponent [0]; public AUAudioUnit AudioUnit { get; private set; } - public AUAudioUnitPreset[] PresetList { get; private set; } + public AUAudioUnitPreset [] PresetList { get; private set; } public AVAudioUnitComponent [] AvailableEffects { get { - AVAudioUnitComponent[] result = null; + AVAudioUnitComponent [] result = null; availableEffectsAccessQueue.DispatchSync (() => { result = availableEffects; @@ -59,7 +59,7 @@ public SimplePlayEngine (Action componentsFoundCallback = null) var error = AVAudioSession.SharedInstance ().SetCategory (AVAudioSessionCategory.Playback); if (error != null) - throw new NSErrorException(error); + throw new NSErrorException (error); AUAudioUnit.Notifications.ObserveAudioComponentInstanceInvalidation ((sender, e) => { var crashedAU = e.Notification.Object as AUAudioUnit; @@ -119,7 +119,7 @@ public bool TogglePlay () ScheduleLoop (); NSError error; - if(!engine.StartAndReturnError (out error)) + if (!engine.StartAndReturnError (out error)) Console.WriteLine (error.LocalizedDescription); player.Play (); @@ -137,8 +137,8 @@ void ScheduleLoop () player.ScheduleFile (file, null, () => stateChangeQueue.DispatchAsync (() => { - if (isPlaying) - ScheduleLoop (); + if (isPlaying) + ScheduleLoop (); }) ); } @@ -156,7 +156,7 @@ public void SelectEffectComponent (AVAudioUnitComponent component, Action comple { AudioComponentDescription? desc = (component != null) ? component.AudioComponentDescription - : default(AudioComponentDescription?); + : default (AudioComponentDescription?); SelectEffectWithComponentDescription (desc, completionHandler); } @@ -176,7 +176,7 @@ public void SelectEffectWithComponentDescription (AudioComponentDescription? com effect = null; AudioUnit = null; - PresetList = new AUAudioUnitPreset[0]; + PresetList = new AUAudioUnitPreset [0]; } if (componentDescription.HasValue) { @@ -195,7 +195,7 @@ public void SelectEffectWithComponentDescription (AudioComponentDescription? com engine.Connect (avAudioUnitEffect, engine.MainMixerNode, file.ProcessingFormat); AudioUnit = avAudioUnitEffect.AUAudioUnit; - PresetList = avAudioUnitEffect.AUAudioUnit.FactoryPresets ?? new AUAudioUnitPreset[0]; + PresetList = avAudioUnitEffect.AUAudioUnit.FactoryPresets ?? new AUAudioUnitPreset [0]; Done (completionHandler); }); } else { diff --git a/ios9/FourInARow/FourInARow/AppDelegate.cs b/ios9/FourInARow/FourInARow/AppDelegate.cs index 6729f6813..4ec3dbb63 100644 --- a/ios9/FourInARow/FourInARow/AppDelegate.cs +++ b/ios9/FourInARow/FourInARow/AppDelegate.cs @@ -11,4 +11,4 @@ public class AppDelegate : UIApplicationDelegate { // Main.storyboard is automagically loaded since it is specified // in the Info.plist -> <key>UIMainStoryboardFile~ipad</key> } -} \ No newline at end of file +} diff --git a/ios9/FourInARow/FourInARow/Board.cs b/ios9/FourInARow/FourInARow/Board.cs index 134ec730c..55f2a33b9 100644 --- a/ios9/FourInARow/FourInARow/Board.cs +++ b/ios9/FourInARow/FourInARow/Board.cs @@ -11,7 +11,7 @@ public class Board : NSObject, IGKGameModel { public const int Width = 7; public const int Height = 6; - public Chip[] Cells { get; private set; } + public Chip [] Cells { get; private set; } public Player CurrentPlayer { get; set; } @@ -50,7 +50,7 @@ public void AddChipInColumn (Chip chip, int column) SetChipInColumnRow (chip, column, row); } - public IGKGameModelPlayer[] GetPlayers () + public IGKGameModelPlayer [] GetPlayers () { return Player.AllPlayers; } @@ -69,12 +69,12 @@ public NSObject Copy (NSZone zone) public void SetGameModel (IGKGameModel gameModel) { - var board = (Board)gameModel; + var board = (Board) gameModel; UpdateChipsFromBoard (board); CurrentPlayer = board.CurrentPlayer; } - public IGKGameModelUpdate[] GetGameModelUpdates (IGKGameModelPlayer player) + public IGKGameModelUpdate [] GetGameModelUpdates (IGKGameModelPlayer player) { var moves = new List<Move> (); @@ -88,7 +88,7 @@ public IGKGameModelUpdate[] GetGameModelUpdates (IGKGameModelPlayer player) public void ApplyGameModelUpdate (IGKGameModelUpdate gameModelUpdate) { - AddChipInColumn (CurrentPlayer.Chip, ((Move)gameModelUpdate).Column); + AddChipInColumn (CurrentPlayer.Chip, ((Move) gameModelUpdate).Column); CurrentPlayer = CurrentPlayer.Opponent; } @@ -116,7 +116,7 @@ bool IsLoss (Player player) return IsWin (player.Opponent); } - int[] RunCountsForPlayer (Player player) + int [] RunCountsForPlayer (Player player) { var chip = player.Chip; var counts = new List<int> (); @@ -220,4 +220,4 @@ int NextEmptySlotInColumn (int column) return -1; } } -} \ No newline at end of file +} diff --git a/ios9/FourInARow/FourInARow/Main.cs b/ios9/FourInARow/FourInARow/Main.cs index 4fc659162..1b6760e09 100644 --- a/ios9/FourInARow/FourInARow/Main.cs +++ b/ios9/FourInARow/FourInARow/Main.cs @@ -3,7 +3,7 @@ namespace FourInARow { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/FourInARow/FourInARow/Move.cs b/ios9/FourInARow/FourInARow/Move.cs index a0325d033..5704404b6 100644 --- a/ios9/FourInARow/FourInARow/Move.cs +++ b/ios9/FourInARow/FourInARow/Move.cs @@ -20,4 +20,4 @@ public static Move MoveInColumn (int column) return new Move (column); } } -} \ No newline at end of file +} diff --git a/ios9/FourInARow/FourInARow/Player.cs b/ios9/FourInARow/FourInARow/Player.cs index 08d06e3a9..3f15215ba 100644 --- a/ios9/FourInARow/FourInARow/Player.cs +++ b/ios9/FourInARow/FourInARow/Player.cs @@ -28,7 +28,7 @@ public static Player BlackPlayer { public int PlayerID { [Export ("playerId")] get { - return (int)Chip; + return (int) Chip; } } @@ -60,7 +60,7 @@ public string Name { } } - public Player Opponent { + public Player Opponent { get { switch (Chip) { case Chip.Red: @@ -73,8 +73,8 @@ public Player Opponent { } } - static Player[] allPlayers; - public static Player[] AllPlayers { + static Player [] allPlayers; + public static Player [] AllPlayers { get { allPlayers = allPlayers ?? new [] { new Player (Chip.Red), @@ -91,7 +91,7 @@ public Player (Chip chip) public static Player PlayerForChip (Chip chip) { - return (chip == Chip.None) ? null : AllPlayers [(int)chip - 1]; + return (chip == Chip.None) ? null : AllPlayers [(int) chip - 1]; } } -} \ No newline at end of file +} diff --git a/ios9/FourInARow/FourInARow/ViewController.cs b/ios9/FourInARow/FourInARow/ViewController.cs index 818343730..d7cfc3189 100644 --- a/ios9/FourInARow/FourInARow/ViewController.cs +++ b/ios9/FourInARow/FourInARow/ViewController.cs @@ -14,7 +14,7 @@ public partial class ViewController : UIViewController { const int NanoSecondsPerSeond = 1000000000; GKMinMaxStrategist strategist; - CAShapeLayer[][] chipLayers; + CAShapeLayer [] [] chipLayers; Board board; UIBezierPath chipPath; @@ -31,9 +31,9 @@ public override void ViewDidLoad () RandomSource = new GKARC4RandomSource () }; - var columns = new CAShapeLayer[Board.Width][]; + var columns = new CAShapeLayer [Board.Width] []; for (int column = 0; column < Board.Width; column++) - columns [column] = new CAShapeLayer[Board.Height]; + columns [column] = new CAShapeLayer [Board.Height]; chipLayers = columns; ResetBoard (); @@ -62,7 +62,7 @@ public override void ViewDidLayoutSubviews () partial void MakeMove (UIButton sender) { - var column = (int)sender.Tag; + var column = (int) sender.Tag; if (!board.CanMoveInColumn (column)) return; @@ -73,7 +73,7 @@ partial void MakeMove (UIButton sender) void UpdateButton (UIControl button) { - var column = (int)button.Tag; + var column = (int) button.Tag; button.Enabled = board.CanMoveInColumn (column); int row = Board.Height; var chip = Chip.None; @@ -98,7 +98,7 @@ void AddChipLayerAtColumnRowColor (int column, int row, UIColor color) { int count = chipLayers [column].Count (c => c != null); if (count < row + 1) { - var newChip = (CAShapeLayer)CAShapeLayer.Create (); + var newChip = (CAShapeLayer) CAShapeLayer.Create (); newChip.Path = chipPath.CGPath; newChip.Frame = chipPath.Bounds; newChip.FillColor = color.CGColor; @@ -158,7 +158,7 @@ void UpdateUI () NavigationItem.Title = string.Format ("{0} Turn", board.CurrentPlayer.Name); NavigationController.NavigationBar.BackgroundColor = board.CurrentPlayer.Color; - #if USE_AI_PLAYER +#if USE_AI_PLAYER if (board.CurrentPlayer.Chip != Chip.Black) return; @@ -181,7 +181,7 @@ void UpdateUI () DispatchQueue.MainQueue.DispatchAfter (new DispatchTime (DispatchTime.Now, delay * NanoSecondsPerSeond), () => MakeAIMoveInColumn (column)); }); - #endif +#endif } int ColumnForAIMove () @@ -203,4 +203,4 @@ void MakeAIMoveInColumn (int column) UpdateGame (); } } -} \ No newline at end of file +} diff --git a/ios9/Fox/Fox.iOS/AppDelegate.cs b/ios9/Fox/Fox.iOS/AppDelegate.cs index 25145372a..dd1149874 100644 --- a/ios9/Fox/Fox.iOS/AppDelegate.cs +++ b/ios9/Fox/Fox.iOS/AppDelegate.cs @@ -11,4 +11,4 @@ public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations (UI return UIInterfaceOrientationMask.Landscape; } } -} \ No newline at end of file +} diff --git a/ios9/Fox/Fox.iOS/GameViewController.cs b/ios9/Fox/Fox.iOS/GameViewController.cs index 91e3d173c..2700b5696 100644 --- a/ios9/Fox/Fox.iOS/GameViewController.cs +++ b/ios9/Fox/Fox.iOS/GameViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace Fox.iOS -{ - public partial class GameViewController : UIViewController - { +namespace Fox.iOS { + public partial class GameViewController : UIViewController { public GameViewController (IntPtr handle) : base (handle) { } diff --git a/ios9/Fox/Fox.iOS/Main.cs b/ios9/Fox/Fox.iOS/Main.cs index 94653a9ad..504000b84 100644 --- a/ios9/Fox/Fox.iOS/Main.cs +++ b/ios9/Fox/Fox.iOS/Main.cs @@ -3,7 +3,7 @@ namespace Fox.iOS { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/Fox/Fox/Character.cs b/ios9/Fox/Fox/Character.cs index f55ae553a..026f25f17 100644 --- a/ios9/Fox/Fox/Character.cs +++ b/ios9/Fox/Fox/Character.cs @@ -37,7 +37,7 @@ public class Character : NSObject { nfloat smokeBirthRate; nfloat whiteSmokeBirthRate; - SCNAudioSource [,] steps = new SCNAudioSource [StepsSoundCount, (int)FloorMaterial.Count]; + SCNAudioSource [,] steps = new SCNAudioSource [StepsSoundCount, (int) FloorMaterial.Count]; public SCNNode Node { get; private set; } @@ -58,7 +58,7 @@ public bool Walking { if (walking) Node.AddAnimation (walkAnimation, "walk"); else - Node.RemoveAnimation ((NSString)"walk", 0.2f); // TODO RemoveAnimation should accept "string" and NSString + Node.RemoveAnimation ((NSString) "walk", 0.2f); // TODO RemoveAnimation should accept "string" and NSString } } @@ -79,18 +79,18 @@ public float Direction { public Character () { for (int i = 0; i < StepsSoundCount; i++) { - steps [i, (int)FloorMaterial.Grass] = SCNAudioSource.FromFile (string.Format ("game.scnassets/sounds/Step_grass_0{0}.mp3", i)); - steps [i, (int)FloorMaterial.Grass].Volume = 0.5f; - steps [i, (int)FloorMaterial.Rock] = SCNAudioSource.FromFile (string.Format ("game.scnassets/sounds/Step_rock_0{0}.mp3", i)); + steps [i, (int) FloorMaterial.Grass] = SCNAudioSource.FromFile (string.Format ("game.scnassets/sounds/Step_grass_0{0}.mp3", i)); + steps [i, (int) FloorMaterial.Grass].Volume = 0.5f; + steps [i, (int) FloorMaterial.Rock] = SCNAudioSource.FromFile (string.Format ("game.scnassets/sounds/Step_rock_0{0}.mp3", i)); if (i < StepsInWaterSoundCount) { - steps [i, (int)FloorMaterial.Water] = SCNAudioSource.FromFile (string.Format ("game.scnassets/sounds/Step_splash_0{0}.mp3", i)); - steps [i, (int)FloorMaterial.Water].Load (); + steps [i, (int) FloorMaterial.Water] = SCNAudioSource.FromFile (string.Format ("game.scnassets/sounds/Step_splash_0{0}.mp3", i)); + steps [i, (int) FloorMaterial.Water].Load (); } else { - steps [i, (int)FloorMaterial.Water] = steps [i % StepsInWaterSoundCount, (int)FloorMaterial.Water]; + steps [i, (int) FloorMaterial.Water] = steps [i % StepsInWaterSoundCount, (int) FloorMaterial.Water]; } - steps [i, (int)FloorMaterial.Rock].Load (); - steps [i, (int)FloorMaterial.Grass].Load (); + steps [i, (int) FloorMaterial.Rock].Load (); + steps [i, (int) FloorMaterial.Grass].Load (); // Load the character. SCNScene characterScene = SCNScene.FromFile ("game.scnassets/panda.scn"); @@ -143,7 +143,7 @@ public Character () ); // We want contact notifications with the collectables, enemies and walls. - colliderNode.PhysicsBody.ContactTestBitMask = (nuint)(int)(Bitmask.SuperCollectable | Bitmask.Collectable | Bitmask.Collision | Bitmask.Enemy); + colliderNode.PhysicsBody.ContactTestBitMask = (nuint) (int) (Bitmask.SuperCollectable | Bitmask.Collectable | Bitmask.Collision | Bitmask.Enemy); Node.AddChildNode (colliderNode); walkAnimation = LoadAnimationFromSceneNamed ("game.scnassets/walk.scn"); @@ -167,7 +167,7 @@ public void PlayFootStep () return; // We are in the air, no sound to play int stepSoundIndex = Math.Min (StepsSoundCount - 1, new Random ().Next (0, 32767) * StepsSoundCount); - Node.RunAction (SCNAction.PlayAudioSource (steps[stepSoundIndex, (int)CurrentFloorMaterial], false)); + Node.RunAction (SCNAction.PlayAudioSource (steps [stepSoundIndex, (int) CurrentFloorMaterial], false)); } void UpdateWalkSpeed (nfloat speedFactor) @@ -176,7 +176,7 @@ void UpdateWalkSpeed (nfloat speedFactor) if (wasWalking) Walking = false; - walkAnimation.Speed = (float)(CharacterSpeedFactor * speedFactor); + walkAnimation.Speed = (float) (CharacterSpeedFactor * speedFactor); Walking |= wasWalking; } @@ -217,7 +217,7 @@ static CAAnimation LoadAnimationFromSceneNamed (string path) foreach (var childNode in scene.RootNode.ChildNodes) { var animationKeys = childNode.ChildNodes [0].GetAnimationKeys (); if (animationKeys?.Length > 0) { - animation = childNode.ChildNodes[0].GetAnimation (animationKeys[0]); + animation = childNode.ChildNodes [0].GetAnimation (animationKeys [0]); break; } } @@ -225,4 +225,4 @@ static CAAnimation LoadAnimationFromSceneNamed (string path) return animation; } } -} \ No newline at end of file +} diff --git a/ios9/Fox/Fox/GameView.cs b/ios9/Fox/Fox/GameView.cs index f21937e01..04608897d 100644 --- a/ios9/Fox/Fox/GameView.cs +++ b/ios9/Fox/Fox/GameView.cs @@ -24,7 +24,7 @@ public partial class GameView : SCNView, IUIGestureRecognizerDelegate { UITouch padTouch; CGRect padRect; - SKSpriteNode[] flowers = new SKSpriteNode[3]; + SKSpriteNode [] flowers = new SKSpriteNode [3]; SKLabelNode pearlLabel; SKNode overlayGroup; int pearlCount; @@ -95,7 +95,7 @@ public void Setup () flowers [i] = SKSpriteNode.FromImageNamed ("Images/FlowerEmpty.png"); flowers [i].Position = new CGPoint (110f + i * 40f, -50f); flowers [i].XScale = flowers [i].YScale = 0.25f; - overlayGroup.AddChild (flowers[i]); + overlayGroup.AddChild (flowers [i]); } // The peal icon and count. @@ -165,7 +165,7 @@ public override void TouchesBegan (NSSet touches, UIEvent touchEvent) if (TouchIsInRect (touch, padRect)) padTouch = padTouch ?? touch; else if (panningTouch == null) - panningTouch = (UITouch)touches.AnyObject; + panningTouch = (UITouch) touches.AnyObject; if (padTouch != null && panningTouch != null) break; @@ -264,7 +264,7 @@ CGPoint DirectionFromPressedKeys () SCNVector3 ComputeDirection () { CGPoint p = DirectionFromPressedKeys (); - var dir = new SCNVector3 ((float)p.X, 0f, (float)p.Y); + var dir = new SCNVector3 ((float) p.X, 0f, (float) p.Y); var p0 = new SCNVector3 (0f, 0f, 0f); dir = PointOfView.PresentationNode.ConvertPositionToNode (dir, null); @@ -278,4 +278,4 @@ SCNVector3 ComputeDirection () return dir; } } -} \ No newline at end of file +} diff --git a/ios9/Fox/Fox/GameViewController.cs b/ios9/Fox/Fox/GameViewController.cs index ba7f28000..2df45596f 100644 --- a/ios9/Fox/Fox/GameViewController.cs +++ b/ios9/Fox/Fox/GameViewController.cs @@ -25,8 +25,8 @@ public partial class GameViewController : UIViewController, ISCNSceneRendererDel SCNMaterial grassArea; SCNMaterial waterArea; - SCNNode[] flames; - SCNNode[] enemies; + SCNNode [] flames; + SCNNode [] enemies; bool gameIsComplete; bool isInvincible; @@ -52,7 +52,7 @@ public partial class GameViewController : UIViewController, ISCNSceneRendererDel double previousUpdateTime; nfloat maxPenetrationDistance; float accelerationY; - bool positionNeedsAdjustment; + bool positionNeedsAdjustment; SCNVector3 replacementPosition; public Character Character { get; set; } @@ -93,8 +93,8 @@ void SetupCamera () pov.EulerAngles = new SCNVector3 (0f, 0f, 0f); pov.Position = new SCNVector3 (0f, 0f, distance); - cameraYHandle.Rotation = new SCNVector4 (0f, 1f, 0f, (float)Math.PI / 2f + (float)Math.PI / 4f * 3f); - cameraXHandle.Rotation = new SCNVector4 (1f, 0f, 0f, -(float)Math.PI / 4f * 0.125f); + cameraYHandle.Rotation = new SCNVector4 (0f, 1f, 0f, (float) Math.PI / 2f + (float) Math.PI / 4f * 3f); + cameraXHandle.Rotation = new SCNVector4 (1f, 0f, 0f, -(float) Math.PI / 4f * 0.125f); cameraXHandle.AddChildNode (pov); // Animate camera on launch and prevent the user from manipulating the camera until the end of the animation @@ -115,7 +115,7 @@ void SetupCamera () cameraYHandle.AddAnimation (cameraYAnimation, null); var cameraXAnimation = CABasicAnimation.FromKeyPath ("rotation.w"); - cameraXAnimation.From = NSNumber.FromDouble (-Math.PI / 2 + cameraXHandle.Rotation.W); + cameraXAnimation.From = NSNumber.FromDouble (-Math.PI / 2 + cameraXHandle.Rotation.W); cameraXAnimation.To = NSNumber.FromDouble (0.0); cameraXAnimation.Additive = true; cameraXAnimation.FillMode = CAFillMode.Both; @@ -128,7 +128,7 @@ void SetupCamera () var lookAtConstraint = SCNLookAtConstraint.Create (Character.Node.FindChildNode ("Bip001_Head", true)); lookAtConstraint.InfluenceFactor = 0; - pov.Constraints = new SCNConstraint[] { lookAtConstraint }; + pov.Constraints = new SCNConstraint [] { lookAtConstraint }; } public void PanCamera (CGSize dir) @@ -149,15 +149,15 @@ public void PanCamera (CGSize dir) if (cameraXHandle.Rotation.X < 0f) cameraXHandle.Rotation = new SCNVector4 (1f, 0f, 0f, -cameraXHandle.Rotation.W); - + SCNTransaction.Commit (); SCNTransaction.Begin (); SCNTransaction.AnimationDuration = 0.5; SCNTransaction.AnimationTimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseOut); - cameraYHandle.Rotation = new SCNVector4 (0f, 1f, 0f, cameraYHandle.Rotation.Y * (cameraYHandle.Rotation.W - (float)dir.Width * f)); - cameraXHandle.Rotation = new SCNVector4 (1f, 0f, 0f, (float)Math.Max (-Math.PI / 2.0, Math.Min (0.13, cameraXHandle.Rotation.W + dir.Height * f))); + cameraYHandle.Rotation = new SCNVector4 (0f, 1f, 0f, cameraYHandle.Rotation.Y * (cameraYHandle.Rotation.W - (float) dir.Width * f)); + cameraXHandle.Rotation = new SCNVector4 (1f, 0f, 0f, (float) Math.Max (-Math.PI / 2.0, Math.Min (0.13, cameraXHandle.Rotation.W + dir.Height * f))); SCNTransaction.Commit (); } @@ -166,7 +166,7 @@ void SetupCollisionNodes (SCNNode node) if (node.Geometry != null) { Console.WriteLine (node.Name); node.PhysicsBody = SCNPhysicsBody.CreateStaticBody (); - node.PhysicsBody.CategoryBitMask = (nuint)(int)Bitmask.Collision; + node.PhysicsBody.CategoryBitMask = (nuint) (int) Bitmask.Collision; var options = new SCNPhysicsShapeOptions { ShapeType = SCNPhysicsShapeType.ConcavePolyhedron @@ -194,7 +194,7 @@ void SetupCollisionNodes (SCNNode node) node.Hidden = false; if (node.Name == "water") - node.PhysicsBody.CategoryBitMask = (nuint)(int)Bitmask.Water; + node.PhysicsBody.CategoryBitMask = (nuint) (int) Bitmask.Water; } foreach (SCNNode child in node.ChildNodes) { @@ -282,7 +282,7 @@ void SetupAutomaticCameraPositions () public override void AwakeFromNib () { - GameView = (GameView)View; + GameView = (GameView) View; // Create a new scene. SCNScene scene = SCNScene.FromFile ("game.scnassets/level.scn"); @@ -313,7 +313,7 @@ public override void AwakeFromNib () Character.Node.Transform = sp.Transform; // Setup physics masks and physics shape - SCNNode[] collisionNodes = scene.RootNode.FindNodes ((SCNNode node, out bool stop) => { + SCNNode [] collisionNodes = scene.RootNode.FindNodes ((SCNNode node, out bool stop) => { bool? collidable = node.Name?.Contains ("collision"); stop = false; return collidable.HasValue && collidable.Value; @@ -328,7 +328,7 @@ public override void AwakeFromNib () flames = scene.RootNode.FindNodes ((SCNNode node, out bool stop) => { stop = false; if (node.Name == "flame") { - node.PhysicsBody.CategoryBitMask = (nuint)(int)Bitmask.Enemy; + node.PhysicsBody.CategoryBitMask = (nuint) (int) Bitmask.Enemy; return true; } @@ -398,7 +398,7 @@ public virtual void Update (ISCNSceneRenderer renderer, double timeInSeconds) // Move if (Math.Abs (direction.X) > float.Epsilon && Math.Abs (direction.Z) > float.Epsilon) { - var characterSpeed = (float)deltaTime * CharacterSpeedFactor * .84f; + var characterSpeed = (float) deltaTime * CharacterSpeedFactor * .84f; Character.Node.Position = new SCNVector3 ( initialPosition.X + direction.X * characterSpeed, initialPosition.Y + direction.Y * characterSpeed, @@ -407,7 +407,7 @@ public virtual void Update (ISCNSceneRenderer renderer, double timeInSeconds) // update orientation double angle = Math.Atan2 (direction.X, direction.Z); - Character.Direction = (float)angle; + Character.Direction = (float) angle; Character.Walking = true; } else { Character.Walking = false; @@ -420,15 +420,15 @@ public virtual void Update (ISCNSceneRenderer renderer, double timeInSeconds) p1.Y += MaxRise; var options = new SCNPhysicsTest { - CollisionBitMask = (nuint)(int)(Bitmask.Collision | Bitmask.Water), + CollisionBitMask = (nuint) (int) (Bitmask.Collision | Bitmask.Water), SearchMode = SCNPhysicsSearchMode.Closest }; - SCNHitTestResult[] results = GameView.Scene.PhysicsWorld.RayTestWithSegmentFromPoint (p1, p0, options); + SCNHitTestResult [] results = GameView.Scene.PhysicsWorld.RayTestWithSegmentFromPoint (p1, p0, options); float groundY = -10; if (results.Length > 0) { - + SCNHitTestResult result = results [0]; groundY = result.WorldCoordinates.Y; UpdateCameraWithCurrentGround (result.Node); @@ -447,7 +447,7 @@ public virtual void Update (ISCNSceneRenderer renderer, double timeInSeconds) Character.CurrentFloorMaterial = FloorMaterial.Water; options = new SCNPhysicsTest { - CollisionBitMask = (nuint)(int)Bitmask.Collision, + CollisionBitMask = (nuint) (int) Bitmask.Collision, SearchMode = SCNPhysicsSearchMode.Closest }; @@ -459,25 +459,25 @@ public virtual void Update (ISCNSceneRenderer renderer, double timeInSeconds) } } -// var nextPosition = Character.Node.Position; -// const double threshold = 1e-5; -// -// if (groundY < nextPosition.Y - threshold) { -// // approximation of acceleration for a delta time -// accelerationY += (float)(deltaTime * GravityAcceleration); -// if (groundY < nextPosition.Y - 0.2) -// Character.CurrentFloorMaterial = FloorMaterial.Air; -// } else { -// accelerationY = 0; -// } -// -// nextPosition.Y -= accelerationY; -// -// // reset acceleration if we touch the ground -// if (groundY > nextPosition.Y) { -// accelerationY = 0; -// nextPosition.Y = groundY; -// } + // var nextPosition = Character.Node.Position; + // const double threshold = 1e-5; + // + // if (groundY < nextPosition.Y - threshold) { + // // approximation of acceleration for a delta time + // accelerationY += (float)(deltaTime * GravityAcceleration); + // if (groundY < nextPosition.Y - 0.2) + // Character.CurrentFloorMaterial = FloorMaterial.Air; + // } else { + // accelerationY = 0; + // } + // + // nextPosition.Y -= accelerationY; + // + // // reset acceleration if we touch the ground + // if (groundY > nextPosition.Y) { + // accelerationY = 0; + // nextPosition.Y = groundY; + // } // Flames are static physics bodies, but they are moved by an action - So we need to tell the physics engine that the transforms did change. foreach (SCNNode flame in flames) @@ -497,47 +497,47 @@ public virtual void Update (ISCNSceneRenderer renderer, double timeInSeconds) // Adjust sounds volumes based on distance with the enemy. if (!gameIsComplete) { double fireVolume = 0.3 * Math.Max (0.0, Math.Min (1.0, 1.0 - (distanceToClosestEnemy - 1.2) / 1.6)); - var mixerNode = flameThrowerSound.AudioNode as AVAudioMixerNode; + var mixerNode = flameThrowerSound.AudioNode as AVAudioMixerNode; if (mixerNode != null) - mixerNode.Volume = (float)fireVolume; + mixerNode.Volume = (float) fireVolume; } } [Export ("physicsWorld:didBeginContact:")] public virtual void DidBeginContact (SCNPhysicsWorld world, SCNPhysicsContact contact) { - if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Collision) + if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Collision) CharacterNodeHitWallWithContact (contact.NodeB, contact); - if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Collision) + if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Collision) CharacterNodeHitWallWithContact (contact.NodeA, contact); - if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Collectable) + if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Collectable) CollectPearl (contact.NodeA); - if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Collectable) + if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Collectable) CollectPearl (contact.NodeB); - if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.SuperCollectable) + if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.SuperCollectable) CollectFlower (contact.NodeA); - if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.SuperCollectable) + if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.SuperCollectable) CollectFlower (contact.NodeB); - if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Enemy) + if (contact.NodeA.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Enemy) WasHit (); - if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Enemy) + if (contact.NodeB.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Enemy) WasHit (); } [Export ("physicsWorld:didUpdateContact:")] public virtual void DidUpdateContact (SCNPhysicsWorld world, SCNPhysicsContact contact) { - if (contact.NodeA?.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Collision) + if (contact.NodeA?.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Collision) CharacterNodeHitWallWithContact (contact.NodeB, contact); - if (contact.NodeB?.PhysicsBody.CategoryBitMask == (nuint)(int)Bitmask.Collision) + if (contact.NodeB?.PhysicsBody.CategoryBitMask == (nuint) (int) Bitmask.Collision) CharacterNodeHitWallWithContact (contact.NodeA, contact); } @@ -579,7 +579,7 @@ void CharacterNodeHitWallWithContact (SCNNode capsule, SCNPhysicsContact contact var charPosition = Character.Node.Position; SCNVector3 n = contact.ContactNormal; - SCNVector3.Multiply (ref n, (float)contact.PenetrationDistance, out n); + SCNVector3.Multiply (ref n, (float) contact.PenetrationDistance, out n); n.Y = 0; SCNVector3.Add (ref charPosition, ref n, out replacementPosition); @@ -635,7 +635,7 @@ void ShowEndScreen () // Animate the camera forever DispatchQueue.MainQueue.DispatchAfter (new DispatchTime (DispatchTime.Now, 1 * NanoSecondsPerSeond), () => { cameraYHandle.RunAction (SCNAction.RepeatActionForever (SCNAction.RotateBy (0f, -1f, 0f, 3.0))); - cameraXHandle.RunAction (SCNAction.RotateTo (-(float)Math.PI / 4f, 0f, 0f, 5.0)); + cameraXHandle.RunAction (SCNAction.RotateTo (-(float) Math.PI / 4f, 0f, 0f, 5.0)); }); } @@ -685,7 +685,7 @@ void CollectFlower (SCNNode node) NSString PathForArtResource (string resourceName) { - return (NSString)string.Format ("{0}/{1}", ArtFolderRoot, resourceName); + return (NSString) string.Format ("{0}/{1}", ArtFolderRoot, resourceName); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/AppDelegate.cs b/ios9/HomeKitCatalog/HomeKitCatalog/AppDelegate.cs index b10593592..d0f1c9162 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/AppDelegate.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/AppDelegate.cs @@ -1,14 +1,12 @@ -using Foundation; +using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Main.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Main.cs index eb88c7388..5a5f01acd 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Main.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace HomeKitCatalog -{ - public class Application - { +namespace HomeKitCatalog { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Alert.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Alert.cs index 0ce95a0dd..35acced03 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Alert.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Alert.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace HomeKitCatalog -{ - public static class Alert - { +namespace HomeKitCatalog { + public static class Alert { /// <summary> /// A simple factory which creates `UIAlertController` that prompts for a name, then runs a completion block passing in the name. /// </summary> @@ -13,7 +11,7 @@ public static class Alert /// <param name="completionHandler">A block to call, passing in the provided text</param> public static UIAlertController Create (string attributeType, Action<string> completionHandler, string placeholder, string shortType) { - if (string.IsNullOrWhiteSpace(placeholder)) + if (string.IsNullOrWhiteSpace (placeholder)) placeholder = attributeType; if (string.IsNullOrWhiteSpace (shortType)) shortType = attributeType; @@ -29,16 +27,16 @@ public static UIAlertController Create (string attributeType, Action<string> com var cancelAction = UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, action => alert.DismissViewController (true, null)); string addString = string.Format ("Add {0}", shortType); - var addNewObject = UIAlertAction.Create(addString, UIAlertActionStyle.Default, action => { + var addNewObject = UIAlertAction.Create (addString, UIAlertActionStyle.Default, action => { var textFields = alert.TextFields; - if(textFields != null && textFields.Length > 0) { - var textField = textFields[0]; - if(textField != null) { - var trimmedName = textField.Text.Trim(); - completionHandler(trimmedName); + if (textFields != null && textFields.Length > 0) { + var textField = textFields [0]; + if (textField != null) { + var trimmedName = textField.Text.Trim (); + completionHandler (trimmedName); } } - alert.DismissViewController(true, null); + alert.DismissViewController (true, null); }); alert.AddAction (cancelAction); @@ -47,7 +45,7 @@ public static UIAlertController Create (string attributeType, Action<string> com return alert; } - public static UIAlertController Create(string title, string body) + public static UIAlertController Create (string title, string body) { var alert = UIAlertController.Create (title, body, UIAlertControllerStyle.Alert); var okayAction = UIAlertAction.Create ("Okay", UIAlertActionStyle.Default, action => alert.DismissViewController (true, null)); @@ -56,4 +54,4 @@ public static UIAlertController Create(string title, string body) return alert; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ArraySotring.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ArraySotring.cs index e26e30a1d..b4c5e21db 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ArraySotring.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ArraySotring.cs @@ -1,18 +1,16 @@ -using System; +using System; using System.Collections.Generic; using HomeKit; -namespace HomeKitCatalog -{ - public static class ArraySotringExtensions - { - public static void SortByLocalizedName<T> (this T[] array, Func<T, string> nameGetter) +namespace HomeKitCatalog { + public static class ArraySotringExtensions { + public static void SortByLocalizedName<T> (this T [] array, Func<T, string> nameGetter) { - Array.Sort(array, (x, y) => { - var xName = nameGetter(x); + Array.Sort (array, (x, y) => { + var xName = nameGetter (x); var yName = nameGetter (y); - return xName.CompareTo(yName); + return xName.CompareTo (yName); }); } @@ -20,9 +18,9 @@ public static void SortByLocalizedName<T> (this T[] array, Func<T, string> nameG public static void SortByLocalizedName<T> (this List<T> list, Func<T, string> nameGetter) { list.Sort ((x, y) => { - var xName = nameGetter(x); + var xName = nameGetter (x); var yName = nameGetter (y); - return xName.CompareTo(yName); + return xName.CompareTo (yName); }); } @@ -48,4 +46,4 @@ static int ActionSetComparision (HMActionSet x, HMActionSet y) return x.Name.CompareTo (y.Name); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Colors.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Colors.cs index b87aea206..e17b950bd 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Colors.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/Colors.cs @@ -1,12 +1,10 @@ -using UIKit; +using UIKit; -namespace HomeKitCatalog -{ - public static class Colors - { - public static UIColor EditableBlueColor() +namespace HomeKitCatalog { + public static class Colors { + public static UIColor EditableBlueColor () { return new UIColor (0f, 122f / 255f, 1f, 1f); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMActionSetExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMActionSetExtensions.cs index 7b42423b8..a7861d102 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMActionSetExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMActionSetExtensions.cs @@ -1,12 +1,10 @@ -using System; +using System; using HomeKit; -namespace HomeKitCatalog -{ - public static class HMActionSetExtensions - { - static readonly HMActionSetType[] BuiltInActionSetTypes = { +namespace HomeKitCatalog { + public static class HMActionSetExtensions { + static readonly HMActionSetType [] BuiltInActionSetTypes = { HMActionSetType.WakeUp, HMActionSetType.HomeDeparture, HMActionSetType.HomeArrival, @@ -30,4 +28,4 @@ public static int CompareWitBuiltIn (this HMActionSet actionSet, HMActionSet ano return anotherIndex - index; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMCharacteristicExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMCharacteristicExtensions.cs index a5dd05d80..b2fe33ae0 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMCharacteristicExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMCharacteristicExtensions.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Linq; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ - public static class HMCharacteristicExtensions - { - static readonly NSNumberFormatter formatter = new NSNumberFormatter(); +namespace HomeKitCatalog { + public static class HMCharacteristicExtensions { + static readonly NSNumberFormatter formatter = new NSNumberFormatter (); - static readonly HMCharacteristicMetadataFormat[] numericFormats = { + static readonly HMCharacteristicMetadataFormat [] numericFormats = { HMCharacteristicMetadataFormat.Int, HMCharacteristicMetadataFormat.Float, HMCharacteristicMetadataFormat.UInt8, @@ -20,7 +18,7 @@ public static class HMCharacteristicExtensions }; // Returns the description for a provided value, taking the characteristic's metadata and possible values into account. - public static string DescriptionForValue(this HMCharacteristic self, NSObject value) + public static string DescriptionForValue (this HMCharacteristic self, NSObject value) { if (self.IsWriteOnly ()) return "Write-Only Characteristic"; @@ -32,7 +30,7 @@ public static string DescriptionForValue(this HMCharacteristic self, NSObject va public static string DescriptionForValue (this HMCharacteristic self, int value) { if (self.IsBoolean ()) - return Convert.ToBoolean(value) ? "On" : "Off"; + return Convert.ToBoolean (value) ? "On" : "Off"; var predeterminedValueString = self.PredeterminedValueDescriptionForNumber (value); if (predeterminedValueString != null) @@ -42,7 +40,7 @@ public static string DescriptionForValue (this HMCharacteristic self, int value) if (metadata != null) { var stepValue = metadata.StepValue; if (stepValue != null) { - formatter.MaximumFractionDigits = (int)Math.Log10 (1f / stepValue.DoubleValue); + formatter.MaximumFractionDigits = (int) Math.Log10 (1f / stepValue.DoubleValue); var str = formatter.StringFromNumber (value); if (!string.IsNullOrEmpty (str)) return str + self.LocalizedUnitDescription (); @@ -52,7 +50,7 @@ public static string DescriptionForValue (this HMCharacteristic self, int value) return value.ToString (); } - public static string PredeterminedValueDescriptionForNumber(this HMCharacteristic self, int number) + public static string PredeterminedValueDescriptionForNumber (this HMCharacteristic self, int number) { switch (self.CharacteristicType) { case HMCharacteristicType.PowerState: @@ -69,7 +67,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi case HMCharacteristicType.TargetDoorState: case HMCharacteristicType.CurrentDoorState: - var doorState = (HMCharacteristicValueDoorState)number; + var doorState = (HMCharacteristicValueDoorState) number; switch (doorState) { case HMCharacteristicValueDoorState.Open: return "Open"; @@ -85,7 +83,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.TargetHeatingCooling: - var targetMode = (HMCharacteristicValueHeatingCooling)number; + var targetMode = (HMCharacteristicValueHeatingCooling) number; switch (targetMode) { case HMCharacteristicValueHeatingCooling.Off: return "Off"; @@ -99,7 +97,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.CurrentHeatingCooling: - var currentMode = (HMCharacteristicValueHeatingCooling)number; + var currentMode = (HMCharacteristicValueHeatingCooling) number; switch (currentMode) { case HMCharacteristicValueHeatingCooling.Off: return "Off"; @@ -109,12 +107,12 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi return "Cooling"; case HMCharacteristicValueHeatingCooling.Auto: return "Auto"; - } + } break; case HMCharacteristicType.TargetLockMechanismState: case HMCharacteristicType.CurrentLockMechanismState: - var lockState = (HMCharacteristicValueLockMechanismState)number; + var lockState = (HMCharacteristicValueLockMechanismState) number; switch (lockState) { case HMCharacteristicValueLockMechanismState.Unsecured: return "Unsecured"; @@ -128,7 +126,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.TemperatureUnits: - var unit = (HMCharacteristicValueTemperatureUnit)number; + var unit = (HMCharacteristicValueTemperatureUnit) number; switch (unit) { case HMCharacteristicValueTemperatureUnit.Celsius: return "Celsius"; @@ -138,7 +136,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.LockMechanismLastKnownAction: - var lastKnownAction = (HMCharacteristicValueLockMechanism)number; + var lastKnownAction = (HMCharacteristicValueLockMechanism) number; switch (lastKnownAction) { case HMCharacteristicValueLockMechanism.LastKnownActionSecuredUsingPhysicalMovementInterior: return "Interior Secured"; @@ -166,7 +164,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.RotationDirection: - var rotationDirection = (HMCharacteristicValueRotationDirection)number; + var rotationDirection = (HMCharacteristicValueRotationDirection) number; switch (rotationDirection) { case HMCharacteristicValueRotationDirection.Clockwise: return "Clockwise"; @@ -176,7 +174,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.AirParticulateSize: - var size = (HMCharacteristicValueAirParticulate)number; + var size = (HMCharacteristicValueAirParticulate) number; switch (size) { case HMCharacteristicValueAirParticulate.Size10: return "Size 10"; @@ -187,7 +185,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.PositionState: - var state = (HMCharacteristicValuePositionState)number; + var state = (HMCharacteristicValuePositionState) number; switch (state) { case HMCharacteristicValuePositionState.Opening: return "Opening"; @@ -199,7 +197,7 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi break; case HMCharacteristicType.CurrentSecuritySystemState: - var positionState = (HMCharacteristicValueCurrentSecuritySystemState)number; + var positionState = (HMCharacteristicValueCurrentSecuritySystemState) number; switch (positionState) { case HMCharacteristicValueCurrentSecuritySystemState.AwayArm: return "Away"; @@ -211,11 +209,11 @@ public static string PredeterminedValueDescriptionForNumber(this HMCharacteristi return "Disarm"; case HMCharacteristicValueCurrentSecuritySystemState.Triggered: return "Triggered"; - } + } break; case HMCharacteristicType.TargetSecuritySystemState: - var securityState = (HMCharacteristicValueTargetSecuritySystemState)number; + var securityState = (HMCharacteristicValueTargetSecuritySystemState) number; switch (securityState) { case HMCharacteristicValueTargetSecuritySystemState.AwayArm: return "Away"; @@ -251,7 +249,7 @@ static string LocalizedUnitDescription (this HMCharacteristic self) return string.Empty; } - public static string LocalizedCharacteristicType(this HMCharacteristic self) + public static string LocalizedCharacteristicType (this HMCharacteristic self) { var type = self.LocalizedDescription; @@ -272,43 +270,43 @@ public static bool IsInteger (this HMCharacteristic self) return self.IsNumeric () && !self.IsFloatingPoint (); } - public static bool IsNumeric(this HMCharacteristic self) + public static bool IsNumeric (this HMCharacteristic self) { var metadata = self.Metadata; return metadata != null && numericFormats.Contains (metadata.Format); } - public static bool IsBoolean(this HMCharacteristic self) + public static bool IsBoolean (this HMCharacteristic self) { return CharacteristicFormatEqualsTo (self, HMCharacteristicMetadataFormat.Bool); } - public static bool IsTextWritable(this HMCharacteristic self) + public static bool IsTextWritable (this HMCharacteristic self) { return CharacteristicFormatEqualsTo (self, HMCharacteristicMetadataFormat.String) && self.Writable; } - public static bool IsFloatingPoint(this HMCharacteristic self) + public static bool IsFloatingPoint (this HMCharacteristic self) { return CharacteristicFormatEqualsTo (self, HMCharacteristicMetadataFormat.Float); } - public static bool IsReadOnly(this HMCharacteristic self) + public static bool IsReadOnly (this HMCharacteristic self) { return self.Readable && !self.Writable; } - public static bool IsWriteOnly(this HMCharacteristic self) + public static bool IsWriteOnly (this HMCharacteristic self) { return !self.Readable && self.Writable; } - public static bool IsIdentify(this HMCharacteristic self) + public static bool IsIdentify (this HMCharacteristic self) { return self.CharacteristicType == HMCharacteristicType.Identify; } - public static int[] AllPossibleValues (this HMCharacteristic self) + public static int [] AllPossibleValues (this HMCharacteristic self) { if (!self.IsInteger ()) return null; @@ -323,11 +321,11 @@ public static int[] AllPossibleValues (this HMCharacteristic self) var step = stepValue.DoubleValue; return Enumerable.Range (0, self.NumberOfChoices ()) - .Select (i => (int)(i * step)) + .Select (i => (int) (i * step)) .ToArray (); } - static int NumberOfChoices(this HMCharacteristic self) + static int NumberOfChoices (this HMCharacteristic self) { var metadata = self.Metadata; if (metadata == null) @@ -347,12 +345,12 @@ static int NumberOfChoices(this HMCharacteristic self) var stepValue = metadata.StepValue; if (stepValue != null) - range = (int)(range / stepValue.DoubleValue); + range = (int) (range / stepValue.DoubleValue); return range + 1; } - public static bool HasPredeterminedValueDescriptions(this HMCharacteristic self) + public static bool HasPredeterminedValueDescriptions (this HMCharacteristic self) { var number = self.Value as NSNumber; if (number == null) @@ -362,18 +360,18 @@ public static bool HasPredeterminedValueDescriptions(this HMCharacteristic self) return self.PredeterminedValueDescriptionForNumber (num) != null; } - static bool CharacteristicFormatEqualsTo(HMCharacteristic characteristic, HMCharacteristicMetadataFormat format) + static bool CharacteristicFormatEqualsTo (HMCharacteristic characteristic, HMCharacteristicMetadataFormat format) { var metadata = characteristic.Metadata; return metadata != null && metadata.Format == format; } - public static bool IsFavorite(this HMCharacteristic self) + public static bool IsFavorite (this HMCharacteristic self) { return FavoritesManager.SharedManager.IsFavorite (self); } - public static void IsFavorite(this HMCharacteristic self, bool newValue) + public static void IsFavorite (this HMCharacteristic self, bool newValue) { if (newValue) FavoritesManager.SharedManager.FavoriteCharacteristic (self); @@ -381,4 +379,4 @@ public static void IsFavorite(this HMCharacteristic self, bool newValue) FavoritesManager.SharedManager.UnfavoriteCharacteristic (self); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMEventTriggerExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMEventTriggerExtensions.cs index 4d9eaa447..5db67922a 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMEventTriggerExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMEventTriggerExtensions.cs @@ -1,12 +1,10 @@ -using System; +using System; using System.Linq; using HomeKit; -namespace HomeKitCatalog -{ - public static class HMEventTriggerExtensions - { +namespace HomeKitCatalog { + public static class HMEventTriggerExtensions { // returns: `true` if the trigger contains a location event, `false` otherwise. public static bool IsLocationEvent (this HMEventTrigger trigger) { @@ -24,9 +22,9 @@ public static HMLocationEvent LocationEvent (this HMEventTrigger self) return null; } - public static HMCharacteristicEvent[] CharacteristicEvents(this HMEventTrigger self) + public static HMCharacteristicEvent [] CharacteristicEvents (this HMEventTrigger self) { return self.Events.OfType<HMCharacteristicEvent> ().ToArray (); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMHomeExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMHomeExtensions.cs index e7ed067cb..4c990e189 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMHomeExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMHomeExtensions.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using HomeKit; using Foundation; -namespace HomeKitCatalog -{ - public static class HMHomeExtensions - { +namespace HomeKitCatalog { + public static class HMHomeExtensions { // All the services within all the accessories within the home. static HashSet<HMService> GetAllServices (this HMHome self) { @@ -25,7 +23,7 @@ public static HashSet<HMCharacteristic> GetAllCharacteristics (this HMHome self) public static Dictionary<string, List<HMService>> GetServiceTable (this HMHome self) { var serviceDictionary = new Dictionary<string, List<HMService>> (); - foreach (var service in self.GetAllServices()) { + foreach (var service in self.GetAllServices ()) { if (!service.IsControllType ()) continue; @@ -44,10 +42,10 @@ public static Dictionary<string, List<HMService>> GetServiceTable (this HMHome s } // returns: All rooms in the home, including `roomForEntireHome`. - public static HMRoom[] GetAllRooms (this HMHome self) + public static HMRoom [] GetAllRooms (this HMHome self) { var rooms = self.Rooms; - var allRooms = new HMRoom[rooms.Length + 1]; + var allRooms = new HMRoom [rooms.Length + 1]; Array.Copy (rooms, allRooms, rooms.Length); allRooms [rooms.Length] = self.GetRoomForEntireHome (); return allRooms; @@ -73,7 +71,7 @@ public static IEnumerable<HMAccessory> AccessoriesWithIdentifiers (this HMHome s } // Searches through the home's accessories to find the accessory that is bridging the provided accessory. - public static HMAccessory BridgeForAccessory (this HMHome self, HMAccessory accessory) + public static HMAccessory BridgeForAccessory (this HMHome self, HMAccessory accessory) { if (!accessory.Bridged) return null; @@ -112,4 +110,4 @@ public static IEnumerable<HMService> ServicesNotAlreadyInServiceGroup (this HMHo return self.GetAllServices ().Where (filter); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMServiceExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMServiceExtensions.cs index 99ad3dc0f..f736e32e8 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMServiceExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/HMServiceExtensions.cs @@ -1,13 +1,11 @@ -using System; +using System; using Foundation; using HomeKit; using ObjCRuntime; -namespace HomeKitCatalog -{ - public static class HMServiceExtensions - { +namespace HomeKitCatalog { + public static class HMServiceExtensions { // returns: `true` if this service supports the `associatedServiceType` property; `false` otherwise. public static bool SupportsAssociatedServiceType (this HMService self) @@ -23,8 +21,7 @@ public static bool IsControllType (this HMService self) } // TODO: https://bugzilla.xamarin.com/show_bug.cgi?id=33909 - internal static class HMServiceKeys - { + internal static class HMServiceKeys { public static readonly IntPtr Handle = Dlfcn.dlopen ("/System/Library/Frameworks/HomeKit.framework/HomeKit", 0); static NSString _AccessoryInformation; diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ListExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ListExtensions.cs index 2d319daed..1957ff8c3 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ListExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/ListExtensions.cs @@ -1,9 +1,7 @@ -using System.Collections.Generic; +using System.Collections.Generic; -namespace HomeKitCatalog -{ - public static class ListExtensions - { +namespace HomeKitCatalog { + public static class ListExtensions { public static T RemoveAtIndex<T> (this List<T> list, int index) { var item = list [index]; diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/NSPredicateExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/NSPredicateExtensions.cs index 0e3543279..d61f422fb 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/NSPredicateExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/NSPredicateExtensions.cs @@ -1,13 +1,11 @@ -using System; +using System; using HomeKit; using Foundation; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents condition type in HomeKit with associated values. - public enum HomeKitConditionType - { + public enum HomeKitConditionType { Unknown, // The predicate is not a HomeKit condition. Characteristic, @@ -15,8 +13,7 @@ public enum HomeKitConditionType ExactTime, } - public class HomeKitCondition - { + public class HomeKitCondition { // Represents a characteristic condition. // The tuple represents the `HMCharacteristic` and its condition value. // For example, "Current gargage door is set to 'Open'". @@ -72,8 +69,7 @@ public static HomeKitCondition CreateExactTime (TimeConditionOrder order, NSDate } } - public static class NSPredicateExtensions - { + public static class NSPredicateExtensions { // returns: The 'type' of HomeKit condition, with associated value, if applicable. public static HomeKitCondition HomeKitConditionType (this NSPredicate self) { @@ -233,8 +229,7 @@ static string GetEnumConstant (HMSignificantEvent value) } } - internal static class HMSignificantEventInternal - { + internal static class HMSignificantEventInternal { public static readonly IntPtr Handle = ObjCRuntime.Dlfcn.dlopen ("/System/Library/Frameworks/HomeKit.framework/HomeKit", 0); static NSString _Sunrise; static NSString _Sunset; @@ -258,4 +253,4 @@ public static NSString Sunset { } } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIStoryboardSegueExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIStoryboardSegueExtensions.cs index 28f1b21ce..f0caf3946 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIStoryboardSegueExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIStoryboardSegueExtensions.cs @@ -1,15 +1,13 @@ -using System; +using System; using UIKit; -namespace HomeKitCatalog -{ - public static class UIStoryboardSegueExtensions - { - public static UIViewController IntendedDestinationViewController(this UIStoryboardSegue segue) +namespace HomeKitCatalog { + public static class UIStoryboardSegueExtensions { + public static UIViewController IntendedDestinationViewController (this UIStoryboardSegue segue) { var navigationController = segue.DestinationViewController as UINavigationController; return navigationController != null ? navigationController.TopViewController : segue.DestinationViewController; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UITableViewExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UITableViewExtensions.cs index 6e1a7aeaf..93fdf69af 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UITableViewExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UITableViewExtensions.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace HomeKitCatalog -{ - public static class UITableViewExtensions - { +namespace HomeKitCatalog { + public static class UITableViewExtensions { public static void SetBackgroundMessage (this UITableView tableView, string msg) { if (string.IsNullOrWhiteSpace (msg)) { @@ -24,4 +22,4 @@ public static void SetBackgroundMessage (this UITableView tableView, string msg) } } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIViewControllerExtensions.cs b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIViewControllerExtensions.cs index d3ee7e953..01de2a2a1 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIViewControllerExtensions.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/Utils/UIViewControllerExtensions.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using CoreFoundation; @@ -6,10 +6,8 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ - public static class UIViewControllerExtensions - { +namespace HomeKitCatalog { + public static class UIViewControllerExtensions { public static void PresentAddAlertWithAttributeType (this UIViewController vc, string type, string placeholder, string shortType, Action<string> completion) { var alertController = Alert.Create (type, completion, placeholder, shortType); @@ -21,7 +19,7 @@ public static void DisplayErrors (this UIViewController self, IEnumerable<NSErro { var messages = new List<string> (); foreach (var error in errors) { - var errorCode = (HMError)(int)error.Code; + var errorCode = (HMError) (int) error.Code; if (self.PresentedViewController != null || errorCode == HMError.OperationCancelled || errorCode == HMError.UserDeclinedAddingUser) Console.WriteLine (error.LocalizedDescription); else @@ -49,4 +47,4 @@ static void DisplayMessage (this UIViewController self, string title, string mes }); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryBrowserViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryBrowserViewController.cs index 413e69ce9..6a2e09ca4 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryBrowserViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryBrowserViewController.cs @@ -8,10 +8,8 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ - public enum AccessoryType - { +namespace HomeKitCatalog { + public enum AccessoryType { // A HomeKit object HomeKit, // An external, `EAWiFiUnconfiguredAccessory` object @@ -19,8 +17,7 @@ public enum AccessoryType } // Represents an accessory type and encapsulated accessory. - public class Accessory : IEquatable<Accessory> - { + public class Accessory : IEquatable<Accessory> { Func<string> nameGetter; public string Name { @@ -54,10 +51,10 @@ public bool Equals (Accessory other) public override bool Equals (object obj) { - if (obj == null || obj.GetType () != typeof(Accessory)) + if (obj == null || obj.GetType () != typeof (Accessory)) return false; - var other = (Accessory)obj; + var other = (Accessory) obj; return Name == other.Name; } @@ -87,10 +84,9 @@ public static Accessory CreateExternalObject (EAWiFiUnconfiguredAccessory access } } - public partial class AccessoryBrowserViewController : HMCatalogViewController, IModifyAccessoryDelegate, IEAWiFiUnconfiguredAccessoryBrowserDelegate, IHMAccessoryBrowserDelegate - { - static readonly NSString AccessoryCell = (NSString)"AccessoryCell"; - static readonly NSString AddedAccessoryCell = (NSString)"AddedAccessoryCell"; + public partial class AccessoryBrowserViewController : HMCatalogViewController, IModifyAccessoryDelegate, IEAWiFiUnconfiguredAccessoryBrowserDelegate, IHMAccessoryBrowserDelegate { + static readonly NSString AccessoryCell = (NSString) "AccessoryCell"; + static readonly NSString AddedAccessoryCell = (NSString) "AddedAccessoryCell"; const string AddAccessorySegue = "Add Accessory"; readonly List<HMAccessory> addedAccessories = new List<HMAccessory> (); @@ -149,7 +145,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) var accessorySender = sender as HMAccessory; if (accessorySender != null && segue.Identifier == AddAccessorySegue) { - var modifyViewController = (ModifyAccessoryViewController)segue.IntendedDestinationViewController (); + var modifyViewController = (ModifyAccessoryViewController) segue.IntendedDestinationViewController (); modifyViewController.Accessory = accessorySender; modifyViewController.Delegate = this; } @@ -337,7 +333,7 @@ public void DidFindNewAccessory (HMAccessoryBrowser browser, HMAccessory accesso var newIndex = displayedAccessories.IndexOf (newAccessory); if (newIndex >= 0) { var newIndexPath = NSIndexPath.FromRowSection (newIndex, 0); - TableView.InsertRows (new []{ newIndexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new [] { newIndexPath }, UITableViewRowAnimation.Automatic); } } @@ -352,7 +348,7 @@ public void DidRemoveNewAccessory (HMAccessoryBrowser browser, HMAccessory acces var removedIndexPath = NSIndexPath.FromRowSection (removedIndex, 0); displayedAccessories.RemoveAt (removedIndex); - TableView.DeleteRows (new []{ removedIndexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new [] { removedIndexPath }, UITableViewRowAnimation.Automatic); } #endregion diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryUpdateController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryUpdateController.cs index 9926f3354..f084e090f 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryUpdateController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/AccessoryUpdateController.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using CoreFoundation; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // An object that responds to `CharacteristicCell` updates and notifies HomeKit of changes. // TODO: do we need NSObject here? - public class AccessoryUpdateController : NSObject, ICharacteristicCellDelegate - { + public class AccessoryUpdateController : NSObject, ICharacteristicCellDelegate { readonly DispatchQueue updateQueue = new DispatchQueue ("CharacteristicUpdateQueue"); readonly Dictionary<HMCharacteristic, NSObject> pendingWrites = new Dictionary<HMCharacteristic, NSObject> (); readonly Dictionary<HMCharacteristic, NSObject> sentWrites = new Dictionary<HMCharacteristic, NSObject> (); @@ -87,7 +85,7 @@ void UpdateCharacteristics () } // Synchronously adds the characteristic-value pair into the `sentWrites` map. - void DidSendWrite (HMCharacteristic characteristic, NSObject value) + void DidSendWrite (HMCharacteristic characteristic, NSObject value) { updateQueue.DispatchSync (() => { sentWrites [characteristic] = value; @@ -101,4 +99,4 @@ void DidCompleteWrite (HMCharacteristic characteristic, NSObject value) } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsTableViewDataSource.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsTableViewDataSource.cs index 5e7bbdddd..e48b88a2e 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsTableViewDataSource.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsTableViewDataSource.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,16 +6,14 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewDataSource` that populates the table in `ControlsViewController`. - public class ControlsTableViewDataSource: UITableViewDataSource - { - static readonly NSString serviceCell = (NSString)"ServiceCell"; - static readonly NSString unreachableServiceCell = (NSString)"UnreachableServiceCell"; + public class ControlsTableViewDataSource : UITableViewDataSource { + static readonly NSString serviceCell = (NSString) "ServiceCell"; + static readonly NSString unreachableServiceCell = (NSString) "UnreachableServiceCell"; Dictionary<string, List<HMService>> serviceTable; - string[] sortedKeys; + string [] sortedKeys; UITableView tableView; @@ -50,7 +48,7 @@ public void ReloadTable () public override string TitleForHeader (UITableView tableView, nint section) { - return sortedKeys != null ? sortedKeys [(int)section] : null; + return sortedKeys != null ? sortedKeys [(int) section] : null; } public override nint NumberOfSections (UITableView tableView) @@ -73,7 +71,7 @@ public string EmptyMessage () public override nint RowsInSection (UITableView tableView, nint section) { - return serviceTable [sortedKeys [(int)section]].Count; + return serviceTable [sortedKeys [(int) section]].Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) @@ -81,7 +79,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde var service = ServiceForIndexPath (indexPath); var reuseIdentifier = service.Accessory.Reachable ? serviceCell : unreachableServiceCell; - var cell = (ServiceCell)tableView.DequeueReusableCell (reuseIdentifier, indexPath); + var cell = (ServiceCell) tableView.DequeueReusableCell (reuseIdentifier, indexPath); cell.Service = service; return cell; @@ -99,4 +97,4 @@ public HMService ServiceForIndexPath (NSIndexPath indexPath) return null; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsViewController.cs index 0552aca6c..ad92e8f25 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ControlsViewController.cs @@ -4,11 +4,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller which displays a list of `HMServices`, separated by Service Type. - public partial class ControlsViewController : HMCatalogViewController, IHMAccessoryDelegate - { + public partial class ControlsViewController : HMCatalogViewController, IHMAccessoryDelegate { const string ShowServiceSegue = "Show Service"; readonly AccessoryUpdateController cellController = new AccessoryUpdateController (); @@ -37,9 +35,9 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); if (segue.Identifier == ShowServiceSegue) { - var indexPath = TableView.IndexPathForCell ((UITableViewCell)sender); + var indexPath = TableView.IndexPathForCell ((UITableViewCell) sender); if (indexPath != null) { - var characteristicsViewController = (CharacteristicsViewController)segue.IntendedDestinationViewController (); + var characteristicsViewController = (CharacteristicsViewController) segue.IntendedDestinationViewController (); var selectedService = tableViewDataSource.ServiceForIndexPath (indexPath); if (selectedService != null) characteristicsViewController.Service = selectedService; diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ModifyAccessoryViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ModifyAccessoryViewController.cs index 8f93de316..6e7876fe5 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ModifyAccessoryViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/ModifyAccessoryViewController.cs @@ -6,25 +6,21 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents the sections in the `ModifyAccessoryViewController`. - public enum AddAccessoryTableViewSection - { + public enum AddAccessoryTableViewSection { Name, Rooms, Identify } - public interface IModifyAccessoryDelegate - { + public interface IModifyAccessoryDelegate { void AccessoryViewControllerDidSaveAccessory (ModifyAccessoryViewController accessoryViewController, HMAccessory accessory); } // A view controller that allows for renaming, reassigning, and identifying accessories before and after they've been added to a home. - public partial class ModifyAccessoryViewController : HMCatalogViewController, IHMAccessoryDelegate - { - static readonly NSString RoomCell = (NSString)"RoomCell"; + public partial class ModifyAccessoryViewController : HMCatalogViewController, IHMAccessoryDelegate { + static readonly NSString RoomCell = (NSString) "RoomCell"; // Update this if the acessory failed in any way. bool didEncounterError; @@ -97,7 +93,7 @@ public override void ViewDidLoad () ResetNameField (); // Register a cell for the rooms. - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), RoomCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), RoomCell); } // Registers as the delegate for the current home and the accessory. @@ -249,12 +245,12 @@ void NameFieldDidChange (NSObject sender) public override nint NumberOfSections (UITableView tableView) { - return Enum.GetNames (typeof(AddAccessoryTableViewSection)).Length; + return Enum.GetNames (typeof (AddAccessoryTableViewSection)).Length; } public override nint RowsInSection (UITableView tableView, nint section) { - switch ((AddAccessoryTableViewSection)(int)section) { + switch ((AddAccessoryTableViewSection) (int) section) { case AddAccessoryTableViewSection.Rooms: return Home.GetAllRooms ().Length; case AddAccessoryTableViewSection.Identify: @@ -267,7 +263,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { - switch ((AddAccessoryTableViewSection)indexPath.Section) { + switch ((AddAccessoryTableViewSection) indexPath.Section) { case AddAccessoryTableViewSection.Rooms: return UITableView.AutomaticDimension; case AddAccessoryTableViewSection.Identify: @@ -280,7 +276,7 @@ public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath index public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - switch ((AddAccessoryTableViewSection)indexPath.Section) { + switch ((AddAccessoryTableViewSection) indexPath.Section) { case AddAccessoryTableViewSection.Rooms: return GetCellForRoom (tableView, indexPath); case AddAccessoryTableViewSection.Identify: @@ -309,13 +305,13 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { tableView.DeselectRow (indexPath, true); - switch ((AddAccessoryTableViewSection)indexPath.Section) { + switch ((AddAccessoryTableViewSection) indexPath.Section) { case AddAccessoryTableViewSection.Rooms: if (!Home.IsAdmin ()) return; selectedRoom = Home.GetAllRooms () [indexPath.Row]; - var sections = NSIndexSet.FromIndex ((nint)(int)AddAccessoryTableViewSection.Rooms); + var sections = NSIndexSet.FromIndex ((nint) (int) AddAccessoryTableViewSection.Rooms); tableView.ReloadSections (sections, UITableViewRowAnimation.Automatic); break; case AddAccessoryTableViewSection.Identify: diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/CharacteristicCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/CharacteristicCell.cs index 6519bc4ad..9b4995d53 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/CharacteristicCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/CharacteristicCell.cs @@ -1,18 +1,16 @@ -using System; +using System; using CoreGraphics; using Foundation; using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewCell` subclass that displays the current value of an `HMCharacteristic` and // notifies its delegate of changes. Subclasses of this class will provide additional controls // to display different kinds of data. [Register ("CharacteristicCell")] - public class CharacteristicCell : UITableViewCell - { + public class CharacteristicCell : UITableViewCell { // An alpha percentage used when disabling cells. protected readonly nfloat DisabledAlpha = 0.4f; @@ -106,7 +104,7 @@ public virtual HMCharacteristic Characteristic { TypeLabel.Alpha = alpha; var lable = ValueLabel; - if(lable != null) + if (lable != null) ValueLabel.Alpha = alpha; if (Enabled) { @@ -166,4 +164,4 @@ public virtual void SetValue (NSObject newValue, bool notify) } } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/ICharacteristicCellDelegate.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/ICharacteristicCellDelegate.cs index 905483583..ec8bc1921 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/ICharacteristicCellDelegate.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/ICharacteristicCellDelegate.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ - public interface ICharacteristicCellDelegate - { +namespace HomeKitCatalog { + public interface ICharacteristicCellDelegate { // Called whenever the control within the cell updates its value. // // parameter cell: The cell which has updated its value. @@ -26,4 +24,4 @@ public interface ICharacteristicCellDelegate // parameter completion: The closure that the cell provides to be called when values have been read successfully. void CharacteristicCellReadInitialValueForCharacteristic (CharacteristicCell cell, HMCharacteristic characteristic, Action<NSObject, NSError> completion); } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SegmentedControlCharacteristicCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SegmentedControlCharacteristicCell.cs index 55b1ab97e..5a2d35dd1 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SegmentedControlCharacteristicCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SegmentedControlCharacteristicCell.cs @@ -1,17 +1,15 @@ -using System; +using System; using CoreGraphics; using Foundation; using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `CharacteristicCell` subclass that contains a `UISegmentedControl`. // Used for `HMCharacteristic`s which have associated, non-numeric values, like Lock Management State. [Register ("SegmentedControlCharacteristicCell")] - public class SegmentedControlCharacteristicCell : CharacteristicCell - { + public class SegmentedControlCharacteristicCell : CharacteristicCell { [Outlet ("segmentedControl")] UISegmentedControl SegmentedControl { get; set; } @@ -34,8 +32,8 @@ public override HMCharacteristic Characteristic { // The possible values for this characteristic. // When this is set, adds localized descriptions to the segmented control. - int[] possibleValues = new int[0]; - int[] PossibleValues { + int [] possibleValues = new int [0]; + int [] PossibleValues { get { return possibleValues; } @@ -71,11 +69,11 @@ public SegmentedControlCharacteristicCell (NSCoder coder) // Responds to the segmented control's segment changing. // Sets the value and notifies its delegate. - [Export("segmentedControlDidChange:")] - void segmentedControlDidChange(UISegmentedControl sender) + [Export ("segmentedControlDidChange:")] + void segmentedControlDidChange (UISegmentedControl sender) { - var value = possibleValues [(int)sender.SelectedSegment]; - SetValue (new NSNumber(value), true); + var value = possibleValues [(int) sender.SelectedSegment]; + SetValue (new NSNumber (value), true); } // If notify is false, then this is an external change, @@ -101,4 +99,4 @@ void ResetSelectedIndex () SegmentedControl.SelectedSegment = index; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SliderCharacteristicCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SliderCharacteristicCell.cs index 3fd26ea55..d35c32ce6 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SliderCharacteristicCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SliderCharacteristicCell.cs @@ -1,17 +1,15 @@ -using System; +using System; using CoreGraphics; using Foundation; using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `CharacteristicCell` subclass that contains a slider. // Used for numeric characteristics that have a continuous range of options. [Register ("SliderCharacteristicCell")] - public class SliderCharacteristicCell : CharacteristicCell - { + public class SliderCharacteristicCell : CharacteristicCell { [Outlet ("valueSlider")] public UISlider ValueSlider { get; set; } @@ -28,7 +26,7 @@ public override HMCharacteristic Characteristic { set { // These are sane defaults in case the max and min are not set. HMCharacteristicMetadata metadata; - if(value != null && (metadata = value.Metadata) != null) { + if (value != null && (metadata = value.Metadata) != null) { ValueSlider.MinValue = metadata.MinimumValue.FloatValue; ValueSlider.MaxValue = metadata.MaximumValue.FloatValue; } else { @@ -84,7 +82,7 @@ float RoundedValueForSliderValue (float value) float stepValue = metadata.StepValue.FloatValue; if (stepValue > 0) { - var newStep = (float)Math.Round (value / stepValue); + var newStep = (float) Math.Round (value / stepValue); var stepped = newStep * stepValue; return stepped; } @@ -99,4 +97,4 @@ void DidChangeSliderValue (UISlider slider) SetValue (new NSNumber (value), true); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SwitchCharacteristicCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SwitchCharacteristicCell.cs index 0ec8453e6..b01dd4d4b 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SwitchCharacteristicCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/SwitchCharacteristicCell.cs @@ -1,16 +1,14 @@ -using System; +using System; using CoreGraphics; using Foundation; using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `CharacteristicCell` subclass that contains a single switch. Used for Boolean characteristics. - [Register("SwitchCharacteristicCell")] - public class SwitchCharacteristicCell : CharacteristicCell - { + [Register ("SwitchCharacteristicCell")] + public class SwitchCharacteristicCell : CharacteristicCell { [Outlet ("valueSwitch")] public UISwitch ValueSwitch { get; set; } @@ -64,4 +62,4 @@ void DidChangeSwitchValue (UISwitch valueSwitch) SetValue (new NSNumber (valueSwitch.On), true); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/TextCharacteristicCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/TextCharacteristicCell.cs index af9984eee..b706fbddf 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/TextCharacteristicCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicCells/TextCharacteristicCell.cs @@ -1,15 +1,13 @@ -using System; +using System; using CoreGraphics; using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `CharacteristicCell` subclass that contains a text field. Used for text-input characteristics. [Register ("TextCharacteristicCell")] - public class TextCharacteristicCell : CharacteristicCell, IUITextFieldDelegate - { + public class TextCharacteristicCell : CharacteristicCell, IUITextFieldDelegate { [Outlet ("textField")] public UITextField TextField { get; set; } @@ -68,7 +66,7 @@ public bool ShouldReturn (UITextField textField) [Export ("textFieldDidEndEditing:")] public void EditingEnded (UITextField textField) { - SetValue ((NSString)TextField.Text, true); + SetValue ((NSString) TextField.Text, true); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsTableViewDataSource.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsTableViewDataSource.cs index 6b9ccd173..94e485b98 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsTableViewDataSource.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsTableViewDataSource.cs @@ -1,33 +1,30 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { /// Represents the sections in the `CharacteristicsViewController`. - public enum CharacteristicTableViewSection - { + public enum CharacteristicTableViewSection { Characteristics, AssociatedServiceType } /// A `UITableViewDataSource` that populates a `CharacteristicsViewController`. - public class CharacteristicsTableViewDataSource : NSObject, IUITableViewDelegate, IUITableViewDataSource - { + public class CharacteristicsTableViewDataSource : NSObject, IUITableViewDelegate, IUITableViewDataSource { static readonly Dictionary<HMServiceType, string> serviceMap = new Dictionary<HMServiceType, string> { { HMServiceType.LightBulb, "Lightbulb" }, { HMServiceType.Fan, "Fan" } }; - static readonly NSString characteristicCell = (NSString)"CharacteristicCell"; - static readonly NSString sliderCharacteristicCell = (NSString)"SliderCharacteristicCell"; - static readonly NSString switchCharacteristicCell = (NSString)"SwitchCharacteristicCell"; - static readonly NSString segmentedControlCharacteristicCell = (NSString)"SegmentedControlCharacteristicCell"; - static readonly NSString textCharacteristicCell = (NSString)"TextCharacteristicCell"; - static readonly NSString serviceTypeCell = (NSString)"ServiceTypeCell"; + static readonly NSString characteristicCell = (NSString) "CharacteristicCell"; + static readonly NSString sliderCharacteristicCell = (NSString) "SliderCharacteristicCell"; + static readonly NSString switchCharacteristicCell = (NSString) "SwitchCharacteristicCell"; + static readonly NSString segmentedControlCharacteristicCell = (NSString) "SegmentedControlCharacteristicCell"; + static readonly NSString textCharacteristicCell = (NSString) "TextCharacteristicCell"; + static readonly NSString serviceTypeCell = (NSString) "ServiceTypeCell"; ICharacteristicCellDelegate Delegate; bool showsFavorites; @@ -35,7 +32,7 @@ public class CharacteristicsTableViewDataSource : NSObject, IUITableViewDelegate // returns: The valid associated service types for this service, // e.g. `HMServiceTypeFan` or `HMServiceTypeLightbulb` - public static readonly HMServiceType[] ValidAssociatedServiceTypes = { + public static readonly HMServiceType [] ValidAssociatedServiceTypes = { HMServiceType.Fan, HMServiceType.LightBulb }; @@ -73,7 +70,7 @@ static void RegisterReuseIdentifiers (UITableView tableView) var textNib = UINib.FromName (textCharacteristicCell, null); tableView.RegisterNibForCellReuse (textNib, textCharacteristicCell); - tableView.RegisterClassForCellReuse (typeof(UITableViewCell), serviceTypeCell); + tableView.RegisterClassForCellReuse (typeof (UITableViewCell), serviceTypeCell); } [Foundation.Export ("numberOfSectionsInTableView:")] @@ -86,7 +83,7 @@ public nint NumberOfSections (UITableView tableView) // The associated service type uses the valid associated service types. public nint RowsInSection (UITableView tableView, nint section) { - switch ((CharacteristicTableViewSection)(int)section) { + switch ((CharacteristicTableViewSection) (int) section) { case CharacteristicTableViewSection.Characteristics: return Service.Characteristics.Length; case CharacteristicTableViewSection.AssociatedServiceType: @@ -150,7 +147,7 @@ UITableViewCell GetCellForCharacteristicCell (UITableView tableView, NSIndexPath else if (characteristic.IsTextWritable ()) reuseIdentifier = textCharacteristicCell; - var cell = (CharacteristicCell)tableView.DequeueReusableCell(reuseIdentifier, indexPath); + var cell = (CharacteristicCell) tableView.DequeueReusableCell (reuseIdentifier, indexPath); cell.ShowsFavorites = showsFavorites; cell.Delegate = Delegate; @@ -162,7 +159,7 @@ UITableViewCell GetCellForCharacteristicCell (UITableView tableView, NSIndexPath // Uses convenience methods to generate a cell based on the index path's section. public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - switch ((CharacteristicTableViewSection)indexPath.Section) { + switch ((CharacteristicTableViewSection) indexPath.Section) { case CharacteristicTableViewSection.Characteristics: return GetCellForCharacteristicCell (tableView, indexPath); case CharacteristicTableViewSection.AssociatedServiceType: @@ -175,7 +172,7 @@ public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) [Export ("tableView:titleForHeaderInSection:")] public string TitleForHeader (UITableView tableView, nint section) { - switch ((CharacteristicTableViewSection)(int)section) { + switch ((CharacteristicTableViewSection) (int) section) { case CharacteristicTableViewSection.Characteristics: return "Characteristics"; case CharacteristicTableViewSection.AssociatedServiceType: @@ -191,4 +188,4 @@ static string DescriptionForServiceType (HMServiceType type) return serviceMap.TryGetValue (type, out description) ? description : type.ToString (); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsViewController.cs index 1df98e756..b3bde01f5 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/CharacteristicsViewController.cs @@ -4,11 +4,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller that displays a list of characteristics within an `HMService`. - public partial class CharacteristicsViewController : HMCatalogViewController, IHMAccessoryDelegate - { + public partial class CharacteristicsViewController : HMCatalogViewController, IHMAccessoryDelegate { CharacteristicsTableViewDataSource tableViewDataSource; public HMService Service { get; set; } @@ -79,7 +77,7 @@ void SetNotificationsEnabled (bool notificationsEnabled) } // Reloads the table view and stops the refresh control. - [Export("reloadTableView")] + [Export ("reloadTableView")] void ReloadTableView () { SetNotificationsEnabled (true); @@ -94,7 +92,7 @@ void ReloadTableView () public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { - switch ((CharacteristicTableViewSection)indexPath.Section) { + switch ((CharacteristicTableViewSection) indexPath.Section) { case CharacteristicTableViewSection.Characteristics: var characteristic = Service.Characteristics [indexPath.Row]; DidSelectCharacteristic (characteristic, indexPath); @@ -123,7 +121,7 @@ void DidSelectCharacteristic (HMCharacteristic characteristic, NSIndexPath index // Handles selection of one of the associated service types in the list. void DidSelectAssociatedServiceTypeAtIndexPath (NSIndexPath indexPath) { - HMServiceType[] serviceTypes = CharacteristicsTableViewDataSource.ValidAssociatedServiceTypes; + HMServiceType [] serviceTypes = CharacteristicsTableViewDataSource.ValidAssociatedServiceTypes; HMServiceType newServiceType = HMServiceType.None; if (indexPath.Row < serviceTypes.Length) newServiceType = serviceTypes [indexPath.Row]; @@ -142,7 +140,7 @@ void DidSelectAssociatedServiceTypeAtIndexPath (NSIndexPath indexPath) // Reloads the associated service section in the table view. void DidUpdateAssociatedServiceType () { - var associatedServiceTypeIndexSet = new NSIndexSet ((nuint)(int)CharacteristicTableViewSection.AssociatedServiceType); + var associatedServiceTypeIndexSet = new NSIndexSet ((nuint) (int) CharacteristicTableViewSection.AssociatedServiceType); TableView.ReloadSections (associatedServiceTypeIndexSet, UITableViewRowAnimation.Automatic); } @@ -177,7 +175,7 @@ public void DidUpdateValueForCharacteristic (HMAccessory accessory, HMService se var index = Array.IndexOf (service.Characteristics, characteristic); if (index >= 0) { var indexPath = NSIndexPath.FromRowSection (index, 0); - var cell = (CharacteristicCell)TableView.CellAt (indexPath); + var cell = (CharacteristicCell) TableView.CellAt (indexPath); cell.SetValue (characteristic.Value, false); } } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServiceCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServiceCell.cs index 87cea71c0..c66137990 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServiceCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServiceCell.cs @@ -5,11 +5,9 @@ using UIKit; using CoreGraphics; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewCell` subclass for displaying a service and the room and accessory where it resides. - public partial class ServiceCell : UITableViewCell - { + public partial class ServiceCell : UITableViewCell { public bool IncludeAccessoryText { get; set; } HMService service; @@ -62,4 +60,4 @@ void Initialize () IncludeAccessoryText = true; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServicesViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServicesViewController.cs index 4b25c51ec..076b67afe 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServicesViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Accessories/Services/ServicesViewController.cs @@ -6,19 +6,16 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ - public enum AccessoryTableViewSection - { +namespace HomeKitCatalog { + public enum AccessoryTableViewSection { Services, BridgedAccessories } // A view controller which displays all the services of a provided accessory, and passes its cell delegate onto a `CharacteristicsViewController`. - public partial class ServicesViewController : HMCatalogViewController, IHMAccessoryDelegate - { - static readonly NSString AccessoryCell = (NSString)"AccessoryCell"; - static readonly NSString ServiceCell = (NSString)"ServiceCell"; + public partial class ServicesViewController : HMCatalogViewController, IHMAccessoryDelegate { + static readonly NSString AccessoryCell = (NSString) "AccessoryCell"; + static readonly NSString ServiceCell = (NSString) "ServiceCell"; static readonly string ShowServiceSegue = "Show Service"; List<HMService> displayedServices = new List<HMService> (); @@ -83,12 +80,12 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (segue.Identifier != ShowServiceSegue) return; - var indexPath = TableView.IndexPathForCell ((UITableViewCell)sender); + var indexPath = TableView.IndexPathForCell ((UITableViewCell) sender); if (indexPath == null) return; var selectedService = displayedServices [indexPath.Row]; - var characteristicsViewController = (CharacteristicsViewController)segue.IntendedDestinationViewController (); + var characteristicsViewController = (CharacteristicsViewController) segue.IntendedDestinationViewController (); characteristicsViewController.ShowsFavorites = ShowsFavorites; characteristicsViewController.AllowsAllWrites = AllowsAllWrites; characteristicsViewController.Service = selectedService; @@ -128,7 +125,7 @@ public override nint NumberOfSections (UITableView tableView) // Section 2 contains the bridged accessories. public override nint RowsInSection (UITableView tableView, nint section) { - switch ((AccessoryTableViewSection)(int)section) { + switch ((AccessoryTableViewSection) (int) section) { case AccessoryTableViewSection.Services: return displayedServices.Count; case AccessoryTableViewSection.BridgedAccessories: @@ -141,7 +138,7 @@ public override nint RowsInSection (UITableView tableView, nint section) // returns: A Service or Bridged Accessory Cell based on the section. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - switch ((AccessoryTableViewSection)indexPath.Section) { + switch ((AccessoryTableViewSection) indexPath.Section) { case AccessoryTableViewSection.Services: return GetServiceCell (tableView, indexPath); case AccessoryTableViewSection.BridgedAccessories: @@ -178,7 +175,7 @@ UITableViewCell GetServiceCell (UITableView tableView, NSIndexPath indexPath) public override string TitleForHeader (UITableView tableView, nint section) { - switch ((AccessoryTableViewSection)(int)section) { + switch ((AccessoryTableViewSection) (int) section) { case AccessoryTableViewSection.Services: return "Services"; case AccessoryTableViewSection.BridgedAccessories: @@ -191,7 +188,7 @@ public override string TitleForHeader (UITableView tableView, nint section) // returns: A description of the accessories bridged status. public override string TitleForFooter (UITableView tableView, nint section) { - if (Accessory.Bridged && (AccessoryTableViewSection)(int)section == AccessoryTableViewSection.Services) { + if (Accessory.Bridged && (AccessoryTableViewSection) (int) section == AccessoryTableViewSection.Services) { var bridge = Home.BridgeForAccessory (Accessory); return bridge != null ? string.Format ("This accessory is being bridged into HomeKit by {0}.", bridge.Name) : @@ -226,7 +223,7 @@ void ReloadData () displayedServices.AddRange (filtered); } - NSUuid[] identifiers = Accessory.UniqueIdentifiersForBridgedAccessories; + NSUuid [] identifiers = Accessory.UniqueIdentifiersForBridgedAccessories; if (identifiers != null) { bridgedAccessories.Clear (); bridgedAccessories.AddRange (Home.AccessoriesWithIdentifiers (new HashSet<NSUuid> (identifiers))); @@ -252,8 +249,8 @@ public void DidUpdateNameForService (HMAccessory accessory, HMService service) { var index = displayedServices.IndexOf (service); if (index >= 0) { - var path = NSIndexPath.FromRowSection (index, (int)AccessoryTableViewSection.Services); - TableView.ReloadRows (new []{ path }, UITableViewRowAnimation.Automatic); + var path = NSIndexPath.FromRowSection (index, (int) AccessoryTableViewSection.Services); + TableView.ReloadRows (new [] { path }, UITableViewRowAnimation.Automatic); } } @@ -273,4 +270,4 @@ public void DidUpdateReachability (HMAccessory accessory) #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionCell.cs index 483538732..b57555145 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionCell.cs @@ -5,11 +5,9 @@ using CoreGraphics; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewCell` subclass that displays a characteristic's 'target value'. - public partial class ActionCell : UITableViewCell - { + public partial class ActionCell : UITableViewCell { public ActionCell (UITableViewCellStyle style, string reuseId) : base (UITableViewCellStyle.Subtitle, reuseId) { diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetCreator.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetCreator.cs index af9fd350b..5b64a398b 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetCreator.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetCreator.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,11 +6,9 @@ using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `CharacteristicCellDelegate` that builds an `HMActionSet` when it receives delegate callbacks. - public class ActionSetCreator : ICharacteristicCellDelegate - { + public class ActionSetCreator : ICharacteristicCellDelegate { HMActionSet ActionSet { get; set; } HMHome Home { get; set; } @@ -98,7 +96,7 @@ void CreateActionSetWithName (string name) // as the action passed in. If such an action exists, the method tells the // existing action to update its target value. Otherwise, the new action is // simply added to the action set. - void AddAction (HMCharacteristicWriteAction action, HMActionSet actionSet, Action<NSError>completion) + void AddAction (HMCharacteristicWriteAction action, HMActionSet actionSet, Action<NSError> completion) { var existingAction = ExistingActionInActionSetMatchingAction (action); if (existingAction != null) @@ -113,7 +111,7 @@ HMCharacteristicWriteAction ExistingActionInActionSetMatchingAction (HMCharacter { var actionSet = ActionSet; if (actionSet != null) { - foreach (var existingAction in actionSet.Actions.Cast<HMCharacteristicWriteAction>()) { + foreach (var existingAction in actionSet.Actions.Cast<HMCharacteristicWriteAction> ()) { if (action.Characteristic == existingAction.Characteristic) return existingAction; } @@ -123,7 +121,7 @@ HMCharacteristicWriteAction ExistingActionInActionSetMatchingAction (HMCharacter // Iterates over a map table of HMCharacteristic -> object and creates // an array of HMCharacteristicWriteActions based on those targets. - HMCharacteristicWriteAction[] ActionsFromMapTable () + HMCharacteristicWriteAction [] ActionsFromMapTable () { return targetValueMap.Keys.Select (characteristic => { NSObject targetValue = targetValueMap [characteristic]; @@ -139,7 +137,7 @@ public bool ContainsActions { } // All existing characteristics within `HMCharacteristiWriteActions` and target values in the target value map. - public HMCharacteristic[] AllCharacteristics () + public HMCharacteristic [] AllCharacteristics () { var characteristics = new HashSet<HMCharacteristic> (); diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetViewController.cs index 7b32416e7..ebae140db 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/ActionSets/ActionSetViewController.cs @@ -6,11 +6,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents table view sections of the `ActionSetViewController`. - public enum ActionSetTableViewSection - { + public enum ActionSetTableViewSection { Name, Actions, Accessories @@ -20,11 +18,10 @@ public enum ActionSetTableViewSection // It contains a cell for a name, and lists accessories within a home. // If there are actions within the action set, it also displays a list of ActionCells displaying those actions. // It owns an `ActionSetCreator` and routes events to the creator as appropriate. - public partial class ActionSetViewController : HMCatalogViewController - { - static readonly NSString accessoryCell = (NSString)"AccessoryCell"; - static readonly NSString unreachableAccessoryCell = (NSString)"UnreachableAccessoryCell"; - static readonly NSString actionCell = (NSString)"ActionCell"; + public partial class ActionSetViewController : HMCatalogViewController { + static readonly NSString accessoryCell = (NSString) "AccessoryCell"; + static readonly NSString unreachableAccessoryCell = (NSString) "UnreachableAccessoryCell"; + static readonly NSString actionCell = (NSString) "ActionCell"; const string showServiceSegue = "Show Services"; [Outlet ("nameField")] @@ -62,9 +59,9 @@ public override void ViewDidLoad () displayedAccessories.Clear (); displayedAccessories.AddRange (Home.SortedControlAccessories ()); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), accessoryCell); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), unreachableAccessoryCell); - TableView.RegisterClassForCellReuse (typeof(ActionCell), actionCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), accessoryCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), unreachableAccessoryCell); + TableView.RegisterClassForCellReuse (typeof (ActionCell), actionCell); TableView.RowHeight = UITableView.AutomaticDimension; @@ -104,11 +101,11 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) base.PrepareForSegue (segue, sender); if (segue.Identifier == showServiceSegue) { - var servicesViewController = (ServicesViewController)segue.IntendedDestinationViewController (); + var servicesViewController = (ServicesViewController) segue.IntendedDestinationViewController (); servicesViewController.OnlyShowsControlServices = true; servicesViewController.CellDelegate = ActionSetCreator; - var index = TableView.IndexPathForCell ((UITableViewCell)sender).Row; + var index = TableView.IndexPathForCell ((UITableViewCell) sender).Row; servicesViewController.Accessory = displayedAccessories [index]; } } @@ -159,7 +156,7 @@ public override nint NumberOfSections (UITableView tableView) // In the Accessories section: The number of accessories in the home. public override nint RowsInSection (UITableView tableView, nint section) { - switch ((ActionSetTableViewSection)(int)section) { + switch ((ActionSetTableViewSection) (int) section) { case ActionSetTableViewSection.Name: return base.RowsInSection (tableView, section); case ActionSetTableViewSection.Actions: @@ -186,9 +183,9 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE var characteristic = ActionSetCreator.AllCharacteristics () [indexPath.Row]; ActionSetCreator.RemoveTargetValueForCharacteristic (characteristic, () => { if (ActionSetCreator.ContainsActions) - tableView.DeleteRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); else - tableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); }); } } @@ -196,13 +193,13 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE // returns: `true` for the Actions section; `false` otherwise. public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { - return (ActionSetTableViewSection)indexPath.Section == ActionSetTableViewSection.Actions && Home.IsAdmin (); + return (ActionSetTableViewSection) indexPath.Section == ActionSetTableViewSection.Actions && Home.IsAdmin (); } // returns: `UITableViewAutomaticDimension` for dynamic sections, otherwise the superclass's implementation. public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { - switch ((ActionSetTableViewSection)indexPath.Section) { + switch ((ActionSetTableViewSection) indexPath.Section) { case ActionSetTableViewSection.Name: return base.GetHeightForRow (tableView, indexPath); case ActionSetTableViewSection.Actions: @@ -216,7 +213,7 @@ public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath index // returns: An action cell for the actions section, an accessory cell for the accessory section, or the superclass's implementation. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - switch ((ActionSetTableViewSection)indexPath.Section) { + switch ((ActionSetTableViewSection) indexPath.Section) { case ActionSetTableViewSection.Name: return base.GetCell (tableView, indexPath); case ActionSetTableViewSection.Actions: @@ -260,12 +257,12 @@ bool ShouldPopViewController () // - returns: An `ActionCell` instance with the target value for the characteristic at the specified index path. UITableViewCell GetActionCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (ActionCell)tableView.DequeueReusableCell (actionCell, indexPath); + var cell = (ActionCell) tableView.DequeueReusableCell (actionCell, indexPath); var characteristic = ActionSetCreator.AllCharacteristics () [indexPath.Row]; NSObject target = ActionSetCreator.TargetValueForCharacteristic (characteristic); if (target != null) - cell.SetCharacteristic (characteristic, (NSNumber)target); + cell.SetCharacteristic (characteristic, (NSNumber) target); return cell; } @@ -305,7 +302,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) if (cell.SelectionStyle == UITableViewCellSelectionStyle.None) return; - if ((ActionSetTableViewSection)indexPath.Section == ActionSetTableViewSection.Accessories) + if ((ActionSetTableViewSection) indexPath.Section == ActionSetTableViewSection.Accessories) PerformSegue (showServiceSegue, cell); } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesManager.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesManager.cs index a041d342d..eeb88cc0c 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesManager.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesManager.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Handles interactions with `NSUserDefault`s to save the user's favorite accessories. - public class FavoritesManager - { + public class FavoritesManager { const string accessoryToCharacteristicIdentifierMappingKey = "FavoritesManager.accessoryToCharacteristicIdentifierMappingKey"; const string accessoryIdentifiersKey = "FavoritesManager.accessoryIdentifiersKey"; @@ -38,7 +36,7 @@ static HMHomeManager HomeManager { } } - static HMHome[] Homes { + static HMHome [] Homes { get { return HomeManager.Homes; } @@ -53,13 +51,13 @@ static HMHome[] Homes { var rawDictionary = NSKeyedUnarchiver.UnarchiveObject (mapData) as NSDictionary; if (rawDictionary != null) { foreach (var kvp in rawDictionary) - accessoryToCharacteristicIdentifiers [(NSUuid)kvp.Key] = new List<NSUuid> (NSArray.FromArray<NSUuid> ((NSArray)kvp.Value)); + accessoryToCharacteristicIdentifiers [(NSUuid) kvp.Key] = new List<NSUuid> (NSArray.FromArray<NSUuid> ((NSArray) kvp.Value)); } } } // returns: An array of all favorite characteristics. The array is sorted by localized type. - public HMCharacteristic[] FavoriteCharacteristics () + public HMCharacteristic [] FavoriteCharacteristics () { // Find all of the favorite characteristics. var favoriteCharacteristics = Homes.SelectMany (home => { @@ -71,11 +69,11 @@ public HMCharacteristic[] FavoriteCharacteristics () } // returns: An array of all favorite accessories. The array is sorted by localized name. - public HMAccessory[] FavoriteAccessories () + public HMAccessory [] FavoriteAccessories () { var ids = new HashSet<NSUuid> (accessoryToCharacteristicIdentifiers.Keys); - HMAccessory[] allAccessories = Homes.SelectMany (h => h.Accessories) + HMAccessory [] allAccessories = Homes.SelectMany (h => h.Accessories) .Where (a => ids.Contains (a.UniqueIdentifier)) .ToArray (); @@ -85,11 +83,11 @@ public HMAccessory[] FavoriteAccessories () // returns: An array of tuples representing accessories and all favorite characteristics they contain. // The array is sorted by localized type. - public Tuple<HMAccessory, HMCharacteristic[]>[] FavoriteGroups () + public Tuple<HMAccessory, HMCharacteristic []> [] FavoriteGroups () { return FavoriteAccessories ().Select (a => { var characteristics = FavoriteCharacteristicsForAccessory (a); - return new Tuple<HMAccessory, HMCharacteristic[]> (a, characteristics); + return new Tuple<HMAccessory, HMCharacteristic []> (a, characteristics); }).ToArray (); } @@ -139,7 +137,7 @@ public void FavoriteCharacteristic (HMCharacteristic characteristic) } // Provides an array of favorite `HMCharacteristic`s within a given accessory. - public HMCharacteristic[] FavoriteCharacteristicsForAccessory (HMAccessory accessory) + public HMCharacteristic [] FavoriteCharacteristicsForAccessory (HMAccessory accessory) { var result = accessory.Services .SelectMany (s => s.Characteristics) @@ -212,7 +210,7 @@ static NSDictionary Convert (Dictionary<NSUuid, List<NSUuid>> dictionary) { var result = new NSMutableDictionary (); foreach (var kvp in dictionary) { - NSUuid[] array = kvp.Value.ToArray (); + NSUuid [] array = kvp.Value.ToArray (); var nativeArray = NSArray.FromNSObjects (array); result.Add (kvp.Key, nativeArray); } @@ -230,4 +228,4 @@ static int CharacteristicOrderedBefore (HMCharacteristic characteristic1, HMChar return type1.CompareTo (type2); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesViewController.cs index 381019183..6115ca6f0 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Favorites/FavoritesViewController.cs @@ -4,19 +4,17 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Lists favorite characteristics (grouped by accessory) and allows users to manipulate their values. - partial class FavoritesViewController : UITableViewController, IUITabBarControllerDelegate, IHMAccessoryDelegate, IHMHomeManagerDelegate - { - static readonly NSString characteristicCell = (NSString)"CharacteristicCell"; - static readonly NSString segmentedControlCharacteristicCell = (NSString)"SegmentedControlCharacteristicCell"; - static readonly NSString switchCharacteristicCell = (NSString)"SwitchCharacteristicCell"; - static readonly NSString sliderCharacteristicCell = (NSString)"SliderCharacteristicCell"; - static readonly NSString textCharacteristicCell = (NSString)"TextCharacteristicCell"; - static readonly NSString serviceTypeCell = (NSString)"ServiceTypeCell"; - - HMAccessory[] favoriteAccessories = FavoritesManager.SharedManager.FavoriteAccessories (); + partial class FavoritesViewController : UITableViewController, IUITabBarControllerDelegate, IHMAccessoryDelegate, IHMHomeManagerDelegate { + static readonly NSString characteristicCell = (NSString) "CharacteristicCell"; + static readonly NSString segmentedControlCharacteristicCell = (NSString) "SegmentedControlCharacteristicCell"; + static readonly NSString switchCharacteristicCell = (NSString) "SwitchCharacteristicCell"; + static readonly NSString sliderCharacteristicCell = (NSString) "SliderCharacteristicCell"; + static readonly NSString textCharacteristicCell = (NSString) "TextCharacteristicCell"; + static readonly NSString serviceTypeCell = (NSString) "ServiceTypeCell"; + + HMAccessory [] favoriteAccessories = FavoritesManager.SharedManager.FavoriteAccessories (); AccessoryUpdateController cellDelegate = new AccessoryUpdateController (); // If `true`, the characteristic cells should show stars. @@ -98,7 +96,7 @@ void RegisterReuseIdentifiers () var textNib = UINib.FromName (textCharacteristicCell, null); TableView.RegisterNibForCellReuse (textNib, textCharacteristicCell); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), serviceTypeCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), serviceTypeCell); } @@ -135,7 +133,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde else if (characteristic.IsTextWritable ()) reuseIdentifier = textCharacteristicCell; - var cell = (CharacteristicCell)tableView.DequeueReusableCell (reuseIdentifier, indexPath); + var cell = (CharacteristicCell) tableView.DequeueReusableCell (reuseIdentifier, indexPath); cell.ShowsFavorites = ShowsFavorites; cell.Delegate = cellDelegate; cell.Characteristic = characteristic; @@ -145,7 +143,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override string TitleForHeader (UITableView tableView, nint section) { - return favoriteAccessories [(int)section].Name; + return favoriteAccessories [(int) section].Name; } #endregion @@ -169,7 +167,7 @@ void ReloadData () // Enables or disables notifications for all favorite characteristics which support event notifications. static void SetNotificationsEnabled (bool notificationsEnabled) { - foreach (var characteristic in FavoritesManager.SharedManager.FavoriteCharacteristics()) { + foreach (var characteristic in FavoritesManager.SharedManager.FavoriteCharacteristics ()) { if (characteristic.SupportsEventNotification) { characteristic.EnableNotification (notificationsEnabled, error => { if (error != null) @@ -220,7 +218,7 @@ public void DidUpdateValueForCharacteristic (HMAccessory accessory, HMService se return; var indexPath = NSIndexPath.FromRowSection (indexOfCharacteristic, indexOfAccessory); - var cell = (CharacteristicCell)TableView.CellAt (indexPath); + var cell = (CharacteristicCell) TableView.CellAt (indexPath); cell.SetValue (characteristic.Value, false); } @@ -238,4 +236,4 @@ public void DidUpdateHomes (HMHomeManager manager) #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/HMCatalogViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/HMCatalogViewController.cs index fc1265e69..bec8180ee 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/HMCatalogViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/HMCatalogViewController.cs @@ -1,12 +1,11 @@ -using System; +using System; using CoreFoundation; using Foundation; using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { /// <summary> /// The `HMCatalogViewController` is a base class which mainly provides easy-access methods for shared HomeKit objects. /// @@ -15,8 +14,7 @@ namespace HomeKitCatalog /// a home has been deleted. /// </summary> [Register ("HMCatalogViewController")] - public class HMCatalogViewController : UITableViewController, IHMHomeDelegate - { + public class HMCatalogViewController : UITableViewController, IHMHomeDelegate { public HomeStore HomeStore { get { return HomeStore.SharedStore; @@ -80,7 +78,7 @@ protected virtual void RegisterAsDelegate () protected void DisplayError (NSError error) { if (error != null) { - var errorCode = (HMError)(int)error.Code; + var errorCode = (HMError) (int) error.Code; if (PresentedViewController != null || errorCode == HMError.OperationCancelled || errorCode == HMError.UserDeclinedAddingUser) Console.WriteLine (error.LocalizedDescription); else @@ -103,4 +101,4 @@ protected void DisplayMessage (string title, string message) }); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeKitObjectCollection.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeKitObjectCollection.cs index 232d4babe..5331b5fe2 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeKitObjectCollection.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeKitObjectCollection.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents the all different types of HomeKit objects. - public enum HomeKitObjectSection - { + public enum HomeKitObjectSection { Accessory, Room, Zone, @@ -22,8 +20,7 @@ public enum HomeKitObjectSection /// The `HomeKitObjectCollection` is a model object for the `HomeViewController`. It manages arrays of HomeKit objects. /// Manages internal lists of HomeKit objects to allow for save insertion into a table view. /// </summary> - public class HomeKitObjectCollection - { + public class HomeKitObjectCollection { readonly List<HMAccessory> accessories; public List<HMAccessory> Accessories { get { @@ -208,7 +205,7 @@ public NSIndexPath IndexPathOfObject (HMServiceGroup serviceGroup) static NSIndexPath BuildIndexPath (int row, HomeKitObjectSection section) { - return NSIndexPath.FromRowSection (row, (int)section); + return NSIndexPath.FromRowSection (row, (int) section); } #endregion @@ -220,12 +217,12 @@ public void ResetWithHome (HMHome home) Accessories.SortByLocalizedName (a => a.Name); Rooms.Clear (); - Rooms.AddRange (home.GetAllRooms()); + Rooms.AddRange (home.GetAllRooms ()); Rooms.SortByLocalizedName (r => r.Name); Zones.Clear (); Zones.AddRange (home.Zones); - Zones.SortByLocalizedName(z => z.Name); + Zones.SortByLocalizedName (z => z.Name); ActionSets.Clear (); ActionSets.AddRange (home.ActionSets); @@ -262,4 +259,4 @@ public int ObjectsCountForSection (HomeKitObjectSection section) } } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListConfigurationViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListConfigurationViewController.cs index 8e4496310..24e68563e 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListConfigurationViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListConfigurationViewController.cs @@ -4,11 +4,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents the sections in the `HomeListConfigurationViewController`. - enum HomeListSection - { + enum HomeListSection { Homes, PrimaryHome } @@ -16,11 +14,10 @@ enum HomeListSection /// <summary> /// A `HomeListViewController` subclass which allows the user to add and remove homes and set the primary home. /// </summary> - partial class HomeListConfigurationViewController : HomeListViewController - { - static readonly NSString AddHomeCell = (NSString)"AddHomeCell"; - static readonly NSString NoHomesCell = (NSString)"NoHomesCell"; - static readonly NSString PrimaryHomeCell = (NSString)"PrimaryHomeCell"; + partial class HomeListConfigurationViewController : HomeListViewController { + static readonly NSString AddHomeCell = (NSString) "AddHomeCell"; + static readonly NSString NoHomesCell = (NSString) "NoHomesCell"; + static readonly NSString PrimaryHomeCell = (NSString) "PrimaryHomeCell"; [Export ("initWithCoder:")] public HomeListConfigurationViewController (NSCoder coder) @@ -41,12 +38,12 @@ public HomeListConfigurationViewController () public override nint NumberOfSections (UITableView tableView) { - return Enum.GetNames (typeof(HomeListSection)).Length; + return Enum.GetNames (typeof (HomeListSection)).Length; } public override nint RowsInSection (UITableView tableView, nint section) { - switch ((HomeListSection)(int)section) { + switch ((HomeListSection) (int) section) { case HomeListSection.Homes: return Homes.Count + 1; case HomeListSection.PrimaryHome: @@ -63,7 +60,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde else if (Homes.Count == 0) return tableView.DequeueReusableCell (NoHomesCell, indexPath); - var section = (HomeListSection)indexPath.Section; + var section = (HomeListSection) indexPath.Section; NSString reuseId; switch (section) { @@ -104,7 +101,7 @@ public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) // Provides subtext about the use of designating a "primary home". public override string TitleForHeader (UITableView tableView, nint section) { - var isPrimeHome = (HomeListSection)(int)section == HomeListSection.PrimaryHome; + var isPrimeHome = (HomeListSection) (int) section == HomeListSection.PrimaryHome; return isPrimeHome ? "Primary Home" : null; } @@ -136,7 +133,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE static HomeListSection GetSection (NSIndexPath indexPath) { - return (HomeListSection)indexPath.Section; + return (HomeListSection) indexPath.Section; } // Updates the primary home in HomeKit and reloads the view. @@ -156,7 +153,7 @@ void UpdatePrimaryHome (HMHome newPrimaryHome) // Reloads the 'primary home' section. void DidUpdatePrimaryHome () { - TableView.ReloadSections (NSIndexSet.FromIndex ((int)HomeListSection.PrimaryHome), UITableViewRowAnimation.Automatic); + TableView.ReloadSections (NSIndexSet.FromIndex ((int) HomeListSection.PrimaryHome), UITableViewRowAnimation.Automatic); } // Removed the home at the specified index path from HomeKit and updates the view. @@ -185,9 +182,9 @@ protected override void DidRemoveHome (HMHome home) if (index < 0) return; - var indexPath = NSIndexPath.FromRowSection (index, (int)HomeListSection.Homes); + var indexPath = NSIndexPath.FromRowSection (index, (int) HomeListSection.Homes); Homes.RemoveAt (index); - var primaryIndexPath = NSIndexPath.FromRowSection (index, (int)HomeListSection.PrimaryHome); + var primaryIndexPath = NSIndexPath.FromRowSection (index, (int) HomeListSection.PrimaryHome); // If there aren't any homes, we still want one cell to display 'No Homes'. // Just reload. @@ -211,9 +208,9 @@ protected override void DidAddHome (HMHome home) if (newHomeIndex < 0) return; - var indexPath = NSIndexPath.FromRowSection (newHomeIndex, (int)HomeListSection.Homes); + var indexPath = NSIndexPath.FromRowSection (newHomeIndex, (int) HomeListSection.Homes); - var primaryIndexPath = NSIndexPath.FromRowSection (newHomeIndex, (int)HomeListSection.PrimaryHome); + var primaryIndexPath = NSIndexPath.FromRowSection (newHomeIndex, (int) HomeListSection.PrimaryHome); TableView.BeginUpdates (); @@ -259,8 +256,8 @@ protected override void HomeDidUpdateName (HMHome home) { var index = Homes.IndexOf (home); if (index >= 0) { - var listIndexPath = NSIndexPath.FromRowSection (index, (int)HomeListSection.Homes); - var primaryIndexPath = NSIndexPath.FromRowSection (index, (int)HomeListSection.PrimaryHome); + var listIndexPath = NSIndexPath.FromRowSection (index, (int) HomeListSection.Homes); + var primaryIndexPath = NSIndexPath.FromRowSection (index, (int) HomeListSection.PrimaryHome); TableView.ReloadRows (new [] { listIndexPath, primaryIndexPath }, UITableViewRowAnimation.Automatic); } else { @@ -281,4 +278,4 @@ public void DidUpdatePrimaryHome (HMHomeManager manager) #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListViewController.cs index 48373b15c..4188dd91e 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeListViewController.cs @@ -5,14 +5,12 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ - partial class HomeListViewController : HMCatalogViewController, IHMHomeManagerDelegate - { - public static readonly NSString HomeCell = (NSString)"HomeCell"; - public static readonly NSString ShowHomeSegue = (NSString)"Show Home"; - - readonly List<HMHome> homes = new List<HMHome>(); +namespace HomeKitCatalog { + partial class HomeListViewController : HMCatalogViewController, IHMHomeManagerDelegate { + public static readonly NSString HomeCell = (NSString) "HomeCell"; + public static readonly NSString ShowHomeSegue = (NSString) "Show Home"; + + readonly List<HMHome> homes = new List<HMHome> (); public List<HMHome> Homes { get { return homes; @@ -68,7 +66,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (segue.Identifier == ShowHomeSegue) { if (sender == this) return; - var indexPath = TableView.IndexPathForCell ((UITableViewCell)sender); + var indexPath = TableView.IndexPathForCell ((UITableViewCell) sender); HomeStore.Home = Homes [indexPath.Row]; } } @@ -78,14 +76,14 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) public override nint RowsInSection (UITableView tableView, nint section) { var rows = Homes.Count; - TableView.SetBackgroundMessage(rows == 0 ? "No Homes": null); + TableView.SetBackgroundMessage (rows == 0 ? "No Homes" : null); return rows; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (HomeCell, indexPath); - var home = Homes [(int)indexPath.Row]; + var home = Homes [(int) indexPath.Row]; cell.TextLabel.Text = home.Name; @@ -133,7 +131,7 @@ protected virtual void DidAddHome (HMHome home) var newHomeIndex = Homes.IndexOf (home); var indexPathOfNewHome = NSIndexPath.FromRowSection (newHomeIndex, 0); - TableView.InsertRows (new []{ indexPathOfNewHome }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new [] { indexPathOfNewHome }, UITableViewRowAnimation.Automatic); } protected virtual void DidRemoveHome (HMHome home) @@ -144,7 +142,7 @@ protected virtual void DidRemoveHome (HMHome home) Homes.RemoveAt (removedHomeIndex); var indexPath = NSIndexPath.FromRowSection (removedHomeIndex, 0); - TableView.DeleteRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } protected static string SharedTextForHome (HMHome home) @@ -157,12 +155,12 @@ protected static string SharedTextForHome (HMHome home) #region HMHomeDelegate Methods [Export ("homeDidUpdateName:")] - protected virtual void HomeDidUpdateName(HMHome home) + protected virtual void HomeDidUpdateName (HMHome home) { var homeIndex = Homes.IndexOf (home); if (homeIndex >= 0) { var indexPath = NSIndexPath.FromRowSection (homeIndex, 0); - TableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } } @@ -179,7 +177,7 @@ public void DidUpdateHomes (HMHomeManager manager) var home = HomeStore.Home; if (home != null && Array.IndexOf (manager.Homes, home) < 0) { // Close all modal and detail views. - DismissViewController(true, null); + DismissViewController (true, null); if (NavigationController != null) NavigationController.PopToRootViewController (true); } @@ -204,7 +202,7 @@ public void DidRemoveHome (HMHomeManager manager, HMHome home) HomeStore.Home = null; // Close all modal and detail views. - DismissViewController(true, null); + DismissViewController (true, null); if (NavigationController != null) NavigationController.PopToRootViewController (true); } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeStore.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeStore.cs index f5e169bd1..16319fd62 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeStore.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeStore.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { /// <summary> /// The `HomeStore` class is a simple singleton class which holds a home manager and the current selected home. /// </summary> - public class HomeStore : NSObject, IHMHomeManagerDelegate - { + public class HomeStore : NSObject, IHMHomeManagerDelegate { public static readonly HomeStore SharedStore = new HomeStore (); // The current 'selected' home. @@ -25,4 +23,4 @@ public HMHomeManager HomeManager { homeManager = new HMHomeManager (); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeViewController.cs index 5176383a2..3b0577090 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Homes/HomeViewController.cs @@ -5,11 +5,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Distinguishes between the three types of cells in the `HomeViewController`. - public enum HomeCellType - { + public enum HomeCellType { // Represents an actual object in HomeKit. Object, // Represents an "Add" row for users to select to create an object in HomeKit. @@ -23,18 +21,17 @@ public enum HomeCellType /// It contains separate sections for Accessories, Rooms, Zones, Action Sets, /// Triggers, and Service Groups. /// </summary> - public partial class HomeViewController : HMCatalogViewController, IHMAccessoryDelegate - { - static readonly NSString AddCell = (NSString)"AddCell"; - static readonly NSString DisabledAddCell = (NSString)"DisabledAddCell"; - static readonly NSString AccessoryCell = (NSString)"AccessoryCell"; - static readonly NSString UnreachableAccessoryCell = (NSString)"UnreachableAccessoryCell"; - static readonly NSString RoomCell = (NSString)"RoomCell"; - static readonly NSString ZoneCell = (NSString)"ZoneCell"; - static readonly NSString UserCell = (NSString)"UserCell"; - static readonly NSString ActionSetCell = (NSString)"ActionSetCell"; - static readonly NSString TriggerCell = (NSString)"TriggerCell"; - static readonly NSString ServiceGroupCell = (NSString)"ServiceGroupCell"; + public partial class HomeViewController : HMCatalogViewController, IHMAccessoryDelegate { + static readonly NSString AddCell = (NSString) "AddCell"; + static readonly NSString DisabledAddCell = (NSString) "DisabledAddCell"; + static readonly NSString AccessoryCell = (NSString) "AccessoryCell"; + static readonly NSString UnreachableAccessoryCell = (NSString) "UnreachableAccessoryCell"; + static readonly NSString RoomCell = (NSString) "RoomCell"; + static readonly NSString ZoneCell = (NSString) "ZoneCell"; + static readonly NSString UserCell = (NSString) "UserCell"; + static readonly NSString ActionSetCell = (NSString) "ActionSetCell"; + static readonly NSString TriggerCell = (NSString) "TriggerCell"; + static readonly NSString ServiceGroupCell = (NSString) "ServiceGroupCell"; const string AddTimerTriggerSegue = "Add Timer Trigger"; const string AddCharacteristicTriggerSegue = "Add Characteristic Trigger"; @@ -81,27 +78,27 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) switch (segue.Identifier) { case ShowRoomSegue: - var roomVC = (RoomViewController)destination; + var roomVC = (RoomViewController) destination; roomVC.Room = ObjectCollection.Rooms [row]; break; case ShowZoneSegue: - var zoneViewController = (ZoneViewController)destination; + var zoneViewController = (ZoneViewController) destination; zoneViewController.HomeZone = ObjectCollection.Zones [row]; break; case ShowActionSetSegue: - var actionSetVC = (ActionSetViewController)destination; + var actionSetVC = (ActionSetViewController) destination; actionSetVC.ActionSet = ObjectCollection.ActionSets [row]; break; case ShowServiceGroupSegue: - var serviceGroupVC = (ServiceGroupViewController)destination; + var serviceGroupVC = (ServiceGroupViewController) destination; serviceGroupVC.ServiceGroup = ObjectCollection.ServiceGroups [row]; break; case ShowAccessorySegue: - var detailVC = (ServicesViewController)destination; + var detailVC = (ServicesViewController) destination; // The services view controller is generic, we need to provide // `showsFavorites` to display the stars next to characteristics. detailVC.Accessory = ObjectCollection.Accessories [row]; @@ -111,22 +108,22 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) break; case ModifyAccessorySegue: - var addAccessoryVC = (ModifyAccessoryViewController)destination; + var addAccessoryVC = (ModifyAccessoryViewController) destination; addAccessoryVC.Accessory = ObjectCollection.Accessories [row]; break; case ShowTimerTriggerSegue: - var triggerVC = (TimerTriggerViewController)destination; + var triggerVC = (TimerTriggerViewController) destination; triggerVC.Trigger = ObjectCollection.Triggers [row]; break; case ShowLocationTriggerSegue: - var locationTriggerVC = (LocationTriggerViewController)destination; + var locationTriggerVC = (LocationTriggerViewController) destination; locationTriggerVC.Trigger = ObjectCollection.Triggers [row]; break; case ShowCharacteristicTriggerSegue: - var characteristicTriggerVC = (CharacteristicTriggerViewController)destination; + var characteristicTriggerVC = (CharacteristicTriggerViewController) destination; characteristicTriggerVC.Trigger = ObjectCollection.Triggers [row]; break; @@ -157,10 +154,10 @@ void ReloadTable () TableView.ReloadData (); } - HomeCellType CellTypeForIndexPath(NSIndexPath indexPath) + HomeCellType CellTypeForIndexPath (NSIndexPath indexPath) { - var section = (HomeKitObjectSection)indexPath.Section; - bool contains = Array.IndexOf (Enum.GetValues (typeof(HomeKitObjectSection)), section) >= 0; + var section = (HomeKitObjectSection) indexPath.Section; + bool contains = Array.IndexOf (Enum.GetValues (typeof (HomeKitObjectSection)), section) >= 0; if (!contains) return HomeCellType.None; @@ -173,16 +170,16 @@ HomeCellType CellTypeForIndexPath(NSIndexPath indexPath) return indexPath.Row == objectCount ? HomeCellType.Add : HomeCellType.Object; } - void UpdateTriggerAddRow() + void UpdateTriggerAddRow () { - var triggerSection = NSIndexSet.FromIndex ((int)HomeKitObjectSection.Trigger); + var triggerSection = NSIndexSet.FromIndex ((int) HomeKitObjectSection.Trigger); TableView.ReloadSections (triggerSection, UITableViewRowAnimation.Automatic); } // Reloads the action set section. void UpdateActionSetSection () { - var actionSetSection = NSIndexSet.FromIndex ((int)HomeKitObjectSection.ActionSet); + var actionSetSection = NSIndexSet.FromIndex ((int) HomeKitObjectSection.ActionSet); TableView.ReloadSections (actionSetSection, UITableViewRowAnimation.Automatic); UpdateTriggerAddRow (); @@ -208,12 +205,12 @@ bool CanAddTrigger { public override nint NumberOfSections (UITableView tableView) { - return Enum.GetNames (typeof(HomeKitObjectSection)).Length; + return Enum.GetNames (typeof (HomeKitObjectSection)).Length; } public override string TitleForHeader (UITableView tableView, nint section) { - switch ((HomeKitObjectSection)(int)section) { + switch ((HomeKitObjectSection) (int) section) { case HomeKitObjectSection.Accessory: return "Accessories"; case HomeKitObjectSection.Room: @@ -233,7 +230,7 @@ public override string TitleForHeader (UITableView tableView, nint section) } } - static string TitleForAddRowInSection(HomeKitObjectSection section) + static string TitleForAddRowInSection (HomeKitObjectSection section) { switch (section) { case HomeKitObjectSection.Accessory: @@ -255,7 +252,7 @@ static string TitleForAddRowInSection(HomeKitObjectSection section) } } - static string TitleForNoneRowInSection(HomeKitObjectSection section) + static string TitleForNoneRowInSection (HomeKitObjectSection section) { switch (section) { case HomeKitObjectSection.Accessory: @@ -279,7 +276,7 @@ static string TitleForNoneRowInSection(HomeKitObjectSection section) public override string TitleForFooter (UITableView tableView, nint section) { - switch ((HomeKitObjectSection)(int)section) { + switch ((HomeKitObjectSection) (int) section) { case HomeKitObjectSection.Accessory: case HomeKitObjectSection.Room: return null; @@ -300,7 +297,7 @@ public override string TitleForFooter (UITableView tableView, nint section) public override nint RowsInSection (UITableView tableView, nint section) { - var sectionEnum = (HomeKitObjectSection)(int)section; + var sectionEnum = (HomeKitObjectSection) (int) section; // Only "Manage Users" button is in the Users section if (sectionEnum == HomeKitObjectSection.User) @@ -328,10 +325,10 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde } // Generates a 'none cell' with a localized title. - UITableViewCell GetNoneCellForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) + UITableViewCell GetNoneCellForRowAtIndexPath (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (DisabledAddCell, indexPath); - var section = (HomeKitObjectSection)indexPath.Section; + var section = (HomeKitObjectSection) indexPath.Section; cell.TextLabel.Text = TitleForNoneRowInSection (section); return cell; } @@ -340,11 +337,11 @@ UITableViewCell GetNoneCellForRowAtIndexPath(UITableView tableView, NSIndexPath // // In some cases, the 'add cell' will be 'disabled' because the user is not // allowed to perform the action. - UITableViewCell GetAddCellForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) + UITableViewCell GetAddCellForRowAtIndexPath (UITableView tableView, NSIndexPath indexPath) { var reuseIdentifier = AddCell; - var section = (HomeKitObjectSection)indexPath.Section; + var section = (HomeKitObjectSection) indexPath.Section; if ((!CanAddActionSet && section == HomeKitObjectSection.ActionSet) || (!CanAddTrigger && section == HomeKitObjectSection.Trigger) || !Home.IsAdmin ()) @@ -356,12 +353,12 @@ UITableViewCell GetAddCellForRowAtIndexPath(UITableView tableView, NSIndexPath i return cell; } - UITableViewCell HomeKitObjectCellForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath) + UITableViewCell HomeKitObjectCellForRowAtIndexPath (UITableView tableView, NSIndexPath indexPath) { string name; var row = indexPath.Row; - switch ((HomeKitObjectSection)indexPath.Section) { + switch ((HomeKitObjectSection) indexPath.Section) { case HomeKitObjectSection.Accessory: var accessory = ObjectCollection.Accessories [row]; name = accessory.Name; @@ -401,9 +398,9 @@ UITableViewCell HomeKitObjectCellForRowAtIndexPath(UITableView tableView, NSInde return cell; } - NSString ReuseIdentifierForIndexPath(NSIndexPath indexPath) + NSString ReuseIdentifierForIndexPath (NSIndexPath indexPath) { - switch( (HomeKitObjectSection)indexPath.Section) { + switch ((HomeKitObjectSection) indexPath.Section) { case HomeKitObjectSection.Accessory: var accessory = ObjectCollection.Accessories [indexPath.Row]; return accessory.Reachable ? AccessoryCell : UnreachableAccessoryCell; @@ -427,14 +424,14 @@ NSString ReuseIdentifierForIndexPath(NSIndexPath indexPath) // Allows users to remove HomeKit object rows if they are the admin of the home. public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { - if(!Home.IsAdmin()) + if (!Home.IsAdmin ()) return false; // Any row that is not an 'add' row can be removed. if (CellTypeForIndexPath (indexPath) == HomeCellType.Add) return false; - var section = (HomeKitObjectSection)indexPath.Section; + var section = (HomeKitObjectSection) indexPath.Section; // We cannot remove built-in action sets. if (section == HomeKitObjectSection.ActionSet) { @@ -454,7 +451,7 @@ public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { - if( editingStyle == UITableViewCellEditingStyle.Delete) + if (editingStyle == UITableViewCellEditingStyle.Delete) RemoveHomeKitObjectAtIndexPath (indexPath); } @@ -462,7 +459,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE void RemoveHomeKitObjectAtIndexPath (NSIndexPath indexPath) { int row = indexPath.Row; - var section = (HomeKitObjectSection)indexPath.Section; + var section = (HomeKitObjectSection) indexPath.Section; switch (section) { case HomeKitObjectSection.Accessory: @@ -493,7 +490,7 @@ void RemoveHomeKitObjectAtIndexPath (NSIndexPath indexPath) throw new InvalidOperationException ("Unexpected `HomeKitObjectSection` value."); } - TableView.DeleteRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } async void TryRemove (HMAccessory accessory) @@ -588,17 +585,17 @@ void Add (HMServiceGroup serviceGroup) void InsertRowAt (NSIndexPath indexPath) { - TableView.InsertRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } void DeleteRowAt (NSIndexPath indexPath) { - TableView.DeleteRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } void ReloadRowAt (NSIndexPath indexPath) { - TableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } // Handles cell selection based on the cell type. @@ -610,7 +607,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) if (cell.SelectionStyle == UITableViewCellSelectionStyle.None) return; - var section = (HomeKitObjectSection)indexPath.Section; + var section = (HomeKitObjectSection) indexPath.Section; if (CellTypeForIndexPath (indexPath) == HomeCellType.Add) { switch (section) { @@ -648,7 +645,7 @@ public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath i { var cell = tableView.CellAt (indexPath); - if ((HomeKitObjectSection)indexPath.Section == HomeKitObjectSection.Trigger) { + if ((HomeKitObjectSection) indexPath.Section == HomeKitObjectSection.Trigger) { var trigger = ObjectCollection.Triggers [indexPath.Row]; var timerTrigger = trigger as HMTimerTrigger; @@ -727,7 +724,7 @@ async void AddRoomWithName (string roomName) { try { HMRoom room = await Home.AddRoomAsync (roomName); - Add(room); + Add (room); } catch (NSErrorException ex) { DisplayError (ex.Error); } @@ -806,13 +803,13 @@ public void DidRemoveAccessory (HomeKit.HMHome home, HomeKit.HMAccessory accesso [Export ("home:didAddTrigger:")] public void DidAddTrigger (HomeKit.HMHome home, HomeKit.HMTrigger trigger) { - Add(trigger); + Add (trigger); } [Export ("home:didRemoveTrigger:")] public void DidRemoveTrigger (HomeKit.HMHome home, HomeKit.HMTrigger trigger) { - DeleteRowAt(ObjectCollection.Remove(trigger)); + DeleteRowAt (ObjectCollection.Remove (trigger)); } [Export ("home:didUpdateNameForTrigger:")] @@ -828,7 +825,7 @@ public void DidUpdateNameForTrigger (HMHome home, HMTrigger trigger) [Export ("home:didAddServiceGroup:")] public void DidAddServiceGroup (HMHome home, HMServiceGroup group) { - Add(group); + Add (group); } [Export ("home:didRemoveServiceGroup:")] diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Rooms/RoomViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Rooms/RoomViewController.cs index 1dead4942..2ec4a0587 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Rooms/RoomViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Rooms/RoomViewController.cs @@ -6,12 +6,10 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ - public partial class RoomViewController : HMCatalogViewController, IHMAccessoryDelegate - { - static readonly NSString AccessoryCell = (NSString)"AccessoryCell"; - static readonly NSString UnreachableAccessoryCell = (NSString)"UnreachableAccessoryCell"; +namespace HomeKitCatalog { + public partial class RoomViewController : HMCatalogViewController, IHMAccessoryDelegate { + static readonly NSString AccessoryCell = (NSString) "AccessoryCell"; + static readonly NSString UnreachableAccessoryCell = (NSString) "UnreachableAccessoryCell"; static readonly string ModifyAccessorySegue = "Modify Accessory"; HMRoom room; @@ -123,9 +121,9 @@ protected override void RegisterAsDelegate () public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); - var indexPath = TableView.IndexPathForCell ((UITableViewCell)sender); + var indexPath = TableView.IndexPathForCell ((UITableViewCell) sender); if (segue.Identifier == ModifyAccessorySegue) { - var modifyViewController = (ModifyAccessoryViewController)segue.IntendedDestinationViewController (); + var modifyViewController = (ModifyAccessoryViewController) segue.IntendedDestinationViewController (); modifyViewController.Accessory = Room.Accessories [indexPath.Row]; } } @@ -139,7 +137,7 @@ void DidAssignAccessory (HMAccessory accessory) var newAccessoryIndex = Accessories.IndexOf (accessory); if (newAccessoryIndex >= 0) { var newAccessoryIndexPath = NSIndexPath.FromRowSection (newAccessoryIndex, 0); - TableView.InsertRows (new []{ newAccessoryIndexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new [] { newAccessoryIndexPath }, UITableViewRowAnimation.Automatic); } } @@ -183,7 +181,7 @@ void DidModifyAccessory (HMAccessory accessory) { var index = Accessories.IndexOf (accessory); if (index >= 0) - TableView.ReloadRows (new []{ NSIndexPath.FromRowSection (index, 0) }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new [] { NSIndexPath.FromRowSection (index, 0) }, UITableViewRowAnimation.Automatic); } #endregion diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/TabBarController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/TabBarController.cs index fde39b839..0e56c1e98 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/TabBarController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/TabBarController.cs @@ -3,13 +3,11 @@ using UIKit; using Foundation; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { /// <summary> /// The `TabBarController` maintains the state of the tabs across app launches. /// </summary> - partial class TabBarController : UITabBarController - { + partial class TabBarController : UITabBarController { const string StartingTabIndexKey = "TabBarController-StartingTabIndexKey"; public TabBarController (IntPtr handle) @@ -22,7 +20,7 @@ public override void ViewDidLoad () base.ViewDidLoad (); var userDefaults = NSUserDefaults.StandardUserDefaults; - var startingIndex = (NSNumber)userDefaults [StartingTabIndexKey]; + var startingIndex = (NSNumber) userDefaults [StartingTabIndexKey]; if (startingIndex != null) SelectedIndex = startingIndex.NIntValue; @@ -31,7 +29,7 @@ public override void ViewDidLoad () public override void ItemSelected (UITabBar tabbar, UITabBarItem item) { var userDefaults = NSUserDefaults.StandardUserDefaults; - userDefaults [StartingTabIndexKey] = new NSNumber ((nint)Array.IndexOf (tabbar.Items, item)); + userDefaults [StartingTabIndexKey] = new NSNumber ((nint) Array.IndexOf (tabbar.Items, item)); } } } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicSelectionViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicSelectionViewController.cs index 833b886c8..512af7648 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicSelectionViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicSelectionViewController.cs @@ -5,19 +5,17 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Allows for the selection of characteristics. This is mainly used for creating characteristic events and conditions - public partial class CharacteristicSelectionViewController : HMCatalogViewController - { - static readonly NSString AccessoryCell = (NSString)"AccessoryCell"; - static readonly NSString UnreachableAccessoryCell = (NSString)"UnreachableAccessoryCell"; + public partial class CharacteristicSelectionViewController : HMCatalogViewController { + static readonly NSString AccessoryCell = (NSString) "AccessoryCell"; + static readonly NSString UnreachableAccessoryCell = (NSString) "UnreachableAccessoryCell"; const string ShowServicesSegue = "Show Services"; readonly List<HMAccessory> accessories = new List<HMAccessory> (); [Outlet ("saveButton")] - public UIBarButtonItem SaveButton { get; set; } + public UIBarButtonItem SaveButton { get; set; } public HMEventTrigger EventTrigger { get; set; } @@ -50,8 +48,8 @@ public override void ViewWillAppear (bool animated) public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == ShowServicesSegue) { - var senderCell = (UITableViewCell)sender; - var servicesVC = (ServicesViewController)segue.IntendedDestinationViewController (); + var senderCell = (UITableViewCell) sender; + var servicesVC = (ServicesViewController) segue.IntendedDestinationViewController (); var cellIndex = TableView.IndexPathForCell (senderCell).Row; servicesVC.AllowsAllWrites = true; servicesVC.OnlyShowsControlServices = true; @@ -114,4 +112,4 @@ public override string TitleForHeader (UITableView tableView, nint section) #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerCreator.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerCreator.cs index 1949694b0..fdb054d6f 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerCreator.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerCreator.cs @@ -1,22 +1,19 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents modes for a `CharacteristicTriggerCreator`. - public enum CharacteristicTriggerCreatorMode - { + public enum CharacteristicTriggerCreatorMode { Event, Condition } // An `EventTriggerCreator` subclass which allows for the creation of characteristic triggers. - public class CharacteristicTriggerCreator : EventTriggerCreator - { + public class CharacteristicTriggerCreator : EventTriggerCreator { // This object will be a characteristic cell delegate and will therefore // be receiving updates when UI elements change value. However, this object // can construct both characteristic events and characteristic triggers. @@ -25,7 +22,7 @@ public class CharacteristicTriggerCreator : EventTriggerCreator public CharacteristicTriggerCreatorMode Mode { get; set; } readonly Dictionary<HMCharacteristic, INSCopying> targetValueMap = new Dictionary<HMCharacteristic, INSCopying> (); - + // `HMCharacteristicEvent`s that should be removed if `SaveTriggerWithName()` is called. readonly List<HMCharacteristicEvent> removalCharacteristicEvents = new List<HMCharacteristicEvent> (); @@ -63,7 +60,7 @@ protected override void UpdateTrigger () // returns: A new `HMEventTrigger` with the pending characteristic events and constructed predicate. protected override HMTrigger NewTrigger () { - return new HMEventTrigger (Name, PendingCharacteristicEvents(), NewPredicate ()); + return new HMEventTrigger (Name, PendingCharacteristicEvents (), NewPredicate ()); } // Remove all objects from the map so they don't show up in the `events` computed array. @@ -86,7 +83,7 @@ public void RemoveEvent (HMCharacteristicEvent e) #region Helper Methods - HMCharacteristicEvent[] PendingCharacteristicEvents () + HMCharacteristicEvent [] PendingCharacteristicEvents () { return targetValueMap.Select (kvp => new HMCharacteristicEvent (kvp.Key, kvp.Value)).ToArray (); } @@ -101,7 +98,7 @@ void MatchEventsFromTriggerIfNecessary () return; // Find events who's characteristic is in our map table. - foreach (var e in eventTrigger.CharacteristicEvents()) { + foreach (var e in eventTrigger.CharacteristicEvents ()) { INSCopying triggerValue; if (targetValueMap.TryGetValue (e.Characteristic, out triggerValue)) { SaveTriggerGroup.Enter (); @@ -135,7 +132,7 @@ void RemovePendingEventsFromTrigger () } // All `HMCharacteristic`s in the `targetValueMap`. - HMCharacteristic[] AllCharacteristics () + HMCharacteristic [] AllCharacteristics () { var characteristics = new HashSet<HMCharacteristic> (targetValueMap.Keys); return characteristics.ToArray (); @@ -160,10 +157,10 @@ void UpdateEventValue (INSCopying value, HMCharacteristic characteristic) // The current, sorted collection of `HMCharacteristicEvent`s accumulated by // filtering out the events pending removal from the original trigger events and // then adding new pending events. - public HMCharacteristicEvent[] Events () + public HMCharacteristicEvent [] Events () { var eventTrigger = EventTrigger; - HMCharacteristicEvent[] characteristicEvents = eventTrigger != null ? eventTrigger.CharacteristicEvents () : new HMCharacteristicEvent[0]; + HMCharacteristicEvent [] characteristicEvents = eventTrigger != null ? eventTrigger.CharacteristicEvents () : new HMCharacteristicEvent [0]; var originalEvents = characteristicEvents.Where (c => !removalCharacteristicEvents.Contains (c)); var allEvents = originalEvents.Union (PendingCharacteristicEvents ()).ToArray (); @@ -185,7 +182,7 @@ public override void CharacteristicCellDidUpdateValueForCharacteristic (Characte { switch (Mode) { case CharacteristicTriggerCreatorMode.Event: - UpdateEventValue ((INSCopying)value, characteristic); + UpdateEventValue ((INSCopying) value, characteristic); break; default: @@ -204,7 +201,7 @@ public override void CharacteristicCellReadInitialValueForCharacteristic (Charac INSCopying value; if (targetValueMap.TryGetValue (characteristic, out value)) { - completion ((NSObject)value, null); + completion ((NSObject) value, null); return; } @@ -212,7 +209,7 @@ public override void CharacteristicCellReadInitialValueForCharacteristic (Charac characteristic.ReadValue (error => { INSCopying v; if (targetValueMap.TryGetValue (characteristic, out v)) - completion ((NSObject)v, null); + completion ((NSObject) v, null); else completion (characteristic.Value, error); }); @@ -220,4 +217,4 @@ public override void CharacteristicCellReadInitialValueForCharacteristic (Charac #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerViewController.cs index f85e8cdcd..2232dd9b5 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Characteristic/CharacteristicTriggerViewController.cs @@ -5,16 +5,14 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller which facilitates the creation of characteristic triggers. - public partial class CharacteristicTriggerViewController : EventTriggerViewController - { + public partial class CharacteristicTriggerViewController : EventTriggerViewController { const string SelectCharacteristicSegue = "Select Characteristic"; CharacteristicTriggerCreator CharacteristicTriggerCreator { get { - return (CharacteristicTriggerCreator)TriggerCreator; + return (CharacteristicTriggerCreator) TriggerCreator; } } @@ -71,7 +69,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) public override nint RowsInSection (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Characteristics: // Plus one for the add row. return events.Count + 1; @@ -96,9 +94,9 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde // Returns A 'condition cell' with the event at the specified index path. UITableViewCell GetConditionCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (ConditionCell)tableView.DequeueReusableCell (ConditionCell, indexPath); + var cell = (ConditionCell) tableView.DequeueReusableCell (ConditionCell, indexPath); var e = events [indexPath.Row]; - cell.SetCharacteristic (e.Characteristic, (NSNumber)e.TriggerValue); + cell.SetCharacteristic (e.Characteristic, (NSNumber) e.TriggerValue); return cell; } @@ -154,7 +152,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE CharacteristicTriggerCreator.RemoveEvent (events [indexPath.Row]); events.Clear (); events.AddRange (CharacteristicTriggerCreator.Events ()); - tableView.DeleteRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); break; default: base.CommitEditingStyle (tableView, editingStyle, indexPath); @@ -165,7 +163,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE public override string TitleForFooter (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Characteristics: return "This trigger will activate when any of these characteristics change to their value. For example, 'run when the garage door is opened'."; default: diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/ConditionCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/ConditionCell.cs index 745b4712c..f3a6fe725 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/ConditionCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/ConditionCell.cs @@ -1,16 +1,14 @@ -using System; +using System; using Foundation; using HomeKit; using UIKit; using CoreGraphics; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewCell` subclass that displays a trigger condition. [Register ("ConditionCell")] - public class ConditionCell : UITableViewCell - { + public class ConditionCell : UITableViewCell { /// A static, short date formatter. static NSDateFormatter DateFormatter { get { @@ -134,4 +132,4 @@ void TrySetDetailText (string text) detailTextLabel.Text = text; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/SegmentedTimeCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/SegmentedTimeCell.cs index 7817d5094..afcbc5202 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/SegmentedTimeCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/SegmentedTimeCell.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewCell` subclass with a `UISegmentedControl`, used for selecting the time type. - public partial class SegmentedTimeCell : UITableViewCell - { + public partial class SegmentedTimeCell : UITableViewCell { [Outlet ("segmentedControl")] public UISegmentedControl SegmentedControl { get; set; } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimeConditionViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimeConditionViewController.cs index b09aec452..259f4ac2a 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimeConditionViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimeConditionViewController.cs @@ -4,11 +4,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents a section in the `TimeConditionViewController`. - enum TimeConditionTableViewSection - { + enum TimeConditionTableViewSection { // This section contains the segmented control to // choose a time condition type. TimeOrSun, @@ -25,42 +23,38 @@ enum TimeConditionTableViewSection // Represents the type of time condition. // The condition can be an exact time, or relative to a solar event. - enum TimeConditionType - { + enum TimeConditionType { Time, Sun } // Represents the type of solar event. // This can be sunrise or sunset. - public enum TimeConditionSunState - { + public enum TimeConditionSunState { Sunrise, Sunset } // Represents the condition order. // Conditions can be before, after, or exactly at a given time. - public enum TimeConditionOrder - { + public enum TimeConditionOrder { Before, After, At } - public partial class TimeConditionViewController : HMCatalogViewController - { - static readonly NSString selectionCell = (NSString)"SelectionCell"; - static readonly NSString timePickerCell = (NSString)"TimePickerCell"; - static readonly NSString segmentedTimeCell = (NSString)"SegmentedTimeCell"; + public partial class TimeConditionViewController : HMCatalogViewController { + static readonly NSString selectionCell = (NSString) "SelectionCell"; + static readonly NSString timePickerCell = (NSString) "TimePickerCell"; + static readonly NSString segmentedTimeCell = (NSString) "SegmentedTimeCell"; - static readonly string[] BeforeOrAfterTitles = { + static readonly string [] BeforeOrAfterTitles = { "Before", "After", "At", }; - static readonly string[] SunriseSunsetTitles = { + static readonly string [] SunriseSunsetTitles = { "Sunrise", "Sunset", }; @@ -97,12 +91,12 @@ public override void ViewDidLoad () public override nint NumberOfSections (UITableView tableView) { - return Enum.GetNames (typeof(TimeConditionTableViewSection)).Length; + return Enum.GetNames (typeof (TimeConditionTableViewSection)).Length; } public override nint RowsInSection (UITableView tableView, nint section) { - switch ((TimeConditionTableViewSection)(int)section) { + switch ((TimeConditionTableViewSection) (int) section) { case TimeConditionTableViewSection.TimeOrSun: return 1; case TimeConditionTableViewSection.BeforeOrAfter: @@ -119,7 +113,7 @@ public override nint RowsInSection (UITableView tableView, nint section) // Switches based on the section to generate a cell. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - switch ((TimeConditionTableViewSection)indexPath.Section) { + switch ((TimeConditionTableViewSection) indexPath.Section) { case TimeConditionTableViewSection.TimeOrSun: return GetSegmentedCell (tableView, indexPath); case TimeConditionTableViewSection.BeforeOrAfter: @@ -140,7 +134,7 @@ public override UITableViewCell GetCell (UITableView tableView, NSIndexPath inde public override string TitleForHeader (UITableView tableView, nint section) { - switch ((TimeConditionTableViewSection)(int)section) { + switch ((TimeConditionTableViewSection) (int) section) { case TimeConditionTableViewSection.TimeOrSun: return "Condition Type"; case TimeConditionTableViewSection.BeforeOrAfter: @@ -154,7 +148,7 @@ public override string TitleForHeader (UITableView tableView, nint section) public override string TitleForFooter (UITableView tableView, nint section) { - switch ((TimeConditionTableViewSection)(int)section) { + switch ((TimeConditionTableViewSection) (int) section) { case TimeConditionTableViewSection.TimeOrSun: return "Time conditions can relate to specific times or special events, like sunrise and sunset."; case TimeConditionTableViewSection.BeforeOrAfter: @@ -175,18 +169,18 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) tableView.DeselectRow (indexPath, true); - switch ((TimeConditionTableViewSection)indexPath.Section) { + switch ((TimeConditionTableViewSection) indexPath.Section) { case TimeConditionTableViewSection.TimeOrSun: - timeType = (TimeConditionType)indexPath.Row; + timeType = (TimeConditionType) indexPath.Row; ReloadDynamicSections (); return; case TimeConditionTableViewSection.BeforeOrAfter: - order = (TimeConditionOrder)indexPath.Row; + order = (TimeConditionOrder) indexPath.Row; tableView.ReloadSections (NSIndexSet.FromIndex (indexPath.Section), UITableViewRowAnimation.Automatic); break; case TimeConditionTableViewSection.Value: if (timeType == TimeConditionType.Sun) - sunState = (TimeConditionSunState)indexPath.Row; + sunState = (TimeConditionSunState) indexPath.Row; tableView.ReloadSections (NSIndexSet.FromIndex (indexPath.Section), UITableViewRowAnimation.Automatic); break; default: @@ -199,15 +193,15 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) UITableViewCell GetSectionCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (selectionCell, indexPath); - switch ((TimeConditionTableViewSection)indexPath.Section) { + switch ((TimeConditionTableViewSection) indexPath.Section) { case TimeConditionTableViewSection.BeforeOrAfter: cell.TextLabel.Text = BeforeOrAfterTitles [indexPath.Row]; - cell.Accessory = ((int)order == indexPath.Row) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + cell.Accessory = ((int) order == indexPath.Row) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; break; case TimeConditionTableViewSection.Value: if (timeType == TimeConditionType.Sun) { cell.TextLabel.Text = SunriseSunsetTitles [indexPath.Row]; - cell.Accessory = ((int)sunState == indexPath.Row) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; + cell.Accessory = ((int) sunState == indexPath.Row) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; } break; case TimeConditionTableViewSection.TimeOrSun: @@ -221,7 +215,7 @@ UITableViewCell GetSectionCell (UITableView tableView, NSIndexPath indexPath) // Generates a date picker cell and sets the internal date picker when created. UITableViewCell GetDatePickerCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (TimePickerCell)tableView.DequeueReusableCell (timePickerCell, indexPath); + var cell = (TimePickerCell) tableView.DequeueReusableCell (timePickerCell, indexPath); // Save the date picker so we can get the result later. datePicker = cell.DatePicker; return cell; @@ -230,8 +224,8 @@ UITableViewCell GetDatePickerCell (UITableView tableView, NSIndexPath indexPath) /// Generates a segmented cell and sets its target when created. UITableViewCell GetSegmentedCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (SegmentedTimeCell)tableView.DequeueReusableCell (segmentedTimeCell, indexPath); - cell.SegmentedControl.SelectedSegment = (int)timeType; + var cell = (SegmentedTimeCell) tableView.DequeueReusableCell (segmentedTimeCell, indexPath); + cell.SegmentedControl.SelectedSegment = (int) timeType; cell.SegmentedControl.ValueChanged -= OnSegmentedControlDidChange; cell.SegmentedControl.ValueChanged += OnSegmentedControlDidChange; return cell; @@ -250,18 +244,18 @@ NSDateComponents dateComponents { // Updates the time type and reloads dynamic sections. void OnSegmentedControlDidChange (object sender, EventArgs e) { - var segmentedControl = (UISegmentedControl)sender; - timeType = (TimeConditionType)(int)segmentedControl.SelectedSegment; + var segmentedControl = (UISegmentedControl) sender; + timeType = (TimeConditionType) (int) segmentedControl.SelectedSegment; ReloadDynamicSections (); } - + // Reloads the BeforeOrAfter and Value section. void ReloadDynamicSections () { if (timeType == TimeConditionType.Sun && order == TimeConditionOrder.At) order = TimeConditionOrder.Before; - var reloadIndexSet = NSIndexSet.FromNSRange (new NSRange ((int)TimeConditionTableViewSection.BeforeOrAfter, 2)); + var reloadIndexSet = NSIndexSet.FromNSRange (new NSRange ((int) TimeConditionTableViewSection.BeforeOrAfter, 2)); TableView.ReloadSections (reloadIndexSet, UITableViewRowAnimation.Automatic); } @@ -315,4 +309,4 @@ void Dismiss (UIBarButtonItem sender) DismissViewController (true, null); } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimePickerCell.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimePickerCell.cs index e8e54b82a..7c0178dba 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimePickerCell.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Conditions/TimePickerCell.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `UITableViewCell` subclass with a `UIDatePicker`, used for selecting a specific time of day. - public partial class TimePickerCell : UITableViewCell - { + public partial class TimePickerCell : UITableViewCell { [Outlet ("datePicker")] public UIDatePicker DatePicker { get; set; } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerCreator.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerCreator.cs index 5baef3d99..ec930f2e8 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerCreator.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerCreator.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using HomeKit; using Foundation; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A base class for event trigger creators. // These classes manage the state for characteristic trigger conditions. - public class EventTriggerCreator : TriggerCreator, ICharacteristicCellDelegate - { + public class EventTriggerCreator : TriggerCreator, ICharacteristicCellDelegate { /// A mapping of `HMCharacteristic`s to their values. readonly Dictionary<HMCharacteristic, NSObject> conditionValueMap = new Dictionary<HMCharacteristic, NSObject> (); @@ -22,7 +20,7 @@ protected HMEventTrigger EventTrigger { // An array of top-level `NSPredicate` objects. // Currently, HMCatalog only supports top-level `NSPredicate`s // which have type `AndPredicateType`. - NSPredicate[] OriginalConditions { + NSPredicate [] OriginalConditions { get { var eventTrigger = EventTrigger; if (eventTrigger != null) { @@ -34,7 +32,7 @@ NSPredicate[] OriginalConditions { } } - return new NSPredicate[0]; + return new NSPredicate [0]; } } @@ -96,7 +94,7 @@ public virtual void CharacteristicCellReadInitialValueForCharacteristic (Charact }); } - bool TryReadValue (HMCharacteristic characteristic, Action<NSObject, NSError> completion) + bool TryReadValue (HMCharacteristic characteristic, Action<NSObject, NSError> completion) { NSObject value; if (conditionValueMap.TryGetValue (characteristic, out value)) { @@ -128,7 +126,7 @@ protected void SavePredicate () // Generates predicates from the characteristic-value map and adds them to the pending conditions. public void UpdatePredicates () { - foreach (var kvp in conditionValueMap) { + foreach (var kvp in conditionValueMap) { HMCharacteristic characteristic = kvp.Key; NSObject value = kvp.Value; NSPredicate predicate = HMEventTrigger.CreatePredicateForEvaluatingTrigger (characteristic, NSPredicateOperatorType.EqualTo, value); @@ -140,4 +138,4 @@ public void UpdatePredicates () #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerViewController.cs index 3ecd62540..66cd17d7f 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/EventTriggerViewController.cs @@ -1,21 +1,19 @@ -using System; +using System; using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A base class for all event-based view controllers. // It handles the process of creating and managing trigger conditions. - public class EventTriggerViewController : TriggerViewController - { - protected static readonly NSString AddCell = (NSString)"AddCell"; - protected static readonly NSString ConditionCell = (NSString)"ConditionCell"; + public class EventTriggerViewController : TriggerViewController { + protected static readonly NSString AddCell = (NSString) "AddCell"; + protected static readonly NSString ConditionCell = (NSString) "ConditionCell"; const string ShowTimeConditionSegue = "Show Time Condition"; EventTriggerCreator EventTriggerCreator { get { - return (EventTriggerCreator)TriggerCreator; + return (EventTriggerCreator) TriggerCreator; } } @@ -37,8 +35,8 @@ public EventTriggerViewController (NSCoder coder) public override void ViewDidLoad () { base.ViewDidLoad (); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), AddCell); - TableView.RegisterClassForCellReuse (typeof(ConditionCell), ConditionCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), AddCell); + TableView.RegisterClassForCellReuse (typeof (ConditionCell), ConditionCell); } public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) @@ -55,7 +53,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) var characteristicEventVC = vc as CharacteristicSelectionViewController; if (characteristicEventVC != null) { - characteristicEventVC.TriggerCreator = (EventTriggerCreator)TriggerCreator; + characteristicEventVC.TriggerCreator = (EventTriggerCreator) TriggerCreator; return; } } @@ -64,7 +62,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) public override nint RowsInSection (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { // Add row. case TriggerTableViewSection.Conditions: return EventTriggerCreator.Conditions.Count + 1; @@ -118,7 +116,7 @@ public override void CommitEditingStyle (UITableView tableView, UITableViewCellE if (editingStyle == UITableViewCellEditingStyle.Delete) { var predicate = EventTriggerCreator.Conditions [indexPath.Row]; EventTriggerCreator.RemoveCondition (predicate); - tableView.DeleteRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.DeleteRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } } @@ -144,13 +142,13 @@ protected virtual UITableViewCell GetAddCell (UITableView tableView, NSIndexPath // returns: A 'condition cell', which displays information about the condition. UITableViewCell GetConditionCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (ConditionCell)tableView.DequeueReusableCell (ConditionCell); + var cell = (ConditionCell) tableView.DequeueReusableCell (ConditionCell); NSPredicate condition = EventTriggerCreator.Conditions [indexPath.Row]; var hkCondition = condition.HomeKitConditionType (); switch (hkCondition.Type) { case HomeKitConditionType.Characteristic: - cell.SetCharacteristic (hkCondition.CharacteristicData.Item1, (NSNumber)hkCondition.CharacteristicData.Item2); + cell.SetCharacteristic (hkCondition.CharacteristicData.Item1, (NSNumber) hkCondition.CharacteristicData.Item2); break; case HomeKitConditionType.ExactTime: cell.SetOrder (hkCondition.ExactTimeData.Item1, hkCondition.ExactTimeData.Item2); @@ -168,7 +166,7 @@ UITableViewCell GetConditionCell (UITableView tableView, NSIndexPath indexPath) public override string TitleForFooter (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Conditions: return "When a trigger is activated by an event, it checks these conditions. If all of them are true, it will set its scenes."; default: @@ -215,4 +213,4 @@ protected virtual bool IndexPathIsAdd (NSIndexPath indexPath) } } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerCreator.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerCreator.cs index 499ba76ca..0d350e996 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerCreator.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerCreator.cs @@ -1,13 +1,11 @@ -using System.Collections.Generic; +using System.Collections.Generic; using CoreLocation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // An `EventTriggerCreator` subclass which allows for the creation of location triggers. - public class LocationTriggerCreator : EventTriggerCreator, IMapViewControllerDelegate - { + public class LocationTriggerCreator : EventTriggerCreator, IMapViewControllerDelegate { HMLocationEvent LocationEvent { get; set; } public CLCircularRegion TargetRegion { get; set; } @@ -79,4 +77,4 @@ public void MapViewDidUpdateRegion (CLCircularRegion region) #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerViewController.cs index 5f1157446..168186fed 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/LocationTriggerViewController.cs @@ -6,18 +6,16 @@ using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller which facilitates the creation of a location trigger. - public partial class LocationTriggerViewController : EventTriggerViewController - { - static readonly NSString LocationCell = (NSString)"LocationCell"; - static readonly NSString RegionStatusCell = (NSString)"RegionStatusCell"; + public partial class LocationTriggerViewController : EventTriggerViewController { + static readonly NSString LocationCell = (NSString) "LocationCell"; + static readonly NSString RegionStatusCell = (NSString) "RegionStatusCell"; const string selectLocationSegue = "Select Location"; static readonly CLGeocoder geocoder = new CLGeocoder (); - static readonly string[] RegionStatusTitles = { + static readonly string [] RegionStatusTitles = { "When I Enter The Area", "When I Leave The Area" }; @@ -28,7 +26,7 @@ public partial class LocationTriggerViewController : EventTriggerViewController LocationTriggerCreator LocationTriggerCreator { get { - return (LocationTriggerCreator)TriggerCreator; + return (LocationTriggerCreator) TriggerCreator; } } @@ -52,8 +50,8 @@ public override void ViewDidLoad () base.ViewDidLoad (); TriggerCreator = new LocationTriggerCreator (Trigger, Home); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), LocationCell); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), RegionStatusCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), LocationCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), RegionStatusCell); } public override void ViewDidAppear (bool animated) @@ -115,7 +113,7 @@ public override void ViewWillDisappear (bool animated) public override nint RowsInSection (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Region: return 2; @@ -182,7 +180,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) public override string TitleForHeader (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Location: return "Location"; @@ -196,7 +194,7 @@ public override string TitleForHeader (UITableView tableView, nint section) public override string TitleForFooter (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Region: return "This trigger can activate when you enter or leave a region. For example, when you arrive at home or when you leave work."; @@ -245,4 +243,4 @@ static CNMutablePostalAddress CreatePostalAddress (CLPlacemark placemark) }; } } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapOverlayView.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapOverlayView.cs index 6655552e0..d3ce9ffdf 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapOverlayView.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapOverlayView.cs @@ -4,11 +4,9 @@ using Foundation; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A simple `UIView` subclass to draw a selection circle over a MKMapView of the same size. - public partial class MapOverlayView : UIView - { + public partial class MapOverlayView : UIView { #region ctors public MapOverlayView () @@ -51,7 +49,7 @@ public override void Draw (CGRect rect) strokeColor.SetStroke (); circlePath.LineWidth = 3; context.SaveState (); - context.SetLineDash (0, new nfloat[] { 6, 6 }, 2); + context.SetLineDash (0, new nfloat [] { 6, 6 }, 2); circlePath.Stroke (); context.RestoreState (); } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapViewController.cs index 01425f3de..34fba188d 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Events/Location/Mapping/MapViewController.cs @@ -9,17 +9,14 @@ using MapKit; using UIKit; -namespace HomeKitCatalog -{ - public interface IMapViewControllerDelegate - { +namespace HomeKitCatalog { + public interface IMapViewControllerDelegate { // Notifies the delegate that the `MapViewController`'s region has been updated. void MapViewDidUpdateRegion (CLCircularRegion region); } // A view controller which allows the selection of a circular region on a map. - public partial class MapViewController : UIViewController, IUISearchBarDelegate, ICLLocationManagerDelegate, IMKMapViewDelegate - { + public partial class MapViewController : UIViewController, IUISearchBarDelegate, ICLLocationManagerDelegate, IMKMapViewDelegate { const string CircularRegion = "MapViewController.Region"; // When the view loads, we'll zoom to this longitude/latitude span delta. @@ -160,7 +157,7 @@ public void SearchButtonClicked (UISearchBar searchBar) #region Location Manager Methods [Export ("locationManager:didUpdateLocations:")] - public void LocationsUpdated (CLLocationManager manager, CLLocation[] locations) + public void LocationsUpdated (CLLocationManager manager, CLLocation [] locations) { CLLocation lastLocation = locations == null ? null : locations.LastOrDefault (); if (lastLocation == null) @@ -211,9 +208,9 @@ void PerformSearch () var matchingItems = new List<MKMapItem> (); search.Start ((response, error) => { - MKMapItem[] mapItems = null; + MKMapItem [] mapItems = null; if (response != null) - mapItems = response.MapItems ?? new MKMapItem[0]; + mapItems = response.MapItems ?? new MKMapItem [0]; foreach (var item in mapItems) { matchingItems.Add (item); diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/AddServicesViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/AddServicesViewController.cs index 3590d63e4..dfd2a038f 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/AddServicesViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/AddServicesViewController.cs @@ -7,13 +7,11 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller that provides a list of services and lets the user select services to be added to the provided Service Group. // The services are not added to the service group until the 'Done' button is pressed. - public partial class AddServicesViewController : HMCatalogViewController, IHMAccessoryDelegate - { - static readonly NSString ServiceCell = (NSString)"ServiceCell"; + public partial class AddServicesViewController : HMCatalogViewController, IHMAccessoryDelegate { + static readonly NSString ServiceCell = (NSString) "ServiceCell"; readonly List<HMAccessory> displayedAccessories = new List<HMAccessory> (); readonly Dictionary<HMAccessory, List<HMService>> displayedServicesForAccessory = new Dictionary<HMAccessory, List<HMService>> (); @@ -59,13 +57,13 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableView, nint section) { - var accessory = displayedAccessories [(int)section]; + var accessory = displayedAccessories [(int) section]; return displayedServicesForAccessory [accessory].Count; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (ServiceCell)tableView.DequeueReusableCell (ServiceCell, indexPath); + var cell = (ServiceCell) tableView.DequeueReusableCell (ServiceCell, indexPath); var service = ServiceAtIndexPath (indexPath); @@ -88,12 +86,12 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) else selectedServices.Add (service); - tableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } public override string TitleForHeader (UITableView tableView, nint section) { - return displayedAccessories [(int)section].Name; + return displayedAccessories [(int) section].Name; } #endregion diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/ServiceGroupViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/ServiceGroupViewController.cs index 048606b1d..5576156e8 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/ServiceGroupViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/ServiceGroups/ServiceGroupViewController.cs @@ -6,12 +6,10 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller that allows the user to add services to a service group. - public partial class ServiceGroupViewController : HMCatalogViewController, IHMAccessoryDelegate - { - static readonly NSString ServiceCell = (NSString)"ServiceCell"; + public partial class ServiceGroupViewController : HMCatalogViewController, IHMAccessoryDelegate { + static readonly NSString ServiceCell = (NSString) "ServiceCell"; const string AddServicesSegue = "Add Services Plus"; [Outlet ("plusButton")] @@ -64,14 +62,14 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableView, nint section) { - var accessory = accessories [(int)section]; + var accessory = accessories [(int) section]; List<HMService> services; return servicesForAccessory.TryGetValue (accessory, out services) ? services.Count : 0; } public override string TitleForHeader (UITableView tableView, nint section) { - return accessories [(int)section].Name; + return accessories [(int) section].Name; } public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) @@ -81,7 +79,7 @@ public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = (ServiceCell)tableView.DequeueReusableCell (ServiceCell, indexPath); + var cell = (ServiceCell) tableView.DequeueReusableCell (ServiceCell, indexPath); var service = ServiceAtIndexPath (indexPath); cell.IncludeAccessoryText = false; cell.Service = service; @@ -121,7 +119,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); if (segue.Identifier == AddServicesSegue) { - var addServicesVC = (AddServicesViewController)segue.IntendedDestinationViewController (); + var addServicesVC = (AddServicesViewController) segue.IntendedDestinationViewController (); addServicesVC.ServiceGroup = ServiceGroup; } } diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerCreator.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerCreator.cs index 47b109519..f3e7144d4 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerCreator.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerCreator.cs @@ -1,20 +1,18 @@ -using System; +using System; using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A `TriggerCreator` subclass which allows for the creation of timer triggers. - public class TimerTriggerCreator : TriggerCreator - { - static readonly NSCalendarUnit[] Components = { + public class TimerTriggerCreator : TriggerCreator { + static readonly NSCalendarUnit [] Components = { NSCalendarUnit.Hour, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear }; - public int SelectedRecurrenceIndex { get ; set; } + public int SelectedRecurrenceIndex { get; set; } HMTimerTrigger TimerTrigger { get { @@ -90,7 +88,7 @@ static int RecurrenceIndexFromDateComponents (NSDateComponents components) if (components == null) return -1; - var unit = (NSCalendarUnit)0; + var unit = (NSCalendarUnit) 0; if (components.Day == 1) unit = NSCalendarUnit.Day; else if (components.WeekOfYear == 1) @@ -98,7 +96,7 @@ static int RecurrenceIndexFromDateComponents (NSDateComponents components) else if (components.Hour == 1) unit = NSCalendarUnit.Hour; - return (int)unit == 0 ? -1 : Math.Max (Array.IndexOf (Components, unit), -1); + return (int) unit == 0 ? -1 : Math.Max (Array.IndexOf (Components, unit), -1); } // Updates the trigger's fire date, entering and leaving the dispatch group if necessary. @@ -135,4 +133,4 @@ void UpdateRecurrenceIfNecessary () #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerViewController.cs index 25ed6cd7d..5634cf4f1 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/Timer/TimerTriggerViewController.cs @@ -4,14 +4,12 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller which facilitates the creation of timer triggers. - public partial class TimerTriggerViewController : TriggerViewController - { - static readonly NSString recurrenceCell = (NSString)"RecurrenceCell"; + public partial class TimerTriggerViewController : TriggerViewController { + static readonly NSString recurrenceCell = (NSString) "RecurrenceCell"; - static readonly string[] RecurrenceTitles = { + static readonly string [] RecurrenceTitles = { "Every Hour", "Every Day", "Every Week", @@ -58,7 +56,7 @@ public override void ViewDidLoad () TableView.EstimatedRowHeight = 44; TriggerCreator = new TimerTriggerCreator (Trigger, Home); datePicker.Date = TimerTriggerCreator.FireDate; - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), recurrenceCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), recurrenceCell); } // Reset our saved fire date to the date in the picker. @@ -73,7 +71,7 @@ void didChangeDate (UIDatePicker picker) // returns: The number of rows in the Recurrence section; defaults to the super implementation for other sections public override nint RowsInSection (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Recurrence: return RecurrenceTitles.Length; diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerCreator.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerCreator.cs index e6acdcb56..fb1736e85 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerCreator.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerCreator.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,12 +6,10 @@ using Foundation; using HomeKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A base class for all trigger creators. // These classes manage the temporary state of the trigger and unify some of the saving processes. - public class TriggerCreator - { + public class TriggerCreator { protected HMHome Home { get; set; } protected HMTrigger Trigger { get; set; } @@ -30,7 +28,7 @@ protected List<NSError> Errors { get { return errors; } - } + } // Initializes a trigger creator from an existing trigger (if it exists), and the current home. public TriggerCreator (HMTrigger trigger, HMHome home) @@ -139,4 +137,4 @@ void UpdateNameIfNecessary () #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerViewController.cs index 04c17b80b..5ffd766aa 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Triggers/TriggerViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -6,11 +6,9 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // Represents all possible sections in a `TriggerViewController` subclass. - public enum TriggerTableViewSection - { + public enum TriggerTableViewSection { None, // All triggers have these sections. Name, @@ -32,9 +30,8 @@ public enum TriggerTableViewSection // It manages the name, enabled state, and action set components of the view, // as these are shared components. [Register ("TriggerViewController")] - public class TriggerViewController : HMCatalogViewController - { - readonly NSString actionSetCell = (NSString)"ActionSetCell"; + public class TriggerViewController : HMCatalogViewController { + readonly NSString actionSetCell = (NSString) "ActionSetCell"; [Outlet ("saveButton")] public UIBarButtonItem SaveButton { get; set; } @@ -96,7 +93,7 @@ public override void ViewDidLoad () } EnableSaveButtonIfApplicable (); - TableView.RegisterClassForCellReuse (typeof(UITableViewCell), actionSetCell); + TableView.RegisterClassForCellReuse (typeof (UITableViewCell), actionSetCell); } #region IBAction Methods @@ -201,7 +198,7 @@ UITableViewCell GetActionSetCell (UITableView tableView, NSIndexPath indexPath) public override nint RowsInSection (UITableView tableView, nint section) { - var triggerSection = SectionForIndex ((int)section); + var triggerSection = SectionForIndex ((int) section); return triggerSection == TriggerTableViewSection.ActionSets ? actionSets.Count : base.RowsInSection (tableView, section); @@ -257,7 +254,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) // on this implementation after attempting to handle any special trigger sections. public override string TitleForFooter (UITableView tableView, nint section) { - switch (SectionForIndex ((int)section)) { + switch (SectionForIndex ((int) section)) { case TriggerTableViewSection.Enabled: return "This trigger will only activate if it is enabled. You can disable triggers to temporarily stop them from running."; case TriggerTableViewSection.ActionSets: @@ -287,7 +284,7 @@ void SelectActionSet (UITableView tableView, NSIndexPath indexPath) selectedActionSets.Add (actionSet); EnableSaveButtonIfApplicable (); - tableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } #endregion diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/AddRoomViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/AddRoomViewController.cs index 4351cc408..9d002fcd3 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/AddRoomViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/AddRoomViewController.cs @@ -6,12 +6,10 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller that lists rooms within a home and allows the user to add the rooms to a provided zone. - public partial class AddRoomViewController : HMCatalogViewController - { - static readonly NSString RoomCell = (NSString)"RoomCell"; + public partial class AddRoomViewController : HMCatalogViewController { + static readonly NSString RoomCell = (NSString) "RoomCell"; readonly List<HMRoom> displayedRooms = new List<HMRoom> (); readonly List<HMRoom> selectedRooms = new List<HMRoom> (); @@ -88,7 +86,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) else selectedRooms.Add (room); - tableView.ReloadRows (new []{ indexPath }, UITableViewRowAnimation.Automatic); + tableView.ReloadRows (new [] { indexPath }, UITableViewRowAnimation.Automatic); } // Resets the list of displayed rooms and reloads the table. @@ -156,4 +154,4 @@ public void DidRemoveRoomFromZone (HMHome home, HMRoom room, HMZone zone) #endregion } -} \ No newline at end of file +} diff --git a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/ZoneViewController.cs b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/ZoneViewController.cs index 61e8e44ab..a2476338a 100644 --- a/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/ZoneViewController.cs +++ b/ios9/HomeKitCatalog/HomeKitCatalog/ViewControllers/Zones/ZoneViewController.cs @@ -5,14 +5,12 @@ using HomeKit; using UIKit; -namespace HomeKitCatalog -{ +namespace HomeKitCatalog { // A view controller that lists the rooms within a provided zone. - public partial class ZoneViewController : HMCatalogViewController - { - static readonly NSString RoomCell = (NSString)"RoomCell"; - static readonly NSString AddCell = (NSString)"AddCell"; - static readonly NSString DisabledAddCell = (NSString)"DisabledAddCell"; + public partial class ZoneViewController : HMCatalogViewController { + static readonly NSString RoomCell = (NSString) "RoomCell"; + static readonly NSString AddCell = (NSString) "AddCell"; + static readonly NSString DisabledAddCell = (NSString) "DisabledAddCell"; const string AddRoomsSegue = "Add Rooms"; readonly List<HMRoom> rooms = new List<HMRoom> (); @@ -50,7 +48,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); if (segue.Identifier == AddRoomsSegue) { - var addViewController = (AddRoomViewController)segue.IntendedDestinationViewController (); + var addViewController = (AddRoomViewController) segue.IntendedDestinationViewController (); addViewController.HomeZone = HomeZone; } } @@ -93,7 +91,7 @@ void DidAddRoom (HMRoom room) var newRoomIndex = rooms.IndexOf (room); if (newRoomIndex >= 0) { var newRoomIndexPath = NSIndexPath.FromRowSection (newRoomIndex, 0); - TableView.InsertRows (new []{ newRoomIndexPath }, UITableViewRowAnimation.Automatic); + TableView.InsertRows (new [] { newRoomIndexPath }, UITableViewRowAnimation.Automatic); } ReloadAddIndexPath (); @@ -106,7 +104,7 @@ void DidRemoveRoom (HMRoom room) if (roomIndex >= 0) { rooms.RemoveAtIndex (roomIndex); var roomIndexPath = NSIndexPath.FromRowSection (roomIndex, 0); - TableView.DeleteRows (new []{ roomIndexPath }, UITableViewRowAnimation.Automatic); + TableView.DeleteRows (new [] { roomIndexPath }, UITableViewRowAnimation.Automatic); } ReloadAddIndexPath (); @@ -114,7 +112,7 @@ void DidRemoveRoom (HMRoom room) void ReloadAddIndexPath () { - TableView.ReloadRows (new []{ AddIndexPath () }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new [] { AddIndexPath () }, UITableViewRowAnimation.Automatic); } // Reloads the cell corresponding a given room. @@ -123,7 +121,7 @@ void DidUpdateRoom (HMRoom room) var roomIndex = rooms.IndexOf (room); if (roomIndex >= 0) { var roomIndexPath = NSIndexPath.FromRowSection (roomIndex, 0); - TableView.ReloadRows (new []{ roomIndexPath }, UITableViewRowAnimation.Automatic); + TableView.ReloadRows (new [] { roomIndexPath }, UITableViewRowAnimation.Automatic); } } diff --git a/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/AppDelegate.cs b/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/AppDelegate.cs index 445c89aa6..65de7868b 100644 --- a/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/AppDelegate.cs +++ b/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/AppDelegate.cs @@ -2,7 +2,7 @@ using Foundation; namespace MetalPerformanceShadersHelloWorld { - + [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { @@ -15,4 +15,4 @@ public override UIWindow Window { // Main.storyboard is automagically loaded since it is specified // in the Info.plist -> <key>UIMainStoryboardFile~ipad</key> } -} \ No newline at end of file +} diff --git a/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/GameViewController.cs b/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/GameViewController.cs index 5ff25dc4f..a6322d8ee 100644 --- a/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/GameViewController.cs +++ b/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/GameViewController.cs @@ -21,7 +21,7 @@ public GameViewController (NSCoder coder) : base (coder) public override void ViewDidLoad () { - metalView = (MTKView)View; + metalView = (MTKView) View; // Set the view to use the default device. metalView.Device = MTLDevice.SystemDefault; @@ -78,7 +78,7 @@ void Render () // Initialize MetalPerformanceShaders gaussianBlur with Sigma = 10.0f. var gaussianblur = new MPSImageGaussianBlur (metalView.Device, 10f); - var drawable = ((CAMetalLayer)metalView.Layer).NextDrawable (); + var drawable = ((CAMetalLayer) metalView.Layer).NextDrawable (); // Run MetalPerformanceShader gaussianblur. gaussianblur.EncodeToCommandBuffer (commandBuffer, sourceTexture, drawable.Texture); @@ -103,4 +103,4 @@ public void DrawableSizeWillChange (MTKView view, CGSize size) // Called whenever view changes orientation or layout is changed } } -} \ No newline at end of file +} diff --git a/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/Main.cs b/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/Main.cs index c5fa40151..2da39a441 100644 --- a/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/Main.cs +++ b/ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/Main.cs @@ -3,7 +3,7 @@ namespace MetalPerformanceShadersHelloWorld { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/MultiTask/MultiTask/AppDelegate.cs b/ios9/MultiTask/MultiTask/AppDelegate.cs index 8c91745ec..8bfdfccdc 100644 --- a/ios9/MultiTask/MultiTask/AppDelegate.cs +++ b/ios9/MultiTask/MultiTask/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace MultiTask -{ +namespace MultiTask { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate - { + public class AppDelegate : UIApplicationDelegate, IUISplitViewControllerDelegate { // class-level declarations public override UIWindow Window { @@ -18,8 +16,8 @@ public override UIWindow Window { public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. - var splitViewController = (UISplitViewController)Window.RootViewController; - var navigationController = (UINavigationController)splitViewController.ViewControllers [1]; + var splitViewController = (UISplitViewController) Window.RootViewController; + var navigationController = (UINavigationController) splitViewController.ViewControllers [1]; navigationController.TopViewController.NavigationItem.LeftBarButtonItem = splitViewController.DisplayModeButtonItem; splitViewController.WeakDelegate = this; @@ -60,9 +58,9 @@ public override void WillTerminate (UIApplication application) [Export ("splitViewController:collapseSecondaryViewController:ontoPrimaryViewController:")] public bool CollapseSecondViewController (UISplitViewController splitViewController, UIViewController secondaryViewController, UIViewController primaryViewController) { - if (secondaryViewController.GetType () == typeof(UINavigationController) && - ((UINavigationController)secondaryViewController).TopViewController.GetType () == typeof(DetailViewController) && - ((DetailViewController)((UINavigationController)secondaryViewController).TopViewController).DetailItem == null) { + if (secondaryViewController.GetType () == typeof (UINavigationController) && + ((UINavigationController) secondaryViewController).TopViewController.GetType () == typeof (DetailViewController) && + ((DetailViewController) ((UINavigationController) secondaryViewController).TopViewController).DetailItem == null) { // Return YES to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true; } diff --git a/ios9/MultiTask/MultiTask/DetailViewController.cs b/ios9/MultiTask/MultiTask/DetailViewController.cs index 74fc0165a..2291fda22 100644 --- a/ios9/MultiTask/MultiTask/DetailViewController.cs +++ b/ios9/MultiTask/MultiTask/DetailViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace MultiTask -{ - public partial class DetailViewController : UIViewController - { +namespace MultiTask { + public partial class DetailViewController : UIViewController { public object DetailItem { get; set; } public DetailViewController (IntPtr handle) : base (handle) @@ -16,7 +14,7 @@ public void SetDetailItem (object newDetailItem) { if (DetailItem != newDetailItem) { DetailItem = newDetailItem; - + // Update the view ConfigureView (); } diff --git a/ios9/MultiTask/MultiTask/Main.cs b/ios9/MultiTask/MultiTask/Main.cs index 2527dec46..7e5628c2b 100644 --- a/ios9/MultiTask/MultiTask/Main.cs +++ b/ios9/MultiTask/MultiTask/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace MultiTask -{ - public class Application - { +namespace MultiTask { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/MultiTask/MultiTask/MasterViewController.cs b/ios9/MultiTask/MultiTask/MasterViewController.cs index ebf6c2659..741ab4794 100644 --- a/ios9/MultiTask/MultiTask/MasterViewController.cs +++ b/ios9/MultiTask/MultiTask/MasterViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; @@ -6,10 +6,8 @@ using CoreGraphics; using ObjCRuntime; -namespace MultiTask -{ - public partial class MasterViewController : UITableViewController - { +namespace MultiTask { + public partial class MasterViewController : UITableViewController { public DetailViewController DetailViewController { get; set; } #region Custom Keyboard Shortcut @@ -17,16 +15,17 @@ public override bool CanBecomeFirstResponder { get { return true; } } - public override UIKeyCommand[] KeyCommands { + public override UIKeyCommand [] KeyCommands { get { - var keyCommand = UIKeyCommand.Create (new NSString("n"), UIKeyModifierFlags.Command, new Selector ("NewEntry"), new NSString("New Entry")); - return new UIKeyCommand[]{ keyCommand }; + var keyCommand = UIKeyCommand.Create (new NSString ("n"), UIKeyModifierFlags.Command, new Selector ("NewEntry"), new NSString ("New Entry")); + return new UIKeyCommand [] { keyCommand }; } } - [Export("NewEntry")] - public void NewEntry() { + [Export ("NewEntry")] + public void NewEntry () + { // Add new date-time stamp dataSource.Objects.Insert (0, DateTime.Now); @@ -43,14 +42,14 @@ public void NewEntry() { public MasterViewController (IntPtr handle) : base (handle) { Title = NSBundle.MainBundle.LocalizedString ("Master", "Master"); - + if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) { PreferredContentSize = new CGSize (320f, 600f); ClearsSelectionOnViewWillAppear = false; } - + } - + public override void ViewDidLoad () { @@ -63,7 +62,7 @@ public override void ViewDidLoad () addButton.AccessibilityLabel = "addButton"; NavigationItem.RightBarButtonItem = addButton; - DetailViewController = (DetailViewController)((UINavigationController)SplitViewController.ViewControllers [1]).TopViewController; + DetailViewController = (DetailViewController) ((UINavigationController) SplitViewController.ViewControllers [1]).TopViewController; TableView.Source = dataSource = new DataSource (this); } @@ -87,15 +86,14 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (segue.Identifier == "showDetail") { var indexPath = TableView.IndexPathForSelectedRow; var item = dataSource.Objects [indexPath.Row]; - var controller = (DetailViewController)((UINavigationController)segue.DestinationViewController).TopViewController; + var controller = (DetailViewController) ((UINavigationController) segue.DestinationViewController).TopViewController; controller.SetDetailItem (item); controller.NavigationItem.LeftBarButtonItem = SplitViewController.DisplayModeButtonItem; controller.NavigationItem.LeftItemsSupplementBackButton = true; } } - class DataSource : UITableViewSource - { + class DataSource : UITableViewSource { static readonly NSString CellIdentifier = new NSString ("Cell"); readonly List<object> objects = new List<object> (); readonly MasterViewController controller; diff --git a/ios9/MusicMotion/MusicMotion/AppDelegate.cs b/ios9/MusicMotion/MusicMotion/AppDelegate.cs index 228126695..50a1151b9 100644 --- a/ios9/MusicMotion/MusicMotion/AppDelegate.cs +++ b/ios9/MusicMotion/MusicMotion/AppDelegate.cs @@ -1,10 +1,10 @@ -using Foundation; +using Foundation; using UIKit; namespace MusicMotion { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { - + public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) diff --git a/ios9/MusicMotion/MusicMotion/Data Model Classes/Activity.cs b/ios9/MusicMotion/MusicMotion/Data Model Classes/Activity.cs index 696ade6c2..288ac231b 100644 --- a/ios9/MusicMotion/MusicMotion/Data Model Classes/Activity.cs +++ b/ios9/MusicMotion/MusicMotion/Data Model Classes/Activity.cs @@ -37,7 +37,7 @@ public string CalculatedPace { get { if (Distance == 0) return "N/A"; - + var miles = Distance * Activity.MilesPerMeter; var paceInSecondsPerMile = timeInterval / miles; return TimeSpan.FromSeconds (paceInSecondsPerMile).ToString ("h'h 'm'm 's's'"); diff --git a/ios9/MusicMotion/MusicMotion/Data Model Classes/Extensions.cs b/ios9/MusicMotion/MusicMotion/Data Model Classes/Extensions.cs index afd6b36e5..45480bfc1 100644 --- a/ios9/MusicMotion/MusicMotion/Data Model Classes/Extensions.cs +++ b/ios9/MusicMotion/MusicMotion/Data Model Classes/Extensions.cs @@ -1,4 +1,4 @@ -using CoreMotion; +using CoreMotion; namespace MusicMotion { public static class Extensions { diff --git a/ios9/MusicMotion/MusicMotion/Data Model Classes/MotionManager.cs b/ios9/MusicMotion/MusicMotion/Data Model Classes/MotionManager.cs index c7f52a541..fd8bce1c0 100644 --- a/ios9/MusicMotion/MusicMotion/Data Model Classes/MotionManager.cs +++ b/ios9/MusicMotion/MusicMotion/Data Model Classes/MotionManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using static System.Console; @@ -17,7 +17,7 @@ public static class MotionContext { } public class MotionManager { - + const int MaxActivitySamples = 2; const int MaxAltitudeSamples = 10; const int MaxPedometerSamples = 1; @@ -46,7 +46,7 @@ public class MotionManager { NSOperationQueue motionQueue; NSOperationQueue MotionQueue { get { - motionQueue = motionQueue ?? new NSOperationQueue { Name = "musicMotionQueue" }; + motionQueue = motionQueue ?? new NSOperationQueue { Name = "musicMotionQueue" }; return motionQueue; } } @@ -60,10 +60,10 @@ NSOperationQueue MotionQueue { bool IsInLowIntensityContext => IsUserStationary; - bool IsInDrivingContext => + bool IsInDrivingContext => IsUserDriving; - bool IsUserPaceHigh => + bool IsUserPaceHigh => (CurrentPace == 0) ? true : CurrentPace < MotionManager.HighPace; bool IsUserPaceMedium => @@ -88,7 +88,7 @@ bool HasAltitudeChangedRecently { if (firstAltitude == null || lastAltitude == null) return false; - + return Math.Abs (firstAltitude.RelativeAltitude.DoubleValue - lastAltitude.RelativeAltitude.DoubleValue) > MotionManager.MetersForSignificantAltitudeChange; } } @@ -193,7 +193,7 @@ void UpdateContextAndNotifyDelegate () } } - List<Activity> CreateActivityDataWithActivities (CMMotionActivity[] activities, Action completionHandler) + List<Activity> CreateActivityDataWithActivities (CMMotionActivity [] activities, Action completionHandler) { var results = new List<Activity> (); @@ -201,20 +201,20 @@ List<Activity> CreateActivityDataWithActivities (CMMotionActivity[] activities, var queue = new DispatchQueue ("resultQueue"); var filteredActivities = activities.Where (activity => activity.HasActivitySignature () - && !activity.Stationary - && activity.Confidence != CMMotionActivityConfidence.Low).ToArray<CMMotionActivity> (); + && !activity.Stationary + && activity.Confidence != CMMotionActivityConfidence.Low).ToArray<CMMotionActivity> (); var activitySegments = FindActivitySegments (filteredActivities); foreach (var segment in activitySegments) { group.Enter (); - pedometer.QueryPedometerData (segment.Item1.StartDate, (NSDate)segment.Item2, (pedometerData, error) => { + pedometer.QueryPedometerData (segment.Item1.StartDate, (NSDate) segment.Item2, (pedometerData, error) => { queue.DispatchAsync (() => { var activity = new Activity (segment.Item1, - ((DateTime)segment.Item1.StartDate).ToLocalTime (), - segment.Item2.ToLocalTime (), - pedometerData); - + ((DateTime) segment.Item1.StartDate).ToLocalTime (), + segment.Item2.ToLocalTime (), + pedometerData); + results.Add (activity); }); @@ -236,34 +236,34 @@ List<Activity> CreateActivityDataWithActivities (CMMotionActivity[] activities, return results; } - List<Tuple<CMMotionActivity, DateTime>> FindActivitySegments (CMMotionActivity[] activities) + List<Tuple<CMMotionActivity, DateTime>> FindActivitySegments (CMMotionActivity [] activities) { var segments = new List<Tuple<CMMotionActivity, DateTime>> (); for (int i = 0; i < activities.Length - 1; i++) { var activity = activities [i]; - var startDate = (DateTime)activity.StartDate; + var startDate = (DateTime) activity.StartDate; var nextActivity = activities [++i]; - var endDate = (DateTime)nextActivity.StartDate; + var endDate = (DateTime) nextActivity.StartDate; while (i < activities.Length - 1) { - + if (!activity.IsSimilarToActivity (nextActivity)) break; - var previousActivityEnd = (DateTime)activities [i - 1].StartDate; + var previousActivityEnd = (DateTime) activities [i - 1].StartDate; var secondsBetweenActivites = (endDate - previousActivityEnd).TotalSeconds; if (secondsBetweenActivites >= 60 * 60) break; nextActivity = activities [++i]; - endDate = (DateTime)nextActivity.StartDate; + endDate = (DateTime) nextActivity.StartDate; } nextActivity = (i != activities.Length - 1) ? activities [--i] : activities [i]; - endDate = (DateTime)nextActivity.StartDate; + endDate = (DateTime) nextActivity.StartDate; if ((endDate - startDate).TotalSeconds > 60) segments.Add (new Tuple<CMMotionActivity, DateTime> (activity, endDate)); @@ -299,7 +299,7 @@ void SaveMotionActivity (CMMotionActivity activity) void HandleError (NSError error) { - if (error.Code == (int)CMError.MotionActivityNotAuthorized) + if (error.Code == (int) CMError.MotionActivityNotAuthorized) DidEncounterAuthorizationError?.Invoke (this, null); else WriteLine (error.LocalizedDescription); diff --git a/ios9/MusicMotion/MusicMotion/Data Model Classes/Song.cs b/ios9/MusicMotion/MusicMotion/Data Model Classes/Song.cs index 878730327..aa54147d9 100644 --- a/ios9/MusicMotion/MusicMotion/Data Model Classes/Song.cs +++ b/ios9/MusicMotion/MusicMotion/Data Model Classes/Song.cs @@ -1,8 +1,8 @@ -using UIKit; +using UIKit; namespace MusicMotion { public class Song { - + public string Artist { get; set; } public string Title { get; set; } diff --git a/ios9/MusicMotion/MusicMotion/Data Model Classes/SongManager.cs b/ios9/MusicMotion/MusicMotion/Data Model Classes/SongManager.cs index b0efc65df..06e4a6e58 100644 --- a/ios9/MusicMotion/MusicMotion/Data Model Classes/SongManager.cs +++ b/ios9/MusicMotion/MusicMotion/Data Model Classes/SongManager.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using UIKit; diff --git a/ios9/MusicMotion/MusicMotion/Main.cs b/ios9/MusicMotion/MusicMotion/Main.cs index 09646868d..1c9fa4dce 100644 --- a/ios9/MusicMotion/MusicMotion/Main.cs +++ b/ios9/MusicMotion/MusicMotion/Main.cs @@ -1,10 +1,10 @@ -using UIKit; +using UIKit; namespace MusicMotion { public class Application { - + // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/MusicMotion/MusicMotion/View Controller Classes/HistoryViewController.cs b/ios9/MusicMotion/MusicMotion/View Controller Classes/HistoryViewController.cs index eb8adfad4..9632f1820 100644 --- a/ios9/MusicMotion/MusicMotion/View Controller Classes/HistoryViewController.cs +++ b/ios9/MusicMotion/MusicMotion/View Controller Classes/HistoryViewController.cs @@ -6,7 +6,7 @@ namespace MusicMotion { public partial class HistoryViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource, INSCoding { - + readonly string textCellIdentifier = "HistoryCell"; List<Tuple<string, Func<Activity, string>>> recentActivityItems = new List<Tuple<string, Func<Activity, string>>> { @@ -60,7 +60,7 @@ public nint NumberOfSections (UITableView tableView) [Export ("tableView:numberOfRowsInSection:")] public nint RowsInSection (UITableView tableView, nint section) { - var activity = motionManager.RecentActivities [(int)section].MotionActivity; + var activity = motionManager.RecentActivities [(int) section].MotionActivity; return (activity.Running || activity.Walking) ? recentActivityItems.Count : 3; } @@ -81,7 +81,7 @@ public UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) [Export ("tableView:titleForHeaderInSection:")] public string TitleForHeader (UITableView tableView, nint section) { - return motionManager.RecentActivities [(int)section].ActivityType; + return motionManager.RecentActivities [(int) section].ActivityType; } } } diff --git a/ios9/MusicMotion/MusicMotion/View Controller Classes/SongViewController.cs b/ios9/MusicMotion/MusicMotion/View Controller Classes/SongViewController.cs index 83ceae972..3f054784b 100644 --- a/ios9/MusicMotion/MusicMotion/View Controller Classes/SongViewController.cs +++ b/ios9/MusicMotion/MusicMotion/View Controller Classes/SongViewController.cs @@ -8,7 +8,7 @@ namespace MusicMotion { public partial class SongViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource, INSCoding { - + readonly string textCellIdentifier = "SongCell"; MotionManager motionManager; @@ -100,14 +100,14 @@ void UpdateAlbumViewWithSong (Song song) if (currentSong == null) return; - + AlbumView.Image = currentSong.AlbumImage; } void DidUpdateSongQueue (object sender, EventArgs e) { var indexSet = new NSIndexSet (0); - cachedSongQueue = ((SongManager)sender).SongQueue; + cachedSongQueue = ((SongManager) sender).SongQueue; DispatchQueue.MainQueue.DispatchAsync (() => { SongTableView.ReloadSections (indexSet, UITableViewRowAnimation.Fade); UpdateAlbumViewWithSong (null); diff --git a/ios9/PhotoProgress/PhotoProgress/Album/Album.cs b/ios9/PhotoProgress/PhotoProgress/Album/Album.cs index 44940df96..8151bc0ff 100644 --- a/ios9/PhotoProgress/PhotoProgress/Album/Album.cs +++ b/ios9/PhotoProgress/PhotoProgress/Album/Album.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; diff --git a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoDownload.cs b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoDownload.cs index b2a852e4f..03e032945 100644 --- a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoDownload.cs +++ b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoDownload.cs @@ -5,7 +5,7 @@ namespace PhotoProgress { class DownloadState { - + public DispatchQueue Queue { get; set; } public DispatchSource.Timer DownloadTimer { get; set; } @@ -50,13 +50,13 @@ public void Start (Action<NSData, NSError> completionHandler) downloadState.DownloadTimer = new DispatchSource.Timer (downloadState.Queue); int downloadedBytes = 0; int randomMilliseconds = new Random ().Next (0, 500); - var delay = new DispatchTime (DispatchTime.Now, (long)(TimerInterval * NanosecondsPerSecond - randomMilliseconds * NanosecondsPerMillisecond)); - downloadState.DownloadTimer.SetTimer (delay, (long)TimerInterval * NanosecondsPerSecond, 0); + var delay = new DispatchTime (DispatchTime.Now, (long) (TimerInterval * NanosecondsPerSecond - randomMilliseconds * NanosecondsPerMillisecond)); + downloadState.DownloadTimer.SetTimer (delay, (long) TimerInterval * NanosecondsPerSecond, 0); downloadState.DownloadTimer.SetEventHandler (() => { - downloadedBytes += (int)(BatchSize * TimerInterval); + downloadedBytes += (int) (BatchSize * TimerInterval); - if (downloadedBytes >= (int)data.Length) { + if (downloadedBytes >= (int) data.Length) { downloadState.DownloadTimer.Cancel (); return; } @@ -65,7 +65,7 @@ public void Start (Action<NSData, NSError> completionHandler) }); downloadState.DownloadTimer.SetCancelHandler (() => { - if (downloadedBytes >= (int)data.Length) + if (downloadedBytes >= (int) data.Length) DidFinishDownload (data); else DidFailDownloadWithError (downloadState.DownloadError); @@ -73,7 +73,7 @@ public void Start (Action<NSData, NSError> completionHandler) downloadState.DownloadTimer = null; }); - WillBeginDownload ((int)data.Length); + WillBeginDownload ((int) data.Length); downloadState.DownloadTimer.Resume (); } catch (Exception) { var error = new NSError (NSError.CocoaErrorDomain, 0, null); @@ -87,7 +87,7 @@ void FailDownloadWithError (NSError error) downloadState.Queue.DispatchAsync (() => { if (downloadState.DownloadTimer == null) return; - + downloadState.DownloadError = error; if (downloadState.IsPaused) @@ -103,7 +103,7 @@ void ChangeDownloadStatus (bool pause) if ((downloadState.DownloadTimer == null) || (downloadState.IsPaused == pause && !downloadState.DownloadTimer.IsCanceled)) return; - + downloadState.IsPaused = pause; if (pause) @@ -118,7 +118,7 @@ void WillBeginDownload (int downloadLength) Progress.TotalUnitCount = downloadLength; Progress.Cancellable = true; Progress.SetCancellationHandler (() => { - var error = new NSError (NSError.CocoaErrorDomain, (nint)(int)NSCocoaError.UserCancelled, null); + var error = new NSError (NSError.CocoaErrorDomain, (nint) (int) NSCocoaError.UserCancelled, null); FailDownloadWithError (error); }); @@ -134,7 +134,7 @@ void DidDownloadData (int numberOfBytes) void DidFinishDownload (NSData downloadedData) { - Progress.CompletedUnitCount = (long)downloadedData.Length; + Progress.CompletedUnitCount = (long) downloadedData.Length; completionHandler?.Invoke (downloadedData, null); completionHandler = null; } diff --git a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoFilter.cs b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoFilter.cs index 5d5450fe9..6afe1bcbb 100644 --- a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoFilter.cs +++ b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoFilter.cs @@ -1,4 +1,4 @@ -using CoreImage; +using CoreImage; using Foundation; using UIKit; diff --git a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoImport.cs b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoImport.cs index 9d34e75c3..5ba31fe0f 100644 --- a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoImport.cs +++ b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoImport.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; diff --git a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoProgress.cs b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoProgress.cs index 036d47f27..d15f01604 100644 --- a/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoProgress.cs +++ b/ios9/PhotoProgress/PhotoProgress/Album/Operations/PhotoProgress.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; @@ -13,7 +13,7 @@ public class PhotoProgress : NSProgress { public void AddChild (PhotoProgress child, int pendingUnitCount) { - child.CompletedUnitCountChanged += (obj, args) => CompletedUnitCountChanged?.Invoke(obj, args); + child.CompletedUnitCountChanged += (obj, args) => CompletedUnitCountChanged?.Invoke (obj, args); base.AddChild (child, pendingUnitCount); } diff --git a/ios9/PhotoProgress/PhotoProgress/Album/Photo.cs b/ios9/PhotoProgress/PhotoProgress/Album/Photo.cs index de44dd077..ec495dba3 100644 --- a/ios9/PhotoProgress/PhotoProgress/Album/Photo.cs +++ b/ios9/PhotoProgress/PhotoProgress/Album/Photo.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; @@ -57,7 +57,7 @@ public void Reset () void ReportError (NSError error) { - if (error.Domain == NSError.CocoaErrorDomain || error.Code == (nint)(int)NSCocoaError.UserCancelled) + if (error.Domain == NSError.CocoaErrorDomain || error.Code == (nint) (int) NSCocoaError.UserCancelled) Console.WriteLine ("Error importing photo: {0}", error.LocalizedDescription); } } diff --git a/ios9/PhotoProgress/PhotoProgress/AppDelegate.cs b/ios9/PhotoProgress/PhotoProgress/AppDelegate.cs index 864ef4a4b..4b9526e29 100644 --- a/ios9/PhotoProgress/PhotoProgress/AppDelegate.cs +++ b/ios9/PhotoProgress/PhotoProgress/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace PhotoProgress { diff --git a/ios9/PhotoProgress/PhotoProgress/Main.cs b/ios9/PhotoProgress/PhotoProgress/Main.cs index 3936e9c4b..26b246f6e 100644 --- a/ios9/PhotoProgress/PhotoProgress/Main.cs +++ b/ios9/PhotoProgress/PhotoProgress/Main.cs @@ -1,13 +1,13 @@ -using UIKit; +using UIKit; namespace PhotoProgress { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main (args, null, "AppDelegate"); } } -} \ No newline at end of file +} diff --git a/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotoCollectionViewCell.cs b/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotoCollectionViewCell.cs index d45a0f010..07f5e8131 100644 --- a/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotoCollectionViewCell.cs +++ b/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotoCollectionViewCell.cs @@ -13,7 +13,7 @@ public Photo Photo { get { return photo; } - set { + set { Unsubscribe (); photo = value; Subscribe (); @@ -50,7 +50,7 @@ void UpdateProgressView (object sender, EventArgs e) NSOperationQueue.MainQueue.AddOperation (() => { var photoImport = Photo?.PhotoImport; if (photoImport != null) { - ProgressView.Progress = (float)photoImport.Progress.FractionCompleted; + ProgressView.Progress = (float) photoImport.Progress.FractionCompleted; ProgressView.Hidden = false; } else { ProgressView.Hidden = true; @@ -79,7 +79,7 @@ protected override void Dispose (bool disposing) } disposed = true; - base.Dispose(disposing); + base.Dispose (disposing); } } } diff --git a/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosCollectionViewController.cs b/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosCollectionViewController.cs index 14742fa47..24cf0574b 100644 --- a/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosCollectionViewController.cs +++ b/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosCollectionViewController.cs @@ -29,7 +29,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cell = (PhotoCollectionViewCell)CollectionView.DequeueReusableCell ("Photo", indexPath); + var cell = (PhotoCollectionViewCell) CollectionView.DequeueReusableCell ("Photo", indexPath); cell.Photo = album.Photos [indexPath.Row]; return cell; } diff --git a/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosViewController.cs b/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosViewController.cs index 90b07b385..8d503a0df 100644 --- a/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosViewController.cs +++ b/ios9/PhotoProgress/PhotoProgress/ViewControllers/PhotosViewController.cs @@ -52,7 +52,7 @@ partial void StartImport (NSObject sender) partial void CanceltImport (NSObject sender) { - OverallProgress.Cancel(); + OverallProgress.Cancel (); } partial void PauseImport (NSObject sender) @@ -76,7 +76,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) if (segue.Identifier != "photos collection") return; - var collectionViewController = (PhotosCollectionViewController)segue.DestinationViewController; + var collectionViewController = (PhotosCollectionViewController) segue.DestinationViewController; collectionViewController.Album = album; } @@ -110,7 +110,7 @@ void UpdateProgressView () if (OverallProgress != null) { shouldHide = OverallProgressIsFinished || OverallProgress.Cancelled; - ProgressView.Progress = (float)OverallProgress.FractionCompleted; + ProgressView.Progress = (float) OverallProgress.FractionCompleted; } else { shouldHide = true; } diff --git a/ios9/PictureInPicture/PictureInPicture/AppDelegate.cs b/ios9/PictureInPicture/PictureInPicture/AppDelegate.cs index 5c9b2c175..32b25a59e 100644 --- a/ios9/PictureInPicture/PictureInPicture/AppDelegate.cs +++ b/ios9/PictureInPicture/PictureInPicture/AppDelegate.cs @@ -1,12 +1,10 @@ -using AVFoundation; +using AVFoundation; using Foundation; using UIKit; -namespace PictureInPicture -{ +namespace PictureInPicture { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) @@ -21,10 +19,10 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary // If an application is not configured correctly, AVPictureInPictureController.PictureInPicturePossible returns false. var audioSession = AVAudioSession.SharedInstance (); NSError error = audioSession.SetCategory (AVAudioSessionCategory.Playback); - if(error != null) + if (error != null) System.Console.WriteLine ("Audio session SetCategory failed"); return true; } } -} \ No newline at end of file +} diff --git a/ios9/PictureInPicture/PictureInPicture/Main.cs b/ios9/PictureInPicture/PictureInPicture/Main.cs index 9e6587e17..24f0c8565 100644 --- a/ios9/PictureInPicture/PictureInPicture/Main.cs +++ b/ios9/PictureInPicture/PictureInPicture/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace PictureInPicture -{ - public class Application - { +namespace PictureInPicture { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/PictureInPicture/PictureInPicture/PlayerView.cs b/ios9/PictureInPicture/PictureInPicture/PlayerView.cs index b977c2970..7dab540e5 100644 --- a/ios9/PictureInPicture/PictureInPicture/PlayerView.cs +++ b/ios9/PictureInPicture/PictureInPicture/PlayerView.cs @@ -1,4 +1,4 @@ -using System; +using System; using AVFoundation; using CoreGraphics; @@ -6,15 +6,13 @@ using ObjCRuntime; using UIKit; -namespace PictureInPicture -{ - [Register("PlayerView")] - public class PlayerView : UIView - { +namespace PictureInPicture { + [Register ("PlayerView")] + public class PlayerView : UIView { static Class LayerClass { - [Export("layerClass")] + [Export ("layerClass")] get { - return new Class (typeof(AVPlayerLayer)); + return new Class (typeof (AVPlayerLayer)); } } @@ -29,7 +27,7 @@ public AVPlayer Player { public AVPlayerLayer PlayerLayer { get { - return (AVPlayerLayer)Layer; + return (AVPlayerLayer) Layer; } } @@ -44,4 +42,4 @@ public PlayerView (IntPtr handle) { } } -} \ No newline at end of file +} diff --git a/ios9/PictureInPicture/PictureInPicture/PlayerViewController.cs b/ios9/PictureInPicture/PictureInPicture/PlayerViewController.cs index e88b6c17f..3c612ba30 100644 --- a/ios9/PictureInPicture/PictureInPicture/PlayerViewController.cs +++ b/ios9/PictureInPicture/PictureInPicture/PlayerViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using AVFoundation; using AVKit; @@ -7,17 +7,15 @@ using Foundation; using UIKit; -namespace PictureInPicture -{ +namespace PictureInPicture { // Manages the view used for playback and sets up the `AVPictureInPictureController` for video playback in picture in picture. - public partial class PlayerViewController : UIViewController, IAVPictureInPictureControllerDelegate - { + public partial class PlayerViewController : UIViewController, IAVPictureInPictureControllerDelegate { IDisposable durationObserver; IDisposable rateObserver; IDisposable statusObserver; // Attempt to load and test these asset keys before playing - static readonly NSString[] assetKeysRequiredToPlay = { + static readonly NSString [] assetKeysRequiredToPlay = { (NSString)"playable", (NSString)"hasProtectedContent" }; @@ -35,7 +33,7 @@ AVPlayer Player { PlayerView PlayerView { get { - return (PlayerView)View; + return (PlayerView) View; } } @@ -95,7 +93,7 @@ double Duration { [Outlet] UIToolbar Toolbar { get; set; } - [Outlet("pictureInPictureActiveLabel")] + [Outlet ("pictureInPictureActiveLabel")] UILabel PictureInPictureActiveLabel { get; set; } public PlayerViewController (IntPtr handle) @@ -103,8 +101,8 @@ public PlayerViewController (IntPtr handle) { } - [Action("playPauseButtonWasPressed:")] - void PlayPauseButtonWasPressed(UIButton sender) + [Action ("playPauseButtonWasPressed:")] + void PlayPauseButtonWasPressed (UIButton sender) { PlayPauseButtonWasPressed (); } @@ -130,8 +128,8 @@ void PlayPauseButtonWasPressed () } } - [Action("togglePictureInPictureMode:")] - void togglePictureInPictureMode(UIButton sender) + [Action ("togglePictureInPictureMode:")] + void togglePictureInPictureMode (UIButton sender) { // Toggle picture in picture mode. // If active, stop picture in picture and return to inline playback. @@ -144,8 +142,8 @@ void togglePictureInPictureMode(UIButton sender) pictureInPictureController.StartPictureInPicture (); } - [Action("timeSliderDidChange:")] - void timeSliderDidChange(UISlider sender) + [Action ("timeSliderDidChange:")] + void timeSliderDidChange (UISlider sender) { CurrentTime = sender.Value; } @@ -184,10 +182,10 @@ public override void ViewDidDisappear (bool animated) statusObserver.Dispose (); } - void SetupPlayback() + void SetupPlayback () { var movieURL = NSBundle.MainBundle.GetUrlForResource ("samplemovie", "mov"); - var asset = new AVUrlAsset (movieURL, (AVUrlAssetOptions)null); + var asset = new AVUrlAsset (movieURL, (AVUrlAssetOptions) null); // Create a new `AVPlayerItem` and make it our player's current item. // @@ -200,14 +198,14 @@ void SetupPlayback() PlayerItem = new AVPlayerItem (asset, assetKeysRequiredToPlay); } - void SetupPlayerPeriodicTimeObserver() + void SetupPlayerPeriodicTimeObserver () { // Only add the time observer if one hasn't been created yet. if (timeObserverToken != null) return; var time = new CMTime (1, 1); - timeObserverToken = Player.AddPeriodicTimeObserver (time, DispatchQueue.MainQueue, t => TimeSlider.Value = (float)t.Seconds); + timeObserverToken = Player.AddPeriodicTimeObserver (time, DispatchQueue.MainQueue, t => TimeSlider.Value = (float) t.Seconds); } void CleanUpPlayerPeriodicTimeObserver () @@ -275,10 +273,10 @@ void ObserveCurrentItemDuration (NSObservedChange change) var hasValidDuration = newDuration.IsNumeric && newDuration.Value != 0; var newDurationSeconds = hasValidDuration ? newDuration.Seconds : 0; - TimeSlider.MaxValue = (float)newDurationSeconds; + TimeSlider.MaxValue = (float) newDurationSeconds; var currentTime = Player.CurrentTime.Seconds; - TimeSlider.Value = (float)(hasValidDuration ? currentTime : 0); + TimeSlider.Value = (float) (hasValidDuration ? currentTime : 0); PlayPauseButton.Enabled = hasValidDuration; TimeSlider.Enabled = hasValidDuration; @@ -287,19 +285,19 @@ void ObserveCurrentItemDuration (NSObservedChange change) void ObserveCurrentRate (NSObservedChange change) { // Update playPauseButton type. - var newRate = ((NSNumber)change.NewValue).DoubleValue; + var newRate = ((NSNumber) change.NewValue).DoubleValue; - UIBarButtonSystemItem style = (Math.Abs(newRate) < float.Epsilon) ? UIBarButtonSystemItem.Play : UIBarButtonSystemItem.Pause; - var newPlayPauseButton = new UIBarButtonItem(style, PlayPauseButtonWasPressed); + UIBarButtonSystemItem style = (Math.Abs (newRate) < float.Epsilon) ? UIBarButtonSystemItem.Play : UIBarButtonSystemItem.Pause; + var newPlayPauseButton = new UIBarButtonItem (style, PlayPauseButtonWasPressed); // Replace the current button with the updated button in the toolbar. - UIBarButtonItem[] items = Toolbar.Items; + UIBarButtonItem [] items = Toolbar.Items; - var playPauseItemIndex = Array.IndexOf(items, PlayPauseButton); + var playPauseItemIndex = Array.IndexOf (items, PlayPauseButton); if (playPauseItemIndex >= 0) { - items[playPauseItemIndex] = newPlayPauseButton; + items [playPauseItemIndex] = newPlayPauseButton; PlayPauseButton = newPlayPauseButton; - Toolbar.SetItems(items, false); + Toolbar.SetItems (items, false); } } @@ -308,11 +306,11 @@ void ObserveCurrentItemStatus (NSObservedChange change) // Display an error if status becomes Failed var newStatusAsNumber = change.NewValue as NSNumber; AVPlayerItemStatus newStatus = (newStatusAsNumber != null) - ? (AVPlayerItemStatus)newStatusAsNumber.Int32Value + ? (AVPlayerItemStatus) newStatusAsNumber.Int32Value : AVPlayerItemStatus.Unknown; if (newStatus == AVPlayerItemStatus.Failed) { - HandleError(Player.CurrentItem.Error); + HandleError (Player.CurrentItem.Error); } else if (newStatus == AVPlayerItemStatus.ReadyToPlay) { var asset = Player.CurrentItem != null ? Player.CurrentItem.Asset : null; if (asset != null) { @@ -321,15 +319,15 @@ void ObserveCurrentItemStatus (NSObservedChange change) // have been successfully loaded. foreach (var key in assetKeysRequiredToPlay) { NSError error; - if (asset.StatusOfValue(key, out error) == AVKeyValueStatus.Failed) { - HandleError(error); + if (asset.StatusOfValue (key, out error) == AVKeyValueStatus.Failed) { + HandleError (error); return; } } if (!asset.Playable || asset.ProtectedContent) { // We can't play this asset. - HandleError(null); + HandleError (null); return; } @@ -353,7 +351,7 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio // Enable the `PictureInPictureButton` only if `PictureInPicturePossible` // is true. If this returns false, it might mean that the application // was not configured as shown in the AppDelegate. - PictureInPictureButton.Enabled = ((NSNumber)ch.NewValue).BoolValue; + PictureInPictureButton.Enabled = ((NSNumber) ch.NewValue).BoolValue; } } @@ -368,4 +366,4 @@ void HandleError (NSError error) #endregion } -} \ No newline at end of file +} diff --git a/ios9/SegueCatalog/SegueCatalog/AppDelegate.cs b/ios9/SegueCatalog/SegueCatalog/AppDelegate.cs index 0f848a9e9..6885c2be1 100644 --- a/ios9/SegueCatalog/SegueCatalog/AppDelegate.cs +++ b/ios9/SegueCatalog/SegueCatalog/AppDelegate.cs @@ -1,14 +1,12 @@ -using Foundation; +using Foundation; using UIKit; -namespace SegueCatalog -{ +namespace SegueCatalog { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } -} \ No newline at end of file +} diff --git a/ios9/SegueCatalog/SegueCatalog/Main.cs b/ios9/SegueCatalog/SegueCatalog/Main.cs index 66ba050a2..0c1adfe51 100644 --- a/ios9/SegueCatalog/SegueCatalog/Main.cs +++ b/ios9/SegueCatalog/SegueCatalog/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace SegueCatalog -{ - public class Application - { +namespace SegueCatalog { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/SegueCatalog/SegueCatalog/Segue/AdaptableFormSheetSegue.cs b/ios9/SegueCatalog/SegueCatalog/Segue/AdaptableFormSheetSegue.cs index f3e791c5a..f0d525a75 100644 --- a/ios9/SegueCatalog/SegueCatalog/Segue/AdaptableFormSheetSegue.cs +++ b/ios9/SegueCatalog/SegueCatalog/Segue/AdaptableFormSheetSegue.cs @@ -4,8 +4,7 @@ using UIKit; using ObjCRuntime; -namespace SegueCatalog -{ +namespace SegueCatalog { /// <summary> /// This segue subclass demonstrates how to adapt a view controller that has been /// modally presented by a segue. An instance of this segue is triggered by the @@ -15,8 +14,7 @@ namespace SegueCatalog /// full-screen presentation, using the same view controller. We would like to /// provide an alternative representation in the adapted case. /// </summary> - public partial class AdaptableFormSheetSegue : UIStoryboardSegue, IUIAdaptivePresentationControllerDelegate - { + public partial class AdaptableFormSheetSegue : UIStoryboardSegue, IUIAdaptivePresentationControllerDelegate { public AdaptableFormSheetSegue (IntPtr handle) : base (handle) { @@ -51,7 +49,7 @@ That storyboard is stored within the same bundle that contains this class. */ - var adaptableFormSheetSegueBundle = NSBundle.FromClass (new Class (typeof(AdaptableFormSheetSegue))); + var adaptableFormSheetSegueBundle = NSBundle.FromClass (new Class (typeof (AdaptableFormSheetSegue))); return UIStoryboard.FromName ("Detail", adaptableFormSheetSegueBundle).InstantiateViewController ("Adapted"); } } diff --git a/ios9/SegueCatalog/SegueCatalog/Segue/CustomAnimationPresentationSegue.cs b/ios9/SegueCatalog/SegueCatalog/Segue/CustomAnimationPresentationSegue.cs index c89cab672..ebd88c31d 100644 --- a/ios9/SegueCatalog/SegueCatalog/Segue/CustomAnimationPresentationSegue.cs +++ b/ios9/SegueCatalog/SegueCatalog/Segue/CustomAnimationPresentationSegue.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace SegueCatalog -{ - public partial class CustomAnimationPresentationSegue : UIStoryboardSegue, IUIViewControllerTransitioningDelegate, IUIViewControllerAnimatedTransitioning - { +namespace SegueCatalog { + public partial class CustomAnimationPresentationSegue : UIStoryboardSegue, IUIViewControllerTransitioningDelegate, IUIViewControllerAnimatedTransitioning { public CustomAnimationPresentationSegue (IntPtr handle) : base (handle) { } diff --git a/ios9/SegueCatalog/SegueCatalog/Segue/NonAnimatingSegue.cs b/ios9/SegueCatalog/SegueCatalog/Segue/NonAnimatingSegue.cs index ec8243a2a..e59d0348d 100644 --- a/ios9/SegueCatalog/SegueCatalog/Segue/NonAnimatingSegue.cs +++ b/ios9/SegueCatalog/SegueCatalog/Segue/NonAnimatingSegue.cs @@ -2,10 +2,8 @@ using UIKit; -namespace SegueCatalog -{ - public partial class NonAnimatingSegue : UIStoryboardSegue - { +namespace SegueCatalog { + public partial class NonAnimatingSegue : UIStoryboardSegue { public NonAnimatingSegue (IntPtr handle) : base (handle) { diff --git a/ios9/SegueCatalog/SegueCatalog/ViewControllers/MasterViewController.cs b/ios9/SegueCatalog/SegueCatalog/ViewControllers/MasterViewController.cs index 14ad7fa89..498a4b005 100644 --- a/ios9/SegueCatalog/SegueCatalog/ViewControllers/MasterViewController.cs +++ b/ios9/SegueCatalog/SegueCatalog/ViewControllers/MasterViewController.cs @@ -3,17 +3,15 @@ using Foundation; using UIKit; -namespace SegueCatalog -{ - public partial class MasterViewController : UITableViewController - { +namespace SegueCatalog { + public partial class MasterViewController : UITableViewController { public MasterViewController (IntPtr handle) : base (handle) { } - [Action("unwindInMaster:")] - void UnwindInMaster(UIStoryboardSegue segue) + [Action ("unwindInMaster:")] + void UnwindInMaster (UIStoryboardSegue segue) { /* Empty. Exists solely so that "unwind in master" segues can diff --git a/ios9/SegueCatalog/SegueCatalog/ViewControllers/NestedViewController.cs b/ios9/SegueCatalog/SegueCatalog/ViewControllers/NestedViewController.cs index c916e5b22..c2b0fec7e 100644 --- a/ios9/SegueCatalog/SegueCatalog/ViewControllers/NestedViewController.cs +++ b/ios9/SegueCatalog/SegueCatalog/ViewControllers/NestedViewController.cs @@ -3,10 +3,8 @@ using Foundation; using UIKit; -namespace SegueCatalog -{ - public partial class NestedViewController : UIViewController - { +namespace SegueCatalog { + public partial class NestedViewController : UIViewController { public NestedViewController (IntPtr handle) : base (handle) { diff --git a/ios9/SegueCatalog/SegueCatalog/ViewControllers/OuterViewController.cs b/ios9/SegueCatalog/SegueCatalog/ViewControllers/OuterViewController.cs index c29b41439..c1d672a70 100644 --- a/ios9/SegueCatalog/SegueCatalog/ViewControllers/OuterViewController.cs +++ b/ios9/SegueCatalog/SegueCatalog/ViewControllers/OuterViewController.cs @@ -3,17 +3,15 @@ using Foundation; using UIKit; -namespace SegueCatalog -{ - public partial class OuterViewController : UIViewController - { +namespace SegueCatalog { + public partial class OuterViewController : UIViewController { public OuterViewController (IntPtr handle) : base (handle) { } - [Action("unwindToOuter:")] - void UnwindToOuter(UIStoryboardSegue segue) + [Action ("unwindToOuter:")] + void UnwindToOuter (UIStoryboardSegue segue) { /* Empty. Exists solely so that "unwind to outer" segues can find diff --git a/ios9/StackView/StackView/AppDelegate.cs b/ios9/StackView/StackView/AppDelegate.cs index 0b46c7e2b..bd2bbd4a5 100644 --- a/ios9/StackView/StackView/AppDelegate.cs +++ b/ios9/StackView/StackView/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace StackView -{ +namespace StackView { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/ios9/StackView/StackView/Main.cs b/ios9/StackView/StackView/Main.cs index 3d2216cf6..c2ec91086 100644 --- a/ios9/StackView/StackView/Main.cs +++ b/ios9/StackView/StackView/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace StackView -{ - public class Application - { +namespace StackView { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/StackView/StackView/ViewController.cs b/ios9/StackView/StackView/ViewController.cs index 0d211adfe..334e3c44f 100644 --- a/ios9/StackView/StackView/ViewController.cs +++ b/ios9/StackView/StackView/ViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using UIKit; -namespace StackView -{ - public partial class ViewController : UIViewController - { +namespace StackView { + public partial class ViewController : UIViewController { #region Computed Properties - public int Rating { get; set;} = 0; + public int Rating { get; set; } = 0; #endregion #region Constructors @@ -31,48 +29,50 @@ public override void DidReceiveMemoryWarning () #endregion #region Actions - partial void IncreaseRating (Foundation.NSObject sender) { + partial void IncreaseRating (Foundation.NSObject sender) + { // Maximum of 5 "stars" - if (++Rating > 5 ) { + if (++Rating > 5) { // Abort Rating = 5; return; } // Create new rating icon and add it to stack - var icon = new UIImageView (new UIImage("icon.png")); + var icon = new UIImageView (new UIImage ("icon.png")); icon.ContentMode = UIViewContentMode.ScaleAspectFit; - RatingView.AddArrangedSubview(icon); + RatingView.AddArrangedSubview (icon); // Animate stack - UIView.Animate(0.25, ()=>{ + UIView.Animate (0.25, () => { // Adjust stack view - RatingView.LayoutIfNeeded(); + RatingView.LayoutIfNeeded (); }); } - partial void DecreaseRating (Foundation.NSObject sender) { + partial void DecreaseRating (Foundation.NSObject sender) + { // Minimum of zero "stars" if (--Rating < 0) { // Abort - Rating =0; + Rating = 0; return; } // Get the last subview added - var icon = RatingView.ArrangedSubviews[RatingView.ArrangedSubviews.Length-1]; + var icon = RatingView.ArrangedSubviews [RatingView.ArrangedSubviews.Length - 1]; // Remove from stack and screen - RatingView.RemoveArrangedSubview(icon); - icon.RemoveFromSuperview(); + RatingView.RemoveArrangedSubview (icon); + icon.RemoveFromSuperview (); // Animate stack - UIView.Animate(0.25, ()=>{ + UIView.Animate (0.25, () => { // Adjust stack view - RatingView.LayoutIfNeeded(); + RatingView.LayoutIfNeeded (); }); } #endregion diff --git a/ios9/StickyCorners/StickyCorners/AppDelegate.cs b/ios9/StickyCorners/StickyCorners/AppDelegate.cs index eb9f2a2aa..d3bc31af3 100644 --- a/ios9/StickyCorners/StickyCorners/AppDelegate.cs +++ b/ios9/StickyCorners/StickyCorners/AppDelegate.cs @@ -1,14 +1,14 @@ -using Foundation; +using Foundation; using UIKit; namespace StickyCorners { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { - + public override UIWindow Window { get; set; } // There is no need for a FinishedLaunching method here as the // Main.storyboard is automagically loaded since it is specified // in the Info.plist -> <key>UIMainStoryboardFile~ipad</key> } -} \ No newline at end of file +} diff --git a/ios9/StickyCorners/StickyCorners/Main.cs b/ios9/StickyCorners/StickyCorners/Main.cs index 2871e5577..7d7821d1b 100644 --- a/ios9/StickyCorners/StickyCorners/Main.cs +++ b/ios9/StickyCorners/StickyCorners/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace StickyCorners -{ - public class Application - { +namespace StickyCorners { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/StickyCorners/StickyCorners/StickyCornersBehavior.cs b/ios9/StickyCorners/StickyCorners/StickyCornersBehavior.cs index 073732536..421099662 100644 --- a/ios9/StickyCorners/StickyCorners/StickyCornersBehavior.cs +++ b/ios9/StickyCorners/StickyCorners/StickyCornersBehavior.cs @@ -20,7 +20,7 @@ public sealed class StickyCornersBehavior : UIDynamicBehavior { UICollisionBehavior collisionBehavior; IUIDynamicItem item; List<UIFieldBehavior> fieldBehaviors; - + public StickyCorner CurrentCorner { get { var bounds = DynamicAnimator.ReferenceView.Bounds; @@ -34,7 +34,7 @@ public StickyCorner CurrentCorner { // Top left. if (rect.Contains (position)) return StickyCorner.TopLeft; - + // Bottom left. rect.Location = new CGPoint (0, halfHeight); if (rect.Contains (position)) @@ -113,7 +113,7 @@ public override void WillMoveToAnimator (UIDynamicAnimator targetAnimator) public CGPoint GetPositionForCorner (StickyCorner corner) { - return fieldBehaviors [(int)corner - 1].Position; + return fieldBehaviors [(int) corner - 1].Position; } public void UpdateFieldsInBounds (CGRect bounds) @@ -134,10 +134,10 @@ public void UpdateFieldsInBounds (CGRect bounds) var topRight = new CGPoint (w - dx, dy); var regionRect = new CGRect (dx, dy, w, h); - UpdateFieldBehaviour (fieldBehaviors [(int)StickyCorner.TopLeft - 1], topLeft, regionRect); - UpdateFieldBehaviour (fieldBehaviors [(int)StickyCorner.BottomLeft - 1], bottomLeft, regionRect); - UpdateFieldBehaviour (fieldBehaviors [(int)StickyCorner.BottomRight - 1], bottomRight, regionRect); - UpdateFieldBehaviour (fieldBehaviors [(int)StickyCorner.TopRight - 1], topRight, regionRect); + UpdateFieldBehaviour (fieldBehaviors [(int) StickyCorner.TopLeft - 1], topLeft, regionRect); + UpdateFieldBehaviour (fieldBehaviors [(int) StickyCorner.BottomLeft - 1], bottomLeft, regionRect); + UpdateFieldBehaviour (fieldBehaviors [(int) StickyCorner.BottomRight - 1], bottomRight, regionRect); + UpdateFieldBehaviour (fieldBehaviors [(int) StickyCorner.TopRight - 1], topRight, regionRect); } public void AddLinearVelocity (CGPoint velocity) diff --git a/ios9/StickyCorners/StickyCorners/StickyCornersViewController.cs b/ios9/StickyCorners/StickyCorners/StickyCornersViewController.cs index 2c5bb9e8c..92295cebe 100644 --- a/ios9/StickyCorners/StickyCorners/StickyCornersViewController.cs +++ b/ios9/StickyCorners/StickyCorners/StickyCornersViewController.cs @@ -39,7 +39,7 @@ public override void ViewDidLoad () View.AddGestureRecognizer (longPressGestureRecognizer); animator = new UIDynamicAnimator (View); - stickyBehavior = new StickyCornersBehavior (itemView, (float)length * 0.5f); + stickyBehavior = new StickyCornersBehavior (itemView, (float) length * 0.5f); animator.AddBehavior (stickyBehavior); } diff --git a/ios9/TouchCanvas/TouchCanvas/AppDelegate.cs b/ios9/TouchCanvas/TouchCanvas/AppDelegate.cs index 5d0458730..229216795 100644 --- a/ios9/TouchCanvas/TouchCanvas/AppDelegate.cs +++ b/ios9/TouchCanvas/TouchCanvas/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace TouchCanvas { diff --git a/ios9/TouchCanvas/TouchCanvas/Helpers/CGRectHelpers.cs b/ios9/TouchCanvas/TouchCanvas/Helpers/CGRectHelpers.cs index 424255650..58a639f7a 100644 --- a/ios9/TouchCanvas/TouchCanvas/Helpers/CGRectHelpers.cs +++ b/ios9/TouchCanvas/TouchCanvas/Helpers/CGRectHelpers.cs @@ -1,10 +1,8 @@ -using System; +using System; using CoreGraphics; -namespace TouchCanvas -{ - public static class CGRectHelpers - { +namespace TouchCanvas { + public static class CGRectHelpers { public static CGRect CGRectNull () { return new CGRect (nfloat.PositiveInfinity, nfloat.PositiveInfinity, 0, 0); diff --git a/ios9/TouchCanvas/TouchCanvas/Main.cs b/ios9/TouchCanvas/TouchCanvas/Main.cs index 21300f026..f430ef8e3 100644 --- a/ios9/TouchCanvas/TouchCanvas/Main.cs +++ b/ios9/TouchCanvas/TouchCanvas/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace TouchCanvas -{ - public class Application - { +namespace TouchCanvas { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/TouchCanvas/TouchCanvas/Model/Line.cs b/ios9/TouchCanvas/TouchCanvas/Model/Line.cs index 40eca0d1f..8325b5ffe 100644 --- a/ios9/TouchCanvas/TouchCanvas/Model/Line.cs +++ b/ios9/TouchCanvas/TouchCanvas/Model/Line.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; @@ -27,7 +27,7 @@ public bool UpdateWithTouch (UITouch touch, out CGRect rect) rect = CGRectNull (); var estimationUpdateIndex = touch.EstimationUpdateIndex; - var point = pointsWaitingForUpdatesByEstimationIndex[estimationUpdateIndex]; + var point = pointsWaitingForUpdatesByEstimationIndex [estimationUpdateIndex]; if (point != null) { rect = UpdateRectForExistingPoint (point); var didUpdate = point.UpdateWithTouch (touch); @@ -116,7 +116,7 @@ public void DrawInContext (CGContext context, bool isDebuggingEnabled, bool useP color = UIColor.Red; else if (pointType.HasFlag (PointType.Finger)) color = UIColor.Purple; - + if (pointType.HasFlag (PointType.Predicted) && !pointType.HasFlag (PointType.Cancelled)) color = color.ColorWithAlpha (.5f); } @@ -133,9 +133,9 @@ public void DrawInContext (CGContext context, bool isDebuggingEnabled, bool useP // Draw azimuith and elevation on all non-coalesced points when debugging. if (isDebuggingEnabled && - !point.PointType.HasFlag (PointType.Coalesced) && - !point.PointType.HasFlag (PointType.Predicted) && - !point.PointType.HasFlag (PointType.Finger)) { + !point.PointType.HasFlag (PointType.Coalesced) && + !point.PointType.HasFlag (PointType.Predicted) && + !point.PointType.HasFlag (PointType.Finger)) { context.BeginPath (); context.SetStrokeColor (UIColor.Red.CGColor); context.SetLineWidth (.5f); @@ -162,7 +162,7 @@ public void DrawFixedPointsInContext (CGContext context, bool isDebuggingEnabled Points.Clear (); } else { for (int i = 0; i < allPoints.Count; i++) { - var point = allPoints[i]; + var point = allPoints [i]; if (!point.PointType.HasFlag (PointType.NeedsUpdate | PointType.Predicted) || i >= (allPoints.Count - 2)) { committing.Add (Points.First ()); break; @@ -235,12 +235,12 @@ CGRect UpdateRectForExistingPoint (LinePoint point) var arrayIndex = point.SequenceNumber - Points.First ().SequenceNumber; if (arrayIndex > 0 && arrayIndex + 1 < Points.Count) - rect = rect.UnionWith (UpdateRectForLinePoint (point, Points[arrayIndex - 1])); + rect = rect.UnionWith (UpdateRectForLinePoint (point, Points [arrayIndex - 1])); if (arrayIndex + 1 < Points.Count && arrayIndex + 1 > 0) - rect = rect.UnionWith (UpdateRectForLinePoint (point, Points[arrayIndex + 1])); + rect = rect.UnionWith (UpdateRectForLinePoint (point, Points [arrayIndex + 1])); return rect; } } -} \ No newline at end of file +} diff --git a/ios9/TouchCanvas/TouchCanvas/Model/LinePoint.cs b/ios9/TouchCanvas/TouchCanvas/Model/LinePoint.cs index bdd4999b7..4bca83649 100644 --- a/ios9/TouchCanvas/TouchCanvas/Model/LinePoint.cs +++ b/ios9/TouchCanvas/TouchCanvas/Model/LinePoint.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreGraphics; using Foundation; @@ -74,11 +74,11 @@ public LinePoint (UITouch touch, int sequenceNumber, PointType pointType) public bool UpdateWithTouch (UITouch touch) { - if (!touch.EstimationUpdateIndex.IsEqualTo(EstimationUpdateIndex)) + if (!touch.EstimationUpdateIndex.IsEqualTo (EstimationUpdateIndex)) return false; // An array of the touch properties that may be of interest. - UITouchProperties[] touchProperties = { + UITouchProperties [] touchProperties = { UITouchProperties.Location, UITouchProperties.Force, UITouchProperties.Altitude, @@ -125,4 +125,4 @@ public bool UpdateWithTouch (UITouch touch) return true; } } -} \ No newline at end of file +} diff --git a/ios9/TouchCanvas/TouchCanvas/UI/CanvasView.cs b/ios9/TouchCanvas/TouchCanvas/UI/CanvasView.cs index d12206448..4ec8dbeda 100644 --- a/ios9/TouchCanvas/TouchCanvas/UI/CanvasView.cs +++ b/ios9/TouchCanvas/TouchCanvas/UI/CanvasView.cs @@ -64,7 +64,7 @@ public CGBitmapContext FrozenContext { size.Height *= scale; var colorSpace = CGColorSpace.CreateDeviceRGB (); - frozenContext = new CGBitmapContext (null, (nint)size.Width, (nint)size.Height, 8, 0, colorSpace, CGImageAlphaInfo.PremultipliedLast); + frozenContext = new CGBitmapContext (null, (nint) size.Width, (nint) size.Height, 8, 0, colorSpace, CGImageAlphaInfo.PremultipliedLast); frozenContext.SetLineCap (CGLineCap.Round); frozenContext.ConcatCTM (CGAffineTransform.MakeScale (scale, scale)); } @@ -102,7 +102,7 @@ public override void Draw (CGRect rect) } frozenImage = frozenImage ?? FrozenContext.ToImage (); - if(frozenImage != null) + if (frozenImage != null) context.DrawImage (Bounds, frozenImage); foreach (var line in lines) @@ -143,7 +143,7 @@ public void DrawTouches (NSSet touches, UIEvent evt) // Incorporate coalesced touch data. The data in the last touch in the returned array will match // the data of the touch supplied to GetCoalescedTouches - var coalescedTouches = evt.GetCoalescedTouches (touch) ?? new UITouch[0]; + var coalescedTouches = evt.GetCoalescedTouches (touch) ?? new UITouch [0]; var coalescedRect = AddPointsOfType (PointType.Coalesced, coalescedTouches, line); updateRect = updateRect.UnionWith (coalescedRect); @@ -151,7 +151,7 @@ public void DrawTouches (NSSet touches, UIEvent evt) // you may want to use them as inputs to smoothing algorithms rather than directly drawing them. // Points derived from predicted touches should be removed from the line at the next event for this touch. if (isPredictionEnabled) { - var predictedTouches = evt.GetPredictedTouches (touch) ?? new UITouch[0]; + var predictedTouches = evt.GetPredictedTouches (touch) ?? new UITouch [0]; var predictedRect = AddPointsOfType (PointType.Predicted, predictedTouches, line); updateRect = updateRect.UnionWith (predictedRect); } @@ -167,7 +167,7 @@ Line AddActiveLineForTouch (UITouch touch) return newLine; } - CGRect AddPointsOfType (PointType type, UITouch[] touches, Line line) + CGRect AddPointsOfType (PointType type, UITouch [] touches, Line line) { var accumulatedRect = CGRectNull (); diff --git a/ios9/TouchCanvas/TouchCanvas/UI/MainViewController.cs b/ios9/TouchCanvas/TouchCanvas/UI/MainViewController.cs index 57affa86a..bfc2563b3 100644 --- a/ios9/TouchCanvas/TouchCanvas/UI/MainViewController.cs +++ b/ios9/TouchCanvas/TouchCanvas/UI/MainViewController.cs @@ -25,7 +25,7 @@ ReticleView ReticleView { public CanvasView CanvasView { get { - return (CanvasView)View; + return (CanvasView) View; } } @@ -69,7 +69,7 @@ public override void TouchesMoved (NSSet touches, UIEvent evt) UpdateReticleView (touch); - UITouch[] predictedTouches = evt?.GetPredictedTouches (touch); + UITouch [] predictedTouches = evt?.GetPredictedTouches (touch); UITouch predictedTouch = predictedTouches?.LastOrDefault (); if (predictedTouch != null) diff --git a/ios9/TouchCanvas/TouchCanvas/UI/ReticleView.cs b/ios9/TouchCanvas/TouchCanvas/UI/ReticleView.cs index 73b7e7514..60d91f951 100644 --- a/ios9/TouchCanvas/TouchCanvas/UI/ReticleView.cs +++ b/ios9/TouchCanvas/TouchCanvas/UI/ReticleView.cs @@ -1,4 +1,4 @@ -using System; +using System; using UIKit; using CoreAnimation; @@ -221,4 +221,4 @@ static void ConfigureLineLayer (CALayer targetLayer, UIColor color) targetLayer.Position = CGPoint.Empty; } } -} \ No newline at end of file +} diff --git a/ios9/ViewControllerPreview/ViewControllerPreview/AppDelegate.cs b/ios9/ViewControllerPreview/ViewControllerPreview/AppDelegate.cs index 9ae63df7f..d5e672be5 100644 --- a/ios9/ViewControllerPreview/ViewControllerPreview/AppDelegate.cs +++ b/ios9/ViewControllerPreview/ViewControllerPreview/AppDelegate.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace ViewControllerPreview { @@ -27,4 +27,4 @@ public virtual bool CollapseSecondViewController (UISplitViewController splitVie } } - + diff --git a/ios9/ViewControllerPreview/ViewControllerPreview/DetailViewController.cs b/ios9/ViewControllerPreview/ViewControllerPreview/DetailViewController.cs index 2eb7b859e..1bd23ac3a 100644 --- a/ios9/ViewControllerPreview/ViewControllerPreview/DetailViewController.cs +++ b/ios9/ViewControllerPreview/ViewControllerPreview/DetailViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; @@ -7,13 +7,13 @@ namespace ViewControllerPreview { public partial class DetailViewController : UIViewController { public string DetailItemTitle { get; set; } - public override IUIPreviewActionItem[] PreviewActionItems { + public override IUIPreviewActionItem [] PreviewActionItems { get { return PreviewActions; } } - IUIPreviewActionItem[] PreviewActions { + IUIPreviewActionItem [] PreviewActions { get { var action1 = PreviewActionForTitle ("Default Action"); var action2 = PreviewActionForTitle ("Destructive Action", UIPreviewActionStyle.Destructive); @@ -44,7 +44,7 @@ public override void ViewDidLoad () static UIPreviewAction PreviewActionForTitle (string title, UIPreviewActionStyle style = UIPreviewActionStyle.Default) { return UIPreviewAction.Create (title, style, (action, previewViewController) => { - var detailViewController = (DetailViewController)previewViewController; + var detailViewController = (DetailViewController) previewViewController; var item = detailViewController?.DetailItemTitle; Console.WriteLine ("{0} triggered from `DetailViewController` for item: {1}", action.Title, item); diff --git a/ios9/ViewControllerPreview/ViewControllerPreview/Main.cs b/ios9/ViewControllerPreview/ViewControllerPreview/Main.cs index 1b7c5ad97..a6bc327d6 100644 --- a/ios9/ViewControllerPreview/ViewControllerPreview/Main.cs +++ b/ios9/ViewControllerPreview/ViewControllerPreview/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace ViewControllerPreview -{ - public class Application - { +namespace ViewControllerPreview { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/ViewControllerPreview/ViewControllerPreview/MasterViewController.cs b/ios9/ViewControllerPreview/ViewControllerPreview/MasterViewController.cs index 970474879..4f748df36 100644 --- a/ios9/ViewControllerPreview/ViewControllerPreview/MasterViewController.cs +++ b/ios9/ViewControllerPreview/ViewControllerPreview/MasterViewController.cs @@ -6,14 +6,13 @@ namespace ViewControllerPreview { public partial class MasterViewController : UITableViewController, IUIViewControllerPreviewingDelegate { - class PreviewDetail - { + class PreviewDetail { public string Title { get; set; } public double PreferredHeight { get; set; } } - readonly PreviewDetail[] sampleData = { + readonly PreviewDetail [] sampleData = { new PreviewDetail { Title = "Small", PreferredHeight = 160 }, new PreviewDetail { Title = "Medium", PreferredHeight = 320 }, new PreviewDetail { Title = "Large", PreferredHeight = 0 } @@ -34,19 +33,19 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - + } - public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection) - { - //Important: Must call base method - base.TraitCollectionDidChange(previousTraitCollection); + public override void TraitCollectionDidChange (UITraitCollection previousTraitCollection) + { + //Important: Must call base method + base.TraitCollectionDidChange (previousTraitCollection); - if (TraitCollection.ForceTouchCapability == UIForceTouchCapability.Available) - RegisterForPreviewingWithDelegate (this, View); - else - alertController = UIAlertController.Create ("3D Touch Not Available", "Unsupported device.", UIAlertControllerStyle.Alert); - } + if (TraitCollection.ForceTouchCapability == UIForceTouchCapability.Available) + RegisterForPreviewingWithDelegate (this, View); + else + alertController = UIAlertController.Create ("3D Touch Not Available", "Unsupported device.", UIAlertControllerStyle.Alert); + } public override void ViewWillAppear (bool animated) { @@ -72,9 +71,9 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) return; var indexPath = TableView.IndexPathForSelectedRow; - var previewDetail = sampleData[indexPath.Row]; + var previewDetail = sampleData [indexPath.Row]; - var detailViewController = (DetailViewController)((UINavigationController)segue.DestinationViewController)?.TopViewController; + var detailViewController = (DetailViewController) ((UINavigationController) segue.DestinationViewController)?.TopViewController; // Pass the `title` to the `detailViewController`. detailViewController.DetailItemTitle = previewDetail.Title; @@ -108,7 +107,7 @@ public UIViewController GetViewControllerForPreview (IUIViewControllerPreviewing return null; // Create a detail view controller and set its properties. - var detailViewController = (DetailViewController)Storyboard.InstantiateViewController ("DetailViewController"); + var detailViewController = (DetailViewController) Storyboard.InstantiateViewController ("DetailViewController"); if (detailViewController == null) return null; diff --git a/ios9/iTravel/iTravel/AlbumViewController.cs b/ios9/iTravel/iTravel/AlbumViewController.cs index 1d4d6d622..e6b62d360 100644 --- a/ios9/iTravel/iTravel/AlbumViewController.cs +++ b/ios9/iTravel/iTravel/AlbumViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; @@ -14,7 +14,7 @@ public partial class AlbumViewController : UIViewController, IUITableViewDataSou NSBundleResourceRequest request; List<PreviewDetail> previewDetails = new List<PreviewDetail> (); - protected AlbumViewController(IntPtr handle) : base (handle) + protected AlbumViewController (IntPtr handle) : base (handle) { } @@ -48,9 +48,9 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio { if (context == progressObserverContext && keyPath == "fractionCompleted") { NSOperationQueue.MainQueue.AddOperation (() => { - var progress = (NSProgress)ofObject; + var progress = (NSProgress) ofObject; - ProgressView.Progress = (float)progress.FractionCompleted; + ProgressView.Progress = (float) progress.FractionCompleted; DetailsLabel.Text = progress.LocalizedDescription; }); } else { @@ -88,8 +88,8 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) return; var selectedRowIndex = CustomTableView.IndexPathForSelectedRow.Row; - albumViewController.PictureName = previewDetails[selectedRowIndex].Picture; - albumViewController.Title = previewDetails[selectedRowIndex].Caption; + albumViewController.PictureName = previewDetails [selectedRowIndex].Picture; + albumViewController.Title = previewDetails [selectedRowIndex].Caption; } [Export ("numberOfSectionsInTableView:")] diff --git a/ios9/iTravel/iTravel/AppDelegate.cs b/ios9/iTravel/iTravel/AppDelegate.cs index 27aa54aa8..077db4cbf 100644 --- a/ios9/iTravel/iTravel/AppDelegate.cs +++ b/ios9/iTravel/iTravel/AppDelegate.cs @@ -1,8 +1,8 @@ -using Foundation; +using Foundation; using UIKit; namespace iTravel { - [Register("AppDelegate")] + [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } diff --git a/ios9/iTravel/iTravel/ImageViewController.cs b/ios9/iTravel/iTravel/ImageViewController.cs index 91b9cc133..6eb384864 100644 --- a/ios9/iTravel/iTravel/ImageViewController.cs +++ b/ios9/iTravel/iTravel/ImageViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; @@ -6,7 +6,7 @@ namespace iTravel { public partial class ImageViewController : UIViewController { public string PictureName { get; set; } - protected ImageViewController(IntPtr handle) : base (handle) + protected ImageViewController (IntPtr handle) : base (handle) { } diff --git a/ios9/iTravel/iTravel/Main.cs b/ios9/iTravel/iTravel/Main.cs index a1366c006..a8cf04026 100644 --- a/ios9/iTravel/iTravel/Main.cs +++ b/ios9/iTravel/iTravel/Main.cs @@ -1,9 +1,9 @@ -using UIKit; +using UIKit; namespace iTravel { public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/ios9/iTravel/iTravel/PreviewDetail.cs b/ios9/iTravel/iTravel/PreviewDetail.cs index f0d091924..1ae9448f9 100644 --- a/ios9/iTravel/iTravel/PreviewDetail.cs +++ b/ios9/iTravel/iTravel/PreviewDetail.cs @@ -1,4 +1,4 @@ -using Newtonsoft.Json; +using Newtonsoft.Json; namespace iTravel { public class PreviewDetail { diff --git a/ios9/iTravel/iTravel/ViewController.cs b/ios9/iTravel/iTravel/ViewController.cs index 5348c9cdc..931b34b35 100644 --- a/ios9/iTravel/iTravel/ViewController.cs +++ b/ios9/iTravel/iTravel/ViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; @@ -28,7 +28,7 @@ public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) return; var indexPath = TableView.IndexPathForSelectedRow; - var previewDetail = sampleData[indexPath.Row]; + var previewDetail = sampleData [indexPath.Row]; var albumViewController = segue.DestinationViewController as AlbumViewController; if (albumViewController == null) @@ -46,7 +46,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = TableView.DequeueReusableCell ("Cell"); - var previewDetail = sampleData[indexPath.Row]; + var previewDetail = sampleData [indexPath.Row]; cell.TextLabel.Text = previewDetail.Title; return cell; } diff --git a/nnyeah-samples/geo/AppDelegate.cs b/nnyeah-samples/geo/AppDelegate.cs index a3a336e80..3468c3fc7 100644 --- a/nnyeah-samples/geo/AppDelegate.cs +++ b/nnyeah-samples/geo/AppDelegate.cs @@ -31,8 +31,8 @@ public override bool FinishedLaunching (UIApplication application, NSDictionary // make the window visible Window.MakeKeyAndVisible (); - - Task.Run(() => Query ()); + + Task.Run (() => Query ()); return true; } @@ -51,8 +51,7 @@ async void Query () SetTextOnMainThread ("checking if we can get location"); if (!CrossGeolocator.Current.IsGeolocationAvailable) { SetTextOnMainThread ("Does not have permissions!"); - } - else { + } else { SetTextOnMainThread ("getting position."); var position = await GetPosition (); if (position is not null) { @@ -75,7 +74,7 @@ async void Query () return position; } catch (Exception e) { - SetTextOnMainThread ($"Oops: {e.GetType().Name} - {e.Message}\n{e.StackTrace}"); + SetTextOnMainThread ($"Oops: {e.GetType ().Name} - {e.Message}\n{e.StackTrace}"); return null; } } diff --git a/nnyeah-samples/sidebar/AppDelegate.cs b/nnyeah-samples/sidebar/AppDelegate.cs index 37e1179c1..78f08511f 100644 --- a/nnyeah-samples/sidebar/AppDelegate.cs +++ b/nnyeah-samples/sidebar/AppDelegate.cs @@ -1,13 +1,11 @@ using Foundation; using UIKit; -namespace StoryboardSample -{ +namespace StoryboardSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow? Window { @@ -20,7 +18,7 @@ public override UIWindow? Window { public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // create a new window instance based on the screen size - Window = new UIWindow(UIScreen.MainScreen.Bounds); + Window = new UIWindow (UIScreen.MainScreen.Bounds); // If you have defined a root view controller, set it here: Window.RootViewController = new RootViewController (); diff --git a/nnyeah-samples/sidebar/BaseController.cs b/nnyeah-samples/sidebar/BaseController.cs index 663329d37..decb482fc 100644 --- a/nnyeah-samples/sidebar/BaseController.cs +++ b/nnyeah-samples/sidebar/BaseController.cs @@ -4,19 +4,17 @@ using UIKit; using ObjCRuntime; -namespace StoryboardSample -{ - public partial class BaseController : UIViewController - { +namespace StoryboardSample { + public partial class BaseController : UIViewController { // provide access to the sidebar controller to all inheriting controllers - protected SidebarNavigation.SidebarController? SidebarController { + protected SidebarNavigation.SidebarController? SidebarController { get { return (UIApplication.SharedApplication.Delegate as AppDelegate)?.RootViewController?.SidebarController; - } + } } // provide access to the navigation controller to all inheriting controllers - protected NavController NavController { + protected NavController NavController { get { if (UIApplication.SharedApplication.Delegate is AppDelegate appDelegate && appDelegate.RootViewController is not null) { return appDelegate.RootViewController.NavController; @@ -24,11 +22,11 @@ protected NavController NavController { Console.WriteLine ("NavController failed"); throw new NotSupportedException ("unable to get root view controller."); } - } + } } // provide access to the storyboard to all inheriting controllers - public override UIStoryboard Storyboard { + public override UIStoryboard Storyboard { get { if (UIApplication.SharedApplication.Delegate is AppDelegate appDelegate && appDelegate.RootViewController is not null) { return appDelegate.RootViewController.Storyboard; @@ -36,7 +34,7 @@ public override UIStoryboard Storyboard { Console.WriteLine ("Storyboard failed."); throw new NotSupportedException ("unable to get storyboard."); } - } + } } public BaseController (NativeHandle handle) : base (handle) @@ -54,7 +52,8 @@ public override void ViewDidLoad () ButtonHandler), true); } - void ButtonHandler (object? sender, EventArgs e) { + void ButtonHandler (object? sender, EventArgs e) + { if (SidebarController is not null) { SidebarController.ToggleMenu (); } diff --git a/nnyeah-samples/sidebar/ContentController.cs b/nnyeah-samples/sidebar/ContentController.cs index 177a2b9d7..ef2ccf43e 100644 --- a/nnyeah-samples/sidebar/ContentController.cs +++ b/nnyeah-samples/sidebar/ContentController.cs @@ -4,10 +4,8 @@ using UIKit; using ObjCRuntime; -namespace StoryboardSample -{ - partial class ContentController : BaseController - { +namespace StoryboardSample { + partial class ContentController : BaseController { public ContentController (NativeHandle handle) : base (handle) { } diff --git a/nnyeah-samples/sidebar/IntroController.cs b/nnyeah-samples/sidebar/IntroController.cs index de1a3a8c9..06a6da839 100644 --- a/nnyeah-samples/sidebar/IntroController.cs +++ b/nnyeah-samples/sidebar/IntroController.cs @@ -4,10 +4,8 @@ using UIKit; using ObjCRuntime; -namespace StoryboardSample -{ - partial class IntroController : BaseController - { +namespace StoryboardSample { + partial class IntroController : BaseController { public IntroController (NativeHandle handle) : base (handle) { } diff --git a/nnyeah-samples/sidebar/Main.cs b/nnyeah-samples/sidebar/Main.cs index 952722f91..ffe393aad 100644 --- a/nnyeah-samples/sidebar/Main.cs +++ b/nnyeah-samples/sidebar/Main.cs @@ -1,15 +1,13 @@ using UIKit; -namespace StoryboardSample -{ - public class Application - { +namespace StoryboardSample { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, typeof (UIApplication), typeof (AppDelegate)); + UIApplication.Main (args, typeof (UIApplication), typeof (AppDelegate)); } } } diff --git a/nnyeah-samples/sidebar/MenuController.cs b/nnyeah-samples/sidebar/MenuController.cs index 3beb17751..e54942b5b 100644 --- a/nnyeah-samples/sidebar/MenuController.cs +++ b/nnyeah-samples/sidebar/MenuController.cs @@ -4,10 +4,8 @@ using UIKit; using ObjCRuntime; -namespace StoryboardSample -{ - partial class MenuController : BaseController - { +namespace StoryboardSample { + partial class MenuController : BaseController { public MenuController (NativeHandle handle) : base (handle) { } @@ -16,7 +14,7 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - var contentController = (ContentController)Storyboard.InstantiateViewController ("ContentController"); + var contentController = (ContentController) Storyboard.InstantiateViewController ("ContentController"); ContentButton.TouchUpInside += (o, e) => { if (NavController.TopViewController as ContentController is null) diff --git a/nnyeah-samples/sidebar/NavController.cs b/nnyeah-samples/sidebar/NavController.cs index 74708989a..8fb758c9a 100644 --- a/nnyeah-samples/sidebar/NavController.cs +++ b/nnyeah-samples/sidebar/NavController.cs @@ -5,17 +5,15 @@ using Foundation; using UIKit; -namespace StoryboardSample -{ - public partial class NavController : UINavigationController - { - public NavController () : base ((string)null, null) +namespace StoryboardSample { + public partial class NavController : UINavigationController { + public NavController () : base ((string) null, null) { } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. } diff --git a/nnyeah-samples/sidebar/RootViewController.cs b/nnyeah-samples/sidebar/RootViewController.cs index 9a9b84db8..a21751954 100644 --- a/nnyeah-samples/sidebar/RootViewController.cs +++ b/nnyeah-samples/sidebar/RootViewController.cs @@ -5,10 +5,8 @@ using CoreGraphics; using SidebarNavigation; -namespace StoryboardSample -{ - public partial class RootViewController : UIViewController - { +namespace StoryboardSample { + public partial class RootViewController : UIViewController { private UIStoryboard? _storyboard; @@ -22,12 +20,12 @@ public partial class RootViewController : UIViewController public override UIStoryboard Storyboard { get { if (_storyboard is null) - _storyboard = UIStoryboard.FromName("Phone", null); + _storyboard = UIStoryboard.FromName ("Phone", null); return _storyboard; } } - public RootViewController () : base(null, null) + public RootViewController () : base (null, null) { } @@ -36,12 +34,12 @@ public override void ViewDidLoad () { base.ViewDidLoad (); - var introController = (IntroController)Storyboard.InstantiateViewController("IntroController"); - var menuController = (MenuController)Storyboard.InstantiateViewController("MenuController"); + var introController = (IntroController) Storyboard.InstantiateViewController ("IntroController"); + var menuController = (MenuController) Storyboard.InstantiateViewController ("MenuController"); // create a slideout navigation controller with the top navigation controller and the menu view controller NavController = new NavController (); - NavController.PushViewController(introController, false); + NavController.PushViewController (introController, false); SidebarController = new SidebarNavigation.SidebarController (this, NavController, menuController); SidebarController.MenuWidth = 220; SidebarController.ReopenOnRotate = false; diff --git a/tvos/Hello-tvOS/Hello-tvOS/AppDelegate.cs b/tvos/Hello-tvOS/Hello-tvOS/AppDelegate.cs index 7ca3920e5..51799c71b 100644 --- a/tvos/Hello-tvOS/Hello-tvOS/AppDelegate.cs +++ b/tvos/Hello-tvOS/Hello-tvOS/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace HellotvOS -{ +namespace HellotvOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/Hello-tvOS/Hello-tvOS/Main.cs b/tvos/Hello-tvOS/Hello-tvOS/Main.cs index 69adaeb7e..a026750c2 100644 --- a/tvos/Hello-tvOS/Hello-tvOS/Main.cs +++ b/tvos/Hello-tvOS/Hello-tvOS/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace HellotvOS -{ - public class Application - { +namespace HellotvOS { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/Hello-tvOS/Hello-tvOS/ViewController.cs b/tvos/Hello-tvOS/Hello-tvOS/ViewController.cs index fd9ce3f6d..061176095 100644 --- a/tvos/Hello-tvOS/Hello-tvOS/ViewController.cs +++ b/tvos/Hello-tvOS/Hello-tvOS/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { private int numberOfTimesClicked = 0; public ViewController (IntPtr handle) : base (handle) @@ -16,7 +14,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -25,7 +23,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Set the initial value for the label ClickedLabel.Text = "Button has not been clicked yet."; } @@ -53,10 +51,11 @@ public override void ViewDidDisappear (bool animated) #endregion #region Actions - partial void ClickedButton (Foundation.NSObject sender) { + partial void ClickedButton (Foundation.NSObject sender) + { // Update counter and label - ClickedLabel.Text = string.Format("The button has been clicked {0} time{1}.",++numberOfTimesClicked, (numberOfTimesClicked < 2) ? "" : "s"); + ClickedLabel.Text = string.Format ("The button has been clicked {0} time{1}.", ++numberOfTimesClicked, (numberOfTimesClicked < 2) ? "" : "s"); } #endregion } diff --git a/tvos/UICatalog/UICatalog/AppDelegate.cs b/tvos/UICatalog/UICatalog/AppDelegate.cs index 5e7f32e65..4db261cb1 100644 --- a/tvos/UICatalog/UICatalog/AppDelegate.cs +++ b/tvos/UICatalog/UICatalog/AppDelegate.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; diff --git a/tvos/UICatalog/UICatalog/ControlSamples/ButtonsViewController.cs b/tvos/UICatalog/UICatalog/ControlSamples/ButtonsViewController.cs index ed2fe79f1..0ef02d9b9 100644 --- a/tvos/UICatalog/UICatalog/ControlSamples/ButtonsViewController.cs +++ b/tvos/UICatalog/UICatalog/ControlSamples/ButtonsViewController.cs @@ -1,4 +1,4 @@ -using System; +using System; using Foundation; using UIKit; @@ -7,7 +7,7 @@ namespace UICatalog { public partial class ButtonsViewController : UIViewController { [Export ("initWithCoder:")] - public ButtonsViewController (NSCoder coder): base (coder) + public ButtonsViewController (NSCoder coder) : base (coder) { } diff --git a/tvos/UICatalog/UICatalog/ControlSamples/ControlsMenuViewController.cs b/tvos/UICatalog/UICatalog/ControlSamples/ControlsMenuViewController.cs index 6bf5b4235..6ac5207d0 100644 --- a/tvos/UICatalog/UICatalog/ControlSamples/ControlsMenuViewController.cs +++ b/tvos/UICatalog/UICatalog/ControlSamples/ControlsMenuViewController.cs @@ -3,10 +3,10 @@ namespace UICatalog { public partial class ControlsMenuViewController : MenuTableViewController { - List<string[]> segueIdentifierMap; - public override List<string[]> SegueIdentifierMap { + List<string []> segueIdentifierMap; + public override List<string []> SegueIdentifierMap { get { - segueIdentifierMap = segueIdentifierMap ?? new List<string[]> { + segueIdentifierMap = segueIdentifierMap ?? new List<string []> { new [] { "ShowButtons", "ShowProgressViews", diff --git a/tvos/UICatalog/UICatalog/ControlSamples/ProgressViewController.cs b/tvos/UICatalog/UICatalog/ControlSamples/ProgressViewController.cs index 7477d8343..24e077297 100644 --- a/tvos/UICatalog/UICatalog/ControlSamples/ProgressViewController.cs +++ b/tvos/UICatalog/UICatalog/ControlSamples/ProgressViewController.cs @@ -15,7 +15,7 @@ public partial class ProgressViewController : UIViewController { }; [Export ("initWithCoder:")] - public ProgressViewController (NSCoder coder): base (coder) + public ProgressViewController (NSCoder coder) : base (coder) { Initialize (); } @@ -25,10 +25,10 @@ public void Initialize () progress.AddObserver (this, "fractionCompleted", NSKeyValueObservingOptions.New, progressViewKVOContext); } - protected override void Dispose(bool disposing) + protected override void Dispose (bool disposing) { if (disposed) - return; + return; if (disposing) progress.RemoveObserver (this, "fractionCompleted"); @@ -59,7 +59,7 @@ public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictio if (context == progressViewKVOContext && keyPath == "fractionCompleted" && ofObject == progress) { InvokeOnMainThread (() => { foreach (var progressView in ProgressViews) - progressView.SetProgress ((float)progress.FractionCompleted, true); + progressView.SetProgress ((float) progress.FractionCompleted, true); }); } else { base.ObserveValue (keyPath, ofObject, change, context); diff --git a/tvos/UICatalog/UICatalog/ControlSamples/SegmentedControlsViewController.cs b/tvos/UICatalog/UICatalog/ControlSamples/SegmentedControlsViewController.cs index cb5d699af..3afdc85d4 100644 --- a/tvos/UICatalog/UICatalog/ControlSamples/SegmentedControlsViewController.cs +++ b/tvos/UICatalog/UICatalog/ControlSamples/SegmentedControlsViewController.cs @@ -5,7 +5,7 @@ namespace UICatalog { public partial class SegmentedControlsViewController : UIViewController { [Export ("initWithCoder:")] - public SegmentedControlsViewController (NSCoder coder): base (coder) + public SegmentedControlsViewController (NSCoder coder) : base (coder) { } @@ -32,15 +32,15 @@ void ConfigureCustomBackgroundSegmentedControl () //TODO fix it https://bugzilla.xamarin.com/show_bug.cgi?id=35338 // Create a font to use for the attributed title (both normal and highlighted states). -// var font = UIFont.FromName (".HelveticaNeueInterface-M3", 30f); + // var font = UIFont.FromName (".HelveticaNeueInterface-M3", 30f); -// var normalTextAttributes = new UITextAttributes { -// TextColor = UIColor.Purple, -// Font = font -// }; + // var normalTextAttributes = new UITextAttributes { + // TextColor = UIColor.Purple, + // Font = font + // }; -// CustomBackgroundSegmentControl.SetTitleTextAttributes (normalTextAttributes, UIControlState.Normal); -// CustomBackgroundSegmentControl.SetTitleTextAttributes (normalTextAttributes, UIControlState.Highlighted); + // CustomBackgroundSegmentControl.SetTitleTextAttributes (normalTextAttributes, UIControlState.Normal); + // CustomBackgroundSegmentControl.SetTitleTextAttributes (normalTextAttributes, UIControlState.Highlighted); } } } diff --git a/tvos/UICatalog/UICatalog/DataItemCellComposer.cs b/tvos/UICatalog/UICatalog/DataItemCellComposer.cs index 43a16771d..aa11538ca 100644 --- a/tvos/UICatalog/UICatalog/DataItemCellComposer.cs +++ b/tvos/UICatalog/UICatalog/DataItemCellComposer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using CoreFoundation; @@ -10,7 +10,7 @@ namespace UICatalog { public class DataItemCellComposer { readonly static NSCache processedImageCache = new NSCache (); - readonly Dictionary <DataItemCollectionViewCell, NSOperationQueue> operationQueues = new Dictionary<DataItemCollectionViewCell, NSOperationQueue> (); + readonly Dictionary<DataItemCollectionViewCell, NSOperationQueue> operationQueues = new Dictionary<DataItemCollectionViewCell, NSOperationQueue> (); public void ComposeCell (DataItemCollectionViewCell cell, DataItem dataItem) { @@ -20,7 +20,7 @@ public void ComposeCell (DataItemCollectionViewCell cell, DataItem dataItem) cell.RepresentedDataItem = dataItem; cell.Label.Text = dataItem.Title; cell.ImageView.Alpha = 1f; - cell.ImageView.Image = (UIImage)processedImageCache.ObjectForKey ((NSString)dataItem.Identifier); + cell.ImageView.Image = (UIImage) processedImageCache.ObjectForKey ((NSString) dataItem.Identifier); if (cell.ImageView.Image != null) return; @@ -38,7 +38,7 @@ public void ComposeCell (DataItemCollectionViewCell cell, DataItem dataItem) if (image == null) return; - processedImageCache.SetObjectforKey (image, (NSString)dataItem.Identifier); + processedImageCache.SetObjectforKey (image, (NSString) dataItem.Identifier); NSOperationQueue.MainQueue.AddOperation (() => { if (cell.RepresentedDataItem == null) return; @@ -77,8 +77,8 @@ static UIImage ProcessImageNamed (string imageName) using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) { // Create a bitmap context of the same size as the image. - var imageWidth = (int)image.Size.Width; - var imageHeight = (int)image.Size.Height; + var imageWidth = (int) image.Size.Width; + var imageHeight = (int) image.Size.Height; using (var bitmapContext = new CGBitmapContext (null, imageWidth, imageHeight, 8, imageHeight * 4, colorSpace, CGBitmapFlags.PremultipliedLast | CGBitmapFlags.ByteOrder32Little)) { diff --git a/tvos/UICatalog/UICatalog/DataItemCollectionViewCell.cs b/tvos/UICatalog/UICatalog/DataItemCollectionViewCell.cs index 4caeeb1d4..754ffa054 100644 --- a/tvos/UICatalog/UICatalog/DataItemCollectionViewCell.cs +++ b/tvos/UICatalog/UICatalog/DataItemCollectionViewCell.cs @@ -1,4 +1,4 @@ -using Foundation; +using Foundation; using UIKit; namespace UICatalog { @@ -10,7 +10,7 @@ public partial class DataItemCollectionViewCell : UICollectionViewCell { public DataItem RepresentedDataItem { get; set; } [Export ("initWithCoder:")] - public DataItemCollectionViewCell (NSCoder coder): base (coder) + public DataItemCollectionViewCell (NSCoder coder) : base (coder) { } diff --git a/tvos/UICatalog/UICatalog/DataItems/DataItem.cs b/tvos/UICatalog/UICatalog/DataItems/DataItem.cs index c1d82e4a4..fea42b4fb 100644 --- a/tvos/UICatalog/UICatalog/DataItems/DataItem.cs +++ b/tvos/UICatalog/UICatalog/DataItems/DataItem.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Foundation; @@ -6,12 +6,12 @@ namespace UICatalog { public class DataItem { - static DataItem[] sampleItems; - public static DataItem[] SampleItems { + static DataItem [] sampleItems; + public static DataItem [] SampleItems { get { if (sampleItems == null) { var items = new List<DataItem> (); - foreach (Group groupType in Enum.GetValues (typeof(Group))) { + foreach (Group groupType in Enum.GetValues (typeof (Group))) { int itemCount = 0; switch (groupType) { @@ -101,19 +101,19 @@ public DataItem (Group group, int number) public override bool Equals (object obj) { - if (obj == null || GetType () != obj.GetType()) + if (obj == null || GetType () != obj.GetType ()) return false; - var dataItem = (DataItem)obj; + var dataItem = (DataItem) obj; return Identifier == dataItem.Identifier; } - public override int GetHashCode () + public override int GetHashCode () { int hash = 17; - hash = hash * 23 + Title.GetHashCode(); - hash = hash * 23 + Identifier.GetHashCode(); - hash = hash * 23 + DisplayURL.GetHashCode(); + hash = hash * 23 + Title.GetHashCode (); + hash = hash * 23 + Identifier.GetHashCode (); + hash = hash * 23 + DisplayURL.GetHashCode (); return hash; } } diff --git a/tvos/UICatalog/UICatalog/DataItems/Group.cs b/tvos/UICatalog/UICatalog/DataItems/Group.cs index b1c097660..1d4917440 100644 --- a/tvos/UICatalog/UICatalog/DataItems/Group.cs +++ b/tvos/UICatalog/UICatalog/DataItems/Group.cs @@ -1,4 +1,4 @@ -namespace UICatalog { +namespace UICatalog { public enum Group { Scenery, diff --git a/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerCell.cs b/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerCell.cs index 03a1a137d..afcba6ea2 100644 --- a/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerCell.cs +++ b/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerCell.cs @@ -6,7 +6,7 @@ namespace UICatalog { public partial class CollectionViewContainerCell : UICollectionViewCell, IUICollectionViewDataSource, IUICollectionViewDelegate { - DataItem[] dataItems; + DataItem [] dataItems; DataItemCellComposer cellComposer = new DataItemCellComposer (); [Export ("reuseIdentifier")] @@ -18,14 +18,14 @@ public override UIView PreferredFocusedView { } } - public void ConfigureWithDataItems (DataItem[] dataItems) + public void ConfigureWithDataItems (DataItem [] dataItems) { this.dataItems = dataItems; CollectionView.ReloadData (); } [Export ("initWithCoder:")] - public CollectionViewContainerCell (NSCoder coder): base (coder) + public CollectionViewContainerCell (NSCoder coder) : base (coder) { } @@ -42,7 +42,7 @@ public nint NumberOfSections (UICollectionView collectionView) public UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - return (UICollectionViewCell)CollectionView.DequeueReusableCell (DataItemCollectionViewCell.ReuseIdentifier, indexPath); + return (UICollectionViewCell) CollectionView.DequeueReusableCell (DataItemCollectionViewCell.ReuseIdentifier, indexPath); } [Export ("collectionView:willDisplayCell:forItemAtIndexPath:")] diff --git a/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerViewController.cs b/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerViewController.cs index 2dd922d3c..2781c2d93 100644 --- a/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerViewController.cs +++ b/tvos/UICatalog/UICatalog/FocusSamples/CollectionViewContainerViewController.cs @@ -10,13 +10,13 @@ public partial class CollectionViewContainerViewController : UICollectionViewCon readonly nfloat MinimumEdgePadding = 90f; - List<DataItem[]> dataItemsByGroup; - public List<DataItem[]> DataItemsByGroup { + List<DataItem []> dataItemsByGroup; + public List<DataItem []> DataItemsByGroup { get { if (dataItemsByGroup == null) { - dataItemsByGroup = new List<DataItem[]> (); + dataItemsByGroup = new List<DataItem []> (); - foreach (Group groupType in Enum.GetValues (typeof(Group))) + foreach (Group groupType in Enum.GetValues (typeof (Group))) dataItemsByGroup.Add (DataItem.SampleItems.Where (c => c.Group == groupType).ToArray ()); } @@ -25,7 +25,7 @@ public List<DataItem[]> DataItemsByGroup { } [Export ("initWithCoder:")] - public CollectionViewContainerViewController (NSCoder coder): base (coder) + public CollectionViewContainerViewController (NSCoder coder) : base (coder) { } @@ -38,7 +38,7 @@ public override void ViewDidLoad () if (collectionView == null || layout == null) return; - + CollectionView.ContentInset = new UIEdgeInsets ( MinimumEdgePadding - layout.SectionInset.Top, CollectionView.ContentInset.Left, @@ -59,7 +59,7 @@ public override nint NumberOfSections (UICollectionView collectionView) public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - return (UICollectionViewCell)CollectionView.DequeueReusableCell (CollectionViewContainerCell.ReuseIdentifier, indexPath); + return (UICollectionViewCell) CollectionView.DequeueReusableCell (CollectionViewContainerCell.ReuseIdentifier, indexPath); } public override void WillDisplayCell (UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath) diff --git a/tvos/UICatalog/UICatalog/FocusSamples/FocusGuidesViewController.cs b/tvos/UICatalog/UICatalog/FocusSamples/FocusGuidesViewController.cs index b50fd5d86..760596760 100644 --- a/tvos/UICatalog/UICatalog/FocusSamples/FocusGuidesViewController.cs +++ b/tvos/UICatalog/UICatalog/FocusSamples/FocusGuidesViewController.cs @@ -7,7 +7,7 @@ public partial class FocusGuidesViewController : UIViewController { UIFocusGuide focusGuide; [Export ("initWithCoder:")] - public FocusGuidesViewController (NSCoder coder): base (coder) + public FocusGuidesViewController (NSCoder coder) : base (coder) { } diff --git a/tvos/UICatalog/UICatalog/Main.cs b/tvos/UICatalog/UICatalog/Main.cs index 15031e9b5..7c271bc8f 100644 --- a/tvos/UICatalog/UICatalog/Main.cs +++ b/tvos/UICatalog/UICatalog/Main.cs @@ -1,9 +1,9 @@ -using UIKit; +using UIKit; namespace UICatalog { public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/UICatalog/UICatalog/MenuSplitViewController.cs b/tvos/UICatalog/UICatalog/MenuSplitViewController.cs index 929e06e8c..d1f476edc 100644 --- a/tvos/UICatalog/UICatalog/MenuSplitViewController.cs +++ b/tvos/UICatalog/UICatalog/MenuSplitViewController.cs @@ -6,7 +6,7 @@ namespace UICatalog { public partial class MenuSplitViewController : UISplitViewController { bool preferDetailViewControllerOnNextFocusUpdate; - + public override UIView PreferredFocusedView { get { UIView preferredFocusedView; diff --git a/tvos/UICatalog/UICatalog/MenuTableViewController.cs b/tvos/UICatalog/UICatalog/MenuTableViewController.cs index 9b44fd48a..86292b3a0 100644 --- a/tvos/UICatalog/UICatalog/MenuTableViewController.cs +++ b/tvos/UICatalog/UICatalog/MenuTableViewController.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Foundation; @@ -32,7 +32,7 @@ public override void RowSelected (UITableView tableView, NSIndexPath indexPath) var menuSplitViewController = SplitViewController as MenuSplitViewController; if (menuSplitViewController == null) return; - + menuSplitViewController.UpdateFocusToDetailViewController (); } @@ -43,7 +43,7 @@ public override void DidUpdateFocus (UIFocusUpdateContext context, UIFocusAnimat if (!nextFocusedView.IsDescendantOfView (TableView)) return; - NSIndexPath indexPath = ((UITableViewFocusUpdateContext)context).NextFocusedIndexPath; + NSIndexPath indexPath = ((UITableViewFocusUpdateContext) context).NextFocusedIndexPath; if (indexPath == null) return; @@ -52,7 +52,7 @@ public override void DidUpdateFocus (UIFocusUpdateContext context, UIFocusAnimat // Create an `NSBlockOperation` to perform the detail segue after a delay. var performSegueOperation = new NSBlockOperation (); - var segueIdentifier = SegueIdentifierMap[indexPath.Section][indexPath.Row]; + var segueIdentifier = SegueIdentifierMap [indexPath.Section] [indexPath.Row]; performSegueOperation.AddExecutionBlock (() => { NSThread.SleepFor (performSegueDelay); diff --git a/tvos/UICatalog/UICatalog/TextEntry/AlertFormViewController.cs b/tvos/UICatalog/UICatalog/TextEntry/AlertFormViewController.cs index 0cc2d996e..0d5a3fe7f 100644 --- a/tvos/UICatalog/UICatalog/TextEntry/AlertFormViewController.cs +++ b/tvos/UICatalog/UICatalog/TextEntry/AlertFormViewController.cs @@ -15,7 +15,7 @@ public partial class AlertFormViewController : UIViewController { UIAlertAction secureTextAlertAction; [Export ("initWithCoder:")] - public AlertFormViewController (NSCoder coder): base (coder) + public AlertFormViewController (NSCoder coder) : base (coder) { } @@ -55,7 +55,7 @@ partial void ShowSimpleForm (NSObject sender) textField.Placeholder = "Name"; textField.InputAccessoryView = new CustomInputAccessoryView ("Enter your name"); }); - + alertController.AddTextField (textField => { textField.KeyboardType = UIKeyboardType.EmailAddress; textField.Placeholder = "example@example.com"; @@ -85,7 +85,7 @@ void HandleTextFieldTextDidChangeNotification (object sender, EventArgs e) { if (secureTextAlertAction == null) throw new Exception ("secureTextAlertAction has not been set"); - var textField = (UITextField)sender; + var textField = (UITextField) sender; var text = textField.Text ?? string.Empty; secureTextAlertAction.Enabled = text.Length >= 5; diff --git a/tvos/UICatalog/UICatalog/TextEntry/CustomInputAccessoryView.cs b/tvos/UICatalog/UICatalog/TextEntry/CustomInputAccessoryView.cs index 4d9dd81ce..105c17d75 100644 --- a/tvos/UICatalog/UICatalog/TextEntry/CustomInputAccessoryView.cs +++ b/tvos/UICatalog/UICatalog/TextEntry/CustomInputAccessoryView.cs @@ -1,10 +1,10 @@ -using CoreGraphics; +using CoreGraphics; using Foundation; using UIKit; namespace UICatalog { public class CustomInputAccessoryView : UIView { - + UILabel titleLabel; [Export ("initWithFrame:")] @@ -29,7 +29,7 @@ void Initialize (string title) AddSubview (titleLabel); TranslatesAutoresizingMaskIntoConstraints = false; - var viewsDictionary = NSMutableDictionary.FromObjectAndKey (titleLabel, (NSString)"titleLabel"); + var viewsDictionary = NSMutableDictionary.FromObjectAndKey (titleLabel, (NSString) "titleLabel"); AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-[titleLabel]-|", 0, null, viewsDictionary)); AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-[titleLabel]-60-|", 0, null, viewsDictionary)); } diff --git a/tvos/UICatalog/UICatalog/TextEntry/TextEntryMenuViewController.cs b/tvos/UICatalog/UICatalog/TextEntry/TextEntryMenuViewController.cs index a6c0295ae..64c4f81ae 100644 --- a/tvos/UICatalog/UICatalog/TextEntry/TextEntryMenuViewController.cs +++ b/tvos/UICatalog/UICatalog/TextEntry/TextEntryMenuViewController.cs @@ -3,9 +3,9 @@ namespace UICatalog { public partial class TextEntryMenuViewController : MenuTableViewController { - public override List<string[]> SegueIdentifierMap { + public override List<string []> SegueIdentifierMap { get { - return new List<string[]> { + return new List<string []> { new [] { "ShowSimpleForm", "ShowAlertForm" diff --git a/tvos/UICatalog/UICatalog/TextEntry/TextFieldsViewController.cs b/tvos/UICatalog/UICatalog/TextEntry/TextFieldsViewController.cs index 84c25b48e..44dcc13a7 100644 --- a/tvos/UICatalog/UICatalog/TextEntry/TextFieldsViewController.cs +++ b/tvos/UICatalog/UICatalog/TextEntry/TextFieldsViewController.cs @@ -5,7 +5,7 @@ namespace UICatalog { public partial class TextFieldsViewController : UIViewController { [Export ("initWithCoder:")] - public TextFieldsViewController (NSCoder coder): base (coder) + public TextFieldsViewController (NSCoder coder) : base (coder) { } diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/AlertsViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/AlertsViewController.cs index d6b89dc65..fe2b3fc6b 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/AlertsViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/AlertsViewController.cs @@ -13,7 +13,7 @@ public partial class AlertsViewController : UIViewController { const string deleteButtonTitle = "Delete"; [Export ("initWithCoder:")] - public AlertsViewController (NSCoder coder): base (coder) + public AlertsViewController (NSCoder coder) : base (coder) { } @@ -22,7 +22,7 @@ partial void ShowSimpleAlert (NSObject sender) var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); // Create the action. - var acceptAction = UIAlertAction.Create (acceptButtonTitle, UIAlertActionStyle.Default, _ => + var acceptAction = UIAlertAction.Create (acceptButtonTitle, UIAlertActionStyle.Default, _ => Console.WriteLine ("The simple alert's accept action occurred.") ); @@ -36,11 +36,11 @@ partial void ShowOkCancelAlert (NSObject sender) var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); // Create the action. - var acceptAction = UIAlertAction.Create (acceptButtonTitle, UIAlertActionStyle.Default, _ => + var acceptAction = UIAlertAction.Create (acceptButtonTitle, UIAlertActionStyle.Default, _ => Console.WriteLine ("The \"OK/Cancel\" alert's other action occurred.") ); - var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, _ => + var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, _ => Console.WriteLine ("The \"OK/Cancel\" alert's other action occurred.") ); @@ -54,11 +54,11 @@ partial void ShowDestructiveAlert (NSObject sender) { var alertController = UIAlertController.Create (title, message, UIAlertControllerStyle.Alert); - var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, _ => + var cancelAction = UIAlertAction.Create (cancelButtonTitle, UIAlertActionStyle.Cancel, _ => Console.WriteLine ("The \"Other\" alert's other action occurred.") ); - var deleteAction = UIAlertAction.Create (deleteButtonTitle, UIAlertActionStyle.Destructive, _ => + var deleteAction = UIAlertAction.Create (deleteButtonTitle, UIAlertActionStyle.Destructive, _ => Console.WriteLine ("The \"Other\" alert's other action occurred.") ); diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/CollectionViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/CollectionViewController.cs index 18c9c4df0..a3ce7df64 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/CollectionViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/CollectionViewController.cs @@ -7,11 +7,11 @@ namespace UICatalog { public partial class CollectionViewController : UICollectionViewController { - readonly DataItem[] items = DataItem.SampleItems; + readonly DataItem [] items = DataItem.SampleItems; readonly DataItemCellComposer cellComposer = new DataItemCellComposer (); [Export ("initWithCoder:")] - public CollectionViewController (NSCoder coder): base (coder) + public CollectionViewController (NSCoder coder) : base (coder) { } @@ -19,7 +19,7 @@ public override void ViewDidLoad () { if (CollectionView == null) return; - + CollectionView.MaskView = new GradientMaskView (new CGRect (CGPoint.Empty, CollectionView.Bounds.Size)); } @@ -54,7 +54,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - return (UICollectionViewCell)CollectionView.DequeueReusableCell (DataItemCollectionViewCell.ReuseIdentifier, indexPath); + return (UICollectionViewCell) CollectionView.DequeueReusableCell (DataItemCollectionViewCell.ReuseIdentifier, indexPath); } public override void WillDisplayCell (UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath) diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/DataItemViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/DataItemViewController.cs index 2d75f6e4d..bdfc57b6a 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/DataItemViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/DataItemViewController.cs @@ -9,7 +9,7 @@ public partial class DataItemViewController : UIViewController { public DataItem DataItem { get; private set; } [Export ("initWithCoder:")] - public DataItemViewController (NSCoder coder): base (coder) + public DataItemViewController (NSCoder coder) : base (coder) { } @@ -18,7 +18,7 @@ public override void ViewDidLoad () ImageView.Image = UIImage.FromBundle (DataItem.LargeImageName); } - public void ConfigureWithDataItem (DataItem dataItem) + public void ConfigureWithDataItem (DataItem dataItem) { DataItem = dataItem; } diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/GradientMaskView.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/GradientMaskView.cs index 281085b6c..76c405fdd 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/GradientMaskView.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/GradientMaskView.cs @@ -1,4 +1,4 @@ -using CoreAnimation; +using CoreAnimation; using CoreGraphics; using Foundation; using UIKit; diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/PageViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/PageViewController.cs index f2f06f977..5e9f45efa 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/PageViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/PageViewController.cs @@ -6,11 +6,11 @@ namespace UICatalog { public partial class PageViewController : UIPageViewController, IUIPageViewControllerDataSource { - readonly DataItem[] dataItems = DataItem.SampleItems.Where (c => c.Group == Group.Lola).ToArray (); + readonly DataItem [] dataItems = DataItem.SampleItems.Where (c => c.Group == Group.Lola).ToArray (); readonly NSCache dataItemViewControllerCache = new NSCache (); [Export ("initWithCoder:")] - public PageViewController (NSCoder coder): base (coder) + public PageViewController (NSCoder coder) : base (coder) { } @@ -29,7 +29,7 @@ public override void ViewDidLoad () [Export ("presentationCountForPageViewController:")] public new nint GetPresentationCount (UIPageViewController pageViewController) { - return (nint)dataItems.Length; + return (nint) dataItems.Length; } [Export ("presentationIndexForPageViewController:")] @@ -41,7 +41,7 @@ public override void ViewDidLoad () throw new Exception ("Unexpected view controller type in page view controller."); for (int i = 0; i < dataItems.Length; i++) { - if (firstViewController.DataItem == dataItems[i]) + if (firstViewController.DataItem == dataItems [i]) return i; } @@ -67,7 +67,7 @@ int IndexOfDataItemForViewController (UIViewController viewController) throw new Exception ("Unexpected view controller type in page view controller"); for (int i = 0; i < dataItems.Length; i++) { - if (dataItemViewController.DataItem == dataItems[i]) + if (dataItemViewController.DataItem == dataItems [i]) return i; } @@ -77,15 +77,15 @@ int IndexOfDataItemForViewController (UIViewController viewController) DataItemViewController DataItemViewControllerForPage (int index) { var dataItem = dataItems [index]; - var cachedController = dataItemViewControllerCache.ObjectForKey ((NSString)dataItem.Identifier) as DataItemViewController; + var cachedController = dataItemViewControllerCache.ObjectForKey ((NSString) dataItem.Identifier) as DataItemViewController; if (cachedController == null) { - var viewController = (DataItemViewController)Storyboard.InstantiateViewController (DataItemViewController.StoryboardIdentifier); + var viewController = (DataItemViewController) Storyboard.InstantiateViewController (DataItemViewController.StoryboardIdentifier); if (viewController == null) throw new Exception ("Unable to instantiate a DataItemViewController."); viewController.ConfigureWithDataItem (dataItem); - dataItemViewControllerCache.SetObjectforKey (viewController, (NSString)dataItem.Identifier); + dataItemViewControllerCache.SetObjectforKey (viewController, (NSString) dataItem.Identifier); return viewController; } else { return cachedController; diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchResultsViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchResultsViewController.cs index bf0cd34a4..9e5633a87 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchResultsViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchResultsViewController.cs @@ -10,8 +10,8 @@ public partial class SearchResultsViewController : UICollectionViewController, I public static readonly string StoryboardIdentifier = "SearchResultsViewController"; DataItemCellComposer cellComposer = new DataItemCellComposer (); - DataItem[] allDataItems = DataItem.SampleItems; - DataItem[] filteredDataItems = DataItem.SampleItems; + DataItem [] allDataItems = DataItem.SampleItems; + DataItem [] filteredDataItems = DataItem.SampleItems; string filterString; string FilterString { @@ -21,7 +21,7 @@ string FilterString { set { if (filterString == value) return; - + filterString = value; filteredDataItems = string.IsNullOrEmpty (filterString) ? allDataItems : allDataItems.Where (c => c.Title.Contains (filterString)).ToArray (); @@ -31,7 +31,7 @@ string FilterString { } [Export ("initWithCoder:")] - public SearchResultsViewController (NSCoder coder): base (coder) + public SearchResultsViewController (NSCoder coder) : base (coder) { } @@ -48,7 +48,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { var cell = collectionView.DequeueReusableCell (DataItemCollectionViewCell.ReuseIdentifier, indexPath); - return (UICollectionViewCell)cell; + return (UICollectionViewCell) cell; } public override void WillDisplayCell (UICollectionView collectionView, UICollectionViewCell cell, NSIndexPath indexPath) @@ -57,7 +57,7 @@ public override void WillDisplayCell (UICollectionView collectionView, UICollect if (currentCell == null) throw new Exception ("Expected to display a `DataItemCollectionViewCell`."); - var item = filteredDataItems[indexPath.Row]; + var item = filteredDataItems [indexPath.Row]; cellComposer.ComposeCell (currentCell, item); } diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchViewController.cs index 3f71f9b0e..a717b2dc2 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/SearchViewController.cs @@ -7,7 +7,7 @@ namespace UICatalog { public partial class SearchViewController : UIViewController { [Export ("initWithCoder:")] - public SearchViewController (NSCoder coder): base (coder) + public SearchViewController (NSCoder coder) : base (coder) { } diff --git a/tvos/UICatalog/UICatalog/ViewControllerSamples/ViewControllersMenuViewController.cs b/tvos/UICatalog/UICatalog/ViewControllerSamples/ViewControllersMenuViewController.cs index c4639720a..9773e8af6 100644 --- a/tvos/UICatalog/UICatalog/ViewControllerSamples/ViewControllersMenuViewController.cs +++ b/tvos/UICatalog/UICatalog/ViewControllerSamples/ViewControllersMenuViewController.cs @@ -3,9 +3,9 @@ namespace UICatalog { public partial class ViewControllersMenuViewController : MenuTableViewController { - public override List<string[]> SegueIdentifierMap { + public override List<string []> SegueIdentifierMap { get { - return new List<string[]> { + return new List<string []> { new [] { "ShowAlertControllers", "ShowCollectionViewController", diff --git a/tvos/tvAlerts/tvAlerts/AppDelegate.cs b/tvos/tvAlerts/tvAlerts/AppDelegate.cs index 8384ec85c..b479df906 100644 --- a/tvos/tvAlerts/tvAlerts/AppDelegate.cs +++ b/tvos/tvAlerts/tvAlerts/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvAlerts -{ +namespace tvAlerts { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvAlerts/tvAlerts/Classes/AlertViewController.cs b/tvos/tvAlerts/tvAlerts/Classes/AlertViewController.cs index 3333eb171..ce44ef71a 100644 --- a/tvos/tvAlerts/tvAlerts/Classes/AlertViewController.cs +++ b/tvos/tvAlerts/tvAlerts/Classes/AlertViewController.cs @@ -1,88 +1,90 @@ -using System; +using System; using Foundation; using UIKit; using System.CodeDom.Compiler; -namespace UIKit -{ +namespace UIKit { /// <summary> /// Alert view controller is a reusable helper class that makes working with <c>UIAlertViewController</c> alerts /// easier in a tvOS app. /// </summary> - public class AlertViewController - { + public class AlertViewController { #region Static Methods - public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) { + public static UIAlertController PresentOKAlert (string title, string description, UIViewController controller) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Configure the alert - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {})); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (action) => { })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentOKCancelAlert(string title, string description, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentOKCancelAlert (string title, string description, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentDestructiveAlert(string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentDestructiveAlert (string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create(destructiveAction,UIAlertActionStyle.Destructive,(actionOK) => { + alert.AddAction (UIAlertAction.Create (destructiveAction, UIAlertActionStyle.Destructive, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; } - public static UIAlertController PresentTextInputAlert(string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) { + public static UIAlertController PresentTextInputAlert (string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); UITextField field = null; // Add and configure text field @@ -101,23 +103,23 @@ public static UIAlertController PresentTextInputAlert(string title, string descr }); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false,""); + if (action != null) { + action (false, ""); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null && field !=null) { - action(true, field.Text); + if (action != null && field != null) { + action (true, field.Text); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -125,8 +127,8 @@ public static UIAlertController PresentTextInputAlert(string title, string descr #endregion #region Delegates - public delegate void AlertOKCancelDelegate(bool OK); - public delegate void AlertTextInputDelegate(bool OK, string text); + public delegate void AlertOKCancelDelegate (bool OK); + public delegate void AlertTextInputDelegate (bool OK, string text); #endregion } } diff --git a/tvos/tvAlerts/tvAlerts/Main.cs b/tvos/tvAlerts/tvAlerts/Main.cs index 36f6b2615..2c8f74bfa 100644 --- a/tvos/tvAlerts/tvAlerts/Main.cs +++ b/tvos/tvAlerts/tvAlerts/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvAlerts -{ - public class Application - { +namespace tvAlerts { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvAlerts/tvAlerts/ViewController.cs b/tvos/tvAlerts/tvAlerts/ViewController.cs index 50ff3a092..cecd9fb80 100644 --- a/tvos/tvAlerts/tvAlerts/ViewController.cs +++ b/tvos/tvAlerts/tvAlerts/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Constructors public ViewController (IntPtr handle) : base (handle) { @@ -27,29 +25,33 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void DisplayDestructiveAlert (Foundation.NSObject sender) { + partial void DisplayDestructiveAlert (Foundation.NSObject sender) + { // User helper class to present alert - AlertViewController.PresentDestructiveAlert("A Short Title is Best","The message should be a short, complete sentence.","Delete",this, (ok) => { - Console.WriteLine("Destructive Alert: The user selected {0}",ok); + AlertViewController.PresentDestructiveAlert ("A Short Title is Best", "The message should be a short, complete sentence.", "Delete", this, (ok) => { + Console.WriteLine ("Destructive Alert: The user selected {0}", ok); }); } - partial void DisplayOkCancelAlert (Foundation.NSObject sender) { + partial void DisplayOkCancelAlert (Foundation.NSObject sender) + { // User helper class to present alert - AlertViewController.PresentOKCancelAlert("A Short Title is Best","The message should be a short, complete sentence.",this, (ok) => { - Console.WriteLine("OK/Cancel Alert: The user selected {0}",ok); + AlertViewController.PresentOKCancelAlert ("A Short Title is Best", "The message should be a short, complete sentence.", this, (ok) => { + Console.WriteLine ("OK/Cancel Alert: The user selected {0}", ok); }); } - partial void DisplaySimpleAlert (Foundation.NSObject sender) { + partial void DisplaySimpleAlert (Foundation.NSObject sender) + { // User helper class to present alert - AlertViewController.PresentOKAlert("A Short Title is Best","The message should be a short, complete sentence.",this); + AlertViewController.PresentOKAlert ("A Short Title is Best", "The message should be a short, complete sentence.", this); } - partial void DisplayTextInputAlert (Foundation.NSObject sender) { + partial void DisplayTextInputAlert (Foundation.NSObject sender) + { // User helper class to present alert - AlertViewController.PresentTextInputAlert("A Short Title is Best","The message should be a short, complete sentence.","placeholder", "", this, (ok, text) => { - Console.WriteLine("Text Input Alert: The user selected {0} and entered `{1}`",ok,text); + AlertViewController.PresentTextInputAlert ("A Short Title is Best", "The message should be a short, complete sentence.", "placeholder", "", this, (ok, text) => { + Console.WriteLine ("Text Input Alert: The user selected {0} and entered `{1}`", ok, text); }); } #endregion diff --git a/tvos/tvButtons/tvButtons/AppDelegate.cs b/tvos/tvButtons/tvButtons/AppDelegate.cs index b74e3d2ae..2889fb935 100644 --- a/tvos/tvButtons/tvButtons/AppDelegate.cs +++ b/tvos/tvButtons/tvButtons/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvButtons -{ +namespace tvButtons { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvButtons/tvButtons/Main.cs b/tvos/tvButtons/tvButtons/Main.cs index 489f94f40..f46f082bf 100644 --- a/tvos/tvButtons/tvButtons/Main.cs +++ b/tvos/tvButtons/tvButtons/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvButtons -{ - public class Application - { +namespace tvButtons { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvButtons/tvButtons/ViewController.cs b/tvos/tvButtons/tvButtons/ViewController.cs index 4884b9b1d..de1c6686c 100644 --- a/tvos/tvButtons/tvButtons/ViewController.cs +++ b/tvos/tvButtons/tvButtons/ViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using UIKit; using CoreGraphics; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Constructors public ViewController (IntPtr handle) : base (handle) { @@ -20,14 +18,14 @@ public override void ViewDidLoad () // Add a button via code - var button = new UIButton(UIButtonType.System); - button.Frame = new CGRect (ClickMeButton.Frame.Left, ClickMeButton.Frame.Top+ClickMeButton.Frame.Height+25, ClickMeButton.Frame.Width, ClickMeButton.Frame.Height); + var button = new UIButton (UIButtonType.System); + button.Frame = new CGRect (ClickMeButton.Frame.Left, ClickMeButton.Frame.Top + ClickMeButton.Frame.Height + 25, ClickMeButton.Frame.Width, ClickMeButton.Frame.Height); button.SetTitle ("Hello", UIControlState.Normal); button.AllEvents += (sender, e) => { - Console.WriteLine("Hello button clicked!"); + Console.WriteLine ("Hello button clicked!"); }; button.SetTitleColor (UIColor.Red, UIControlState.Normal); - button.SetTitleShadowColor(UIColor.Black, UIControlState.Normal); + button.SetTitleShadowColor (UIColor.Black, UIControlState.Normal); button.ReverseTitleShadowWhenHighlighted = true; View.AddSubview (button); } @@ -40,8 +38,9 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void ButtonPressed (Foundation.NSObject sender) { - Console.WriteLine("The button was clicked."); + partial void ButtonPressed (Foundation.NSObject sender) + { + Console.WriteLine ("The button was clicked."); } #endregion } diff --git a/tvos/tvCollection/tvCollection/AppDelegate.cs b/tvos/tvCollection/tvCollection/AppDelegate.cs index abf3d1cdf..c0df3e9b7 100644 --- a/tvos/tvCollection/tvCollection/AppDelegate.cs +++ b/tvos/tvCollection/tvCollection/AppDelegate.cs @@ -1,16 +1,14 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvCollection -{ +namespace tvCollection { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { #region Computed Properties - public override UIWindow Window { get; set;} - public CityInfo SelectedCity { get; set;} = new CityInfo("City02.jpg", "Turning Circle", true); + public override UIWindow Window { get; set; } + public CityInfo SelectedCity { get; set; } = new CityInfo ("City02.jpg", "Turning Circle", true); #endregion #region Override Methods diff --git a/tvos/tvCollection/tvCollection/CityCollectionView.cs b/tvos/tvCollection/tvCollection/CityCollectionView.cs index 1f3f7dbff..766fa96b4 100644 --- a/tvos/tvCollection/tvCollection/CityCollectionView.cs +++ b/tvos/tvCollection/tvCollection/CityCollectionView.cs @@ -2,29 +2,27 @@ using Foundation; using UIKit; -namespace tvCollection -{ - public partial class CityCollectionView : UICollectionView - { +namespace tvCollection { + public partial class CityCollectionView : UICollectionView { #region Application Access public static AppDelegate App { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion #region Computed Properties public CityViewDatasource Source { - get { return DataSource as CityViewDatasource;} + get { return DataSource as CityViewDatasource; } } - public CityCollectionViewController ParentController { get; set;} + public CityCollectionViewController ParentController { get; set; } #endregion #region Constructors public CityCollectionView (IntPtr handle) : base (handle) { // Initialize - RegisterClassForCell (typeof(CityCollectionViewCell), CityViewDatasource.CardCellId); + RegisterClassForCell (typeof (CityCollectionViewCell), CityViewDatasource.CardCellId); DataSource = new CityViewDatasource (this); Delegate = new CityViewDelegate (); } diff --git a/tvos/tvCollection/tvCollection/CityCollectionViewCell.cs b/tvos/tvCollection/tvCollection/CityCollectionViewCell.cs index aa12c4020..9630e0cc2 100644 --- a/tvos/tvCollection/tvCollection/CityCollectionViewCell.cs +++ b/tvos/tvCollection/tvCollection/CityCollectionViewCell.cs @@ -3,16 +3,14 @@ using UIKit; using CoreGraphics; -namespace tvCollection -{ - public partial class CityCollectionViewCell : UICollectionViewCell - { +namespace tvCollection { + public partial class CityCollectionViewCell : UICollectionViewCell { #region Private Variables private CityInfo _city; #endregion #region Computed Properties - public UIImageView CityView { get ; set; } + public UIImageView CityView { get; set; } public UILabel CityTitle { get; set; } public CityInfo City { @@ -30,7 +28,7 @@ public CityInfo City { public CityCollectionViewCell (IntPtr handle) : base (handle) { // Initialize - CityView = new UIImageView(new CGRect(22, 19, 320, 171)); + CityView = new UIImageView (new CGRect (22, 19, 320, 171)); CityView.AdjustsImageWhenAncestorFocused = true; AddSubview (CityView); @@ -42,7 +40,7 @@ public CityCollectionViewCell (IntPtr handle) : base (handle) AddSubview (CityTitle); } #endregion - + } } diff --git a/tvos/tvCollection/tvCollection/CityCollectionViewController.cs b/tvos/tvCollection/tvCollection/CityCollectionViewController.cs index 5aa422045..7dfd8f246 100644 --- a/tvos/tvCollection/tvCollection/CityCollectionViewController.cs +++ b/tvos/tvCollection/tvCollection/CityCollectionViewController.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace tvCollection -{ - public partial class CityCollectionViewController : UICollectionViewController - { +namespace tvCollection { + public partial class CityCollectionViewController : UICollectionViewController { #region Computed Properties public CityCollectionView Collection { get { return CollectionView as CityCollectionView; } diff --git a/tvos/tvCollection/tvCollection/Classes/CityInfo.cs b/tvos/tvCollection/tvCollection/Classes/CityInfo.cs index d5a125251..aa25d90de 100644 --- a/tvos/tvCollection/tvCollection/Classes/CityInfo.cs +++ b/tvos/tvCollection/tvCollection/Classes/CityInfo.cs @@ -1,13 +1,11 @@ -using System; +using System; -namespace tvCollection -{ - public class CityInfo - { +namespace tvCollection { + public class CityInfo { #region Computed Properties public string ImageFilename { get; set; } public string Title { get; set; } - public bool CanSelect{ get; set; } + public bool CanSelect { get; set; } #endregion #region Constructors diff --git a/tvos/tvCollection/tvCollection/Classes/CityViewDatasource.cs b/tvos/tvCollection/tvCollection/Classes/CityViewDatasource.cs index 26b58785a..2f6294a4a 100644 --- a/tvos/tvCollection/tvCollection/Classes/CityViewDatasource.cs +++ b/tvos/tvCollection/tvCollection/Classes/CityViewDatasource.cs @@ -1,17 +1,15 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using Foundation; using CoreGraphics; using ObjCRuntime; -namespace tvCollection -{ - public class CityViewDatasource : UICollectionViewDataSource - { +namespace tvCollection { + public class CityViewDatasource : UICollectionViewDataSource { #region Application Access public static AppDelegate App { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -20,7 +18,7 @@ public static AppDelegate App { #endregion #region Computed Properties - public List<CityInfo> Cities { get; set; } = new List<CityInfo>(); + public List<CityInfo> Cities { get; set; } = new List<CityInfo> (); public CityCollectionView ViewController { get; set; } #endregion @@ -34,31 +32,32 @@ public CityViewDatasource (CityCollectionView controller) #endregion #region Public Methods - public void PopulateCities() { + public void PopulateCities () + { // Clear existing cities - Cities.Clear(); + Cities.Clear (); // Add new cities - Cities.Add(new CityInfo("City01.jpg", "Houses by Water", false)); - Cities.Add(new CityInfo("City02.jpg", "Turning Circle", true)); - Cities.Add(new CityInfo("City03.jpg", "Skyline at Night", true)); - Cities.Add(new CityInfo("City04.jpg", "Golden Gate Bridge", true)); - Cities.Add(new CityInfo("City05.jpg", "Roads by Night", true)); - Cities.Add(new CityInfo("City06.jpg", "Church Domes", true)); - Cities.Add(new CityInfo("City07.jpg", "Mountain Lights", true)); - Cities.Add(new CityInfo("City08.jpg", "City Scene", false)); - Cities.Add(new CityInfo("City09.jpg", "House in Winter", true)); - Cities.Add(new CityInfo("City10.jpg", "By the Lake", true)); - Cities.Add(new CityInfo("City11.jpg", "At the Dome", true)); - Cities.Add(new CityInfo("City12.jpg", "Cityscape", true)); - Cities.Add(new CityInfo("City13.jpg", "Model City", true)); - Cities.Add(new CityInfo("City14.jpg", "Taxi, Taxi!", true)); - Cities.Add(new CityInfo("City15.jpg", "On the Sidewalk", true)); - Cities.Add(new CityInfo("City16.jpg", "Midnight Walk", true)); - Cities.Add(new CityInfo("City17.jpg", "Lunchtime Cafe", true)); - Cities.Add(new CityInfo("City18.jpg", "Coffee Shop", true)); - Cities.Add(new CityInfo("City19.jpg", "Rustic Tavern", true)); + Cities.Add (new CityInfo ("City01.jpg", "Houses by Water", false)); + Cities.Add (new CityInfo ("City02.jpg", "Turning Circle", true)); + Cities.Add (new CityInfo ("City03.jpg", "Skyline at Night", true)); + Cities.Add (new CityInfo ("City04.jpg", "Golden Gate Bridge", true)); + Cities.Add (new CityInfo ("City05.jpg", "Roads by Night", true)); + Cities.Add (new CityInfo ("City06.jpg", "Church Domes", true)); + Cities.Add (new CityInfo ("City07.jpg", "Mountain Lights", true)); + Cities.Add (new CityInfo ("City08.jpg", "City Scene", false)); + Cities.Add (new CityInfo ("City09.jpg", "House in Winter", true)); + Cities.Add (new CityInfo ("City10.jpg", "By the Lake", true)); + Cities.Add (new CityInfo ("City11.jpg", "At the Dome", true)); + Cities.Add (new CityInfo ("City12.jpg", "Cityscape", true)); + Cities.Add (new CityInfo ("City13.jpg", "Model City", true)); + Cities.Add (new CityInfo ("City14.jpg", "Taxi, Taxi!", true)); + Cities.Add (new CityInfo ("City15.jpg", "On the Sidewalk", true)); + Cities.Add (new CityInfo ("City16.jpg", "Midnight Walk", true)); + Cities.Add (new CityInfo ("City17.jpg", "Lunchtime Cafe", true)); + Cities.Add (new CityInfo ("City18.jpg", "Coffee Shop", true)); + Cities.Add (new CityInfo ("City19.jpg", "Rustic Tavern", true)); } #endregion @@ -75,7 +74,7 @@ public override nint GetItemsCount (UICollectionView collectionView, nint sectio public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath) { - var cityCell = (CityCollectionViewCell)collectionView.DequeueReusableCell (CardCellId, indexPath); + var cityCell = (CityCollectionViewCell) collectionView.DequeueReusableCell (CardCellId, indexPath); var city = Cities [indexPath.Row]; // Initialize city diff --git a/tvos/tvCollection/tvCollection/Classes/CityViewDelegate.cs b/tvos/tvCollection/tvCollection/Classes/CityViewDelegate.cs index fa4c67ae5..feba2389c 100644 --- a/tvos/tvCollection/tvCollection/Classes/CityViewDelegate.cs +++ b/tvos/tvCollection/tvCollection/Classes/CityViewDelegate.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using UIKit; using Foundation; using CoreGraphics; -namespace tvCollection -{ - public class CityViewDelegate : UICollectionViewDelegateFlowLayout - { +namespace tvCollection { + public class CityViewDelegate : UICollectionViewDelegateFlowLayout { #region Application Access public static AppDelegate App { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -32,7 +30,7 @@ public override bool CanFocusItem (UICollectionView collectionView, NSIndexPath return false; } else { var controller = collectionView as CityCollectionView; - return controller.Source.Cities[indexPath.Row].CanSelect; + return controller.Source.Cities [indexPath.Row].CanSelect; } } @@ -42,7 +40,7 @@ public override void ItemSelected (UICollectionView collectionView, NSIndexPath App.SelectedCity = controller.Source.Cities [indexPath.Row]; // Close Collection - controller.ParentController.DismissViewController(true,null); + controller.ParentController.DismissViewController (true, null); } #endregion } diff --git a/tvos/tvCollection/tvCollection/Main.cs b/tvos/tvCollection/tvCollection/Main.cs index e7f74ec57..1f9232b76 100644 --- a/tvos/tvCollection/tvCollection/Main.cs +++ b/tvos/tvCollection/tvCollection/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvCollection -{ - public class Application - { +namespace tvCollection { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvCollection/tvCollection/ViewController.cs b/tvos/tvCollection/tvCollection/ViewController.cs index 94965e1a0..df03448ef 100644 --- a/tvos/tvCollection/tvCollection/ViewController.cs +++ b/tvos/tvCollection/tvCollection/ViewController.cs @@ -1,15 +1,13 @@ -using System; +using System; using Foundation; using UIKit; using tvCollection; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Application Access public static AppDelegate App { - get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } + get { return (AppDelegate) UIApplication.SharedApplication.Delegate; } } #endregion @@ -31,7 +29,7 @@ public override void ViewWillAppear (bool animated) base.ViewWillAppear (animated); // Update image with the currently selected one - CityView.Image = UIImage.FromFile(App.SelectedCity.ImageFilename); + CityView.Image = UIImage.FromFile (App.SelectedCity.ImageFilename); BackgroundView.Image = CityView.Image; CityTitle.Text = App.SelectedCity.Title; } diff --git a/tvos/tvFocus/tvFocus/AppDelegate.cs b/tvos/tvFocus/tvFocus/AppDelegate.cs index f1d6e888d..b5865be6b 100644 --- a/tvos/tvFocus/tvFocus/AppDelegate.cs +++ b/tvos/tvFocus/tvFocus/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvFocus -{ +namespace tvFocus { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { #region Computed Properties public override UIWindow Window { get; diff --git a/tvos/tvFocus/tvFocus/Classes/AlertViewController.cs b/tvos/tvFocus/tvFocus/Classes/AlertViewController.cs index e52ef63d2..e156b889e 100644 --- a/tvos/tvFocus/tvFocus/Classes/AlertViewController.cs +++ b/tvos/tvFocus/tvFocus/Classes/AlertViewController.cs @@ -1,16 +1,14 @@ -using System; +using System; using Foundation; using UIKit; using System.CodeDom.Compiler; -namespace UIKit -{ +namespace UIKit { /// <summary> /// Alert view controller is a reusable helper class that makes working with <c>UIAlertViewController</c> alerts /// easier in a tvOS app. /// </summary> - public class AlertViewController - { + public class AlertViewController { #region Static Methods /// <summary> /// Presents an alert containing only the OK button. @@ -19,15 +17,16 @@ public class AlertViewController /// <param name="title">The alert's title.</param> /// <param name="description">The alert's description.</param> /// <param name="controller">The View Controller that will present the alert.</param> - public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) { + public static UIAlertController PresentOKAlert (string title, string description, UIViewController controller) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Configure the alert - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {})); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (action) => { })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -41,28 +40,29 @@ public static UIAlertController PresentOKAlert(string title, string description, /// <param name="description">The alert's Description.</param> /// <param name="controller">The Vinew Controller that will present the alert.</param> /// <param name="action">The <c>AlertOKCancelDelegate</c> use to respond to the user's action.</param> - public static UIAlertController PresentOKCancelAlert(string title, string description, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentOKCancelAlert (string title, string description, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -77,28 +77,29 @@ public static UIAlertController PresentOKCancelAlert(string title, string descri /// <param name="destructiveAction">The title for the destructive action's button (such as delete).</param> /// <param name="controller">The View Controller that will present the alert.</param> /// <param name="action">The <c>AlertOKCancelDelegate</c> use to respond to the user's action.</param> - public static UIAlertController PresentDestructiveAlert(string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentDestructiveAlert (string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create(destructiveAction,UIAlertActionStyle.Destructive,(actionOK) => { + alert.AddAction (UIAlertAction.Create (destructiveAction, UIAlertActionStyle.Destructive, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -114,9 +115,10 @@ public static UIAlertController PresentDestructiveAlert(string title, string des /// <param name="text">The initial value for the text field.</param> /// <param name="controller">The View Controller that will present the alert.</param> /// <param name="action">The <c>AlertTextInputDelegate</c> that will respond to the user's action.</param> - public static UIAlertController PresentTextInputAlert(string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) { + public static UIAlertController PresentTextInputAlert (string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); UITextField field = null; // Add and configure text field @@ -135,23 +137,23 @@ public static UIAlertController PresentTextInputAlert(string title, string descr }); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false,""); + if (action != null) { + action (false, ""); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null && field !=null) { - action(true, field.Text); + if (action != null && field != null) { + action (true, field.Text); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -162,12 +164,12 @@ public static UIAlertController PresentTextInputAlert(string title, string descr /// <summary> /// Delegate to handle the user's selection on an OK/Cancel alert. /// </summary> - public delegate void AlertOKCancelDelegate(bool OK); + public delegate void AlertOKCancelDelegate (bool OK); /// <summary> /// Delegate to handle the user's selection on an single line text entry alert. /// </summary> - public delegate void AlertTextInputDelegate(bool OK, string text); + public delegate void AlertTextInputDelegate (bool OK, string text); #endregion } -} \ No newline at end of file +} diff --git a/tvos/tvFocus/tvFocus/Main.cs b/tvos/tvFocus/tvFocus/Main.cs index 32543082a..e8d788b20 100644 --- a/tvos/tvFocus/tvFocus/Main.cs +++ b/tvos/tvFocus/tvFocus/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace tvFocus -{ - public class Application - { +namespace tvFocus { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/tvos/tvFocus/tvFocus/ViewController.cs b/tvos/tvFocus/tvFocus/ViewController.cs index f1306caf8..56fa59a6b 100644 --- a/tvos/tvFocus/tvFocus/ViewController.cs +++ b/tvos/tvFocus/tvFocus/ViewController.cs @@ -1,16 +1,14 @@ -using System; +using System; using Foundation; using UIKit; -namespace tvFocus -{ +namespace tvFocus { /// <summary> /// Controls the main View for the app and is responsible for setting up a Foucs Guide /// <c>UIFocusGuide</c> that allows the user to move between the More Info and Buy /// button in the User Interface. /// </summary> - public partial class ViewController : UIViewController - { + public partial class ViewController : UIViewController { #region Private Variables /// <summary> /// Private storage for the Focus Guide that will allow us to @@ -98,12 +96,12 @@ partial void MoreInfoButton_PrimaryActionTriggered (UIButton sender) /// <param name="sender">Sender.</param> partial void BuyButton_PrimaryActionTriggered (UIButton sender) { - AlertViewController.PresentOKCancelAlert( "Add Flower to Shopping Cart", - "Would you like to add the currently selected flower to your shopping cart?", - this, - (ok) => { + AlertViewController.PresentOKCancelAlert ("Add Flower to Shopping Cart", + "Would you like to add the currently selected flower to your shopping cart?", + this, + (ok) => { - }); + }); } #endregion } diff --git a/tvos/tvNavBars/tvNavBars/AppDelegate.cs b/tvos/tvNavBars/tvNavBars/AppDelegate.cs index 8fc7f19dd..9a12ef074 100644 --- a/tvos/tvNavBars/tvNavBars/AppDelegate.cs +++ b/tvos/tvNavBars/tvNavBars/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvNavBars -{ +namespace tvNavBars { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvNavBars/tvNavBars/Main.cs b/tvos/tvNavBars/tvNavBars/Main.cs index 0f2a07e61..9ba6caabc 100644 --- a/tvos/tvNavBars/tvNavBars/Main.cs +++ b/tvos/tvNavBars/tvNavBars/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvNavBars -{ - public class Application - { +namespace tvNavBars { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvNavBars/tvNavBars/ViewController.cs b/tvos/tvNavBars/tvNavBars/ViewController.cs index e26885957..282f651ef 100644 --- a/tvos/tvNavBars/tvNavBars/ViewController.cs +++ b/tvos/tvNavBars/tvNavBars/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Constructors public ViewController (IntPtr handle) : base (handle) { @@ -27,19 +25,22 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void ShowFirstHotel (Foundation.NSObject sender) { + partial void ShowFirstHotel (Foundation.NSObject sender) + { // Change background image - HotelImage.Image = UIImage.FromFile("Motel01.jpg"); + HotelImage.Image = UIImage.FromFile ("Motel01.jpg"); } - partial void ShowSecondHotel (Foundation.NSObject sender) { + partial void ShowSecondHotel (Foundation.NSObject sender) + { // Change background image - HotelImage.Image = UIImage.FromFile("Motel02.jpg"); + HotelImage.Image = UIImage.FromFile ("Motel02.jpg"); } - partial void ShowThirdHotel (Foundation.NSObject sender) { + partial void ShowThirdHotel (Foundation.NSObject sender) + { // Change background image - HotelImage.Image = UIImage.FromFile("Motel03.jpg"); + HotelImage.Image = UIImage.FromFile ("Motel03.jpg"); } #endregion } diff --git a/tvos/tvPages/tvPages/AppDelegate.cs b/tvos/tvPages/tvPages/AppDelegate.cs index 314505a7e..5d39d6b72 100644 --- a/tvos/tvPages/tvPages/AppDelegate.cs +++ b/tvos/tvPages/tvPages/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvPages -{ +namespace tvPages { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvPages/tvPages/Main.cs b/tvos/tvPages/tvPages/Main.cs index 66085e87c..84700ddf9 100644 --- a/tvos/tvPages/tvPages/Main.cs +++ b/tvos/tvPages/tvPages/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvPages -{ - public class Application - { +namespace tvPages { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvPages/tvPages/ViewController.cs b/tvos/tvPages/tvPages/ViewController.cs index 5771af825..751573670 100644 --- a/tvos/tvPages/tvPages/ViewController.cs +++ b/tvos/tvPages/tvPages/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Computed Properties public nint PageNumber { get; set; } = 0; #endregion @@ -34,27 +32,30 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void NextCat (Foundation.NSObject sender) { + partial void NextCat (Foundation.NSObject sender) + { // Display next Cat if (++PageNumber > 5) { PageNumber = 5; } - ShowCat(); + ShowCat (); } - partial void PreviousCat (Foundation.NSObject sender) { + partial void PreviousCat (Foundation.NSObject sender) + { // Display previous cat if (--PageNumber < 0) { PageNumber = 0; } - ShowCat(); + ShowCat (); } #endregion #region Private Methods - private void ShowCat() { + private void ShowCat () + { // Adjust UI PreviousButton.Enabled = (PageNumber > 0); @@ -62,7 +63,7 @@ private void ShowCat() { PageView.CurrentPage = PageNumber; // Display new cat - CatView.Image = UIImage.FromFile(string.Format("Cat{0:00}.jpg",PageNumber+1)); + CatView.Image = UIImage.FromFile (string.Format ("Cat{0:00}.jpg", PageNumber + 1)); } #endregion } diff --git a/tvos/tvProgress/tvProgress/AppDelegate.cs b/tvos/tvProgress/tvProgress/AppDelegate.cs index 7bc0bbf4f..e35152ab6 100644 --- a/tvos/tvProgress/tvProgress/AppDelegate.cs +++ b/tvos/tvProgress/tvProgress/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvProgress -{ +namespace tvProgress { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvProgress/tvProgress/Main.cs b/tvos/tvProgress/tvProgress/Main.cs index b2c52395b..1683e3d91 100644 --- a/tvos/tvProgress/tvProgress/Main.cs +++ b/tvos/tvProgress/tvProgress/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvProgress -{ - public class Application - { +namespace tvProgress { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvProgress/tvProgress/ViewController.cs b/tvos/tvProgress/tvProgress/ViewController.cs index c42935292..733303202 100644 --- a/tvos/tvProgress/tvProgress/ViewController.cs +++ b/tvos/tvProgress/tvProgress/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Constructors public ViewController (IntPtr handle) : base (handle) { @@ -27,27 +25,30 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void StartStopAction (Foundation.NSObject sender) { + partial void StartStopAction (Foundation.NSObject sender) + { // Take action based on the Activity Indicator state if (ActivityIndicator.IsAnimating) { - StartStopButton.SetTitle("Start",UIControlState.Normal); - ActivityIndicator.StopAnimating(); + StartStopButton.SetTitle ("Start", UIControlState.Normal); + ActivityIndicator.StopAnimating (); } else { - StartStopButton.SetTitle("Stop",UIControlState.Normal); - ActivityIndicator.StartAnimating(); + StartStopButton.SetTitle ("Stop", UIControlState.Normal); + ActivityIndicator.StartAnimating (); } } - partial void LessAction (Foundation.NSObject sender) { + partial void LessAction (Foundation.NSObject sender) + { // At minimum? - if (ProgressBar.Progress > 0) ProgressBar.Progress -=0.10f; + if (ProgressBar.Progress > 0) ProgressBar.Progress -= 0.10f; } - partial void MoreAction (Foundation.NSObject sender) { + partial void MoreAction (Foundation.NSObject sender) + { // At maximum? - if (ProgressBar.Progress < 1) ProgressBar.Progress +=0.10f; + if (ProgressBar.Progress < 1) ProgressBar.Progress += 0.10f; } #endregion } diff --git a/tvos/tvRemote/tvRemote/AppDelegate.cs b/tvos/tvRemote/tvRemote/AppDelegate.cs index 4b46d4005..87c1e986e 100644 --- a/tvos/tvRemote/tvRemote/AppDelegate.cs +++ b/tvos/tvRemote/tvRemote/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvRemote -{ +namespace tvRemote { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvRemote/tvRemote/EventView.cs b/tvos/tvRemote/tvRemote/EventView.cs index 0eddf2119..62e889eab 100644 --- a/tvos/tvRemote/tvRemote/EventView.cs +++ b/tvos/tvRemote/tvRemote/EventView.cs @@ -2,10 +2,8 @@ using Foundation; using UIKit; -namespace tvRemote -{ - public partial class EventView : UIView - { +namespace tvRemote { + public partial class EventView : UIView { #region Computed Properties public override bool CanBecomeFocused { get { diff --git a/tvos/tvRemote/tvRemote/FirstViewController.cs b/tvos/tvRemote/tvRemote/FirstViewController.cs index 07ca1c1da..aadec4739 100644 --- a/tvos/tvRemote/tvRemote/FirstViewController.cs +++ b/tvos/tvRemote/tvRemote/FirstViewController.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace tvRemote -{ - public partial class FirstViewController : UIViewController - { +namespace tvRemote { + public partial class FirstViewController : UIViewController { #region Constructors public FirstViewController (IntPtr handle) : base (handle) { @@ -26,43 +24,50 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void TouchSurfaceClicked (Foundation.NSObject sender) { + partial void TouchSurfaceClicked (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ButtonPressed = "Touch"; ButtonLabel.Text = "Touch Surface Clicked"; } - partial void MenuPressed (Foundation.NSObject sender) { + partial void MenuPressed (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ButtonPressed = "Menu"; ButtonLabel.Text = "Menu Button Pressed"; } - partial void PlayPausePressed (Foundation.NSObject sender) { + partial void PlayPausePressed (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ButtonPressed = "PlayPause"; ButtonLabel.Text = "Play/Pause Button Pressed"; } - partial void UpPressed (Foundation.NSObject sender) { + partial void UpPressed (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ArrowPressed = "Up"; ButtonLabel.Text = "D-Pad Up Pressed"; } - partial void DownPressed (Foundation.NSObject sender) { + partial void DownPressed (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ArrowPressed = "Down"; ButtonLabel.Text = "D-Pad Down Pressed"; } - partial void LeftPressed (Foundation.NSObject sender) { + partial void LeftPressed (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ArrowPressed = "Left"; ButtonLabel.Text = "D-Pad Left Pressed"; } - partial void RightPressed (Foundation.NSObject sender) { + partial void RightPressed (Foundation.NSObject sender) + { // Highlight tapped button RemoteView.ArrowPressed = "Right"; ButtonLabel.Text = "D-Pad Right Pressed"; diff --git a/tvos/tvRemote/tvRemote/Graphics/SiriRemote.cs b/tvos/tvRemote/tvRemote/Graphics/SiriRemote.cs index baf2d0612..5d3ae0150 100644 --- a/tvos/tvRemote/tvRemote/Graphics/SiriRemote.cs +++ b/tvos/tvRemote/tvRemote/Graphics/SiriRemote.cs @@ -22,373 +22,367 @@ using UIFont = global::UIKit.TVFont; #endif -namespace tvRemote -{ - [Register ("SiriRemote")] - public class SiriRemote : NSObject - { - - //// Initialization - - static SiriRemote() - { - } - - //// Drawing Methods - - public static void DrawSiriRemote(string pressed, string arrow) - { - //// General Declarations - var colorSpace = CGColorSpace.CreateDeviceRGB(); - var context = UIGraphics.GetCurrentContext(); - - //// Color Declarations - var gradientColor = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); - var gradientColor2 = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 1.000f); - var gradientColor3 = UIColor.FromRGBA(0.368f, 0.368f, 0.368f, 1.000f); - var gradientColor4 = UIColor.FromRGBA(0.147f, 0.147f, 0.147f, 1.000f); - var strokeColor = UIColor.FromRGBA(0.521f, 0.521f, 0.521f, 1.000f); - var strokeColor2 = UIColor.FromRGBA(0.264f, 0.260f, 0.260f, 1.000f); - var fillColor = UIColor.FromRGBA(0.000f, 0.000f, 0.000f, 1.000f); - var textForeground = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); - var strokeColor3 = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); - var fillColor2 = UIColor.FromRGBA(1.000f, 1.000f, 1.000f, 1.000f); - var pressedColor = UIColor.FromRGBA(0.847f, 0.187f, 0.187f, 1.000f); - var gradientColor5 = UIColor.FromRGBA(0.401f, 0.015f, 0.015f, 1.000f); - - //// Gradient Declarations - var radialGradient1Colors = new CGColor [] {gradientColor.CGColor, gradientColor2.CGColor}; - var radialGradient1Locations = new nfloat [] {0.0f, 1.0f}; - var radialGradient1 = new CGGradient(colorSpace, radialGradient1Colors, radialGradient1Locations); - var touchGradientColors = new CGColor [] {gradientColor3.CGColor, gradientColor4.CGColor}; - var touchGradientLocations = new nfloat [] {0.0f, 1.0f}; - var touchGradient = new CGGradient(colorSpace, touchGradientColors, touchGradientLocations); - var pressedGradientColors = new CGColor [] {pressedColor.CGColor, gradientColor5.CGColor}; - var pressedGradientLocations = new nfloat [] {0.0f, 1.0f}; - var pressedGradient = new CGGradient(colorSpace, pressedGradientColors, pressedGradientLocations); - - //// Variable Declarations - var menuPressed = pressed == "Menu" ? pressedColor : fillColor; - var homePressed = pressed == "Home" ? pressedColor : fillColor; - var siriPressed = pressed == "Siri" ? pressedColor : fillColor; - var volumePressed = pressed == "Volume" ? pressedColor : fillColor; - var playPausePressed = pressed == "PlayPause" ? pressedColor : fillColor; - var touchSurfacePressed = pressed == "Touch" ? pressedGradient : touchGradient; - var upArrow = arrow == "Up" ? true : false; - var downArrow = arrow == "Down" ? true : false; - var leftArrow = arrow == "Left" ? true : false; - var rightArrow = arrow == "Right" ? true : false; - - //// Page-1 - { - //// Intro01 - { - //// Siri-Remote-Render - { - //// Rectangle-4 Drawing - var rectangle4Path = UIBezierPath.FromRoundedRect(new CGRect(1.0f, 0.0f, 253.0f, 747.0f), 40.0f); - context.SaveState(); - rectangle4Path.AddClip(); - context.DrawRadialGradient(radialGradient1, - new CGPoint(8.62f, 234.62f), 0.0f, - new CGPoint(8.62f, 234.62f), 567.36f, - CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); - context.RestoreState(); - strokeColor.SetStroke(); - rectangle4Path.LineWidth = 3.0f; - rectangle4Path.Stroke(); - - - //// Rectangle-4-Copy Drawing - UIBezierPath rectangle4CopyPath = new UIBezierPath(); - rectangle4CopyPath.MoveTo(new CGPoint(254.0f, 312.0f)); - rectangle4CopyPath.AddLineTo(new CGPoint(254.0f, 40.0f)); - rectangle4CopyPath.AddCurveToPoint(new CGPoint(214.0f, 0.0f), new CGPoint(254.0f, 17.91f), new CGPoint(236.09f, 0.0f)); - rectangle4CopyPath.AddLineTo(new CGPoint(41.0f, 0.0f)); - rectangle4CopyPath.AddCurveToPoint(new CGPoint(1.0f, 40.0f), new CGPoint(18.92f, 0.0f), new CGPoint(1.0f, 17.91f)); - rectangle4CopyPath.AddLineTo(new CGPoint(1.0f, 312.0f)); - rectangle4CopyPath.AddLineTo(new CGPoint(254.0f, 312.0f)); - rectangle4CopyPath.ClosePath(); - rectangle4CopyPath.MiterLimit = 4.0f; - - rectangle4CopyPath.UsesEvenOddFillRule = true; - - context.SaveState(); - rectangle4CopyPath.AddClip(); - context.DrawLinearGradient(touchSurfacePressed, - new CGPoint(127.5f, 0.0f), - new CGPoint(127.5f, 312.0f), - CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); - context.RestoreState(); - strokeColor2.SetStroke(); - rectangle4CopyPath.LineWidth = 3.0f; - rectangle4CopyPath.Stroke(); - - - //// Menu-Button - { - //// Oval-1 Drawing - var oval1Path = UIBezierPath.FromOval(new CGRect(18.0f, 214.0f, 87.0f, 87.0f)); - menuPressed.SetFill(); - oval1Path.Fill(); - - - //// Label Drawing - CGRect labelRect = new CGRect(31.42f, 243.0f, 71.58f, 30.0f); - textForeground.SetFill(); - new NSString("MENU").DrawString(labelRect, UIFont.BoldSystemFontOfSize(20.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); - - - if (upArrow) - { - //// Bezier Drawing - UIBezierPath bezierPath = new UIBezierPath(); - bezierPath.MoveTo(new CGPoint(105.5f, 74.5f)); - bezierPath.AddLineTo(new CGPoint(149.5f, 74.5f)); - bezierPath.AddLineTo(new CGPoint(127.5f, 44.5f)); - bezierPath.AddLineTo(new CGPoint(105.5f, 74.5f)); - pressedColor.SetFill(); - bezierPath.Fill(); - } - - - if (downArrow) - { - //// Bezier 2 Drawing - UIBezierPath bezier2Path = new UIBezierPath(); - bezier2Path.MoveTo(new CGPoint(106.0f, 180.0f)); - bezier2Path.AddLineTo(new CGPoint(150.0f, 180.0f)); - bezier2Path.AddLineTo(new CGPoint(128.0f, 210.0f)); - bezier2Path.AddLineTo(new CGPoint(106.0f, 180.0f)); - pressedColor.SetFill(); - bezier2Path.Fill(); - } - - - if (rightArrow) - { - //// Bezier 3 Drawing - context.SaveState(); - context.TranslateCTM(212.0f, 129.0f); - context.RotateCTM(90.0f * NMath.PI / 180.0f); - - UIBezierPath bezier3Path = new UIBezierPath(); - bezier3Path.MoveTo(new CGPoint(-22.0f, 15.0f)); - bezier3Path.AddLineTo(new CGPoint(22.0f, 15.0f)); - bezier3Path.AddLineTo(new CGPoint(0.0f, -15.0f)); - bezier3Path.AddLineTo(new CGPoint(-22.0f, 15.0f)); - pressedColor.SetFill(); - bezier3Path.Fill(); - - context.RestoreState(); - } - - - if (leftArrow) - { - //// Bezier 4 Drawing - context.SaveState(); - context.TranslateCTM(38.0f, 129.0f); - context.RotateCTM(-90.0f * NMath.PI / 180.0f); - - UIBezierPath bezier4Path = new UIBezierPath(); - bezier4Path.MoveTo(new CGPoint(-22.0f, 15.0f)); - bezier4Path.AddLineTo(new CGPoint(22.0f, 15.0f)); - bezier4Path.AddLineTo(new CGPoint(0.0f, -15.0f)); - bezier4Path.AddLineTo(new CGPoint(-22.0f, 15.0f)); - pressedColor.SetFill(); - bezier4Path.Fill(); - - context.RestoreState(); - } - } - - - //// Home-Button - { - //// Oval-1-Copy Drawing - var oval1CopyPath = UIBezierPath.FromOval(new CGRect(147.0f, 214.0f, 87.0f, 87.0f)); - homePressed.SetFill(); - oval1CopyPath.Fill(); - - - //// Rectangle-1-+-Line - { - //// Rectangle-1 Drawing - var rectangle1Path = UIBezierPath.FromRect(new CGRect(166.0f, 239.0f, 49.0f, 32.0f)); - strokeColor3.SetStroke(); - rectangle1Path.LineWidth = 2.0f; - rectangle1Path.Stroke(); +namespace tvRemote { + [Register ("SiriRemote")] + public class SiriRemote : NSObject { + + //// Initialization + + static SiriRemote () + { + } + + //// Drawing Methods + + public static void DrawSiriRemote (string pressed, string arrow) + { + //// General Declarations + var colorSpace = CGColorSpace.CreateDeviceRGB (); + var context = UIGraphics.GetCurrentContext (); + + //// Color Declarations + var gradientColor = UIColor.FromRGBA (1.000f, 1.000f, 1.000f, 1.000f); + var gradientColor2 = UIColor.FromRGBA (0.000f, 0.000f, 0.000f, 1.000f); + var gradientColor3 = UIColor.FromRGBA (0.368f, 0.368f, 0.368f, 1.000f); + var gradientColor4 = UIColor.FromRGBA (0.147f, 0.147f, 0.147f, 1.000f); + var strokeColor = UIColor.FromRGBA (0.521f, 0.521f, 0.521f, 1.000f); + var strokeColor2 = UIColor.FromRGBA (0.264f, 0.260f, 0.260f, 1.000f); + var fillColor = UIColor.FromRGBA (0.000f, 0.000f, 0.000f, 1.000f); + var textForeground = UIColor.FromRGBA (1.000f, 1.000f, 1.000f, 1.000f); + var strokeColor3 = UIColor.FromRGBA (1.000f, 1.000f, 1.000f, 1.000f); + var fillColor2 = UIColor.FromRGBA (1.000f, 1.000f, 1.000f, 1.000f); + var pressedColor = UIColor.FromRGBA (0.847f, 0.187f, 0.187f, 1.000f); + var gradientColor5 = UIColor.FromRGBA (0.401f, 0.015f, 0.015f, 1.000f); + + //// Gradient Declarations + var radialGradient1Colors = new CGColor [] { gradientColor.CGColor, gradientColor2.CGColor }; + var radialGradient1Locations = new nfloat [] { 0.0f, 1.0f }; + var radialGradient1 = new CGGradient (colorSpace, radialGradient1Colors, radialGradient1Locations); + var touchGradientColors = new CGColor [] { gradientColor3.CGColor, gradientColor4.CGColor }; + var touchGradientLocations = new nfloat [] { 0.0f, 1.0f }; + var touchGradient = new CGGradient (colorSpace, touchGradientColors, touchGradientLocations); + var pressedGradientColors = new CGColor [] { pressedColor.CGColor, gradientColor5.CGColor }; + var pressedGradientLocations = new nfloat [] { 0.0f, 1.0f }; + var pressedGradient = new CGGradient (colorSpace, pressedGradientColors, pressedGradientLocations); + + //// Variable Declarations + var menuPressed = pressed == "Menu" ? pressedColor : fillColor; + var homePressed = pressed == "Home" ? pressedColor : fillColor; + var siriPressed = pressed == "Siri" ? pressedColor : fillColor; + var volumePressed = pressed == "Volume" ? pressedColor : fillColor; + var playPausePressed = pressed == "PlayPause" ? pressedColor : fillColor; + var touchSurfacePressed = pressed == "Touch" ? pressedGradient : touchGradient; + var upArrow = arrow == "Up" ? true : false; + var downArrow = arrow == "Down" ? true : false; + var leftArrow = arrow == "Left" ? true : false; + var rightArrow = arrow == "Right" ? true : false; + + //// Page-1 + { + //// Intro01 + { + //// Siri-Remote-Render + { + //// Rectangle-4 Drawing + var rectangle4Path = UIBezierPath.FromRoundedRect (new CGRect (1.0f, 0.0f, 253.0f, 747.0f), 40.0f); + context.SaveState (); + rectangle4Path.AddClip (); + context.DrawRadialGradient (radialGradient1, + new CGPoint (8.62f, 234.62f), 0.0f, + new CGPoint (8.62f, 234.62f), 567.36f, + CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); + context.RestoreState (); + strokeColor.SetStroke (); + rectangle4Path.LineWidth = 3.0f; + rectangle4Path.Stroke (); + + + //// Rectangle-4-Copy Drawing + UIBezierPath rectangle4CopyPath = new UIBezierPath (); + rectangle4CopyPath.MoveTo (new CGPoint (254.0f, 312.0f)); + rectangle4CopyPath.AddLineTo (new CGPoint (254.0f, 40.0f)); + rectangle4CopyPath.AddCurveToPoint (new CGPoint (214.0f, 0.0f), new CGPoint (254.0f, 17.91f), new CGPoint (236.09f, 0.0f)); + rectangle4CopyPath.AddLineTo (new CGPoint (41.0f, 0.0f)); + rectangle4CopyPath.AddCurveToPoint (new CGPoint (1.0f, 40.0f), new CGPoint (18.92f, 0.0f), new CGPoint (1.0f, 17.91f)); + rectangle4CopyPath.AddLineTo (new CGPoint (1.0f, 312.0f)); + rectangle4CopyPath.AddLineTo (new CGPoint (254.0f, 312.0f)); + rectangle4CopyPath.ClosePath (); + rectangle4CopyPath.MiterLimit = 4.0f; + + rectangle4CopyPath.UsesEvenOddFillRule = true; + + context.SaveState (); + rectangle4CopyPath.AddClip (); + context.DrawLinearGradient (touchSurfacePressed, + new CGPoint (127.5f, 0.0f), + new CGPoint (127.5f, 312.0f), + CGGradientDrawingOptions.DrawsBeforeStartLocation | CGGradientDrawingOptions.DrawsAfterEndLocation); + context.RestoreState (); + strokeColor2.SetStroke (); + rectangle4CopyPath.LineWidth = 3.0f; + rectangle4CopyPath.Stroke (); + + + //// Menu-Button + { + //// Oval-1 Drawing + var oval1Path = UIBezierPath.FromOval (new CGRect (18.0f, 214.0f, 87.0f, 87.0f)); + menuPressed.SetFill (); + oval1Path.Fill (); + + + //// Label Drawing + CGRect labelRect = new CGRect (31.42f, 243.0f, 71.58f, 30.0f); + textForeground.SetFill (); + new NSString ("MENU").DrawString (labelRect, UIFont.BoldSystemFontOfSize (20.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); + + + if (upArrow) { + //// Bezier Drawing + UIBezierPath bezierPath = new UIBezierPath (); + bezierPath.MoveTo (new CGPoint (105.5f, 74.5f)); + bezierPath.AddLineTo (new CGPoint (149.5f, 74.5f)); + bezierPath.AddLineTo (new CGPoint (127.5f, 44.5f)); + bezierPath.AddLineTo (new CGPoint (105.5f, 74.5f)); + pressedColor.SetFill (); + bezierPath.Fill (); + } + + + if (downArrow) { + //// Bezier 2 Drawing + UIBezierPath bezier2Path = new UIBezierPath (); + bezier2Path.MoveTo (new CGPoint (106.0f, 180.0f)); + bezier2Path.AddLineTo (new CGPoint (150.0f, 180.0f)); + bezier2Path.AddLineTo (new CGPoint (128.0f, 210.0f)); + bezier2Path.AddLineTo (new CGPoint (106.0f, 180.0f)); + pressedColor.SetFill (); + bezier2Path.Fill (); + } + + + if (rightArrow) { + //// Bezier 3 Drawing + context.SaveState (); + context.TranslateCTM (212.0f, 129.0f); + context.RotateCTM (90.0f * NMath.PI / 180.0f); + + UIBezierPath bezier3Path = new UIBezierPath (); + bezier3Path.MoveTo (new CGPoint (-22.0f, 15.0f)); + bezier3Path.AddLineTo (new CGPoint (22.0f, 15.0f)); + bezier3Path.AddLineTo (new CGPoint (0.0f, -15.0f)); + bezier3Path.AddLineTo (new CGPoint (-22.0f, 15.0f)); + pressedColor.SetFill (); + bezier3Path.Fill (); + + context.RestoreState (); + } + + + if (leftArrow) { + //// Bezier 4 Drawing + context.SaveState (); + context.TranslateCTM (38.0f, 129.0f); + context.RotateCTM (-90.0f * NMath.PI / 180.0f); + + UIBezierPath bezier4Path = new UIBezierPath (); + bezier4Path.MoveTo (new CGPoint (-22.0f, 15.0f)); + bezier4Path.AddLineTo (new CGPoint (22.0f, 15.0f)); + bezier4Path.AddLineTo (new CGPoint (0.0f, -15.0f)); + bezier4Path.AddLineTo (new CGPoint (-22.0f, 15.0f)); + pressedColor.SetFill (); + bezier4Path.Fill (); + + context.RestoreState (); + } + } + + + //// Home-Button + { + //// Oval-1-Copy Drawing + var oval1CopyPath = UIBezierPath.FromOval (new CGRect (147.0f, 214.0f, 87.0f, 87.0f)); + homePressed.SetFill (); + oval1CopyPath.Fill (); + + //// Rectangle-1-+-Line + { + //// Rectangle-1 Drawing + var rectangle1Path = UIBezierPath.FromRect (new CGRect (166.0f, 239.0f, 49.0f, 32.0f)); + strokeColor3.SetStroke (); + rectangle1Path.LineWidth = 2.0f; + rectangle1Path.Stroke (); - //// Line Drawing - UIBezierPath linePath = new UIBezierPath(); - linePath.MoveTo(new CGPoint(174.5f, 276.0f)); - linePath.AddLineTo(new CGPoint(205.56f, 276.0f)); - linePath.MiterLimit = 4.0f; - - linePath.LineCapStyle = CGLineCap.Square; - linePath.UsesEvenOddFillRule = true; + //// Line Drawing + UIBezierPath linePath = new UIBezierPath (); + linePath.MoveTo (new CGPoint (174.5f, 276.0f)); + linePath.AddLineTo (new CGPoint (205.56f, 276.0f)); + linePath.MiterLimit = 4.0f; - strokeColor3.SetStroke(); - linePath.LineWidth = 2.0f; - linePath.Stroke(); - } - } - - - //// Volume-Button - { - //// Rectangle- 6 Drawing - var rectangle6Path = UIBezierPath.FromRoundedRect(new CGRect(147.0f, 321.0f, 87.0f, 197.0f), 40.0f); - volumePressed.SetFill(); - rectangle6Path.Fill(); + linePath.LineCapStyle = CGLineCap.Square; + linePath.UsesEvenOddFillRule = true; - //// Label 2 Drawing - CGRect label2Rect = new CGRect(174.96f, 329.0f, 31.08f, 71.0f); - textForeground.SetFill(); - new NSString("+\n").DrawString(label2Rect, UIFont.BoldSystemFontOfSize(48.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); + strokeColor3.SetStroke (); + linePath.LineWidth = 2.0f; + linePath.Stroke (); + } + } - //// Label 3 Drawing - CGRect label3Rect = new CGRect(179.89f, 436.0f, 21.21f, 71.0f); - textForeground.SetFill(); - new NSString("-").DrawString(label3Rect, UIFont.BoldSystemFontOfSize(48.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); - } + //// Volume-Button + { + //// Rectangle- 6 Drawing + var rectangle6Path = UIBezierPath.FromRoundedRect (new CGRect (147.0f, 321.0f, 87.0f, 197.0f), 40.0f); + volumePressed.SetFill (); + rectangle6Path.Fill (); + + //// Label 2 Drawing + CGRect label2Rect = new CGRect (174.96f, 329.0f, 31.08f, 71.0f); + textForeground.SetFill (); + new NSString ("+\n").DrawString (label2Rect, UIFont.BoldSystemFontOfSize (48.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); - //// Siri-Button - { - //// Oval-1-Copy-2 Drawing - var oval1Copy2Path = UIBezierPath.FromOval(new CGRect(18.0f, 321.0f, 87.0f, 87.0f)); - siriPressed.SetFill(); - oval1Copy2Path.Fill(); + //// Label 3 Drawing + CGRect label3Rect = new CGRect (179.89f, 436.0f, 21.21f, 71.0f); + textForeground.SetFill (); + new NSString ("-").DrawString (label3Rect, UIFont.BoldSystemFontOfSize (48.0f), UILineBreakMode.WordWrap, UITextAlignment.Left); + } - //// Group 11 - { - //// Rectangle- 10 Drawing - var rectangle10Path = UIBezierPath.FromRoundedRect(new CGRect(49.52f, 338.0f, 22.55f, 38.57f), 11.27f); - fillColor2.SetFill(); - rectangle10Path.Fill(); + //// Siri-Button + { + //// Oval-1-Copy-2 Drawing + var oval1Copy2Path = UIBezierPath.FromOval (new CGRect (18.0f, 321.0f, 87.0f, 87.0f)); + siriPressed.SetFill (); + oval1Copy2Path.Fill (); - //// Path-2 Drawing - UIBezierPath path2Path = new UIBezierPath(); - path2Path.MoveTo(new CGPoint(46.0f, 363.63f)); - path2Path.AddCurveToPoint(new CGPoint(61.24f, 381.48f), new CGPoint(46.0f, 363.63f), new CGPoint(45.67f, 381.58f)); - path2Path.AddCurveToPoint(new CGPoint(76.81f, 363.25f), new CGPoint(76.81f, 381.38f), new CGPoint(76.81f, 363.25f)); - path2Path.MiterLimit = 4.0f; - path2Path.UsesEvenOddFillRule = true; + //// Group 11 + { + //// Rectangle- 10 Drawing + var rectangle10Path = UIBezierPath.FromRoundedRect (new CGRect (49.52f, 338.0f, 22.55f, 38.57f), 11.27f); + fillColor2.SetFill (); + rectangle10Path.Fill (); - strokeColor3.SetStroke(); - path2Path.LineWidth = 4.0f; - path2Path.Stroke(); + //// Path-2 Drawing + UIBezierPath path2Path = new UIBezierPath (); + path2Path.MoveTo (new CGPoint (46.0f, 363.63f)); + path2Path.AddCurveToPoint (new CGPoint (61.24f, 381.48f), new CGPoint (46.0f, 363.63f), new CGPoint (45.67f, 381.58f)); + path2Path.AddCurveToPoint (new CGPoint (76.81f, 363.25f), new CGPoint (76.81f, 381.38f), new CGPoint (76.81f, 363.25f)); + path2Path.MiterLimit = 4.0f; - //// Line 2 Drawing - UIBezierPath line2Path = new UIBezierPath(); - line2Path.MoveTo(new CGPoint(61.5f, 381.83f)); - line2Path.AddLineTo(new CGPoint(61.5f, 389.55f)); - line2Path.MiterLimit = 4.0f; + path2Path.UsesEvenOddFillRule = true; - line2Path.LineCapStyle = CGLineCap.Square; + strokeColor3.SetStroke (); + path2Path.LineWidth = 4.0f; + path2Path.Stroke (); - line2Path.UsesEvenOddFillRule = true; - strokeColor3.SetStroke(); - line2Path.LineWidth = 4.0f; - line2Path.Stroke(); + //// Line 2 Drawing + UIBezierPath line2Path = new UIBezierPath (); + line2Path.MoveTo (new CGPoint (61.5f, 381.83f)); + line2Path.AddLineTo (new CGPoint (61.5f, 389.55f)); + line2Path.MiterLimit = 4.0f; + line2Path.LineCapStyle = CGLineCap.Square; - //// Line 3 Drawing - UIBezierPath line3Path = new UIBezierPath(); - line3Path.MoveTo(new CGPoint(49.88f, 390.6f)); - line3Path.AddLineTo(new CGPoint(72.46f, 390.6f)); - line3Path.MiterLimit = 4.0f; + line2Path.UsesEvenOddFillRule = true; - line3Path.LineCapStyle = CGLineCap.Square; + strokeColor3.SetStroke (); + line2Path.LineWidth = 4.0f; + line2Path.Stroke (); - line3Path.UsesEvenOddFillRule = true; - strokeColor3.SetStroke(); - line3Path.LineWidth = 4.0f; - line3Path.Stroke(); - } - } + //// Line 3 Drawing + UIBezierPath line3Path = new UIBezierPath (); + line3Path.MoveTo (new CGPoint (49.88f, 390.6f)); + line3Path.AddLineTo (new CGPoint (72.46f, 390.6f)); + line3Path.MiterLimit = 4.0f; + line3Path.LineCapStyle = CGLineCap.Square; - //// Play/Pause-Button - { - //// Oval-1-Copy-3 Drawing - var oval1Copy3Path = UIBezierPath.FromOval(new CGRect(18.0f, 428.0f, 87.0f, 87.0f)); - playPausePressed.SetFill(); - oval1Copy3Path.Fill(); + line3Path.UsesEvenOddFillRule = true; + strokeColor3.SetStroke (); + line3Path.LineWidth = 4.0f; + line3Path.Stroke (); + } + } - //// Path-5-+-Line-+-Line-Copy - { - //// Path-5 Drawing - UIBezierPath path5Path = new UIBezierPath(); - path5Path.MoveTo(new CGPoint(40.98f, 457.24f)); - path5Path.AddLineTo(new CGPoint(40.98f, 485.25f)); - path5Path.AddLineTo(new CGPoint(59.77f, 471.25f)); - path5Path.AddLineTo(new CGPoint(40.98f, 457.24f)); - path5Path.ClosePath(); - path5Path.MiterLimit = 4.0f; - path5Path.UsesEvenOddFillRule = true; + //// Play/Pause-Button + { + //// Oval-1-Copy-3 Drawing + var oval1Copy3Path = UIBezierPath.FromOval (new CGRect (18.0f, 428.0f, 87.0f, 87.0f)); + playPausePressed.SetFill (); + oval1Copy3Path.Fill (); - fillColor2.SetFill(); - path5Path.Fill(); + //// Path-5-+-Line-+-Line-Copy + { + //// Path-5 Drawing + UIBezierPath path5Path = new UIBezierPath (); + path5Path.MoveTo (new CGPoint (40.98f, 457.24f)); + path5Path.AddLineTo (new CGPoint (40.98f, 485.25f)); + path5Path.AddLineTo (new CGPoint (59.77f, 471.25f)); + path5Path.AddLineTo (new CGPoint (40.98f, 457.24f)); + path5Path.ClosePath (); + path5Path.MiterLimit = 4.0f; - //// Line 4 Drawing - UIBezierPath line4Path = new UIBezierPath(); - line4Path.MoveTo(new CGPoint(69.18f, 457.72f)); - line4Path.AddLineTo(new CGPoint(69.18f, 484.8f)); - line4Path.MiterLimit = 4.0f; + path5Path.UsesEvenOddFillRule = true; - line4Path.LineCapStyle = CGLineCap.Square; + fillColor2.SetFill (); + path5Path.Fill (); - line4Path.UsesEvenOddFillRule = true; - strokeColor3.SetStroke(); - line4Path.LineWidth = 4.0f; - line4Path.Stroke(); + //// Line 4 Drawing + UIBezierPath line4Path = new UIBezierPath (); + line4Path.MoveTo (new CGPoint (69.18f, 457.72f)); + line4Path.AddLineTo (new CGPoint (69.18f, 484.8f)); + line4Path.MiterLimit = 4.0f; + line4Path.LineCapStyle = CGLineCap.Square; - //// Line-Copy Drawing - UIBezierPath lineCopyPath = new UIBezierPath(); - lineCopyPath.MoveTo(new CGPoint(79.61f, 457.72f)); - lineCopyPath.AddLineTo(new CGPoint(79.61f, 484.8f)); - lineCopyPath.MiterLimit = 4.0f; + line4Path.UsesEvenOddFillRule = true; - lineCopyPath.LineCapStyle = CGLineCap.Square; + strokeColor3.SetStroke (); + line4Path.LineWidth = 4.0f; + line4Path.Stroke (); - lineCopyPath.UsesEvenOddFillRule = true; - strokeColor3.SetStroke(); - lineCopyPath.LineWidth = 4.0f; - lineCopyPath.Stroke(); - } - } + //// Line-Copy Drawing + UIBezierPath lineCopyPath = new UIBezierPath (); + lineCopyPath.MoveTo (new CGPoint (79.61f, 457.72f)); + lineCopyPath.AddLineTo (new CGPoint (79.61f, 484.8f)); + lineCopyPath.MiterLimit = 4.0f; + lineCopyPath.LineCapStyle = CGLineCap.Square; - //// Rectangle- 12 Drawing - var rectangle12Path = UIBezierPath.FromRoundedRect(new CGRect(110.0f, 13.0f, 34.0f, 13.0f), 6.5f); - fillColor.SetFill(); - rectangle12Path.Fill(); - strokeColor.SetStroke(); - rectangle12Path.LineWidth = 1.0f; - rectangle12Path.Stroke(); - } - } - } - } + lineCopyPath.UsesEvenOddFillRule = true; - } + strokeColor3.SetStroke (); + lineCopyPath.LineWidth = 4.0f; + lineCopyPath.Stroke (); + } + } + + + //// Rectangle- 12 Drawing + var rectangle12Path = UIBezierPath.FromRoundedRect (new CGRect (110.0f, 13.0f, 34.0f, 13.0f), 6.5f); + fillColor.SetFill (); + rectangle12Path.Fill (); + strokeColor.SetStroke (); + rectangle12Path.LineWidth = 1.0f; + rectangle12Path.Stroke (); + } + } + } + } + + } } diff --git a/tvos/tvRemote/tvRemote/Main.cs b/tvos/tvRemote/tvRemote/Main.cs index 28f236ae2..3ae18f90b 100644 --- a/tvos/tvRemote/tvRemote/Main.cs +++ b/tvos/tvRemote/tvRemote/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvRemote -{ - public class Application - { +namespace tvRemote { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvRemote/tvRemote/SecondViewController.cs b/tvos/tvRemote/tvRemote/SecondViewController.cs index 006653886..317351f30 100644 --- a/tvos/tvRemote/tvRemote/SecondViewController.cs +++ b/tvos/tvRemote/tvRemote/SecondViewController.cs @@ -1,10 +1,8 @@ -using System; +using System; using UIKit; -namespace tvRemote -{ - public partial class SecondViewController : UIViewController - { +namespace tvRemote { + public partial class SecondViewController : UIViewController { #region Constructors public SecondViewController (IntPtr handle) : base (handle) { @@ -14,7 +12,7 @@ public SecondViewController (IntPtr handle) : base (handle) #region Override Methods public override void ViewDidLoad () { - base.ViewDidLoad (); + base.ViewDidLoad (); // Wire-up gestures var upGesture = new UISwipeGestureRecognizer (() => { diff --git a/tvos/tvRemote/tvRemote/SiriRemoteView.cs b/tvos/tvRemote/tvRemote/SiriRemoteView.cs index 01b964f36..da8861b50 100644 --- a/tvos/tvRemote/tvRemote/SiriRemoteView.cs +++ b/tvos/tvRemote/tvRemote/SiriRemoteView.cs @@ -3,10 +3,8 @@ using System.CodeDom.Compiler; using UIKit; -namespace tvRemote -{ - public partial class SiriRemoteView : UIView - { +namespace tvRemote { + public partial class SiriRemoteView : UIView { #region Private Variables private string _buttonPressed = ""; private string _arrowPressed = ""; diff --git a/tvos/tvRemote/tvRemote/UIKit/TVColor.cs b/tvos/tvRemote/tvRemote/UIKit/TVColor.cs index ff2047fff..ab0fe3256 100644 --- a/tvos/tvRemote/tvRemote/UIKit/TVColor.cs +++ b/tvos/tvRemote/tvRemote/UIKit/TVColor.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; using CoreGraphics; -namespace UIKit -{ - public class TVColor : NSObject - { +namespace UIKit { + public class TVColor : NSObject { #region Computed Properties public UIColor UIColor { get; set; } @@ -17,67 +15,78 @@ public CGColor CGColor { #endregion #region Type Conversion - public static implicit operator UIColor(TVColor color) { + public static implicit operator UIColor (TVColor color) + { return color.UIColor; } - public static implicit operator TVColor(UIColor color) { - return new TVColor(color); + public static implicit operator TVColor (UIColor color) + { + return new TVColor (color); } #endregion #region Constructors - public TVColor(UIColor color) : base() { + public TVColor (UIColor color) : base () + { // Initialize this.UIColor = color; } - public TVColor(nfloat red, nfloat green, nfloat blue, nfloat alpha) : base() { + public TVColor (nfloat red, nfloat green, nfloat blue, nfloat alpha) : base () + { // Initialize this.UIColor = UIColor.FromRGBA (red, green, blue, alpha); } - public TVColor (NSObjectFlag x) : base(x) { + public TVColor (NSObjectFlag x) : base (x) + { } - public TVColor (IntPtr handle) : base(handle) { + public TVColor (IntPtr handle) : base (handle) + { } #endregion #region Static Methods - public static TVColor FromRGBA(nfloat red, nfloat green, nfloat blue, nfloat alpha) { + public static TVColor FromRGBA (nfloat red, nfloat green, nfloat blue, nfloat alpha) + { return new TVColor (UIColor.FromRGBA (red, green, blue, alpha)); } #endregion #region Public Methods - public void SetStroke() { + public void SetStroke () + { this.UIColor.SetStroke (); } - public void SetFill() { + public void SetFill () + { // Send color change to the String drawing routines UIStringDrawing.FillColor = this.UIColor; this.UIColor.SetFill (); } - public void GetRGBA (out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha){ + public void GetRGBA (out nfloat red, out nfloat green, out nfloat blue, out nfloat alpha) + { this.UIColor.GetRGBA (out red, out green, out blue, out alpha); } - public UIColor ColorWithAlpha(nfloat alpha) { + public UIColor ColorWithAlpha (nfloat alpha) + { return this.UIColor.ColorWithAlpha (alpha); } - public UIColor BlendedColor(nfloat fraction, UIColor color2) + public UIColor BlendedColor (nfloat fraction, UIColor color2) { - var rgba1 = new nfloat[4]; - var rgba2 = new nfloat[4]; + var rgba1 = new nfloat [4]; + var rgba2 = new nfloat [4]; - this.UIColor.GetRGBA(out rgba1 [0], out rgba1 [1], out rgba1 [2], out rgba1 [3]); - color2.GetRGBA(out rgba2 [0], out rgba2 [1], out rgba2 [2], out rgba2 [3]); + this.UIColor.GetRGBA (out rgba1 [0], out rgba1 [1], out rgba1 [2], out rgba1 [3]); + color2.GetRGBA (out rgba2 [0], out rgba2 [1], out rgba2 [2], out rgba2 [3]); return new UIColor ( rgba1 [0] * (1 - fraction) + rgba2 [0] * fraction, diff --git a/tvos/tvRemote/tvRemote/UIKit/TVFont.cs b/tvos/tvRemote/tvRemote/UIKit/TVFont.cs index 3454a9525..46327bd56 100644 --- a/tvos/tvRemote/tvRemote/UIKit/TVFont.cs +++ b/tvos/tvRemote/tvRemote/UIKit/TVFont.cs @@ -1,14 +1,12 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; using CoreGraphics; -namespace UIKit -{ - [Register("TVFont")] - public class TVFont : NSObject - { +namespace UIKit { + [Register ("TVFont")] + public class TVFont : NSObject { #region Static constants public static float LabelFontSize = 16f; #endregion @@ -18,12 +16,14 @@ public class TVFont : NSObject #endregion #region Type Conversion - public static implicit operator UIFont(TVFont font) { + public static implicit operator UIFont (TVFont font) + { return font.UIFont; } - public static implicit operator TVFont(UIFont font) { - return new TVFont(font); + public static implicit operator TVFont (UIFont font) + { + return new TVFont (font); } #endregion @@ -36,16 +36,19 @@ public TVFont (UIFont font) #endregion #region Static Methods - public static UIFont BoldSystemFontOfSize(nfloat size) { + public static UIFont BoldSystemFontOfSize (nfloat size) + { return UIFont.BoldSystemFontOfSize (size); } - public static UIFont SystemFontOfSize(nfloat size) { + public static UIFont SystemFontOfSize (nfloat size) + { return UIFont.SystemFontOfSize (size); } - public static UIFont FromName(string name, nfloat size) { - return UIFont.FromName(name,size); + public static UIFont FromName (string name, nfloat size) + { + return UIFont.FromName (name, size); } #endregion } diff --git a/tvos/tvRemote/tvRemote/UIKit/UIStringDrawing.cs b/tvos/tvRemote/tvRemote/UIKit/UIStringDrawing.cs index 62d495f41..af6bac0c7 100644 --- a/tvos/tvRemote/tvRemote/UIKit/UIStringDrawing.cs +++ b/tvos/tvRemote/tvRemote/UIKit/UIStringDrawing.cs @@ -1,19 +1,18 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; using CoreGraphics; -namespace UIKit -{ - public static class UIStringDrawing - { +namespace UIKit { + public static class UIStringDrawing { public static UIColor FillColor { get; set; } = UIColor.Black; - public static CGSize DrawString (this NSString item, CGRect rect, UIFont font, UILineBreakMode mode, UITextAlignment alignment) { + public static CGSize DrawString (this NSString item, CGRect rect, UIFont font, UILineBreakMode mode, UITextAlignment alignment) + { // Get paragraph style - var labelStyle = NSParagraphStyle.Default.MutableCopy() as UIKit.NSMutableParagraphStyle; + var labelStyle = NSParagraphStyle.Default.MutableCopy () as UIKit.NSMutableParagraphStyle; // Adjust alignment labelStyle.Alignment = alignment; @@ -29,12 +28,12 @@ public static CGSize DrawString (this NSString item, CGRect rect, UIFont font, U }; // Preform drawing - item.DrawString(rect, attributes); + item.DrawString (rect, attributes); // Return new bounding size return new CGSize (rect.Width, rect.Height); } - + } } diff --git a/tvos/tvSplit/tvSplit/AppDelegate.cs b/tvos/tvSplit/tvSplit/AppDelegate.cs index db23ca58c..1e62346b3 100644 --- a/tvos/tvSplit/tvSplit/AppDelegate.cs +++ b/tvos/tvSplit/tvSplit/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvSplit -{ +namespace tvSplit { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvSplit/tvSplit/DetailViewController.cs b/tvos/tvSplit/tvSplit/DetailViewController.cs index b98609813..8052c469f 100644 --- a/tvos/tvSplit/tvSplit/DetailViewController.cs +++ b/tvos/tvSplit/tvSplit/DetailViewController.cs @@ -2,28 +2,26 @@ using Foundation; using UIKit; -namespace tvSplit -{ - public partial class DetailViewController : UIViewController - { +namespace tvSplit { + public partial class DetailViewController : UIViewController { #region Computed Properties - public MainSplitViewController SplitViewController { get; set;} + public MainSplitViewController SplitViewController { get; set; } public string Title { - get {return PageTitle.Text; } + get { return PageTitle.Text; } set { PageTitle.Text = value; } } public string FirstChoice { - get {return ButtonA.Title(UIControlState.Normal); } - set { + get { return ButtonA.Title (UIControlState.Normal); } + set { ButtonA.SetTitle (value, UIControlState.Normal); BackgroundImage.Image = UIImage.FromFile ("default.jpg"); } } public string SecondChoice { - get {return ButtonB.Title(UIControlState.Normal); } + get { return ButtonB.Title (UIControlState.Normal); } set { ButtonB.SetTitle (value, UIControlState.Normal); } } #endregion @@ -35,7 +33,8 @@ public DetailViewController (IntPtr handle) : base (handle) #endregion #region Custom Actions - partial void PlayPausePressed (Foundation.NSObject sender) { + partial void PlayPausePressed (Foundation.NSObject sender) + { // Show hide split view if (SplitViewController.DisplayMode == UISplitViewControllerDisplayMode.PrimaryHidden) { @@ -48,12 +47,12 @@ partial void PlayPausePressed (Foundation.NSObject sender) { partial void ChooseA (NSObject sender) { - BackgroundImage.Image = UIImage.FromFile (string.Format("{0}.jpg",ButtonA.Title(UIControlState.Normal))); + BackgroundImage.Image = UIImage.FromFile (string.Format ("{0}.jpg", ButtonA.Title (UIControlState.Normal))); } partial void ChooseB (NSObject sender) { - BackgroundImage.Image = UIImage.FromFile (string.Format("{0}.jpg",ButtonB.Title(UIControlState.Normal))); + BackgroundImage.Image = UIImage.FromFile (string.Format ("{0}.jpg", ButtonB.Title (UIControlState.Normal))); } #endregion } diff --git a/tvos/tvSplit/tvSplit/Main.cs b/tvos/tvSplit/tvSplit/Main.cs index be8b83f66..a91690d07 100644 --- a/tvos/tvSplit/tvSplit/Main.cs +++ b/tvos/tvSplit/tvSplit/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvSplit -{ - public class Application - { +namespace tvSplit { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvSplit/tvSplit/MainSplitViewController.cs b/tvos/tvSplit/tvSplit/MainSplitViewController.cs index 6f11c0a1b..2abe4ee57 100644 --- a/tvos/tvSplit/tvSplit/MainSplitViewController.cs +++ b/tvos/tvSplit/tvSplit/MainSplitViewController.cs @@ -2,10 +2,8 @@ using Foundation; using UIKit; -namespace tvSplit -{ - public partial class MainSplitViewController : UISplitViewController - { +namespace tvSplit { + public partial class MainSplitViewController : UISplitViewController { #region Constructors public MainSplitViewController (IntPtr handle) : base (handle) { diff --git a/tvos/tvSplit/tvSplit/MasterViewController.cs b/tvos/tvSplit/tvSplit/MasterViewController.cs index 6d2546a7f..a7ef935d1 100644 --- a/tvos/tvSplit/tvSplit/MasterViewController.cs +++ b/tvos/tvSplit/tvSplit/MasterViewController.cs @@ -2,13 +2,11 @@ using Foundation; using UIKit; -namespace tvSplit -{ - public partial class MasterViewController : UIViewController - { +namespace tvSplit { + public partial class MasterViewController : UIViewController { #region Computed Properties - public MainSplitViewController SplitViewController { get; set;} - public DetailViewController DetailController { get; set;} + public MainSplitViewController SplitViewController { get; set; } + public DetailViewController DetailController { get; set; } #endregion #region Constructors @@ -18,7 +16,8 @@ public MasterViewController (IntPtr handle) : base (handle) #endregion #region Custom Actions - partial void PlayPausePressed (Foundation.NSObject sender) { + partial void PlayPausePressed (Foundation.NSObject sender) + { // Show hide split view if (SplitViewController.DisplayMode == UISplitViewControllerDisplayMode.PrimaryHidden) { @@ -29,7 +28,8 @@ partial void PlayPausePressed (Foundation.NSObject sender) { } - partial void Page1Pressed (Foundation.NSObject sender) { + partial void Page1Pressed (Foundation.NSObject sender) + { // Update GUI DetailController.Title = "Hot or Cold?"; @@ -38,7 +38,8 @@ partial void Page1Pressed (Foundation.NSObject sender) { } - partial void Page2Pressed (Foundation.NSObject sender) { + partial void Page2Pressed (Foundation.NSObject sender) + { // Update GUI DetailController.Title = "Wet or Dry?"; @@ -46,7 +47,8 @@ partial void Page2Pressed (Foundation.NSObject sender) { DetailController.SecondChoice = "Ocean"; } - partial void Page3Pressed (Foundation.NSObject sender) { + partial void Page3Pressed (Foundation.NSObject sender) + { // Update GUI DetailController.Title = "Sweet or Sour?"; diff --git a/tvos/tvStackView/tvStackView/AppDelegate.cs b/tvos/tvStackView/tvStackView/AppDelegate.cs index bea83912f..f562016d3 100644 --- a/tvos/tvStackView/tvStackView/AppDelegate.cs +++ b/tvos/tvStackView/tvStackView/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvStackView -{ +namespace tvStackView { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/tvos/tvStackView/tvStackView/Main.cs b/tvos/tvStackView/tvStackView/Main.cs index f94a3b846..29a71bb98 100644 --- a/tvos/tvStackView/tvStackView/Main.cs +++ b/tvos/tvStackView/tvStackView/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace tvStackView -{ - public class Application - { +namespace tvStackView { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/tvos/tvStackView/tvStackView/ViewController.cs b/tvos/tvStackView/tvStackView/ViewController.cs index 2479e64aa..dc506e8cd 100644 --- a/tvos/tvStackView/tvStackView/ViewController.cs +++ b/tvos/tvStackView/tvStackView/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using Foundation; using UIKit; -namespace MySingleView -{ - public partial class ViewController : UIViewController - { +namespace MySingleView { + public partial class ViewController : UIViewController { #region Constructors public ViewController (IntPtr handle) : base (handle) { @@ -27,10 +25,11 @@ public override void DidReceiveMemoryWarning () #endregion #region Custom Actions - partial void PlayerCountChanged (Foundation.NSObject sender) { + partial void PlayerCountChanged (Foundation.NSObject sender) + { // Take Action based on the segment - switch(PlayerCount.SelectedSegment) { + switch (PlayerCount.SelectedSegment) { case 0: Player1.Hidden = false; Player2.Hidden = true; diff --git a/tvos/tvTable/tvTable/AppDelegate.cs b/tvos/tvTable/tvTable/AppDelegate.cs index 842153e0d..192a1c040 100644 --- a/tvos/tvTable/tvTable/AppDelegate.cs +++ b/tvos/tvTable/tvTable/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { #region Computed Properties /// <summary> /// Gets or sets main window for the app. diff --git a/tvos/tvTable/tvTable/AttractionTableCell.cs b/tvos/tvTable/tvTable/AttractionTableCell.cs index 87a68b0e9..579b2039a 100644 --- a/tvos/tvTable/tvTable/AttractionTableCell.cs +++ b/tvos/tvTable/tvTable/AttractionTableCell.cs @@ -2,13 +2,11 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// This is the prototype for every Cell (row) that will be added to the <c>AttractionTableView</c>. /// </summary> - public partial class AttractionTableCell : UITableViewCell - { + public partial class AttractionTableCell : UITableViewCell { #region Private Variables /// <summary> /// The backing store for the <c>AttractionInfomarion</c> object being displayed in this cell. diff --git a/tvos/tvTable/tvTable/AttractionTableView.cs b/tvos/tvTable/tvTable/AttractionTableView.cs index 4951f645f..2d30c25bd 100644 --- a/tvos/tvTable/tvTable/AttractionTableView.cs +++ b/tvos/tvTable/tvTable/AttractionTableView.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// The Table View used to display a collection of <c>CityInformation</c> as Sections and /// <c>AttractionInformation</c> objects as the Rows in each section /// </summary> - public partial class AttractionTableView : UITableView - { + public partial class AttractionTableView : UITableView { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:tvTable.AttractionTableView"/> class. diff --git a/tvos/tvTable/tvTable/AttractionTableViewController.cs b/tvos/tvTable/tvTable/AttractionTableViewController.cs index 284fa48ab..0a27f0cea 100644 --- a/tvos/tvTable/tvTable/AttractionTableViewController.cs +++ b/tvos/tvTable/tvTable/AttractionTableViewController.cs @@ -2,14 +2,12 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// Controls the <c>AttractionTableView</c> used to display a collection of <c>CityInformation</c> and /// <c>AttractionInformation</c> objects. /// </summary> - public partial class AttractionTableViewController : UITableViewController - { + public partial class AttractionTableViewController : UITableViewController { #region Computed Properties /// <summary> /// Gets a shortcut to the <c>AttractionTableDatasource</c> that is providing the data for the diff --git a/tvos/tvTable/tvTable/AttractionView.cs b/tvos/tvTable/tvTable/AttractionView.cs index bbf229ec5..a4aaa7c2f 100644 --- a/tvos/tvTable/tvTable/AttractionView.cs +++ b/tvos/tvTable/tvTable/AttractionView.cs @@ -5,14 +5,12 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// The View used as the Details section of the Spilt View to display detailed information /// about the Row highlighted in the Master section. /// </summary> - public partial class AttractionView : UIView - { + public partial class AttractionView : UIView { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:tvTable.AttractionView"/> class. diff --git a/tvos/tvTable/tvTable/AttractionViewController.cs b/tvos/tvTable/tvTable/AttractionViewController.cs index 47170b981..1346894f0 100644 --- a/tvos/tvTable/tvTable/AttractionViewController.cs +++ b/tvos/tvTable/tvTable/AttractionViewController.cs @@ -2,14 +2,12 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// Controls the <c>AttractionView</c> used to present the detailed information about a <c>AttractionInformation</c> /// object attached to the highlighted Row in the <c>AttractionTableView</c>. /// </summary> - public partial class AttractionViewController : UIViewController - { + public partial class AttractionViewController : UIViewController { #region Private Variables /// <summary> /// The backing store for the <c>AttractionInformation</c> object that the details are being displayed for. @@ -34,7 +32,7 @@ public AttractionInformation Attraction { /// Gets or sets the split view that the <c>AttractionView</c> is being displayed in. /// </summary> /// <value>The <c>MasertSplitView</c> object.</value> - public MasterSplitView SplitView { get; set;} + public MasterSplitView SplitView { get; set; } #endregion #region Constructors @@ -94,12 +92,12 @@ partial void BookFlight (NSObject sender) { // Ask user to book flight AlertViewController.PresentOKCancelAlert ("Book Flight", - string.Format ("Would you like to book a flight to {0}?", Attraction.City.Name), - this, - (ok) => { - Attraction.City.FlightBooked = ok; - IsFlighBooked.Hidden = (!Attraction.City.FlightBooked); - }); + string.Format ("Would you like to book a flight to {0}?", Attraction.City.Name), + this, + (ok) => { + Attraction.City.FlightBooked = ok; + IsFlighBooked.Hidden = (!Attraction.City.FlightBooked); + }); } /// <summary> diff --git a/tvos/tvTable/tvTable/Classes/AlertViewController.cs b/tvos/tvTable/tvTable/Classes/AlertViewController.cs index e52ef63d2..e156b889e 100644 --- a/tvos/tvTable/tvTable/Classes/AlertViewController.cs +++ b/tvos/tvTable/tvTable/Classes/AlertViewController.cs @@ -1,16 +1,14 @@ -using System; +using System; using Foundation; using UIKit; using System.CodeDom.Compiler; -namespace UIKit -{ +namespace UIKit { /// <summary> /// Alert view controller is a reusable helper class that makes working with <c>UIAlertViewController</c> alerts /// easier in a tvOS app. /// </summary> - public class AlertViewController - { + public class AlertViewController { #region Static Methods /// <summary> /// Presents an alert containing only the OK button. @@ -19,15 +17,16 @@ public class AlertViewController /// <param name="title">The alert's title.</param> /// <param name="description">The alert's description.</param> /// <param name="controller">The View Controller that will present the alert.</param> - public static UIAlertController PresentOKAlert(string title, string description, UIViewController controller) { + public static UIAlertController PresentOKAlert (string title, string description, UIViewController controller) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Configure the alert - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(action) => {})); + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (action) => { })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -41,28 +40,29 @@ public static UIAlertController PresentOKAlert(string title, string description, /// <param name="description">The alert's Description.</param> /// <param name="controller">The Vinew Controller that will present the alert.</param> /// <param name="action">The <c>AlertOKCancelDelegate</c> use to respond to the user's action.</param> - public static UIAlertController PresentOKCancelAlert(string title, string description, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentOKCancelAlert (string title, string description, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -77,28 +77,29 @@ public static UIAlertController PresentOKCancelAlert(string title, string descri /// <param name="destructiveAction">The title for the destructive action's button (such as delete).</param> /// <param name="controller">The View Controller that will present the alert.</param> /// <param name="action">The <c>AlertOKCancelDelegate</c> use to respond to the user's action.</param> - public static UIAlertController PresentDestructiveAlert(string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) { + public static UIAlertController PresentDestructiveAlert (string title, string description, string destructiveAction, UIViewController controller, AlertOKCancelDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false); + if (action != null) { + action (false); } })); // Add ok button - alert.AddAction(UIAlertAction.Create(destructiveAction,UIAlertActionStyle.Destructive,(actionOK) => { + alert.AddAction (UIAlertAction.Create (destructiveAction, UIAlertActionStyle.Destructive, (actionOK) => { // Any action? - if (action!=null) { - action(true); + if (action != null) { + action (true); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -114,9 +115,10 @@ public static UIAlertController PresentDestructiveAlert(string title, string des /// <param name="text">The initial value for the text field.</param> /// <param name="controller">The View Controller that will present the alert.</param> /// <param name="action">The <c>AlertTextInputDelegate</c> that will respond to the user's action.</param> - public static UIAlertController PresentTextInputAlert(string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) { + public static UIAlertController PresentTextInputAlert (string title, string description, string placeholder, string text, UIViewController controller, AlertTextInputDelegate action) + { // No, inform the user that they must create a home first - UIAlertController alert = UIAlertController.Create(title, description, UIAlertControllerStyle.Alert); + UIAlertController alert = UIAlertController.Create (title, description, UIAlertControllerStyle.Alert); UITextField field = null; // Add and configure text field @@ -135,23 +137,23 @@ public static UIAlertController PresentTextInputAlert(string title, string descr }); // Add cancel button - alert.AddAction(UIAlertAction.Create("Cancel",UIAlertActionStyle.Cancel,(actionCancel) => { + alert.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, (actionCancel) => { // Any action? - if (action!=null) { - action(false,""); + if (action != null) { + action (false, ""); } })); // Add ok button - alert.AddAction(UIAlertAction.Create("OK",UIAlertActionStyle.Default,(actionOK) => { + alert.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, (actionOK) => { // Any action? - if (action!=null && field !=null) { - action(true, field.Text); + if (action != null && field != null) { + action (true, field.Text); } })); // Display the alert - controller.PresentViewController(alert,true,null); + controller.PresentViewController (alert, true, null); // Return created controller return alert; @@ -162,12 +164,12 @@ public static UIAlertController PresentTextInputAlert(string title, string descr /// <summary> /// Delegate to handle the user's selection on an OK/Cancel alert. /// </summary> - public delegate void AlertOKCancelDelegate(bool OK); + public delegate void AlertOKCancelDelegate (bool OK); /// <summary> /// Delegate to handle the user's selection on an single line text entry alert. /// </summary> - public delegate void AlertTextInputDelegate(bool OK, string text); + public delegate void AlertTextInputDelegate (bool OK, string text); #endregion } -} \ No newline at end of file +} diff --git a/tvos/tvTable/tvTable/Classes/AttractionInformation.cs b/tvos/tvTable/tvTable/Classes/AttractionInformation.cs index eace65f95..4ed933f02 100644 --- a/tvos/tvTable/tvTable/Classes/AttractionInformation.cs +++ b/tvos/tvTable/tvTable/Classes/AttractionInformation.cs @@ -1,50 +1,48 @@ -using System; +using System; using Foundation; -namespace tvTable -{ +namespace tvTable { /// <summary> /// This class stores information about a give attraction for a <c>CityInformation</c> /// instance. /// </summary> - public class AttractionInformation : NSObject - { + public class AttractionInformation : NSObject { #region Computed Properties /// <summary> /// Gets or sets the city that this Attraction belongs to. /// </summary> /// <value>The <c>CityInformation</c> object.</value> - public CityInformation City { get; set;} + public CityInformation City { get; set; } /// <summary> /// Gets or sets the name of the Attraction. /// </summary> /// <value>The name.</value> - public string Name { get; set;} + public string Name { get; set; } /// <summary> /// Gets or sets a short description for the Attraction. /// </summary> /// <value>The description.</value> - public string Description { get; set;} + public string Description { get; set; } /// <summary> /// Gets or sets the Image Asset Name of the image that will be displayed for this Attraction. /// </summary> /// <value>The name of the image as stored in the <c>Assets.xcassets</c>.</value> - public string ImageName { get; set;} + public string ImageName { get; set; } /// <summary> /// Gets or sets a flag marking this Attraction as a favorite. /// </summary> /// <value><c>true</c> if the Attraction is a favorite, else <c>false</c>.</value> - public bool IsFavorite { get; set;} + public bool IsFavorite { get; set; } /// <summary> /// Gets or sets a flag denoting if the user wants directions to this Attraction. /// </summary> /// <value>The add directions.</value> - public bool AddDirections { get; set;} + public bool AddDirections { get; set; } #endregion #region Constructors diff --git a/tvos/tvTable/tvTable/Classes/AttractionTableDatasource.cs b/tvos/tvTable/tvTable/Classes/AttractionTableDatasource.cs index 360b991b7..3acbdfce2 100644 --- a/tvos/tvTable/tvTable/Classes/AttractionTableDatasource.cs +++ b/tvos/tvTable/tvTable/Classes/AttractionTableDatasource.cs @@ -1,15 +1,13 @@ -using System; +using System; using System.Collections.Generic; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// Attraction table datasource defines all of the data for the Attraction Table /// and provides the individual cells as asked for by the table. /// </summary> - public class AttractionTableDatasource : UITableViewDataSource - { + public class AttractionTableDatasource : UITableViewDataSource { #region Constants /// <summary> /// The unique ID for the prototype cell as defined in the designer. @@ -22,13 +20,13 @@ public class AttractionTableDatasource : UITableViewDataSource /// Gets or sets the a shortcut to the parent Table View Controller. /// </summary> /// <value>The <c>AttractionTableViewController</c>.</value> - public AttractionTableViewController Controller { get; set;} + public AttractionTableViewController Controller { get; set; } /// <summary> /// Gets or sets the collection of cities. /// </summary> /// <value>A collection of <c>CityInformation</c> objects.</value> - public List<CityInformation> Cities { get; set;} + public List<CityInformation> Cities { get; set; } #endregion #region Constructors @@ -117,7 +115,7 @@ public override nint NumberOfSections (UITableView tableView) public override nint RowsInSection (UITableView tableView, nint section) { // Return the number of attractions in the given city - return Cities [(int)section].Attractions.Count; + return Cities [(int) section].Attractions.Count; } /// <summary> @@ -129,7 +127,7 @@ public override nint RowsInSection (UITableView tableView, nint section) public override string TitleForHeader (UITableView tableView, nint section) { // Get the name of the current city - return Cities [(int)section].Name; + return Cities [(int) section].Name; } #endregion } diff --git a/tvos/tvTable/tvTable/Classes/AttractionTableDelegate.cs b/tvos/tvTable/tvTable/Classes/AttractionTableDelegate.cs index 5236baa5d..55e295ee7 100644 --- a/tvos/tvTable/tvTable/Classes/AttractionTableDelegate.cs +++ b/tvos/tvTable/tvTable/Classes/AttractionTableDelegate.cs @@ -1,21 +1,19 @@ -using System; +using System; using System.Collections.Generic; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// The <c>AttractionTableDelegate</c> handles the user interactions on the <c>AttractionTable</c> such /// as highlighting or selecting a row. /// </summary> - public class AttractionTableDelegate : UITableViewDelegate - { + public class AttractionTableDelegate : UITableViewDelegate { #region Computed Properties /// <summary> /// Gets or sets a shortcut to the Table View Controller. /// </summary> /// <value>The <c>ActionTableViewController</c>.</value> - public AttractionTableViewController Controller { get; set;} + public AttractionTableViewController Controller { get; set; } #endregion #region Constructors diff --git a/tvos/tvTable/tvTable/Classes/CityInformation.cs b/tvos/tvTable/tvTable/Classes/CityInformation.cs index 5cd22fab0..96e93059a 100644 --- a/tvos/tvTable/tvTable/Classes/CityInformation.cs +++ b/tvos/tvTable/tvTable/Classes/CityInformation.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using Foundation; -namespace tvTable -{ +namespace tvTable { /// <summary> /// Holds information about a given city that will be idplayed as the Sections of a Table View. Each City /// also contains a collection of <c>AttractionInformation</c> objects that will be the Rows in each Table /// View section. /// </summary> - public class CityInformation : NSObject - { + public class CityInformation : NSObject { #region Computed Properties /// <summary> /// Gets or sets the name of the city. @@ -22,13 +20,13 @@ public class CityInformation : NSObject /// Gets or sets the list of attractions. /// </summary> /// <value>A collection of <c>AttractionInformation</c> objects.</value> - public List<AttractionInformation> Attractions { get; set;} + public List<AttractionInformation> Attractions { get; set; } /// <summary> /// Gets or sets a flag denoting that the user wants to book a flight to this city. /// </summary> /// <value><c>true</c> is a flight has been booked, else <c>false</c>.</value> - public bool FlightBooked { get; set;} + public bool FlightBooked { get; set; } #endregion #region Constructors diff --git a/tvos/tvTable/tvTable/Main.cs b/tvos/tvTable/tvTable/Main.cs index 9b3c5ea17..55d9a3050 100644 --- a/tvos/tvTable/tvTable/Main.cs +++ b/tvos/tvTable/tvTable/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace tvTable -{ - public class Application - { +namespace tvTable { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/tvos/tvTable/tvTable/MasterNavigationController.cs b/tvos/tvTable/tvTable/MasterNavigationController.cs index 809789efa..37ce5d255 100644 --- a/tvos/tvTable/tvTable/MasterNavigationController.cs +++ b/tvos/tvTable/tvTable/MasterNavigationController.cs @@ -2,20 +2,18 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// Controls the <c>NavigationBar</c> for the Master side of the Split View that houses /// the <c>AttractionTableView</c>. /// </summary> - public partial class MasterNavigationController : UINavigationController - { + public partial class MasterNavigationController : UINavigationController { #region Computed Properties /// <summary> /// Gets or sets the split view that this <c>UINavigationController</c> is hosted in. /// </summary> /// <value>The <c>MasterSplitView</c>.</value> - public MasterSplitView SplitView { get; set;} + public MasterSplitView SplitView { get; set; } /// <summary> /// A shortcut to the <c>AttractionTableViewController</c> that is presenting the Master diff --git a/tvos/tvTable/tvTable/MasterSplitView.cs b/tvos/tvTable/tvTable/MasterSplitView.cs index 9cd62b188..b0adedb6a 100644 --- a/tvos/tvTable/tvTable/MasterSplitView.cs +++ b/tvos/tvTable/tvTable/MasterSplitView.cs @@ -2,16 +2,14 @@ using Foundation; using UIKit; -namespace tvTable -{ +namespace tvTable { /// <summary> /// Controls the Split View that acts as the main interface for the tvOS app. A <c>AttractionTableView</c> is presented /// in the left hand side of the Split View containing a collection of <c>CityInformation</c> and <c>AttractionInformation</c> /// objects. If a Row is highlighted in the <c>AttractionTableView</c>, the details of the <c>AttractionInformation</c> /// for that row will be presented in the <c>AttractionView</c> on the right hand side of the Split View. /// </summary> - public partial class MasterSplitView : UISplitViewController - { + public partial class MasterSplitView : UISplitViewController { #region Computed Properties /// <summary> /// A shortcut to the <c>AttractionViewController</c> used to present the Details of the highlighted diff --git a/tvos/tvText/tvText/AppDelegate.cs b/tvos/tvText/tvText/AppDelegate.cs index 8115be212..0be0ed8eb 100644 --- a/tvos/tvText/tvText/AppDelegate.cs +++ b/tvos/tvText/tvText/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace tvText -{ +namespace tvText { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { #region Computed Properties /// <summary> /// Gets or sets the window. diff --git a/tvos/tvText/tvText/Classes/PictureInformation.cs b/tvos/tvText/tvText/Classes/PictureInformation.cs index 63e1ff086..5bcb50be8 100644 --- a/tvos/tvText/tvText/Classes/PictureInformation.cs +++ b/tvos/tvText/tvText/Classes/PictureInformation.cs @@ -1,33 +1,31 @@ -using System; +using System; using Foundation; -namespace tvText -{ +namespace tvText { /// <summary> /// Holds all information about a picture that will be displayed in the Search /// Results Collection View. /// </summary> - public class PictureInformation : NSObject - { + public class PictureInformation : NSObject { #region Computed Properties /// <summary> /// Gets or sets the title. /// </summary> /// <value>The title.</value> - public string Title { get; set;} + public string Title { get; set; } /// <summary> /// Gets or sets the name of the image. /// </summary> /// <value>The name of the image.</value> /// <remarks>Images are stored in the <c>Assets.xcassets</c> collection.</remarks> - public string ImageName { get; set;} + public string ImageName { get; set; } /// <summary> /// Gets or sets the keywords. /// </summary> /// <value>The keywords.</value> - public string Keywords { get; set;} + public string Keywords { get; set; } #endregion #region Constructors diff --git a/tvos/tvText/tvText/FirstViewController.cs b/tvos/tvText/tvText/FirstViewController.cs index ebc6bef32..ff011cf5c 100644 --- a/tvos/tvText/tvText/FirstViewController.cs +++ b/tvos/tvText/tvText/FirstViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; -namespace tvText -{ +namespace tvText { /// <summary> /// This View Controller controls the Text tab that is used to enter a User ID /// and password. /// </summary> - public partial class FirstViewController : UIViewController - { + public partial class FirstViewController : UIViewController { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:tvText.FirstViewController"/> class. diff --git a/tvos/tvText/tvText/Main.cs b/tvos/tvText/tvText/Main.cs index dab3cd970..96837ba3b 100644 --- a/tvos/tvText/tvText/Main.cs +++ b/tvos/tvText/tvText/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace tvText -{ - public class Application - { +namespace tvText { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/tvos/tvText/tvText/SearchResultViewCell.cs b/tvos/tvText/tvText/SearchResultViewCell.cs index 99d26577c..017f9e621 100644 --- a/tvos/tvText/tvText/SearchResultViewCell.cs +++ b/tvos/tvText/tvText/SearchResultViewCell.cs @@ -2,14 +2,12 @@ using System; using UIKit; -namespace tvText -{ +namespace tvText { /// <summary> /// Contains the information about a <c>PictureInformation</c> object displayed in the /// <c>SearchResultsViewController</c> as a Collection View. /// </summary> - public partial class SearchResultViewCell : UICollectionViewCell - { + public partial class SearchResultViewCell : UICollectionViewCell { #region Private Variables /// <summary> /// The backing store for the displayed picture information. @@ -74,4 +72,4 @@ private void UpdateUI () #endregion } -} \ No newline at end of file +} diff --git a/tvos/tvText/tvText/SearchResultsViewController.cs b/tvos/tvText/tvText/SearchResultsViewController.cs index 99771435d..aa0783111 100644 --- a/tvos/tvText/tvText/SearchResultsViewController.cs +++ b/tvos/tvText/tvText/SearchResultsViewController.cs @@ -3,8 +3,7 @@ using UIKit; using System.Collections.Generic; -namespace tvText -{ +namespace tvText { /// <summary> /// Controlls the Collection View that will be used to display the results of the user's /// search input. This controller both provides the data for the Collection, but responds @@ -14,8 +13,7 @@ namespace tvText /// See our Working with Collection View documentation for more information: /// https://developer.xamarin.com/guides/ios/tvos/user-interface/collection-views/ /// </remarks> - public partial class SearchResultsViewController : UICollectionViewController , IUISearchResultsUpdating - { + public partial class SearchResultsViewController : UICollectionViewController, IUISearchResultsUpdating { #region Constants /// <summary> /// The cell identifier as entered in the Storyboard. @@ -35,7 +33,7 @@ public partial class SearchResultsViewController : UICollectionViewController , /// Gets or sets all pictures that the user can search for. /// </summary> /// <value>A collection of <c>PictureInformation</c> objects.</value> - public List<PictureInformation> AllPictures { get; set;} + public List<PictureInformation> AllPictures { get; set; } /// <summary> /// Gets or sets the pictures that match the user's search term either by @@ -52,7 +50,7 @@ public partial class SearchResultsViewController : UICollectionViewController , public string SearchFilter { get { return _searchFilter; } set { - _searchFilter = value.ToLower(); + _searchFilter = value.ToLower (); FindPictures (); CollectionView?.ReloadData (); } @@ -64,15 +62,15 @@ public string SearchFilter { /// Initializes a new instance of the <see cref="T:tvText.SearchResultsViewController"/> class. /// </summary> /// <param name="handle">Handle.</param> - public SearchResultsViewController (IntPtr handle) : base (handle) - { + public SearchResultsViewController (IntPtr handle) : base (handle) + { // Initialize this.AllPictures = new List<PictureInformation> (); this.FoundPictures = new List<PictureInformation> (); PopulatePictures (); FindPictures (); - } + } #endregion #region Private Methods @@ -85,7 +83,7 @@ private void PopulatePictures () AllPictures.Clear (); // Add images - AllPictures.Add (new PictureInformation ("Antipasta Platter","Antipasta","cheese,grapes,tomato,coffee,meat,plate")); + AllPictures.Add (new PictureInformation ("Antipasta Platter", "Antipasta", "cheese,grapes,tomato,coffee,meat,plate")); AllPictures.Add (new PictureInformation ("Cheese Plate", "CheesePlate", "cheese,plate,bread")); AllPictures.Add (new PictureInformation ("Coffee House", "CoffeeHouse", "coffee,people,menu,restaurant,cafe")); AllPictures.Add (new PictureInformation ("Computer and Expresso", "ComputerExpresso", "computer,coffee,expresso,phone,notebook")); @@ -153,7 +151,7 @@ public override UICollectionViewCell GetCell (UICollectionView collectionView, N { // Get a new cell and return it var cell = collectionView.DequeueReusableCell (CellID, indexPath); - return (UICollectionViewCell)cell; + return (UICollectionViewCell) cell; } /// <summary> @@ -223,5 +221,5 @@ public override void DidUpdateFocus (UIFocusUpdateContext context, UIFocusAnimat } } #endregion - } -} \ No newline at end of file + } +} diff --git a/tvos/tvText/tvText/SecondViewController.cs b/tvos/tvText/tvText/SecondViewController.cs index c8bda581d..f4e67c89b 100644 --- a/tvos/tvText/tvText/SecondViewController.cs +++ b/tvos/tvText/tvText/SecondViewController.cs @@ -1,14 +1,12 @@ -using System; +using System; using UIKit; -namespace tvText -{ +namespace tvText { /// <summary> /// Controls the View for the Search tab. /// </summary> - public partial class SecondViewController : UIViewController - { + public partial class SecondViewController : UIViewController { #region Constants /// <summary> /// The ID of the View Controller used to present search results to the user @@ -22,7 +20,7 @@ public partial class SecondViewController : UIViewController /// Gets or sets the results controller. /// </summary> /// <value>The <c>SearchResultsViewController</c>.</value> - public SearchResultsViewController ResultsController { get; set;} + public SearchResultsViewController ResultsController { get; set; } #endregion #region Constructors diff --git a/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/ExtensionDelegate.cs b/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/ExtensionDelegate.cs index 0c1798b87..4d81add6c 100644 --- a/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/ExtensionDelegate.cs +++ b/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/ExtensionDelegate.cs @@ -1,13 +1,11 @@ -using System; +using System; using Foundation; using WatchKit; -namespace ActivityRings.ActivityRingsWatchAppExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { +namespace ActivityRings.ActivityRingsWatchAppExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { } } diff --git a/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/InterfaceController.cs b/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/InterfaceController.cs index 9ce57bfba..71f514b68 100644 --- a/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/InterfaceController.cs +++ b/watchOS/ActivityRings/ActivityRings.ActivityRingsWatchAppExtension/InterfaceController.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using CoreFoundation; @@ -6,11 +6,9 @@ using HealthKit; using WatchKit; -namespace ActivityRings.ActivityRingsWatchAppExtension -{ - public partial class InterfaceController : WKInterfaceController, IHKWorkoutSessionDelegate - { - public HKHealthStore HealthStore { get; set; } = new HKHealthStore(); +namespace ActivityRings.ActivityRingsWatchAppExtension { + public partial class InterfaceController : WKInterfaceController, IHKWorkoutSessionDelegate { + public HKHealthStore HealthStore { get; set; } = new HKHealthStore (); public HKWorkoutSession CurrentWorkoutSession { get; set; } @@ -18,7 +16,7 @@ public partial class InterfaceController : WKInterfaceController, IHKWorkoutSess public DateTime WorkoutEndDate { get; set; } - public bool IsWorkoutRunning { get; set; } = false; + public bool IsWorkoutRunning { get; set; } = false; public HKQuery CurrentQuery { get; set; } @@ -47,8 +45,8 @@ public override void WillActivate () HealthStore.RequestAuthorizationToShare (typesToShare, typesToRead, (bool success, NSError error) => { if (error != null && !success) Console.WriteLine ("You didn't allow HealthKit to access these read/write data types. " + - "In your app, try to handle this error gracefully when a user decides not to provide access. " + - $"The error was: {error.LocalizedDescription}. If you're using a simulator, try it on a device."); + "In your app, try to handle this error gracefully when a user decides not to provide access. " + + $"The error was: {error.LocalizedDescription}. If you're using a simulator, try it on a device."); }); } @@ -80,7 +78,7 @@ partial void ToggleWorkout () Delegate = this }; - HealthStore.StartWorkoutSession(CurrentWorkoutSession); + HealthStore.StartWorkoutSession (CurrentWorkoutSession); } } @@ -98,30 +96,30 @@ public void SaveWorkout () NSDictionary metadata = null; var workout = HKWorkout.Create (HKWorkoutActivityType.Walking, - (NSDate)beginDate, - (NSDate)endDate, - duration, - CurrentActiveEnergyQuantity, - HKQuantity.FromQuantity (HKUnit.Mile, 0.0), - metadata); + (NSDate) beginDate, + (NSDate) endDate, + duration, + CurrentActiveEnergyQuantity, + HKQuantity.FromQuantity (HKUnit.Mile, 0.0), + metadata); var finalActiveEnergySamples = ActiveEnergySamples; - if (HealthStore.GetAuthorizationStatus(activeEnergyType) != HKAuthorizationStatus.SharingAuthorized || - HealthStore.GetAuthorizationStatus(HKObjectType.GetWorkoutType()) != HKAuthorizationStatus.SharingAuthorized) + if (HealthStore.GetAuthorizationStatus (activeEnergyType) != HKAuthorizationStatus.SharingAuthorized || + HealthStore.GetAuthorizationStatus (HKObjectType.GetWorkoutType ()) != HKAuthorizationStatus.SharingAuthorized) return; - HealthStore.SaveObject(workout, (success, error) => { + HealthStore.SaveObject (workout, (success, error) => { if (!success) { Console.WriteLine ($"An error occured saving the workout. In your app, try to handle this gracefully. The error was: {error}."); return; } - + if (finalActiveEnergySamples.Count > 0) { HealthStore.AddSamples (finalActiveEnergySamples.ToArray (), workout, (addSuccess, addError) => { // Handle any errors if (addError != null) - Console.WriteLine ($"An error occurred adding the samples. In your app, try to handle this gracefully. The error was: {error.ToString()}."); + Console.WriteLine ($"An error occurred adding the samples. In your app, try to handle this gracefully. The error was: {error.ToString ()}."); }); } }); @@ -141,17 +139,18 @@ public void BeginWorkout (DateTime beginDate) workoutButton.SetTitle ("End Workout"); // Set up a predicate to obtain only samples from the local device starting from `beginDate`. - - var datePredicate = HKQuery.GetPredicateForSamples ((NSDate)beginDate, null, HKQueryOptions.None); - var devices = new NSSet<HKDevice> (new HKDevice[] { HKDevice.LocalDevice }); - var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices(devices); - var predicate = NSCompoundPredicate.CreateAndPredicate (new NSPredicate[] { datePredicate, devicePredicate }); + var datePredicate = HKQuery.GetPredicateForSamples ((NSDate) beginDate, null, HKQueryOptions.None); + + var devices = new NSSet<HKDevice> (new HKDevice [] { HKDevice.LocalDevice }); + var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices (devices); + var predicate = NSCompoundPredicate.CreateAndPredicate (new NSPredicate [] { datePredicate, devicePredicate }); //Create a results handler to recreate the samples generated by a query of active energy samples so that they can be associated with this app in the move graph.It should be noted that if your app has different heuristics for active energy burned you can generate your own quantities rather than rely on those from the watch.The sum of your sample's quantity values should equal the energy burned value provided for the workout - Action <List<HKSample>> sampleHandler; + Action<List<HKSample>> sampleHandler; sampleHandler = (List<HKSample> samples) => { - DispatchQueue.MainQueue.DispatchAsync (delegate { + DispatchQueue.MainQueue.DispatchAsync (delegate + { var accumulatedSamples = new List<HKQuantitySample> (); var initialActivityEnergy = CurrentActiveEnergyQuantity.GetDoubleValue (energyUnit); @@ -172,11 +171,11 @@ public void BeginWorkout (DateTime beginDate) }; // Create a query to report new Active Energy Burned samples to our app. - var activeEnergyQuery = new HKAnchoredObjectQuery (activeEnergyType, predicate, null,HKSampleQuery.NoLimit, (query, addedObjects, deletedObjects, newAnchor, error) => { + var activeEnergyQuery = new HKAnchoredObjectQuery (activeEnergyType, predicate, null, HKSampleQuery.NoLimit, (query, addedObjects, deletedObjects, newAnchor, error) => { if (error == null) { // NOTE: `deletedObjects` are not considered in the handler as there is no way to delete samples from the watch during a workout - ActiveEnergySamples = new List<HKSample>(addedObjects); - sampleHandler(ActiveEnergySamples); + ActiveEnergySamples = new List<HKSample> (addedObjects); + sampleHandler (ActiveEnergySamples); } else { Console.WriteLine ($"An error occured executing the query. In your app, try to handle this gracefully. The error was: {error}."); @@ -187,7 +186,7 @@ public void BeginWorkout (DateTime beginDate) activeEnergyQuery.UpdateHandler = (query, addedObjects, deletedObjects, newAnchor, error) => { if (error == null) { ActiveEnergySamples = new List<HKSample> (addedObjects); - sampleHandler(ActiveEnergySamples); + sampleHandler (ActiveEnergySamples); } else { Console.WriteLine ($"An error occured executing the query. In your app, try to handle this gracefully. The error was: {error}."); } @@ -205,7 +204,7 @@ public void EndWorkout (DateTime endDate) activeEnergyBurnedLabel.SetText ("0.0"); if (CurrentQuery != null) { var query = CurrentQuery; - HealthStore.StopQuery(query); + HealthStore.StopQuery (query); } SaveWorkout (); @@ -213,24 +212,25 @@ public void EndWorkout (DateTime endDate) public void DidChangeToState (HKWorkoutSession workoutSession, HKWorkoutSessionState toState, HKWorkoutSessionState fromState, NSDate date) { - DispatchQueue.MainQueue.DispatchAsync (delegate { + DispatchQueue.MainQueue.DispatchAsync (delegate + { // Take action based on the change in state switch (toState) { - case HKWorkoutSessionState.Running: - BeginWorkout ((DateTime)date); - break; - case HKWorkoutSessionState.Ended: - EndWorkout ((DateTime)date); - break; - default: - Console.WriteLine ($"Unexpected workout session: {toState}."); - break; + case HKWorkoutSessionState.Running: + BeginWorkout ((DateTime) date); + break; + case HKWorkoutSessionState.Ended: + EndWorkout ((DateTime) date); + break; + default: + Console.WriteLine ($"Unexpected workout session: {toState}."); + break; } }); } - public void DidFail (HKWorkoutSession workoutSession, NSError error) - { + public void DidFail (HKWorkoutSession workoutSession, NSError error) + { Console.WriteLine ($"An error occured with the workout session. In your app, try to handle this gracefully. The error was: {error}."); } } diff --git a/watchOS/ActivityRings/ActivityRings/AppDelegate.cs b/watchOS/ActivityRings/ActivityRings/AppDelegate.cs index 3c1566da0..95ff4baff 100644 --- a/watchOS/ActivityRings/ActivityRings/AppDelegate.cs +++ b/watchOS/ActivityRings/ActivityRings/AppDelegate.cs @@ -1,26 +1,24 @@ -using System; +using System; using Foundation; using HealthKit; using UIKit; -namespace ActivityRings -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace ActivityRings { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } HKHealthStore healthStore = new HKHealthStore (); - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { return true; } - public override void ShouldRequestHealthAuthorization(UIApplication application) + public override void ShouldRequestHealthAuthorization (UIApplication application) { - healthStore.HandleAuthorizationForExtension( (bool success, NSError error) => { + healthStore.HandleAuthorizationForExtension ((bool success, NSError error) => { if (error != null && !success) Console.WriteLine ($"You didn't allow HealthKit to access these read/write data types. In your app, try to handle this error gracefully when a user decides not to provide access. The error was: {error.LocalizedDescription}. If you're using a simulator, try it on a device."); }); diff --git a/watchOS/ActivityRings/ActivityRings/Main.cs b/watchOS/ActivityRings/ActivityRings/Main.cs index 275e1e199..869d09a6c 100644 --- a/watchOS/ActivityRings/ActivityRings/Main.cs +++ b/watchOS/ActivityRings/ActivityRings/Main.cs @@ -1,10 +1,8 @@ -using UIKit; +using UIKit; -namespace ActivityRings -{ - public class Application - { - static void Main (string[] args) +namespace ActivityRings { + public class Application { + static void Main (string [] args) { UIApplication.Main (args, null, "AppDelegate"); } diff --git a/watchOS/ActivityRings/ActivityRings/ViewController.cs b/watchOS/ActivityRings/ActivityRings/ViewController.cs index 331a669e2..cbbcc25f9 100644 --- a/watchOS/ActivityRings/ActivityRings/ViewController.cs +++ b/watchOS/ActivityRings/ActivityRings/ViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; -namespace ActivityRings -{ - public partial class ViewController : UIViewController - { - protected ViewController (IntPtr handle) : base(handle) +namespace ActivityRings { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/CommandStatus.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/CommandStatus.cs index c3b552cb6..add7434a7 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/CommandStatus.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/CommandStatus.cs @@ -1,107 +1,93 @@ - -namespace SimpleWatchConnectivity -{ - using System; - using Foundation; - using UIKit; - using WatchConnectivity; - /// <summary> - /// Constants to identify the Watch Connectivity methods, also used as user-visible strings in UI. - /// </summary> - public enum Command - { - UpdateAppContext, - SendMessage, - SendMessageData, - TransferFile, - TransferUserInfo, - TransferCurrentComplicationUserInfo - } +namespace SimpleWatchConnectivity { + using System; + using Foundation; + using UIKit; + using WatchConnectivity; - /// <summary> - /// Constants to identify the phrases of a Watch Connectivity communication. - /// </summary> - public enum Phrase - { - Updated, - Sent, - Received, - Replied, - Transferring, - Canceled, - Finished, - Failed, - } + /// <summary> + /// Constants to identify the Watch Connectivity methods, also used as user-visible strings in UI. + /// </summary> + public enum Command { + UpdateAppContext, + SendMessage, + SendMessageData, + TransferFile, + TransferUserInfo, + TransferCurrentComplicationUserInfo + } - /// <summary> - /// Wrap a timed color payload dictionary with a stronger type. - /// </summary> - public class TimedColor - { - public TimedColor(NSDictionary timedColor) - { - if (timedColor.TryGetValue(PayloadKey.TimeStamp, out NSObject timeStamp) && - timedColor.TryGetValue(PayloadKey.ColorData, out NSObject colorData)) - { - this.TimeStamp = (timeStamp as NSString).ToString(); - this.ColorData = colorData as NSData; - } - else - { - throw new Exception("Timed color dictionary doesn't have right keys!"); - } - } + /// <summary> + /// Constants to identify the phrases of a Watch Connectivity communication. + /// </summary> + public enum Phrase { + Updated, + Sent, + Received, + Replied, + Transferring, + Canceled, + Finished, + Failed, + } - public static TimedColor Create(NSData timedColor) - { - var data = NSKeyedUnarchiver.UnarchiveTopLevelObject(timedColor, out NSError error); - if (data is NSDictionary dictionary) - { - return new TimedColor(dictionary); - } - else - { - throw new Exception("Failed to unarchive a timedColor dictionary!"); - } - } + /// <summary> + /// Wrap a timed color payload dictionary with a stronger type. + /// </summary> + public class TimedColor { + public TimedColor (NSDictionary timedColor) + { + if (timedColor.TryGetValue (PayloadKey.TimeStamp, out NSObject timeStamp) && + timedColor.TryGetValue (PayloadKey.ColorData, out NSObject colorData)) { + this.TimeStamp = (timeStamp as NSString).ToString (); + this.ColorData = colorData as NSData; + } else { + throw new Exception ("Timed color dictionary doesn't have right keys!"); + } + } - public string TimeStamp { get; set; } + public static TimedColor Create (NSData timedColor) + { + var data = NSKeyedUnarchiver.UnarchiveTopLevelObject (timedColor, out NSError error); + if (data is NSDictionary dictionary) { + return new TimedColor (dictionary); + } else { + throw new Exception ("Failed to unarchive a timedColor dictionary!"); + } + } - public NSData ColorData { get; set; } + public string TimeStamp { get; set; } - public UIColor Color - { - get - { - var optional = NSKeyedUnarchiver.GetUnarchivedObject(typeof(UIColor), this.ColorData, out NSError error); - if (!(optional is UIColor color)) - { - throw new Exception("Failed to unarchive a UIClor object!"); - } + public NSData ColorData { get; set; } - return color; - } - } - } + public UIColor Color { + get { + var optional = NSKeyedUnarchiver.GetUnarchivedObject (typeof (UIColor), this.ColorData, out NSError error); + if (!(optional is UIColor color)) { + throw new Exception ("Failed to unarchive a UIClor object!"); + } - /// <summary> - /// Wrap the command status to bridge the commands status and UI. - /// </summary> - public class CommandStatus : NSObject - { - public CommandStatus(Command command, Phrase phrase) - { - this.Command = command; - this.Phrase = phrase; - } + return color; + } + } + } - public Command Command { get; set; } - public Phrase Phrase { get; set; } - public TimedColor TimedColor { get; set; } - public WCSessionFileTransfer FileTransfer { get; set; } - public WCSessionFile File { get; set; } - public WCSessionUserInfoTransfer UserInfoTranser { get; set; } - public string ErrorMessage { get; set; } - } -} \ No newline at end of file + /// <summary> + /// Wrap the command status to bridge the commands status and UI. + /// </summary> + public class CommandStatus : NSObject { + public CommandStatus (Command command, Phrase phrase) + { + this.Command = command; + this.Phrase = phrase; + } + + public Command Command { get; set; } + public Phrase Phrase { get; set; } + public TimedColor TimedColor { get; set; } + public WCSessionFileTransfer FileTransfer { get; set; } + public WCSessionFile File { get; set; } + public WCSessionUserInfoTransfer UserInfoTranser { get; set; } + public string ErrorMessage { get; set; } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/FileTransferObservers.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/FileTransferObservers.cs index b0c856092..d7785df0a 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/FileTransferObservers.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/FileTransferObservers.cs @@ -1,60 +1,55 @@ - -namespace SimpleWatchConnectivity -{ - using Foundation; - using System; - using System.Collections.Generic; - using WatchConnectivity; - - /// <summary> - /// Manage the observation of file transfers. - /// </summary> - public class FileTransferObservers - { - // Hold the observations and file transfers. - // KVO will be removed automatically after observations are released. - private readonly List<WCSessionFileTransfer> fileTransfers = new List<WCSessionFileTransfer>(); - private readonly List<IDisposable> observations = new List<IDisposable>(); - - ~FileTransferObservers() - { - // Dispose all the observations. - foreach (var observation in this.observations) - { - observation.Dispose(); - } - - this.observations.Clear(); - } - - /// <summary> - /// Observe a file transfer, hold the observation. - /// </summary> - public void Observe(WCSessionFileTransfer fileTransfer, Action<NSProgress> handler) - { - var observation = fileTransfer.Progress.AddObserver("fractionCompleted", NSKeyValueObservingOptions.New, (_) => - { - handler(fileTransfer.Progress); - }); - - this.observations.Add(observation); - this.fileTransfers.Add(fileTransfer); - } - - /// <summary> - /// Unobserve a file transfer, invalidate the observation. - /// </summary> - public void Unobserve(WCSessionFileTransfer fileTransfer) - { - var index = this.fileTransfers.IndexOf(fileTransfer); - if (index != -1) - { - var observation = this.observations[index]; - observation.Dispose(); - - this.observations.RemoveAt(index); - this.fileTransfers.RemoveAt(index); - } - } - } -} \ No newline at end of file + +namespace SimpleWatchConnectivity { + using Foundation; + using System; + using System.Collections.Generic; + using WatchConnectivity; + + /// <summary> + /// Manage the observation of file transfers. + /// </summary> + public class FileTransferObservers { + // Hold the observations and file transfers. + // KVO will be removed automatically after observations are released. + private readonly List<WCSessionFileTransfer> fileTransfers = new List<WCSessionFileTransfer> (); + private readonly List<IDisposable> observations = new List<IDisposable> (); + + ~FileTransferObservers () + { + // Dispose all the observations. + foreach (var observation in this.observations) { + observation.Dispose (); + } + + this.observations.Clear (); + } + + /// <summary> + /// Observe a file transfer, hold the observation. + /// </summary> + public void Observe (WCSessionFileTransfer fileTransfer, Action<NSProgress> handler) + { + var observation = fileTransfer.Progress.AddObserver ("fractionCompleted", NSKeyValueObservingOptions.New, (_) => { + handler (fileTransfer.Progress); + }); + + this.observations.Add (observation); + this.fileTransfers.Add (fileTransfer); + } + + /// <summary> + /// Unobserve a file transfer, invalidate the observation. + /// </summary> + public void Unobserve (WCSessionFileTransfer fileTransfer) + { + var index = this.fileTransfers.IndexOf (fileTransfer); + if (index != -1) { + var observation = this.observations [index]; + observation.Dispose (); + + this.observations.RemoveAt (index); + this.fileTransfers.RemoveAt (index); + } + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/Logger.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/Logger.cs index e8fa38e70..b6db5b70e 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/Logger.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/Logger.cs @@ -1,174 +1,157 @@ - -namespace SimpleWatchConnectivity -{ - using CoreFoundation; - using Foundation; - using System; - using System.Linq; - - // Logger is a debug utility, used to write logs into a log file. - // WKWatchConnectivityRefreshBackgroundTask is mostly triggered when the watch app is in the background - // and background task budget is limited, we hence can't use Xcode debugger to attach the process. - // Mostly for debugging purpose, the class writes logs into a file. Clients thus can tranfer the log file - // and view it on iOS side. - public class Logger - { - private static Logger shared; - - private NSFileHandle fileHandle; - - private Logger() - { - this.fileHandle = NSFileHandle.OpenUpdateUrl(this.FileUrl, out NSError error); - System.Diagnostics.Debug.Assert(this.fileHandle != null, "Failed to create the file handle!"); - } - - public static Logger Shared => shared ?? (shared = new Logger()); - - // Return folder URL, create it if not existing yet. - // Return nil to trigger a crash if the folder creation fails. - // Not using lazy because we need to recreate when clearLogs is called. - private NSUrl folderUrl; - protected NSUrl FolderUrl - { - get - { - if (this.folderUrl == null) - { - this.folderUrl = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).Last(); - this.folderUrl = this.folderUrl.Append("Logs", true); - - if (!NSFileManager.DefaultManager.FileExists(this.folderUrl.Path)) - { - NSFileManager.DefaultManager.CreateDirectory(this.folderUrl, true, null, out NSError error); - if (error != null) - { - Console.WriteLine($"Failed to create the log folder: {this.folderUrl} \n{error.LocalizedDescription}"); - this.folderUrl = null; - } - } - } - - return this.folderUrl; - } - } - - // Return file URL, create it if not existing yet. - // Return nil to trigger a crash if the file creation fails. - // Not using lazy because we need to recreate when clearLogs is called. - private NSUrl fileUrl; - protected NSUrl FileUrl - { - get - { - if (this.fileUrl == null) - { - var dateFormatter = new NSDateFormatter { DateStyle = NSDateFormatterStyle.Medium }; - var dateString = dateFormatter.StringFor(new NSDate()); - - this.fileUrl = this.FolderUrl; - this.fileUrl = this.fileUrl.Append($"{dateString}.log", false); - - if (!NSFileManager.DefaultManager.FileExists(this.fileUrl.Path)) - { - if (!NSFileManager.DefaultManager.CreateFile(this.fileUrl.Path, NSData.FromString(string.Empty), (NSDictionary)null)) - { - Console.WriteLine($"Failed to create the log file: {this.fileUrl}!"); - this.fileUrl = null; - } - } - } - - return this.fileUrl; - } - } - - #region logging - - // Avoid creating DateFormatter for time stamp as Logger may count into execution budget. - private readonly NSDateFormatter timeStampFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; - - // Use this dispatch queue to make the log file access is thread-safe. - // Public methods use performBlockAndWait to access the resource; private methods don't. - private readonly DispatchQueue ioQueue = new DispatchQueue("ioQueue"); - - /// <summary> - /// Get the current log file URL. - /// </summary> - public NSUrl GetFileURL() - { - return PerformBlockAndWait(() => fileUrl); - } - - /// <summary> - /// Append a line of text to the end of the file. - /// Use FileHandle so that we can see to the end directly. - /// </summary> - public void Append(string line) - { - var timeStamp = this.timeStampFormatter.StringFor(new NSDate()); - var timedLine = $"{timeStamp}: {line} \n"; - - var data = NSData.FromString(timedLine, NSStringEncoding.UTF8); - using (data) - { - this.PerformBlockAndWait(() => - { - this.fileHandle.SeekToEndOfFile(); - this.fileHandle.WriteData(data); - }); - } - } - - /// <summary> - /// Read the file content and return it as a string. - /// </summary> - public string Content() - { - return this.PerformBlockAndWait(() => - { - this.fileHandle.SeekToFileOffset(0); // Read from the very beginning. - return NSString.FromData(this.fileHandle.AvailableData(), NSStringEncoding.UTF8); - }); - } - - /// <summary> - /// Clear logs. Reset the folder and file URL for later use. - /// </summary> - public void ClearLogs() - { - this.PerformBlockAndWait(() => - { - this.fileHandle.CloseFile(); - this.fileHandle.Dispose(); - this.fileHandle = null; - - NSFileManager.DefaultManager.Remove(this.folderUrl, out NSError error); - if (error != null) - { - Console.WriteLine($"Failed to clear the log folder!\n{error.LocalizedDescription ?? string.Empty}"); - } - - // Create a new file handle. - this.fileUrl = null; - this.folderUrl = null; - this.fileHandle = NSFileHandle.OpenUpdateUrl(this.FileUrl, out NSError urlError); - System.Diagnostics.Debug.Assert(this.fileHandle != null, "Failed to create the file handle!"); - }); - } - - private T PerformBlockAndWait<T>(Func<T> block) - { - return block(); - // TODO: https://github.com/xamarin/xamarin-macios/issues/5002 - //return this.ioQueue.DispatchSync(() => return block()); - } - - private void PerformBlockAndWait(Action block) - { - this.ioQueue.DispatchSync(block); - } - - #endregion - } -} \ No newline at end of file + +namespace SimpleWatchConnectivity { + using CoreFoundation; + using Foundation; + using System; + using System.Linq; + + // Logger is a debug utility, used to write logs into a log file. + // WKWatchConnectivityRefreshBackgroundTask is mostly triggered when the watch app is in the background + // and background task budget is limited, we hence can't use Xcode debugger to attach the process. + // Mostly for debugging purpose, the class writes logs into a file. Clients thus can tranfer the log file + // and view it on iOS side. + public class Logger { + private static Logger shared; + + private NSFileHandle fileHandle; + + private Logger () + { + this.fileHandle = NSFileHandle.OpenUpdateUrl (this.FileUrl, out NSError error); + System.Diagnostics.Debug.Assert (this.fileHandle != null, "Failed to create the file handle!"); + } + + public static Logger Shared => shared ?? (shared = new Logger ()); + + // Return folder URL, create it if not existing yet. + // Return nil to trigger a crash if the folder creation fails. + // Not using lazy because we need to recreate when clearLogs is called. + private NSUrl folderUrl; + protected NSUrl FolderUrl { + get { + if (this.folderUrl == null) { + this.folderUrl = NSFileManager.DefaultManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User).Last (); + this.folderUrl = this.folderUrl.Append ("Logs", true); + + if (!NSFileManager.DefaultManager.FileExists (this.folderUrl.Path)) { + NSFileManager.DefaultManager.CreateDirectory (this.folderUrl, true, null, out NSError error); + if (error != null) { + Console.WriteLine ($"Failed to create the log folder: {this.folderUrl} \n{error.LocalizedDescription}"); + this.folderUrl = null; + } + } + } + + return this.folderUrl; + } + } + + // Return file URL, create it if not existing yet. + // Return nil to trigger a crash if the file creation fails. + // Not using lazy because we need to recreate when clearLogs is called. + private NSUrl fileUrl; + protected NSUrl FileUrl { + get { + if (this.fileUrl == null) { + var dateFormatter = new NSDateFormatter { DateStyle = NSDateFormatterStyle.Medium }; + var dateString = dateFormatter.StringFor (new NSDate ()); + + this.fileUrl = this.FolderUrl; + this.fileUrl = this.fileUrl.Append ($"{dateString}.log", false); + + if (!NSFileManager.DefaultManager.FileExists (this.fileUrl.Path)) { + if (!NSFileManager.DefaultManager.CreateFile (this.fileUrl.Path, NSData.FromString (string.Empty), (NSDictionary) null)) { + Console.WriteLine ($"Failed to create the log file: {this.fileUrl}!"); + this.fileUrl = null; + } + } + } + + return this.fileUrl; + } + } + + #region logging + + // Avoid creating DateFormatter for time stamp as Logger may count into execution budget. + private readonly NSDateFormatter timeStampFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; + + // Use this dispatch queue to make the log file access is thread-safe. + // Public methods use performBlockAndWait to access the resource; private methods don't. + private readonly DispatchQueue ioQueue = new DispatchQueue ("ioQueue"); + + /// <summary> + /// Get the current log file URL. + /// </summary> + public NSUrl GetFileURL () + { + return PerformBlockAndWait (() => fileUrl); + } + + /// <summary> + /// Append a line of text to the end of the file. + /// Use FileHandle so that we can see to the end directly. + /// </summary> + public void Append (string line) + { + var timeStamp = this.timeStampFormatter.StringFor (new NSDate ()); + var timedLine = $"{timeStamp}: {line} \n"; + + var data = NSData.FromString (timedLine, NSStringEncoding.UTF8); + using (data) { + this.PerformBlockAndWait (() => { + this.fileHandle.SeekToEndOfFile (); + this.fileHandle.WriteData (data); + }); + } + } + + /// <summary> + /// Read the file content and return it as a string. + /// </summary> + public string Content () + { + return this.PerformBlockAndWait (() => { + this.fileHandle.SeekToFileOffset (0); // Read from the very beginning. + return NSString.FromData (this.fileHandle.AvailableData (), NSStringEncoding.UTF8); + }); + } + + /// <summary> + /// Clear logs. Reset the folder and file URL for later use. + /// </summary> + public void ClearLogs () + { + this.PerformBlockAndWait (() => { + this.fileHandle.CloseFile (); + this.fileHandle.Dispose (); + this.fileHandle = null; + + NSFileManager.DefaultManager.Remove (this.folderUrl, out NSError error); + if (error != null) { + Console.WriteLine ($"Failed to clear the log folder!\n{error.LocalizedDescription ?? string.Empty}"); + } + + // Create a new file handle. + this.fileUrl = null; + this.folderUrl = null; + this.fileHandle = NSFileHandle.OpenUpdateUrl (this.FileUrl, out NSError urlError); + System.Diagnostics.Debug.Assert (this.fileHandle != null, "Failed to create the file handle!"); + }); + } + + private T PerformBlockAndWait<T> (Func<T> block) + { + return block (); + // TODO: https://github.com/xamarin/xamarin-macios/issues/5002 + //return this.ioQueue.DispatchSync(() => return block()); + } + + private void PerformBlockAndWait (Action block) + { + this.ioQueue.DispatchSync (block); + } + + #endregion + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionCommands.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionCommands.cs index 98cf711a2..51f958aa6 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionCommands.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionCommands.cs @@ -1,150 +1,127 @@ - -namespace SimpleWatchConnectivity -{ - using CoreFoundation; - using Foundation; - using WatchConnectivity; - - /// <summary> - /// Every command handles the communication and notifies clients - /// when WCSession status changes or data flows. Shared by the iOS app and watchOS app. - /// </summary> - public static class SessionCommands - { - /// <summary> - /// Update app context if the session is activated and update UI with the command status. - /// </summary> - public static void UpdateAppContext(NSDictionary<NSString, NSObject> context) - { - var commandStatus = new CommandStatus(Command.UpdateAppContext, Phrase.Updated) { TimedColor = new TimedColor(context) }; - - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - WCSession.DefaultSession.UpdateApplicationContext(context, out NSError error); - if (error != null) - { - commandStatus.Phrase = Phrase.Failed; - commandStatus.ErrorMessage = error.LocalizedDescription; - } - - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - else - { - HandleSessionUnactivated(commandStatus); - } - } - - /// <summary> - /// Send a message if the session is activated and update UI with the command status. - /// </summary> - public static void SendMessage(NSDictionary<NSString, NSObject> message) - { - var commandStatus = new CommandStatus(Command.SendMessage, Phrase.Sent) { TimedColor = new TimedColor(message) }; - - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - WCSession.DefaultSession.SendMessage(message, (replyMessage) => - { - commandStatus.Phrase = Phrase.Replied; - commandStatus.TimedColor = new TimedColor(replyMessage); - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - }, (error) => - { - commandStatus.Phrase = Phrase.Failed; - commandStatus.ErrorMessage = error.LocalizedDescription; - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - }); - - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - - } - else - { - HandleSessionUnactivated(commandStatus); - } - } - - /// <summary> - /// Send a piece of message data if the session is activated and update UI with the command status. - /// </summary> - public static void SendMessageData(NSData messageData) - { - var commandStatus = new CommandStatus(Command.SendMessageData, Phrase.Sent) { TimedColor = TimedColor.Create(messageData) }; - - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - WCSession.DefaultSession.SendMessage(messageData, (replyData) => - { - commandStatus.Phrase = Phrase.Replied; - commandStatus.TimedColor = TimedColor.Create(replyData); - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - }, (error) => - { - commandStatus.Phrase = Phrase.Failed; - commandStatus.ErrorMessage = error.LocalizedDescription; - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - }); - - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - - } - else - { - HandleSessionUnactivated(commandStatus); - } - } - - /// <summary> - /// Transfer a piece of user info if the session is activated and update UI with the command status. - /// A WCSessionUserInfoTransfer object is returned to monitor the progress or cancel the operation. - /// </summary> - public static void TransferUserInfo(NSDictionary<NSString, NSObject> userInfo) - { - var commandStatus = new CommandStatus(Command.TransferUserInfo, Phrase.Transferring) { TimedColor = new TimedColor(userInfo) }; - - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - commandStatus.UserInfoTranser = WCSession.DefaultSession.TransferUserInfo(userInfo); - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - else - { - HandleSessionUnactivated(commandStatus); - } - } - - /// <summary> - /// Transfer a file if the session is activated and update UI with the command status. - /// A WCSessionFileTransfer object is returned to monitor the progress or cancel the operation. - /// </summary> - public static void TransferFile(NSUrl file, NSDictionary<NSString, NSObject> metadata) - { - var commandStatus = new CommandStatus(Command.TransferFile, Phrase.Transferring) { TimedColor = new TimedColor(metadata) }; - - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - commandStatus.FileTransfer = WCSession.DefaultSession.TransferFile(file, metadata); - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - else - { - HandleSessionUnactivated(commandStatus); - } - } - - /// <summary> - /// Transfer a piece fo user info for current complications if the session is activated and update UI with the command status. - /// A WCSessionUserInfoTransfer object is returned to monitor the progress or cancel the operation. - /// </summary> - public static void TransferCurrentComplicationUserInfo(NSDictionary<NSString, NSObject> userInfo) - { - var commandStatus = new CommandStatus(Command.TransferCurrentComplicationUserInfo, Phrase.Failed) { TimedColor = new TimedColor(userInfo) }; - - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - commandStatus.ErrorMessage = "Not supported on watchOS!"; +namespace SimpleWatchConnectivity { + using CoreFoundation; + using Foundation; + using WatchConnectivity; + + /// <summary> + /// Every command handles the communication and notifies clients + /// when WCSession status changes or data flows. Shared by the iOS app and watchOS app. + /// </summary> + public static class SessionCommands { + /// <summary> + /// Update app context if the session is activated and update UI with the command status. + /// </summary> + public static void UpdateAppContext (NSDictionary<NSString, NSObject> context) + { + var commandStatus = new CommandStatus (Command.UpdateAppContext, Phrase.Updated) { TimedColor = new TimedColor (context) }; + + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + WCSession.DefaultSession.UpdateApplicationContext (context, out NSError error); + if (error != null) { + commandStatus.Phrase = Phrase.Failed; + commandStatus.ErrorMessage = error.LocalizedDescription; + } + + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } else { + HandleSessionUnactivated (commandStatus); + } + } + + /// <summary> + /// Send a message if the session is activated and update UI with the command status. + /// </summary> + public static void SendMessage (NSDictionary<NSString, NSObject> message) + { + var commandStatus = new CommandStatus (Command.SendMessage, Phrase.Sent) { TimedColor = new TimedColor (message) }; + + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + WCSession.DefaultSession.SendMessage (message, (replyMessage) => { + commandStatus.Phrase = Phrase.Replied; + commandStatus.TimedColor = new TimedColor (replyMessage); + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + + }, (error) => { + commandStatus.Phrase = Phrase.Failed; + commandStatus.ErrorMessage = error.LocalizedDescription; + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + }); + + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + + } else { + HandleSessionUnactivated (commandStatus); + } + } + + /// <summary> + /// Send a piece of message data if the session is activated and update UI with the command status. + /// </summary> + public static void SendMessageData (NSData messageData) + { + var commandStatus = new CommandStatus (Command.SendMessageData, Phrase.Sent) { TimedColor = TimedColor.Create (messageData) }; + + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + WCSession.DefaultSession.SendMessage (messageData, (replyData) => { + commandStatus.Phrase = Phrase.Replied; + commandStatus.TimedColor = TimedColor.Create (replyData); + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + }, (error) => { + commandStatus.Phrase = Phrase.Failed; + commandStatus.ErrorMessage = error.LocalizedDescription; + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + }); + + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + + } else { + HandleSessionUnactivated (commandStatus); + } + } + + /// <summary> + /// Transfer a piece of user info if the session is activated and update UI with the command status. + /// A WCSessionUserInfoTransfer object is returned to monitor the progress or cancel the operation. + /// </summary> + public static void TransferUserInfo (NSDictionary<NSString, NSObject> userInfo) + { + var commandStatus = new CommandStatus (Command.TransferUserInfo, Phrase.Transferring) { TimedColor = new TimedColor (userInfo) }; + + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + commandStatus.UserInfoTranser = WCSession.DefaultSession.TransferUserInfo (userInfo); + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } else { + HandleSessionUnactivated (commandStatus); + } + } + + /// <summary> + /// Transfer a file if the session is activated and update UI with the command status. + /// A WCSessionFileTransfer object is returned to monitor the progress or cancel the operation. + /// </summary> + public static void TransferFile (NSUrl file, NSDictionary<NSString, NSObject> metadata) + { + var commandStatus = new CommandStatus (Command.TransferFile, Phrase.Transferring) { TimedColor = new TimedColor (metadata) }; + + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + commandStatus.FileTransfer = WCSession.DefaultSession.TransferFile (file, metadata); + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } else { + HandleSessionUnactivated (commandStatus); + } + } + + /// <summary> + /// Transfer a piece fo user info for current complications if the session is activated and update UI with the command status. + /// A WCSessionUserInfoTransfer object is returned to monitor the progress or cancel the operation. + /// </summary> + public static void TransferCurrentComplicationUserInfo (NSDictionary<NSString, NSObject> userInfo) + { + var commandStatus = new CommandStatus (Command.TransferCurrentComplicationUserInfo, Phrase.Failed) { TimedColor = new TimedColor (userInfo) }; + + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + commandStatus.ErrorMessage = "Not supported on watchOS!"; #if __IOS__ if (WCSession.DefaultSession.ComplicationEnabled) @@ -160,34 +137,31 @@ public static void TransferCurrentComplicationUserInfo(NSDictionary<NSString, NS } #endif - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - else - { - HandleSessionUnactivated(commandStatus); - } - } - - /// <summary> - /// Post a notification on the main thread asynchronously. - /// </summary> - private static void PostNotificationOnMainQueueAsync(string name, CommandStatus @object) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - NSNotificationCenter.DefaultCenter.PostNotificationName(name, @object); - }); - } - - /// <summary> - /// Handle the session unactived error. WCSession commands require an activated session. - /// </summary> - private static void HandleSessionUnactivated(CommandStatus commandStatus) - { - var mutableStatus = commandStatus; - mutableStatus.Phrase = Phrase.Failed; - mutableStatus.ErrorMessage = "WCSession is not activeted yet!"; - PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - } -} \ No newline at end of file + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } else { + HandleSessionUnactivated (commandStatus); + } + } + + /// <summary> + /// Post a notification on the main thread asynchronously. + /// </summary> + private static void PostNotificationOnMainQueueAsync (string name, CommandStatus @object) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + NSNotificationCenter.DefaultCenter.PostNotificationName (name, @object); + }); + } + + /// <summary> + /// Handle the session unactived error. WCSession commands require an activated session. + /// </summary> + private static void HandleSessionUnactivated (CommandStatus commandStatus) + { + var mutableStatus = commandStatus; + mutableStatus.Phrase = Phrase.Failed; + mutableStatus.ErrorMessage = "WCSession is not activeted yet!"; + PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionDelegater.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionDelegater.cs index c4c368879..aafce7d0b 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionDelegater.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionDelegater.cs @@ -1,105 +1,101 @@ - -namespace SimpleWatchConnectivity -{ - using CoreFoundation; - using Foundation; - using System; - using System.Linq; - using WatchConnectivity; + +namespace SimpleWatchConnectivity { + using CoreFoundation; + using Foundation; + using System; + using System.Linq; + using WatchConnectivity; #if __WATCHOS__ using ClockKit; #endif - /// <summary> - /// Custom notifications. - /// Posted when Watch Connectivity activation or reachibility status is changed, or when data is received or sent. Clients observe these notifications to update the UI. - /// </summary> - public static class NotificationName - { - public static NSString DataDidFlow = new NSString("DataDidFlow"); - public static NSString ActivationDidComplete = new NSString("ActivationDidComplete"); - public static NSString ReachabilityDidChange = new NSString("ReachabilityDidChange"); - } - - /// <summary> - /// Implement WCSessionDelegate methods to receive Watch Connectivity data and notify clients. - /// WCsession status changes are also handled here. - /// </summary> - public class SessionDelegater : WCSessionDelegate - { - /// <summary> - /// Called when WCSession activation state is changed. - /// </summary> - public override void ActivationDidComplete(WCSession session, WCSessionActivationState activationState, NSError error) - { - this.PostNotificationOnMainQueueAsync(NotificationName.ActivationDidComplete); - } - - /// <summary> - /// Called when WCSession reachability is changed. - /// </summary> - public override void SessionReachabilityDidChange(WCSession session) - { - this.PostNotificationOnMainQueueAsync(NotificationName.ReachabilityDidChange); - } - - /// <summary> - /// Called when an app context is received. - /// </summary> - public override void DidReceiveApplicationContext(WCSession session, NSDictionary<NSString, NSObject> applicationContext) - { - var commandStatus = new CommandStatus(Command.UpdateAppContext, Phrase.Received) { TimedColor = new TimedColor(applicationContext) }; - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - - /// <summary> - /// Called when a message is received and the peer doesn't need a response. - /// </summary> - public override void DidReceiveMessage(WCSession session, NSDictionary<NSString, NSObject> message) - { - var commandStatus = new CommandStatus(Command.SendMessage, Phrase.Received) { TimedColor = new TimedColor(message) }; - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - - /// <summary> - /// Called when a message is received and the peer needs a response. - /// </summary> - public override void DidReceiveMessage(WCSession session, NSDictionary<NSString, NSObject> message, WCSessionReplyHandler replyHandler) - { - this.DidReceiveMessage(session, message); - replyHandler(message); // Echo back the time stamp. - } - - /// <summary> - /// Called when a piece of message data is received and the peer doesn't need a respons - /// </summary> - public override void DidReceiveMessageData(WCSession session, NSData messageData) - { - var commandStatus = new CommandStatus(Command.SendMessageData, Phrase.Received) { TimedColor = TimedColor.Create(messageData) }; - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - - /// <summary> - /// Called when a piece of message data is received and the peer needs a response. - /// </summary> - public override void DidReceiveMessageData(WCSession session, NSData messageData, WCSessionReplyDataHandler replyHandler) - { - this.DidReceiveMessageData(session, messageData); - replyHandler(messageData); // Echo back the time stamp. - } - - /// <summary> - /// Called when a userInfo is received. - /// </summary> - public override void DidReceiveUserInfo(WCSession session, NSDictionary<NSString, NSObject> userInfo) - { - var commandStatus = new CommandStatus(Command.TransferUserInfo, Phrase.Received) { TimedColor = new TimedColor(userInfo) }; - - if (userInfo.TryGetValue(PayloadKey.IsCurrentComplicationInfo, out NSObject isComplicationInfoObject) && - isComplicationInfoObject is NSNumber isComplicationInfo && isComplicationInfo.BoolValue) - { - commandStatus.Command = Command.TransferCurrentComplicationUserInfo; + /// <summary> + /// Custom notifications. + /// Posted when Watch Connectivity activation or reachibility status is changed, or when data is received or sent. Clients observe these notifications to update the UI. + /// </summary> + public static class NotificationName { + public static NSString DataDidFlow = new NSString ("DataDidFlow"); + public static NSString ActivationDidComplete = new NSString ("ActivationDidComplete"); + public static NSString ReachabilityDidChange = new NSString ("ReachabilityDidChange"); + } + + /// <summary> + /// Implement WCSessionDelegate methods to receive Watch Connectivity data and notify clients. + /// WCsession status changes are also handled here. + /// </summary> + public class SessionDelegater : WCSessionDelegate { + /// <summary> + /// Called when WCSession activation state is changed. + /// </summary> + public override void ActivationDidComplete (WCSession session, WCSessionActivationState activationState, NSError error) + { + this.PostNotificationOnMainQueueAsync (NotificationName.ActivationDidComplete); + } + + /// <summary> + /// Called when WCSession reachability is changed. + /// </summary> + public override void SessionReachabilityDidChange (WCSession session) + { + this.PostNotificationOnMainQueueAsync (NotificationName.ReachabilityDidChange); + } + + /// <summary> + /// Called when an app context is received. + /// </summary> + public override void DidReceiveApplicationContext (WCSession session, NSDictionary<NSString, NSObject> applicationContext) + { + var commandStatus = new CommandStatus (Command.UpdateAppContext, Phrase.Received) { TimedColor = new TimedColor (applicationContext) }; + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } + + /// <summary> + /// Called when a message is received and the peer doesn't need a response. + /// </summary> + public override void DidReceiveMessage (WCSession session, NSDictionary<NSString, NSObject> message) + { + var commandStatus = new CommandStatus (Command.SendMessage, Phrase.Received) { TimedColor = new TimedColor (message) }; + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } + + /// <summary> + /// Called when a message is received and the peer needs a response. + /// </summary> + public override void DidReceiveMessage (WCSession session, NSDictionary<NSString, NSObject> message, WCSessionReplyHandler replyHandler) + { + this.DidReceiveMessage (session, message); + replyHandler (message); // Echo back the time stamp. + } + + /// <summary> + /// Called when a piece of message data is received and the peer doesn't need a respons + /// </summary> + public override void DidReceiveMessageData (WCSession session, NSData messageData) + { + var commandStatus = new CommandStatus (Command.SendMessageData, Phrase.Received) { TimedColor = TimedColor.Create (messageData) }; + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } + + /// <summary> + /// Called when a piece of message data is received and the peer needs a response. + /// </summary> + public override void DidReceiveMessageData (WCSession session, NSData messageData, WCSessionReplyDataHandler replyHandler) + { + this.DidReceiveMessageData (session, messageData); + replyHandler (messageData); // Echo back the time stamp. + } + + /// <summary> + /// Called when a userInfo is received. + /// </summary> + public override void DidReceiveUserInfo (WCSession session, NSDictionary<NSString, NSObject> userInfo) + { + var commandStatus = new CommandStatus (Command.TransferUserInfo, Phrase.Received) { TimedColor = new TimedColor (userInfo) }; + + if (userInfo.TryGetValue (PayloadKey.IsCurrentComplicationInfo, out NSObject isComplicationInfoObject) && + isComplicationInfoObject is NSNumber isComplicationInfo && isComplicationInfo.BoolValue) { + commandStatus.Command = Command.TransferCurrentComplicationUserInfo; #if __WATCHOS__ var server = CLKComplicationServer.SharedInstance; @@ -114,17 +110,17 @@ public override void DidReceiveUserInfo(WCSession session, NSDictionary<NSString } } #endif - } + } - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } - /// <summary> - /// Called when sending a userInfo is done. - /// </summary> - public override void DidFinishUserInfoTransfer(WCSession session, WCSessionUserInfoTransfer userInfoTransfer, NSError error) - { - var commandStatus = new CommandStatus(Command.TransferUserInfo, Phrase.Finished) { TimedColor = new TimedColor(userInfoTransfer.UserInfo) }; + /// <summary> + /// Called when sending a userInfo is done. + /// </summary> + public override void DidFinishUserInfoTransfer (WCSession session, WCSessionUserInfoTransfer userInfoTransfer, NSError error) + { + var commandStatus = new CommandStatus (Command.TransferUserInfo, Phrase.Finished) { TimedColor = new TimedColor (userInfoTransfer.UserInfo) }; #if __IOS__ if (userInfoTransfer.CurrentComplicationInfo) @@ -133,51 +129,45 @@ public override void DidFinishUserInfoTransfer(WCSession session, WCSessionUserI } #endif - if (error != null) - { - commandStatus.ErrorMessage = error.LocalizedDescription; - } - - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - - /// <summary> - /// Called when a file is received. - /// </summary> - public override void DidReceiveFile(WCSession session, WCSessionFile file) - { - var commandStatus = new CommandStatus(Command.TransferFile, Phrase.Received) - { - File = file, - TimedColor = new TimedColor(file.Metadata) - }; - - // Note that WCSessionFile.fileURL will be removed once this method returns, - // so instead of calling postNotificationOnMainQueue(name: .dataDidFlow, userInfo: userInfo), - // we dispatch to main queue SYNCHRONOUSLY. - - DispatchQueue.MainQueue.DispatchSync(() => - { - NSNotificationCenter.DefaultCenter.PostNotificationName(NotificationName.DataDidFlow, commandStatus); - }); - } - - /// <summary> - /// Called when a file transfer is done. - /// </summary> - public override void DidFinishFileTransfer(WCSession session, WatchConnectivity.WCSessionFileTransfer fileTransfer, NSError error) - { - var commandStatus = new CommandStatus(Command.TransferFile, Phrase.Finished); - - if (error != null) - { - commandStatus.ErrorMessage = error.LocalizedDescription; - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - else - { - commandStatus.FileTransfer = fileTransfer; - commandStatus.TimedColor = new TimedColor(fileTransfer.File.Metadata); + if (error != null) { + commandStatus.ErrorMessage = error.LocalizedDescription; + } + + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } + + /// <summary> + /// Called when a file is received. + /// </summary> + public override void DidReceiveFile (WCSession session, WCSessionFile file) + { + var commandStatus = new CommandStatus (Command.TransferFile, Phrase.Received) { + File = file, + TimedColor = new TimedColor (file.Metadata) + }; + + // Note that WCSessionFile.fileURL will be removed once this method returns, + // so instead of calling postNotificationOnMainQueue(name: .dataDidFlow, userInfo: userInfo), + // we dispatch to main queue SYNCHRONOUSLY. + + DispatchQueue.MainQueue.DispatchSync (() => { + NSNotificationCenter.DefaultCenter.PostNotificationName (NotificationName.DataDidFlow, commandStatus); + }); + } + + /// <summary> + /// Called when a file transfer is done. + /// </summary> + public override void DidFinishFileTransfer (WCSession session, WatchConnectivity.WCSessionFileTransfer fileTransfer, NSError error) + { + var commandStatus = new CommandStatus (Command.TransferFile, Phrase.Finished); + + if (error != null) { + commandStatus.ErrorMessage = error.LocalizedDescription; + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } else { + commandStatus.FileTransfer = fileTransfer; + commandStatus.TimedColor = new TimedColor (fileTransfer.File.Metadata); #if __WATCHOS__ if (!string.IsNullOrEmpty(WatchSettings.SharedContainerId)) @@ -189,11 +179,11 @@ public override void DidFinishFileTransfer(WCSession session, WatchConnectivity. } } #endif - this.PostNotificationOnMainQueueAsync(NotificationName.DataDidFlow, commandStatus); - } - } + this.PostNotificationOnMainQueueAsync (NotificationName.DataDidFlow, commandStatus); + } + } - #region WCSessionDelegate methods for iOS only. + #region WCSessionDelegate methods for iOS only. #if __IOS__ public override void DidBecomeInactive(WCSession session) @@ -213,17 +203,16 @@ public override void SessionWatchStateDidChange(WCSession session) } #endif - #endregion - - /// <summary> - /// Post a notification on the main thread asynchronously. - /// </summary> - private void PostNotificationOnMainQueueAsync(NSString name, CommandStatus @object = null) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - NSNotificationCenter.DefaultCenter.PostNotificationName(name, @object); - }); - } - } + #endregion + + /// <summary> + /// Post a notification on the main thread asynchronously. + /// </summary> + private void PostNotificationOnMainQueueAsync (NSString name, CommandStatus @object = null) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + NSNotificationCenter.DefaultCenter.PostNotificationName (name, @object); + }); + } + } } diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionTransfer.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionTransfer.cs index a311f1149..302f487ee 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionTransfer.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/SessionTransfer.cs @@ -1,68 +1,56 @@ -/* +/* SessionTransfer protocol defines the session transfer interface. Its extension implements the cancel method to cancel the transfer and notify UI. Used on both iOS and watchOS. */ -namespace SimpleWatchConnectivity -{ - using CoreFoundation; - using Foundation; - using WatchConnectivity; - - // Implement the cancel method to cancel the transfer and notify UI. - // - public class SessionTransfer - { - public WCSessionFileTransfer SessionFileTransfer { get; set; } - - public WCSessionUserInfoTransfer SessionUserInfoTransfer { get; set; } - - public TimedColor TimedColor - { - get - { - TimedColor result = null; - if (this.SessionFileTransfer != null) - { - result = new TimedColor(this.SessionFileTransfer.File.Metadata); - } - else if (this.SessionUserInfoTransfer != null) - { - result = new TimedColor(this.SessionUserInfoTransfer.UserInfo); - } - - return result; - } - } - - public void Cancel(Command command) - { - var commandStatus = new CommandStatus(command, Phrase.Canceled) { TimedColor = TimedColor }; - this.Cancel(); - - var dateFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; - if (commandStatus.TimedColor != null) - { - commandStatus.TimedColor.TimeStamp = dateFormatter.StringFor(new NSDate()); - } - - DispatchQueue.MainQueue.DispatchAsync(() => - { - NSNotificationCenter.DefaultCenter.PostNotificationName(NotificationName.DataDidFlow, commandStatus); - }); - } - - public void Cancel() - { - if (this.SessionFileTransfer != null) - { - this.SessionFileTransfer.Cancel(); - } - else if (this.SessionUserInfoTransfer != null) - { - this.SessionUserInfoTransfer.Cancel(); - } - } - } +namespace SimpleWatchConnectivity { + using CoreFoundation; + using Foundation; + using WatchConnectivity; + + // Implement the cancel method to cancel the transfer and notify UI. + // + public class SessionTransfer { + public WCSessionFileTransfer SessionFileTransfer { get; set; } + + public WCSessionUserInfoTransfer SessionUserInfoTransfer { get; set; } + + public TimedColor TimedColor { + get { + TimedColor result = null; + if (this.SessionFileTransfer != null) { + result = new TimedColor (this.SessionFileTransfer.File.Metadata); + } else if (this.SessionUserInfoTransfer != null) { + result = new TimedColor (this.SessionUserInfoTransfer.UserInfo); + } + + return result; + } + } + + public void Cancel (Command command) + { + var commandStatus = new CommandStatus (command, Phrase.Canceled) { TimedColor = TimedColor }; + this.Cancel (); + + var dateFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; + if (commandStatus.TimedColor != null) { + commandStatus.TimedColor.TimeStamp = dateFormatter.StringFor (new NSDate ()); + } + + DispatchQueue.MainQueue.DispatchAsync (() => { + NSNotificationCenter.DefaultCenter.PostNotificationName (NotificationName.DataDidFlow, commandStatus); + }); + } + + public void Cancel () + { + if (this.SessionFileTransfer != null) { + this.SessionFileTransfer.Cancel (); + } else if (this.SessionUserInfoTransfer != null) { + this.SessionUserInfoTransfer.Cancel (); + } + } + } } diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/TestDataProvider.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/TestDataProvider.cs index 4dfbc77ed..be9f91ee5 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/TestDataProvider.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.Shared/TestDataProvider.cs @@ -1,103 +1,93 @@ - -namespace SimpleWatchConnectivity -{ - using System; - using Foundation; - using UIKit; - using System.Linq; - - // Constants to access the payload dictionary. - // isCurrentComplicationInfo is to tell if the userInfo is from transferCurrentComplicationUserInfo - // in session:didReceiveUserInfo: (see SessionDelegater). - public static class PayloadKey - { - public static NSString TimeStamp = new NSString("timeStamp"); - public static NSString ColorData = new NSString("colorData"); - public static NSString IsCurrentComplicationInfo = new NSString("isCurrentComplicationInfo"); - } - - // Constants to identify the app group container used for Settings-Watch.bundle and access - // the information in Settings-Watch.bundle. - public static class WatchSettings - { - //public static string SharedContainerId = "" // Specify your group container ID here and Root.plist to make watch settings work. - public static NSString SharedContainerId = new NSString("group.com.xamarin.simple-watch-connectivity"); - public static NSString UseLogFileForFileTransfer = new NSString("useLogFileForFileTransfer"); - public static NSString ClearLogsAfterTransferred = new NSString("clearLogsAfterTransferred"); - } - - /// <summary> - /// Generate default payload for commands, which contains a random color and a time stamp. - /// </summary> - public static class TestDataProvider - { - /// <summary> - /// Generate a dictionary containing a time stamp and a random color data. - /// </summary> - private static NSDictionary<NSString, NSObject> GetTimedColor() - { - var random = new Random(); - var red = (float)random.NextDouble(); - var green = (float)random.NextDouble(); - var blue = (float)random.NextDouble(); - - var randomColor = UIColor.FromRGBA(red, green, blue, 1f); - - var data = NSKeyedArchiver.ArchivedDataWithRootObject(randomColor, false, out NSError error); - if (data == null || error != null) - { - throw new Exception("Failed to archive a UIColor!"); - } - - var dateFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; - var timeString = dateFormatter.StringFor(new NSDate()); - - return NSDictionary<NSString, NSObject>.FromObjectsAndKeys(new NSObject[] { new NSString(timeString), data }, - new NSString[] { PayloadKey.TimeStamp, PayloadKey.ColorData }); - } - - /// <summary> - /// Generate an app context, used as the payload for updateApplicationContext. - /// </summary> - public static NSDictionary<NSString, NSObject> AppContext => GetTimedColor(); - - /// <summary> - /// Generate a message, used as the payload for sendMessage. - /// </summary> - public static NSDictionary<NSString, NSObject> Message => GetTimedColor(); - - /// <summary> - /// Generate a message, used as the payload for sendMessageData. - /// </summary> - public static NSData MessageData - { - get - { - var data = NSKeyedArchiver.ArchivedDataWithRootObject(GetTimedColor(), false, out NSError error); - if (data == null || error != null) - { - throw new Exception("Failed to archive a timedColor dictionary!"); - } - return data; - } - } - - /// <summary> - /// Generate a userInfo dictionary, used as the payload for transferUserInfo. - /// </summary> - /// <value>The user info.</value> - public static NSDictionary<NSString, NSObject> UserInfo => GetTimedColor(); - - // Generate a file URL, used as the payload for transferFile. - // - // Use WatchSettings to choose the log file, which is generated by Logger - // for debugging purpose, for file transfer from the watch side. - // This is only for watchOS as the iOS app doesn't have WKBackgroundTask. - public static NSUrl File - { - get - { +namespace SimpleWatchConnectivity { + using System; + using Foundation; + using UIKit; + using System.Linq; + + // Constants to access the payload dictionary. + // isCurrentComplicationInfo is to tell if the userInfo is from transferCurrentComplicationUserInfo + // in session:didReceiveUserInfo: (see SessionDelegater). + public static class PayloadKey { + public static NSString TimeStamp = new NSString ("timeStamp"); + public static NSString ColorData = new NSString ("colorData"); + public static NSString IsCurrentComplicationInfo = new NSString ("isCurrentComplicationInfo"); + } + + // Constants to identify the app group container used for Settings-Watch.bundle and access + // the information in Settings-Watch.bundle. + public static class WatchSettings { + //public static string SharedContainerId = "" // Specify your group container ID here and Root.plist to make watch settings work. + public static NSString SharedContainerId = new NSString ("group.com.xamarin.simple-watch-connectivity"); + public static NSString UseLogFileForFileTransfer = new NSString ("useLogFileForFileTransfer"); + public static NSString ClearLogsAfterTransferred = new NSString ("clearLogsAfterTransferred"); + } + + /// <summary> + /// Generate default payload for commands, which contains a random color and a time stamp. + /// </summary> + public static class TestDataProvider { + /// <summary> + /// Generate a dictionary containing a time stamp and a random color data. + /// </summary> + private static NSDictionary<NSString, NSObject> GetTimedColor () + { + var random = new Random (); + var red = (float) random.NextDouble (); + var green = (float) random.NextDouble (); + var blue = (float) random.NextDouble (); + + var randomColor = UIColor.FromRGBA (red, green, blue, 1f); + + var data = NSKeyedArchiver.ArchivedDataWithRootObject (randomColor, false, out NSError error); + if (data == null || error != null) { + throw new Exception ("Failed to archive a UIColor!"); + } + + var dateFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; + var timeString = dateFormatter.StringFor (new NSDate ()); + + return NSDictionary<NSString, NSObject>.FromObjectsAndKeys (new NSObject [] { new NSString (timeString), data }, + new NSString [] { PayloadKey.TimeStamp, PayloadKey.ColorData }); + } + + /// <summary> + /// Generate an app context, used as the payload for updateApplicationContext. + /// </summary> + public static NSDictionary<NSString, NSObject> AppContext => GetTimedColor (); + + /// <summary> + /// Generate a message, used as the payload for sendMessage. + /// </summary> + public static NSDictionary<NSString, NSObject> Message => GetTimedColor (); + + /// <summary> + /// Generate a message, used as the payload for sendMessageData. + /// </summary> + public static NSData MessageData { + get { + var data = NSKeyedArchiver.ArchivedDataWithRootObject (GetTimedColor (), false, out NSError error); + if (data == null || error != null) { + throw new Exception ("Failed to archive a timedColor dictionary!"); + } + + return data; + } + } + + /// <summary> + /// Generate a userInfo dictionary, used as the payload for transferUserInfo. + /// </summary> + /// <value>The user info.</value> + public static NSDictionary<NSString, NSObject> UserInfo => GetTimedColor (); + + // Generate a file URL, used as the payload for transferFile. + // + // Use WatchSettings to choose the log file, which is generated by Logger + // for debugging purpose, for file transfer from the watch side. + // This is only for watchOS as the iOS app doesn't have WKBackgroundTask. + public static NSUrl File { + get { #if __WATCHOS__ if (!string.IsNullOrEmpty(WatchSettings.SharedContainerId)) { @@ -109,36 +99,33 @@ public static NSUrl File } #endif - // Use Info.plist for file transfer. - // Change this to a bigger file to make the file transfer progress more obvious. - var url = NSBundle.MainBundle.GetUrlForResource("Info", "plist"); ; - if (url == null) - { - throw new Exception("Failed to find Info.plist in current bundle!"); - } - - return url; - } - } - - /// <summary> - /// Generate a file metadata dictionary, used as the payload for transferFile. - /// </summary> - public static NSDictionary<NSString, NSObject> FileMetaData => GetTimedColor(); - - /// <summary> - /// Generate a complication info dictionary, used as the payload for transferCurrentComplicationUserInfo. - /// </summary> - public static NSDictionary<NSString, NSObject> CurrentComplicationInfo - { - get - { - var complicationInfo = GetTimedColor(); - - var objects = complicationInfo.Values.Append(new NSNumber(true)).ToArray(); - var keys = complicationInfo.Keys.Append(PayloadKey.IsCurrentComplicationInfo).ToArray(); - return NSDictionary<NSString, NSObject>.FromObjectsAndKeys(objects, keys); - } - } - } -} \ No newline at end of file + // Use Info.plist for file transfer. + // Change this to a bigger file to make the file transfer progress more obvious. + var url = NSBundle.MainBundle.GetUrlForResource ("Info", "plist"); ; + if (url == null) { + throw new Exception ("Failed to find Info.plist in current bundle!"); + } + + return url; + } + } + + /// <summary> + /// Generate a file metadata dictionary, used as the payload for transferFile. + /// </summary> + public static NSDictionary<NSString, NSObject> FileMetaData => GetTimedColor (); + + /// <summary> + /// Generate a complication info dictionary, used as the payload for transferCurrentComplicationUserInfo. + /// </summary> + public static NSDictionary<NSString, NSObject> CurrentComplicationInfo { + get { + var complicationInfo = GetTimedColor (); + + var objects = complicationInfo.Values.Append (new NSNumber (true)).ToArray (); + var keys = complicationInfo.Keys.Append (PayloadKey.IsCurrentComplicationInfo).ToArray (); + return NSDictionary<NSString, NSObject>.FromObjectsAndKeys (objects, keys); + } + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ComplicationController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ComplicationController.cs index 6a845e63a..eddfae5ae 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ComplicationController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ComplicationController.cs @@ -1,4 +1,4 @@ - + // The complication simply supports the Modular Large (tall body) family and // shows a random number for the current timeline entry. // You can make the complication current by following these steps: @@ -8,110 +8,100 @@ // 3. Rotate the digital crown to choose the SimpleWatchConnectivity complication. // 4. Press the digital crown and tap the screen to go back to the watch face. -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using ClockKit; - using Foundation; - using System; - - /// <summary> - /// The complication controller class for the complication. - /// </summary> - public class ComplicationController : CLKComplicationDataSource - { - #region Timeline Configuration. - - public override void GetSupportedTimeTravelDirections(CLKComplication complication, Action<CLKComplicationTimeTravelDirections> handler) - { - handler(CLKComplicationTimeTravelDirections.Forward | CLKComplicationTimeTravelDirections.Backward); - } - - public override void GetTimelineStartDate(CLKComplication complication, Action<NSDate> handler) - { - handler(null); - } - - public override void GetTimelineEndDate(CLKComplication complication, Action<NSDate> handler) - { - handler(null); - } - - public override void GetPrivacyBehavior(CLKComplication complication, Action<CLKComplicationPrivacyBehavior> handler) - { - handler(CLKComplicationPrivacyBehavior.ShowOnLockScreen); - } - - #endregion - - #region Timeline Population - - public override void GetCurrentTimelineEntry(CLKComplication complication, Action<CLKComplicationTimelineEntry> handler) - { - // Only support .modularLarge currently. - if (complication.Family == CLKComplicationFamily.ModularLarge) - { - var random = new Random(); - - // Display a random number string on the body. - var tallBody = new CLKComplicationTemplateModularLargeTallBody - { - HeaderTextProvider = CLKSimpleTextProvider.FromText("SimpleWC"), - BodyTextProvider = CLKSimpleTextProvider.FromText($"{random.Next(400)}") - }; - - // Pass the entry to ClockKit. - var entry = CLKComplicationTimelineEntry.Create(new NSDate(), tallBody); - handler(entry); - } - else - { - handler(null); - } - } - - public override void GetTimelineEntriesBeforeDate(CLKComplication complication, NSDate beforeDate, nuint limit, Action<CLKComplicationTimelineEntry[]> handler) - { - // Call the handler with the timeline entries prior to the given date. - handler(null); - } - - public override void GetTimelineEntriesAfterDate(CLKComplication complication, NSDate afterDate, nuint limit, Action<CLKComplicationTimelineEntry[]> handler) - { - // Call the handler with the timeline entries after to the given date. - handler(null); - } - - #endregion - - #region Placeholder Templates. - - public override void GetLocalizableSampleTemplate(CLKComplication complication, Action<CLKComplicationTemplate> handler) - { - // This method will be called once per supported complication, and the results will be cached. - handler(null); - } - - public override void GetPlaceholderTemplate(CLKComplication complication, Action<CLKComplicationTemplate> handler) - { - // Only support .modularLarge currently. - if (complication.Family == CLKComplicationFamily.ModularLarge) - { - // Display a random number string on the body. - var tallBody = new CLKComplicationTemplateModularLargeTallBody - { - HeaderTextProvider = CLKSimpleTextProvider.FromText("SimpleWC"), - BodyTextProvider = CLKSimpleTextProvider.FromText("Random") - }; - - // Pass the template to ClockKit. - handler(tallBody); - } - else - { - handler(null); - } - } - - #endregion - } +namespace SimpleWatchConnectivity.WatchAppExtension { + using ClockKit; + using Foundation; + using System; + + /// <summary> + /// The complication controller class for the complication. + /// </summary> + public class ComplicationController : CLKComplicationDataSource { + #region Timeline Configuration. + + public override void GetSupportedTimeTravelDirections (CLKComplication complication, Action<CLKComplicationTimeTravelDirections> handler) + { + handler (CLKComplicationTimeTravelDirections.Forward | CLKComplicationTimeTravelDirections.Backward); + } + + public override void GetTimelineStartDate (CLKComplication complication, Action<NSDate> handler) + { + handler (null); + } + + public override void GetTimelineEndDate (CLKComplication complication, Action<NSDate> handler) + { + handler (null); + } + + public override void GetPrivacyBehavior (CLKComplication complication, Action<CLKComplicationPrivacyBehavior> handler) + { + handler (CLKComplicationPrivacyBehavior.ShowOnLockScreen); + } + + #endregion + + #region Timeline Population + + public override void GetCurrentTimelineEntry (CLKComplication complication, Action<CLKComplicationTimelineEntry> handler) + { + // Only support .modularLarge currently. + if (complication.Family == CLKComplicationFamily.ModularLarge) { + var random = new Random (); + + // Display a random number string on the body. + var tallBody = new CLKComplicationTemplateModularLargeTallBody { + HeaderTextProvider = CLKSimpleTextProvider.FromText ("SimpleWC"), + BodyTextProvider = CLKSimpleTextProvider.FromText ($"{random.Next (400)}") + }; + + // Pass the entry to ClockKit. + var entry = CLKComplicationTimelineEntry.Create (new NSDate (), tallBody); + handler (entry); + } else { + handler (null); + } + } + + public override void GetTimelineEntriesBeforeDate (CLKComplication complication, NSDate beforeDate, nuint limit, Action<CLKComplicationTimelineEntry []> handler) + { + // Call the handler with the timeline entries prior to the given date. + handler (null); + } + + public override void GetTimelineEntriesAfterDate (CLKComplication complication, NSDate afterDate, nuint limit, Action<CLKComplicationTimelineEntry []> handler) + { + // Call the handler with the timeline entries after to the given date. + handler (null); + } + + #endregion + + #region Placeholder Templates. + + public override void GetLocalizableSampleTemplate (CLKComplication complication, Action<CLKComplicationTemplate> handler) + { + // This method will be called once per supported complication, and the results will be cached. + handler (null); + } + + public override void GetPlaceholderTemplate (CLKComplication complication, Action<CLKComplicationTemplate> handler) + { + // Only support .modularLarge currently. + if (complication.Family == CLKComplicationFamily.ModularLarge) { + // Display a random number string on the body. + var tallBody = new CLKComplicationTemplateModularLargeTallBody { + HeaderTextProvider = CLKSimpleTextProvider.FromText ("SimpleWC"), + BodyTextProvider = CLKSimpleTextProvider.FromText ("Random") + }; + + // Pass the template to ClockKit. + handler (tallBody); + } else { + handler (null); + } + } + + #endregion + } } diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ExtensionDelegate.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ExtensionDelegate.cs index af020afb6..a47d1ad68 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ExtensionDelegate.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/ExtensionDelegate.cs @@ -1,111 +1,97 @@ - -namespace SimpleWatchConnectivity.WatchKitExtension -{ - using CoreFoundation; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using WatchConnectivity; - using WatchKit; - /// <summary> - /// The extension delegate of the WatchKit extension. - /// </summary> - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - private readonly SessionDelegater sessionDelegater = new SessionDelegater(); +namespace SimpleWatchConnectivity.WatchKitExtension { + using CoreFoundation; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using WatchConnectivity; + using WatchKit; - // An array to keep the background tasks. - private readonly List<WKWatchConnectivityRefreshBackgroundTask> wcBackgroundTasks = new List<WKWatchConnectivityRefreshBackgroundTask>(); + /// <summary> + /// The extension delegate of the WatchKit extension. + /// </summary> + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + private readonly SessionDelegater sessionDelegater = new SessionDelegater (); - // Hold the KVO observers as we want to keep oberving in the extension life time. - private readonly IDisposable activationStateObservation; - private readonly IDisposable hasContentPendingObservation; + // An array to keep the background tasks. + private readonly List<WKWatchConnectivityRefreshBackgroundTask> wcBackgroundTasks = new List<WKWatchConnectivityRefreshBackgroundTask> (); - public ExtensionDelegate() : base() - { - System.Diagnostics.Debug.Assert(WCSession.IsSupported, "This sample requires a platform supporting Watch Connectivity!"); - if (string.IsNullOrEmpty(WatchSettings.SharedContainerId)) - { - Console.WriteLine("Specify a shared container ID for WatchSettings.SharedContainerID to use watch settings!"); - } + // Hold the KVO observers as we want to keep oberving in the extension life time. + private readonly IDisposable activationStateObservation; + private readonly IDisposable hasContentPendingObservation; - // WKWatchConnectivityRefreshBackgroundTask should be completed – Otherwise they will keep consuming - // the background executing time and eventually causes an app crash. - // The timing to complete the tasks is when the current WCSession turns to not .activated or - // hasContentPending flipped to false (see completeBackgroundTasks), so KVO is set up here to observe - // the changes if the two properties. - this.activationStateObservation = WCSession.DefaultSession.AddObserver("activationState", NSKeyValueObservingOptions.New, (_) => - { - DispatchQueue.MainQueue.DispatchAsync(() => this.CompleteBackgroundTasks()); - }); + public ExtensionDelegate () : base () + { + System.Diagnostics.Debug.Assert (WCSession.IsSupported, "This sample requires a platform supporting Watch Connectivity!"); + if (string.IsNullOrEmpty (WatchSettings.SharedContainerId)) { + Console.WriteLine ("Specify a shared container ID for WatchSettings.SharedContainerID to use watch settings!"); + } - this.hasContentPendingObservation = WCSession.DefaultSession.AddObserver("hasContentPending", NSKeyValueObservingOptions.New, (_) => - { - DispatchQueue.MainQueue.DispatchAsync(() => this.CompleteBackgroundTasks()); - }); + // WKWatchConnectivityRefreshBackgroundTask should be completed – Otherwise they will keep consuming + // the background executing time and eventually causes an app crash. + // The timing to complete the tasks is when the current WCSession turns to not .activated or + // hasContentPending flipped to false (see completeBackgroundTasks), so KVO is set up here to observe + // the changes if the two properties. + this.activationStateObservation = WCSession.DefaultSession.AddObserver ("activationState", NSKeyValueObservingOptions.New, (_) => { + DispatchQueue.MainQueue.DispatchAsync (() => this.CompleteBackgroundTasks ()); + }); - // Activate the session asynchronously as early as possible. - // In the case of being background launched with a task, this may save some background runtime budget. - WCSession.DefaultSession.Delegate = this.sessionDelegater; - WCSession.DefaultSession.ActivateSession(); - } + this.hasContentPendingObservation = WCSession.DefaultSession.AddObserver ("hasContentPending", NSKeyValueObservingOptions.New, (_) => { + DispatchQueue.MainQueue.DispatchAsync (() => this.CompleteBackgroundTasks ()); + }); - /// <summary> - /// Compelete the background tasks, and schedule a snapshot refresh. - /// </summary> - private void CompleteBackgroundTasks() - { - if (this.wcBackgroundTasks.Any()) - { - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated && - !WCSession.DefaultSession.HasContentPending) - { - foreach (var item in this.wcBackgroundTasks) - { - item.SetTaskCompleted(false); - } + // Activate the session asynchronously as early as possible. + // In the case of being background launched with a task, this may save some background runtime budget. + WCSession.DefaultSession.Delegate = this.sessionDelegater; + WCSession.DefaultSession.ActivateSession (); + } - // Use Logger to log the tasks for debug purpose. A real app may remove the log - // to save the precious background time. - Logger.Shared.Append($"'CompleteBackgroundTasks':{wcBackgroundTasks} was completed!"); + /// <summary> + /// Compelete the background tasks, and schedule a snapshot refresh. + /// </summary> + private void CompleteBackgroundTasks () + { + if (this.wcBackgroundTasks.Any ()) { + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated && + !WCSession.DefaultSession.HasContentPending) { + foreach (var item in this.wcBackgroundTasks) { + item.SetTaskCompleted (false); + } - // Schedule a snapshot refresh if the UI is updated by background tasks. - var date = NSDate.FromTimeIntervalSinceNow(1d); - WKExtension.SharedExtension.ScheduleSnapshotRefresh(date, null, (error) => - { - if (error != null) - { - Console.WriteLine($"scheduleSnapshotRefresh error: {error}"); - } - }); + // Use Logger to log the tasks for debug purpose. A real app may remove the log + // to save the precious background time. + Logger.Shared.Append ($"'CompleteBackgroundTasks':{wcBackgroundTasks} was completed!"); - this.wcBackgroundTasks.Clear(); - } - } - } + // Schedule a snapshot refresh if the UI is updated by background tasks. + var date = NSDate.FromTimeIntervalSinceNow (1d); + WKExtension.SharedExtension.ScheduleSnapshotRefresh (date, null, (error) => { + if (error != null) { + Console.WriteLine ($"scheduleSnapshotRefresh error: {error}"); + } + }); - public override void HandleBackgroundTasks(NSSet<WKRefreshBackgroundTask> backgroundTasks) - { - foreach (WKRefreshBackgroundTask task in backgroundTasks) - { - // Use Logger to log the tasks for debug purpose. A real app may remove the log - // to save the precious background time. - if (task is WKWatchConnectivityRefreshBackgroundTask wcTask) - { - this.wcBackgroundTasks.Add(wcTask); - Logger.Shared.Append($"'HandleBackgroundTasks':{wcTask.Description} was appended!"); - } - else - { - task.SetTaskCompleted(false); - Logger.Shared.Append($"'HandleBackgroundTasks':{task.Description} was completed!"); - } - } + this.wcBackgroundTasks.Clear (); + } + } + } - this.CompleteBackgroundTasks(); - } - } -} \ No newline at end of file + public override void HandleBackgroundTasks (NSSet<WKRefreshBackgroundTask> backgroundTasks) + { + foreach (WKRefreshBackgroundTask task in backgroundTasks) { + // Use Logger to log the tasks for debug purpose. A real app may remove the log + // to save the precious background time. + if (task is WKWatchConnectivityRefreshBackgroundTask wcTask) { + this.wcBackgroundTasks.Add (wcTask); + Logger.Shared.Append ($"'HandleBackgroundTasks':{wcTask.Description} was appended!"); + } else { + task.SetTaskCompleted (false); + Logger.Shared.Append ($"'HandleBackgroundTasks':{task.Description} was completed!"); + } + } + + this.CompleteBackgroundTasks (); + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/FileTransfersController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/FileTransfersController.cs index f9e42c5b1..fa59d05dc 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/FileTransfersController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/FileTransfersController.cs @@ -1,58 +1,48 @@ -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using CoreFoundation; - using System; - using System.Collections.Generic; - using System.Linq; - using WatchConnectivity; - - public partial class FileTransfersController : UserInfoTransfersController - { - // Hold the file transfer observers to keep observing the progress. - private FileTransferObservers fileTransferObservers; - - public FileTransfersController(IntPtr handle) : base(handle) { } - - protected override string RowType { get; } = nameof(FileTransferRowController); - - /// <summary> - /// Rebuild the fileTransferObservers every time transfersStore is rebuilt. - /// </summary> - protected override List<SessionTransfer> Transfers - { - get - { - if (this.TransfersStore == null) - { - this.fileTransferObservers = new FileTransferObservers(); - - var fileTransfers = WCSession.DefaultSession.OutstandingFileTransfers; - this.TransfersStore = fileTransfers.Select(transfer => new SessionTransfer { SessionFileTransfer = transfer }).ToList(); - - // Observing handler can be called from background so dispatch - // the UI update code to main queue and use the table data at the moment. - foreach (var transfer in fileTransfers) - { - this.fileTransferObservers.Observe(transfer, (progress) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var index = this.Transfers.FindIndex(t => t.SessionFileTransfer?.Progress == progress); - if (index != -1) - { - if (this.Table.GetRowController(index) is FileTransferRowController row) - { - row.Progress = progress.LocalizedDescription; - } - } - }); - }); - } - } - - return this.TransfersStore; - } - } - } -} \ No newline at end of file +namespace SimpleWatchConnectivity.WatchAppExtension { + using CoreFoundation; + using System; + using System.Collections.Generic; + using System.Linq; + using WatchConnectivity; + + public partial class FileTransfersController : UserInfoTransfersController { + // Hold the file transfer observers to keep observing the progress. + private FileTransferObservers fileTransferObservers; + + public FileTransfersController (IntPtr handle) : base (handle) { } + + protected override string RowType { get; } = nameof (FileTransferRowController); + + /// <summary> + /// Rebuild the fileTransferObservers every time transfersStore is rebuilt. + /// </summary> + protected override List<SessionTransfer> Transfers { + get { + if (this.TransfersStore == null) { + this.fileTransferObservers = new FileTransferObservers (); + + var fileTransfers = WCSession.DefaultSession.OutstandingFileTransfers; + this.TransfersStore = fileTransfers.Select (transfer => new SessionTransfer { SessionFileTransfer = transfer }).ToList (); + + // Observing handler can be called from background so dispatch + // the UI update code to main queue and use the table data at the moment. + foreach (var transfer in fileTransfers) { + this.fileTransferObservers.Observe (transfer, (progress) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + var index = this.Transfers.FindIndex (t => t.SessionFileTransfer?.Progress == progress); + if (index != -1) { + if (this.Table.GetRowController (index) is FileTransferRowController row) { + row.Progress = progress.LocalizedDescription; + } + } + }); + }); + } + } + + return this.TransfersStore; + } + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/MainInterfaceController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/MainInterfaceController.cs index 445fc6977..162b87790 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/MainInterfaceController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/MainInterfaceController.cs @@ -1,302 +1,256 @@ -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - using WatchConnectivity; - using WatchKit; +namespace SimpleWatchConnectivity.WatchAppExtension { + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + using WatchConnectivity; + using WatchKit; - public partial class MainInterfaceController : WKInterfaceController - { - // Retain the controllers so that we don't have to reload root controllers for every switch. - private static readonly List<MainInterfaceController> Instances = new List<MainInterfaceController>(); + public partial class MainInterfaceController : WKInterfaceController { + // Retain the controllers so that we don't have to reload root controllers for every switch. + private static readonly List<MainInterfaceController> Instances = new List<MainInterfaceController> (); - private readonly FileTransferObservers fileTransferObservers = new FileTransferObservers(); + private readonly FileTransferObservers fileTransferObservers = new FileTransferObservers (); - private Command? command; + private Command? command; - public MainInterfaceController(IntPtr handle) : base(handle) { } + public MainInterfaceController (IntPtr handle) : base (handle) { } - public override void Awake(NSObject context) - { - base.Awake(context); + public override void Awake (NSObject context) + { + base.Awake (context); - if (context is CommandStatus commandStatus) - { - this.command = commandStatus.Command; - this.UpdateUI(commandStatus); - MainInterfaceController.Instances.Add(this); - } - else - { - this.StatusLabel.SetText("Activating..."); - this.ReloadRootController(); - } + if (context is CommandStatus commandStatus) { + this.command = commandStatus.Command; + this.UpdateUI (commandStatus); + MainInterfaceController.Instances.Add (this); + } else { + this.StatusLabel.SetText ("Activating..."); + this.ReloadRootController (); + } - // Install notification observer. - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.DataDidFlow, this.DataDidFlow); - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.ActivationDidComplete, this.ActivationDidComplete); - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.ReachabilityDidChange, this.ReachabilityDidChange); - } + // Install notification observer. + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.DataDidFlow, this.DataDidFlow); + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.ActivationDidComplete, this.ActivationDidComplete); + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.ReachabilityDidChange, this.ReachabilityDidChange); + } - ~MainInterfaceController() - { - NSNotificationCenter.DefaultCenter.RemoveObserver(this); - } + ~MainInterfaceController () + { + NSNotificationCenter.DefaultCenter.RemoveObserver (this); + } - public override void WillActivate() - { - base.WillActivate(); + public override void WillActivate () + { + base.WillActivate (); - if (this.command.HasValue) - { - // For .updateAppContext, retrieve the receieved app context if any and update the UI. - // For .transferFile and .transferUserInfo, log the outstanding transfers if any. - if (this.command == Command.UpdateAppContext) - { - var timedColor = WCSession.DefaultSession.ReceivedApplicationContext; - if (timedColor.Count > 0) - { - var commandStatus = new CommandStatus(this.command.Value, Phrase.Received) { TimedColor = new TimedColor(timedColor) }; - this.UpdateUI(commandStatus); - } - } - else if (this.command == Command.TransferFile) - { - var transferCount = WCSession.DefaultSession.OutstandingFileTransfers.Length; - if (transferCount > 0) - { - var commandStatus = new CommandStatus(Command.TransferFile, Phrase.Finished); - this.LogOutstandingTransfers(commandStatus, transferCount); - } - } - else if (this.command == Command.TransferUserInfo) - { - var transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers.Length; - if (transferCount > 0) - { - var commandStatus = new CommandStatus(Command.TransferUserInfo, Phrase.Finished); - this.LogOutstandingTransfers(commandStatus, transferCount); - } - } + if (this.command.HasValue) { + // For .updateAppContext, retrieve the receieved app context if any and update the UI. + // For .transferFile and .transferUserInfo, log the outstanding transfers if any. + if (this.command == Command.UpdateAppContext) { + var timedColor = WCSession.DefaultSession.ReceivedApplicationContext; + if (timedColor.Count > 0) { + var commandStatus = new CommandStatus (this.command.Value, Phrase.Received) { TimedColor = new TimedColor (timedColor) }; + this.UpdateUI (commandStatus); + } + } else if (this.command == Command.TransferFile) { + var transferCount = WCSession.DefaultSession.OutstandingFileTransfers.Length; + if (transferCount > 0) { + var commandStatus = new CommandStatus (Command.TransferFile, Phrase.Finished); + this.LogOutstandingTransfers (commandStatus, transferCount); + } + } else if (this.command == Command.TransferUserInfo) { + var transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers.Length; + if (transferCount > 0) { + var commandStatus = new CommandStatus (Command.TransferUserInfo, Phrase.Finished); + this.LogOutstandingTransfers (commandStatus, transferCount); + } + } - // Update the status group background color. - if (this.command != Command.TransferFile && this.command != Command.TransferUserInfo) - { - this.StatusGroup.SetBackgroundColor(UIColor.Black); - } - } - } + // Update the status group background color. + if (this.command != Command.TransferFile && this.command != Command.TransferUserInfo) { + this.StatusGroup.SetBackgroundColor (UIColor.Black); + } + } + } - /// <summary> - /// Load paged-based UI. If a current context is specified, use the timed color it provided. - /// </summary> - private void ReloadRootController(CommandStatus currentContext = null) - { - var commands = Enum.GetValues(typeof(Command)).Cast<Command>(); - var contexts = new List<CommandStatus>(); - foreach (var aCommand in commands) - { - var commandStatus = new CommandStatus(aCommand, Phrase.Finished); + /// <summary> + /// Load paged-based UI. If a current context is specified, use the timed color it provided. + /// </summary> + private void ReloadRootController (CommandStatus currentContext = null) + { + var commands = Enum.GetValues (typeof (Command)).Cast<Command> (); + var contexts = new List<CommandStatus> (); + foreach (var aCommand in commands) { + var commandStatus = new CommandStatus (aCommand, Phrase.Finished); - if (currentContext != null && aCommand == currentContext.Command) - { - commandStatus.Phrase = currentContext.Phrase; - commandStatus.TimedColor = currentContext.TimedColor; - } + if (currentContext != null && aCommand == currentContext.Command) { + commandStatus.Phrase = currentContext.Phrase; + commandStatus.TimedColor = currentContext.TimedColor; + } - contexts.Add(commandStatus); - } + contexts.Add (commandStatus); + } - var names = new string[contexts.Count]; - for (int i = 0; i < contexts.Count; i++) - { - names[i] = nameof(MainInterfaceController); - } + var names = new string [contexts.Count]; + for (int i = 0; i < contexts.Count; i++) { + names [i] = nameof (MainInterfaceController); + } - WKInterfaceController.ReloadRootPageControllers(names, contexts.ToArray(), WKPageOrientation.Horizontal, 0); - } + WKInterfaceController.ReloadRootPageControllers (names, contexts.ToArray (), WKPageOrientation.Horizontal, 0); + } - /// <summary> - /// Update the UI based on the command status. - /// </summary> - private void DataDidFlow(NSNotification notification) - { - if (notification.Object is CommandStatus commandStatus) - { - // If the data is from current channel, simple update color and time stamp, then return. - if (commandStatus.Command == command) - { - this.UpdateUI(commandStatus, commandStatus.ErrorMessage); - } - else - { - // Move the screen to the page matching the data channel, then update the color and time stamp. - var index = MainInterfaceController.Instances.FindIndex(instance => instance.command == commandStatus.Command); - if (index != -1) - { - var controller = MainInterfaceController.Instances[index]; - controller.BecomeCurrentPage(); - controller.UpdateUI(commandStatus, commandStatus.ErrorMessage); - } - } - } - } + /// <summary> + /// Update the UI based on the command status. + /// </summary> + private void DataDidFlow (NSNotification notification) + { + if (notification.Object is CommandStatus commandStatus) { + // If the data is from current channel, simple update color and time stamp, then return. + if (commandStatus.Command == command) { + this.UpdateUI (commandStatus, commandStatus.ErrorMessage); + } else { + // Move the screen to the page matching the data channel, then update the color and time stamp. + var index = MainInterfaceController.Instances.FindIndex (instance => instance.command == commandStatus.Command); + if (index != -1) { + var controller = MainInterfaceController.Instances [index]; + controller.BecomeCurrentPage (); + controller.UpdateUI (commandStatus, commandStatus.ErrorMessage); + } + } + } + } - private void ActivationDidComplete(NSNotification notification) - { - Console.WriteLine($"'ActivationDidComplete': activationState: {WCSession.DefaultSession.ActivationState}"); - } + private void ActivationDidComplete (NSNotification notification) + { + Console.WriteLine ($"'ActivationDidComplete': activationState: {WCSession.DefaultSession.ActivationState}"); + } - private void ReachabilityDidChange(NSNotification notification) - { - Console.WriteLine($"'ReachabilityDidChange': isReachable: {WCSession.DefaultSession.Reachable}"); - } + private void ReachabilityDidChange (NSNotification notification) + { + Console.WriteLine ($"'ReachabilityDidChange': isReachable: {WCSession.DefaultSession.Reachable}"); + } - /// <summary> - /// Do the command associated with the current page. - /// </summary> - partial void CommandAction() - { - if (this.command.HasValue) - { - switch (command.Value) - { - case Command.UpdateAppContext: - SessionCommands.UpdateAppContext(TestDataProvider.AppContext); - break; - case Command.SendMessage: - SessionCommands.SendMessage(TestDataProvider.Message); - break; - case Command.SendMessageData: - SessionCommands.SendMessageData(TestDataProvider.MessageData); - break; - case Command.TransferUserInfo: - SessionCommands.TransferUserInfo(TestDataProvider.UserInfo); - break; - case Command.TransferFile: - SessionCommands.TransferFile(TestDataProvider.File, TestDataProvider.FileMetaData); - break; - case Command.TransferCurrentComplicationUserInfo: - SessionCommands.TransferCurrentComplicationUserInfo(TestDataProvider.CurrentComplicationInfo); - break; - } - } - } + /// <summary> + /// Do the command associated with the current page. + /// </summary> + partial void CommandAction () + { + if (this.command.HasValue) { + switch (command.Value) { + case Command.UpdateAppContext: + SessionCommands.UpdateAppContext (TestDataProvider.AppContext); + break; + case Command.SendMessage: + SessionCommands.SendMessage (TestDataProvider.Message); + break; + case Command.SendMessageData: + SessionCommands.SendMessageData (TestDataProvider.MessageData); + break; + case Command.TransferUserInfo: + SessionCommands.TransferUserInfo (TestDataProvider.UserInfo); + break; + case Command.TransferFile: + SessionCommands.TransferFile (TestDataProvider.File, TestDataProvider.FileMetaData); + break; + case Command.TransferCurrentComplicationUserInfo: + SessionCommands.TransferCurrentComplicationUserInfo (TestDataProvider.CurrentComplicationInfo); + break; + } + } + } - /// <summary> - /// Show outstanding transfer UI for .transferFile and .transferUserInfo. - /// </summary> - partial void StatusAction() - { - if (this.command == Command.TransferFile) - { - this.PresentController(nameof(FileTransfersController), this.command.Value.ToString()); - } - else if (this.command == Command.TransferUserInfo) - { - this.PresentController(nameof(UserInfoTransfersController), this.command.Value.ToString()); - } - } + /// <summary> + /// Show outstanding transfer UI for .transferFile and .transferUserInfo. + /// </summary> + partial void StatusAction () + { + if (this.command == Command.TransferFile) { + this.PresentController (nameof (FileTransfersController), this.command.Value.ToString ()); + } else if (this.command == Command.TransferUserInfo) { + this.PresentController (nameof (UserInfoTransfersController), this.command.Value.ToString ()); + } + } - #region Update status view. + #region Update status view. - // Update the user interface with the command status. - // Note that there isn't a timed color when the interface controller is initially loaded. - private void UpdateUI(CommandStatus commandStatus, string errorMessage = null) - { - var timedColor = commandStatus.TimedColor; - if (timedColor == null) - { - this.StatusLabel.SetText(string.Empty); - this.CommandButton.SetTitle(commandStatus.Command.ToString()); - } - else - { - var title = new NSAttributedString(commandStatus.Command.ToString(), new UIStringAttributes { ForegroundColor = timedColor.Color }); - this.CommandButton.SetTitle(title); - this.StatusLabel.SetTextColor(timedColor.Color); + // Update the user interface with the command status. + // Note that there isn't a timed color when the interface controller is initially loaded. + private void UpdateUI (CommandStatus commandStatus, string errorMessage = null) + { + var timedColor = commandStatus.TimedColor; + if (timedColor == null) { + this.StatusLabel.SetText (string.Empty); + this.CommandButton.SetTitle (commandStatus.Command.ToString ()); + } else { + var title = new NSAttributedString (commandStatus.Command.ToString (), new UIStringAttributes { ForegroundColor = timedColor.Color }); + this.CommandButton.SetTitle (title); + this.StatusLabel.SetTextColor (timedColor.Color); - // If there is an error, show the message and return. - if (!string.IsNullOrEmpty(errorMessage)) - { - this.StatusLabel.SetText($"{errorMessage}"); - } - else - { - // Observe the file transfer if it's phrase is "transferring". - // Unobserve a file transfer if it's phrase is "finished". - if (commandStatus.FileTransfer != null && commandStatus.Command == Command.TransferFile) - { - if (commandStatus.Phrase == Phrase.Finished) - { - this.fileTransferObservers.Unobserve(commandStatus.FileTransfer); - } - else if (commandStatus.Phrase == Phrase.Transferring) - { - this.fileTransferObservers.Observe(commandStatus.FileTransfer, (_) => this.LogProgress(commandStatus)); - } - } + // If there is an error, show the message and return. + if (!string.IsNullOrEmpty (errorMessage)) { + this.StatusLabel.SetText ($"{errorMessage}"); + } else { + // Observe the file transfer if it's phrase is "transferring". + // Unobserve a file transfer if it's phrase is "finished". + if (commandStatus.FileTransfer != null && commandStatus.Command == Command.TransferFile) { + if (commandStatus.Phrase == Phrase.Finished) { + this.fileTransferObservers.Unobserve (commandStatus.FileTransfer); + } else if (commandStatus.Phrase == Phrase.Transferring) { + this.fileTransferObservers.Observe (commandStatus.FileTransfer, (_) => this.LogProgress (commandStatus)); + } + } - // Log the outstanding file transfers if any. - if (commandStatus.Command == Command.TransferFile) - { - var transferCount = WCSession.DefaultSession.OutstandingFileTransfers.Length; - if (transferCount > 0) - { - this.LogOutstandingTransfers(commandStatus, transferCount); - return; - } - } - // Log the outstanding UserInfo transfers if any. - else if (commandStatus.Command == Command.TransferUserInfo) - { - var transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers.Length; - if (transferCount > 0) - { - this.LogOutstandingTransfers(commandStatus, transferCount); - return; - } - } + // Log the outstanding file transfers if any. + if (commandStatus.Command == Command.TransferFile) { + var transferCount = WCSession.DefaultSession.OutstandingFileTransfers.Length; + if (transferCount > 0) { + this.LogOutstandingTransfers (commandStatus, transferCount); + return; + } + } + // Log the outstanding UserInfo transfers if any. + else if (commandStatus.Command == Command.TransferUserInfo) { + var transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers.Length; + if (transferCount > 0) { + this.LogOutstandingTransfers (commandStatus, transferCount); + return; + } + } - this.StatusLabel.SetText($"{commandStatus.Phrase.ToString()} at\n{timedColor.TimeStamp}"); - } - } - } + this.StatusLabel.SetText ($"{commandStatus.Phrase.ToString ()} at\n{timedColor.TimeStamp}"); + } + } + } - /// <summary> - /// Log the outstanding transfer information if any. - /// </summary> - private void LogOutstandingTransfers(CommandStatus commandStatus, int outstandingCount) - { - if (commandStatus.Phrase == Phrase.Transferring) - { - var text = $"{commandStatus.Phrase.ToString()} at\n{commandStatus.TimedColor.TimeStamp}\nOutstanding: {outstandingCount}\n Tap to view"; - this.StatusLabel.SetText(text); - } - else if (commandStatus.Phrase == Phrase.Finished) - { - this.StatusLabel.SetText($"Outstanding: {outstandingCount}\n Tap to view"); - } - } + /// <summary> + /// Log the outstanding transfer information if any. + /// </summary> + private void LogOutstandingTransfers (CommandStatus commandStatus, int outstandingCount) + { + if (commandStatus.Phrase == Phrase.Transferring) { + var text = $"{commandStatus.Phrase.ToString ()} at\n{commandStatus.TimedColor.TimeStamp}\nOutstanding: {outstandingCount}\n Tap to view"; + this.StatusLabel.SetText (text); + } else if (commandStatus.Phrase == Phrase.Finished) { + this.StatusLabel.SetText ($"Outstanding: {outstandingCount}\n Tap to view"); + } + } - /// <summary> - /// Log the file transfer progress. The command status is captured at the momment when the file transfer is observed. - /// </summary> - /// <param name="commandStatus">Command status.</param> - private void LogProgress(CommandStatus commandStatus) - { - if (commandStatus.FileTransfer != null) - { - var fileName = commandStatus.FileTransfer.File.FileUrl.LastPathComponent; - var progress = commandStatus.FileTransfer.Progress.LocalizedDescription ?? "No progress"; - this.StatusLabel.SetText($"{commandStatus.Phrase.ToString()}\n{fileName}\n{progress}"); - } - } + /// <summary> + /// Log the file transfer progress. The command status is captured at the momment when the file transfer is observed. + /// </summary> + /// <param name="commandStatus">Command status.</param> + private void LogProgress (CommandStatus commandStatus) + { + if (commandStatus.FileTransfer != null) { + var fileName = commandStatus.FileTransfer.File.FileUrl.LastPathComponent; + var progress = commandStatus.FileTransfer.Progress.LocalizedDescription ?? "No progress"; + this.StatusLabel.SetText ($"{commandStatus.Phrase.ToString ()}\n{fileName}\n{progress}"); + } + } - #endregion - } -} \ No newline at end of file + #endregion + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/DoneRowController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/DoneRowController.cs index 2c05e6479..3c56d45a5 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/DoneRowController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/DoneRowController.cs @@ -1,11 +1,9 @@ -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using Foundation; - using System; +namespace SimpleWatchConnectivity.WatchAppExtension { + using Foundation; + using System; - public partial class DoneRowController : NSObject - { - public DoneRowController (IntPtr handle) : base (handle) { } - } -} \ No newline at end of file + public partial class DoneRowController : NSObject { + public DoneRowController (IntPtr handle) : base (handle) { } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/FileTransferRowController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/FileTransferRowController.cs index 43488483b..87e350d00 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/FileTransferRowController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/FileTransferRowController.cs @@ -1,36 +1,31 @@ -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using System; +namespace SimpleWatchConnectivity.WatchAppExtension { + using System; - public partial class FileTransferRowController : UserInfoTransferRowController - { - private string progress; + public partial class FileTransferRowController : UserInfoTransferRowController { + private string progress; - public FileTransferRowController(IntPtr handle) : base(handle) { } + public FileTransferRowController (IntPtr handle) : base (handle) { } - public string Progress - { - get - { - return this.progress; - } - set - { - this.progress = value; - this.ProgressLabel.SetText(this.progress); - } - } + public string Progress { + get { + return this.progress; + } + set { + this.progress = value; + this.ProgressLabel.SetText (this.progress); + } + } - /// <summary> - /// Update the table cell with the transfer's timed color. - /// </summary> - public override void Update(SessionTransfer transfer) - { - this.TitleLabel.SetText(transfer.TimedColor.TimeStamp); - this.TitleLabel.SetTextColor(transfer.TimedColor.Color); - this.ProgressLabel.SetText("%0 completed"); - this.ProgressLabel.SetTextColor(transfer.TimedColor.Color); - } - } -} \ No newline at end of file + /// <summary> + /// Update the table cell with the transfer's timed color. + /// </summary> + public override void Update (SessionTransfer transfer) + { + this.TitleLabel.SetText (transfer.TimedColor.TimeStamp); + this.TitleLabel.SetTextColor (transfer.TimedColor.Color); + this.ProgressLabel.SetText ("%0 completed"); + this.ProgressLabel.SetTextColor (transfer.TimedColor.Color); + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/UserInfoTransferRowController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/UserInfoTransferRowController.cs index 27d3e1e1d..90904c11e 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/UserInfoTransferRowController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/Rows/UserInfoTransferRowController.cs @@ -1,23 +1,21 @@ -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using Foundation; - using System; +namespace SimpleWatchConnectivity.WatchAppExtension { + using Foundation; + using System; - public partial class UserInfoTransferRowController : NSObject - { - public UserInfoTransferRowController(IntPtr handle) : base(handle) { } + public partial class UserInfoTransferRowController : NSObject { + public UserInfoTransferRowController (IntPtr handle) : base (handle) { } - [Outlet] - protected WatchKit.WKInterfaceLabel TitleLabel { get; set; } + [Outlet] + protected WatchKit.WKInterfaceLabel TitleLabel { get; set; } - /// <summary> - /// Update the table cell with the transfer's timed color. - /// </summary> - public virtual void Update(SessionTransfer transfer) - { - this.TitleLabel.SetText(transfer.TimedColor.TimeStamp); - this.TitleLabel.SetTextColor(transfer.TimedColor.Color); - } - } -} \ No newline at end of file + /// <summary> + /// Update the table cell with the transfer's timed color. + /// </summary> + public virtual void Update (SessionTransfer transfer) + { + this.TitleLabel.SetText (transfer.TimedColor.TimeStamp); + this.TitleLabel.SetTextColor (transfer.TimedColor.Color); + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/UserInfoTransfersController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/UserInfoTransfersController.cs index 598226ad1..5339536d7 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/UserInfoTransfersController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity.WatchAppExtension/UserInfoTransfersController.cs @@ -1,124 +1,106 @@ -namespace SimpleWatchConnectivity.WatchAppExtension -{ - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using WatchConnectivity; - using WatchKit; - - public partial class UserInfoTransfersController : WKInterfaceController - { - private Command command; - - public UserInfoTransfersController(IntPtr handle) : base(handle) { } - - protected virtual string RowType { get; } = nameof(UserInfoTransfersController); - - // Outstnding transfers can change in the background so make a copy (cache) to - // make sure the data doesn't change during the table loading cycle. - // Subclasses can override the computed property to provide the right transfers. - protected List<SessionTransfer> TransfersStore { get; set; } - - [Outlet] - protected WKInterfaceTable Table { get; set; } - - protected virtual List<SessionTransfer> Transfers - { - get - { - if (this.TransfersStore == null) - { - this.TransfersStore = WCSession.DefaultSession.OutstandingUserInfoTransfers - .Select(transfer => new SessionTransfer { SessionUserInfoTransfer = transfer }) - .ToList(); - } - - return this.TransfersStore; - } - } - - /// <summary> - /// Load the table.Show the "Done" row if there isn't any outstanding transfers. - /// </summary> - protected void LoadTable() - { - if (this.Transfers.Any()) - { - this.Table.SetNumberOfRows(this.Transfers.Count, this.RowType); - - for (var index = 0; index < this.Transfers.Count; index++) - { - var transfer = this.Transfers[index]; - if (this.Table.GetRowController(index) is UserInfoTransferRowController row) - { - row.Update(transfer); - } - } - } - else - { - this.Table.SetNumberOfRows(1, nameof(DoneRowController)); - } - } - - public override void Awake(NSObject context) - { - base.Awake(context); - - if (context != null && Enum.TryParse(context.ToString(), out Command acommand)) - { - this.command = acommand; - this.LoadTable(); - } - else - { - throw new Exception("Invalid context for presenting this controller!"); - } - } - - public override void WillActivate() - { - base.WillActivate(); - NSNotificationCenter.DefaultCenter.AddObserver(new NSString(NotificationName.DataDidFlow), this.DataDidFlow); - } - - public override void DidDeactivate() - { - base.DidDeactivate(); - NSNotificationCenter.DefaultCenter.RemoveObserver(this); - } - - /// <summary> - /// Cancel the transfer when the table row is selected. - /// </summary> - public override void DidSelectRow(WKInterfaceTable table, nint rowIndex) - { - if (rowIndex >= this.Transfers.Count) - { - Console.WriteLine($"Selected row has been removed! Current transfers: {Transfers}"); - } - else - { - var transfer = this.Transfers[(int)rowIndex]; - transfer.Cancel(this.command); - } - } - - /// <summary> - /// Update the UI the notification object. - /// </summary> - private void DataDidFlow(NSNotification notification) - { - if (notification.Object is CommandStatus commandStatus) - { - if (commandStatus.Command == this.command && commandStatus.Phrase != Phrase.Failed) - { - this.TransfersStore = null; - this.LoadTable(); - } - } - } - } -} \ No newline at end of file +namespace SimpleWatchConnectivity.WatchAppExtension { + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using WatchConnectivity; + using WatchKit; + + public partial class UserInfoTransfersController : WKInterfaceController { + private Command command; + + public UserInfoTransfersController (IntPtr handle) : base (handle) { } + + protected virtual string RowType { get; } = nameof (UserInfoTransfersController); + + // Outstnding transfers can change in the background so make a copy (cache) to + // make sure the data doesn't change during the table loading cycle. + // Subclasses can override the computed property to provide the right transfers. + protected List<SessionTransfer> TransfersStore { get; set; } + + [Outlet] + protected WKInterfaceTable Table { get; set; } + + protected virtual List<SessionTransfer> Transfers { + get { + if (this.TransfersStore == null) { + this.TransfersStore = WCSession.DefaultSession.OutstandingUserInfoTransfers + .Select (transfer => new SessionTransfer { SessionUserInfoTransfer = transfer }) + .ToList (); + } + + return this.TransfersStore; + } + } + + /// <summary> + /// Load the table.Show the "Done" row if there isn't any outstanding transfers. + /// </summary> + protected void LoadTable () + { + if (this.Transfers.Any ()) { + this.Table.SetNumberOfRows (this.Transfers.Count, this.RowType); + + for (var index = 0; index < this.Transfers.Count; index++) { + var transfer = this.Transfers [index]; + if (this.Table.GetRowController (index) is UserInfoTransferRowController row) { + row.Update (transfer); + } + } + } else { + this.Table.SetNumberOfRows (1, nameof (DoneRowController)); + } + } + + public override void Awake (NSObject context) + { + base.Awake (context); + + if (context != null && Enum.TryParse (context.ToString (), out Command acommand)) { + this.command = acommand; + this.LoadTable (); + } else { + throw new Exception ("Invalid context for presenting this controller!"); + } + } + + public override void WillActivate () + { + base.WillActivate (); + NSNotificationCenter.DefaultCenter.AddObserver (new NSString (NotificationName.DataDidFlow), this.DataDidFlow); + } + + public override void DidDeactivate () + { + base.DidDeactivate (); + NSNotificationCenter.DefaultCenter.RemoveObserver (this); + } + + /// <summary> + /// Cancel the transfer when the table row is selected. + /// </summary> + public override void DidSelectRow (WKInterfaceTable table, nint rowIndex) + { + if (rowIndex >= this.Transfers.Count) { + Console.WriteLine ($"Selected row has been removed! Current transfers: {Transfers}"); + } else { + var transfer = this.Transfers [(int) rowIndex]; + transfer.Cancel (this.command); + } + } + + /// <summary> + /// Update the UI the notification object. + /// </summary> + private void DataDidFlow (NSNotification notification) + { + if (notification.Object is CommandStatus commandStatus) { + if (commandStatus.Command == this.command && commandStatus.Phrase != Phrase.Failed) { + this.TransfersStore = null; + this.LoadTable (); + } + } + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/AppDelegate.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/AppDelegate.cs index 9b5afa2e8..57ce58c42 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/AppDelegate.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/AppDelegate.cs @@ -1,32 +1,29 @@ - -namespace SimpleWatchConnectivity -{ - using Foundation; - using System; - using UIKit; - using WatchConnectivity; - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - private readonly SessionDelegater sessionDelegater = new SessionDelegater(); +namespace SimpleWatchConnectivity { + using Foundation; + using System; + using UIKit; + using WatchConnectivity; - public override UIWindow Window { get; set; } + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + private readonly SessionDelegater sessionDelegater = new SessionDelegater (); - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - // Trigger WCSession activation at the early phase of app launching. - System.Diagnostics.Debug.Assert(WCSession.IsSupported, "This sample requires Watch Connectivity support!"); - WCSession.DefaultSession.Delegate = this.sessionDelegater; - WCSession.DefaultSession.ActivateSession(); + public override UIWindow Window { get; set; } - // Remind the setup of WatchSettings.sharedContainerID. - if (string.IsNullOrEmpty(WatchSettings.SharedContainerId)) - { - Console.WriteLine("Specify a shared container ID for WatchSettings.sharedContainerID to use watch settings!"); - } + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + // Trigger WCSession activation at the early phase of app launching. + System.Diagnostics.Debug.Assert (WCSession.IsSupported, "This sample requires Watch Connectivity support!"); + WCSession.DefaultSession.Delegate = this.sessionDelegater; + WCSession.DefaultSession.ActivateSession (); - return true; - } - } -} \ No newline at end of file + // Remind the setup of WatchSettings.sharedContainerID. + if (string.IsNullOrEmpty (WatchSettings.SharedContainerId)) { + Console.WriteLine ("Specify a shared container ID for WatchSettings.sharedContainerID to use watch settings!"); + } + + return true; + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/CommandsViewController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/CommandsViewController.cs index 2c89fb3df..1e9e9136d 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/CommandsViewController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/CommandsViewController.cs @@ -1,188 +1,168 @@ -namespace SimpleWatchConnectivity -{ - using CoreFoundation; - using CoreGraphics; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - using WatchConnectivity; - - public partial class CommandsViewController : UITableViewController - { - // List the supported methods, shown in the main table. - private readonly List<Command> commands; - - private Command currentCommand = Command.UpdateAppContext; // Default to .updateAppContext. - - private UIColor currentColor; - - public CommandsViewController(IntPtr handle) : base(handle) - { - this.commands = Enum.GetValues(typeof(Command)).Cast<Command>().ToList(); - } - - ~CommandsViewController() - { - NSNotificationCenter.DefaultCenter.RemoveObserver(this); - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.TableView.RowHeight = 42f; - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.DataDidFlow, this.DataDidFlow); - } - - private void DataDidFlow(NSNotification notification) - { - if (notification.Object is CommandStatus commandStatus) - { - this.currentCommand = commandStatus.Command; - this.currentColor = commandStatus.TimedColor?.Color; - this.TableView.ReloadData(); - } - } - - #region UITableViewDelegate and UITableViewDataSoruce. - - /// <summary> - /// Create a button for the specified command and with the title color. - /// The button is used as the accessory view of the table cell. - /// </summary> - private UIButton NewAccessoryView(Command cellCommand, UIColor titleColor) - { - var transferCount = 0; - - // Retrieve the transfer count for the command. - if (cellCommand == Command.TransferFile) - { - transferCount = WCSession.DefaultSession.OutstandingFileTransfers?.Length ?? 0; - } - else if (cellCommand == Command.TransferUserInfo) - { - transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers?.Count(transfer => !transfer.CurrentComplicationInfo) ?? 0; - } - else if (cellCommand == Command.TransferCurrentComplicationUserInfo) - { - transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers?.Count(transfer => transfer.CurrentComplicationInfo) ?? 0; - } - - // Create and configure the button. - var button = new UIButton(UIButtonType.RoundedRect); - button.AddTarget((sender, args) => this.ShowTransfers(sender as UIButton), UIControlEvent.TouchUpInside); - button.SetTitleColor(titleColor, UIControlState.Normal); - button.SetTitle($" {transferCount} ", UIControlState.Normal); - button.SizeToFit(); - return button; - } - - /// <summary> - /// Action handler of the accessory view. Present the view controller for the current command. - /// </summary> - private void ShowTransfers(UIButton sender) - { - var buttonPosition = sender.ConvertPointToView(CGPoint.Empty, this.TableView); - var indexPath = this.TableView.IndexPathForRowAtPoint(buttonPosition); - if (indexPath != null) - { - var storyboard = UIStoryboard.FromName("Main", null); - var command = this.commands[indexPath.Row]; - - UIViewController childViewController; - - if (command == Command.TransferFile) - { - var viewController = storyboard.InstantiateViewController("FileTransfersViewController"); - if (viewController is FileTransfersViewController transfersViewController) - { - transfersViewController.Command = command; - childViewController = transfersViewController; - } - else - { - throw new Exception("View controller (FileTransfersViewController) deson't have a right class!"); - } - } - else - { - var viewController = storyboard.InstantiateViewController("UserInfoTransfersViewController"); - if (viewController is UserInfoTransfersViewController transfersViewController) - { - transfersViewController.Command = command; - childViewController = transfersViewController; - } - else - { - throw new Exception("View controller (UserInfoTransfersViewController) deson't have a right class!"); - } - } - - this.AddChildViewController(childViewController); - childViewController.View.Frame = this.View.ConvertRectToView(this.TableView.Bounds, this.TableView); - this.View.AddSubview(childViewController.View); - childViewController.DidMoveToParentViewController(this); - } - } - - public override nint RowsInSection(UITableView tableView, nint section) - { - return this.commands.Count; - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("CommandCell", indexPath); - - var cellCommand = this.commands[indexPath.Row]; - cell.TextLabel.Text = cellCommand.ToString(); - - UIColor textColor = cellCommand == currentCommand ? this.currentColor : null; - cell.TextLabel.TextColor = textColor; - cell.DetailTextLabel.TextColor = textColor; - - cell.DetailTextLabel.Text = string.Empty; - cell.AccessoryView = null; - - if (cellCommand == Command.TransferFile || - cellCommand == Command.TransferUserInfo || - cellCommand == Command.TransferCurrentComplicationUserInfo) - { - cell.AccessoryView = this.NewAccessoryView(cellCommand, textColor); - } - - return cell; - } - - public override void RowSelected(UITableView tableView, NSIndexPath indexPath) - { - this.currentCommand = this.commands[indexPath.Row]; - switch (this.currentCommand) - { - case Command.UpdateAppContext: - SessionCommands.UpdateAppContext(TestDataProvider.AppContext); - break; - case Command.SendMessage: - SessionCommands.SendMessage(TestDataProvider.Message); - break; - case Command.SendMessageData: - SessionCommands.SendMessageData(TestDataProvider.MessageData); - break; - case Command.TransferUserInfo: - SessionCommands.TransferUserInfo(TestDataProvider.UserInfo); - break; - case Command.TransferFile: - SessionCommands.TransferFile(TestDataProvider.File, TestDataProvider.FileMetaData); - break; - case Command.TransferCurrentComplicationUserInfo: - SessionCommands.TransferCurrentComplicationUserInfo(TestDataProvider.CurrentComplicationInfo); - break; - } - } - - #endregion - } -} \ No newline at end of file +namespace SimpleWatchConnectivity { + using CoreFoundation; + using CoreGraphics; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + using WatchConnectivity; + + public partial class CommandsViewController : UITableViewController { + // List the supported methods, shown in the main table. + private readonly List<Command> commands; + + private Command currentCommand = Command.UpdateAppContext; // Default to .updateAppContext. + + private UIColor currentColor; + + public CommandsViewController (IntPtr handle) : base (handle) + { + this.commands = Enum.GetValues (typeof (Command)).Cast<Command> ().ToList (); + } + + ~CommandsViewController () + { + NSNotificationCenter.DefaultCenter.RemoveObserver (this); + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.TableView.RowHeight = 42f; + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.DataDidFlow, this.DataDidFlow); + } + + private void DataDidFlow (NSNotification notification) + { + if (notification.Object is CommandStatus commandStatus) { + this.currentCommand = commandStatus.Command; + this.currentColor = commandStatus.TimedColor?.Color; + this.TableView.ReloadData (); + } + } + + #region UITableViewDelegate and UITableViewDataSoruce. + + /// <summary> + /// Create a button for the specified command and with the title color. + /// The button is used as the accessory view of the table cell. + /// </summary> + private UIButton NewAccessoryView (Command cellCommand, UIColor titleColor) + { + var transferCount = 0; + + // Retrieve the transfer count for the command. + if (cellCommand == Command.TransferFile) { + transferCount = WCSession.DefaultSession.OutstandingFileTransfers?.Length ?? 0; + } else if (cellCommand == Command.TransferUserInfo) { + transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers?.Count (transfer => !transfer.CurrentComplicationInfo) ?? 0; + } else if (cellCommand == Command.TransferCurrentComplicationUserInfo) { + transferCount = WCSession.DefaultSession.OutstandingUserInfoTransfers?.Count (transfer => transfer.CurrentComplicationInfo) ?? 0; + } + + // Create and configure the button. + var button = new UIButton (UIButtonType.RoundedRect); + button.AddTarget ((sender, args) => this.ShowTransfers (sender as UIButton), UIControlEvent.TouchUpInside); + button.SetTitleColor (titleColor, UIControlState.Normal); + button.SetTitle ($" {transferCount} ", UIControlState.Normal); + button.SizeToFit (); + return button; + } + + /// <summary> + /// Action handler of the accessory view. Present the view controller for the current command. + /// </summary> + private void ShowTransfers (UIButton sender) + { + var buttonPosition = sender.ConvertPointToView (CGPoint.Empty, this.TableView); + var indexPath = this.TableView.IndexPathForRowAtPoint (buttonPosition); + if (indexPath != null) { + var storyboard = UIStoryboard.FromName ("Main", null); + var command = this.commands [indexPath.Row]; + + UIViewController childViewController; + + if (command == Command.TransferFile) { + var viewController = storyboard.InstantiateViewController ("FileTransfersViewController"); + if (viewController is FileTransfersViewController transfersViewController) { + transfersViewController.Command = command; + childViewController = transfersViewController; + } else { + throw new Exception ("View controller (FileTransfersViewController) deson't have a right class!"); + } + } else { + var viewController = storyboard.InstantiateViewController ("UserInfoTransfersViewController"); + if (viewController is UserInfoTransfersViewController transfersViewController) { + transfersViewController.Command = command; + childViewController = transfersViewController; + } else { + throw new Exception ("View controller (UserInfoTransfersViewController) deson't have a right class!"); + } + } + + this.AddChildViewController (childViewController); + childViewController.View.Frame = this.View.ConvertRectToView (this.TableView.Bounds, this.TableView); + this.View.AddSubview (childViewController.View); + childViewController.DidMoveToParentViewController (this); + } + } + + public override nint RowsInSection (UITableView tableView, nint section) + { + return this.commands.Count; + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("CommandCell", indexPath); + + var cellCommand = this.commands [indexPath.Row]; + cell.TextLabel.Text = cellCommand.ToString (); + + UIColor textColor = cellCommand == currentCommand ? this.currentColor : null; + cell.TextLabel.TextColor = textColor; + cell.DetailTextLabel.TextColor = textColor; + + cell.DetailTextLabel.Text = string.Empty; + cell.AccessoryView = null; + + if (cellCommand == Command.TransferFile || + cellCommand == Command.TransferUserInfo || + cellCommand == Command.TransferCurrentComplicationUserInfo) { + cell.AccessoryView = this.NewAccessoryView (cellCommand, textColor); + } + + return cell; + } + + public override void RowSelected (UITableView tableView, NSIndexPath indexPath) + { + this.currentCommand = this.commands [indexPath.Row]; + switch (this.currentCommand) { + case Command.UpdateAppContext: + SessionCommands.UpdateAppContext (TestDataProvider.AppContext); + break; + case Command.SendMessage: + SessionCommands.SendMessage (TestDataProvider.Message); + break; + case Command.SendMessageData: + SessionCommands.SendMessageData (TestDataProvider.MessageData); + break; + case Command.TransferUserInfo: + SessionCommands.TransferUserInfo (TestDataProvider.UserInfo); + break; + case Command.TransferFile: + SessionCommands.TransferFile (TestDataProvider.File, TestDataProvider.FileMetaData); + break; + case Command.TransferCurrentComplicationUserInfo: + SessionCommands.TransferCurrentComplicationUserInfo (TestDataProvider.CurrentComplicationInfo); + break; + } + } + + #endregion + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/FileTransfersViewController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/FileTransfersViewController.cs index 6f86d7b95..9d7e7fb4a 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/FileTransfersViewController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/FileTransfersViewController.cs @@ -1,73 +1,62 @@ -namespace SimpleWatchConnectivity -{ - using CoreFoundation; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - using WatchConnectivity; - - /// <summary> - /// FileTransfersViewController manages the file transfer of the iOS app. - /// </summary> - public partial class FileTransfersViewController : UserInfoTransfersViewController - { - // Hold the file transfer observers to keep observing the progress. - private FileTransferObservers fileTransferObservers; - - public FileTransfersViewController(IntPtr handle) : base(handle) { } - - protected override List<SessionTransfer> Transfers - { - get - { - if (this.TransfersStore == null) - { - this.fileTransferObservers = new FileTransferObservers(); - - var fileTransfers = WCSession.DefaultSession.OutstandingFileTransfers; - this.TransfersStore = fileTransfers.Select(transfer => new SessionTransfer { SessionFileTransfer = transfer }).ToList(); - - // Observing handler can be called from background so dispatch - // the UI update code to main queue and use the table data at the moment. - foreach (var transfer in fileTransfers) - { - this.fileTransferObservers.Observe(transfer, (progress) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var index = this.Transfers.FindIndex(t => t.SessionFileTransfer?.Progress == progress); - if (index != -1) - { - var indexPath = NSIndexPath.FromRowSection(index, 0); - var cell = this.TableView.CellAt(indexPath); - if (cell != null) - { - cell.DetailTextLabel.Text = progress.LocalizedDescription; - } - } - }); - }); - } - } - - return this.TransfersStore; - } - } - - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = base.GetCell(tableView, indexPath); - - var transfer = this.Transfers[indexPath.Row]?.SessionFileTransfer; - if (transfer != null) - { - cell.DetailTextLabel.Text = transfer.Progress.LocalizedDescription; - } - - return cell; - } - } -} \ No newline at end of file +namespace SimpleWatchConnectivity { + using CoreFoundation; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + using WatchConnectivity; + + /// <summary> + /// FileTransfersViewController manages the file transfer of the iOS app. + /// </summary> + public partial class FileTransfersViewController : UserInfoTransfersViewController { + // Hold the file transfer observers to keep observing the progress. + private FileTransferObservers fileTransferObservers; + + public FileTransfersViewController (IntPtr handle) : base (handle) { } + + protected override List<SessionTransfer> Transfers { + get { + if (this.TransfersStore == null) { + this.fileTransferObservers = new FileTransferObservers (); + + var fileTransfers = WCSession.DefaultSession.OutstandingFileTransfers; + this.TransfersStore = fileTransfers.Select (transfer => new SessionTransfer { SessionFileTransfer = transfer }).ToList (); + + // Observing handler can be called from background so dispatch + // the UI update code to main queue and use the table data at the moment. + foreach (var transfer in fileTransfers) { + this.fileTransferObservers.Observe (transfer, (progress) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + var index = this.Transfers.FindIndex (t => t.SessionFileTransfer?.Progress == progress); + if (index != -1) { + var indexPath = NSIndexPath.FromRowSection (index, 0); + var cell = this.TableView.CellAt (indexPath); + if (cell != null) { + cell.DetailTextLabel.Text = progress.LocalizedDescription; + } + } + }); + }); + } + } + + return this.TransfersStore; + } + } + + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = base.GetCell (tableView, indexPath); + + var transfer = this.Transfers [indexPath.Row]?.SessionFileTransfer; + if (transfer != null) { + cell.DetailTextLabel.Text = transfer.Progress.LocalizedDescription; + } + + return cell; + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/Main.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/Main.cs index 9dcf8fec9..68c100b46 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/Main.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/Main.cs @@ -1,16 +1,14 @@ - -namespace SimpleWatchConnectivity -{ - using UIKit; - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file +namespace SimpleWatchConnectivity { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/MainViewController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/MainViewController.cs index 0c088e703..9a0337ee5 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/MainViewController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/MainViewController.cs @@ -1,170 +1,150 @@ -namespace SimpleWatchConnectivity -{ - using CoreAnimation; - using CoreFoundation; - using CoreGraphics; - using Foundation; - using System; - using UIKit; - using WatchConnectivity; - - public partial class MainViewController : UIViewController - { - // We log the file transfer progress on the log view, so need to - // oberve the file transfer progress. - private readonly FileTransferObservers fileTransferObservers = new FileTransferObservers(); - - public MainViewController(IntPtr handle) : base(handle) { } - - ~MainViewController() - { - NSNotificationCenter.DefaultCenter.RemoveObserver(this); - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.DataDidFlow, this.DataDidFlow); - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.ActivationDidComplete, this.ActivationDidComplete); - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.ReachabilityDidChange, this.ReachabilityDidChange); - } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - - var layer = new CALayer - { - ShadowOpacity = 1f, - ShadowOffset = new CGSize(0f, 1f) - }; - - // Make sure the shadow is outside of the bottom of the screen. - var rect = this.TableContainerView.Bounds; - rect.Size = new CGSize(rect.Size.Width, - rect.Size.Height + this.View.Window.SafeAreaInsets.Bottom); - - var path = UIBezierPath.FromRoundedRect(rect, - UIRectCorner.TopRight | UIRectCorner.TopLeft, - new CGSize(10f, 10f)); - var shapeLayer = new CAShapeLayer - { - Path = path.CGPath, - FillColor = UIColor.White.CGColor - }; - - layer.AddSublayer(shapeLayer); - - this.TableContainerView.Layer.AddSublayer(layer); - this.TablePlaceholderView.Layer.ZPosition = layer.ZPosition + 1f; - } - - /// <summary> - /// Append the message to the end of the text view and make sure it is visiable. - /// </summary> - private void Log(string message) - { - this.LogView.Text = $"{LogView.Text}\n\n{message}"; - this.LogView.ScrollRangeToVisible(new NSRange(LogView.Text.Length, 1)); - } - - private void UpdateReachabilityColor() - { - // WCSession.isReachable triggers a warning if the session is not activated. - var isReachable = false; - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - isReachable = WCSession.DefaultSession.Reachable; - } - - this.ReachableLabel.BackgroundColor = isReachable ? UIColor.Green : UIColor.Red; - } - - private void ActivationDidComplete(NSNotification notification) - { - this.UpdateReachabilityColor(); - } - - private void ReachabilityDidChange(NSNotification notification) - { - this.UpdateReachabilityColor(); - } - - partial void Clear(UIButton sender) - { - this.LogView.Text = string.Empty; - } - - /// <summary> - /// Update the UI based on the userInfo dictionary of the notification. - /// </summary> - private void DataDidFlow(NSNotification notification) - { - if (notification.Object is CommandStatus commandStatus) - { - // If an error occurs, show the error message and returns. - if (!string.IsNullOrEmpty(commandStatus.ErrorMessage)) - { - this.Log($"! {commandStatus.Command}...{commandStatus.ErrorMessage}"); - } - else - { - if (commandStatus.TimedColor != null) - { - this.Log($"#{commandStatus.Command}...\n{commandStatus.Phrase} at {commandStatus.TimedColor.TimeStamp}"); - - var fileURL = commandStatus.File?.FileUrl; - if (fileURL != null) - { - if (fileURL.PathExtension == "log") - { - var content = NSString.FromData(NSData.FromUrl(fileURL), NSStringEncoding.UTF8); - if (content.Length > 0) - { - this.Log($"{fileURL.LastPathComponent}\n{content}"); - } - else - { - this.Log($"{fileURL.LastPathComponent}\n"); - } - } - } - - var fileTransfer = commandStatus.FileTransfer; - if (fileTransfer != null && commandStatus.Command == Command.TransferFile) - { - if (commandStatus.Phrase == Phrase.Finished) - { - this.fileTransferObservers.Unobserve(fileTransfer); - } - else if (commandStatus.Phrase == Phrase.Transferring) - { - this.fileTransferObservers.Observe(fileTransfer, (_) => this.LogProgress(fileTransfer)); - } - } - } - - this.NoteLabel.Hidden = !string.IsNullOrEmpty(this.LogView.Text); - } - } - } - - /// <summary> - /// Log the file transfer progress. - /// </summary> - private void LogProgress(WCSessionFileTransfer fileTransfer) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var dateFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; - var timeString = dateFormatter.StringFor(new NSDate()); - var fileName = fileTransfer.File.FileUrl.LastPathComponent; - - var progress = fileTransfer.Progress.LocalizedDescription ?? "No progress"; - this.Log($"- {fileName}: {progress} at {timeString}"); - }); - } - } -} \ No newline at end of file +namespace SimpleWatchConnectivity { + using CoreAnimation; + using CoreFoundation; + using CoreGraphics; + using Foundation; + using System; + using UIKit; + using WatchConnectivity; + + public partial class MainViewController : UIViewController { + // We log the file transfer progress on the log view, so need to + // oberve the file transfer progress. + private readonly FileTransferObservers fileTransferObservers = new FileTransferObservers (); + + public MainViewController (IntPtr handle) : base (handle) { } + + ~MainViewController () + { + NSNotificationCenter.DefaultCenter.RemoveObserver (this); + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.DataDidFlow, this.DataDidFlow); + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.ActivationDidComplete, this.ActivationDidComplete); + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.ReachabilityDidChange, this.ReachabilityDidChange); + } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + + var layer = new CALayer { + ShadowOpacity = 1f, + ShadowOffset = new CGSize (0f, 1f) + }; + + // Make sure the shadow is outside of the bottom of the screen. + var rect = this.TableContainerView.Bounds; + rect.Size = new CGSize (rect.Size.Width, + rect.Size.Height + this.View.Window.SafeAreaInsets.Bottom); + + var path = UIBezierPath.FromRoundedRect (rect, + UIRectCorner.TopRight | UIRectCorner.TopLeft, + new CGSize (10f, 10f)); + var shapeLayer = new CAShapeLayer { + Path = path.CGPath, + FillColor = UIColor.White.CGColor + }; + + layer.AddSublayer (shapeLayer); + + this.TableContainerView.Layer.AddSublayer (layer); + this.TablePlaceholderView.Layer.ZPosition = layer.ZPosition + 1f; + } + + /// <summary> + /// Append the message to the end of the text view and make sure it is visiable. + /// </summary> + private void Log (string message) + { + this.LogView.Text = $"{LogView.Text}\n\n{message}"; + this.LogView.ScrollRangeToVisible (new NSRange (LogView.Text.Length, 1)); + } + + private void UpdateReachabilityColor () + { + // WCSession.isReachable triggers a warning if the session is not activated. + var isReachable = false; + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + isReachable = WCSession.DefaultSession.Reachable; + } + + this.ReachableLabel.BackgroundColor = isReachable ? UIColor.Green : UIColor.Red; + } + + private void ActivationDidComplete (NSNotification notification) + { + this.UpdateReachabilityColor (); + } + + private void ReachabilityDidChange (NSNotification notification) + { + this.UpdateReachabilityColor (); + } + + partial void Clear (UIButton sender) + { + this.LogView.Text = string.Empty; + } + + /// <summary> + /// Update the UI based on the userInfo dictionary of the notification. + /// </summary> + private void DataDidFlow (NSNotification notification) + { + if (notification.Object is CommandStatus commandStatus) { + // If an error occurs, show the error message and returns. + if (!string.IsNullOrEmpty (commandStatus.ErrorMessage)) { + this.Log ($"! {commandStatus.Command}...{commandStatus.ErrorMessage}"); + } else { + if (commandStatus.TimedColor != null) { + this.Log ($"#{commandStatus.Command}...\n{commandStatus.Phrase} at {commandStatus.TimedColor.TimeStamp}"); + + var fileURL = commandStatus.File?.FileUrl; + if (fileURL != null) { + if (fileURL.PathExtension == "log") { + var content = NSString.FromData (NSData.FromUrl (fileURL), NSStringEncoding.UTF8); + if (content.Length > 0) { + this.Log ($"{fileURL.LastPathComponent}\n{content}"); + } else { + this.Log ($"{fileURL.LastPathComponent}\n"); + } + } + } + + var fileTransfer = commandStatus.FileTransfer; + if (fileTransfer != null && commandStatus.Command == Command.TransferFile) { + if (commandStatus.Phrase == Phrase.Finished) { + this.fileTransferObservers.Unobserve (fileTransfer); + } else if (commandStatus.Phrase == Phrase.Transferring) { + this.fileTransferObservers.Observe (fileTransfer, (_) => this.LogProgress (fileTransfer)); + } + } + } + + this.NoteLabel.Hidden = !string.IsNullOrEmpty (this.LogView.Text); + } + } + } + + /// <summary> + /// Log the file transfer progress. + /// </summary> + private void LogProgress (WCSessionFileTransfer fileTransfer) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + var dateFormatter = new NSDateFormatter { TimeStyle = NSDateFormatterStyle.Medium }; + var timeString = dateFormatter.StringFor (new NSDate ()); + var fileName = fileTransfer.File.FileUrl.LastPathComponent; + + var progress = fileTransfer.Progress.LocalizedDescription ?? "No progress"; + this.Log ($"- {fileName}: {progress} at {timeString}"); + }); + } + } +} diff --git a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/UserInfoTransfersViewController.cs b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/UserInfoTransfersViewController.cs index f9ddd03c3..fd062df91 100644 --- a/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/UserInfoTransfersViewController.cs +++ b/watchOS/SimpleWatchConnectivity/SimpleWatchConnectivity/UserInfoTransfersViewController.cs @@ -1,134 +1,123 @@ -namespace SimpleWatchConnectivity -{ - using CoreGraphics; - using Foundation; - using System; - using System.Collections.Generic; - using System.Linq; - using UIKit; - using WatchConnectivity; - - /// <summary> - /// UserInfoTransfersViewController manages the UserInfo transfer of the iOS app. - /// </summary> - public partial class UserInfoTransfersViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource - { - public UserInfoTransfersViewController(IntPtr handle) : base(handle) { } - - ~UserInfoTransfersViewController() - { - NSNotificationCenter.DefaultCenter.RemoveObserver(this); - } - - [Outlet] - protected UITableView TableView { get; set; } - - public Command Command { get; set; } - - // Outstanding transfers can change in the background so make a copy (cache) to - // make sure the data doesn't change during the table view loading cycle. - // Subclasses can override the computed property to provide the right transfers. - protected List<SessionTransfer> TransfersStore { get; set; } - - protected virtual List<SessionTransfer> Transfers - { - get - { - if (this.TransfersStore == null) - { - List<WCSessionUserInfoTransfer> transfersStore = null; - if (this.Command == Command.TransferUserInfo) - { - transfersStore = WCSession.DefaultSession.OutstandingUserInfoTransfers.Where(transfer => !transfer.CurrentComplicationInfo).ToList(); - } - else if (this.Command == Command.TransferCurrentComplicationUserInfo) - { - transfersStore = WCSession.DefaultSession.OutstandingUserInfoTransfers.Where(transfer => transfer.CurrentComplicationInfo).ToList(); - } - - this.TransfersStore = transfersStore.Select(transfer => new SessionTransfer { SessionUserInfoTransfer = transfer }).ToList(); - } - - return this.TransfersStore; - } - } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - this.TableView.Delegate = this; - this.TableView.DataSource = this; - NSNotificationCenter.DefaultCenter.AddObserver(NotificationName.DataDidFlow, this.DataDidFlow); - } - - #region Actions handlers. - - partial void Dismiss(UIButton sender) - { - this.WillMoveToParentViewController(null); - this.View.RemoveFromSuperview(); - this.RemoveFromParentViewController(); - } - - private void Cancel(UIButton sender) - { - var buttonOrigin = sender.ConvertPointToView(CGPoint.Empty, this.TableView); - var indexPath = this.TableView.IndexPathForRowAtPoint(buttonOrigin); - if (indexPath != null) - { - var transfer = this.Transfers[indexPath.Row]; - transfer.Cancel(this.Command); - } - } - - private void DataDidFlow(NSNotification notification) - { - if (notification.Object is CommandStatus commandStatus) - { - // Invalidate the cached transfers and reload the table view with animation - // if the notification command is relevant and is not failed. - if (commandStatus.Command == this.Command && commandStatus.Phrase != Phrase.Failed) - { - this.TransfersStore = null; - this.TableView.ReloadSections(new NSIndexSet(0), UITableViewRowAnimation.Automatic); - } - } - } - - #endregion - - #region UITableViewDelegate, UITableViewDataSource - - public nint RowsInSection(UITableView tableView, nint section) - { - return this.Transfers.Count; - } - - public virtual UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) - { - var cell = tableView.DequeueReusableCell("TransferCell", indexPath); - - var transfer = this.Transfers[indexPath.Row]; - cell.AccessoryView = this.NewAccessoryView(transfer.TimedColor.Color); - cell.TextLabel.Text = transfer.TimedColor.TimeStamp; - cell.TextLabel.TextColor = transfer.TimedColor.Color; - cell.DetailTextLabel.Text = string.Empty; - - return cell; - } - - private UIButton NewAccessoryView(UIColor titleColor) - { - var button = new UIButton(UIButtonType.RoundedRect); - button.SetTitle(" X ", UIControlState.Normal); - button.SetTitleColor(titleColor, UIControlState.Normal); - button.SizeToFit(); - button.AddTarget((sender, e) => this.Cancel(sender as UIButton), UIControlEvent.TouchUpInside); - - return button; - } - - #endregion - } -} \ No newline at end of file +namespace SimpleWatchConnectivity { + using CoreGraphics; + using Foundation; + using System; + using System.Collections.Generic; + using System.Linq; + using UIKit; + using WatchConnectivity; + + /// <summary> + /// UserInfoTransfersViewController manages the UserInfo transfer of the iOS app. + /// </summary> + public partial class UserInfoTransfersViewController : UIViewController, IUITableViewDelegate, IUITableViewDataSource { + public UserInfoTransfersViewController (IntPtr handle) : base (handle) { } + + ~UserInfoTransfersViewController () + { + NSNotificationCenter.DefaultCenter.RemoveObserver (this); + } + + [Outlet] + protected UITableView TableView { get; set; } + + public Command Command { get; set; } + + // Outstanding transfers can change in the background so make a copy (cache) to + // make sure the data doesn't change during the table view loading cycle. + // Subclasses can override the computed property to provide the right transfers. + protected List<SessionTransfer> TransfersStore { get; set; } + + protected virtual List<SessionTransfer> Transfers { + get { + if (this.TransfersStore == null) { + List<WCSessionUserInfoTransfer> transfersStore = null; + if (this.Command == Command.TransferUserInfo) { + transfersStore = WCSession.DefaultSession.OutstandingUserInfoTransfers.Where (transfer => !transfer.CurrentComplicationInfo).ToList (); + } else if (this.Command == Command.TransferCurrentComplicationUserInfo) { + transfersStore = WCSession.DefaultSession.OutstandingUserInfoTransfers.Where (transfer => transfer.CurrentComplicationInfo).ToList (); + } + + this.TransfersStore = transfersStore.Select (transfer => new SessionTransfer { SessionUserInfoTransfer = transfer }).ToList (); + } + + return this.TransfersStore; + } + } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + this.TableView.Delegate = this; + this.TableView.DataSource = this; + NSNotificationCenter.DefaultCenter.AddObserver (NotificationName.DataDidFlow, this.DataDidFlow); + } + + #region Actions handlers. + + partial void Dismiss (UIButton sender) + { + this.WillMoveToParentViewController (null); + this.View.RemoveFromSuperview (); + this.RemoveFromParentViewController (); + } + + private void Cancel (UIButton sender) + { + var buttonOrigin = sender.ConvertPointToView (CGPoint.Empty, this.TableView); + var indexPath = this.TableView.IndexPathForRowAtPoint (buttonOrigin); + if (indexPath != null) { + var transfer = this.Transfers [indexPath.Row]; + transfer.Cancel (this.Command); + } + } + + private void DataDidFlow (NSNotification notification) + { + if (notification.Object is CommandStatus commandStatus) { + // Invalidate the cached transfers and reload the table view with animation + // if the notification command is relevant and is not failed. + if (commandStatus.Command == this.Command && commandStatus.Phrase != Phrase.Failed) { + this.TransfersStore = null; + this.TableView.ReloadSections (new NSIndexSet (0), UITableViewRowAnimation.Automatic); + } + } + } + + #endregion + + #region UITableViewDelegate, UITableViewDataSource + + public nint RowsInSection (UITableView tableView, nint section) + { + return this.Transfers.Count; + } + + public virtual UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) + { + var cell = tableView.DequeueReusableCell ("TransferCell", indexPath); + + var transfer = this.Transfers [indexPath.Row]; + cell.AccessoryView = this.NewAccessoryView (transfer.TimedColor.Color); + cell.TextLabel.Text = transfer.TimedColor.TimeStamp; + cell.TextLabel.TextColor = transfer.TimedColor.Color; + cell.DetailTextLabel.Text = string.Empty; + + return cell; + } + + private UIButton NewAccessoryView (UIColor titleColor) + { + var button = new UIButton (UIButtonType.RoundedRect); + button.SetTitle (" X ", UIControlState.Normal); + button.SetTitleColor (titleColor, UIControlState.Normal); + button.SizeToFit (); + button.AddTarget ((sender, e) => this.Cancel (sender as UIButton), UIControlEvent.TouchUpInside); + + return button; + } + + #endregion + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ConfigurationInterfaceController.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ConfigurationInterfaceController.cs index 69eccd177..81d664950 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ConfigurationInterfaceController.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ConfigurationInterfaceController.cs @@ -1,276 +1,241 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using CoreLocation; - using Foundation; - using HealthKit; - using System; - using System.Collections.Generic; - using System.Linq; - using WatchKit; - - public partial class ConfigurationInterfaceController : WKInterfaceController - { - private readonly List<WorkoutType> activityTypes = new List<WorkoutType> { WorkoutType.Walking, WorkoutType.Running, WorkoutType.Hiking }; - - private readonly List<LocationType> locationTypes = new List<LocationType> { LocationType.Indoor, LocationType.Outdoor }; - - private readonly HKHealthStore healthStore = new HKHealthStore(); - - private LocationType selectedLocationType; - - private WorkoutType selectedActivityType; - - public ConfigurationInterfaceController() : base() - { - this.selectedLocationType = this.locationTypes[0]; - this.selectedActivityType = this.activityTypes[0]; - } - - protected ConfigurationInterfaceController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } - - public override void Awake(NSObject context) - { - base.Awake(context); - this.SetTitle("Speedy Sloth"); - - // populate the activity type picker - var activityTypePickerItems = this.activityTypes.Select(type => new WKPickerItem { Title = type.DisplayString() }); - this.ActivityTypePicker.SetItems(activityTypePickerItems.ToArray()); - - // populate the location type picker - var locationTypePickerItems = this.locationTypes.Select(type => new WKPickerItem { Title = type.DisplayString() }); - this.LocationTypePicker.SetItems(locationTypePickerItems.ToArray()); - } - - #region Post processing of workouts (Slothify) - - private void MakeWorkoutsSlothy() - { - this.LoadWorkouts((workouts) => - { - foreach (var workout in workouts) - { - this.MakeWorkoutsSlothy(workout); - } - }); - } - - private void LoadWorkouts(Action<List<HKWorkout>> completion) - { - var workoutType = HKObjectType.GetWorkoutType(); - var predicate = HKQuery.GetPredicateForObjectsFromSource(HKSource.GetDefaultSource); - var query = new HKSampleQuery(workoutType, predicate, HKSampleQuery.NoLimit, null, (sender, results, error) => - { - var isSuccess = results != null; - if (isSuccess) - { - var workouts = results.OfType<HKWorkout>().ToList(); - isSuccess = workouts.Any(); - if (isSuccess) - { - completion(workouts); - } - } - - if (!isSuccess) - { - Console.WriteLine($"An error occurred: ({error?.LocalizedDescription ?? "Unknown"})"); - } - }); - - this.healthStore.ExecuteQuery(query); - } - - private void MakeWorkoutsSlothy(HKWorkout workout) - { - // Query for workout's rotes - var routeType = HKSeriesType.WorkoutRouteType; - var workoutPredicate = HKQuery.GetPredicateForObjectsFromWorkout(workout); - var routeQuery = new HKSampleQuery(routeType, workoutPredicate, HKSampleQuery.NoLimit, null, (sender, results, error) => - { - var route = results?.FirstOrDefault() as HKWorkoutRoute; - if (route != null) - { - var version = route.Metadata?.SyncVersion; - if (!version.HasValue) - { - Console.WriteLine($"Route does not have a sync version ({route})"); - } - else if (version.Value == 1) - { - this.MakeRouteWorkoutsSlothy(workout, route); - } - } - else - { - Console.WriteLine($"An error occurred fetching the route ({error?.LocalizedDescription ?? "Workout has no routes"})"); - } - }); - - this.healthStore.ExecuteQuery(routeQuery); - } - - private void MakeRouteWorkoutsSlothy(HKWorkout workout, HKWorkoutRoute route) - { - // Get all of the locations - this.LoadRouteLocations(route, (locations) => - { - // Slothify route - var newLocations = this.SlothifyRouteLocations(locations); - this.UpdateWorkoutLocationsRoute(workout, route, newLocations); - }); - } - - private void LoadRouteLocations(HKWorkoutRoute route, Action<List<CLLocation>> completion) - { - var locations = new List<CLLocation>(); - - var locationQuery = new HKWorkoutRouteQuery(route, (query, routeData, done, error) => - { - if (routeData != null) - { - locations.AddRange(routeData); - if (done) - { - completion(locations); - } - } - else - { - Console.WriteLine($"Error occurred wile querying for locations: ({error?.LocalizedDescription ?? ""})"); - } - }); - - this.healthStore.ExecuteQuery(locationQuery); - } - - - /// <summary> - /// Slothifying a workout route's locations will shift the locations left and right to form a moving spiral - /// around the original route - /// </summary> - /// <param name="locations"></param> - /// <returns></returns> - private List<CLLocation> SlothifyRouteLocations(List<CLLocation> locations) - { - var newLocations = new List<CLLocation>(); - - var start = locations.FirstOrDefault() ?? new CLLocation(0d, 0d); - newLocations.Add(start); - - var radius = 0.0001; - - var theta = 0d; - for (int i = 1; i < locations.Count - 1; i++) - { - var location = locations[i]; - - theta += Math.PI / 8d; - var latitude = Math.Sin(theta) * radius; - var longitude = Math.Cos(theta) * radius; - - var coordinate = locations[i].Coordinate; - coordinate.Latitude += latitude; - coordinate.Longitude += longitude; - newLocations.Add(new CLLocation(coordinate, - location.Altitude, - location.HorizontalAccuracy, - location.VerticalAccuracy, - location.Course, - location.Speed, - location.Timestamp)); - } - - // Then jump to the last location - var lastLocation = locations.LastOrDefault(); - if (lastLocation != null) - { - newLocations.Add(lastLocation); - } - - return newLocations; - } - - private void UpdateWorkoutLocationsRoute(HKWorkout workout, HKWorkoutRoute route, List<CLLocation> newLocations) - { - // create a workout route builder - var workoutRouteBuilder = new HKWorkoutRouteBuilder(this.healthStore, null); - - // insert updated route locations - workoutRouteBuilder.InsertRouteData(newLocations.ToArray(), (success, error) => - { - if (success) - { - var syncIdentifier = route.Metadata?.SyncIdentifier; - if (!string.IsNullOrEmpty(syncIdentifier)) - { - // new metadata with the same sync identifier and a higher version - var objects = new NSObject[] { new NSString(syncIdentifier), NSNumber.FromInt32(2) }; - var keys = new NSString[] { HKMetadataKey.SyncIdentifier, HKMetadataKey.SyncVersion }; - - var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys); - var metadata = new HKMetadata(dictionary); - - // finish the route with updated metadata - workoutRouteBuilder.FinishRoute(workout, metadata, (workoutRoute, routeRrror) => - { - if (workoutRoute != null) - { - Console.WriteLine($"Workout route updated: ({route})"); - } - else - { - Console.WriteLine($"An error occurred while finishing the new route: ({error?.LocalizedDescription ?? "Unknown"})"); - } - }); - } - else - { - throw new ArgumentNullException(nameof(syncIdentifier), "Missing expected sync identifier on route"); - } - } - else - { - Console.WriteLine($"An error occurred while inserting route data ({error?.LocalizedDescription ?? "Unknown"})"); - } - }); - } - - #endregion - - partial void SlothifyWorkouts() - { - this.MakeWorkoutsSlothy(); - } - - partial void ActivityTypePickerSelectedItemChanged(nint sender) - { - this.selectedActivityType = this.activityTypes[(int)sender]; - } - - partial void LocationTypePickerSelectedItemChanged(nint sender) - { - this.selectedLocationType = this.locationTypes[(int)sender]; - } - - partial void DidTapStartButton() - { - // Create workout configuration - var workoutConfiguration = new HKWorkoutConfiguration - { - ActivityType = this.selectedActivityType.Map(), - LocationType = this.selectedLocationType.Map() - }; - - // Pass configuration to next interface controller - WKInterfaceController.ReloadRootPageControllers(new[] { nameof(WorkoutInterfaceController) }, - new[] { workoutConfiguration }, - WKPageOrientation.Vertical, - 0); - } - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using CoreLocation; + using Foundation; + using HealthKit; + using System; + using System.Collections.Generic; + using System.Linq; + using WatchKit; + + public partial class ConfigurationInterfaceController : WKInterfaceController { + private readonly List<WorkoutType> activityTypes = new List<WorkoutType> { WorkoutType.Walking, WorkoutType.Running, WorkoutType.Hiking }; + + private readonly List<LocationType> locationTypes = new List<LocationType> { LocationType.Indoor, LocationType.Outdoor }; + + private readonly HKHealthStore healthStore = new HKHealthStore (); + + private LocationType selectedLocationType; + + private WorkoutType selectedActivityType; + + public ConfigurationInterfaceController () : base () + { + this.selectedLocationType = this.locationTypes [0]; + this.selectedActivityType = this.activityTypes [0]; + } + + protected ConfigurationInterfaceController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } + + public override void Awake (NSObject context) + { + base.Awake (context); + this.SetTitle ("Speedy Sloth"); + + // populate the activity type picker + var activityTypePickerItems = this.activityTypes.Select (type => new WKPickerItem { Title = type.DisplayString () }); + this.ActivityTypePicker.SetItems (activityTypePickerItems.ToArray ()); + + // populate the location type picker + var locationTypePickerItems = this.locationTypes.Select (type => new WKPickerItem { Title = type.DisplayString () }); + this.LocationTypePicker.SetItems (locationTypePickerItems.ToArray ()); + } + + #region Post processing of workouts (Slothify) + + private void MakeWorkoutsSlothy () + { + this.LoadWorkouts ((workouts) => { + foreach (var workout in workouts) { + this.MakeWorkoutsSlothy (workout); + } + }); + } + + private void LoadWorkouts (Action<List<HKWorkout>> completion) + { + var workoutType = HKObjectType.GetWorkoutType (); + var predicate = HKQuery.GetPredicateForObjectsFromSource (HKSource.GetDefaultSource); + var query = new HKSampleQuery (workoutType, predicate, HKSampleQuery.NoLimit, null, (sender, results, error) => { + var isSuccess = results != null; + if (isSuccess) { + var workouts = results.OfType<HKWorkout> ().ToList (); + isSuccess = workouts.Any (); + if (isSuccess) { + completion (workouts); + } + } + + if (!isSuccess) { + Console.WriteLine ($"An error occurred: ({error?.LocalizedDescription ?? "Unknown"})"); + } + }); + + this.healthStore.ExecuteQuery (query); + } + + private void MakeWorkoutsSlothy (HKWorkout workout) + { + // Query for workout's rotes + var routeType = HKSeriesType.WorkoutRouteType; + var workoutPredicate = HKQuery.GetPredicateForObjectsFromWorkout (workout); + var routeQuery = new HKSampleQuery (routeType, workoutPredicate, HKSampleQuery.NoLimit, null, (sender, results, error) => { + var route = results?.FirstOrDefault () as HKWorkoutRoute; + if (route != null) { + var version = route.Metadata?.SyncVersion; + if (!version.HasValue) { + Console.WriteLine ($"Route does not have a sync version ({route})"); + } else if (version.Value == 1) { + this.MakeRouteWorkoutsSlothy (workout, route); + } + } else { + Console.WriteLine ($"An error occurred fetching the route ({error?.LocalizedDescription ?? "Workout has no routes"})"); + } + }); + + this.healthStore.ExecuteQuery (routeQuery); + } + + private void MakeRouteWorkoutsSlothy (HKWorkout workout, HKWorkoutRoute route) + { + // Get all of the locations + this.LoadRouteLocations (route, (locations) => { + // Slothify route + var newLocations = this.SlothifyRouteLocations (locations); + this.UpdateWorkoutLocationsRoute (workout, route, newLocations); + }); + } + + private void LoadRouteLocations (HKWorkoutRoute route, Action<List<CLLocation>> completion) + { + var locations = new List<CLLocation> (); + + var locationQuery = new HKWorkoutRouteQuery (route, (query, routeData, done, error) => { + if (routeData != null) { + locations.AddRange (routeData); + if (done) { + completion (locations); + } + } else { + Console.WriteLine ($"Error occurred wile querying for locations: ({error?.LocalizedDescription ?? ""})"); + } + }); + + this.healthStore.ExecuteQuery (locationQuery); + } + + + /// <summary> + /// Slothifying a workout route's locations will shift the locations left and right to form a moving spiral + /// around the original route + /// </summary> + /// <param name="locations"></param> + /// <returns></returns> + private List<CLLocation> SlothifyRouteLocations (List<CLLocation> locations) + { + var newLocations = new List<CLLocation> (); + + var start = locations.FirstOrDefault () ?? new CLLocation (0d, 0d); + newLocations.Add (start); + + var radius = 0.0001; + + var theta = 0d; + for (int i = 1; i < locations.Count - 1; i++) { + var location = locations [i]; + + theta += Math.PI / 8d; + var latitude = Math.Sin (theta) * radius; + var longitude = Math.Cos (theta) * radius; + + var coordinate = locations [i].Coordinate; + coordinate.Latitude += latitude; + coordinate.Longitude += longitude; + newLocations.Add (new CLLocation (coordinate, + location.Altitude, + location.HorizontalAccuracy, + location.VerticalAccuracy, + location.Course, + location.Speed, + location.Timestamp)); + } + + // Then jump to the last location + var lastLocation = locations.LastOrDefault (); + if (lastLocation != null) { + newLocations.Add (lastLocation); + } + + return newLocations; + } + + private void UpdateWorkoutLocationsRoute (HKWorkout workout, HKWorkoutRoute route, List<CLLocation> newLocations) + { + // create a workout route builder + var workoutRouteBuilder = new HKWorkoutRouteBuilder (this.healthStore, null); + + // insert updated route locations + workoutRouteBuilder.InsertRouteData (newLocations.ToArray (), (success, error) => { + if (success) { + var syncIdentifier = route.Metadata?.SyncIdentifier; + if (!string.IsNullOrEmpty (syncIdentifier)) { + // new metadata with the same sync identifier and a higher version + var objects = new NSObject [] { new NSString (syncIdentifier), NSNumber.FromInt32 (2) }; + var keys = new NSString [] { HKMetadataKey.SyncIdentifier, HKMetadataKey.SyncVersion }; + + var dictionary = NSDictionary.FromObjectsAndKeys (objects, keys); + var metadata = new HKMetadata (dictionary); + + // finish the route with updated metadata + workoutRouteBuilder.FinishRoute (workout, metadata, (workoutRoute, routeRrror) => { + if (workoutRoute != null) { + Console.WriteLine ($"Workout route updated: ({route})"); + } else { + Console.WriteLine ($"An error occurred while finishing the new route: ({error?.LocalizedDescription ?? "Unknown"})"); + } + }); + } else { + throw new ArgumentNullException (nameof (syncIdentifier), "Missing expected sync identifier on route"); + } + } else { + Console.WriteLine ($"An error occurred while inserting route data ({error?.LocalizedDescription ?? "Unknown"})"); + } + }); + } + + #endregion + + partial void SlothifyWorkouts () + { + this.MakeWorkoutsSlothy (); + } + + partial void ActivityTypePickerSelectedItemChanged (nint sender) + { + this.selectedActivityType = this.activityTypes [(int) sender]; + } + + partial void LocationTypePickerSelectedItemChanged (nint sender) + { + this.selectedLocationType = this.locationTypes [(int) sender]; + } + + partial void DidTapStartButton () + { + // Create workout configuration + var workoutConfiguration = new HKWorkoutConfiguration { + ActivityType = this.selectedActivityType.Map (), + LocationType = this.selectedLocationType.Map () + }; + + // Pass configuration to next interface controller + WKInterfaceController.ReloadRootPageControllers (new [] { nameof (WorkoutInterfaceController) }, + new [] { workoutConfiguration }, + WKPageOrientation.Vertical, + 0); + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/LocationType.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/LocationType.cs index bfc9c66c4..8fae17dd1 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/LocationType.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/LocationType.cs @@ -1,10 +1,8 @@ - -namespace SpeedySloth.WatchAppExtension -{ - public enum LocationType - { - Indoor, - - Outdoor, - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + public enum LocationType { + Indoor, + + Outdoor, + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/WorkoutType.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/WorkoutType.cs index 8b1634ecb..afa9c9671 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/WorkoutType.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Enums/WorkoutType.cs @@ -1,12 +1,10 @@ - -namespace SpeedySloth.WatchAppExtension -{ - public enum WorkoutType - { - Walking, - - Running, - - Hiking - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + public enum WorkoutType { + Walking, + + Running, + + Hiking + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ExtensionDelegate.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ExtensionDelegate.cs index e21cc9d6c..1d637e22a 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ExtensionDelegate.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/ExtensionDelegate.cs @@ -1,19 +1,17 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using Foundation; - using HealthKit; - using WatchKit; - - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - public override void HandleWorkoutConfiguration(HKWorkoutConfiguration workoutConfiguration) - { - WKInterfaceController.ReloadRootPageControllers(new string[] { nameof(WorkoutInterfaceController) }, - new NSObject[] { workoutConfiguration }, - WKPageOrientation.Vertical, - 0); - } - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using Foundation; + using HealthKit; + using WatchKit; + + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + public override void HandleWorkoutConfiguration (HKWorkoutConfiguration workoutConfiguration) + { + WKInterfaceController.ReloadRootPageControllers (new string [] { nameof (WorkoutInterfaceController) }, + new NSObject [] { workoutConfiguration }, + WKPageOrientation.Vertical, + 0); + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/HealthStoreManager.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/HealthStoreManager.cs index 18dba0266..2874bdd5d 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/HealthStoreManager.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/HealthStoreManager.cs @@ -1,281 +1,251 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using CoreFoundation; - using CoreLocation; - using Foundation; - using HealthKit; - using System; - using System.Collections.Generic; - using System.Linq; - using WatchKit; - - public class HealthStoreManager : CLLocationManagerDelegate - { - private readonly List<HKWorkoutEvent> workoutEvents = new List<HKWorkoutEvent>(); - - private readonly List<HKQuery> activeDataQueries = new List<HKQuery>(); - - private readonly HKHealthStore healthStore = new HKHealthStore(); - - private HKWorkoutRouteBuilder workoutRouteBuilder; - - private CLLocationManager locationManager; - - public List<HKWorkoutEvent> WorkoutEvents => this.workoutEvents; - - public double TotalEnergyBurned { get; private set; } = 0d; - - public double TotalDistance { get; private set; } = 0d; - - #region Health store wrappers - - public void Start(HKWorkoutSession workoutSession) - { - this.healthStore.StartWorkoutSession(workoutSession); - } - - public void End(HKWorkoutSession workoutSession) - { - this.healthStore.EndWorkoutSession(workoutSession); - } - - public void Pause(HKWorkoutSession workoutSession) - { - this.healthStore.PauseWorkoutSession(workoutSession); - } - - public void Resume(HKWorkoutSession workoutSession) - { - this.healthStore.ResumeWorkoutSession(workoutSession); - } - - #endregion - - #region Data Accumulation - - public void StartWalkingRunningQuery(NSDate startDate, Action<List<HKQuantitySample>> handler) - { - this.StartQuery(HKQuantityTypeIdentifier.DistanceWalkingRunning, - startDate, - (query, addedObjects, deletedObjects, newAnchor, error) => - { - if (addedObjects != null) - { - var quantitySamples = addedObjects.OfType<HKQuantitySample>().ToList(); - handler(quantitySamples); - } - else - { - Console.WriteLine($"Distance walking running query failed with error: ({error?.Description ?? "unknown"})"); - } - }); - } - - public void StartActiveEnergyBurnedQuery(NSDate startDate, Action<List<HKQuantitySample>> handler) - { - this.StartQuery(HKQuantityTypeIdentifier.ActiveEnergyBurned, - startDate, - (query, addedObjects, deletedObjects, newAnchor, error) => - { - if (addedObjects != null) - { - var quantitySamples = addedObjects.OfType<HKQuantitySample>().ToList(); - handler(quantitySamples); - } - else - { - Console.WriteLine($"Active energy burned query failed with error: ({error?.Description ?? "unknown"})"); - } - }); - } - - public void StartAccumulatingLocationData() - { - if (CLLocationManager.LocationServicesEnabled) - { - this.locationManager = new CLLocationManager - { - Delegate = this, - AllowsBackgroundLocationUpdates = true, - DesiredAccuracy = CLLocation.AccuracyBest, - }; - - this.locationManager.StartUpdatingLocation(); - this.workoutRouteBuilder = new HKWorkoutRouteBuilder(this.healthStore, null); - } - else - { - Console.WriteLine("User does not have location service enabled"); - } - } - - public void StopAccumulatingData() - { - foreach (var query in this.activeDataQueries) - { - this.healthStore.StopQuery(query); - } - - this.activeDataQueries.Clear(); - this.locationManager?.StopUpdatingLocation(); - } - - private void StartQuery(HKQuantityTypeIdentifier quantityTypeIdentifier, NSDate startDate, HKAnchoredObjectUpdateHandler handler) - { - var datePredicate = HKQuery.GetPredicateForSamples(startDate, null, HKQueryOptions.StrictStartDate); - var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices(new NSSet<HKDevice>(HKDevice.LocalDevice)); - var queryPredicate = NSCompoundPredicate.CreateAndPredicate(new NSPredicate[] { datePredicate, devicePredicate }); - - var quantityType = HKQuantityType.Create(quantityTypeIdentifier); - var query = new HKAnchoredObjectQuery(quantityType, queryPredicate, null, HKSampleQuery.NoLimit, handler); - query.UpdateHandler = handler; - this.healthStore.ExecuteQuery(query); - - this.activeDataQueries.Add(query); - } - - #endregion - - #region Saving Data - - public void SaveWorkout(HKWorkoutSession workoutSession, NSDate startDate, NSDate endDate) - { - // Create and save a workout sample - var configuration = workoutSession.WorkoutConfiguration; - var metadata = new HKMetadata - { - IndoorWorkout = configuration.LocationType == HKWorkoutSessionLocationType.Indoor, - }; - - var workout = HKWorkout.Create(configuration.ActivityType, - startDate, - endDate, - this.workoutEvents.ToArray(), - this.TotalBurningEnergyQuantity(), - this.TotalDistanceQuantity(), - metadata); - - this.healthStore.SaveObject(workout, (isSuccess, error) => - { - if (isSuccess) - { - this.AddSamples(workout, startDate, endDate); - } - }); - } - - private void AddSamples(HKWorkout workout, NSDate startDate, NSDate endDate) - { - // Create energy and distance sample - var totalEnergyBurnedSample = HKQuantitySample.FromType(HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned), - this.TotalBurningEnergyQuantity(), - startDate, - endDate); - - var totalDistanceSample = HKQuantitySample.FromType(HKQuantityType.Create(HKQuantityTypeIdentifier.DistanceWalkingRunning), - this.TotalDistanceQuantity(), - startDate, - endDate); - // add samples to workout - this.healthStore.AddSamples(new HKSample[] { totalEnergyBurnedSample, totalDistanceSample }, workout, (isSuccess, error) => - { - if (isSuccess) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - WKInterfaceController.ReloadRootPageControllers(new string[] { nameof(SummaryInterfaceController) }, - new NSObject[] { workout }, - WKPageOrientation.Vertical, - 0); - }); - } - else - { - Console.WriteLine($"Adding workout subsamples failed with error: ({error?.Description ?? "unknown"})"); - } - }); - - // finish the route with a syn identifier so we can easily update the route later - var objects = new NSObject[] { new NSString(new NSUuid().AsString()), NSNumber.FromInt32(1) }; - var keys = new NSString[] { HKMetadataKey.SyncIdentifier, HKMetadataKey.SyncVersion }; - - var dictionary = NSDictionary.FromObjectsAndKeys(objects, keys); - var metadata = new HKMetadata(dictionary); - - this.workoutRouteBuilder?.FinishRoute(workout, metadata, (workoutRoute, error) => - { - if (workoutRoute == null) - { - Console.WriteLine($"Finishing route failed with error: ({error?.Description ?? "unknown"})"); - } - }); - } - - #endregion - - #region CLLocationManagerDelegate - - public override void LocationsUpdated(CLLocationManager manager, CLLocation[] locations) - { - var filtredLocations = locations.Where(location => location.HorizontalAccuracy <= CLLocation.AccuracyNearestTenMeters).ToArray(); - if (filtredLocations.Any()) - { - this.workoutRouteBuilder?.InsertRouteData(filtredLocations, (isSuccess, error) => - { - if (!isSuccess) - { - Console.WriteLine($"Inserting route data failed with error: ({error?.Description ?? "unknown"})"); - } - }); - } - } - - #endregion - - #region Convenience - - public void ProcessWalkingRunningSamples(List<HKQuantitySample> samples) - { - this.TotalDistance += samples.Sum(sample => sample.Quantity.GetDoubleValue(HKUnit.Meter)); - } - - public void ProcessActiveEnergySamples(List<HKQuantitySample> samples) - { - this.TotalEnergyBurned += samples.Sum(sample => sample.Quantity.GetDoubleValue(HKUnit.Kilocalorie)); - } - - private HKQuantity TotalBurningEnergyQuantity() - { - return HKQuantity.FromQuantity(HKUnit.Kilocalorie, this.TotalEnergyBurned); - } - - private HKQuantity TotalDistanceQuantity() - { - return HKQuantity.FromQuantity(HKUnit.Meter, this.TotalDistance); - } - - #endregion - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - - this.healthStore.Dispose(); - this.workoutEvents.Clear(); - this.activeDataQueries.Clear(); - - if (this.locationManager != null) - { - this.locationManager.Dispose(); - this.locationManager = null; - } - - if (this.workoutRouteBuilder != null) - { - this.workoutRouteBuilder.Dispose(); - this.workoutRouteBuilder = null; - } - } - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using CoreFoundation; + using CoreLocation; + using Foundation; + using HealthKit; + using System; + using System.Collections.Generic; + using System.Linq; + using WatchKit; + + public class HealthStoreManager : CLLocationManagerDelegate { + private readonly List<HKWorkoutEvent> workoutEvents = new List<HKWorkoutEvent> (); + + private readonly List<HKQuery> activeDataQueries = new List<HKQuery> (); + + private readonly HKHealthStore healthStore = new HKHealthStore (); + + private HKWorkoutRouteBuilder workoutRouteBuilder; + + private CLLocationManager locationManager; + + public List<HKWorkoutEvent> WorkoutEvents => this.workoutEvents; + + public double TotalEnergyBurned { get; private set; } = 0d; + + public double TotalDistance { get; private set; } = 0d; + + #region Health store wrappers + + public void Start (HKWorkoutSession workoutSession) + { + this.healthStore.StartWorkoutSession (workoutSession); + } + + public void End (HKWorkoutSession workoutSession) + { + this.healthStore.EndWorkoutSession (workoutSession); + } + + public void Pause (HKWorkoutSession workoutSession) + { + this.healthStore.PauseWorkoutSession (workoutSession); + } + + public void Resume (HKWorkoutSession workoutSession) + { + this.healthStore.ResumeWorkoutSession (workoutSession); + } + + #endregion + + #region Data Accumulation + + public void StartWalkingRunningQuery (NSDate startDate, Action<List<HKQuantitySample>> handler) + { + this.StartQuery (HKQuantityTypeIdentifier.DistanceWalkingRunning, + startDate, + (query, addedObjects, deletedObjects, newAnchor, error) => { + if (addedObjects != null) { + var quantitySamples = addedObjects.OfType<HKQuantitySample> ().ToList (); + handler (quantitySamples); + } else { + Console.WriteLine ($"Distance walking running query failed with error: ({error?.Description ?? "unknown"})"); + } + }); + } + + public void StartActiveEnergyBurnedQuery (NSDate startDate, Action<List<HKQuantitySample>> handler) + { + this.StartQuery (HKQuantityTypeIdentifier.ActiveEnergyBurned, + startDate, + (query, addedObjects, deletedObjects, newAnchor, error) => { + if (addedObjects != null) { + var quantitySamples = addedObjects.OfType<HKQuantitySample> ().ToList (); + handler (quantitySamples); + } else { + Console.WriteLine ($"Active energy burned query failed with error: ({error?.Description ?? "unknown"})"); + } + }); + } + + public void StartAccumulatingLocationData () + { + if (CLLocationManager.LocationServicesEnabled) { + this.locationManager = new CLLocationManager { + Delegate = this, + AllowsBackgroundLocationUpdates = true, + DesiredAccuracy = CLLocation.AccuracyBest, + }; + + this.locationManager.StartUpdatingLocation (); + this.workoutRouteBuilder = new HKWorkoutRouteBuilder (this.healthStore, null); + } else { + Console.WriteLine ("User does not have location service enabled"); + } + } + + public void StopAccumulatingData () + { + foreach (var query in this.activeDataQueries) { + this.healthStore.StopQuery (query); + } + + this.activeDataQueries.Clear (); + this.locationManager?.StopUpdatingLocation (); + } + + private void StartQuery (HKQuantityTypeIdentifier quantityTypeIdentifier, NSDate startDate, HKAnchoredObjectUpdateHandler handler) + { + var datePredicate = HKQuery.GetPredicateForSamples (startDate, null, HKQueryOptions.StrictStartDate); + var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices (new NSSet<HKDevice> (HKDevice.LocalDevice)); + var queryPredicate = NSCompoundPredicate.CreateAndPredicate (new NSPredicate [] { datePredicate, devicePredicate }); + + var quantityType = HKQuantityType.Create (quantityTypeIdentifier); + var query = new HKAnchoredObjectQuery (quantityType, queryPredicate, null, HKSampleQuery.NoLimit, handler); + query.UpdateHandler = handler; + this.healthStore.ExecuteQuery (query); + + this.activeDataQueries.Add (query); + } + + #endregion + + #region Saving Data + + public void SaveWorkout (HKWorkoutSession workoutSession, NSDate startDate, NSDate endDate) + { + // Create and save a workout sample + var configuration = workoutSession.WorkoutConfiguration; + var metadata = new HKMetadata { + IndoorWorkout = configuration.LocationType == HKWorkoutSessionLocationType.Indoor, + }; + + var workout = HKWorkout.Create (configuration.ActivityType, + startDate, + endDate, + this.workoutEvents.ToArray (), + this.TotalBurningEnergyQuantity (), + this.TotalDistanceQuantity (), + metadata); + + this.healthStore.SaveObject (workout, (isSuccess, error) => { + if (isSuccess) { + this.AddSamples (workout, startDate, endDate); + } + }); + } + + private void AddSamples (HKWorkout workout, NSDate startDate, NSDate endDate) + { + // Create energy and distance sample + var totalEnergyBurnedSample = HKQuantitySample.FromType (HKQuantityType.Create (HKQuantityTypeIdentifier.ActiveEnergyBurned), + this.TotalBurningEnergyQuantity (), + startDate, + endDate); + + var totalDistanceSample = HKQuantitySample.FromType (HKQuantityType.Create (HKQuantityTypeIdentifier.DistanceWalkingRunning), + this.TotalDistanceQuantity (), + startDate, + endDate); + // add samples to workout + this.healthStore.AddSamples (new HKSample [] { totalEnergyBurnedSample, totalDistanceSample }, workout, (isSuccess, error) => { + if (isSuccess) { + DispatchQueue.MainQueue.DispatchAsync (() => { + WKInterfaceController.ReloadRootPageControllers (new string [] { nameof (SummaryInterfaceController) }, + new NSObject [] { workout }, + WKPageOrientation.Vertical, + 0); + }); + } else { + Console.WriteLine ($"Adding workout subsamples failed with error: ({error?.Description ?? "unknown"})"); + } + }); + + // finish the route with a syn identifier so we can easily update the route later + var objects = new NSObject [] { new NSString (new NSUuid ().AsString ()), NSNumber.FromInt32 (1) }; + var keys = new NSString [] { HKMetadataKey.SyncIdentifier, HKMetadataKey.SyncVersion }; + + var dictionary = NSDictionary.FromObjectsAndKeys (objects, keys); + var metadata = new HKMetadata (dictionary); + + this.workoutRouteBuilder?.FinishRoute (workout, metadata, (workoutRoute, error) => { + if (workoutRoute == null) { + Console.WriteLine ($"Finishing route failed with error: ({error?.Description ?? "unknown"})"); + } + }); + } + + #endregion + + #region CLLocationManagerDelegate + + public override void LocationsUpdated (CLLocationManager manager, CLLocation [] locations) + { + var filtredLocations = locations.Where (location => location.HorizontalAccuracy <= CLLocation.AccuracyNearestTenMeters).ToArray (); + if (filtredLocations.Any ()) { + this.workoutRouteBuilder?.InsertRouteData (filtredLocations, (isSuccess, error) => { + if (!isSuccess) { + Console.WriteLine ($"Inserting route data failed with error: ({error?.Description ?? "unknown"})"); + } + }); + } + } + + #endregion + + #region Convenience + + public void ProcessWalkingRunningSamples (List<HKQuantitySample> samples) + { + this.TotalDistance += samples.Sum (sample => sample.Quantity.GetDoubleValue (HKUnit.Meter)); + } + + public void ProcessActiveEnergySamples (List<HKQuantitySample> samples) + { + this.TotalEnergyBurned += samples.Sum (sample => sample.Quantity.GetDoubleValue (HKUnit.Kilocalorie)); + } + + private HKQuantity TotalBurningEnergyQuantity () + { + return HKQuantity.FromQuantity (HKUnit.Kilocalorie, this.TotalEnergyBurned); + } + + private HKQuantity TotalDistanceQuantity () + { + return HKQuantity.FromQuantity (HKUnit.Meter, this.TotalDistance); + } + + #endregion + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + this.healthStore.Dispose (); + this.workoutEvents.Clear (); + this.activeDataQueries.Clear (); + + if (this.locationManager != null) { + this.locationManager.Dispose (); + this.locationManager = null; + } + + if (this.workoutRouteBuilder != null) { + this.workoutRouteBuilder.Dispose (); + this.workoutRouteBuilder = null; + } + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/SummaryInterfaceController.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/SummaryInterfaceController.cs index af597b90a..c8881af65 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/SummaryInterfaceController.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/SummaryInterfaceController.cs @@ -1,55 +1,51 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using Foundation; - using HealthKit; - using System; - using WatchKit; - - public partial class SummaryInterfaceController : WKInterfaceController - { - private HKWorkout workout; - - protected SummaryInterfaceController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } - - public override void Awake(NSObject context) - { - base.Awake(context); - - this.workout = context as HKWorkout; - this.SetTitle("Summary"); - } - - public override void WillActivate() - { - base.WillActivate(); - - if (this.workout != null) - { - var workoutTitle = this.workout.WorkoutActivityType.DisplayString(); - if (this.workout.Metadata.IndoorWorkout.HasValue) - { - var locationType = this.workout.Metadata.IndoorWorkout.Value ? LocationType.Indoor : LocationType.Outdoor; - var formatString = NSBundle.MainBundle.GetLocalizedString("LOCATION_TYPE_%@_WORKOUT_TYPE_%@"); - workoutTitle = string.Format(formatString, locationType.DisplayString(), workoutTitle); - } - - this.WorkoutLabel.SetText(workoutTitle); - this.CaloriesLabel.SetText(Utilities.Format(totalEnergyBurned: this.workout.TotalEnergyBurned)); - this.DistanceLabel.SetText(Utilities.Format(totalDistance: this.workout.TotalDistance)); - this.DurationLabel.SetText(Utilities.FormatDuration(this.workout.Duration)); - } - } - - partial void TapDoneTapped() - { - WKInterfaceController.ReloadRootPageControllers(new string[] { nameof(ConfigurationInterfaceController) }, - null, - WKPageOrientation.Vertical, - 0); - } - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using Foundation; + using HealthKit; + using System; + using WatchKit; + + public partial class SummaryInterfaceController : WKInterfaceController { + private HKWorkout workout; + + protected SummaryInterfaceController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } + + public override void Awake (NSObject context) + { + base.Awake (context); + + this.workout = context as HKWorkout; + this.SetTitle ("Summary"); + } + + public override void WillActivate () + { + base.WillActivate (); + + if (this.workout != null) { + var workoutTitle = this.workout.WorkoutActivityType.DisplayString (); + if (this.workout.Metadata.IndoorWorkout.HasValue) { + var locationType = this.workout.Metadata.IndoorWorkout.Value ? LocationType.Indoor : LocationType.Outdoor; + var formatString = NSBundle.MainBundle.GetLocalizedString ("LOCATION_TYPE_%@_WORKOUT_TYPE_%@"); + workoutTitle = string.Format (formatString, locationType.DisplayString (), workoutTitle); + } + + this.WorkoutLabel.SetText (workoutTitle); + this.CaloriesLabel.SetText (Utilities.Format (totalEnergyBurned: this.workout.TotalEnergyBurned)); + this.DistanceLabel.SetText (Utilities.Format (totalDistance: this.workout.TotalDistance)); + this.DurationLabel.SetText (Utilities.FormatDuration (this.workout.Duration)); + } + } + + partial void TapDoneTapped () + { + WKInterfaceController.ReloadRootPageControllers (new string [] { nameof (ConfigurationInterfaceController) }, + null, + WKPageOrientation.Vertical, + 0); + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/LocationTypeExtensions.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/LocationTypeExtensions.cs index f2bd335aa..54087dd13 100644 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/LocationTypeExtensions.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/LocationTypeExtensions.cs @@ -1,40 +1,36 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using HealthKit; - public static class LocationTypeExtensions - { - public static string DisplayString(this LocationType locationType) - { - var result = string.Empty; - switch (locationType) - { - case LocationType.Indoor: - result = "Indoor"; - break; - case LocationType.Outdoor: - result = "Outdoor"; - break; - } +namespace SpeedySloth.WatchAppExtension { + using HealthKit; - return result; - } + public static class LocationTypeExtensions { + public static string DisplayString (this LocationType locationType) + { + var result = string.Empty; + switch (locationType) { + case LocationType.Indoor: + result = "Indoor"; + break; + case LocationType.Outdoor: + result = "Outdoor"; + break; + } - public static HKWorkoutSessionLocationType Map(this LocationType locationType) - { - var result = default(HKWorkoutSessionLocationType); - switch (locationType) - { - case LocationType.Indoor: - result = HKWorkoutSessionLocationType.Indoor; - break; - case LocationType.Outdoor: - result = HKWorkoutSessionLocationType.Outdoor; - break; - } + return result; + } - return result; - } - } -} \ No newline at end of file + public static HKWorkoutSessionLocationType Map (this LocationType locationType) + { + var result = default (HKWorkoutSessionLocationType); + switch (locationType) { + case LocationType.Indoor: + result = HKWorkoutSessionLocationType.Indoor; + break; + case LocationType.Outdoor: + result = HKWorkoutSessionLocationType.Outdoor; + break; + } + + return result; + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/ParentConnector.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/ParentConnector.cs index 37f94a877..6dd3b766f 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/ParentConnector.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/ParentConnector.cs @@ -1,90 +1,76 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using Foundation; - using System.Collections.Generic; - using WatchConnectivity; - - /// <summary> - /// Utilities class to encapsulate messaging with parent application on iPhone - /// </summary> - public class ParentConnector : WCSessionDelegate - { - private readonly List<string> statesToSend = new List<string>(); - - private WCSession session; - - public void Send(string state) - { - if (this.session != null) - { - if (this.session.Reachable) - { - this.SendMessage(state); - } - } - else - { - if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) - { - // if here is an old delegate - dispose it - if (WCSession.DefaultSession.Delegate != null) - { - WCSession.DefaultSession.Delegate.Dispose(); - WCSession.DefaultSession.Delegate = null; - } - - WCSession.DefaultSession.Delegate = this; - this.session = WCSession.DefaultSession; - this.Send(state); - } - else - { - WCSession.DefaultSession.Delegate = this; - WCSession.DefaultSession.ActivateSession(); - this.statesToSend.Add(state); - } - } - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - this.statesToSend.Clear(); - - if (this.session != null) - { - this.session.Dispose(); - this.session = null; - } - } - - public override void ActivationDidComplete(WCSession session, WCSessionActivationState activationState, NSError error) - { - if (activationState == WCSessionActivationState.Activated) - { - this.session = session; - this.SendPending(); - } - } - - private void SendPending() - { - if (this.session != null && this.session.Reachable) - { - foreach (var state in this.statesToSend) - { - this.SendMessage(state); - } - - this.statesToSend.Clear(); - } - } - - private void SendMessage(string state) - { - var data = new NSDictionary<NSString, NSObject>(new NSString("State"), NSObject.FromObject(state)); - this.session.SendMessage(data, null, null); - } - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using Foundation; + using System.Collections.Generic; + using WatchConnectivity; + + /// <summary> + /// Utilities class to encapsulate messaging with parent application on iPhone + /// </summary> + public class ParentConnector : WCSessionDelegate { + private readonly List<string> statesToSend = new List<string> (); + + private WCSession session; + + public void Send (string state) + { + if (this.session != null) { + if (this.session.Reachable) { + this.SendMessage (state); + } + } else { + if (WCSession.DefaultSession.ActivationState == WCSessionActivationState.Activated) { + // if here is an old delegate - dispose it + if (WCSession.DefaultSession.Delegate != null) { + WCSession.DefaultSession.Delegate.Dispose (); + WCSession.DefaultSession.Delegate = null; + } + + WCSession.DefaultSession.Delegate = this; + this.session = WCSession.DefaultSession; + this.Send (state); + } else { + WCSession.DefaultSession.Delegate = this; + WCSession.DefaultSession.ActivateSession (); + this.statesToSend.Add (state); + } + } + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + this.statesToSend.Clear (); + + if (this.session != null) { + this.session.Dispose (); + this.session = null; + } + } + + public override void ActivationDidComplete (WCSession session, WCSessionActivationState activationState, NSError error) + { + if (activationState == WCSessionActivationState.Activated) { + this.session = session; + this.SendPending (); + } + } + + private void SendPending () + { + if (this.session != null && this.session.Reachable) { + foreach (var state in this.statesToSend) { + this.SendMessage (state); + } + + this.statesToSend.Clear (); + } + } + + private void SendMessage (string state) + { + var data = new NSDictionary<NSString, NSObject> (new NSString ("State"), NSObject.FromObject (state)); + this.session.SendMessage (data, null, null); + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/Utilities.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/Utilities.cs index dc3bd57fd..d8a52a940 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/Utilities.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/Utilities.cs @@ -1,105 +1,91 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using Foundation; - using HealthKit; - using System; - using System.Collections.Generic; - using System.Linq; - - public static class Utilities - { - public static string Format(HKQuantity totalDistance = null, HKQuantity totalEnergyBurned = null) - { - var result = string.Empty; - if (totalDistance != null) - { - result = Format(totalDistance: totalDistance.GetDoubleValue(HKUnit.Meter)); - } - else if (totalEnergyBurned != null) - { - result = Format(totalEnergyBurned: totalEnergyBurned.GetDoubleValue(HKUnit.Kilocalorie)); - } - - return result; - } - - public static string Format(double totalDistance = -1d, double totalEnergyBurned = -1d) - { - var result = string.Empty; - if (totalDistance != -1d) - { - result = FormatDistance(totalDistance); - } - else if (totalEnergyBurned != -1d) - { - result = FormatEnergy(totalEnergyBurned); - } - - return result; - } - - private static string FormatDistance(double distance) - { - var metersString = NSBundle.MainBundle.GetLocalizedString("Meters"); - var formatString = NSBundle.MainBundle.GetLocalizedString("VALUE_%@_UNIT_%@"); - - return string.Format(formatString, distance, metersString); - } - - private static string FormatEnergy(double energyBurned) - { - var caloriesString = NSBundle.MainBundle.GetLocalizedString("Calories"); - var formatString = NSBundle.MainBundle.GetLocalizedString("VALUE_%@_UNIT_%@"); - - return string.Format(formatString, energyBurned, caloriesString); - } - - public static string FormatDuration(double duration) - { - var durationFormatter = new NSDateComponentsFormatter - { - UnitsStyle = NSDateComponentsFormatterUnitsStyle.Positional, - ZeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.Pad, - AllowedUnits = NSCalendarUnit.Second | NSCalendarUnit.Minute | NSCalendarUnit.Hour, - }; - - return durationFormatter.StringFromTimeInterval(duration) ?? string.Empty; - } - - public static double ComputeDurationOfWorkout(List<HKWorkoutEvent> workoutEvents, NSDate startDate, NSDate endDate) - { - var duration = 0d; - - if (startDate != null) - { - if (workoutEvents != null) - { - var lastDate = startDate; - - var events = workoutEvents.Where(@event => @event.Type == HKWorkoutEventType.Pause || @event.Type == HKWorkoutEventType.Resume).ToList(); - foreach (var @event in events) - { - switch (@event.Type) - { - case HKWorkoutEventType.Pause: - duration += ((DateTime)@event.DateInterval.StartDate - ((DateTime)lastDate)).TotalSeconds; - break; - case HKWorkoutEventType.Resume: - lastDate = @event.DateInterval.StartDate; - break; - } - } - - if (events.LastOrDefault()?.Type != HKWorkoutEventType.Pause) - { - var end = endDate ?? new NSDate(); - duration += ((DateTime)end - ((DateTime)lastDate)).TotalSeconds; - } - } - } - - return duration; - } - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using Foundation; + using HealthKit; + using System; + using System.Collections.Generic; + using System.Linq; + + public static class Utilities { + public static string Format (HKQuantity totalDistance = null, HKQuantity totalEnergyBurned = null) + { + var result = string.Empty; + if (totalDistance != null) { + result = Format (totalDistance: totalDistance.GetDoubleValue (HKUnit.Meter)); + } else if (totalEnergyBurned != null) { + result = Format (totalEnergyBurned: totalEnergyBurned.GetDoubleValue (HKUnit.Kilocalorie)); + } + + return result; + } + + public static string Format (double totalDistance = -1d, double totalEnergyBurned = -1d) + { + var result = string.Empty; + if (totalDistance != -1d) { + result = FormatDistance (totalDistance); + } else if (totalEnergyBurned != -1d) { + result = FormatEnergy (totalEnergyBurned); + } + + return result; + } + + private static string FormatDistance (double distance) + { + var metersString = NSBundle.MainBundle.GetLocalizedString ("Meters"); + var formatString = NSBundle.MainBundle.GetLocalizedString ("VALUE_%@_UNIT_%@"); + + return string.Format (formatString, distance, metersString); + } + + private static string FormatEnergy (double energyBurned) + { + var caloriesString = NSBundle.MainBundle.GetLocalizedString ("Calories"); + var formatString = NSBundle.MainBundle.GetLocalizedString ("VALUE_%@_UNIT_%@"); + + return string.Format (formatString, energyBurned, caloriesString); + } + + public static string FormatDuration (double duration) + { + var durationFormatter = new NSDateComponentsFormatter { + UnitsStyle = NSDateComponentsFormatterUnitsStyle.Positional, + ZeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehavior.Pad, + AllowedUnits = NSCalendarUnit.Second | NSCalendarUnit.Minute | NSCalendarUnit.Hour, + }; + + return durationFormatter.StringFromTimeInterval (duration) ?? string.Empty; + } + + public static double ComputeDurationOfWorkout (List<HKWorkoutEvent> workoutEvents, NSDate startDate, NSDate endDate) + { + var duration = 0d; + + if (startDate != null) { + if (workoutEvents != null) { + var lastDate = startDate; + + var events = workoutEvents.Where (@event => @event.Type == HKWorkoutEventType.Pause || @event.Type == HKWorkoutEventType.Resume).ToList (); + foreach (var @event in events) { + switch (@event.Type) { + case HKWorkoutEventType.Pause: + duration += ((DateTime) @event.DateInterval.StartDate - ((DateTime) lastDate)).TotalSeconds; + break; + case HKWorkoutEventType.Resume: + lastDate = @event.DateInterval.StartDate; + break; + } + } + + if (events.LastOrDefault ()?.Type != HKWorkoutEventType.Pause) { + var end = endDate ?? new NSDate (); + duration += ((DateTime) end - ((DateTime) lastDate)).TotalSeconds; + } + } + } + + return duration; + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/WorkoutTypeExtensions.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/WorkoutTypeExtensions.cs index ebd0868e7..f7e94f2c1 100644 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/WorkoutTypeExtensions.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/Utilities/WorkoutTypeExtensions.cs @@ -1,71 +1,66 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using HealthKit; - public static class WorkoutTypeExtensions - { - public static string DisplayString(this HKWorkoutActivityType workoutActivityType) - { - var result = string.Empty; - switch (workoutActivityType) - { - case HKWorkoutActivityType.Hiking: - result = "Hiking"; - break; - case HKWorkoutActivityType.Running: - result = "Running"; - break; - case HKWorkoutActivityType.Walking: - result = "Walking"; - break; - default: - break; - } +namespace SpeedySloth.WatchAppExtension { + using HealthKit; - return result; - } + public static class WorkoutTypeExtensions { + public static string DisplayString (this HKWorkoutActivityType workoutActivityType) + { + var result = string.Empty; + switch (workoutActivityType) { + case HKWorkoutActivityType.Hiking: + result = "Hiking"; + break; + case HKWorkoutActivityType.Running: + result = "Running"; + break; + case HKWorkoutActivityType.Walking: + result = "Walking"; + break; + default: + break; + } - public static string DisplayString(this WorkoutType workoutType) - { - var result = string.Empty; - switch (workoutType) - { - case WorkoutType.Hiking: - result = "Hiking"; - break; - case WorkoutType.Running: - result = "Running"; - break; - case WorkoutType.Walking: - result = "Walking"; - break; - default: - break; - } + return result; + } - return result; - } + public static string DisplayString (this WorkoutType workoutType) + { + var result = string.Empty; + switch (workoutType) { + case WorkoutType.Hiking: + result = "Hiking"; + break; + case WorkoutType.Running: + result = "Running"; + break; + case WorkoutType.Walking: + result = "Walking"; + break; + default: + break; + } - public static HKWorkoutActivityType Map(this WorkoutType workoutType) - { - var result = default(HKWorkoutActivityType); - switch (workoutType) - { - case WorkoutType.Hiking: - result = HKWorkoutActivityType.Hiking; - break; - case WorkoutType.Running: - result = HKWorkoutActivityType.Running; - break; - case WorkoutType.Walking: - result = HKWorkoutActivityType.Walking; - break; - default: - break; - } + return result; + } - return result; - } - } -} \ No newline at end of file + public static HKWorkoutActivityType Map (this WorkoutType workoutType) + { + var result = default (HKWorkoutActivityType); + switch (workoutType) { + case WorkoutType.Hiking: + result = HKWorkoutActivityType.Hiking; + break; + case WorkoutType.Running: + result = HKWorkoutActivityType.Running; + break; + case WorkoutType.Walking: + result = HKWorkoutActivityType.Walking; + break; + default: + break; + } + + return result; + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/WorkoutInterfaceController.cs b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/WorkoutInterfaceController.cs index daaf2066d..7a3ba5e79 100755 --- a/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/WorkoutInterfaceController.cs +++ b/watchOS/SpeedySloth/SpeedySloth.WatchAppExtension/WorkoutInterfaceController.cs @@ -1,269 +1,244 @@ - -namespace SpeedySloth.WatchAppExtension -{ - using CoreFoundation; - using Foundation; - using HealthKit; - using System; - using System.Collections.Generic; - using WatchKit; - - public partial class WorkoutInterfaceController : WKInterfaceController, IHKWorkoutSessionDelegate - { - private readonly HealthStoreManager healthStoreManager = new HealthStoreManager(); - - private readonly ParentConnector parentConnector = new ParentConnector(); - - private HKWorkoutSession workoutSession; - - private NSDate startDate; - - private NSDate endDate; - - private NSTimer timer; - - protected WorkoutInterfaceController(IntPtr handle) : base(handle) - { - // Note: this .ctor should not contain any initialization logic. - } - - protected bool IsPaused => this.workoutSession.State == HKWorkoutSessionState.Paused; - - public override void Awake(NSObject context) - { - base.Awake(context); - - // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); - - var workoutConfiguration = context as HKWorkoutConfiguration; - if (workoutConfiguration == null) - { - throw new ArgumentException("The 'context' is not a HKWorkoutConfiguration", nameof(context)); - } - - // create a workout session with the workout configuration - NSError error; - this.workoutSession = new HKWorkoutSession(workoutConfiguration, out error); - if (error == null) - { - // start a workout session - this.workoutSession.Delegate = this; - this.healthStoreManager.Start(this.workoutSession); - } - else - { - throw new Exception(error.Description ?? "Unknown exception"); - } - } - - protected override void Dispose(bool disposing) - { - base.Dispose(disposing); - this.workoutSession.Dispose(); - this.parentConnector.Dispose(); - this.healthStoreManager.Dispose(); - } - - #region Actions - - partial void DidTapPauseResumeButton() - { - this.RequestPauseOrResume(); - } - - partial void DidTapMarkerButton() - { - var markerEvent = HKWorkoutEvent.Create(HKWorkoutEventType.Marker, new NSDateInterval(), (HKMetadata)null); - this.healthStoreManager.WorkoutEvents.Add(markerEvent); - this.NotifyEvent(); - } - - partial void DidTapStopButton() - { - this.healthStoreManager.End(this.workoutSession); - } - - #endregion - - #region UI - - private void UpdateLabels() - { - this.CaloriesLabel.SetText(Utilities.Format(totalEnergyBurned: this.healthStoreManager.TotalEnergyBurned)); - this.DistanceLabel.SetText(Utilities.Format(totalDistance: this.healthStoreManager.TotalDistance)); - - var events = new List<HKWorkoutEvent>(this.healthStoreManager.WorkoutEvents); - var duration = Utilities.ComputeDurationOfWorkout(events, this.startDate, this.endDate); - this.DurationLabel.SetText(Utilities.FormatDuration(duration)); - } - - private void UpdateStates() - { - switch (this.workoutSession.State) - { - case HKWorkoutSessionState.NotStarted: - this.SetTitle(NSBundle.MainBundle.GetLocalizedString("Starting")); - break; - case HKWorkoutSessionState.Running: - this.SetTitle(this.workoutSession.WorkoutConfiguration.ActivityType.DisplayString()); - this.parentConnector.Send("running"); - this.PauseResumeButton.SetTitle(NSBundle.MainBundle.GetLocalizedString("Pause")); - break; - case HKWorkoutSessionState.Ended: - this.SetTitle(NSBundle.MainBundle.GetLocalizedString("Ended")); - this.parentConnector.Send("ended"); - break; - case HKWorkoutSessionState.Paused: - this.SetTitle(NSBundle.MainBundle.GetLocalizedString("Paused")); - this.parentConnector.Send("paused"); - this.PauseResumeButton.SetTitle(NSBundle.MainBundle.GetLocalizedString("Resume")); - break; - default: - break; - } - } - - private void NotifyEvent() - { - WKInterfaceDevice.CurrentDevice.PlayHaptic(WKHapticType.Notification); - - this.MarkerLabel.SetAlpha(1); - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.AnimateWithDuration(1d, () => { this.MarkerLabel.SetAlpha(0); }); - }); - } - - #endregion - - #region Data Accumulation - - private void StartAccumulatingData() - { - this.healthStoreManager.StartWalkingRunningQuery(this.startDate, (quantitySamples) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (!this.IsPaused) - { - this.healthStoreManager.ProcessWalkingRunningSamples(quantitySamples); - this.UpdateLabels(); - } - }); - }); - - this.healthStoreManager.StartActiveEnergyBurnedQuery(this.startDate, (quantitySamples) => - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - if (!this.IsPaused) - { - this.healthStoreManager.ProcessActiveEnergySamples(quantitySamples); - this.UpdateLabels(); - } - }); - }); - - if (this.workoutSession.WorkoutConfiguration.LocationType == HKWorkoutSessionLocationType.Outdoor) - { - this.healthStoreManager.StartAccumulatingLocationData(); - } - } - - private void StopAccumulatingData() - { - this.healthStoreManager.StopAccumulatingData(); - } - - #endregion - - #region Timer - - private void StartTimer() - { - this.timer = NSTimer.CreateScheduledTimer(1, true, (sender) => - { - this.UpdateLabels(); - }); - } - - private void StopTimer() - { - if (this.timer != null) - { - this.timer.Invalidate(); - this.timer.Dispose(); - this.timer = null; - } - } - - #endregion - - #region HKWorkoutSessionDelegate - - [Export("workoutSession:didFailWithError:")] - public void DidFail(HKWorkoutSession workoutSession, NSError error) - { - this.StopTimer(); - this.workoutSession.Dispose(); - Console.WriteLine($"workout session failed with an error: ({error})"); - } - - [Export("workoutSession:didChangeToState:fromState:date:")] - public void DidChangeToState(HKWorkoutSession workoutSession, HKWorkoutSessionState toState, HKWorkoutSessionState fromState, NSDate date) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.HandleWorkoutSessionState(toState, fromState); - }); - } - - [Export("workoutSession:didGenerateEvent:")] - public void WorkoutSession(HKWorkoutSession workoutSession, HKWorkoutEvent @event) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.healthStoreManager.WorkoutEvents.Add(@event); - }); - } - - private void HandleWorkoutSessionState(HKWorkoutSessionState toState, HKWorkoutSessionState fromState) - { - if (fromState == HKWorkoutSessionState.NotStarted && toState == HKWorkoutSessionState.Running) - { - this.startDate = new NSDate(); - this.StartTimer(); - this.StartAccumulatingData(); - } - else if (toState == HKWorkoutSessionState.Ended) - { - this.StopAccumulatingData(); - this.endDate = new NSDate(); - this.StopTimer(); - this.healthStoreManager.SaveWorkout(workoutSession, this.startDate, this.endDate); - } - - this.UpdateLabels(); - this.UpdateStates(); - } - - #endregion - - #region Convenience - - private void RequestPauseOrResume() - { - if (this.IsPaused) - { - this.healthStoreManager.Resume(this.workoutSession); - } - else - { - this.healthStoreManager.Pause(this.workoutSession); - } - } - - #endregion - } -} \ No newline at end of file + +namespace SpeedySloth.WatchAppExtension { + using CoreFoundation; + using Foundation; + using HealthKit; + using System; + using System.Collections.Generic; + using WatchKit; + + public partial class WorkoutInterfaceController : WKInterfaceController, IHKWorkoutSessionDelegate { + private readonly HealthStoreManager healthStoreManager = new HealthStoreManager (); + + private readonly ParentConnector parentConnector = new ParentConnector (); + + private HKWorkoutSession workoutSession; + + private NSDate startDate; + + private NSDate endDate; + + private NSTimer timer; + + protected WorkoutInterfaceController (IntPtr handle) : base (handle) + { + // Note: this .ctor should not contain any initialization logic. + } + + protected bool IsPaused => this.workoutSession.State == HKWorkoutSessionState.Paused; + + public override void Awake (NSObject context) + { + base.Awake (context); + + // Configure interface objects here. + Console.WriteLine ("{0} awake with context", this); + + var workoutConfiguration = context as HKWorkoutConfiguration; + if (workoutConfiguration == null) { + throw new ArgumentException ("The 'context' is not a HKWorkoutConfiguration", nameof (context)); + } + + // create a workout session with the workout configuration + NSError error; + this.workoutSession = new HKWorkoutSession (workoutConfiguration, out error); + if (error == null) { + // start a workout session + this.workoutSession.Delegate = this; + this.healthStoreManager.Start (this.workoutSession); + } else { + throw new Exception (error.Description ?? "Unknown exception"); + } + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + this.workoutSession.Dispose (); + this.parentConnector.Dispose (); + this.healthStoreManager.Dispose (); + } + + #region Actions + + partial void DidTapPauseResumeButton () + { + this.RequestPauseOrResume (); + } + + partial void DidTapMarkerButton () + { + var markerEvent = HKWorkoutEvent.Create (HKWorkoutEventType.Marker, new NSDateInterval (), (HKMetadata) null); + this.healthStoreManager.WorkoutEvents.Add (markerEvent); + this.NotifyEvent (); + } + + partial void DidTapStopButton () + { + this.healthStoreManager.End (this.workoutSession); + } + + #endregion + + #region UI + + private void UpdateLabels () + { + this.CaloriesLabel.SetText (Utilities.Format (totalEnergyBurned: this.healthStoreManager.TotalEnergyBurned)); + this.DistanceLabel.SetText (Utilities.Format (totalDistance: this.healthStoreManager.TotalDistance)); + + var events = new List<HKWorkoutEvent> (this.healthStoreManager.WorkoutEvents); + var duration = Utilities.ComputeDurationOfWorkout (events, this.startDate, this.endDate); + this.DurationLabel.SetText (Utilities.FormatDuration (duration)); + } + + private void UpdateStates () + { + switch (this.workoutSession.State) { + case HKWorkoutSessionState.NotStarted: + this.SetTitle (NSBundle.MainBundle.GetLocalizedString ("Starting")); + break; + case HKWorkoutSessionState.Running: + this.SetTitle (this.workoutSession.WorkoutConfiguration.ActivityType.DisplayString ()); + this.parentConnector.Send ("running"); + this.PauseResumeButton.SetTitle (NSBundle.MainBundle.GetLocalizedString ("Pause")); + break; + case HKWorkoutSessionState.Ended: + this.SetTitle (NSBundle.MainBundle.GetLocalizedString ("Ended")); + this.parentConnector.Send ("ended"); + break; + case HKWorkoutSessionState.Paused: + this.SetTitle (NSBundle.MainBundle.GetLocalizedString ("Paused")); + this.parentConnector.Send ("paused"); + this.PauseResumeButton.SetTitle (NSBundle.MainBundle.GetLocalizedString ("Resume")); + break; + default: + break; + } + } + + private void NotifyEvent () + { + WKInterfaceDevice.CurrentDevice.PlayHaptic (WKHapticType.Notification); + + this.MarkerLabel.SetAlpha (1); + DispatchQueue.MainQueue.DispatchAsync (() => { + this.AnimateWithDuration (1d, () => { this.MarkerLabel.SetAlpha (0); }); + }); + } + + #endregion + + #region Data Accumulation + + private void StartAccumulatingData () + { + this.healthStoreManager.StartWalkingRunningQuery (this.startDate, (quantitySamples) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (!this.IsPaused) { + this.healthStoreManager.ProcessWalkingRunningSamples (quantitySamples); + this.UpdateLabels (); + } + }); + }); + + this.healthStoreManager.StartActiveEnergyBurnedQuery (this.startDate, (quantitySamples) => { + DispatchQueue.MainQueue.DispatchAsync (() => { + if (!this.IsPaused) { + this.healthStoreManager.ProcessActiveEnergySamples (quantitySamples); + this.UpdateLabels (); + } + }); + }); + + if (this.workoutSession.WorkoutConfiguration.LocationType == HKWorkoutSessionLocationType.Outdoor) { + this.healthStoreManager.StartAccumulatingLocationData (); + } + } + + private void StopAccumulatingData () + { + this.healthStoreManager.StopAccumulatingData (); + } + + #endregion + + #region Timer + + private void StartTimer () + { + this.timer = NSTimer.CreateScheduledTimer (1, true, (sender) => { + this.UpdateLabels (); + }); + } + + private void StopTimer () + { + if (this.timer != null) { + this.timer.Invalidate (); + this.timer.Dispose (); + this.timer = null; + } + } + + #endregion + + #region HKWorkoutSessionDelegate + + [Export ("workoutSession:didFailWithError:")] + public void DidFail (HKWorkoutSession workoutSession, NSError error) + { + this.StopTimer (); + this.workoutSession.Dispose (); + Console.WriteLine ($"workout session failed with an error: ({error})"); + } + + [Export ("workoutSession:didChangeToState:fromState:date:")] + public void DidChangeToState (HKWorkoutSession workoutSession, HKWorkoutSessionState toState, HKWorkoutSessionState fromState, NSDate date) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.HandleWorkoutSessionState (toState, fromState); + }); + } + + [Export ("workoutSession:didGenerateEvent:")] + public void WorkoutSession (HKWorkoutSession workoutSession, HKWorkoutEvent @event) + { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.healthStoreManager.WorkoutEvents.Add (@event); + }); + } + + private void HandleWorkoutSessionState (HKWorkoutSessionState toState, HKWorkoutSessionState fromState) + { + if (fromState == HKWorkoutSessionState.NotStarted && toState == HKWorkoutSessionState.Running) { + this.startDate = new NSDate (); + this.StartTimer (); + this.StartAccumulatingData (); + } else if (toState == HKWorkoutSessionState.Ended) { + this.StopAccumulatingData (); + this.endDate = new NSDate (); + this.StopTimer (); + this.healthStoreManager.SaveWorkout (workoutSession, this.startDate, this.endDate); + } + + this.UpdateLabels (); + this.UpdateStates (); + } + + #endregion + + #region Convenience + + private void RequestPauseOrResume () + { + if (this.IsPaused) { + this.healthStoreManager.Resume (this.workoutSession); + } else { + this.healthStoreManager.Pause (this.workoutSession); + } + } + + #endregion + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth/AppDelegate.cs b/watchOS/SpeedySloth/SpeedySloth/AppDelegate.cs index 4f6a49982..05c520405 100755 --- a/watchOS/SpeedySloth/SpeedySloth/AppDelegate.cs +++ b/watchOS/SpeedySloth/SpeedySloth/AppDelegate.cs @@ -1,51 +1,46 @@ - -namespace SpeedySloth -{ - using CoreLocation; - using Foundation; - using HealthKit; - using System; - using UIKit; - - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { - private readonly CLLocationManager locationManager = new CLLocationManager(); - - public override UIWindow Window { get; set; } - - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) - { - this.RequestAccessToHealthKit(); - this.RequestLocationServices(); - - return true; - } - - private void RequestAccessToHealthKit() - { - var healthStore = new HKHealthStore(); - - var types = new NSSet(HKObjectType.GetWorkoutType(), - HKSeriesType.WorkoutRouteType, - HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned), - HKQuantityType.Create(HKQuantityTypeIdentifier.DistanceWalkingRunning)); - - healthStore.RequestAuthorizationToShare(types, types, (isSuccess, error) => - { - if (!isSuccess) - { - Console.WriteLine(error?.LocalizedDescription ?? ""); - } - }); - } - - private void RequestLocationServices() - { - if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) - { - this.locationManager.RequestAlwaysAuthorization(); - } - } - } -} \ No newline at end of file + +namespace SpeedySloth { + using CoreLocation; + using Foundation; + using HealthKit; + using System; + using UIKit; + + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { + private readonly CLLocationManager locationManager = new CLLocationManager (); + + public override UIWindow Window { get; set; } + + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + { + this.RequestAccessToHealthKit (); + this.RequestLocationServices (); + + return true; + } + + private void RequestAccessToHealthKit () + { + var healthStore = new HKHealthStore (); + + var types = new NSSet (HKObjectType.GetWorkoutType (), + HKSeriesType.WorkoutRouteType, + HKQuantityType.Create (HKQuantityTypeIdentifier.ActiveEnergyBurned), + HKQuantityType.Create (HKQuantityTypeIdentifier.DistanceWalkingRunning)); + + healthStore.RequestAuthorizationToShare (types, types, (isSuccess, error) => { + if (!isSuccess) { + Console.WriteLine (error?.LocalizedDescription ?? ""); + } + }); + } + + private void RequestLocationServices () + { + if (CLLocationManager.Status == CLAuthorizationStatus.NotDetermined) { + this.locationManager.RequestAlwaysAuthorization (); + } + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth/ConfigurationViewController.cs b/watchOS/SpeedySloth/SpeedySloth/ConfigurationViewController.cs index 330f104d9..1d506dd74 100755 --- a/watchOS/SpeedySloth/SpeedySloth/ConfigurationViewController.cs +++ b/watchOS/SpeedySloth/SpeedySloth/ConfigurationViewController.cs @@ -1,105 +1,94 @@ - -namespace SpeedySloth -{ - using Foundation; - using HealthKit; - using SpeedySloth.WatchAppExtension; - using System; - using System.Collections.Generic; - using UIKit; - - public partial class ConfigurationViewController : UIViewController, IUIPickerViewDelegate, IUIPickerViewDataSource - { - private readonly List<WorkoutType> activityTypes = new List<WorkoutType> { WorkoutType.Walking, WorkoutType.Running, WorkoutType.Hiking }; - - private readonly List<LocationType> locationTypes = new List<LocationType> { LocationType.Indoor, LocationType.Outdoor }; - - public ConfigurationViewController(IntPtr handle) : base(handle) { } - - public override void ViewDidLoad() - { - base.ViewDidLoad(); - - this.ActivityTypePicker.Delegate = this; - this.ActivityTypePicker.DataSource = this; - - this.LocationTypePicker.Delegate = this; - this.LocationTypePicker.DataSource = this; - } - - #region UIPickerViewDataSource - - public nint GetComponentCount(UIPickerView pickerView) - { - return 1; - } - - public nint GetRowsInComponent(UIPickerView pickerView, nint component) - { - var result = 0; - if (pickerView == this.ActivityTypePicker) - { - result = this.activityTypes.Count; - } - else if (pickerView == this.LocationTypePicker) - { - result = this.locationTypes.Count; - } - - return result; - } - - #endregion - - #region UIPickerViewDelegate - - [Export("pickerView:titleForRow:forComponent:")] - public string GetTitle(UIPickerView pickerView, nint row, nint component) - { - string result = null; - if (pickerView == this.ActivityTypePicker) - { - result = this.activityTypes[(int)row].DisplayString(); - } - else if (pickerView == this.LocationTypePicker) - { - result = this.locationTypes[(int)row].DisplayString(); - } - - return result; - } - - #endregion - - [Action("UnwindToConfigurationWithSegue:")] - public void UnwindToConfigurationWithSegue(UIStoryboardSegue segue) { } - - #region Segues - - public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender) - { - if (segue.Identifier == "presentWorkoutSegue") - { - this.PrepareForPresentWorkoutSegue(segue); - } - } - - private void PrepareForPresentWorkoutSegue(UIStoryboardSegue segue) - { - var selectedActivityType = this.activityTypes[(int)this.ActivityTypePicker.SelectedRowInComponent(0)]; - var selectedLocationType = this.locationTypes[(int)this.LocationTypePicker.SelectedRowInComponent(0)]; - - var workoutViewController = segue.DestinationViewController as WorkoutViewController; - if (workoutViewController != null) - { - workoutViewController.Configuration = new HKWorkoutConfiguration - { - ActivityType = selectedActivityType.Map(), - LocationType = selectedLocationType.Map(), - }; - } - } - - #endregion - } -} \ No newline at end of file + +namespace SpeedySloth { + using Foundation; + using HealthKit; + using SpeedySloth.WatchAppExtension; + using System; + using System.Collections.Generic; + using UIKit; + + public partial class ConfigurationViewController : UIViewController, IUIPickerViewDelegate, IUIPickerViewDataSource { + private readonly List<WorkoutType> activityTypes = new List<WorkoutType> { WorkoutType.Walking, WorkoutType.Running, WorkoutType.Hiking }; + + private readonly List<LocationType> locationTypes = new List<LocationType> { LocationType.Indoor, LocationType.Outdoor }; + + public ConfigurationViewController (IntPtr handle) : base (handle) { } + + public override void ViewDidLoad () + { + base.ViewDidLoad (); + + this.ActivityTypePicker.Delegate = this; + this.ActivityTypePicker.DataSource = this; + + this.LocationTypePicker.Delegate = this; + this.LocationTypePicker.DataSource = this; + } + + #region UIPickerViewDataSource + + public nint GetComponentCount (UIPickerView pickerView) + { + return 1; + } + + public nint GetRowsInComponent (UIPickerView pickerView, nint component) + { + var result = 0; + if (pickerView == this.ActivityTypePicker) { + result = this.activityTypes.Count; + } else if (pickerView == this.LocationTypePicker) { + result = this.locationTypes.Count; + } + + return result; + } + + #endregion + + #region UIPickerViewDelegate + + [Export ("pickerView:titleForRow:forComponent:")] + public string GetTitle (UIPickerView pickerView, nint row, nint component) + { + string result = null; + if (pickerView == this.ActivityTypePicker) { + result = this.activityTypes [(int) row].DisplayString (); + } else if (pickerView == this.LocationTypePicker) { + result = this.locationTypes [(int) row].DisplayString (); + } + + return result; + } + + #endregion + + [Action ("UnwindToConfigurationWithSegue:")] + public void UnwindToConfigurationWithSegue (UIStoryboardSegue segue) { } + + #region Segues + + public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) + { + if (segue.Identifier == "presentWorkoutSegue") { + this.PrepareForPresentWorkoutSegue (segue); + } + } + + private void PrepareForPresentWorkoutSegue (UIStoryboardSegue segue) + { + var selectedActivityType = this.activityTypes [(int) this.ActivityTypePicker.SelectedRowInComponent (0)]; + var selectedLocationType = this.locationTypes [(int) this.LocationTypePicker.SelectedRowInComponent (0)]; + + var workoutViewController = segue.DestinationViewController as WorkoutViewController; + if (workoutViewController != null) { + workoutViewController.Configuration = new HKWorkoutConfiguration { + ActivityType = selectedActivityType.Map (), + LocationType = selectedLocationType.Map (), + }; + } + } + + #endregion + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth/Main.cs b/watchOS/SpeedySloth/SpeedySloth/Main.cs index b1d1f2182..0b51c9fc3 100755 --- a/watchOS/SpeedySloth/SpeedySloth/Main.cs +++ b/watchOS/SpeedySloth/SpeedySloth/Main.cs @@ -1,16 +1,14 @@ - -namespace SpeedySloth -{ - using UIKit; - - public class Application - { - // This is the main entry point of the application. - static void Main(string[] args) - { - // if you want to use a different Application Delegate class from "AppDelegate" - // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); - } - } -} \ No newline at end of file + +namespace SpeedySloth { + using UIKit; + + public class Application { + // This is the main entry point of the application. + static void Main (string [] args) + { + // if you want to use a different Application Delegate class from "AppDelegate" + // you can specify it here. + UIApplication.Main (args, null, "AppDelegate"); + } + } +} diff --git a/watchOS/SpeedySloth/SpeedySloth/WorkoutViewController.cs b/watchOS/SpeedySloth/SpeedySloth/WorkoutViewController.cs index a807da2df..8a4f446bd 100755 --- a/watchOS/SpeedySloth/SpeedySloth/WorkoutViewController.cs +++ b/watchOS/SpeedySloth/SpeedySloth/WorkoutViewController.cs @@ -1,142 +1,123 @@ - -namespace SpeedySloth -{ - using CoreFoundation; - using Foundation; - using HealthKit; - using System; - using UIKit; - using WatchConnectivity; - - public partial class WorkoutViewController : UIViewController, IWCSessionDelegate - { - private readonly HKHealthStore healthStore = new HKHealthStore(); - - private Action<WCSession> sessionActivationCompletion; - - public WorkoutViewController(IntPtr handle) : base(handle) { } - - public HKWorkoutConfiguration Configuration { get; set; } - - public override void ViewDidAppear(bool animated) - { - base.ViewDidAppear(animated); - this.StartWatchApp(); - } - - public override void ViewDidDisappear(bool animated) - { - this.healthStore.Dispose(); - base.ViewDidDisappear(animated); - } - - #region Convenience - - private void StartWatchApp() - { - if (this.Configuration != null) - { - this.GetActiveWCSession((wcSession) => - { - if (wcSession.ActivationState == WCSessionActivationState.Activated && wcSession.WatchAppInstalled) - { - this.healthStore.StartWatchApp(this.Configuration, (isSucces, error) => - { - if (!isSucces) - { - Console.WriteLine($"starting watch app failed with error: ({error.Description})"); - } - }); - } - }); - } - } - - public void GetActiveWCSession(Action<WCSession> completion) - { - if (WCSession.IsSupported) - { - var wcSession = WCSession.DefaultSession; - wcSession.Delegate = this; - - switch (wcSession.ActivationState) - { - case WCSessionActivationState.NotActivated: - case WCSessionActivationState.Inactive: - wcSession.ActivateSession(); - this.sessionActivationCompletion = completion; - break; - case WCSessionActivationState.Activated: - completion(wcSession); - break; - default: - break; - } - } - else - { - // ...Alert the user that their iOS device does not support watch connectivity - throw new NotSupportedException("watch connectivity session nor supported"); - } - } - - public void UpdateSessionState(string state) - { - if (state == "ended") - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - this.DismissModalViewController(true); - }); - } - else - { - this.WorkoutSessionState.Text = state; - } - } - - #endregion - - #region WCSessionDelegate - - [Export("session:activationDidCompleteWithState:error:")] - public void ActivationDidComplete(WCSession session, WCSessionActivationState activationState, NSError error) - { - if (activationState == WCSessionActivationState.Activated) - { - var activationCompletion = this.sessionActivationCompletion; - if (activationCompletion != null) - { - activationCompletion(session); - this.sessionActivationCompletion = null; - } - } - } - - [Export("session:didReceiveMessage:")] - public void DidReceiveMessage(WCSession session, Foundation.NSDictionary<Foundation.NSString, Foundation.NSObject> message) - { - NSObject state; - if (message.TryGetValue(new NSString("State"), out state)) - { - DispatchQueue.MainQueue.DispatchAsync(() => - { - var @string = state as NSString; - this.UpdateSessionState(@string); - }); - } - } - - [Export("sessionDidBecomeInactive:")] - public void DidBecomeInactive(WCSession session) - { - } - - [Export("sessionDidDeactivate:")] - public void DidDeactivate(WCSession session) - { - } - - #endregion - } -} \ No newline at end of file + +namespace SpeedySloth { + using CoreFoundation; + using Foundation; + using HealthKit; + using System; + using UIKit; + using WatchConnectivity; + + public partial class WorkoutViewController : UIViewController, IWCSessionDelegate { + private readonly HKHealthStore healthStore = new HKHealthStore (); + + private Action<WCSession> sessionActivationCompletion; + + public WorkoutViewController (IntPtr handle) : base (handle) { } + + public HKWorkoutConfiguration Configuration { get; set; } + + public override void ViewDidAppear (bool animated) + { + base.ViewDidAppear (animated); + this.StartWatchApp (); + } + + public override void ViewDidDisappear (bool animated) + { + this.healthStore.Dispose (); + base.ViewDidDisappear (animated); + } + + #region Convenience + + private void StartWatchApp () + { + if (this.Configuration != null) { + this.GetActiveWCSession ((wcSession) => { + if (wcSession.ActivationState == WCSessionActivationState.Activated && wcSession.WatchAppInstalled) { + this.healthStore.StartWatchApp (this.Configuration, (isSucces, error) => { + if (!isSucces) { + Console.WriteLine ($"starting watch app failed with error: ({error.Description})"); + } + }); + } + }); + } + } + + public void GetActiveWCSession (Action<WCSession> completion) + { + if (WCSession.IsSupported) { + var wcSession = WCSession.DefaultSession; + wcSession.Delegate = this; + + switch (wcSession.ActivationState) { + case WCSessionActivationState.NotActivated: + case WCSessionActivationState.Inactive: + wcSession.ActivateSession (); + this.sessionActivationCompletion = completion; + break; + case WCSessionActivationState.Activated: + completion (wcSession); + break; + default: + break; + } + } else { + // ...Alert the user that their iOS device does not support watch connectivity + throw new NotSupportedException ("watch connectivity session nor supported"); + } + } + + public void UpdateSessionState (string state) + { + if (state == "ended") { + DispatchQueue.MainQueue.DispatchAsync (() => { + this.DismissModalViewController (true); + }); + } else { + this.WorkoutSessionState.Text = state; + } + } + + #endregion + + #region WCSessionDelegate + + [Export ("session:activationDidCompleteWithState:error:")] + public void ActivationDidComplete (WCSession session, WCSessionActivationState activationState, NSError error) + { + if (activationState == WCSessionActivationState.Activated) { + var activationCompletion = this.sessionActivationCompletion; + if (activationCompletion != null) { + activationCompletion (session); + this.sessionActivationCompletion = null; + } + } + } + + [Export ("session:didReceiveMessage:")] + public void DidReceiveMessage (WCSession session, Foundation.NSDictionary<Foundation.NSString, Foundation.NSObject> message) + { + NSObject state; + if (message.TryGetValue (new NSString ("State"), out state)) { + DispatchQueue.MainQueue.DispatchAsync (() => { + var @string = state as NSString; + this.UpdateSessionState (@string); + }); + } + } + + [Export ("sessionDidBecomeInactive:")] + public void DidBecomeInactive (WCSession session) + { + } + + [Export ("sessionDidDeactivate:")] + public void DidDeactivate (WCSession session) + { + } + + #endregion + } +} diff --git a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/ExtensionDelegate.cs b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/ExtensionDelegate.cs index 617015f91..81d0589de 100644 --- a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/ExtensionDelegate.cs +++ b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/ExtensionDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using WatchKit; -namespace WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { +namespace WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { } } diff --git a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/InterfaceController.cs b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/InterfaceController.cs index 2d7e104ff..860d8a513 100644 --- a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/InterfaceController.cs +++ b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension/InterfaceController.cs @@ -1,12 +1,10 @@ -using System; +using System; using Foundation; using WatchKit; -namespace WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension -{ - public partial class InterfaceController : WKInterfaceController, IWKExtensionDelegate, INSUrlSessionDownloadDelegate - { +namespace WatchBackgroundRefresh.WatchBackgroundRefreshWatchAppExtension { + public partial class InterfaceController : WKInterfaceController, IWKExtensionDelegate, INSUrlSessionDownloadDelegate { NSUrl sampleDownloadURL = new NSUrl ("http://devstreaming.apple.com/videos/wwdc/2015/802mpzd3nzovlygpbg/802/802_designing_for_apple_watch.pdf?dl=1"); NSDateFormatter dateFormatter = new NSDateFormatter { @@ -14,7 +12,7 @@ public partial class InterfaceController : WKInterfaceController, IWKExtensionDe TimeStyle = NSDateFormatterStyle.Long }; - protected InterfaceController (IntPtr handle) : base(handle) + protected InterfaceController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } @@ -26,8 +24,8 @@ public override void Awake (NSObject context) UpdateLabel (); } - [Export("handleBackgroundTasks:")] - public void HandleBackgroundTasks(NSSet<WKRefreshBackgroundTask> backgroundTasks) + [Export ("handleBackgroundTasks:")] + public void HandleBackgroundTasks (NSSet<WKRefreshBackgroundTask> backgroundTasks) { foreach (WKRefreshBackgroundTask task in backgroundTasks) { Console.WriteLine ($"received background task: {task}"); @@ -40,8 +38,8 @@ public void HandleBackgroundTasks(NSSet<WKRefreshBackgroundTask> backgroundTasks ScheduleURLSession (); } } else if (task is WKUrlSessionRefreshBackgroundTask) { - var backgroundConfigObject = NSUrlSessionConfiguration.BackgroundSessionConfiguration (((WKUrlSessionRefreshBackgroundTask)task).SessionIdentifier); - var backgroundSession = NSUrlSession.FromWeakConfiguration(backgroundConfigObject, this, null); + var backgroundConfigObject = NSUrlSessionConfiguration.BackgroundSessionConfiguration (((WKUrlSessionRefreshBackgroundTask) task).SessionIdentifier); + var backgroundSession = NSUrlSession.FromWeakConfiguration (backgroundConfigObject, this, null); Console.WriteLine ($"Rejoining session {backgroundSession}"); } @@ -53,7 +51,7 @@ void ScheduleSnapshot () { // fire now, we're ready var fireDate = DateTime.Now; - WKExtension.SharedExtension.ScheduleSnapshotRefresh ((NSDate)fireDate, null, (NSError error) => { + WKExtension.SharedExtension.ScheduleSnapshotRefresh ((NSDate) fireDate, null, (NSError error) => { if (error == null) Console.WriteLine ("Successfully scheduled snapshot. All background work completed."); }); @@ -62,10 +60,10 @@ void ScheduleSnapshot () void UpdateLabel () { var now = DateTime.Now; - timeDisplayLabel.SetText(dateFormatter.ToString ((NSDate)now)); + timeDisplayLabel.SetText (dateFormatter.ToString ((NSDate) now)); } - [Export("URLSession:downloadTask:didFinishDownloadingToURL:")] + [Export ("URLSession:downloadTask:didFinishDownloadingToURL:")] public void DidFinishDownloading (NSUrlSession session, NSUrlSessionDownloadTask downloadTask, NSUrl location) { Console.WriteLine ($"NSURLSession finished to url: {location}"); @@ -89,12 +87,12 @@ partial void ScheduleRefreshButtonTapped () var fireDate = DateTime.Now.AddSeconds (20); // optional, any SecureCoding compliant data can be passed here - var userInfo = NSDictionary.FromObjectAndKey ((NSString)"background update", (NSString)"reason"); + var userInfo = NSDictionary.FromObjectAndKey ((NSString) "background update", (NSString) "reason"); - WKExtension.SharedExtension.ScheduleBackgroundRefresh ((NSDate)fireDate, userInfo, (NSError error) => { + WKExtension.SharedExtension.ScheduleBackgroundRefresh ((NSDate) fireDate, userInfo, (NSError error) => { if (error == null) Console.WriteLine ("successfully scheduled background task, use the crown to send the app to the background and wait for handle:BackgroundTasks to fire."); }); } } -} \ No newline at end of file +} diff --git a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/AppDelegate.cs b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/AppDelegate.cs index 3b5ef3975..1a34958b8 100644 --- a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/AppDelegate.cs +++ b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace WatchBackgroundRefresh -{ - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { +namespace WatchBackgroundRefresh { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) diff --git a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/Main.cs b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/Main.cs index f0f688920..87d7d1835 100644 --- a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/Main.cs +++ b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/Main.cs @@ -1,12 +1,10 @@ -using UIKit; +using UIKit; -namespace WatchBackgroundRefresh -{ - public class Application - { - static void Main(string[] args) +namespace WatchBackgroundRefresh { + public class Application { + static void Main (string [] args) { - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/ViewController.cs b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/ViewController.cs index ac833738d..234da27f3 100644 --- a/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/ViewController.cs +++ b/watchOS/WatchBackgroundRefresh/WatchBackgroundRefresh/ViewController.cs @@ -1,12 +1,10 @@ -using System; +using System; using UIKit; -namespace WatchBackgroundRefresh -{ - public partial class ViewController : UIViewController - { - protected ViewController (IntPtr handle) : base(handle) +namespace WatchBackgroundRefresh { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } diff --git a/watchOS/WatchComplication/iOSApp.WatchAppExtension/ComplicationController.cs b/watchOS/WatchComplication/iOSApp.WatchAppExtension/ComplicationController.cs index 333d7ff0c..f80196905 100644 --- a/watchOS/WatchComplication/iOSApp.WatchAppExtension/ComplicationController.cs +++ b/watchOS/WatchComplication/iOSApp.WatchAppExtension/ComplicationController.cs @@ -1,143 +1,115 @@ -using System; +using System; using Foundation; using ClockKit; using UIKit; -namespace iOSApp.WatchAppExtension -{ - [Register("ComplicationController")] - public class ComplicationController : CLKComplicationDataSource - { - public ComplicationController() +namespace iOSApp.WatchAppExtension { + [Register ("ComplicationController")] + public class ComplicationController : CLKComplicationDataSource { + public ComplicationController () { } - public override void GetCurrentTimelineEntry(CLKComplication complication, Action<CLKComplicationTimelineEntry> handler) + public override void GetCurrentTimelineEntry (CLKComplication complication, Action<CLKComplicationTimelineEntry> handler) { // Call the handler with the current timeline entry - Console.WriteLine("GetCurrentTimelineEntry"); + Console.WriteLine ("GetCurrentTimelineEntry"); CLKComplicationTimelineEntry entry = null; - try - { - var minutesPastHour = DateTime.Now.Minute.ToString(); + try { + var minutesPastHour = DateTime.Now.Minute.ToString (); - if (complication.Family == CLKComplicationFamily.ModularSmall) - { - var textTemplate1 = new CLKComplicationTemplateModularSmallSimpleText(); - textTemplate1.TextProvider = CLKSimpleTextProvider.FromText(minutesPastHour); - entry = CLKComplicationTimelineEntry.Create(NSDate.Now, textTemplate1); + if (complication.Family == CLKComplicationFamily.ModularSmall) { + var textTemplate1 = new CLKComplicationTemplateModularSmallSimpleText (); + textTemplate1.TextProvider = CLKSimpleTextProvider.FromText (minutesPastHour); + entry = CLKComplicationTimelineEntry.Create (NSDate.Now, textTemplate1); - } - else if (complication.Family == CLKComplicationFamily.ModularLarge) - { - var textTemplate = new CLKComplicationTemplateModularLargeStandardBody(); - textTemplate.HeaderTextProvider = CLKSimpleTextProvider.FromText("Set " + minutesPastHour + " mins past", "XH", "```"); + } else if (complication.Family == CLKComplicationFamily.ModularLarge) { + var textTemplate = new CLKComplicationTemplateModularLargeStandardBody (); + textTemplate.HeaderTextProvider = CLKSimpleTextProvider.FromText ("Set " + minutesPastHour + " mins past", "XH", "```"); - textTemplate.Body1TextProvider = CLKSimpleTextProvider.FromText("Body text", "X1", "~~~"); - textTemplate.Body2TextProvider = CLKSimpleTextProvider.FromText("Body 2", "X2", "---"); + textTemplate.Body1TextProvider = CLKSimpleTextProvider.FromText ("Body text", "X1", "~~~"); + textTemplate.Body2TextProvider = CLKSimpleTextProvider.FromText ("Body 2", "X2", "---"); // if the user typed something in the app, show that in complication - var c = NSUserDefaults.StandardUserDefaults["complication"]; - if (c != null) - { - textTemplate.Body1TextProvider = CLKSimpleTextProvider.FromText("You typed:", "You:", "~~~"); - textTemplate.Body2TextProvider = CLKSimpleTextProvider.FromText(c.ToString(), c.ToString(), "---"); + var c = NSUserDefaults.StandardUserDefaults ["complication"]; + if (c != null) { + textTemplate.Body1TextProvider = CLKSimpleTextProvider.FromText ("You typed:", "You:", "~~~"); + textTemplate.Body2TextProvider = CLKSimpleTextProvider.FromText (c.ToString (), c.ToString (), "---"); } - entry = CLKComplicationTimelineEntry.Create(NSDate.Now, textTemplate); + entry = CLKComplicationTimelineEntry.Create (NSDate.Now, textTemplate); - } - else if (complication.Family == CLKComplicationFamily.UtilitarianSmall) - { - var textTemplate = new CLKComplicationTemplateUtilitarianSmallFlat(); - textTemplate.TextProvider = CLKSimpleTextProvider.FromText(minutesPastHour + "m"); - entry = CLKComplicationTimelineEntry.Create(NSDate.Now, textTemplate); + } else if (complication.Family == CLKComplicationFamily.UtilitarianSmall) { + var textTemplate = new CLKComplicationTemplateUtilitarianSmallFlat (); + textTemplate.TextProvider = CLKSimpleTextProvider.FromText (minutesPastHour + "m"); + entry = CLKComplicationTimelineEntry.Create (NSDate.Now, textTemplate); - } - else if (complication.Family == CLKComplicationFamily.UtilitarianLarge) - { - var textTemplate = new CLKComplicationTemplateUtilitarianLargeFlat(); - textTemplate.TextProvider = CLKSimpleTextProvider.FromText(minutesPastHour + " past hour"); - entry = CLKComplicationTimelineEntry.Create(NSDate.Now, textTemplate); + } else if (complication.Family == CLKComplicationFamily.UtilitarianLarge) { + var textTemplate = new CLKComplicationTemplateUtilitarianLargeFlat (); + textTemplate.TextProvider = CLKSimpleTextProvider.FromText (minutesPastHour + " past hour"); + entry = CLKComplicationTimelineEntry.Create (NSDate.Now, textTemplate); - } - else if (complication.Family == CLKComplicationFamily.CircularSmall) - { - var ringTemplate = new CLKComplicationTemplateCircularSmallRingText(); - ringTemplate.TextProvider = CLKSimpleTextProvider.FromText(minutesPastHour); + } else if (complication.Family == CLKComplicationFamily.CircularSmall) { + var ringTemplate = new CLKComplicationTemplateCircularSmallRingText (); + ringTemplate.TextProvider = CLKSimpleTextProvider.FromText (minutesPastHour); ringTemplate.FillFraction = DateTime.Now.Minute / 60f; - entry = CLKComplicationTimelineEntry.Create(NSDate.Now, ringTemplate); - } - else - { - Console.WriteLine("GetCurrentTimelineEntry: Complication not supported (" + complication.Family + ")"); + entry = CLKComplicationTimelineEntry.Create (NSDate.Now, ringTemplate); + } else { + Console.WriteLine ("GetCurrentTimelineEntry: Complication not supported (" + complication.Family + ")"); } + } catch (Exception x) { + Console.WriteLine ("Exception " + x); } - catch (Exception x) - { - Console.WriteLine("Exception " + x); - } - handler(entry); + handler (entry); } - public override void GetPlaceholderTemplate(CLKComplication complication, Action<CLKComplicationTemplate> handler) + public override void GetPlaceholderTemplate (CLKComplication complication, Action<CLKComplicationTemplate> handler) { // This method will be called once per supported complication, and the results will be cached - Console.WriteLine("GetPlaceholderTemplate for " + complication); + Console.WriteLine ("GetPlaceholderTemplate for " + complication); CLKComplicationTemplate template = null; - if (complication.Family == CLKComplicationFamily.ModularSmall) - { - var textTemplate = new CLKComplicationTemplateModularSmallSimpleText(); - textTemplate.TextProvider = CLKSimpleTextProvider.FromText("X1"); + if (complication.Family == CLKComplicationFamily.ModularSmall) { + var textTemplate = new CLKComplicationTemplateModularSmallSimpleText (); + textTemplate.TextProvider = CLKSimpleTextProvider.FromText ("X1"); template = textTemplate; - } - else if (complication.Family == CLKComplicationFamily.ModularLarge) - { - var textTemplate = new CLKComplicationTemplateModularLargeStandardBody(); - textTemplate.HeaderTextProvider = CLKSimpleTextProvider.FromText("Header A", "A 2", "~~~"); - textTemplate.Body1TextProvider = CLKSimpleTextProvider.FromText("Body B", "B 2", "~~~"); + } else if (complication.Family == CLKComplicationFamily.ModularLarge) { + var textTemplate = new CLKComplicationTemplateModularLargeStandardBody (); + textTemplate.HeaderTextProvider = CLKSimpleTextProvider.FromText ("Header A", "A 2", "~~~"); + textTemplate.Body1TextProvider = CLKSimpleTextProvider.FromText ("Body B", "B 2", "~~~"); template = textTemplate; - } - else if (complication.Family == CLKComplicationFamily.UtilitarianSmall) - { - var textTemplate = new CLKComplicationTemplateUtilitarianSmallFlat(); - textTemplate.TextProvider = CLKSimpleTextProvider.FromText("XAM2"); + } else if (complication.Family == CLKComplicationFamily.UtilitarianSmall) { + var textTemplate = new CLKComplicationTemplateUtilitarianSmallFlat (); + textTemplate.TextProvider = CLKSimpleTextProvider.FromText ("XAM2"); template = textTemplate; - } - else if (complication.Family == CLKComplicationFamily.UtilitarianLarge) - { - var textTemplate = new CLKComplicationTemplateUtilitarianLargeFlat(); - textTemplate.TextProvider = CLKSimpleTextProvider.FromText("XAM3"); + } else if (complication.Family == CLKComplicationFamily.UtilitarianLarge) { + var textTemplate = new CLKComplicationTemplateUtilitarianLargeFlat (); + textTemplate.TextProvider = CLKSimpleTextProvider.FromText ("XAM3"); template = textTemplate; - } - else if (complication.Family == CLKComplicationFamily.CircularSmall) - { - var textTemplate = new CLKComplicationTemplateCircularSmallRingText(); - textTemplate.TextProvider = CLKSimpleTextProvider.FromText("s"); + } else if (complication.Family == CLKComplicationFamily.CircularSmall) { + var textTemplate = new CLKComplicationTemplateCircularSmallRingText (); + textTemplate.TextProvider = CLKSimpleTextProvider.FromText ("s"); template = textTemplate; - } - else - { - Console.WriteLine("GetPlaceholderTemplate: Complication not supported (" + complication + ")"); + } else { + Console.WriteLine ("GetPlaceholderTemplate: Complication not supported (" + complication + ")"); } - handler(template); + handler (template); } - public override void GetSupportedTimeTravelDirections(CLKComplication complication, Action<CLKComplicationTimeTravelDirections> handler) + public override void GetSupportedTimeTravelDirections (CLKComplication complication, Action<CLKComplicationTimeTravelDirections> handler) { // Retrieves the time travel directions supported by your complication - Console.WriteLine("GetSupportedTimeTravelDirections"); - handler(CLKComplicationTimeTravelDirections.None); + Console.WriteLine ("GetSupportedTimeTravelDirections"); + handler (CLKComplicationTimeTravelDirections.None); } } } diff --git a/watchOS/WatchComplication/iOSApp.WatchAppExtension/ExtensionDelegate.cs b/watchOS/WatchComplication/iOSApp.WatchAppExtension/ExtensionDelegate.cs index 9d0c28e6e..b351c76b6 100644 --- a/watchOS/WatchComplication/iOSApp.WatchAppExtension/ExtensionDelegate.cs +++ b/watchOS/WatchComplication/iOSApp.WatchAppExtension/ExtensionDelegate.cs @@ -1,39 +1,34 @@ -using System; +using System; using ClockKit; using Foundation; using WatchKit; -namespace iOSApp.WatchAppExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - public override void ApplicationDidFinishLaunching() +namespace iOSApp.WatchAppExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + public override void ApplicationDidFinishLaunching () { // Perform any final initialization of your application. var complicationServer = CLKComplicationServer.SharedInstance; // is null :-( - if (complicationServer.ActiveComplications != null) - { - Console.WriteLine("Active complications!!!!!!!!!!"); - foreach (var complication in complicationServer.ActiveComplications) - { - Console.WriteLine("Active " + complication.Description); + if (complicationServer.ActiveComplications != null) { + Console.WriteLine ("Active complications!!!!!!!!!!"); + foreach (var complication in complicationServer.ActiveComplications) { + Console.WriteLine ("Active " + complication.Description); //complicationServer.ReloadTimeline (complication); } - } - else { - Console.WriteLine("No active complications"); + } else { + Console.WriteLine ("No active complications"); } } - public override void ApplicationDidBecomeActive() + public override void ApplicationDidBecomeActive () { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void ApplicationWillResignActive() + public override void ApplicationWillResignActive () { // Sent when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions diff --git a/watchOS/WatchComplication/iOSApp.WatchAppExtension/InterfaceController.cs b/watchOS/WatchComplication/iOSApp.WatchAppExtension/InterfaceController.cs index c7b65688b..177b4a75c 100644 --- a/watchOS/WatchComplication/iOSApp.WatchAppExtension/InterfaceController.cs +++ b/watchOS/WatchComplication/iOSApp.WatchAppExtension/InterfaceController.cs @@ -1,82 +1,74 @@ -using System; +using System; using WatchKit; using Foundation; using ClockKit; -namespace iOSApp.WatchAppExtension -{ - public partial class InterfaceController : WKInterfaceController - { - protected InterfaceController(IntPtr handle) : base(handle) +namespace iOSApp.WatchAppExtension { + public partial class InterfaceController : WKInterfaceController { + protected InterfaceController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); + Console.WriteLine ("{0} awake with context", this); } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); - var c = NSUserDefaults.StandardUserDefaults["complication"]; - if (c != null) - { - MessageText.SetText (c.ToString()); // display what they typed last time + var c = NSUserDefaults.StandardUserDefaults ["complication"]; + if (c != null) { + MessageText.SetText (c.ToString ()); // display what they typed last time } } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } string enteredText = ""; - partial void SetMessageClicked() + partial void SetMessageClicked () { - var suggest = new string[] { "Hi Watch!" }; + var suggest = new string [] { "Hi Watch!" }; - PresentTextInputController(suggest, WatchKit.WKTextInputMode.AllowEmoji, (result) => - { + PresentTextInputController (suggest, WatchKit.WKTextInputMode.AllowEmoji, (result) => { // action when the "text input" is complete - if (result != null && result.Count > 0) - { + if (result != null && result.Count > 0) { // this only works if result is a text response (Plain or AllowEmoji) - enteredText = result.GetItem<NSObject>(0).ToString(); - Console.WriteLine(enteredText); + enteredText = result.GetItem<NSObject> (0).ToString (); + Console.WriteLine (enteredText); // do something, such as myLabel.SetText(enteredText); - MessageText.SetText(enteredText); - NSUserDefaults.StandardUserDefaults.SetString(enteredText, "complication"); + MessageText.SetText (enteredText); + NSUserDefaults.StandardUserDefaults.SetString (enteredText, "complication"); } }); } - partial void UpdateClicked() + partial void UpdateClicked () { - Console.WriteLine("BUTTON CLICKED"); + Console.WriteLine ("BUTTON CLICKED"); var complicationServer = CLKComplicationServer.SharedInstance; // is null :-( - if (complicationServer.ActiveComplications != null) - { - Console.WriteLine("Active complications!!!!!!!!!!"); - foreach (var complication in complicationServer.ActiveComplications) - { - Console.WriteLine("Active " + complication.Description ?? "null"); + if (complicationServer.ActiveComplications != null) { + Console.WriteLine ("Active complications!!!!!!!!!!"); + foreach (var complication in complicationServer.ActiveComplications) { + Console.WriteLine ("Active " + complication.Description ?? "null"); - complicationServer.ReloadTimeline(complication); + complicationServer.ReloadTimeline (complication); } - } - else { - Console.WriteLine("No active complications"); + } else { + Console.WriteLine ("No active complications"); } } } diff --git a/watchOS/WatchComplication/iOSApp/AppDelegate.cs b/watchOS/WatchComplication/iOSApp/AppDelegate.cs index b89cf9884..ddceddfb2 100644 --- a/watchOS/WatchComplication/iOSApp/AppDelegate.cs +++ b/watchOS/WatchComplication/iOSApp/AppDelegate.cs @@ -1,13 +1,11 @@ -using Foundation; +using Foundation; using UIKit; -namespace iOSApp -{ +namespace iOSApp { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { diff --git a/watchOS/WatchComplication/iOSApp/Main.cs b/watchOS/WatchComplication/iOSApp/Main.cs index 89e51535b..39ccfdce2 100644 --- a/watchOS/WatchComplication/iOSApp/Main.cs +++ b/watchOS/WatchComplication/iOSApp/Main.cs @@ -1,11 +1,9 @@ -using UIKit; +using UIKit; -namespace iOSApp -{ - public class Application - { +namespace iOSApp { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/watchOS/WatchComplication/iOSApp/ViewController.cs b/watchOS/WatchComplication/iOSApp/ViewController.cs index 3642526fa..6404b17d7 100644 --- a/watchOS/WatchComplication/iOSApp/ViewController.cs +++ b/watchOS/WatchComplication/iOSApp/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace iOSApp -{ - public partial class ViewController : UIViewController - { +namespace iOSApp { + public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } diff --git a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/ExtensionDelegate.cs b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/ExtensionDelegate.cs index 13765e9d7..1b0dce510 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/ExtensionDelegate.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/ExtensionDelegate.cs @@ -1,26 +1,24 @@ -using System; +using System; using Foundation; using WatchKit; -namespace WatchConnectivity.OnWatchExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - public override void ApplicationDidFinishLaunching() +namespace WatchConnectivity.OnWatchExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + public override void ApplicationDidFinishLaunching () { // Perform any final initialization of your application. - WCSessionManager.SharedManager.StartSession(); + WCSessionManager.SharedManager.StartSession (); } - public override void ApplicationDidBecomeActive() + public override void ApplicationDidBecomeActive () { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void ApplicationWillResignActive() + public override void ApplicationWillResignActive () { // Sent when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions diff --git a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/GlanceController.cs b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/GlanceController.cs index 320c3ea24..29e49dcda 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/GlanceController.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/GlanceController.cs @@ -1,35 +1,33 @@ -using System; +using System; using Foundation; using WatchKit; -namespace WatchConnectivity.OnWatchExtension -{ - public partial class GlanceController : WKInterfaceController - { - protected GlanceController(IntPtr handle) : base(handle) +namespace WatchConnectivity.OnWatchExtension { + public partial class GlanceController : WKInterfaceController { + protected GlanceController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); + Console.WriteLine ("{0} awake with context", this); } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } } } diff --git a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/InterfaceController.cs b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/InterfaceController.cs index 3bb75c4ab..47f6e03ee 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/InterfaceController.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/InterfaceController.cs @@ -1,76 +1,73 @@ -using System; +using System; using WatchKit; using Foundation; using System.Collections.Generic; using Newtonsoft.Json.Linq; -namespace WatchConnectivity.OnWatchExtension -{ - public partial class InterfaceController : WKInterfaceController - { - protected InterfaceController(IntPtr handle) : base(handle) +namespace WatchConnectivity.OnWatchExtension { + public partial class InterfaceController : WKInterfaceController { + protected InterfaceController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); - WCSessionManager.SharedManager.ApplicationContextUpdated += DidReceiveApplicationContext; + Console.WriteLine ("{0} awake with context", this); + WCSessionManager.SharedManager.ApplicationContextUpdated += DidReceiveApplicationContext; } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); - WCSessionManager.SharedManager.ApplicationContextUpdated -= DidReceiveApplicationContext; + Console.WriteLine ("{0} did deactivate", this); + WCSessionManager.SharedManager.ApplicationContextUpdated -= DidReceiveApplicationContext; } - public void DidReceiveApplicationContext(WCSession session, Dictionary<string, object> applicationContext) + public void DidReceiveApplicationContext (WCSession session, Dictionary<string, object> applicationContext) { - var message = (string)applicationContext["MessagePhone"]; - if (message != null) - { - Console.WriteLine($"Application context update received : {message}"); - label.SetText($"\ud83d\udcf1 : {message}"); + var message = (string) applicationContext ["MessagePhone"]; + if (message != null) { + Console.WriteLine ($"Application context update received : {message}"); + label.SetText ($"\ud83d\udcf1 : {message}"); } } - partial void TopLeftPressed() + partial void TopLeftPressed () { - sendEmoji("\ud83c\udf4f"); + sendEmoji ("\ud83c\udf4f"); } - partial void TopRightPressed() + partial void TopRightPressed () { - sendEmoji("\ud83c\udf53"); + sendEmoji ("\ud83c\udf53"); } - partial void BottomLeftPressed() + partial void BottomLeftPressed () { - sendEmoji("\ud83c\udf4a"); + sendEmoji ("\ud83c\udf4a"); } - partial void BottomRightPressed() + partial void BottomRightPressed () { - sendEmoji("\ud83c\udf4b"); + sendEmoji ("\ud83c\udf4b"); } - private void sendEmoji(string emoji) + private void sendEmoji (string emoji) { - WCSessionManager.SharedManager.UpdateApplicationContext(new Dictionary<string, object>() { { "MessageWatch", $"{emoji}" } }); + WCSessionManager.SharedManager.UpdateApplicationContext (new Dictionary<string, object> () { { "MessageWatch", $"{emoji}" } }); } } } diff --git a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/NotificationController.cs b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/NotificationController.cs index fe14737fb..0c50a1524 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/NotificationController.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/NotificationController.cs @@ -1,18 +1,16 @@ -using System; +using System; using WatchKit; using Foundation; -namespace WatchConnectivity.OnWatchExtension -{ - public partial class NotificationController : WKUserNotificationInterfaceController - { - protected NotificationController(IntPtr handle) : base(handle) +namespace WatchConnectivity.OnWatchExtension { + public partial class NotificationController : WKUserNotificationInterfaceController { + protected NotificationController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public NotificationController() + public NotificationController () { // Initialize variables here. // Configure interface objects here. @@ -38,16 +36,16 @@ public NotificationController() // completionHandler.Invoke (WKUserNotificationInterfaceType.Custom); // } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } } } diff --git a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/SessionManager/WCSessionManager.cs b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/SessionManager/WCSessionManager.cs index e72ef2347..1bca93bcb 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/SessionManager/WCSessionManager.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity.OnWatchExtension/SessionManager/WCSessionManager.cs @@ -1,16 +1,14 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Foundation; using Newtonsoft.Json; using System; -namespace WatchConnectivity -{ - public sealed class WCSessionManager : WCSessionDelegate - { +namespace WatchConnectivity { + public sealed class WCSessionManager : WCSessionDelegate { // Setup is converted from https://www.natashatherobot.com/watchconnectivity-say-hello-to-wcsession/ // with some extra bits - private static readonly WCSessionManager sharedManager = new WCSessionManager(); + private static readonly WCSessionManager sharedManager = new WCSessionManager (); private static WCSession session = WCSession.IsSupported ? WCSession.DefaultSession : null; #if __IOS__ @@ -20,12 +18,10 @@ public sealed class WCSessionManager : WCSessionDelegate #endif public event ApplicationContextUpdatedHandler ApplicationContextUpdated; - public delegate void ApplicationContextUpdatedHandler(WCSession session, Dictionary<string, object> applicationContext); + public delegate void ApplicationContextUpdatedHandler (WCSession session, Dictionary<string, object> applicationContext); - private WCSession validSession - { - get - { + private WCSession validSession { + get { #if __IOS__ Console.WriteLine($"Paired status:{(session.Paired ? '✓' : '✗')}\n"); Console.WriteLine($"Watch App Installed status:{(session.WatchAppInstalled ? '✓' : '✗')}\n"); @@ -36,88 +32,73 @@ private WCSession validSession } } - private WCSession validReachableSession - { - get - { + private WCSession validReachableSession { + get { return session.Reachable ? validSession : null; } } - private WCSessionManager() : base() { } + private WCSessionManager () : base () { } - public static WCSessionManager SharedManager - { - get - { + public static WCSessionManager SharedManager { + get { return sharedManager; } } - public void StartSession() + public void StartSession () { - if (session != null) - { + if (session != null) { session.Delegate = this; - session.ActivateSession(); - Console.WriteLine($"Started Watch Connectivity Session on {Device}"); + session.ActivateSession (); + Console.WriteLine ($"Started Watch Connectivity Session on {Device}"); } } - public override void SessionReachabilityDidChange(WCSession session) + public override void SessionReachabilityDidChange (WCSession session) { - Console.WriteLine($"Watch connectivity Reachable:{(session.Reachable ? '✓' : '✗')} from {Device}"); + Console.WriteLine ($"Watch connectivity Reachable:{(session.Reachable ? '✓' : '✗')} from {Device}"); // handle session reachability change - if (session.Reachable) - { + if (session.Reachable) { // great! continue on with Interactive Messaging - } - else { + } else { // 😥 prompt the user to unlock their iOS device } } #region Application Context Methods - public void UpdateApplicationContext(Dictionary<string, object> applicationContext) + public void UpdateApplicationContext (Dictionary<string, object> applicationContext) { // Application context doesnt need the watch to be reachable, it will be received when opened - if (validSession != null) - { - try - { - var NSValues = applicationContext.Values.Select(x => new NSString(JsonConvert.SerializeObject(x))).ToArray(); - var NSKeys = applicationContext.Keys.Select(x => new NSString(x)).ToArray(); - var NSApplicationContext = NSDictionary<NSString, NSObject>.FromObjectsAndKeys(NSValues, NSKeys); + if (validSession != null) { + try { + var NSValues = applicationContext.Values.Select (x => new NSString (JsonConvert.SerializeObject (x))).ToArray (); + var NSKeys = applicationContext.Keys.Select (x => new NSString (x)).ToArray (); + var NSApplicationContext = NSDictionary<NSString, NSObject>.FromObjectsAndKeys (NSValues, NSKeys); NSError error; - var sendSuccessfully = validSession.UpdateApplicationContext(NSApplicationContext, out error); - if (sendSuccessfully) - { - Console.WriteLine($"Sent App Context from {Device} \nPayLoad: {NSApplicationContext.ToString()} \n"); - } - else - { - Console.WriteLine($"Error Updating Application Context: {error.LocalizedDescription}"); + var sendSuccessfully = validSession.UpdateApplicationContext (NSApplicationContext, out error); + if (sendSuccessfully) { + Console.WriteLine ($"Sent App Context from {Device} \nPayLoad: {NSApplicationContext.ToString ()} \n"); + } else { + Console.WriteLine ($"Error Updating Application Context: {error.LocalizedDescription}"); } - } - catch (Exception ex) - { - Console.WriteLine($"Exception Updating Application Context: {ex.Message}"); + } catch (Exception ex) { + Console.WriteLine ($"Exception Updating Application Context: {ex.Message}"); } } } - public override void DidReceiveApplicationContext(WCSession session, NSDictionary<NSString, NSObject> applicationContext) + public override void DidReceiveApplicationContext (WCSession session, NSDictionary<NSString, NSObject> applicationContext) { - Console.WriteLine($"Receiving Message on {Device}"); - if (ApplicationContextUpdated != null) - { - var keys = applicationContext.Keys.Select(k => k.ToString()).ToArray(); - var values = applicationContext.Values.Select(v => JsonConvert.DeserializeObject(v.ToString())).ToArray(); - var dictionary = keys.Zip(values, (k, v) => new { Key = k, Value = v }) - .ToDictionary(x => x.Key, x => x.Value); + Console.WriteLine ($"Receiving Message on {Device}"); + if (ApplicationContextUpdated != null) { + var keys = applicationContext.Keys.Select (k => k.ToString ()).ToArray (); + var values = applicationContext.Values.Select (v => JsonConvert.DeserializeObject (v.ToString ())).ToArray (); + var dictionary = keys.Zip (values, (k, v) => new { Key = k, Value = v }) + .ToDictionary (x => x.Key, x => x.Value); - ApplicationContextUpdated(session, dictionary); + ApplicationContextUpdated (session, dictionary); } } diff --git a/watchOS/WatchConnectivity/WatchConnectivity/AppDelegate.cs b/watchOS/WatchConnectivity/WatchConnectivity/AppDelegate.cs index fdcc9d98a..1d77a2070 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity/AppDelegate.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity/AppDelegate.cs @@ -1,32 +1,29 @@ -using Foundation; +using Foundation; using UIKit; -namespace WatchConnectivity -{ +namespace WatchConnectivity { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method // Apple Watch session manager - WCSessionManager.SharedManager.StartSession(); + WCSessionManager.SharedManager.StartSession (); return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -34,25 +31,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/watchOS/WatchConnectivity/WatchConnectivity/CommandTableCell.cs b/watchOS/WatchConnectivity/WatchConnectivity/CommandTableCell.cs index a8a042d32..b7d4cb0de 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity/CommandTableCell.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity/CommandTableCell.cs @@ -5,10 +5,8 @@ using Foundation; using UIKit; -namespace WatchConnectivity -{ - public partial class CommandTableCell : UITableViewCell - { +namespace WatchConnectivity { + public partial class CommandTableCell : UITableViewCell { public CommandTableCell (IntPtr handle) : base (handle) { } diff --git a/watchOS/WatchConnectivity/WatchConnectivity/Main.cs b/watchOS/WatchConnectivity/WatchConnectivity/Main.cs index e96ae91cf..a856c3e1a 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity/Main.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace WatchConnectivity -{ - public class Application - { +namespace WatchConnectivity { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/watchOS/WatchConnectivity/WatchConnectivity/ViewController.cs b/watchOS/WatchConnectivity/WatchConnectivity/ViewController.cs index 31ecce70c..3076c88e0 100644 --- a/watchOS/WatchConnectivity/WatchConnectivity/ViewController.cs +++ b/watchOS/WatchConnectivity/WatchConnectivity/ViewController.cs @@ -1,87 +1,81 @@ -using System; +using System; using System.Collections.Generic; using Foundation; using UIKit; -namespace WatchConnectivity -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) +namespace WatchConnectivity { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. WCSessionManager.SharedManager.ApplicationContextUpdated += DidReceiveApplicationContext; - tableView.Source = new TableSource(new string[] {"🐶", "🐱", "🐼", "🐯", "🦁", "🐷", "🐻", "🐰", "🐨", "🐸", "🐙", "🐵"}); - tableView.Delegate = new TableDelegate(this); + tableView.Source = new TableSource (new string [] { "🐶", "🐱", "🐼", "🐯", "🦁", "🐷", "🐻", "🐰", "🐨", "🐸", "🐙", "🐵" }); + tableView.Delegate = new TableDelegate (this); } - public override void ViewDidUnload() + public override void ViewDidUnload () { - base.ViewDidUnload(); + base.ViewDidUnload (); WCSessionManager.SharedManager.ApplicationContextUpdated -= DidReceiveApplicationContext; } - public void DidReceiveApplicationContext(WCSession session, Dictionary<string, object> applicationContext) + public void DidReceiveApplicationContext (WCSession session, Dictionary<string, object> applicationContext) { - var message = (string)applicationContext["MessageWatch"]; - if (message != null) - { - Console.WriteLine($"Application context update received : {message}"); - InvokeOnMainThread(() => - { + var message = (string) applicationContext ["MessageWatch"]; + if (message != null) { + Console.WriteLine ($"Application context update received : {message}"); + InvokeOnMainThread (() => { label.Text = $"⌚️ : {message}"; }); } } - public void SendEmoji(string emoji) + public void SendEmoji (string emoji) { - WCSessionManager.SharedManager.UpdateApplicationContext(new Dictionary<string, object>() { { "MessagePhone", $"{emoji}" } }); + WCSessionManager.SharedManager.UpdateApplicationContext (new Dictionary<string, object> () { { "MessagePhone", $"{emoji}" } }); } } - public class TableSource : UITableViewSource - { + public class TableSource : UITableViewSource { - string[] TableItems; + string [] TableItems; - public TableSource(string[] items) + public TableSource (string [] items) { TableItems = items; } - public override nint RowsInSection(UITableView tableview, nint section) + public override nint RowsInSection (UITableView tableview, nint section) { return TableItems.Length; } - public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) + public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { - var cell = tableView.DequeueReusableCell("CommandCell", indexPath) as CommandTableCell; - cell.label.Text = TableItems[indexPath.Row]; + var cell = tableView.DequeueReusableCell ("CommandCell", indexPath) as CommandTableCell; + cell.label.Text = TableItems [indexPath.Row]; return cell; } } - public class TableDelegate : UITableViewDelegate - { + public class TableDelegate : UITableViewDelegate { #region Private Variables private ViewController Controller; #endregion #region Constructors - public TableDelegate() + public TableDelegate () { } - public TableDelegate(ViewController controller) + public TableDelegate (ViewController controller) { // Initialize this.Controller = controller; @@ -89,15 +83,15 @@ public TableDelegate(ViewController controller) #endregion #region Override Methods - public override nfloat EstimatedHeight(UITableView tableView, Foundation.NSIndexPath indexPath) + public override nfloat EstimatedHeight (UITableView tableView, Foundation.NSIndexPath indexPath) { return 44f; } - public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath) + public override void RowSelected (UITableView tableView, Foundation.NSIndexPath indexPath) { - var cell = tableView.CellAt(indexPath) as CommandTableCell; - Controller.SendEmoji(cell.label.Text); + var cell = tableView.CellAt (indexPath) as CommandTableCell; + Controller.SendEmoji (cell.label.Text); } #endregion } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/ButtonDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/ButtonDetailController.cs index 8000e79e2..342861d03 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/ButtonDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/ButtonDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays buttons and shows use of groups within buttons. * This also demonstrates how to hide and show UI elements at runtime. */ @@ -8,10 +8,8 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class ButtonDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class ButtonDetailController : WKInterfaceController { bool hidden; bool alpha; @@ -45,4 +43,4 @@ partial void ChangeAlpha (NSObject obj) alpha = !alpha; } } -} \ No newline at end of file +} diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/ControllerDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/ControllerDetailController.cs index f6f91b4b0..fcdfd956c 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/ControllerDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/ControllerDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller demonstrates how to present a modal controller with a page-based navigation style. * By performing a Force Touch gesture on the controller (click-and-hold in the iOS Simulator), you can present a menu. */ @@ -8,10 +8,8 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class ControllerDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class ControllerDetailController : WKInterfaceController { public ControllerDetailController () { } @@ -40,4 +38,4 @@ partial void MenuItemTapped (NSObject obj) Console.WriteLine ("A menu item was tapped."); } } -} \ No newline at end of file +} diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/CrownDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/CrownDetailController.cs index 8f884b299..d87d1bf25 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/CrownDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/CrownDetailController.cs @@ -1,63 +1,61 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using WatchKit; -namespace Watchkit2Extension -{ - /// <summary> - /// New in watchOS 3 - /// </summary> - public partial class CrownDetailController : WKInterfaceController, IWKCrownDelegate - { - public CrownDetailController (IntPtr handle) : base (handle) - { - } - - public override void Awake(NSObject context) +namespace Watchkit2Extension { + /// <summary> + /// New in watchOS 3 + /// </summary> + public partial class CrownDetailController : WKInterfaceController, IWKCrownDelegate { + public CrownDetailController (IntPtr handle) : base (handle) { - base.Awake(context); - - var pickerItems = new WKPickerItem[] - { - new WKPickerItem {Title = "Item 1", Caption="Red"}, - new WKPickerItem {Title = "Item 2", Caption="Green"}, - new WKPickerItem {Title = "Item 3", Caption="Blue"} - }; - - pickerView.SetItems(pickerItems); - + } + + public override void Awake (NSObject context) + { + base.Awake (context); + + var pickerItems = new WKPickerItem [] + { + new WKPickerItem {Title = "Item 1", Caption="Red"}, + new WKPickerItem {Title = "Item 2", Caption="Green"}, + new WKPickerItem {Title = "Item 3", Caption="Blue"} + }; + + pickerView.SetItems (pickerItems); + CrownSequencer.Delegate = this; - } - - public override void WillActivate() + } + + public override void WillActivate () { - base.WillActivate(); - CrownSequencer.Focus(); - } - - void UpdateCrownLabels() + base.WillActivate (); + CrownSequencer.Focus (); + } + + void UpdateCrownLabels () + { + velocityLabel.SetText ("RPS:" + CrownSequencer.RotationsPerSecond); + stateLabel.SetText (CrownSequencer.Idle ? "Idle:true" : "Idle: false"); + } + + + partial void FocusCrown (Foundation.NSObject sender) { - velocityLabel.SetText("RPS:" + CrownSequencer.RotationsPerSecond); - stateLabel.SetText(CrownSequencer.Idle ? "Idle:true" : "Idle: false"); - } - - - partial void FocusCrown(Foundation.NSObject sender) - { - CrownSequencer.Focus(); - } - - [Export("crownDidRotate:rotationalDelta:")] - public void CrownDidRotate(WKCrownSequencer crownSequencer, double rotationalDelta) + CrownSequencer.Focus (); + } + + [Export ("crownDidRotate:rotationalDelta:")] + public void CrownDidRotate (WKCrownSequencer crownSequencer, double rotationalDelta) { - UpdateCrownLabels(); - } - - [Export("crownDidBecomeIdle:")] - public void CrownDidBecomeIdle(WKCrownSequencer crownSequencer) + UpdateCrownLabels (); + } + + [Export ("crownDidBecomeIdle:")] + public void CrownDidBecomeIdle (WKCrownSequencer crownSequencer) { - UpdateCrownLabels(); - } - } -} \ No newline at end of file + UpdateCrownLabels (); + } + } +} diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/DeviceDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/DeviceDetailController.cs index 098bf4a00..27d1b8b47 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/DeviceDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/DeviceDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays device specific information to use for ensuring a great experience to the wearer of the WatchKit app. */ @@ -7,10 +7,8 @@ using WatchKit; using CoreGraphics; -namespace WatchkitExtension -{ - public partial class DeviceDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class DeviceDetailController : WKInterfaceController { public DeviceDetailController () { CGRect bounds = WKInterfaceDevice.CurrentDevice.ScreenBounds; @@ -34,4 +32,4 @@ public override void DidDeactivate () Console.WriteLine ("{0} did deactivate", this); } } -} \ No newline at end of file +} diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/GestureDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/GestureDetailController.cs index b58322acd..7ca01c83b 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/GestureDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/GestureDetailController.cs @@ -1,66 +1,62 @@ -using Foundation; -using System; +using Foundation; +using System; using UIKit; using WatchKit; -namespace Watchkit2Extension -{ - /// <summary> - /// New in watchOS 3 +namespace Watchkit2Extension { + /// <summary> + /// New in watchOS 3 /// </summary> - public partial class GestureDetailController : WKInterfaceController - { - public GestureDetailController(IntPtr handle) : base(handle) + public partial class GestureDetailController : WKInterfaceController { + public GestureDetailController (IntPtr handle) : base (handle) { - } - - partial void LongPressRecognized(Foundation.NSObject sender) + } + + partial void LongPressRecognized (Foundation.NSObject sender) + { + longPresGroup.SetBackgroundColor (UIColor.Green); + ScheduleReset (); + } + + partial void PanRecognized (Foundation.NSObject sender) { - longPresGroup.SetBackgroundColor(UIColor.Green); - ScheduleReset(); - } - - partial void PanRecognized(Foundation.NSObject sender) - { - var panGesture = sender as WKPanGestureRecognizer; - if (panGesture != null) - { - panGroup.SetBackgroundColor(UIColor.Green); - panLabel.SetText("offset:" + panGesture.TranslationInObject.ToString()); + var panGesture = sender as WKPanGestureRecognizer; + if (panGesture != null) { + panGroup.SetBackgroundColor (UIColor.Green); + panLabel.SetText ("offset:" + panGesture.TranslationInObject.ToString ()); + + ScheduleReset (); + } + } - ScheduleReset(); - } - } - - partial void SwipeRecognized(Foundation.NSObject sender) - { - swipeGroup.SetBackgroundColor(UIColor.Green); - ScheduleReset(); - } - - partial void TapRecognized(Foundation.NSObject sender) + partial void SwipeRecognized (Foundation.NSObject sender) { - tapGroup.SetBackgroundColor(UIColor.Green); - ScheduleReset(); - } - - NSTimer timer; - void ScheduleReset() - { - if (timer != null) - { - timer.Invalidate(); - } - timer = NSTimer.CreateTimer( TimeSpan.FromSeconds(1), ResetAllGroups); - NSRunLoop.Current.AddTimer(timer, NSRunLoopMode.Common); - } - + swipeGroup.SetBackgroundColor (UIColor.Green); + ScheduleReset (); + } + + partial void TapRecognized (Foundation.NSObject sender) + { + tapGroup.SetBackgroundColor (UIColor.Green); + ScheduleReset (); + } + + NSTimer timer; + void ScheduleReset () + { + if (timer != null) { + timer.Invalidate (); + } + timer = NSTimer.CreateTimer (TimeSpan.FromSeconds (1), ResetAllGroups); + NSRunLoop.Current.AddTimer (timer, NSRunLoopMode.Common); + } + void ResetAllGroups (NSTimer obj) { - tapGroup.SetBackgroundColor(UIColor.Clear); - swipeGroup.SetBackgroundColor(UIColor.Clear); - panGroup.SetBackgroundColor(UIColor.Clear); - longPresGroup.SetBackgroundColor(UIColor.Clear); + tapGroup.SetBackgroundColor (UIColor.Clear); + swipeGroup.SetBackgroundColor (UIColor.Clear); + panGroup.SetBackgroundColor (UIColor.Clear); + longPresGroup.SetBackgroundColor (UIColor.Clear); } - } -} \ No newline at end of file + } +} diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/GroupDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/GroupDetailController.cs index 0aba0fb27..7db3f8887 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/GroupDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/GroupDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays groups in various configurations. * This controller demonstrates sophisticated layouts using nested groups. */ @@ -9,11 +9,9 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ +namespace WatchkitExtension { [Register ("GroupDetailController")] - public class GroupDetailController : WKInterfaceController - { + public class GroupDetailController : WKInterfaceController { public GroupDetailController () { } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/ImageDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/ImageDetailController.cs index 3264de132..9daaffbec 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/ImageDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/ImageDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays images, static and animated. It demonstrates using the image cache * to send images from the WatchKit app extension bundle to be stored and used in the WatchKit app bundle. * It also demonstrates how to use screenBounds to use the most appropriate sized image for the device at runtime. @@ -11,10 +11,8 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class ImageDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class ImageDetailController : WKInterfaceController { public ImageDetailController () { } @@ -25,9 +23,8 @@ public override void Awake (NSObject context) Console.WriteLine ("Passed in context: {0}", context); // Uses image inside WatchKit Extension bundle. - using (var image = UIImage.FromBundle("Walkway")) - { - staticImage.SetImage(image); + using (var image = UIImage.FromBundle ("Walkway")) { + staticImage.SetImage (image); } } @@ -45,16 +42,16 @@ public override void DidDeactivate () partial void PlayAnimation (NSObject obj) { - animatedImage.SetImage ("Bus"); - animatedImage.StartAnimating (); + animatedImage.SetImage ("Bus"); + animatedImage.StartAnimating (); - // Animate with a specific range, duration, and repeat count. - //animatedImage.StartAnimating (new NSRange (0, 4), 2.0, 3); + // Animate with a specific range, duration, and repeat count. + //animatedImage.StartAnimating (new NSRange (0, 4), 2.0, 3); } partial void StopAnimation (NSObject obj) { - animatedImage.StopAnimating (); + animatedImage.StopAnimating (); } } } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/ElementRowController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/ElementRowController.cs index e0ce2e08a..874ccff99 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/ElementRowController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/ElementRowController.cs @@ -1,4 +1,4 @@ -/* +/* * This is the row controller for the default row type in the table of the initial interface controller. */ @@ -6,10 +6,8 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class ElementRowController : NSObject - { +namespace WatchkitExtension { + public partial class ElementRowController : NSObject { public ElementRowController () { } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/InterfaceController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/InterfaceController.cs index 08bdbab71..cd3b579bc 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/InterfaceController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/Initial Interface Controller/InterfaceController.cs @@ -1,4 +1,4 @@ -/* +/* * This is the initial interface controller for the WatchKit app. * It loads the initial table of the app with data and responds to Handoff launching the WatchKit app. */ @@ -12,58 +12,55 @@ using Newtonsoft.Json; -namespace WatchkitExtension -{ - public partial class InterfaceController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class InterfaceController : WKInterfaceController { readonly List<Dictionary<string, string>> elementsList; public InterfaceController (IntPtr handle) : base (handle) { - var appData = NSBundle.MainBundle.PathForResource("AppData", "json"); - elementsList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(File.ReadAllText(appData)); + var appData = NSBundle.MainBundle.PathForResource ("AppData", "json"); + elementsList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>> (File.ReadAllText (appData)); } public override void Awake (NSObject context) { - LoadTableRows(); + LoadTableRows (); } public override void WillActivate () { // This method is called when the controller is about to be visible to the wearer. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); } public override void DidDeactivate () { // This method is called when the controller is no longer visible. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } public override void HandleUserActivity (NSDictionary userActivity) { - PushController(userActivity["controllerName"].ToString(), userActivity["detailInfo"]); + PushController (userActivity ["controllerName"].ToString (), userActivity ["detailInfo"]); } public override void DidSelectRow (WKInterfaceTable table, nint rowIndex) { - var rowData = elementsList[(int)rowIndex]; + var rowData = elementsList [(int) rowIndex]; - PushController(rowData["controllerIdentifier"], (NSObject)null); + PushController (rowData ["controllerIdentifier"], (NSObject) null); } void LoadTableRows () { - interfaceTable.SetNumberOfRows((nint)elementsList.Count, "default"); + interfaceTable.SetNumberOfRows ((nint) elementsList.Count, "default"); // Create all of the table rows. - for (var i = 0; i < elementsList.Count; i++) - { - var elementRow = (ElementRowController)interfaceTable.GetRowController(i); + for (var i = 0; i < elementsList.Count; i++) { + var elementRow = (ElementRowController) interfaceTable.GetRowController (i); - var rowData = elementsList[i]; - elementRow.ElementLabel.SetText(rowData["label"]); + var rowData = elementsList [i]; + elementRow.ElementLabel.SetText (rowData ["label"]); } } } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/LabelDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/LabelDetailController.cs index 48c5c9f1e..a159078ee 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/LabelDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/LabelDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays labels and specialized labels (Date and Timer). */ @@ -8,21 +8,18 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class LabelDetailController : WKInterfaceController - { - public LabelDetailController() +namespace WatchkitExtension { + public partial class LabelDetailController : WKInterfaceController { + public LabelDetailController () { - coloredLabel.SetTextColor(UIColor.Purple); + coloredLabel.SetTextColor (UIColor.Purple); - var attr = new UIStringAttributes - { - Font = UIFont.SystemFontOfSize(18f, UIFontWeight.UltraLight) + var attr = new UIStringAttributes { + Font = UIFont.SystemFontOfSize (18f, UIFontWeight.UltraLight) }; - var attrString = new NSAttributedString("Ultralight Label", attr.Dictionary); + var attrString = new NSAttributedString ("Ultralight Label", attr.Dictionary); - ultralightLabel.SetText(attrString); + ultralightLabel.SetText (attrString); var components = new NSDateComponents { Day = 7, diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/MapDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/MapDetailController.cs index e939afc71..b5451c243 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/MapDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/MapDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays a map and demonstrates use of setting its coordinate region, zoom level, and addition and removal of annotations. */ @@ -11,10 +11,8 @@ using CoreGraphics; using CoreLocation; -namespace WatchkitExtension -{ - public partial class MapDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class MapDetailController : WKInterfaceController { MKCoordinateRegion currentRegion; MKCoordinateSpan currentSpan; @@ -101,9 +99,8 @@ partial void AddImageAnnotations (NSObject obj) var secondCoordinate = new CLLocationCoordinate2D (currentRegion.Center.Latitude, currentRegion.Center.Longitude + 0.3f); // Uses image in WatchKit Extension bundle - using (var image = UIImage.FromBundle("Bumblebee")) - { - map.AddAnnotation(secondCoordinate, image, CGPoint.Empty); + using (var image = UIImage.FromBundle ("Bumblebee")) { + map.AddAnnotation (secondCoordinate, image, CGPoint.Empty); } } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/MovieDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/MovieDetailController.cs index 1dcc57abd..26fac0c90 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/MovieDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/MovieDetailController.cs @@ -5,40 +5,35 @@ using Foundation; using WatchKit; -namespace Watchkit2Extension -{ - public partial class MovieDetailController : WKInterfaceController - { +namespace Watchkit2Extension { + public partial class MovieDetailController : WKInterfaceController { public MovieDetailController (IntPtr handle) : base (handle) { } bool playingInlineMovie = false; - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); - var movieUrl = NSBundle.MainBundle.GetUrlForResource("Ski1", "m4v", "Media"); - - Movie.SetMovieUrl(movieUrl); - Movie.SetPosterImage(WKImage.CreateFromName("Ski1")); + var movieUrl = NSBundle.MainBundle.GetUrlForResource ("Ski1", "m4v", "Media"); - InlineMovie.SetMovieUrl(movieUrl); - InlineMovie.SetPosterImage(WKImage.CreateFromName("Ski1")); + Movie.SetMovieUrl (movieUrl); + Movie.SetPosterImage (WKImage.CreateFromName ("Ski1")); + + InlineMovie.SetMovieUrl (movieUrl); + InlineMovie.SetPosterImage (WKImage.CreateFromName ("Ski1")); playingInlineMovie = false; } - partial void InlineMovieTapped(Foundation.NSObject sender) + partial void InlineMovieTapped (Foundation.NSObject sender) { - if (playingInlineMovie) - { - InlineMovie.Pause(); - } - else - { - InlineMovie.Play(); + if (playingInlineMovie) { + InlineMovie.Pause (); + } else { + InlineMovie.Play (); } playingInlineMovie = !playingInlineMovie; diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/Notifications/NotificationController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/Notifications/NotificationController.cs index 0097298d7..61f376319 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/Notifications/NotificationController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/Notifications/NotificationController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller handles displaying a custom or static notification. */ @@ -7,11 +7,9 @@ using Foundation; using WatchKit; -namespace WatchkitExtension -{ +namespace WatchkitExtension { [Register ("NotificationController")] - public class NotificationController : WKUserNotificationInterfaceController - { + public class NotificationController : WKUserNotificationInterfaceController { public NotificationController (IntPtr handle) : base (handle) { } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/PageController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/PageController.cs index 9a0dd7e6c..2a25d96e5 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/PageController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/PageController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller represents a single page of the modal page-based navigation controller, * presented in AAPLControllerDetailController. */ @@ -9,10 +9,8 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class PageController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class PageController : WKInterfaceController { public PageController () { } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/SeparatorDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/SeparatorDetailController.cs index d876af559..78b3ab63d 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/SeparatorDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/SeparatorDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays separators and how to visually break up content onscreen. */ @@ -8,11 +8,9 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ +namespace WatchkitExtension { [Register ("SeparatorDetailController")] - public class SeparatorDetailController : WKInterfaceController - { + public class SeparatorDetailController : WKInterfaceController { public SeparatorDetailController () { } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/SliderDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/SliderDetailController.cs index 557c1a376..43d942ffc 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/SliderDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/SliderDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays sliders and their various configurations. */ @@ -8,13 +8,11 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class SliderDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class SliderDetailController : WKInterfaceController { public SliderDetailController () { - coloredSlider.SetColor (UIColor.Red); + coloredSlider.SetColor (UIColor.Red); } public override void WillActivate () diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/SwitchDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/SwitchDetailController.cs index 10b590dcb..f81fd53b8 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/SwitchDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/SwitchDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays switches and their various configurations. */ @@ -8,16 +8,14 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class SwitchDetailController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class SwitchDetailController : WKInterfaceController { public SwitchDetailController () { - offSwitch.SetOn (false); + offSwitch.SetOn (false); - coloredSwitch.SetColor (UIColor.Blue); - coloredSwitch.SetTitle ("Blue Switch"); + coloredSwitch.SetColor (UIColor.Blue); + coloredSwitch.SetTitle ("Blue Switch"); } public override void WillActivate () diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableDetailController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableDetailController.cs index cc11271db..a7a243d08 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableDetailController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableDetailController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller displays a table with rows. This controller demonstrates how to insert rows after the intial set of rows has been added and displayed. */ @@ -7,11 +7,9 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class TableDetailController : WKInterfaceController - { - string[] cityNames; +namespace WatchkitExtension { + public partial class TableDetailController : WKInterfaceController { + string [] cityNames; public TableDetailController () { @@ -41,7 +39,7 @@ void LoadTableData () interfaceTable.SetNumberOfRows (cityNames.Length, "default"); for (var i = 0; i < cityNames.Length; i++) { - var row = (TableRowController)interfaceTable.GetRowController (i); + var row = (TableRowController) interfaceTable.GetRowController (i); row.RowLabel.SetText (cityNames [i]); } } @@ -59,10 +57,10 @@ public override void DidSelectRow (WKInterfaceTable table, nint rowIndex) var newCityNumber = 0; newCityIndexes.EnumerateIndexes ((nuint idx, ref bool stop) => { var newCityName = newCityNames [newCityNumber]; - var row = (TableRowController)interfaceTable.GetRowController ((nint) idx); + var row = (TableRowController) interfaceTable.GetRowController ((nint) idx); row.RowLabel.SetText (newCityName); newCityNumber++; }); } } -} \ No newline at end of file +} diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableRowController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableRowController.cs index 5f1ce5a15..b27517d51 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableRowController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/Table Detail Controller/TableRowController.cs @@ -1,4 +1,4 @@ -/* +/* * This is the row controller for the default row type in the table of the table detail controller. */ @@ -7,10 +7,8 @@ using WatchKit; using Foundation; -namespace WatchkitExtension -{ - public partial class TableRowController : NSObject - { +namespace WatchkitExtension { + public partial class TableRowController : NSObject { public TableRowController () { } diff --git a/watchOS/WatchKitCatalog/WatchKit3Extension/TextInputController.cs b/watchOS/WatchKitCatalog/WatchKit3Extension/TextInputController.cs index c0a43aa82..a4e9eac35 100644 --- a/watchOS/WatchKitCatalog/WatchKit3Extension/TextInputController.cs +++ b/watchOS/WatchKitCatalog/WatchKit3Extension/TextInputController.cs @@ -1,4 +1,4 @@ -/* +/* * This controller demonstrates using the Text Input Controller. */ @@ -8,10 +8,8 @@ using Foundation; using WatchConnectivity; -namespace WatchkitExtension -{ - public partial class TextInputController : WKInterfaceController - { +namespace WatchkitExtension { + public partial class TextInputController : WKInterfaceController { public override void WillActivate () { // This method is called when the controller is about to be visible to the wearer. @@ -27,14 +25,17 @@ public override void DidDeactivate () partial void ReplyWithTextInputController (NSObject obj) { // Using the WKTextInputMode enum, you can specify which aspects of the Text Input Controller are shown when presented. - PresentTextInputController (new [] { "Yes", "No", "Maybe" }, WKTextInputMode.AllowAnimatedEmoji, delegate(NSArray results) { + PresentTextInputController (new [] { "Yes", "No", "Maybe" }, WKTextInputMode.AllowAnimatedEmoji, delegate (NSArray results) + { Console.WriteLine ("Text Input Results: {0}", results); if (results != null) { // Sends a non-nil result to the parent iOS application. - WCSession.DefaultSession.SendMessage (new NSDictionary<NSString, NSObject> (new NSString ("TextInput"), results.GetItem<NSString> (0)), delegate (NSDictionary<NSString, NSObject> replyMessage) { + WCSession.DefaultSession.SendMessage (new NSDictionary<NSString, NSObject> (new NSString ("TextInput"), results.GetItem<NSString> (0)), delegate (NSDictionary<NSString, NSObject> replyMessage) + { Console.WriteLine ("Reply Info: {0}", replyMessage); - }, delegate (NSError error) { + }, delegate (NSError error) + { Console.WriteLine ("Error: {0}", error != null ? error.LocalizedDescription : "null"); }); } diff --git a/watchOS/WatchKitCatalog/WatchKitCatalog/AppDelegate.cs b/watchOS/WatchKitCatalog/WatchKitCatalog/AppDelegate.cs index 62de87be4..5b926141d 100644 --- a/watchOS/WatchKitCatalog/WatchKitCatalog/AppDelegate.cs +++ b/watchOS/WatchKitCatalog/WatchKitCatalog/AppDelegate.cs @@ -1,18 +1,16 @@ -using System; +using System; using UIKit; using Foundation; -namespace WatchKitCatalog -{ +namespace WatchKitCatalog { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; @@ -24,25 +22,25 @@ public override void HandleWatchKitExtensionRequest (UIApplication application, reply (new NSDictionary ("Confirmation", "Text was received")); } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/watchOS/WatchKitCatalog/WatchKitCatalog/Main.cs b/watchOS/WatchKitCatalog/WatchKitCatalog/Main.cs index 4df2258bb..e7f7bf339 100644 --- a/watchOS/WatchKitCatalog/WatchKitCatalog/Main.cs +++ b/watchOS/WatchKitCatalog/WatchKitCatalog/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace WatchKitCatalog -{ - public class Application - { +namespace WatchKitCatalog { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/watchOS/WatchKitCatalog/WatchKitCatalog/WatchKitCatalogViewController.cs b/watchOS/WatchKitCatalog/WatchKitCatalog/WatchKitCatalogViewController.cs index 464feb33c..cbac8500b 100644 --- a/watchOS/WatchKitCatalog/WatchKitCatalog/WatchKitCatalogViewController.cs +++ b/watchOS/WatchKitCatalog/WatchKitCatalog/WatchKitCatalogViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace WatchKitCatalog -{ - public partial class WatchKitCatalogViewController : UIViewController - { +namespace WatchKitCatalog { + public partial class WatchKitCatalogViewController : UIViewController { static bool UserInterfaceIdiomIsPhone { get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; } } @@ -20,7 +18,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -29,7 +27,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. } diff --git a/watchOS/WatchLocalization/Localization.WatchAppExtension/DetailController.cs b/watchOS/WatchLocalization/Localization.WatchAppExtension/DetailController.cs index 28f9af2bb..b86f0d9ea 100644 --- a/watchOS/WatchLocalization/Localization.WatchAppExtension/DetailController.cs +++ b/watchOS/WatchLocalization/Localization.WatchAppExtension/DetailController.cs @@ -3,62 +3,48 @@ using UIKit; using WatchKit; -namespace Localization.WatchAppExtension -{ - public partial class DetailController : WKInterfaceController - { - public DetailController (IntPtr handle) : base (handle) - { - } +namespace Localization.WatchAppExtension { + public partial class DetailController : WKInterfaceController { + public DetailController (IntPtr handle) : base (handle) + { + } - public override void WillActivate() + public override void WillActivate () { - base.WillActivate(); + base.WillActivate (); var hour = DateTime.Now.Hour; var display = "zzzz"; - if (hour < 6) - { + if (hour < 6) { // zzz - } - else if (hour < 10) - { + } else if (hour < 10) { display = "Breakfast time"; - } - else if (hour < 16) - { + } else if (hour < 16) { display = "Lunch time"; - } - else if (hour < 21) - { + } else if (hour < 21) { display = "Dinner time"; - } - else if (hour < 23) - { + } else if (hour < 23) { display = "Bed time"; } - var localizedDisplay = NSBundle.MainBundle.LocalizedString(display, comment: "greeting"); - DisplayText.SetText(localizedDisplay); + var localizedDisplay = NSBundle.MainBundle.LocalizedString (display, comment: "greeting"); + DisplayText.SetText (localizedDisplay); - try - { + try { // "language@2x.png" is located in the Watch Extension // multiple times: once for each language .lproj directory - using (var image = UIImage.FromBundle("language")) - { - // DisplayImage.SetImage(image); + using (var image = UIImage.FromBundle ("language")) { + // DisplayImage.SetImage(image); } - } - catch (Exception ex) { - DisplayText.SetText("Exception: " + ex.Message); + } catch (Exception ex) { + DisplayText.SetText ("Exception: " + ex.Message); } // easiest way to format date and/or time var localizedDateTime = NSDateFormatter.ToLocalizedString (NSDate.Now, NSDateFormatterStyle.Long, NSDateFormatterStyle.Short); - DisplayTime.SetText(localizedDateTime); + DisplayTime.SetText (localizedDateTime); // long way of date or time formatting @@ -68,5 +54,5 @@ public override void WillActivate() // formatter.Locale = NSLocale.CurrentLocale; // var localizedDateTime = formatter.StringFor (NSDate.Now); } - } -} \ No newline at end of file + } +} diff --git a/watchOS/WatchLocalization/Localization.WatchAppExtension/ExtensionDelegate.cs b/watchOS/WatchLocalization/Localization.WatchAppExtension/ExtensionDelegate.cs index 9225289fb..04fd471a4 100644 --- a/watchOS/WatchLocalization/Localization.WatchAppExtension/ExtensionDelegate.cs +++ b/watchOS/WatchLocalization/Localization.WatchAppExtension/ExtensionDelegate.cs @@ -1,25 +1,23 @@ -using System; +using System; using Foundation; using WatchKit; -namespace Localization.WatchAppExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - public override void ApplicationDidFinishLaunching() +namespace Localization.WatchAppExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + public override void ApplicationDidFinishLaunching () { // Perform any final initialization of your application. } - public override void ApplicationDidBecomeActive() + public override void ApplicationDidBecomeActive () { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void ApplicationWillResignActive() + public override void ApplicationWillResignActive () { // Sent when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions diff --git a/watchOS/WatchLocalization/Localization.WatchAppExtension/InterfaceController.cs b/watchOS/WatchLocalization/Localization.WatchAppExtension/InterfaceController.cs index 668856534..b3027dee0 100644 --- a/watchOS/WatchLocalization/Localization.WatchAppExtension/InterfaceController.cs +++ b/watchOS/WatchLocalization/Localization.WatchAppExtension/InterfaceController.cs @@ -1,35 +1,33 @@ -using System; +using System; using WatchKit; using Foundation; -namespace Localization.WatchAppExtension -{ - public partial class InterfaceController : WKInterfaceController - { - protected InterfaceController(IntPtr handle) : base(handle) +namespace Localization.WatchAppExtension { + public partial class InterfaceController : WKInterfaceController { + protected InterfaceController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); + Console.WriteLine ("{0} awake with context", this); } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } } } diff --git a/watchOS/WatchLocalization/Localization.WatchAppExtension/NotificationController.cs b/watchOS/WatchLocalization/Localization.WatchAppExtension/NotificationController.cs index d59a7aadf..9fadbbbf9 100644 --- a/watchOS/WatchLocalization/Localization.WatchAppExtension/NotificationController.cs +++ b/watchOS/WatchLocalization/Localization.WatchAppExtension/NotificationController.cs @@ -1,18 +1,16 @@ -using System; +using System; using WatchKit; using Foundation; -namespace Localization.WatchAppExtension -{ - public partial class NotificationController : WKUserNotificationInterfaceController - { - protected NotificationController(IntPtr handle) : base(handle) +namespace Localization.WatchAppExtension { + public partial class NotificationController : WKUserNotificationInterfaceController { + protected NotificationController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public NotificationController() + public NotificationController () { // Initialize variables here. // Configure interface objects here. @@ -38,16 +36,16 @@ public NotificationController() // completionHandler.Invoke (WKUserNotificationInterfaceType.Custom); // } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } } } diff --git a/watchOS/WatchLocalization/Localization/AppDelegate.cs b/watchOS/WatchLocalization/Localization/AppDelegate.cs index fcd163a96..0738d3c6d 100644 --- a/watchOS/WatchLocalization/Localization/AppDelegate.cs +++ b/watchOS/WatchLocalization/Localization/AppDelegate.cs @@ -1,22 +1,19 @@ -using Foundation; +using Foundation; using UIKit; -namespace Localization -{ +namespace Localization { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. - [Register("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + [Register ("AppDelegate")] + public class AppDelegate : UIApplicationDelegate { // class-level declarations - public override UIWindow Window - { + public override UIWindow Window { get; set; } - public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method @@ -24,7 +21,7 @@ public override bool FinishedLaunching(UIApplication application, NSDictionary l return true; } - public override void OnResignActivation(UIApplication application) + public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) @@ -32,25 +29,25 @@ public override void OnResignActivation(UIApplication application) // Games should use this method to pause the game. } - public override void DidEnterBackground(UIApplication application) + public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } - public override void WillEnterForeground(UIApplication application) + public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } - public override void OnActivated(UIApplication application) + public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void WillTerminate(UIApplication application) + public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } diff --git a/watchOS/WatchLocalization/Localization/Main.cs b/watchOS/WatchLocalization/Localization/Main.cs index 5be21203e..e54a5fa62 100644 --- a/watchOS/WatchLocalization/Localization/Main.cs +++ b/watchOS/WatchLocalization/Localization/Main.cs @@ -1,15 +1,13 @@ -using UIKit; +using UIKit; -namespace Localization -{ - public class Application - { +namespace Localization { + public class Application { // This is the main entry point of the application. - static void Main(string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. - UIApplication.Main(args, null, "AppDelegate"); + UIApplication.Main (args, null, "AppDelegate"); } } } diff --git a/watchOS/WatchLocalization/Localization/ViewController.cs b/watchOS/WatchLocalization/Localization/ViewController.cs index 386b0f485..150846a95 100644 --- a/watchOS/WatchLocalization/Localization/ViewController.cs +++ b/watchOS/WatchLocalization/Localization/ViewController.cs @@ -1,25 +1,23 @@ -using System; +using System; using UIKit; -namespace Localization -{ - public partial class ViewController : UIViewController - { - protected ViewController(IntPtr handle) : base(handle) +namespace Localization { + public partial class ViewController : UIViewController { + protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void ViewDidLoad() + public override void ViewDidLoad () { - base.ViewDidLoad(); + base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. } - public override void DidReceiveMemoryWarning() + public override void DidReceiveMemoryWarning () { - base.DidReceiveMemoryWarning(); + base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } diff --git a/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/ExtensionDelegate.cs b/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/ExtensionDelegate.cs index 4bcee8be6..9ad925234 100644 --- a/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/ExtensionDelegate.cs +++ b/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/ExtensionDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using WatchKit; -namespace WatchPuzzle.WatchKitAppExtension -{ +namespace WatchPuzzle.WatchKitAppExtension { [Register ("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { + public class ExtensionDelegate : WKExtensionDelegate { } } diff --git a/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/InterfaceController.cs b/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/InterfaceController.cs index 9a930f876..a7911a8ef 100644 --- a/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/InterfaceController.cs +++ b/watchOS/WatchPuzzle/WatchPuzzle.WatchKitAppExtension/InterfaceController.cs @@ -1,4 +1,4 @@ -using System; +using System; using CoreGraphics; using Foundation; @@ -8,18 +8,15 @@ using UIKit; using WatchKit; -namespace WatchPuzzle.WatchKitAppExtension -{ - public static class GameColors - { +namespace WatchPuzzle.WatchKitAppExtension { + public static class GameColors { public static readonly UIColor DefaultFont = new UIColor (31f / 255, 226f / 255, 63f / 255, 1); public static readonly UIColor Warning = UIColor.Orange; public static readonly UIColor Danger = UIColor.Red; } // A struct containing all the `SCNNode`s used in the game. - public struct GameNodes - { + public struct GameNodes { public readonly SCNNode Object; public readonly SCNMaterial ObjectMaterial; public readonly SCNNode Confetti; @@ -58,8 +55,7 @@ internal GameNodes (SCNNode sceneRoot) } } - public partial class InterfaceController : WKInterfaceController - { + public partial class InterfaceController : WKInterfaceController { [Outlet ("sceneInterface")] WKInterfaceSCNScene sceneInterface { get; set; } @@ -310,13 +306,13 @@ Vector3 SphereProjection (CGPoint location) var squaredLenght = location.X * location.X + location.Y * location.Y; if (squaredLenght <= 1) { - sphereCoord.X = (float)location.X; - sphereCoord.Y = (float)location.Y; - sphereCoord.Z = (float)NMath.Sqrt (1 - squaredLenght); + sphereCoord.X = (float) location.X; + sphereCoord.Y = (float) location.Y; + sphereCoord.Z = (float) NMath.Sqrt (1 - squaredLenght); } else { var n = 1f / NMath.Sqrt (squaredLenght); - sphereCoord.X = (float)(n * location.X); - sphereCoord.Y = (float)(n * location.Y); + sphereCoord.X = (float) (n * location.X); + sphereCoord.Y = (float) (n * location.Y); sphereCoord.Z = 0; } @@ -329,7 +325,7 @@ SCNMatrix4 RotationFromPoint (Vector3 start, Vector3 end) var axis = Vector3.Cross (start, end); var angle = NMath.Atan2 (axis.Length, Vector3.Dot (start, end)); - return SCNMatrix4.CreateFromAxisAngle (axis, (float)angle); + return SCNMatrix4.CreateFromAxisAngle (axis, (float) angle); } // End the game if the object has its initial orientation with a 10 degree tolerance. diff --git a/watchOS/WatchPuzzle/WatchPuzzle/AppDelegate.cs b/watchOS/WatchPuzzle/WatchPuzzle/AppDelegate.cs index b6917ce62..b09b66f46 100644 --- a/watchOS/WatchPuzzle/WatchPuzzle/AppDelegate.cs +++ b/watchOS/WatchPuzzle/WatchPuzzle/AppDelegate.cs @@ -1,11 +1,9 @@ -using Foundation; +using Foundation; using UIKit; -namespace WatchPuzzle -{ +namespace WatchPuzzle { [Register ("AppDelegate")] - public class AppDelegate : UIApplicationDelegate - { + public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } } } diff --git a/watchOS/WatchPuzzle/WatchPuzzle/Main.cs b/watchOS/WatchPuzzle/WatchPuzzle/Main.cs index 9852dad05..ad4da2368 100644 --- a/watchOS/WatchPuzzle/WatchPuzzle/Main.cs +++ b/watchOS/WatchPuzzle/WatchPuzzle/Main.cs @@ -1,9 +1,7 @@ -using UIKit; +using UIKit; -namespace WatchPuzzle -{ - public class Application - { +namespace WatchPuzzle { + public class Application { // This is the main entry point of the application. static void Main (string [] args) { diff --git a/watchOS/WatchPuzzle/WatchPuzzle/ViewController.cs b/watchOS/WatchPuzzle/WatchPuzzle/ViewController.cs index ddd514afc..51a7336fa 100644 --- a/watchOS/WatchPuzzle/WatchPuzzle/ViewController.cs +++ b/watchOS/WatchPuzzle/WatchPuzzle/ViewController.cs @@ -1,11 +1,9 @@ -using System; +using System; using UIKit; -namespace WatchPuzzle -{ - public partial class ViewController : UIViewController - { +namespace WatchPuzzle { + public partial class ViewController : UIViewController { protected ViewController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. diff --git a/watchOS/WatchTables/WatchTables.OnWatchExtension/DetailController.cs b/watchOS/WatchTables/WatchTables.OnWatchExtension/DetailController.cs index 0f3c49c6d..f7264fd0a 100644 --- a/watchOS/WatchTables/WatchTables.OnWatchExtension/DetailController.cs +++ b/watchOS/WatchTables/WatchTables.OnWatchExtension/DetailController.cs @@ -1,35 +1,32 @@ -using Foundation; -using System; -using UIKit; +using Foundation; +using System; +using UIKit; using WatchKit; -namespace WatchTables.OnWatchExtension -{ - public partial class DetailController : WKInterfaceController - { +namespace WatchTables.OnWatchExtension { + public partial class DetailController : WKInterfaceController { string contextFromPreviousScreen = ""; - - public DetailController(IntPtr handle) : base(handle) + + public DetailController (IntPtr handle) : base (handle) { } - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); // Configure interface objects here. - if (context is NSString) - { - contextFromPreviousScreen = context.ToString(); + if (context is NSString) { + contextFromPreviousScreen = context.ToString (); } - Console.WriteLine("{0} awake with context", this); + Console.WriteLine ("{0} awake with context", this); } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); - SelectedLabel.SetText(contextFromPreviousScreen); - } - } -} \ No newline at end of file + SelectedLabel.SetText (contextFromPreviousScreen); + } + } +} diff --git a/watchOS/WatchTables/WatchTables.OnWatchExtension/ExtensionDelegate.cs b/watchOS/WatchTables/WatchTables.OnWatchExtension/ExtensionDelegate.cs index f451ea3c9..2c3fbcaf8 100644 --- a/watchOS/WatchTables/WatchTables.OnWatchExtension/ExtensionDelegate.cs +++ b/watchOS/WatchTables/WatchTables.OnWatchExtension/ExtensionDelegate.cs @@ -1,25 +1,23 @@ -using System; +using System; using Foundation; using WatchKit; -namespace WatchTables.OnWatchExtension -{ - [Register("ExtensionDelegate")] - public class ExtensionDelegate : WKExtensionDelegate - { - public override void ApplicationDidFinishLaunching() +namespace WatchTables.OnWatchExtension { + [Register ("ExtensionDelegate")] + public class ExtensionDelegate : WKExtensionDelegate { + public override void ApplicationDidFinishLaunching () { // Perform any final initialization of your application. } - public override void ApplicationDidBecomeActive() + public override void ApplicationDidBecomeActive () { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } - public override void ApplicationWillResignActive() + public override void ApplicationWillResignActive () { // Sent when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions diff --git a/watchOS/WatchTables/WatchTables.OnWatchExtension/InterfaceController.cs b/watchOS/WatchTables/WatchTables.OnWatchExtension/InterfaceController.cs index 879628182..354b343ae 100644 --- a/watchOS/WatchTables/WatchTables.OnWatchExtension/InterfaceController.cs +++ b/watchOS/WatchTables/WatchTables.OnWatchExtension/InterfaceController.cs @@ -1,71 +1,68 @@ -using System; +using System; using WatchKit; using Foundation; using System.Collections.Generic; -namespace WatchTables.OnWatchExtension -{ - public partial class InterfaceController : WKInterfaceController - { - List<string> rows = new List<string>(); +namespace WatchTables.OnWatchExtension { + public partial class InterfaceController : WKInterfaceController { + List<string> rows = new List<string> (); - protected InterfaceController(IntPtr handle) : base(handle) + protected InterfaceController (IntPtr handle) : base (handle) { // Note: this .ctor should not contain any initialization logic. } - public override void Awake(NSObject context) + public override void Awake (NSObject context) { - base.Awake(context); + base.Awake (context); // Configure interface objects here. - Console.WriteLine("{0} awake with context", this); + Console.WriteLine ("{0} awake with context", this); - rows.Add("row1"); - rows.Add("row2"); - rows.Add("row3"); - rows.Add("row4"); - rows.Add("row5"); + rows.Add ("row1"); + rows.Add ("row2"); + rows.Add ("row3"); + rows.Add ("row4"); + rows.Add ("row5"); } - public override void WillActivate() + public override void WillActivate () { // This method is called when the watch view controller is about to be visible to the user. - Console.WriteLine("{0} will activate", this); + Console.WriteLine ("{0} will activate", this); - LoadTableRows(); + LoadTableRows (); } - public override void DidDeactivate() + public override void DidDeactivate () { // This method is called when the watch view controller is no longer visible to the user. - Console.WriteLine("{0} did deactivate", this); + Console.WriteLine ("{0} did deactivate", this); } - public override NSObject GetContextForSegue(string segueIdentifier, WKInterfaceTable table, nint rowIndex) + public override NSObject GetContextForSegue (string segueIdentifier, WKInterfaceTable table, nint rowIndex) { // retrieved in DetailController.Awake() - return new NSString(rows[(int)rowIndex]); + return new NSString (rows [(int) rowIndex]); } - void LoadTableRows() + void LoadTableRows () { - MyTable.SetNumberOfRows((nint)rows.Count, "default"); + MyTable.SetNumberOfRows ((nint) rows.Count, "default"); //MyTable.SetRowTypes (new [] {"default", "type1", "type2", "default", "default"}); // Create all of the table rows. - for (var i = 0; i < rows.Count; i++) - { - var elementRow = (RowController)MyTable.GetRowController(i); + for (var i = 0; i < rows.Count; i++) { + var elementRow = (RowController) MyTable.GetRowController (i); - elementRow.MyLabel.SetText(rows[i]); + elementRow.MyLabel.SetText (rows [i]); } } - public override void DidSelectRow(WKInterfaceTable table, nint rowIndex) + public override void DidSelectRow (WKInterfaceTable table, nint rowIndex) { - var rowData = rows[(int)rowIndex]; - Console.WriteLine("Row selected:" + rowData); + var rowData = rows [(int) rowIndex]; + Console.WriteLine ("Row selected:" + rowData); } } } diff --git a/watchOS/WatchTables/WatchTables.OnWatchExtension/RowController.cs b/watchOS/WatchTables/WatchTables.OnWatchExtension/RowController.cs index a3694b759..703d66065 100644 --- a/watchOS/WatchTables/WatchTables.OnWatchExtension/RowController.cs +++ b/watchOS/WatchTables/WatchTables.OnWatchExtension/RowController.cs @@ -1,12 +1,10 @@ -using Foundation; -using System; - -namespace WatchTables.OnWatchExtension -{ - public partial class RowController : NSObject - { - public RowController (IntPtr handle) : base (handle) - { - } - } -} \ No newline at end of file +using Foundation; +using System; + +namespace WatchTables.OnWatchExtension { + public partial class RowController : NSObject { + public RowController (IntPtr handle) : base (handle) + { + } + } +} diff --git a/watchOS/WatchTables/WatchTables/AppDelegate.cs b/watchOS/WatchTables/WatchTables/AppDelegate.cs index a8de66f46..4ead40b5d 100644 --- a/watchOS/WatchTables/WatchTables/AppDelegate.cs +++ b/watchOS/WatchTables/WatchTables/AppDelegate.cs @@ -1,43 +1,41 @@ -using System; +using System; using System.Linq; using System.Collections.Generic; using Foundation; using UIKit; -namespace WatchTables -{ +namespace WatchTables { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register ("AppDelegate")] - public partial class AppDelegate : UIApplicationDelegate - { + public partial class AppDelegate : UIApplicationDelegate { // class-level declarations - + public override UIWindow Window { get; set; } - + // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation (UIApplication application) { } - + // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground (UIApplication application) { } - + // This method is called as part of the transiton from background to active state. public override void WillEnterForeground (UIApplication application) { } - + // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate (UIApplication application) { diff --git a/watchOS/WatchTables/WatchTables/Main.cs b/watchOS/WatchTables/WatchTables/Main.cs index a0c1d3019..429247a78 100644 --- a/watchOS/WatchTables/WatchTables/Main.cs +++ b/watchOS/WatchTables/WatchTables/Main.cs @@ -1,16 +1,14 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; -namespace WatchTables -{ - public class Application - { +namespace WatchTables { + public class Application { // This is the main entry point of the application. - static void Main (string[] args) + static void Main (string [] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. diff --git a/watchOS/WatchTables/WatchTables/WatchTablesViewController.cs b/watchOS/WatchTables/WatchTables/WatchTablesViewController.cs index 07c79c251..14ba8f3c0 100644 --- a/watchOS/WatchTables/WatchTables/WatchTablesViewController.cs +++ b/watchOS/WatchTables/WatchTables/WatchTablesViewController.cs @@ -1,13 +1,11 @@ -using System; +using System; using System.Drawing; using Foundation; using UIKit; -namespace WatchTables -{ - public partial class WatchTablesViewController : UIViewController - { +namespace WatchTables { + public partial class WatchTablesViewController : UIViewController { public WatchTablesViewController (IntPtr handle) : base (handle) { } @@ -16,7 +14,7 @@ public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); - + // Release any cached data, images, etc that aren't in use. } @@ -25,7 +23,7 @@ public override void DidReceiveMemoryWarning () public override void ViewDidLoad () { base.ViewDidLoad (); - + // Perform any additional setup after loading the view, typically from a nib. }