Esempio n. 1
0
 private void InitPlayerForeground(string url, AVUrlAsset asset)
 {
     playEndHandle = NSNotificationCenter.DefaultCenter.AddObserver(AVPlayerItem.DidPlayToEndTimeNotification, HandlePlayEnd);
     if (player == null)
     {
         currentItem = new AVPlayerItem(asset);
         player      = new AVPlayer(currentItem);
         player.AddPeriodicTimeObserver(new CMTime(1, 1), DispatchQueue.MainQueue, TimeUpdate);
     }
     else
     {
         currentItem.Dispose();
         currentItem = new AVPlayerItem(
             new AVUrlAsset(NSUrl.FromString(url),
                            new AVUrlAssetOptions(NSDictionary.FromObjectAndKey(
                                                      NSNumber.FromBoolean(true),
                                                      AVUrlAsset.PreferPreciseDurationAndTimingKey))));
         player.ReplaceCurrentItemWithPlayerItem(currentItem);
     }
     Debug.WriteLine("InitPlayerForeground done");
 }
Esempio n. 2
0
        private void UpdateScanTab()
        {
            NSDictionary param = NSDictionary.FromObjectAndKey(NSNumber.FromBoolean(mergeScanResultsCheckbox.State == NSCellStateValue.On), new NSString("true"));
            NSError      error = null;

            ScanResults = CurrentInterface.ScanForNetworksWithParameters(param, out error);
            if (error == null)
            {
                Array.Sort(ScanResults, delegate(CWNetwork networkA, CWNetwork networkB)
                {
                    return(networkA.Ssid.CompareTo(networkB.Ssid));
                });
            }
            else
            {
                ScanResults = new CWNetwork[0];
                NSAlert.WithError(error).RunModal();
            }

            scanResultsTable.ReloadData();
        }
Esempio n. 3
0
        public RosyWriterPreviewWindow(RectangleF frame) : base(frame)
        {
            // Use 2x scale factor on Retina dispalys.
            ContentScaleFactor = UIScreen.MainScreen.Scale;

            // Initialize OpenGL ES 2
            CAEAGLLayer eagleLayer = (CAEAGLLayer)Layer;

            eagleLayer.Opaque             = true;
            eagleLayer.DrawableProperties = NSDictionary.FromObjectsAndKeys(
                new object[] { NSNumber.FromBoolean(false), EAGLColorFormat.RGBA8 },
                new object[] { EAGLDrawableProperty.RetainedBacking, EAGLDrawableProperty.ColorFormat }
                );

            Context = new EAGLContext(EAGLRenderingAPI.OpenGLES2);

            if (!EAGLContext.SetCurrentContext(Context))
            {
                throw new ApplicationException("Could not set EAGLContext");
            }
        }
Esempio n. 4
0
        private void CreateContext()
        {
            AssertNotDisposed();

            Layer.DrawableProperties = NSDictionary.FromObjectsAndKeys(
                new NSObject [] {
                NSNumber.FromBoolean(true),
                EAGLColorFormat.RGBA8
            },
                new NSObject [] {
                EAGLDrawableProperty.RetainedBacking,
                EAGLDrawableProperty.ColorFormat
            });

            Layer.ContentsScale = Window.Screen.Scale;

            //var strVersion = OpenTK.Graphics.ES11.GL.GetString (OpenTK.Graphics.ES11.All.Version);
            //strVersion = OpenTK.Graphics.ES20.GL.GetString (OpenTK.Graphics.ES20.All.Version);
            //var version = Version.Parse (strVersion);

            EAGLRenderingAPI eaglRenderingAPI;

//			try {
//				_graphicsContext = new GraphicsContext (null, null, 2, 0, GraphicsContextFlags.Embedded);
//				eaglRenderingAPI = EAGLRenderingAPI.OpenGLES2;
//				_glapi = new Gles20Api ();
//			} catch {
            {
                _graphicsContext = new GraphicsContext(null, null, 1, 1, GraphicsContextFlags.Embedded);
                eaglRenderingAPI = EAGLRenderingAPI.OpenGLES1;
                _glapi           = new Gles11Api();
            }

            _graphicsContext.MakeCurrent(null);
            // Should not be required any more _graphicsContext.LoadAll ();

            // FIXME: These static methods on GraphicsDevice need
            // to go away someday.
            GraphicsDevice.OpenGLESVersion = eaglRenderingAPI;
        }
