Example #1
0
 public void HideFinished(string name, NSNumber numFinished, IntPtr context)
 {
     GCHandle h = GCHandle.FromIntPtr (context);
     var view = (UIView) h.Target;
     view.RemoveFromSuperview ();
     h.Free ();
 }
    void ConfigureView()
    {
      // Update the user interface for the detail item
      if (IsViewLoaded && detailItem != null)
      {
        detailDescriptionLabel.Text = detailItem.ToString();
      }

      this.Title = detailItem.Code;

      if(peripheralMgr != null)
      {
        peripheralMgr.StopAdvertising();
      }
      else
      {
        peripheralDelegate = new BTPeripheralDelegate();
        peripheralMgr = new CBPeripheralManager(peripheralDelegate, DispatchQueue.DefaultGlobalQueue);
      }

      beaconUUID = new NSUuid(detailItem.UUID);
      beaconRegion = new CLBeaconRegion(beaconUUID, (ushort)detailItem.Major, (ushort)detailItem.Minor, beaconId);



      //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
      var power = new NSNumber(-59);
      peripheralData = beaconRegion.GetPeripheralData(power);
      peripheralMgr.StartAdvertising(peripheralData);

      QRCode.LoadUrl(GenerateQRCodeUrl(detailItem.ToString(), QRCodeSize.Medium, QRErrorCorrection.H));
    }
        public override void LoadView()
        {
            UIView view = new UIView ();
            view.BackgroundColor = UIColor.White;

            gameView = new TTTGameView () {
                ImageForPlayer = ImageForPlayer,
                ColorForPlayer = ColorForPlayer,
                UserInteractionEnabled = false,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            view.AddSubview (gameView);
            gameView.Game = Game;

            float topHeight = UIApplication.SharedApplication.StatusBarFrame.Size.Height +
                NavigationController.NavigationBar.Frame.Size.Height;

            var mTopHeight = new NSNumber (topHeight + Margin);
            var mBottomHeight = new NSNumber (Margin);
            var mMargin = new NSNumber (Margin);

            view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("|-margin-[gameView]-margin-|",
                (NSLayoutFormatOptions)0,
                "margin", mMargin,
                "gameView", gameView));

            view.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-topHeight-[gameView]-bottomHeight-|",
                (NSLayoutFormatOptions)0,
                "topHeight", mTopHeight,
                "gameView", gameView,
                "bottomHeight", mBottomHeight));

            View = view;
        }
		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear (animated);
			CLBeaconRegion region = (CLBeaconRegion)locationManger.MonitoredRegions.AnyObject;
			enabled = (region != null);
			if (enabled) {
				uuid = region.ProximityUuid;
				major = region.Major;
				minor = region.Minor;
				notifyOnEntry = region.NotifyOnEntry;
				notifyOnExit = region.NotifyOnExit;
				notifyOnDisplay = region.NotifyEntryStateOnDisplay;
			} else {
				uuid = Defaults.DefaultProximityUuid;
				major = minor = null;
				notifyOnEntry = true;
				notifyOnExit = true;
				notifyOnDisplay = false;
			}

			majorTextField.Text = major == null ? String.Empty : major.Int32Value.ToString ();
			minorTextField.Text = minor == null ? String.Empty : minor.Int32Value.ToString ();

			uuidTextField.Text = uuid.AsString ();
			enabledSwitch.On = enabled;
			notifyOnEntrySwitch.On = notifyOnEntry;
			notifyOnExitSwitch.On = notifyOnExit;
			notifyOnDisplaySwitch.On = notifyOnDisplay;
		}
		public CustomVideoCompositionInstruction(NSNumber [] sourceTracksIDS, CMTimeRange timeRange) : base()
		{
			requiredSourceTrackIDs = sourceTracksIDS;
			passthroughTrackID = 0;
			this.timeRange = timeRange;
			containsTweening = true;
			enablePostProcessing = false;
		}
Example #6
0
        public override void ViewDidLoad()
        {
            this.AddOption ("Bar Series", LoadBarSeries);
            this.AddOption ("Column Series", LoadColumnSeries);
            this.AddOption ("Line Series", LoadLineSeries);
            this.AddOption ("Pie Series", LoadPieSeries);
            this.AddOption ("Ohlc Series", LoadFinancialSeries);

            base.ViewDidLoad ();

            chart = new TKChart (this.ExampleBounds);
            chart.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
            chart.AllowAnimations = true;
            chart.Delegate = chartDelegate;
            this.View.AddSubview (chart);

            Random r = new Random ();
            columnData = new List<TKChartDataPoint> ();
            barData = new List<TKChartDataPoint> ();
            string[] categories = new string[] { "Greetings", "Perfecto", "NearBy", "Family Store", "Fresh & Green" };
            for (int i = 0; i < categories.Length; i++) {
                TKChartDataPoint columnPoint = new TKChartDataPoint (new NSString (categories [i]), new NSNumber (r.Next () % 100));
                TKChartDataPoint barPoint = new TKChartDataPoint (new NSNumber (r.Next () % 100), NSObject.FromObject(categories[i]));
                columnData.Add (columnPoint);
                barData.Add (barPoint);
            }

            lineData = new List<TKChartDataPoint> ();
            int[] lineValues = new int[] { 82, 68, 83, 46, 32, 75, 8, 54, 47, 51 };
            for (int i = 0; i < lineValues.Length; i++) {
                TKChartDataPoint point = new TKChartDataPoint (new NSNumber (i), new NSNumber (lineValues [i]));
                lineData.Add (point);
            }

            pieDonutData = new List<TKChartDataPoint> ();
            pieDonutData.Add (new TKChartDataPoint (new NSNumber (20), null, "Google"));
            pieDonutData.Add (new TKChartDataPoint (new NSNumber (30), null, "Apple"));
            pieDonutData.Add (new TKChartDataPoint (new NSNumber (10), null, "Microsoft"));
            pieDonutData.Add (new TKChartDataPoint (new NSNumber (5), null, "IBM"));
            pieDonutData.Add (new TKChartDataPoint (new NSNumber (8), null, "Oracle"));

            int[] openPrices = new int[] { 100, 125, 69, 99, 140, 125 };
            int[] closePrices = new int[] { 85, 65, 135, 120, 80, 136 };
            int[] lowPrices = new int[] { 50, 60, 65, 55, 75, 90 };
            int[] highPrices = new int[] { 129, 142, 141, 123, 150, 161 };
            ohlcData = new List<TKChartFinancialDataPoint> ();
            for (int i = 0; i < openPrices.Length; i++) {
                NSDate date = NSDate.FromTimeIntervalSinceNow (60 * 60 * 24 * i);
                NSNumber open = new NSNumber (openPrices [i]);
                NSNumber high = new NSNumber (highPrices [i]);
                NSNumber low = new NSNumber (lowPrices [i]);
                NSNumber close = new NSNumber (closePrices [i]);
                TKChartFinancialDataPoint point = TKChartFinancialDataPoint.DataPoint(date, open, high, low, close);
                ohlcData.Add (point);
            }

            this.LoadBarSeries (this, EventArgs.Empty);
        }
