コード例 #1
0
		public override void LowLevelSetAttributes (IntPtr attrs, NSRange range)
		{
			BeginEditing ();
			backingStore.LowLevelSetAttributes (attrs, range);
			Edited (NSTextStorageEditActions.Attributes, range, 0);
			EndEditing ();
		}
コード例 #2
0
		void ApplyTokenAttributes (NSRange searchRange)
		{
			NSDictionary attributesForToken = Tokens ["DefaultTokenName"];
			int startPos = (int)searchRange.Location;

			string text = backingStore.Value.Substring ((int)searchRange.Location,(int)searchRange.Length);
			int nextSpace = text.IndexOfAny (" \n\t.".ToCharArray ());
			int lastPos = 0;
			string token;
			NSRange tokenRange;
			while (true) {
				if (nextSpace == -1)
					nextSpace = text.Length;

				token = text.Substring (lastPos, nextSpace - lastPos);
				tokenRange = new NSRange (lastPos + startPos, nextSpace - lastPos);

				if (Tokens.ContainsKey (token))
					attributesForToken = Tokens [token];
				else
					attributesForToken = Tokens ["DefaultTokenName"];

				AddAttributes (attributesForToken, tokenRange);
				if (nextSpace == text.Length)
					break;
				lastPos = nextSpace + 1;
				nextSpace = text.IndexOfAny (" \n\t.".ToCharArray (), nextSpace + 1);
			}
		}
コード例 #3
0
ファイル: NSSpellChecker.cs プロジェクト: afrog33k/mcocoa
        /// <exclude/>
        public int requestCheckingOfString_range_types_options_inSpellDocumentWithTag_completionHandler(
			NSString stringToCheck,
			NSRange range,
			ulong checkingTypes,
			NSDictionary options,
			int tag,
			Action<int, NSArray, NSOrthography, int> callback)
        {
            RequestCheckingCallback thunk = (IntPtr context, int sequenceNumber, IntPtr resultsPtr, IntPtr orthographyPtr, int wordCount) =>
            {
                var results = NSObject.Lookup(resultsPtr).To<NSArray>();
                var orthography = NSObject.Lookup(orthographyPtr).To<NSOrthography>();
                callback(sequenceNumber, results, orthography, wordCount);
            };

            var block = new ExtendedBlock(thunk);
            int result = Call("requestCheckingOfString:range:types:options:inSpellDocumentWithTag:completionHandler:",
                stringToCheck,
                range,
                checkingTypes,
                options,
                tag,
                block).To<int>();
            GC.KeepAlive(block);

            return result;
        }
コード例 #4
0
        public static bool ShoudChange(UITextField textField, NSRange range, string toString)
        {
            int length = getLength (textField.Text);

            if(length == 10)
            {
                if(range.Length == 0)
                    return false;
            }

            if(length == 3)
            {
                string num = formatNumber(textField.Text);
                textField.Text = string.Format ("({0}) ", num);
                if(range.Length > 0)
                    textField.Text = string.Format ("{0}", num.Substring(0, 3));
            }
            else if(length == 6)
            {
                string num = formatNumber(textField.Text);

                textField.Text = string.Format ("({0}) {1}-",num.Substring (0, 3) ,num.Substring (3));
                if(range.Length > 0)
                    textField.Text = string.Format ("({0}) {1}",num.Substring (0, 3) ,num.Substring (3));
            }

            return true;
        }
コード例 #5
0
ファイル: ColorFormatter.cs プロジェクト: yingfangdu/BNR
        public bool IsPartialStringValid(ref NSString partial, ref NSRange selPtr, NSString origString, ref NSRange origSel, IntPtr error)
        {
            // Zero length strings are OK
            if (partial.Length == 0) {
                return true;
            }
            string match = FirstColorKeyForPartialString(partial);
            // No color match?
            if (match == null) {
                return false;
            }

            // If no letters were added, it is a delete
            //			Console.WriteLine("orig string: {0}, partial string: {1}", origString, partial);
            if (oldColorStringLength == partial.Length) {
                oldColorStringLength--;
                selPtr.Location = partial.Length -1;
                selPtr.Length = match.Length - selPtr.Location;
                partial = (NSString)match;
                return false;
            }
            oldColorStringLength = partial.Length;
            // If the partial string is shorter than the match,
            // provide the match and set the selection
            if (match.Length != partial.Length) {
                selPtr.Location = partial.Length;
                selPtr.Length = match.Length - selPtr.Location;
                partial = (NSString)match;
                return false;
            }
            return true;
        }
コード例 #6
0
		public override bool ShouldChangeCharacters(UITextField textField, NSRange theRange, String replacementString)
		{
			System.Console.WriteLine ("ShouldChangeCharacters '{0}' -> {1}, {2}, '{3}' ?", textField.Text, theRange.Location, theRange.Length, replacementString);

			// We could prevent (or warn of) nonsensical or out-of-bounds values?

			return true;
		}
コード例 #7
0
		public override void Replace (NSRange range, string newValue)
		{
			BeginEditing ();
			backingStore.Replace (range, newValue);
			Edited (NSTextStorageEditActions.Characters | NSTextStorageEditActions.Attributes, range, newValue.Length - range.Length);
			dynamicTextNeedsUpdate = true;
			EndEditing ();
		}
コード例 #8
0
		public override bool ShouldChangeText (UITextView textView, NSRange range, string text)
		{
			if (!text.Contains ("\n"))
				return true;

			textView.ResignFirstResponder ();
			return false;
		}