Esempio n. 5
0
        public void StartRecording(string fileName)
        {
            InitializeAudioSession();

            _fileName     = fileName + ".wav";
            _fullFilePath = Path.Combine(Path.GetTempPath(), _fileName);

            Console.WriteLine("Audio File Path: " + _fullFilePath);

            _url = NSUrl.FromFilename(_fullFilePath);
            //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
            NSObject[] values =
            {
                NSNumber.FromFloat(44100.0f),                                    //Sample Rate
                NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.LinearPCM), //AVFormat
                NSNumber.FromInt32(2),                                           //Channels
                NSNumber.FromInt32(16),                                          //PCMBitDepth
                NSNumber.FromBoolean(false),                                     //IsBigEndianKey
                NSNumber.FromBoolean(false)                                      //IsFloatKey
            };

            //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
            NSObject[] keys =
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };

            //Set Settings with the Values and Keys to create the NSDictionary
            _settings = NSDictionary.FromObjectsAndKeys(values, keys);

            //Set recorder parameters
            _recorder = AVAudioRecorder.Create(_url, new AudioSettings(_settings), out _);
            _recorder.PrepareToRecord();
            _recorder.Record();
        }
Esempio n. 6
0
        public void KeyEncryption()
        {
            const int keySize              = 512;
            string    keyIdentifier        = Guid.NewGuid().ToString();
            string    publicKeyIdentifier  = GetPublicKeyIdentifierWithTag(keyIdentifier);
            string    privateKeyIdentifier = GetPrivateKeyIdentifierWithTag(keyIdentifier);

            // Configure parameters for the joint keypair.
            var keyPairAttr = new NSMutableDictionary();

            keyPairAttr[KSec.AttrKeyType]       = KSec.AttrKeyTypeRSA;
            keyPairAttr[KSec.AttrKeySizeInBits] = NSNumber.FromInt32(keySize);

            // Configure parameters for the private key
            var privateKeyAttr = new NSMutableDictionary();

            privateKeyAttr[KSec.AttrIsPermanent]    = NSNumber.FromBoolean(true);
            privateKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(privateKeyIdentifier, NSStringEncoding.UTF8);

            // Configure parameters for the public key
            var publicKeyAttr = new NSMutableDictionary();

            publicKeyAttr[KSec.AttrIsPermanent]    = NSNumber.FromBoolean(true);
            publicKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(publicKeyIdentifier, NSStringEncoding.UTF8);

            // Parent the individual key parameters to the keypair one.
            keyPairAttr[KSec.PublicKeyAttrs]  = publicKeyAttr;
            keyPairAttr[KSec.PrivateKeyAttrs] = privateKeyAttr;

            // Generate the RSA key.
            SecKey        publicKey, privateKey;
            SecStatusCode code = SecKey.GenerateKeyPair(keyPairAttr, out publicKey, out privateKey);

            Verify.Operation(code == SecStatusCode.Success, "status was " + code);

            byte[] plainText = new byte[0]; // when this buffer is non-empty, Encrypt works!
            byte[] cipherText;
            code = publicKey.Encrypt(SecPadding.OAEP, plainText, out cipherText);
            Verify.Operation(code == SecStatusCode.Success, "status was " + code);
        }