Example #7
0
 static Defaults()
 {
   supportedProximityUuids = new NSUuid[] {
     new NSUuid ("E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"), 
     new NSUuid ("5A4BCFCE-174E-4BAC-A814-092E77F6B7E5"),
     new NSUuid ("74278BDA-B644-4520-8F0C-720EAF059935")
   };
   defaultPower = new NSNumber(-59);
 }
		public ConfigurationViewController (IntPtr handle) : base (handle)
		{
			var peripheralDelegate = new PeripheralManagerDelegate ();
			peripheralManager = new CBPeripheralManager (peripheralDelegate, DispatchQueue.DefaultGlobalQueue);
			numberFormatter = new NSNumberFormatter () {
				NumberStyle = NSNumberFormatterStyle.Decimal
			};
			uuid = Defaults.DefaultProximityUuid;
			power = Defaults.DefaultPower;
		}
        // Sets the cell's text to represent a characteristic and target value.
        // For example, "Brightness → 60%"
        // Sets the subtitle to the service and accessory that this characteristic represents.
        public void SetCharacteristic(HMCharacteristic characteristic, NSNumber targetValue)
        {
            var targetDescription = string.Format ("{0} → {1}", characteristic.LocalizedDescription, characteristic.DescriptionForValue (targetValue));
            TextLabel.Text = targetDescription;

            HMService service = characteristic.Service;
            if (service != null && service.Accessory != null)
                TrySetDetailText (string.Format ("{0} in {1}", service.Name, service.Accessory.Name));
            else
                TrySetDetailText ("Unknown Characteristic");
        }
 static Defaults()
 {
     supportedProximityUuids = new NSUuid[] {
         new NSUuid ("E2C56DB5-DFFB-48D2-B060-D0F5A71096E0"),
         new NSUuid ("5A4BCFCE-174E-4BAC-A814-092E77F6B7E5"),
         new NSUuid ("74278BDA-B644-4520-8F0C-720EAF059935"),
         new NSUuid("e20a39f4-73f5-4bc4-a12f-17d1ad07a961"),
         new NSUuid("636f3f8f-6491-4bee-95f7-d8cc64a863b5"),
     };
     defaultPower = new NSNumber(-59);
 }
 private void displayTimerResults()
 {
     UIApplication.SharedApplication.IdleTimerDisabled = false;
     NSDate endTime = new NSDate();
     double interval = endTime.SecondsSinceReferenceDate - startTime.SecondsSinceReferenceDate;
     NSNumber timeNumber = new NSNumber(interval);
     NSNumberFormatter formatter = new NSNumberFormatter();
     formatter.MaximumFractionDigits = 5;
     string formattedTime = formatter.StringFromNumber(timeNumber);
     this.timeLabel.Text = formattedTime;
 }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            if (!UserInterfaceIdiomIsPhone) {

                //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
                var power = new NSNumber (-59);
                peripheralData = beaconRegion.GetPeripheralData (power);
                peripheralMgr.StartAdvertising (peripheralData);
            }
        }
Example #13
0
		// 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)
		{
			if (uuid == null)
				return null;
			if (minor == null) {
				if (major == null)
					return new CLBeaconRegion (uuid, Defaults.Identifier);
				else
					return new CLBeaconRegion (uuid, major.UInt16Value, Defaults.Identifier);
			} else if (major != null) {
				return new CLBeaconRegion (uuid, major.UInt16Value, minor.UInt16Value, Defaults.Identifier);
			}
			return null;
		}
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear (animated);

            beaconUUID = new NSUuid (uuid);
            beaconRegion = new CLBeaconRegion (beaconUUID, beaconMajor, beaconMinor, beaconId);

            //power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
            var power = new NSNumber (-59);

            var peripheralData = beaconRegion.GetPeripheralData (power);
            peripheralDelegate = new BTPeripheralDelegate ();
            peripheralManager.StartAdvertising (peripheralData);
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			beaconUUID = new NSUuid (uuid);
			beaconRegion = new CLBeaconRegion (beaconUUID, beaconMajor, beaconMinor, beaconId);



			//power - the received signal strength indicator (RSSI) value (measured in decibels) of the beacon from one meter away
			var power = new NSNumber (-59);

			NSMutableDictionary peripheralData = beaconRegion.GetPeripheralData (power);
			peripheralDelegate = new BTPeripheralDelegate ();
			peripheralMgr = new CBPeripheralManager (peripheralDelegate, DispatchQueue.DefaultGlobalQueue);

			peripheralMgr.StartAdvertising (peripheralData);
		}
Example #16
0
        void HandleTouchDown(object sender, EventArgs e)
        {
            if (segBeacon.SelectedSegment == 0) {
                var power = new NSNumber (-59);
                NSMutableDictionary peripheralData = bRegion.GetPeripheralData (power);
                pDelegate = new BTPDelegate ();
                pManager = new CBPeripheralManager (pDelegate, DispatchQueue.DefaultGlobalQueue);

                pManager.StartAdvertising (peripheralData);
            } else {

                locManager = new CLLocationManager ();

                locManager.RegionEntered += (object s, CLRegionEventArgs ea) => {
                    if (ea.Region.Identifier == "beacon") {
                        UILocalNotification notification = new UILocalNotification () { AlertBody = "Entering beacon region!" };
                        UIApplication.SharedApplication.PresentLocationNotificationNow (notification);
                    }
                };

                locManager.DidRangeBeacons += (object s, CLRegionBeaconsRangedEventArgs ea) => {
                    if (ea.Beacons.Length > 0) {

                        CLBeacon beacon = ea.Beacons [0];
                        switch (beacon.Proximity) {
                        case CLProximity.Immediate:
                            this.View.BackgroundColor = UIColor.Green;
                            break;
                        case CLProximity.Near:
                            this.View.BackgroundColor = UIColor.Yellow;
                            break;
                        case CLProximity.Far:
                            this.View.BackgroundColor = UIColor.Red;
                            break;
                        case CLProximity.Unknown:
                            this.View.BackgroundColor = UIColor.Black;
                            break;
                        }
                    }
                };

                locManager.StartMonitoring (bRegion);
                locManager.StartRangingBeacons (bRegion);
            }
        }