コード例 #9
0
		/// <summary>
		/// Clears the present logs.
		/// </summary>
		private void ClearLog()
		{
			var stor = LogField.TextStorage;
			var wholeRange = new NSRange(0, stor.Length);

			stor.BeginEditing();
			stor.DeleteRange(wholeRange);
			stor.EndEditing();
		}
コード例 #10
0
ファイル: ListViewSwipe.cs プロジェクト: sudipnath/ios-sdk
 public NSAttributedString AttributedMailText(string text)
 {
     Random r = new Random ();
     string randomString = loremIpsum.GenerateString (10 + r.Next (0, 16));
     string str = String.Format ("{0}\n{1}", text, randomString);
     NSMutableAttributedString attrStr = new NSMutableAttributedString (str, new NSDictionary ());
     NSRange range = new NSRange (str.IndexOf ("\n"), "\n".Length);
     attrStr.AddAttribute(UIStringAttributeKey.ForegroundColor, UIColor.Gray, new NSRange(range.Location, str.Length - range.Location));
     return attrStr;
 }
コード例 #11
0
		bool ShouldInteractWithUrl (UITextView textView, NSUrl url, NSRange characterRange)
		{
			if (url.Host == "www.xamarin.com") {
				var webViewController = (WebViewController)Storyboard.InstantiateViewController ("WebViewController");
				PresentViewController (webViewController, true, delegate {
					webViewController.webView.LoadRequest (NSUrlRequest.FromUrl (url));
				});
				return false;
			};
			return true;
		}
コード例 #12
0
 public override string GetTypo(string txt)
 {
     #if __WATCHOS__
     return string.Empty;
     #else
     var checkRange = new NSRange (0, txt.Length);
     var typoRange = checker.RangeOfMisspelledWordInString (txt, checkRange, checkRange.Location, false, "en_US");
     if (typoRange.Length == 0)
         return String.Empty;
     return txt.Substring ((int) typoRange.Location, (int) typoRange.Length);
     #endif
 }
        public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
        {
            if (string.IsNullOrEmpty(replacementString))
                return true;

            var newText = (textField.Text ?? "").Remove(range.Location, range.Length)
                             .Insert(range.Location, replacementString);
            //MvxTrace.Trace(
            //	"ShouldChangeCharacters, before: {0}, replace: {1}, newtext: {2}",
            //	this.Text, replacementString, newText);

            return IsOk(newText);
        }
コード例 #14
0
            public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
            {
                var newText = textField.Text.Remove (range.Location, range.Length);
                newText = newText.Insert (range.Location, replacementString);

                if (newText.Length > 0) {
                    textField.Text = (UIDecimalField.GetAmountFromString (newText)).ToString ("N2");

                    return false;
                }

                return false;
            }
コード例 #15
0
        /// <summary>
        /// Gets called when pressing the button to calculate PI.
        /// </summary>
        /// <param name="sender">Sender.</param>
partial         void HandleCalculatePi(UIButton sender)
        {
            this.isCalculating = !this.isCalculating;
            btnCalculate.SetTitle(this.isCalculating ? "Stop calculating" : "Start calculating", UIControlState.Normal);

            if(!this.isCalculating)
            {
                // Cancel calculation if it is currently running.
                this.cts.Cancel();
                return;
            }
            else
            {
                // Use a cancellation token to be able to stop the calculation.
                this.cts = new CancellationTokenSource();
                this.txtPi.Text = string.Empty;
            }

            // Prepare for background processing.
            int taskId = -1;

            // We are running on an extra thread here. Still, the app gets paused if it is backgrounded.
            Task.Run(() =>
            {
                // TODO: LongRunningTasks 01 - Comment back in to prevent thread from being interrupted if home button is pressed
            //				taskId = UIApplication.SharedApplication.BeginBackgroundTask(() => {
            //					Console.WriteLine("Background time expires!");
            //					this.cts.Cancel();
            //				});

                Helpers.CalcPi(pi =>
                {
                    Console.WriteLine("Background time remaining: " + Math.Round(UIApplication.SharedApplication.BackgroundTimeRemaining) + " seconds");
                    Console.WriteLine("A bit of Pi: " + pi);
                    this.InvokeOnMainThread(() =>
                    {
                        this.txtPi.Text += " " + pi;
                        var range = new NSRange(txtPi.Text.Length - 1, 1);
                        txtPi.ScrollRangeToVisible(range);
                    });
                }, this.cts.Token);

                if(taskId != -1)
                {
                    // Balanced call to BeginBackgroundTask()
                    UIApplication.SharedApplication.EndBackgroundTask(taskId);
                }
            });
        }
コード例 #16
0
            public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
            {
                var text = textField.Text;
                string newText = text;
                if (range.Location >= text.Length)
                {
                    newText = text + replacementString;
                }
                else
                {
                    var substr = text.Substring(0, range.Location);
                    var finalIndex = range.Location + range.Length - 1;
                    if(finalIndex >= text.Length - 1) {
                        newText = substr + replacementString;
                    }
                    else
                    {
                        var substr2 = text.Substring(finalIndex + 1);
                        newText = substr + replacementString + substr2;
                    }
                }

                var numText = NumberFormattingHelper.StripCurrency(newText);
                if (numText.Length > _digitLimit) return false;

                string result = string.Empty;
                if (numText.Length == 0)
                {
                    result = "$0";
                }
                else
                {
                    int number;
                    if (Int32.TryParse(numText, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.CurrentCulture, out number))
                    {
                        result = string.Format("{0:C0}", number);
                    }
                }

                if (_postChangeAction != null)
                {
                    _postChangeAction(result);
                }
                
                textField.Text = result;
                
                return false;
            }