Esempio n. 7
0
        private void CreateContext()
        {
            AssertNotDisposed();

            // RetainedBacking controls if the content of the colorbuffer should be preserved after being displayed
            // This is the XNA equivalent to set PreserveContent when initializing the GraphicsDevice
            // (should be false by default for better performance)
            Layer.DrawableProperties = NSDictionary.FromObjectsAndKeys
                                       (
                new NSObject []
            {
                NSNumber.FromBoolean(false),
                EAGLColorFormat.RGBA8
            },
                new NSObject []
            {
                EAGLDrawableProperty.RetainedBacking,
                EAGLDrawableProperty.ColorFormat
            }
                                       );

            Layer.ContentsScale = Window.Screen.Scale;

            //var strVersion = OpenTK.Graphics.ES11.GL.GetString (OpenTK.Graphics.ES11.All.Version);
            //strVersion = OpenTK.Graphics.ES20.GL.GetString (OpenTK.Graphics.ES20.All.Version);
            //var version = Version.Parse (strVersion);

            try
            {
                __renderbuffergraphicsContext = new GraphicsContext(null, null, 2, 0, GraphicsContextFlags.Embedded);
                _glapi = new Gles20Api();
            }
            catch
            {
                __renderbuffergraphicsContext = new GraphicsContext(null, null, 1, 1, GraphicsContextFlags.Embedded);
                _glapi = new Gles11Api();
            }

            __renderbuffergraphicsContext.MakeCurrent(null);
        }
Esempio n. 8
0
        public EAGLView(RectangleF frame) : base(frame)
        {
            CAEAGLLayer eagl = (CAEAGLLayer)Layer;

            eagl.DrawableProperties = NSDictionary.FromObjectsAndKeys(new NSObject[] {
                NSNumber.FromBoolean(true),
                EAGLColorFormat.RGBA8
            }, new NSObject[] {
                EAGLDrawableProperty.RetainedBacking,
                EAGLDrawableProperty.ColorFormat
            });

            eagl.ContentsScale = UIScreen.MainScreen.Scale;

            context = (iPhoneOSGraphicsContext)((IGraphicsContextInternal)GraphicsContext.CurrentContext).Implementation;

            CAEAGLLayer eaglLayer = (CAEAGLLayer)Layer;

            context.MakeCurrent(null);

            GL.Oes.GenRenderbuffers(1, out renderbuffer);
            GL.Oes.BindRenderbuffer(All.RenderbufferOes, renderbuffer);

            if (!context.EAGLContext.RenderBufferStorage((uint)All.RenderbufferOes, eaglLayer))
            {
                throw new InvalidOperationException("Error with RenderbufferStorage()!");
            }

            GL.Oes.GenFramebuffers(1, out frameBuffer);
            GL.Oes.BindFramebuffer(All.FramebufferOes, frameBuffer);
            GL.Oes.FramebufferRenderbuffer(All.FramebufferOes, All.ColorAttachment0Oes, All.RenderbufferOes, renderbuffer);

            Instance = this;

            Opaque                 = true;
            ExclusiveTouch         = true;
            MultipleTouchEnabled   = true;
            UserInteractionEnabled = true;
        }