Example #17
0
        public void TestInstanceCreation()
        {
            NSNumber number;

            number = new NSNumber(true);
            Check(number);
            Assert.AreEqual(1, number.IntValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(false);
            Check(number);
            Assert.AreEqual(0, number.IntValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(123.456d);
            Check(number);
            Assert.AreEqual(123.456d, number.DoubleValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(-12345678901234567890d);
            Check(number);
            Assert.AreEqual(-12345678901234567890d, number.DoubleValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(123.456f);
            Check(number);
            Assert.AreEqual(123.456f, number.FloatValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(-12345678901234567890f);
            Check(number);
            Assert.AreEqual(-12345678901234567890f, number.FloatValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(123);
            Check(number);
            Assert.AreEqual(123, number.IntValue, "Number has wrong value");
            number.Autorelease();

            number = new NSNumber(-123456);
            Check(number);
            Assert.AreEqual(-123456, number.IntValue, "Number has wrong value");
            number.Autorelease();
        }
        static void HandleColorCubeFilter(CIFilter filter)
        {
            if (filter.Name != "CIColorCube")
                return;

            int dimension = 64;  // Must be power of 2, max of 128 (max of 64 on ios)
            int cubeDataSize = 4 * dimension * dimension * dimension;
            filter[new NSString("inputCubeDimension")] = new NSNumber(dimension);

            // 2 : 32 /4 = 8 = 2^3
            // 4 : 256 /4 = 64 = 4^3
            // 8 : 2048 /4 = 512 = 8^3

            var cubeData = new byte[cubeDataSize];
            var rnd = new Random();
            rnd.NextBytes(cubeData);
            for (int i = 3; i < cubeDataSize; i += 4)
                cubeData[i] = 255;
            filter[new NSString("inputCubeData")] = NSData.FromArray(cubeData);
        }
        public override void ProvidePlaceholderAtUrl(NSUrl url, Action<NSError> completionHandler)
        {
            var fileName = Path.GetFileName (url.Path);
            var placeholder = NSFileProviderExtension.GetPlaceholderUrl (DocumentStorageUrl.Append (fileName, false));
            NSNumber size = new NSNumber (0);
            NSError error;

            // TODO: get file size for file at <url> from model

            FileCoordinator.CoordinateWrite (placeholder, 0, out error, (newUrl) => {
                var metadata = new NSMutableDictionary ();
                NSError err = null;

                metadata.Add (NSUrl.FileSizeKey, size);

                NSFileProviderExtension.WritePlaceholder (placeholder, metadata, ref err);
            });

            if (completionHandler != null)
                completionHandler (null);
        }
        public static void Display(DisplayedPromptsModel displayedPrompts)
        {
            // Get current notification settings
            //UNUserNotificationCenter.Current.GetNotificationSettings((settings) => {
            //    var alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);
            //});

            var  plist = NSUserDefaults.StandardUserDefaults;
            bool enableNotifications = plist.BoolForKey("enableNotifications");

            if (!enableNotifications)
            {
                return;
            }

            var content = new UNMutableNotificationContent();

            content.Title = displayedPrompts.Category;
            //content.Subtitle = displayedPrompts.Category;
            content.Body  = displayedPrompts.Task;
            content.Badge = NSNumber.FromInt32(Convert.ToInt32(UIApplication.SharedApplication.ApplicationIconBadgeNumber) + 1);

            var timeInterval = new NSDateComponents();

            timeInterval.Second = 1;

            //var trigger = UNCalendarNotificationTrigger.CreateTrigger(timeInterval, false);
            var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger(1, false);

            var requestID = "PromptAlarm";
            var request   = UNNotificationRequest.FromIdentifier(requestID, content, trigger);

            UNUserNotificationCenter.Current.AddNotificationRequest(request, (err) =>
            {
                if (err != null)
                {
                    Console.WriteLine("something went wrong");
                }
            });
        }
Example #21
0
        /// <summary>
        /// Creates a new attributed string from the specified styled text and theme.
        /// </summary>
        /// <param name="styledText">The styled text.</param>
        /// <param name="theme">The theme to apply.</param>
        /// <param name="fontSize">The size of the font to use.</param>
        /// <returns>A new attributed string.</returns>
        public static NSMutableAttributedString FromStyledText(StyledText styledText, LabelTheme theme, int fontSize)
        {
            string text = styledText.ToString();
            NSMutableAttributedString attributedText = new NSMutableAttributedString(text);
            NSRange fullRange = new NSRange(0, text.Length);

            foreach (StyledText.TextPart part in styledText.Parts)
            {
                FontStyle fontStyle = FontStyle.None;
                if (part.Style.HasFlag(StyledText.Style.Bold))
                {
                    fontStyle |= FontStyle.Bold;
                }
                if (part.Style.HasFlag(StyledText.Style.Italic))
                {
                    fontStyle |= FontStyle.Italic;
                }

                UIFont font =
                    string.IsNullOrEmpty(theme.FontName)
                    ? UIFont.SystemFontOfSize(fontSize)
                    : UIFont.FromName(theme.FontName, fontSize);

                font = font.ApplyStyle(fontStyle);

                NSRange range = new NSRange(part.StartIndex, part.Text.Length);

                attributedText.AddAttribute(UIStringAttributeKey.Font, font, range);
                if (part.Style.HasFlag(StyledText.Style.Underline))
                {
                    attributedText.AddAttribute(UIStringAttributeKey.UnderlineStyle,
                                                NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                }
            }

            attributedText.AddAttribute(UIStringAttributeKey.BackgroundColor, theme.BackgroundColor.ToUIColor(), fullRange);
            attributedText.AddAttribute(UIStringAttributeKey.ForegroundColor, theme.FontColor.ToUIColor(), fullRange);

            return(attributedText);
        }
Example #22
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;
        }
Example #23
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();
        }
Example #24
0
        public override NSNumber NumberForPlot(CPTPlot plot, CPTPlotField forFieldEnum, int index)
        {
            var space = graph.DefaultPlotSpace as CPTXYPlotSpace;

            switch (forFieldEnum)
            {
            case CPTPlotField.ScatterPlotFieldX:
                switch (index)
                {
                case 0:
                    return(NSNumber.FromDouble(space.GlobalXRange.MinLimitDouble));

                case 1:
                    return(NSNumber.FromDouble(space.GlobalXRange.MaxLimitDouble));

                case 2:
                case 3:
                case 4:
                    return(1);
                }
                break;

            case CPTPlotField.ScatterPlotFieldY:
                switch (index)
                {
                case 0:
                case 1:
                case 2:
                    return(1);

                case 3:
                    return(NSNumber.FromDouble(space.GlobalYRange.MinLimitDouble));

                case 4:
                    return(NSNumber.FromDouble(space.GlobalYRange.MaxLimitDouble));
                }
                break;
            }
            return(NSNumber.FromDouble(2));
        }
            public TimeEntryCell(IntPtr ptr) : base(ptr)
            {
                textContentView        = new UIView();
                projectLabel           = new UILabel().Apply(Style.Recent.CellProjectLabel);
                clientLabel            = new UILabel().Apply(Style.Recent.CellClientLabel);
                taskLabel              = new UILabel().Apply(Style.Recent.CellTaskLabel);
                descriptionLabel       = new UILabel().Apply(Style.Recent.CellDescriptionLabel);
                taskSeparatorImageView = new UIImageView().Apply(Style.Recent.CellTaskDescriptionSeparator);
                runningImageView       = new UIImageView().Apply(Style.Recent.CellRunningIndicator);

                textContentView.AddSubviews(
                    projectLabel, clientLabel,
                    taskLabel, descriptionLabel,
                    taskSeparatorImageView
                    );

                var maskLayer = new CAGradientLayer()
                {
                    AnchorPoint = PointF.Empty,
                    StartPoint  = new PointF(0.0f, 0.0f),
                    EndPoint    = new PointF(1.0f, 0.0f),
                    Colors      = new [] {
                        UIColor.FromWhiteAlpha(1, 1).CGColor,
                        UIColor.FromWhiteAlpha(1, 1).CGColor,
                        UIColor.FromWhiteAlpha(1, 0).CGColor,
                    },
                    Locations = new [] {
                        NSNumber.FromFloat(0f),
                        NSNumber.FromFloat(0.9f),
                        NSNumber.FromFloat(1f),
                    },
                };

                textContentView.Layer.Mask = maskLayer;

                ActualContentView.AddSubviews(
                    textContentView,
                    runningImageView
                    );
            }
            public ProjectClientTaskButton()
            {
                Add(container = new UIView()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                    UserInteractionEnabled = false,
                });

                var maskLayer = new CAGradientLayer()
                {
                    AnchorPoint = CGPoint.Empty,
                    StartPoint  = new CGPoint(0.0f, 0.0f),
                    EndPoint    = new CGPoint(1.0f, 0.0f),
                    Colors      = new [] {
                        UIColor.FromWhiteAlpha(1, 1).CGColor,
                        UIColor.FromWhiteAlpha(1, 1).CGColor,
                        UIColor.FromWhiteAlpha(1, 0).CGColor,
                    },
                    Locations = new [] {
                        NSNumber.FromFloat(0f),
                        NSNumber.FromFloat(0.9f),
                        NSNumber.FromFloat(1f),
                    },
                };

                container.Layer.Mask = maskLayer;

                container.Add(projectLabel = new UILabel()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                }.Apply(Style.EditTimeEntry.ProjectLabel));
                container.Add(clientLabel = new UILabel()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                }.Apply(Style.EditTimeEntry.ClientLabel));
                container.Add(taskLabel = new UILabel()
                {
                    TranslatesAutoresizingMaskIntoConstraints = false,
                }.Apply(Style.EditTimeEntry.TaskLabel));
            }
Example #27
0
        public void Copy()
        {
            IntPtr nscopying = Runtime.GetProtocol("NSCopying");

            Assert.That(nscopying, Is.Not.EqualTo(IntPtr.Zero), "NSCopying");

            IntPtr nsmutablecopying = Runtime.GetProtocol("NSMutableCopying");

            Assert.That(nsmutablecopying, Is.Not.EqualTo(IntPtr.Zero), "NSMutableCopying");

            // NSObject does not conform to NSCopying
            using (var o = new NSObject()) {
                Assert.False(o.ConformsToProtocol(nscopying), "NSObject/NSCopying");
                Assert.False(o.ConformsToProtocol(nsmutablecopying), "NSObject/NSMutableCopying");
            }

            // NSNumber conforms to NSCopying - but not NSMutableCopying
            using (var n = new NSNumber(-1)) {
                Assert.True(n.ConformsToProtocol(nscopying), "NSNumber/NSCopying");
                using (var xn = n.Copy()) {
                    Assert.NotNull(xn, "NSNumber/Copy/NotNull");
                    Assert.AreSame(n, xn, "NSNumber/Copy/NotSame");
                }
                Assert.False(n.ConformsToProtocol(nsmutablecopying), "NSNumber/NSMutableCopying");
            }

            // NSMutableString conforms to NSCopying - but not NSMutableCopying
            using (var s = new NSMutableString(1)) {
                Assert.True(s.ConformsToProtocol(nscopying), "NSMutableString/NSCopying");
                using (var xs = s.Copy()) {
                    Assert.NotNull(xs, "NSMutableString/Copy/NotNull");
                    Assert.AreNotSame(s, xs, "NSMutableString/Copy/NotSame");
                }
                Assert.True(s.ConformsToProtocol(nsmutablecopying), "NSMutableString/NSMutableCopying");
                using (var xs = s.MutableCopy()) {
                    Assert.NotNull(xs, "NSMutableString/MutableCopy/NotNull");
                    Assert.AreNotSame(s, xs, "NSMutableString/MutableCopy/NotSame");
                }
            }
        }
Example #28
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);
        }