コード例 #17
0
        /// <summary>
        /// Limits the message text to MaxTextLength characters.
        /// </summary>
        public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
        {
            int limit = MaxTextLength;

            int newLength = (textField.Text.Length - (int)range.Length) + replacementString.Length;
            if (newLength <= limit)
                return true;

            int emptySpace = Math.Max(0, limit - (textField.Text.Length - (int)range.Length));
            string beforeCaret = textField.Text.Substring(0, (int)range.Location) + replacementString.Substring(0, emptySpace);
            string afterCaret = textField.Text.Substring((int)(range.Location + range.Length));

            textField.Text = beforeCaret + afterCaret;

            return false;
        }
コード例 #18
0
        /// <summary>
        /// Limits the message text to MaxTextLength characters.
        /// </summary>
        public override bool ShouldChangeText(UITextView textView, NSRange range, string text)
        {
            int limit = MaxTextLength;

            int newLength = (textView.Text.Length - (int)range.Length) + text.Length;
            if (newLength <= limit)
                return true;

            int emptySpace = Math.Max(0, limit - (textView.Text.Length - (int)range.Length));
            string beforeCaret = textView.Text.Substring(0, (int)range.Location) + text.Substring(0, emptySpace);
            string afterCaret = textView.Text.Substring((int)(range.Location + range.Length));

            textView.Text = beforeCaret + afterCaret;
            textView.SelectedRange = new NSRange(beforeCaret.Length, 0);

            return false;
        }
コード例 #19
0
		public static NSMutableAttributedString GetSearchResultAttributedString (this string result, string searchString)
		{
			var attrString = new NSMutableAttributedString (result);

			attrString.AddAttributes (SearchResultStringAttributes, new NSRange (0, result.Length));

			var index = result.IndexOf (searchString, StringComparison.OrdinalIgnoreCase);

			if (index >= 0 && index + searchString.Length <= result.Length) {

				var range = new NSRange (index, searchString.Length);

				attrString.AddAttributes (SearchResultHighlightStringAttributes, range);
			}

			return attrString;
		}
コード例 #20
0
        protected override bool AllowTextChange(string currentText, NSRange changedRange, string replacementText, string result)
        {
            // Base method checks against the max length for us...
            if (!base.AllowTextChange (currentText, changedRange, replacementText, result))
                return false;

            // Validate that all of the characters are legal for an airport code
            for (int i = 0; i < replacementText.Length; i++) {
                if ((replacementText[i] >= 'A' && replacementText[i] <= 'Z') ||
                    (replacementText[i] >= 'a' && replacementText[i] <= 'z') ||
                    (replacementText[i] >= '0' && replacementText[i] <= '9'))
                    continue;

                return false;
            }

            return true;
        }
コード例 #21
0
		void PerformReplacementsForCharacterChange (NSRange changeRange)
		{
			if (changeRange.Location == 0 && changeRange.Length == 0)
				return;

			var searchRange = new NSRange (0,Value.Length);
			int startLoc = Value.Substring (0, (int)changeRange.Location).LastIndexOfAny (" \n\t.".ToCharArray ());
			int endLoc = Value.Substring ((int)(changeRange.Location + changeRange.Length)).IndexOfAny (" \n\t.".ToCharArray ());
			if(startLoc != -1)
				searchRange.Location = startLoc;
			if (endLoc != -1)
				searchRange.Length = changeRange.Location + endLoc + 1 - startLoc;
			else
				searchRange.Length = searchRange.Length - searchRange.Location;

			searchRange.Location = Math.Min ((int)searchRange.Location, (int)changeRange.Location);
			searchRange.Length = Math.Max ((int)searchRange.Length, (int)changeRange.Length);
			ApplyTokenAttributes (searchRange);
		}
コード例 #22
0
		public void AskQuestion (string question, bool sendNotification)
		{
			// Anything to process?
			if (question == "") return;

			// Add question to history
			ChatHistory.Text += string.Format ("\nHuman: {0}", question);

			// Clear input
			ChatInput.Text = "";

			// Get response
			var response = Eliza.ProcessInput (question);

			// Add Eliza's response to history
			ChatHistory.Text += string.Format ("\nEliza: {0}\n", response);

			// Scroll output to bottom
			var bottom = new NSRange (ChatHistory.Text.Length - 1, 1);
			ChatHistory.ScrollRangeToVisible (bottom);

			// Sending a user notification as well
			if (sendNotification) {
				var content = new UNMutableNotificationContent ();
				content.Title = "ElizaChat Question";
				content.Subtitle = question;
				content.Body = response;

				var trigger = UNTimeIntervalNotificationTrigger.CreateTrigger (5, false);

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

				UNUserNotificationCenter.Current.AddNotificationRequest (request, (err) => {
					if (err != null) {
						Console.WriteLine ("Error: {0}", err);
					}
				});
			}
		}