Esempio n. 9
0
        /// <inheritdoc/>
        public ICryptographicKey CreateKeyPair(int keySize)
        {
            Requires.Range(keySize > 0, "keySize");

            string keyIdentifier        = Guid.NewGuid().ToString();
            string publicKeyIdentifier  = RsaCryptographicKey.GetPublicKeyIdentifierWithTag(keyIdentifier);
            string privateKeyIdentifier = RsaCryptographicKey.GetPrivateKeyIdentifierWithTag(keyIdentifier);

            // Configure parameters for the joint keypair.
            var keyPairAttr = new NSMutableDictionary();

            keyPairAttr[KSec.AttrKeyType]       = KSec.AttrKeyTypeRSA;
            keyPairAttr[KSec.AttrKeySizeInBits] = NSNumber.FromInt32(keySize);

            // Configure parameters for the private key
            var privateKeyAttr = new NSMutableDictionary();

            privateKeyAttr[KSec.AttrIsPermanent]    = NSNumber.FromBoolean(true);
            privateKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(privateKeyIdentifier, NSStringEncoding.UTF8);

            // Configure parameters for the public key
            var publicKeyAttr = new NSMutableDictionary();

            publicKeyAttr[KSec.AttrIsPermanent]    = NSNumber.FromBoolean(true);
            publicKeyAttr[KSec.AttrApplicationTag] = NSData.FromString(publicKeyIdentifier, NSStringEncoding.UTF8);

            // Parent the individual key parameters to the keypair one.
            keyPairAttr[KSec.PublicKeyAttrs]  = publicKeyAttr;
            keyPairAttr[KSec.PrivateKeyAttrs] = privateKeyAttr;

            // Generate the RSA key.
            SecKey        publicKey, privateKey;
            SecStatusCode code = SecKey.GenerateKeyPair(keyPairAttr, out publicKey, out privateKey);

            Verify.Operation(code == SecStatusCode.Success, "status was " + code);

            return(new RsaCryptographicKey(publicKey, privateKey, keyIdentifier, this.algorithm));
        }
Esempio n. 10
0
        private void InitialiseAudioRecorder()
        {
            var outputFilePath = CrossStorage.FileSystem.LocalStorage
                                 .CreateFile(this.outputFilename, CreationCollisionOption.ReplaceExisting)
                                 .FullPath;

            var url = NSUrl.FromFilename(outputFilePath);

            var values = new NSObject[]
            {
                NSNumber.FromFloat(this.SAMPLE_RATE),
                NSNumber.FromInt32(this.AUDIO_FORMAT_TYPE),
                NSNumber.FromInt32(this.CHANNEL),
                NSNumber.FromInt32(this.BITS_PER_SAMPLE),
                NSNumber.FromBoolean(this.IS_BIG_ENDIAN_KEY),
                NSNumber.FromBoolean(this.IS_FLOAT_KEY)
            };

            var keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };

            var settingsDictionary = NSDictionary.FromObjectsAndKeys(values, keys);
            var audioSettings      = new AudioSettings(settingsDictionary);

            this._audioRecorder = AVAudioRecorder.Create(url, audioSettings, out NSError error);

            if (error != null)
            {
                throw new MicrophoneServiceException("AudioRecorder creation error !");
            }
        }
Esempio n. 11
0
        //
        // 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)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            var dict = NSDictionary.FromObjectAndKey((NSString)"MANAGE_PERMISSIONS", NSNumber.FromBoolean(false));

            Gimbal.SetAPIKey("5fba002a-5a07-424e-8fa2-decf01fa96d3", dict);

            if (options != null && options.ContainsKey(UIApplication.LaunchOptionsRemoteNotificationKey))
            {
                ProcessRemoteNotification(options[UIApplication.LaunchOptionsRemoteNotificationKey] as NSDictionary);
            }

            if (options != null && options.ContainsKey(UIApplication.LaunchOptionsLocalNotificationKey))
            {
                ProcessLocalNotification(options[UIApplication.LaunchOptionsLocationKey] as UILocalNotification, UIApplication.SharedApplication.ApplicationState);
            }

            RegisterForNotifications(app);

            return(base.FinishedLaunching(app, options));
        }
Esempio n. 12
0
        /// <summary>
        /// Initialize the BlazorWebView.
        /// </summary>
        /// <param name="configure">A delegate that is executed to configure the webview.</param>
        public void Initialize(Action <WebViewOptions> configure)
        {
            var options = new WebViewOptions();

            configure.Invoke(options);

            var webConfig = new WKWebViewConfiguration();

            webConfig.UserContentController = new WKUserContentController();
            webConfig.UserContentController.AddUserScript(new WKUserScript((NSString)InitScriptSource, WKUserScriptInjectionTime.AtDocumentStart, true));
            webConfig.Preferences.SetValueForKey(NSNumber.FromBoolean(true), (NSString)"developerExtrasEnabled");
            webConfig.UserContentController.AddScriptMessageHandler(this, "blazorwebviewinterop");

            foreach (var(schemeName, handler) in options.SchemeHandlers)
            {
                this.AddCustomScheme(webConfig, schemeName, handler);
            }

            this.webView = new WKWebView(this.Frame, webConfig);
            this.webView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
            this.AddSubview(this.webView);
            this.AutosizesSubviews = true;
        }