Example #29
0
        private void SetupAnimationGroup()
        {
            if (animationGroup != null)
            {
                return;
            }

            var defaultCurve = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Default);

            animationGroup = new CAAnimationGroup();
            animationGroup.RemovedOnCompletion = true;
            animationGroup.Duration            = this.Duration + this.PulseInterval;
            animationGroup.RepeatCount         = this.repeatCount;
            animationGroup.TimingFunction      = defaultCurve;

            var scaleAnimation = CABasicAnimation.FromKeyPath("transform.scale.xy");

            scaleAnimation.RemovedOnCompletion = false;
            scaleAnimation.Duration            = this.Duration;
            scaleAnimation.From = NSObject.FromObject(fromValueForRadius);
            scaleAnimation.To   = NSObject.FromObject(1.0f);

            var opacityAnimation = CAKeyFrameAnimation.GetFromKeyPath("opacity");

            opacityAnimation.RemovedOnCompletion = false;
            opacityAnimation.Duration            = this.Duration;
            opacityAnimation.Values = new NSNumber[] {
                NSNumber.FromFloat(fromValueForAlpha),
                NSNumber.FromFloat(0.45f),
                NSNumber.FromFloat(0f),
            };
            opacityAnimation.KeyTimes = new NSNumber[] {
                NSNumber.FromFloat(0f),
                NSNumber.FromFloat(keyTimeForHalfOpacity),
                NSNumber.FromFloat(1f),
            };

            animationGroup.Animations = new CAAnimation[] { scaleAnimation, opacityAnimation };
        }
Example #30
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;
        }