コード例 #23
0
		/// <summary>
		/// Based on the user preferences set on the parent <see cref="AppKit.TextKit.Formatter.SourceTextView"/>, this
		/// method returns the available list of partial word completions.
		/// </summary>
		/// <returns>The list of word completions that will be presented to the user.</returns>
		/// <param name="textView">The source <see cref="AppKit.TextKit.Formatter.SourceTextView"/>.</param>
		/// <param name="words">A list of default words automatically provided by OS X in the user's language.</param>
		/// <param name="charRange">The cursor location where the partial word exists.</param>
		/// <param name="index">The word that should be selected when the list is displayed (usually 0 meaning
		/// the first item in the list). Pass -1 for no selected items.</param>
		public override string[] GetCompletions (NSTextView textView, string[] words, NSRange charRange, ref nint index)
		{
			List<string> completions = new List<string> ();

			// Is auto complete enabled?
			if (TextEditor.AllowAutoComplete) {
				// Use keywords in auto complete?
				if (TextEditor.AutoCompleteKeywords) {
					// Yes, grab word being expanded
					var range = TextEditor.Formatter.FindWordBoundries (TextEditor.TextStorage.Value, charRange);
					var word = TextEditor.TextStorage.Value.Substring ((int)range.Location, (int)range.Length);

					// Scan the keywords for the a possible match
					foreach (string keyword in TextEditor.Formatter.Language.Keywords.Keys) {
						// Found?
						if (keyword.Contains (word)) {
							completions.Add (keyword);
						}
					}
				}

				// Use default words?
				if (TextEditor.AutoCompleteDefaultWords) {
					// Only if keywords list is empty?
					if (TextEditor.DefaultWordsOnlyIfKeywordsEmpty) {
						if (completions.Count == 0) {
							// No keywords, add defaults
							completions.AddRange (words);
						}
					} else {
						// No, always include default words
						completions.AddRange (words);
					}
				}
			}

			// Return results
			return completions.ToArray();
		}
コード例 #24
0
		public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
		{
			if (replacementString.Length > 0)
			{
				var oldLength = textField.Text.Length;
				var replacementLength = replacementString.Length;
				var rangeLength = range.Length;

				var newLength = oldLength - rangeLength + replacementLength;
				var inputAllowed = MaxLength == 0 || newLength <= MaxLength;

				var shouldChange = inputAllowed && (Digits == null || replacementString.IndexOfAny(Digits.ToCharArray()) != -1);

				if (shouldChange)
				{
					textField.Text = textField.Text.FormatToJudoString(Format);
				}

				return shouldChange;
			}
			return true;
		}
コード例 #25
0
		private bool TextShouldChangeCharacters(UITextField textField, NSRange range, string replacementString) {
			native.BecomeFirstResponder ();
			source.Delete = false;
			if (replacementString == "") {
				source.Delete = true;
			}
			else if (textField.Text.Length > source.MaxLengthFromMask && source.MaxLengthFromMask > 0) {
				return false;
			}

			if (source.Locked) {
				return false;
			}
			else if (source.Mask != null) {
				source.SelectionStart = (int)textField.GetOffsetFromPosition (textField.BeginningOfDocument, textField.SelectedTextRange.Start);
				source.SelectionEnd = (int)textField.GetOffsetFromPosition (textField.BeginningOfDocument, textField.SelectedTextRange.End);
				source.TextLength = native.Text.Length;
			} else {
				return true;
			}

			return true;
		}
コード例 #26
0
ファイル: CTTypesetter.cs プロジェクト: savytskyi/maccore
 static extern IntPtr CTTypesetterCreateLine(IntPtr typesetter, NSRange stringRange);