Esempio n. 13
0
 protected override async System.Threading.Tasks.Task <bool> Sync()
 {
     if (Disabled)
     {
         return(true);
     }
     return(await Task.Run(async() => {
         try{
             await Database.Main.ExecuteAsync("update Track set Deleted = 1 where ServiceId = ?", Id);
             var mediaQuery = MPMediaQuery.SongsQuery;
             var predicate = MPMediaPropertyPredicate.PredicateWithValue(NSNumber.FromBoolean(false), MPMediaItem.IsCloudItemProperty);
             mediaQuery.AddFilterPredicate(predicate);
             var items = mediaQuery.Items.Where(x => x.AssetURL != null && !string.IsNullOrEmpty(x.AssetURL.AbsoluteString)).Select(x => new FullTrackData(x.Title, x.Artist, x.AlbumArtist, x.AlbumTitle, x.Genre)
             {
                 Id = x.PersistentID.ToString(),
                 AlbumServerId = x.AlbumPersistentID.ToString(),
                 Disc = x.DiscNumber,
                 Duration = x.PlaybackDuration,
                 FileExtension = "mp3",
                 MediaType = MediaType.Audio,
                 Priority = 1,
                 ServiceId = Id,
                 ServiceType = ServiceType,
                 Track = x.AlbumTrackNumber,
                 //				Year = x.ReleaseDate
             });
             await items.BatchForeach(100, (batch) => MusicProvider.ProcessTracks(batch.ToList()));
             await FinalizeProcessing(Id);
             return true;
         }
         catch (Exception ex)
         {
             LogManager.Shared.Report(ex);
             return false;
         }
     }));
 }