Example #31
0
        public static NSDictionary GetPhotoLibraryMetadata(NSUrl url)
        {
            NSDictionary meta = null;

            var image          = PHAsset.FetchAssets(new NSUrl[] { url }, new PHFetchOptions()).firstObject as PHAsset;
            var imageManager   = PHImageManager.DefaultManager;
            var requestOptions = new PHImageRequestOptions
            {
                Synchronous          = true,
                NetworkAccessAllowed = true,
                DeliveryMode         = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
            };

            imageManager.RequestImageData(image, requestOptions, (data, dataUti, orientation, info) =>
            {
                try
                {
                    var fullimage = CIImage.FromData(data);
                    if (fullimage?.Properties != null)
                    {
                        meta = new NSMutableDictionary
                        {
                            [ImageIO.CGImageProperties.Orientation]    = NSNumber.FromNInt((int)(fullimage.Properties.Orientation ?? CIImageOrientation.TopLeft)),
                            [ImageIO.CGImageProperties.ExifDictionary] = fullimage.Properties.Exif?.Dictionary ?? new NSDictionary(),
                            [ImageIO.CGImageProperties.TIFFDictionary] = fullimage.Properties.Tiff?.Dictionary ?? new NSDictionary(),
                            [ImageIO.CGImageProperties.GPSDictionary]  = fullimage.Properties.Gps?.Dictionary ?? new NSDictionary(),
                            [ImageIO.CGImageProperties.IPTCDictionary] = fullimage.Properties.Iptc?.Dictionary ?? new NSDictionary(),
                            [ImageIO.CGImageProperties.JFIFDictionary] = fullimage.Properties.Jfif?.Dictionary ?? new NSDictionary()
                        };
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            });

            return(meta);
        }
        public void CABasicAnimation_FromToBy_INativeTests()
        {
            CABasicAnimation test   = CABasicAnimation.FromKeyPath("bounds");
            NSNumber         number = new NSNumber(10);

            test.From = number;
            Assert.AreEqual(test.From, number, "NSObject from");
            test.To = number;
            Assert.AreEqual(test.To, number, "NSObject to");
            test.By = number;
            Assert.AreEqual(test.By, number, "NSObject by");

            CGColor color = new CGColor(.5f, .5f, .5f);

            test = CABasicAnimation.FromKeyPath("color");
            test.SetFrom(color);
            Assert.AreEqual(test.GetFromAs <CGColor> (), color, "INativeObject from");
            test.SetTo(color);
            Assert.AreEqual(test.GetToAs <CGColor> (), color, "INativeObject to");
            test.SetBy(color);
            Assert.AreEqual(test.GetByAs <CGColor> (), color, "INativeObject by");
        }
Example #33
0
        static NSNumber[] GetCAGradientLayerLocations(List <PaintGradientStop> gradientStops)
        {
            if (gradientStops == null || gradientStops.Count == 0)
            {
                return(new NSNumber[0]);
            }

            if (gradientStops.Count > 1 && gradientStops.Any(gt => gt.Offset != 0))
            {
                return(gradientStops.Select(x => new NSNumber(x.Offset)).ToArray());
            }
            else
            {
                int   itemCount = gradientStops.Count;
                int   index     = 0;
                float step      = 1.0f / itemCount;

                NSNumber[] locations = new NSNumber[itemCount];

                foreach (var gradientStop in gradientStops)
                {
                    float location    = step * index;
                    bool  setLocation = !gradientStops.Any(gt => gt.Offset > location);

                    if (gradientStop.Offset == 0 && setLocation)
                    {
                        locations[index] = new NSNumber(location);
                    }
                    else
                    {
                        locations[index] = new NSNumber(gradientStop.Offset);
                    }

                    index++;
                }

                return(locations);
            }
        }
Example #34
0
        public override void LayoutSublayers()
        {
            Frame           = View.Bounds;
            LineWidth       = 2;
            FillColor       = UIColor.Clear.CGColor;
            LineJoin        = JoinRound;
            LineDashPattern = new [] { NSNumber.FromNInt(2), NSNumber.FromNInt(5), NSNumber.FromNInt(5) };

            var path = UIBezierPath.FromRoundedRect(Bounds, 15);

            Path = path.CGPath;

            var flash = CABasicAnimation.FromKeyPath("opacity");

            flash.SetFrom(NSNumber.FromFloat(0));
            flash.SetTo(NSNumber.FromFloat(1));
            flash.Duration    = 0.75;
            flash.RepeatCount = 10000;

            AddAnimation(flash, "flashAnimation");
            base.LayoutSublayers();
        }
Example #35
0
        public static NSDictionary <NSString, NSObject> ToOptions(this NxTileSourceOptions nxoptions)
        {
            if (nxoptions == null)
            {
                return(null);
            }

            var options = new NSMutableDictionary <NSString, NSObject>();

            if (nxoptions.MinimumZoomLevel.HasValue)
            {
                options.Add(MGLTileSourceOptions.MinimumZoomLevel, NSNumber.FromNInt(nxoptions.MinimumZoomLevel.Value));
            }
            if (nxoptions.MaximumZoomLevel.HasValue)
            {
                options.Add(MGLTileSourceOptions.MaximumZoomLevel, NSNumber.FromNInt(nxoptions.MaximumZoomLevel.Value));
            }

            // TODO add other options

            return(new NSDictionary <NSString, NSObject>(options.Keys, options.Values));
        }
Example #36
0
        protected override void OnElementChanged(ElementChangedEventArgs <Label> e)
        {
            base.OnElementChanged(e);


            if (this.Control == null)
            {
                return;
            }

            try
            {
                var label = (UILabel)Control;
                var text  = (NSMutableAttributedString)label.AttributedText;
                var range = new NSRange(0, text.Length);
                text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #37
0
        public AnimationBuilder ScaleTo(float scale, double delaySeconds, double durationSeconds)
        {
            var scaleAnimation = CABasicAnimation.FromKeyPath("transform.scale");

            scaleAnimation.TimingFunction = this.EasingFunction;
            if (durationSeconds > 0)
            {
                scaleAnimation.Duration = durationSeconds;
            }
            if (delaySeconds > 0)
            {
                scaleAnimation.BeginTime = delaySeconds;
            }
            scaleAnimation.FillMode            = CAFillMode.Forwards;
            scaleAnimation.RemovedOnCompletion = false;
            scaleAnimation.To = NSNumber.FromFloat(scale);

            this.Animations.Add(scaleAnimation);
            this.EnsureTotalDuration(delaySeconds, durationSeconds);

            return(this);
        }
Example #38
0
        public static CABasicAnimation RotateX(nfloat?angle = null, nfloat?rotation = null, double?duration = null)
        {
            var animation = CABasicAnimation.FromKeyPath("transform.rotation.x");

            if (angle != null)
            {
                animation.To = NSNumber.FromDouble(Math.PI * angle.Value / 180.0);
            }
            else if (rotation != null)
            {
                animation.To = NSNumber.FromDouble(Math.PI * 2 * rotation.Value);
            }

            animation.FillMode            = Convert.MaterialAnimationFillModeToValue(MaterialAnimationFillMode.Forwards);
            animation.RemovedOnCompletion = false;
            animation.TimingFunction      = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut);
            if (duration != null)
            {
                animation.Duration = duration.Value;
            }
            return(animation);
        }
Example #39
0
        public override void Awake(NSObject context)
        {
            base.Awake(context);

            // Configure interface objects here.
            timer          = new Timer(1000);
            timer.Elapsed += (sender, e) => {
                secondsRemaining--;
                InvokeOnMainThread(() => {
                    if (secondsRemaining == 10)
                    {
                        timerLabel.SetTextColor(UIKit.UIColor.Red);
                    }
                    timerLabel.SetText(String.Format("00:{0:00}", secondsRemaining));
                });
                if (secondsRemaining == 0)
                {
                    timer.Enabled = false;
                    InvokeOnMainThread(() => PushController("results", NSNumber.FromInt32(tapCount)));
                }
            };
        }
Example #40
0
        // sets up the scrolling in the correct direction
        // utilizes CSDisplayLink, a timer synchronized to the display refresh rate, to execute the smooth automated scrolling
        private void SetupScrollTimerInDirection(ScrollingDirection direction)
        {
            if (DisplayLink != null && !DisplayLink.Paused)
            {
                var userInfo           = userInfos[DisplayLink];
                var scrollingDirection = userInfo[ScrollingDirectionKey];
                var number             = (NSNumber)NSNumber.FromObject(scrollingDirection);

                ScrollingDirection oldDirection = (ScrollingDirection)number.Int32Value;

                if (direction == oldDirection)
                {
                    return;
                }
            }
            InvalidatesScrollTimer();

            DisplayLink = CADisplayLink.Create(HandleScroll);
            userInfos.Add(DisplayLink, NSDictionary.FromObjectAndKey(NSNumber.FromInt32((int)direction), new NSString(ScrollingDirectionKey)));

            DisplayLink.AddToRunLoop(NSRunLoop.Main, NSRunLoop.NSRunLoopCommonModes);
        }
Example #41
0
        public static void ApplyShimmer(UIView viewToApplyShimmer)
        {
            var gradientLayer = new CAGradientLayer
            {
                Colors     = new CGColor[] { UIColor.White.ColorWithAlpha(0f).CGColor, UIColor.White.ColorWithAlpha(1f).CGColor, UIColor.White.ColorWithAlpha(0f).CGColor },
                StartPoint = new CGPoint(0.7, 1.0),
                EndPoint   = new CGPoint(0, 0.8),
                Frame      = viewToApplyShimmer.Bounds
            };

            viewToApplyShimmer.Layer.InsertSublayer(gradientLayer, 0);

            var animation = new CABasicAnimation();

            animation.KeyPath     = "transform.translation.x";
            animation.Duration    = 1;
            animation.From        = NSNumber.FromNFloat(-viewToApplyShimmer.Frame.Size.Width);
            animation.To          = NSNumber.FromNFloat(viewToApplyShimmer.Frame.Size.Width);
            animation.RepeatCount = float.PositiveInfinity;

            gradientLayer.AddAnimation(animation, "");
        }
Example #42
0
        /// <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));
            }
        }
        public virtual void DidChangeCardStatus(NSNumber status, string device)
        {
            if (status == null)
            {
                throw new ArgumentNullException("status");
            }
            if (device == null)
            {
                throw new ArgumentNullException("device");
            }
            var nsdevice = NSString.CreateNative(device);

            if (IsDirectBinding)
            {
                global::ApiDefinitions.Messaging.void_objc_msgSend_IntPtr_IntPtr(this.Handle, Selector.GetHandle("didChangeCardStatus:fromDevice:"), status.Handle, nsdevice);
            }
            else
            {
                global::ApiDefinitions.Messaging.void_objc_msgSendSuper_IntPtr_IntPtr(this.SuperHandle, Selector.GetHandle("didChangeCardStatus:fromDevice:"), status.Handle, nsdevice);
            }
            NSString.ReleaseNative(nsdevice);
        }
Example #44
0
        void Shine(bool active, UIView view)
        {
            if (view == null)
            {
                throw new ArgumentNullException("view");
            }

            if (active)
            {
                view.Layer.RemoveAllAnimations();

                view.Layer.ShadowColor   = UIColor.Blue.CGColor;
                view.Layer.ShadowOpacity = 0.0f;
                view.Layer.ShadowRadius  = 6.0f;
                view.Layer.ShadowOffset  = SizeF.Empty;
                view.Layer.MasksToBounds = false;

                var glow = CABasicAnimation.FromKeyPath("shadowOpacity");
                glow.AutoReverses = true;
                glow.Duration     = 0.5;
                glow.To           = NSNumber.FromDouble(0.9);
                glow.RepeatCount  = int.MaxValue;

                view.Layer.AddAnimation(glow, "glow");
            }
            else
            {
                view.Layer.RemoveAnimation("glow");

                if (view.Layer.ShadowColor == UIColor.Blue.CGColor)
                {
                    view.Layer.ShadowColor   = UIColor.Clear.CGColor;
                    view.Layer.ShadowOpacity = 0.0f;
                    view.Layer.ShadowRadius  = 0.0f;
                    view.Layer.ShadowOffset  = SizeF.Empty;
                    view.Layer.MasksToBounds = false;
                }
            }
        }
Example #45
0
        void Spin()
        {
            if (!IsRotating)
            {
                return;
            }
            if (Layer.AnimationForKey("Rotation") != null)
            {
                return;
            }

            var animation = new CABasicAnimation();

            animation.KeyPath           = "transform.rotation.z";
            animation.To                = NSNumber.FromDouble(Math.PI * 2);
            animation.Duration          = 2.0;
            animation.Cumulative        = true;
            animation.RepeatCount       = 1;
            animation.AnimationStopped += (s, a) => Spin();

            Layer.AddAnimation(animation, "Rotation");
        }
Example #46
0
        private void SetUnderline(bool underlined)
        {
            try
            {
                var label = (UILabel)Control;
                var text  = (NSMutableAttributedString)label.AttributedText;
                var range = new NSRange(0, text.Length);

                if (underlined)
                {
                    text.AddAttribute(UIStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), range);
                }
                else
                {
                    text.RemoveAttribute(UIStringAttributeKey.UnderlineStyle, range);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot underline Label. Error: ", ex.Message);
            }
        }
Example #47
0
        nfloat CalcRowHeight(nint row, bool tryReuse = true)
        {
            updatingRowHeight = true;
            var height = Table.RowHeight;

            for (int i = 0; i < Columns.Count; i++)
            {
                CompositeCell cell = tryReuse ? Table.GetView(i, row, false) as CompositeCell : null;
                if (cell == null)
                {
                    cell = (Columns [i] as TableColumn)?.DataView as CompositeCell;
                }

                if (cell != null)
                {
                    cell.ObjectValue = NSNumber.FromNInt(row);
                    height           = (nfloat)Math.Max(height, cell.FittingSize.Height);
                }
            }
            updatingRowHeight = false;
            return(height);
        }
Example #48
0
            public override nfloat GetSizeToFitColumnWidth(NSTableView tableView, nint column)
            {
                var tableColumn = Backend.Columns[(int)column] as TableColumn;
                var width       = tableColumn.HeaderCell.CellSize.Width;

                CompositeCell templateCell = null;

                for (int i = 0; i < tableView.RowCount; i++)
                {
                    var cellView = tableView.GetView(column, i, false) as CompositeCell;
                    if (cellView == null)                       // use template for invisible rows
                    {
                        cellView = templateCell ?? (templateCell = (tableColumn as TableColumn)?.DataView?.Copy() as CompositeCell);
                        if (cellView != null)
                        {
                            cellView.ObjectValue = NSNumber.FromInt32(i);
                        }
                    }
                    width = (nfloat)Math.Max(width, cellView.FittingSize.Width);
                }
                return(width);
            }
Example #49
0
        private void SetupRotationAnimation()
        {
            if (null == _rotationAnimation)
            {
                _rotationAnimation = CABasicAnimation.FromKeyPath("transform.rotation.z");
                _rotationAnimation.AnimationStopped += (x, y) =>
                {
                    // Reinitialize any animation settings.
                    SetupRotationAnimation();

                    if (IsIndeterminate)
                    {
                        // Re-queue the animation to keep the loop going.
                        _arcLayer.AddAnimation(_rotationAnimation, ANIMATION_ROTATION);
                    }
                    else if (null != _arcLayer.AnimationForKey(ANIMATION_ROTATION))
                    {
                        // The rotation animation needs to be stopped, we we'll ease it out...
                        _rotationAnimation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseOut);
                        // ...then have it removed so it no longer recurs.
                        _rotationAnimation.RemovedOnCompletion = true;
                        // Queue it up for one final rotation...
                        _arcLayer.AddAnimation(_rotationAnimation, ANIMATION_ROTATION);
                    }
                };
            }

            _rotationAnimation.To             = NSNumber.FromFloat((float)Math.PI * 2);
            _rotationAnimation.Duration       = 0.78f;
            _rotationAnimation.Cumulative     = true;
            _rotationAnimation.FillMode       = CAFillMode.Forwards;
            _rotationAnimation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.Linear);
            // We don't want to remove the animation when completed, because that would cause the arc to snap back
            // to its original rotation value.
            _rotationAnimation.RemovedOnCompletion = false;
            // We're not going to automatically repeat, because we want the opportunity to modify the transform
            // on its final spin. Animations cannot be altered once they have been started.
            _rotationAnimation.RepeatCount = 0;
        }
        protected void AdvancedHudActionForRow(int row)
        {
            switch (row) {
                case 0:
                    hud.SetCaption("This HUD will auto-hide in 2 seconds.");
                    hud.BlockTouches = true;
                    hud.Show();
                    hud.HideAfter(2.0);
                    break;

                case 1:
                    hud.SetCaption("This HUD will update in 2 seconds.");
                    hud.BlockTouches = true;
                    hud.SetActivity(true);
                    hud.Show();
                    NSTimer.CreateScheduledTimer(2.0, () => { UpdatedHud(); });
                    break;

                case 2:
                {
                    float progress = 0.08f;

                    //NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
                    //[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

                    NSTimer timer = new NSTimer();
                    timer = NSTimer.CreateRepeatingScheduledTimer(0.02, () => {

                        progress += 0.01f;
                        hud.SetProgress(progress);
                        if (progress >= 1) {
                            progress = 0;
                            timer.Invalidate();
                            hud.Hide();

                            NSTimer.CreateScheduledTimer(0.2, () => { ResetProgress(); });
                        }
                    });

                    hud.SetCaption("Performing operation...");
                    hud.SetProgress(0.08f);
                    hud.BlockTouches = true;
                    hud.Show();
                    break;
                }

                case 3:
                {
                    string[] captions = new [] { "Display #1", "Display #2", "Display #3" };
                    // Would love to just use UIImage but breaks when using a "null" image.
                    NSArray images = NSArray.FromObjects("", "", UIImage.FromBundle("19-check"));
                    NSNumber[] positions = new NSNumber[] { new NSNumber(2), new NSNumber(1), new NSNumber(2) };
                    NSNumber[] flags = new NSNumber[] { new NSNumber(false), new NSNumber(true), new NSNumber(false) };

                    hud.AddToQueue(captions, images, positions, flags);
                    hud.StartQueue();

                    NSTimer.CreateScheduledTimer(2.0, () => { ShowNextDisplayInQueue();	});
                    break;
                }
            }
        }
		public void AnimationStopped (string name, NSNumber numFinished, IntPtr context)
		{
			Console.WriteLine ("Animation completed");
		}
		public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath)
		{
			NSNumber height = new NSNumber((float)cell.Frame.Size.Height);
			this.heightAtIndexPath.Add (indexPath, height);
		}
        public static NSIndexSet IndexSetFromArray(NSNumber [] array)
        {
            List<NSObject> obj = new List<NSObject>();

            foreach (var item in array)
                obj.Add(item);

            NSArray arr = NSArray.FromNSObjects(obj.ToArray());

            return new NSIndexSet(_IndexSetFromArray(arr.Handle));
        }