コード例 #27
0
        public bool IsPartialStringValid(ref NSString value, IntPtr proposedSelRange, NSString origString, NSRange origSelRange, ref IntPtr error)
        {
            var h = Handler;

            if (h == null)
            {
                return(true);
            }
            if (h.MaxLength > 0)
            {
                int size = (int)value.Length;
                if (size > h.MaxLength)
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #28
0
 public extern static void void_objc_msgSend_stret_rnsrange(ref NSRange stret, IntPtr receiver, IntPtr selector);
コード例 #29
0
        public static void SetBuffers(this IMTLArgumentEncoder encoder, IMTLBuffer[] buffers, nuint[] offsets, NSRange range)
        {
            if (buffers is null)
            {
                ObjCRuntime.ThrowHelper.ThrowArgumentNullException(nameof(buffers));
            }
            if (offsets is null)
            {
                ObjCRuntime.ThrowHelper.ThrowArgumentNullException(nameof(offsets));
            }

            var bufferPtrArray = buffers.Length <= 1024 ? stackalloc IntPtr[buffers.Length] : new IntPtr [buffers.Length];

            // get all intptr from the array to pass to the lower level call
            for (var i = 0; i < buffers.Length; i++)
            {
                bufferPtrArray [i] = buffers [i].Handle;
            }

            unsafe
            {
                fixed(void *buffersPtr = bufferPtrArray)
                fixed(void *offsetsPtr = offsets)                    // can use fixed
                {
                    encoder.SetBuffers((IntPtr)buffersPtr, (IntPtr)offsetsPtr, range);
                }
            }
            GC.KeepAlive(buffers);
        }
コード例 #30
0
        public unsafe nuint GetGlyphs(
            NSRange glyphRange,
            short[] /* CGGlyph* = CGFontIndex* = unsigned short* */ glyphBuffer,
            NSGlyphProperty[] /* NSGlyphProperty* = nint* */ props,
            nuint[] /* NSUInteger */ charIndexBuffer,
            byte[] /* (unsigned char *) */ bidiLevelBuffer)
        {
            if (glyphBuffer != null && glyphBuffer.Length < glyphRange.Length)
            {
                throw new ArgumentOutOfRangeException(string.Format("glyphBuffer must have at least {0} elements", glyphRange.Length));
            }

            if (props != null && props.Length < glyphRange.Length)
            {
                throw new ArgumentOutOfRangeException(string.Format("props must have at least {0} elements", glyphRange.Length));
            }

            if (charIndexBuffer != null && charIndexBuffer.Length < glyphRange.Length)
            {
                throw new ArgumentOutOfRangeException(string.Format("props must have at least {0} elements", glyphRange.Length));
            }

            if (bidiLevelBuffer != null && bidiLevelBuffer.Length < glyphRange.Length)
                throw new ArgumentOutOfRangeException(string.Format("bidiLevelBuffer must have at least {0} elements", glyphRange.Length));

            fixed(short *glyphs = glyphBuffer)
            {
                nuint rv;

#if ARCH_32
                // Unified/32: the output array is not the correct size, it needs to be int[], and it's an array of NSGlyphProperty (which is long)
                nint[] tmpArray = null;
                if (props != null)
                {
                    tmpArray = new nint [props.Length];
                }
#else
                // Unified/64 + Classic: the input array is the correct size
                var tmpArray = props;
#endif
                fixed(void *properties = tmpArray)
                {
                    fixed(nuint *charIBuffer = charIndexBuffer)
                    {
                        fixed(byte *bidi = bidiLevelBuffer)
                        {
                            rv = GetGlyphs(glyphRange, (IntPtr)glyphs, (IntPtr)properties, (IntPtr)charIBuffer, (IntPtr)bidi);
                        }
                    }
                }

#if ARCH_32
                // Marshal back from the tmpArray.
                if (tmpArray != null)
                {
                    for (int i = 0; i < props.Length; i++)
                    {
                        props [i] = (NSGlyphProperty)(long)tmpArray [i];
                    }
                }
#endif

                return(rv);
            }
        }
コード例 #31
0
 public override bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
 {
     return(Validations.ValidateInput(replacementString, Validations.ValidationType.User));
 }
コード例 #32
0
        bool ShouldChangeText(UISearchBar searchBar, NSRange range, string text)
        {
            var newLength = searchBar?.Text?.Length + text.Length - range.Length;

            return(newLength <= Element?.MaxLength);
        }
コード例 #33
0
        public void GetCoordinates(CLLocationCoordinate2D[] coords, NSRange range)
        {
            var ptr = GetPointer(coords);

            this._GetCoordinates(ptr, range);
        }
コード例 #34
0
 public virtual NSData DataFromRange(NSRange range, Dictionary <NSObject, AnyObject> documentAttributes, NSErrorPointer error)
 {
     return(default(NSData));
 }
コード例 #35
0
 bool OnShouldChangeText(UITextView textView, NSRange range, string replacementString) =>
 VirtualView.TextWithinMaxLength(textView.Text, range, replacementString);
コード例 #36
0
 void SetFontAttribute(NSRange range, NSFontTraitMask traitMask, NSFontTraitMask traitUnmask, bool enabled)
 {
     SetFontAttribute(range, enabled, f => UpdateFontTrait(f, traitMask, traitUnmask, enabled));
 }
コード例 #37
0
        internal void UpdateText()
        {
            if (_disposed || _renderer == null || _element == null)
            {
                return;
            }

            var control = Control;

            if (control == null)
            {
                return;
            }

            var transformedText = _element.UpdateFormsText(_element.Text, _element.TextTransform);

            control.SetTitle(transformedText, UIControlState.Normal);

            var normalTitle = control
                              .GetAttributedTitle(UIControlState.Normal);

            if (_element.CharacterSpacing == 0 && normalTitle == null)
            {
                control.SetTitle(transformedText, UIControlState.Normal);
                return;
            }

            if (control.Title(UIControlState.Normal) != null)
            {
                control.SetTitle(null, UIControlState.Normal);
            }

            string text       = transformedText ?? string.Empty;
            var    colorRange = new NSRange(0, text.Length);

            var normal =
                control
                .GetAttributedTitle(UIControlState.Normal)
                .WithCharacterSpacing(_element.CharacterSpacing);

            var highlighted =
                control
                .GetAttributedTitle(UIControlState.Highlighted)
                .WithCharacterSpacing(_element.CharacterSpacing);

            var disabled =
                control
                .GetAttributedTitle(UIControlState.Disabled)
                .WithCharacterSpacing(_element.CharacterSpacing);

            normal.AddAttribute(
                UIStringAttributeKey.ForegroundColor,
                Control.TitleColor(UIControlState.Normal),
                colorRange);

            highlighted.AddAttribute(
                UIStringAttributeKey.ForegroundColor,
                Control.TitleColor(UIControlState.Highlighted),
                colorRange);

            disabled.AddAttribute(
                UIStringAttributeKey.ForegroundColor,
                Control.TitleColor(UIControlState.Disabled),
                colorRange);

            Control.SetAttributedTitle(normal, UIControlState.Normal);
            Control.SetAttributedTitle(highlighted, UIControlState.Highlighted);
            Control.SetAttributedTitle(disabled, UIControlState.Disabled);

            UpdateEdgeInsets();
        }
コード例 #38
0
ファイル: GameLevel.cs プロジェクト: RangoLee/mac-samples
		void AnimateDynamicNodes ()
		{
			SCNNode dummyFront = RootNode.FindChildNode ("dummy_front", true);
			var dynamicNodesWithVertColorAnimation = new List<SCNNode> ();

			foreach (var split in dummyFront.ChildNodes)
				foreach (var splitElement in split.ChildNodes)
					foreach (var child in splitElement.ChildNodes) {

						var range = new NSRange ();
						if (!string.IsNullOrEmpty (child.ParentNode.Name)) {
							int index = child.ParentNode.Name.LastIndexOf ("vine");
							range = new NSRange (index, 4);
						}

						if (child.Geometry != null && child.Geometry.GetGeometrySourcesForSemantic (SCNGeometrySourceSemantic.Color) != null
						    && range.Location != NSRange.NotFound) {
							dynamicNodesWithVertColorAnimation.Add (child);
						}
					}

			string shaderCode = "uniform float timeOffset;\n" +
			                    "#pragma body\n" +
			                    "float speed = 20.05;\n" +
			                    "_geometry.position.xyz += (speed * sin(u_time + timeOffset) * _geometry.color.rgb);\n";

			foreach (SCNNode dynamicNode in dynamicNodesWithVertColorAnimation) {
				dynamicNode.Geometry.ShaderModifiers = new SCNShaderModifiers { EntryPointGeometry = shaderCode };
				var explodeAnimation = new CABasicAnimation {
					KeyPath = "timeOffset",
					Duration = 2.0,
					RepeatCount = float.MaxValue,
					AutoReverses = true,
					To = new NSNumber (MathUtils.RandomPercent ()),
					TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.EaseInEaseOut)
				};

				dynamicNode.Geometry.AddAnimation (explodeAnimation, (NSString)"sway");
			}
		}
コード例 #39
0
        private static bool HandleAttributes(
            IList <IAttributedTextRun> runs,
            TextWriter writer,
            NSAttributedString target,
            NSDictionary attrs,
            NSRange range)
        {
            var text = target.Substring(range.Location, range.Length).Value;

            var formatAttributes = new TextAttributes();
            var run = new AttributedTextRun((int)range.Location, (int)range.Length, formatAttributes);

            NSObject font;

            if (attrs.TryGetValue(NSStringAttributeKey.Font, out font))
            {
                var actualFont = (NSFont)font;
#if __MACOS__
                var fontName = actualFont.FontName;
#else
                var fontName = actualFont.Name;
#endif

                formatAttributes.SetFontSize((float)actualFont.PointSize);
                if (!fontName.StartsWith(".", System.StringComparison.Ordinal))
                {
                    formatAttributes.SetFontName(fontName);
                }
                else
                {
                    if (fontName.Contains("Italic"))
                    {
                        formatAttributes.SetItalic(true);
                    }

                    if (fontName.Contains("Bold"))
                    {
                        formatAttributes.SetBold(true);
                    }
                }
            }

            NSObject underline;
            if (attrs.TryGetValue(NSStringAttributeKey.UnderlineStyle, out underline))
            {
                var number = underline as NSNumber;
                if (number != null && number.Int32Value > 0)
                {
                    formatAttributes.SetUnderline(true);
                }
            }

            NSObject strikethrough;
            if (attrs.TryGetValue(NSStringAttributeKey.StrikethroughStyle, out strikethrough))
            {
                var number = strikethrough as NSNumber;
                if (number != null && number.Int32Value > 0)
                {
                    formatAttributes.SetStrikethrough(true);
                }
            }

#if MONOMAC
            NSObject superscript;
            if (attrs.TryGetValue(NSStringAttributeKey.Superscript, out superscript))
            {
                var number = superscript as NSNumber;
                if (number != null && number.Int32Value == -1)
                {
                    formatAttributes.SetSubscript(true);
                }
                else if (number != null && number.Int32Value == 1)
                {
                    formatAttributes.SetSuperscript(true);
                }
            }
#endif

            NSObject color;
            if (attrs.TryGetValue(NSStringAttributeKey.ForegroundColor, out color))
            {
                var colorObject = color as NSColor;
                if (colorObject != null)
                {
                    formatAttributes.SetForegroundColor(colorObject.ToHex());
                }
            }

            NSObject backgroundColor;
            if (attrs.TryGetValue(NSStringAttributeKey.BackgroundColor, out backgroundColor))
            {
                var colorObject = backgroundColor as NSColor;
                if (colorObject != null)
                {
                    formatAttributes.SetBackgroundColor(colorObject.ToHex());
                }
            }

#if MONOMAC
            NSObject paragraphStyleAsObject;
            if (attrs.TryGetValue(NSStringAttributeKey.ParagraphStyle, out paragraphStyleAsObject))
            {
                var paragraphStyle = (NSParagraphStyle)paragraphStyleAsObject;
                if (paragraphStyle.TextLists != null && paragraphStyle.TextLists.Length > 0)
                {
                    for (int i = 0; i < paragraphStyle.TextLists.Length; i++)
                    {
                        var textList     = paragraphStyle.TextLists [i];
                        var markerFormat = textList.MarkerFormat;

                        if ("{hyphen}".Equals(textList.MarkerFormat))
                        {
                            formatAttributes.SetUnorderedList(true);
                            formatAttributes.SetMarker(MarkerType.Hyphen);
                        }
                        else
                        {
                            formatAttributes.SetUnorderedList(true);
                            formatAttributes.SetMarker(MarkerType.ClosedCircle);
                        }
                    }
                }
            }
#endif

            if (run.Attributes.Count > 0)
            {
                runs.Add(run);
            }

            writer.Write(text);
            return(false);
        }
コード例 #40
0
ファイル: PrintDocumentHandler.cs プロジェクト: cwensley/Eto
 public override bool KnowsPageRange(ref NSRange aRange)
 {
     aRange = new NSRange(1, _numPages);
     return(true);
 }
コード例 #41
0
 public extern static void void_objc_msgSend_nsrange(IntPtr receiver, IntPtr selector, NSRange arg1);
コード例 #42
0
 public NSRange CharacterRangeForGlyphRange(NSRange charRange, ref NSRange actualCharRange)
 {
     return(GetCharacterRange(charRange, out actualCharRange));
 }
コード例 #43
0
 public LinkData(NSRange range, string url)
 {
     Range = range; Url = url;
 }
コード例 #44
0
 public NSRange CharacterRangeForGlyphRange(NSRange charRange)
 {
     return(GetCharacterRange(charRange));
 }
コード例 #45
0
 public extern static void NSRange_objc_msgSend_stret_IntPtr_byte_byte_byte(out NSRange retval, IntPtr receiver, IntPtr selector, IntPtr arg1, byte arg2, byte arg3, byte arg4);
コード例 #46
0
 public CGRect LineFragmentUsedRectForGlyphAtIndex(nuint glyphIndex, ref NSRange effectiveGlyphRange)
 {
     return(GetLineFragmentUsedRect(glyphIndex, out effectiveGlyphRange));
 }
コード例 #47
0
ファイル: UITextView.cs プロジェクト: afrog33k/CocoaSharp
 public virtual void ScrollRangeToVisible(NSRange range)
 {
 }
コード例 #48
0
 public NSTextContainer TextContainerForGlyphAtIndex(nuint glyphIndex, ref NSRange effectiveGlyphRange)
 {
     return(GetTextContainer(glyphIndex, out effectiveGlyphRange));
 }
コード例 #49
0
ファイル: TextDocument.cs プロジェクト: andyhebear/Continuum
		private Dictionary<char, int> DoFindControlChars(NSString str)
		{
			var chars = new Dictionary<char, int>();
			
			int len = (int) str.length();
			
			NSRange range = new NSRange(0, len);
			while (true)
			{
				NSRange temp = str.rangeOfCharacterFromSet_options_range(
					NSCharacterSet.controlCharacterSet(),
					Enums.NSLiteralSearch,
					range);
				if (temp.length == 0)
					break;
					
				char ch = str.characterAtIndex((uint) temp.location);
				if (ch != '\r' && ch != '\n' && ch != '\t' && ch != Constants.BOM[0])
				{
					if (chars.ContainsKey(ch))
						chars[ch] = chars[ch] + 1;
					else
						chars[ch] = 1;
				}
				
				range = new NSRange(temp.location + 1, len - (temp.location + 1));
			}
			
			return chars;
		}
コード例 #50
0
ファイル: CTTypesetter.cs プロジェクト: savytskyi/maccore
 static extern IntPtr CTTypesetterCreateLineWithOffset(IntPtr typesetter, NSRange stringRange, double offset);
コード例 #51
0
 public void _ReplaceCoordinatesInRange(NSRange range, CLLocationCoordinate2D[] coords)
 {
     this._ReplaceCoordinatesInRange(range, GetPointer(coords), Convert.ToUInt32(coords.Length));
 }
コード例 #52
0
ファイル: PrintDocumentHandler.cs プロジェクト: cwensley/Eto
 public override bool KnowsPageRange(ref NSRange aRange)
 {
     aRange = new NSRange(1, Handler.PageCount);
     return(true);
 }
コード例 #53
0
        protected virtual bool ShouldChangeText(UITextView textView, NSRange range, string text)
        {
            var newLength = textView.Text.Length + text.Length - range.Length;

            return(newLength <= Element.MaxLength);
        }
コード例 #54
0
        public static NSMutableAttributedString ToAttributedString(this FormattedText ft)
        {
            NSMutableAttributedString ns = new NSMutableAttributedString(ft.Text);

            ns.BeginEditing();
            foreach (var att in ft.Attributes)
            {
                var r = new NSRange(att.StartIndex, att.Count);
                if (att is BackgroundTextAttribute)
                {
                    var xa = (BackgroundTextAttribute)att;
                    ns.AddAttribute(NSStringAttributeKey.BackgroundColor, xa.Color.ToNSColor(), r);
                }
                else if (att is ColorTextAttribute)
                {
                    var xa = (ColorTextAttribute)att;
                    ns.AddAttribute(NSStringAttributeKey.ForegroundColor, xa.Color.ToNSColor(), r);
                }
                else if (att is UnderlineTextAttribute)
                {
                    var xa    = (UnderlineTextAttribute)att;
                    int style = xa.Underline ? 0x01 /*NSUnderlineStyleSingle*/ : 0;
                    ns.AddAttribute(NSStringAttributeKey.UnderlineStyle, (NSNumber)style, r);
                }
                else if (att is FontStyleTextAttribute)
                {
                    var xa = (FontStyleTextAttribute)att;
                    if (xa.Style == FontStyle.Italic)
                    {
                        Messaging.void_objc_msgSend_int_NSRange(ns.Handle, applyFontTraits.Handle, (IntPtr)(long)NSFontTraitMask.Italic, r);
                    }
                    else if (xa.Style == FontStyle.Oblique)
                    {
                        ns.AddAttribute(NSStringAttributeKey.Obliqueness, (NSNumber)0.2f, r);
                    }
                    else
                    {
                        ns.AddAttribute(NSStringAttributeKey.Obliqueness, (NSNumber)0.0f, r);
                        Messaging.void_objc_msgSend_int_NSRange(ns.Handle, applyFontTraits.Handle, (IntPtr)(long)NSFontTraitMask.Unitalic, r);
                    }
                }
                else if (att is FontWeightTextAttribute)
                {
                    var xa    = (FontWeightTextAttribute)att;
                    var trait = xa.Weight >= FontWeight.Bold ? NSFontTraitMask.Bold : NSFontTraitMask.Unbold;
                    Messaging.void_objc_msgSend_int_NSRange(ns.Handle, applyFontTraits.Handle, (IntPtr)(long)trait, r);
                }
                else if (att is LinkTextAttribute)
                {
                    var xa = (LinkTextAttribute)att;
                    if (xa.Target != null)
                    {
                        ns.AddAttribute(NSStringAttributeKey.Link, new NSUrl(xa.Target.ToString()), r);
                    }
                    ns.AddAttribute(NSStringAttributeKey.ForegroundColor, Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToNSColor(), r);
                    ns.AddAttribute(NSStringAttributeKey.UnderlineStyle, NSNumber.FromInt32((int)NSUnderlineStyle.Single), r);
                }
                else if (att is StrikethroughTextAttribute)
                {
                    var xa    = (StrikethroughTextAttribute)att;
                    int style = xa.Strikethrough ? 0x01 /*NSUnderlineStyleSingle*/ : 0;
                    ns.AddAttribute(NSStringAttributeKey.StrikethroughStyle, (NSNumber)style, r);
                }
                else if (att is FontTextAttribute)
                {
                    var xa = (FontTextAttribute)att;
                    var nf = ((FontData)Toolkit.GetBackend(xa.Font)).Font;
                    ns.AddAttribute(NSStringAttributeKey.Font, nf, r);
                }
            }
            ns.EndEditing();
            return(ns);
        }
コード例 #55
0
ファイル: VariableItem.cs プロジェクト: andyhebear/Continuum
        private void DoRefreshValueText(string newValue, object value)
        {
            NSAttributedString str;
            NSColor nameColor = NSColor.blackColor();

            ObjectMirror obj = value as ObjectMirror;
            if (obj != null && obj.IsCollected)
            {
                str = DoCreateString("garbage collected", NSColor.disabledControlTextColor());
                nameColor = NSColor.disabledControlTextColor();
            }
            else
            {
                string oldValue = AttributedValue.ToString();
                if (newValue != oldValue)
                {
                    if (newValue.Length == 0)
                    {
                        str = DoCreateString(string.Empty, NSColor.redColor());
                        nameColor = NSColor.redColor();						// we've gone from having value text to not having it (probably because the value went from null to non-null), so make it more obvious that it has changed
                    }
                    else
                    {
                        str = DoCreateString(newValue, NSColor.redColor());
                    }
                }
                else
                {
                    str = NSAttributedString.Create(newValue).Retain();
                }
            }

            AttributedValue.release();										// note that we want to reset the text even if it has not changed so that we go from red back to black
            AttributedValue = str;

            NSRange range = new NSRange(0, (int) AttributedName.length());
            AttributedName.addAttribute_value_range(Externs.NSForegroundColorAttributeName, nameColor, range);
        }
コード例 #56
0
ファイル: EntryRenderer.cs プロジェクト: MIliev11/Samples
        bool ShouldChangeCharacters(UITextField textField, NSRange range, string replacementString)
        {
            var newLength = textField?.Text?.Length + replacementString.Length - range.Length;

            return(newLength <= Element?.MaxLength);
        }
コード例 #57
0
ファイル: EditText.iOS.cs プロジェクト: h78hy78yhoi8j/xenko
        private bool ShouldChangeCharacters(UITextField theTextField, NSRange range, string replacementString)
        {
            // check that new characters are correct.
            var predicate = CharacterFilterPredicate;
            foreach (var character in replacementString)
            {
                if (predicate != null && !predicate(character))
                    return false;
            }

            var replacementSize = replacementString.Length - range.Length;
            return replacementSize < 0 || theTextField.Text.Length + replacementSize <= MaxLength;
        }
コード例 #58
0
ファイル: Messaging.cs プロジェクト: zcf7822/monodevelop
 public static extern void void_objc_msgSend_int_NSRange(IntPtr handle, IntPtr sel, IntPtr a1, NSRange a2);
コード例 #59
0
		private void InputControlTextChanged(object sender, EventArgs e)
		{
			NSRange range = new NSRange(_InputControl.Text.Length - 1, 1);
			_InputControl.ScrollRangeToVisible(range);

			var size = new SizeF(GetWidth(), float.MaxValue);
			
			var height = GetHeight(TableView);

			var frame = Cell.RecalculateContentFrame(new RectangleF(0, 0, size.Width, height), ShowCaption);
			
			if (height > frame.Height)
			{
				_InputControl.Frame = frame;

				TableView.BeginUpdates();
				TableView.EndUpdates();
			}
		}
コード例 #60
0
 static extern IntPtr CTFramesetterCreateFrame(IntPtr framesetter, NSRange stringRange, IntPtr path, IntPtr frameAttributes);