Esempio n. 14
0
        public void StartRecording(string path)
        {
            try
            {
                path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), path); // this line is added to place file in iOS temp directory, may not be required in Halza app
                var audioSession = AVAudioSession.SharedInstance();
                audioSession.RequestRecordPermission(delegate(bool granted)
                {
                    if (granted)
                    {
                        var err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);
                        if (err != null)
                        {
                            Console.WriteLine("audioSession: {0}", err);
                        }
                        err = audioSession.SetActive(true);
                        if (err != null)
                        {
                            Console.WriteLine("audioSession: {0}", err);
                        }

                        url = NSUrl.FromFilename(path);
                        //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
                        NSObject[] values = new NSObject[]
                        {
                            NSNumber.FromFloat(16000),                                      //Sample Rate
                            NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.MPEG4AAC), //AVFormat
                            //NSNumber.FromInt32 ((int)AudioToolbox.AudioFormatType.LinearPCM), //AVFormat
                            NSNumber.FromInt32(2),                                          //Channels
                            NSNumber.FromInt32(16),                                         //PCMBitDepth
                            NSNumber.FromBoolean(false),                                    //IsBigEndianKey
                            NSNumber.FromBoolean(false)                                     //IsFloatKey
                        };

                        //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
                        NSObject[] keys = new NSObject[]
                        {
                            AVAudioSettings.AVSampleRateKey,
                            AVAudioSettings.AVFormatIDKey,
                            AVAudioSettings.AVNumberOfChannelsKey,
                            AVAudioSettings.AVLinearPCMBitDepthKey,
                            AVAudioSettings.AVLinearPCMIsBigEndianKey,
                            AVAudioSettings.AVLinearPCMIsFloatKey
                        };

                        //Set Settings with the Values and Keys to create the NSDictionary
                        settings = NSDictionary.FromObjectsAndKeys(values, keys);

                        //Set recorder parameters
                        recorder = AVAudioRecorder.Create(url, new AudioSettings(settings), out error);

                        //Set Recorder to Prepare To Record
                        recorder.PrepareToRecord();

                        recorder.Record();
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 15
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();

            Image.Layer.MasksToBounds = true;
            Image.Layer.CornerRadius = Image.Bounds.Height / 2f;

            Body.LinkAttributes = new NSDictionary();
            Body.ActiveLinkAttributes = new NSMutableDictionary();
            Body.ActiveLinkAttributes[CoreText.CTStringAttributeKey.UnderlineStyle] = NSNumber.FromBoolean(true);

            Header.LinkAttributes = new NSDictionary();
            Header.ActiveLinkAttributes = new NSMutableDictionary();
            Header.ActiveLinkAttributes[CoreText.CTStringAttributeKey.UnderlineStyle] = NSNumber.FromBoolean(true);

            DefaultContentConstraint = ContentConstraint.Constant;

            ActionImage.TintColor = Time.TextColor;
        }
            public bool InitializeRecordService(string path = "")
            {
                var audioSession = AVAudioSession.SharedInstance();
                var err          = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);

                if (err != null)
                {
                    Console.WriteLine("audioSession: {0}", err);
                    return(false);
                }
                err = audioSession.SetActive(true);
                if (err != null)
                {
                    Console.WriteLine("audioSession: {0}", err);
                    return(false);
                }

                //Declare string for application temp path and tack on the file extension
                if (path.Length == 0)
                {
                    path = Path.GetTempPath();
                }

                string fileName      = string.Format("audio{0}.wav", DateTime.Now.ToString("yyyyMMddHHmmss"));
                string audioFilePath = Path.Combine(path, fileName);

                Console.WriteLine("Audio File Path: " + audioFilePath);
                _path = audioFilePath;

                _url = NSUrl.FromFilename(audioFilePath);
                //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
                NSObject[] values = new NSObject[]
                {
                    NSNumber.FromFloat(44100.0f),                                    //Sample Rate
                    NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.LinearPCM), //AVFormat
                    NSNumber.FromInt32(2),                                           //Channels
                    NSNumber.FromInt32(16),                                          //PCMBitDepth
                    NSNumber.FromBoolean(false),                                     //IsBigEndianKey
                    NSNumber.FromBoolean(false)                                      //IsFloatKey
                };

                //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
                NSObject[] keys = new NSObject[]
                {
                    AVAudioSettings.AVSampleRateKey,
                    AVAudioSettings.AVFormatIDKey,
                    AVAudioSettings.AVNumberOfChannelsKey,
                    AVAudioSettings.AVLinearPCMBitDepthKey,
                    AVAudioSettings.AVLinearPCMIsBigEndianKey,
                    AVAudioSettings.AVLinearPCMIsFloatKey
                };

                //Set Settings with the Values and Keys to create the NSDictionary
                _settings = NSDictionary.FromObjectsAndKeys(values, keys);

                //Set recorder parameters
                _recorder = AVAudioRecorder.Create(_url, new AudioSettings(_settings), out _error);

                //Set Recorder to Prepare To Record


                return(_recorder.PrepareToRecord());
            }