Example #54
0
 public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
 {
     base.DiscoveredPeripheral(central, peripheral, advertisementData, RSSI);
 }
Example #55
0
 private static void Check(NSNumber number)
 {
     Assert.IsNotNull(number, "Number cannot be null");
     Assert.AreNotEqual(IntPtr.Zero, number.NativePointer, "Native pointer cannot be null");
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			uuidTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			uuidTextField.InputView = new UuidPickerView (uuidTextField);
			uuidTextField.EditingDidBegin += HandleEditingDidBegin;
			uuidTextField.EditingDidEnd += (sender, e) => {
				uuid = new NSUuid (uuidTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};

			majorTextField.KeyboardType = UIKeyboardType.NumberPad;
			majorTextField.ReturnKeyType = UIReturnKeyType.Done;
			majorTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			majorTextField.EditingDidBegin += HandleEditingDidBegin;
			majorTextField.EditingDidEnd += (sender, e) => {
				major = numberFormatter.NumberFromString (majorTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};

			minorTextField.KeyboardType = UIKeyboardType.NumberPad;
			minorTextField.ReturnKeyType = UIReturnKeyType.Done;
			minorTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			minorTextField.EditingDidBegin += HandleEditingDidBegin;
			minorTextField.EditingDidEnd += (sender, e) => {
				minor = numberFormatter.NumberFromString (minorTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};

			enabledSwitch.ValueChanged += (sender, e) => {
				enabled = enabledSwitch.On;
			};

			notifyOnEntrySwitch.ValueChanged += (sender, e) => {
				notifyOnEntry = notifyOnEntrySwitch.On;
			};

			notifyOnExitSwitch.ValueChanged += (sender, e) => {
				notifyOnExit = notifyOnExitSwitch.On;
			};

			notifyOnDisplaySwitch.ValueChanged += (sender, e) => {
				notifyOnDisplay = notifyOnDisplaySwitch.On;
			};

			doneButton = new UIBarButtonItem (UIBarButtonSystemItem.Done, (sender, e) => {
				uuidTextField.ResignFirstResponder ();
				majorTextField.ResignFirstResponder ();
				minorTextField.ResignFirstResponder ();
				TableView.ReloadData ();
			});

			saveButton = new UIBarButtonItem (UIBarButtonSystemItem.Save, (sender, e) => {
				if (enabled) {
					var region = Helpers.CreateRegion (uuid, major, minor);
					if (region != null) {
						region.NotifyOnEntry = notifyOnEntry;
						region.NotifyOnExit = notifyOnExit;
						region.NotifyEntryStateOnDisplay = notifyOnDisplay;
						locationManger.StartMonitoring (region);
					}
				} else {
					var region = (CLBeaconRegion)locationManger.MonitoredRegions.AnyObject;
					if (region != null)
						locationManger.StopMonitoring (region);
				}
				NavigationController.PopViewController (true);
			});

			NavigationItem.RightBarButtonItem = saveButton;
		}
Example #57
0
 public virtual NSInteger DataSizeAs(NSNumber @as)
 {
     return ObjectiveCRuntime.SendMessage <NSInteger>(this, "dataSizeAs:", @as);
 }
        public object Create(XElement xCurrentElement = null)
        {
            id nsObj = null;

            //XmlElement = (xCurrentElement != null) ? xCurrentElement : XmlElement;
            //var xElement = XmlElement;

            var xElement = (xCurrentElement != null) ? xCurrentElement : XmlElement;

            NSString attrClass = string.Empty;
            //string key = (xElement.Attribute("key") != null) ? xElement.Attribute("key").Value : null;
            NSString id = (xElement.Attribute("id") != null) ? xElement.Attribute("id").Value : null;

            switch (xElement.Name.LocalName)
            {
                case "nil": { nsObj = null; break; }

                case "integer": { nsObj = new NSNumber(Convert.ToInt32(xElement.Attribute("value").Value)); break; }
                case "int": { nsObj = new NSNumber(Convert.ToInt32(xElement.Value)) { }; break; }

                case "string": { nsObj = new NSString(xElement.Value) { }; break; }
                case "bool": { nsObj = new NSNumber(xElement.Value.ConvertFromYesNo()) { }; break; }

                case "array":
                    {
                        attrClass = xElement.AttributeValueOrDefault("class", "NSArray");
                        nsObj = (id)CreateFromClassName(xElement, attrClass);
                        break;
                    }

                case "dictionary":
                    {
                        attrClass = xElement.AttributeValueOrDefault("class", "NSDictionary");
                        nsObj = (id)CreateFromClassName(xElement, attrClass);
                        break;
                    }

                case "object":
                    {
                        attrClass = xElement.AttributeValueOrDefault("class", string.Empty);
                        nsObj = (id)CreateFromClassName(xElement, attrClass);
                        break;
                    }

                case "reference":
                    {
                        NSString refId = xElement.AttributeValueOrDefault("ref", "");
                        bool foundRefID = Document.ListOfReferenceId.TryGetValue(refId, out nsObj);
                        if (!foundRefID)
                        {
                            System.Diagnostics.Debug.WriteLine(string.Format("Unknown ReferenceID {0}", refId));
                        }
                    }
                    break;
                default:

                    System.Diagnostics.Debug.WriteLine(string.Format("Unknown element {0}", xElement.Name.LocalName));
                    break;
            }

            return nsObj;
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			this.Title = "Configure";

			enabledSwitch.ValueChanged += (sender, e) => {
				enabled = enabledSwitch.On;
			};

			uuidTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			uuidTextField.InputView = new UuidPickerView (uuidTextField);
			uuidTextField.EditingDidBegin += HandleEditingDidBegin;
			uuidTextField.EditingDidEnd += (sender, e) => {
				uuid = new NSUuid (uuidTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};
			uuidTextField.Text = uuid.AsString ();

			majorTextField.KeyboardType = UIKeyboardType.NumberPad;
			majorTextField.ReturnKeyType = UIReturnKeyType.Done;
			majorTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			majorTextField.EditingDidBegin += HandleEditingDidBegin;
			majorTextField.EditingDidEnd += (sender, e) => {
				major = numberFormatter.NumberFromString (majorTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};

			minorTextField.KeyboardType = UIKeyboardType.NumberPad;
			minorTextField.ReturnKeyType = UIReturnKeyType.Done;
			minorTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			minorTextField.EditingDidBegin += HandleEditingDidBegin;
			minorTextField.EditingDidEnd += (sender, e) => {
				minor = numberFormatter.NumberFromString (minorTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};

			measuredPowerTextField.KeyboardType = UIKeyboardType.NumberPad;
			measuredPowerTextField.ReturnKeyType = UIReturnKeyType.Done;
			measuredPowerTextField.AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
			measuredPowerTextField.EditingDidBegin += HandleEditingDidBegin;
			measuredPowerTextField.EditingDidEnd += (sender, e) => {
				power = numberFormatter.NumberFromString (measuredPowerTextField.Text);
				NavigationItem.RightBarButtonItem = saveButton;
			};

			doneButton = new UIBarButtonItem (UIBarButtonSystemItem.Done, (sender, e) => {
				uuidTextField.ResignFirstResponder ();
				majorTextField.ResignFirstResponder ();
				minorTextField.ResignFirstResponder ();
				measuredPowerTextField.ResignFirstResponder ();
				TableView.ReloadData ();
			});

			saveButton = new UIBarButtonItem (UIBarButtonSystemItem.Save, (sender, e) => {
				if (peripheralManager.State < CBPeripheralManagerState.PoweredOn) {
					new UIAlertView ("Bluetooth must be enabled", "To configure your device as a beacon", null, "OK", null).Show ();
					return;
				}

				if (enabled) {
					CLBeaconRegion region = Helpers.CreateRegion (uuid, major, minor);
					if (region != null)
						peripheralManager.StartAdvertising (region.GetPeripheralData (power));
				} else {
					peripheralManager.StopAdvertising ();
				}

				NavigationController.PopViewControllerAnimated (true);
			});

			NavigationItem.RightBarButtonItem = saveButton;
		}
	public void _commonInit(){
		NSMutableDictionary buttonDictionary = new NSMutableDictionary();

		/*const*/ MMNumberKeyboardButton numberMin = MMNumberKeyboardButton.NumberMin;
		/*const*/ MMNumberKeyboardButton numberMax = MMNumberKeyboardButton.NumberMax;

		UIFont buttonFont = UIFont.FromName("Helvetica-Bold", 20f);
		if (buttonFont.RespondsToSelector(new Selector ( "weight:"))) {
			buttonFont = UIFont.SystemFontOfSize(28.0f ,/*weight*/ UIFontWeight.Light);
		} else {
			buttonFont = UIFont.FromName("HelveticaNeue-Light" ,/*size*/ 28.0f);
		}

		UIFont doneButtonFont = UIFont.SystemFontOfSize(17.0f);

		//for (MMNumberKeyboardButton key =  numberMin;key < numberMax; key++) {
		foreach (MMNumberKeyboardButton key in Enum.GetValues(typeof(MMNumberKeyboardButton))) {
			UIButton button = new  _MMNumberKeyboardButton(MMNumberKeyboardButtonType.White);
			string Title = (key - numberMin).ToString();

			button.SetTitle(Title ,/*forState*/ UIControlState.Normal);
			button.TitleLabel.Font = buttonFont;
			int keyInt = (int)key;
				Console.WriteLine ("keyInt:"+keyInt);
				var number = new NSNumber (keyInt);
				Console.WriteLine ("number:"+number);
			buttonDictionary.Add(button ,number);
		}

		UIImage backspaceImage = this._keyboardImageNamed("MMNumberKeyboardDeleteKey.png");
		UIImage dismissImage = this._keyboardImageNamed("MMNumberKeyboardDismissKey.png");

		_MMNumberKeyboardButton backspaceButton = new _MMNumberKeyboardButton(MMNumberKeyboardButtonType.Gray);
		backspaceButton.SetImage( /*setImage*/ backspaceImage.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate ), UIControlState.Normal);

		backspaceButton.AddTarget( /*addTarget*/ this ,/*action*/ new Selector ("_backspaceRepeat: ") ,/*.forContinuousPressWithTimeInterval*/ 0.15f);

		buttonDictionary.Add(backspaceButton ,/*forKey*/ NSObject.FromObject(MMNumberKeyboardButton.Backspace));

		UIButton specialButton = new _MMNumberKeyboardButton(MMNumberKeyboardButtonType.Gray);

		buttonDictionary.Add(specialButton ,/*forKey*/ NSObject.FromObject(MMNumberKeyboardButton.Special));

		UIButton doneButton = new _MMNumberKeyboardButton(MMNumberKeyboardButtonType.Done);
		doneButton.TitleLabel.Font = doneButtonFont;
		doneButton.SetTitle(UIKitLocalizedString("Done") ,/*forState*/ UIControlState.Normal);

		buttonDictionary.Add(doneButton ,/*forKey*/ NSObject.FromObject(MMNumberKeyboardButton.Done));

		_MMNumberKeyboardButton decimalPointButton = new _MMNumberKeyboardButton(MMNumberKeyboardButtonType.White);

		NSLocale locale = this.locale ??  NSLocale.CurrentLocale;
		string decimalSeparator = @".";//locale.ObjectForKey(NSLocale.DecimalSeparator);
		decimalPointButton.SetTitle(decimalSeparator ??  "." ,/*forState*/ UIControlState.Normal);

		buttonDictionary.Add(decimalPointButton ,/*forKey*/ NSObject.FromObject(MMNumberKeyboardButton.DecimalPoint));

		foreach (UIButton button in buttonDictionary.Values) {
			button.ExclusiveTouch = true;
			button.AddTarget(this ,/*action*/ new Selector ("_buttonInput") ,/*forControlEvents*/ UIControlEvent.TouchUpInside);
			button.AddTarget(this ,/*action*/ new Selector ("_buttonPlayClick") ,/*forControlEvents*/ UIControlEvent.TouchDown);

			this.AddSubview(button);
		}

		UIPanGestureRecognizer highlightGestureRecognizer = new UIPanGestureRecognizer(this ,/*action*/ new Selector ("_handleHighlightGestureRecognizer"));
		this.AddGestureRecognizer(highlightGestureRecognizer);

		this.buttonDictionary = buttonDictionary;

		// Add default action.
		this.configureSpecialKeyWithImage(dismissImage ,/*target*/ this ,/*action*/ new Selector ("_dismissKeyboard"));

		// Size to fit.
		this.SizeToFit();
	}