Esempio n. 17
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();

            Image.Layer.MasksToBounds = true;
            Image.Layer.CornerRadius  = Image.Bounds.Height / 2f;
            ContentView.Opaque        = true;

            SeparatorInset            = EdgeInsets;
            Body.LinkAttributes       = new NSDictionary();
            Body.ActiveLinkAttributes = new NSMutableDictionary();
            Body.ActiveLinkAttributes[MonoTouch.CoreText.CTStringAttributeKey.UnderlineStyle] = NSNumber.FromBoolean(true);
            Body.Lines         = 0;
            Body.LineBreakMode = UILineBreakMode.TailTruncation;

            Header.LinkAttributes       = new NSDictionary();
            Header.ActiveLinkAttributes = new NSMutableDictionary();
            Header.ActiveLinkAttributes[MonoTouch.CoreText.CTStringAttributeKey.UnderlineStyle] = NSNumber.FromBoolean(true);
            Header.Lines         = 2;
            Header.LineBreakMode = UILineBreakMode.TailTruncation;

            // Special for large fonts
            if (Theme.CurrentTheme.FontSizeRatio > 1.0f)
            {
                Header.Font = HeaderFont;
                Body.Font   = BodyFont;
                Time.Font   = TimeFont;

                var timeSectionheight = (float)Math.Ceiling(TimeFont.LineHeight);
                var timeFrame         = Time.Frame;
                timeFrame.Height = timeSectionheight;
                Time.Frame       = timeFrame;

                var imageFrame = ActionImage.Frame;
                imageFrame.Y     += (timeFrame.Height - imageFrame.Height) / 2f;
                ActionImage.Frame = imageFrame;

                var headerSectionheight = (float)Math.Ceiling(TimeFont.LineHeight);
                var headerFrame         = Header.Frame;
                headerFrame.Height = headerSectionheight * 2f + (float)Math.Ceiling(3f * Theme.CurrentTheme.FontSizeRatio);
                headerFrame.Y      = 6 + timeFrame.Height + 5f;
                Header.Frame       = headerFrame;

                var picFrame = Image.Frame;
                picFrame.Y  = 6 + timeFrame.Height + 5f;
                picFrame.Y += (headerFrame.Height - picFrame.Height) / 2f;
                Image.Frame = picFrame;

                var bodyFrame = Body.Frame;
                bodyFrame.Y = headerFrame.Y + headerFrame.Height + 4f;
                Body.Frame  = bodyFrame;
            }

            this.WhenAnyValue(x => x.ViewModel)
            .Where(x => x != null)
            .Subscribe(x =>
            {
                var avatar = x.Event.Actor != null ? x.Event.Actor.AvatarUrl : null;
                if (avatar != null)
                {
                    Image.SetImage(new NSUrl(x.Event.Actor.AvatarUrl), Images.LoginUserUnknown);
                }
                else
                {
                    Image.Image = null;
                }

                ActionImage.Image = ChooseImage(x.Event);
                Time.Text         = x.Event.CreatedAt.ToDaysAgo();

                List <NewsCellView.Link> headerLinks;
                HeaderString = CreateAttributedStringFromBlocks(x.HeaderBlocks, out headerLinks);

                List <NewsCellView.Link> bodyLinks;
                BodyString = CreateAttributedStringFromBlocks(x.BodyBlocks, out bodyLinks);

                this.Header.Text     = HeaderString;
                this.Header.Delegate = new LabelDelegate(headerLinks, w => {});

                this.Body.Text     = BodyString;
                this.Body.Hidden   = BodyString.Length == 0;
                this.Body.Delegate = new LabelDelegate(bodyLinks, w => {});

                foreach (var b in headerLinks)
                {
                    this.Header.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range);
                }

                foreach (var b in bodyLinks)
                {
                    this.Body.AddLinkToURL(new NSUrl(b.Id.ToString()), b.Range);
                }
            });
        }
Esempio n. 18
0
        public static NewsCellView Create()
        {
            var cell = (NewsCellView)Nib.Instantiate(null, null)[0];

            cell.SeparatorInset            = EdgeInsets;
            cell.Body.LinkAttributes       = new NSDictionary();
            cell.Body.ActiveLinkAttributes = new NSMutableDictionary();
            cell.Body.ActiveLinkAttributes[MonoTouch.CoreText.CTStringAttributeKey.UnderlineStyle] = NSNumber.FromBoolean(true);
            cell.Body.Lines         = 0;
            cell.Body.LineBreakMode = UILineBreakMode.TailTruncation;

            cell.Header.LinkAttributes       = new NSDictionary();
            cell.Header.ActiveLinkAttributes = new NSMutableDictionary();
            cell.Header.ActiveLinkAttributes[MonoTouch.CoreText.CTStringAttributeKey.UnderlineStyle] = NSNumber.FromBoolean(true);
            cell.Header.Lines         = 2;
            cell.Header.LineBreakMode = UILineBreakMode.TailTruncation;

            // Special for large fonts
            if (Theme.CurrentTheme.FontSizeRatio > 1.0f)
            {
                cell.Header.Font = HeaderFont;
                cell.Body.Font   = BodyFont;
                cell.Time.Font   = TimeFont;

                var timeSectionheight = (float)Math.Ceiling(TimeFont.LineHeight);
                var timeFrame         = cell.Time.Frame;
                timeFrame.Height = timeSectionheight;
                cell.Time.Frame  = timeFrame;

                var imageFrame = cell.ActionImage.Frame;
                imageFrame.Y          += (timeFrame.Height - imageFrame.Height) / 2f;
                cell.ActionImage.Frame = imageFrame;

                var headerSectionheight = (float)Math.Ceiling(TimeFont.LineHeight);
                var headerFrame         = cell.Header.Frame;
                headerFrame.Height = headerSectionheight * 2f + (float)Math.Ceiling(3f * Theme.CurrentTheme.FontSizeRatio);
                headerFrame.Y      = 6 + timeFrame.Height + 5f;
                cell.Header.Frame  = headerFrame;

                var picFrame = cell.Image.Frame;
                picFrame.Y       = 6 + timeFrame.Height + 5f;
                picFrame.Y      += (headerFrame.Height - picFrame.Height) / 2f;
                cell.Image.Frame = picFrame;

                var bodyFrame = cell.Body.Frame;
                bodyFrame.Y     = headerFrame.Y + headerFrame.Height + 4f;
                cell.Body.Frame = bodyFrame;
            }

            return(cell);
        }
 private static void SetOption(NSString option, Boolean newValue)
 {
     TestFlight.SetOptions(new NSDictionary(option, NSNumber.FromBoolean(newValue)));
 }
        public static NSObject ConvertToNSObject(object obj)
        {
            if (obj != null)
            {
                if (obj is Boolean)
                {
                    return(NSNumber.FromBoolean((bool)obj));
                }
                else if (obj is Byte)
                {
                    return(NSNumber.FromByte((byte)obj));
                }
                else if (obj is SByte)
                {
                    return(NSNumber.FromSByte((sbyte)obj));
                }
                else if (obj is Int16)
                {
                    return(NSNumber.FromInt16((short)obj));
                }
                else if (obj is Int32)
                {
                    return(NSNumber.FromInt32((int)obj));
                }
                else if (obj is Int64)
                {
                    return(NSNumber.FromInt64((long)obj));
                }
                else if (obj is UInt16)
                {
                    return(NSNumber.FromUInt16((ushort)obj));
                }
                else if (obj is UInt32)
                {
                    return(NSNumber.FromUInt32((uint)obj));
                }
                else if (obj is UInt64)
                {
                    return(NSNumber.FromUInt64((ulong)obj));
                }
                else if (obj is Single)
                {
                    return(NSNumber.FromFloat((float)obj));
                }
                else if (obj is Double)
                {
                    return(NSNumber.FromDouble((double)obj));
                }
                else if (obj is string)
                {
                    return(new NSString(obj.ToString()));
                }
                else if (obj is Guid)
                {
                    return(new NSUuid(((Guid)obj).ToByteArray()));
                }
                else if (obj is DateTime)
                {
                    return(((DateTime)obj).ToNSDate());
                }
                else if (obj is DateTimeOffset)
                {
                    return(new NSString(((DateTimeOffset)obj).ToString("O")));
                }
            }

            return(null);
        }