Example #1
0
        public bool OnCompletedLayout(NSLayoutManager layout, bool atEnd)
        {
            bool finished = false;

            if (atEnd || (m_origin == NSPoint.Zero && layout.firstUnlaidCharacterIndex() > m_selected.location + 100))
            {
                if (m_length == -1 || m_length == m_controller.Text.Length)	// only restore the view if it has not changed since we last had it open
                {
                    if (m_origin != NSPoint.Zero)
                    {
                        var clip = m_controller.ScrollView.contentView().To<NSClipView>();
                        clip.scrollToPoint(m_origin);
                        m_controller.ScrollView.reflectScrolledClipView(clip);

                        if (m_selected != NSRange.Empty)
                            m_controller.TextView.setSelectedRange(m_selected);
                    }
                    else if (m_selected != NSRange.Empty && m_selected.location + m_selected.length <= m_controller.TextView.textStorage().string_().length())
                    {
                        m_controller.TextView.setSelectedRange(m_selected);
                        m_controller.TextView.scrollRangeToVisible(m_visible);

                        m_controller.TextView.showFindIndicatorForRange(m_deferred);
                    }
                }

                finished = true;
            }

            return finished;
        }
Example #2
0
        int IndexAtPoint(Point point)
        {
            if (Control is UILabel control)
            {
                var cgPoint = new CGPoint(point.X, point.Y - control.Frame.Y);

                // init text storage
                var textStorage = new NSTextStorage();
                var attrText    = new NSAttributedString(control.AttributedText);
                textStorage.SetString(attrText);

                // init layout manager
                var layoutManager = new NSLayoutManager();
                textStorage.AddLayoutManager(layoutManager);

                // init text container
                var textContainer = new NSTextContainer(new CGSize(control.Frame.Width, control.Frame.Height * 2))
                {
                    LineFragmentPadding  = 0,
                    MaximumNumberOfLines = (nuint)_currentDrawState.Lines,
                    LineBreakMode        = UILineBreakMode.WordWrap,
                    Size = new CGSize(control.Frame.Width, control.Frame.Height * 2)
                };
                layoutManager.AddTextContainer(textContainer);
                layoutManager.AllowsNonContiguousLayout = true;

                var characterIndex = layoutManager.GetCharacterIndex(cgPoint, textContainer);
                return((int)characterIndex);
            }
            return(-1);
        }
Example #3
0
        static double FindDefaultLineHeight(this NativeLabel control, int start, int length)
        {
            if (length == 0)
            {
                return(0.0);
            }

            var textStorage = new NSTextStorage();

#if __MOBILE__
            textStorage.SetString(control.AttributedText.Substring(start, length));
#else
            textStorage.SetString(control.AttributedStringValue.Substring(start, length));
#endif
            var layoutManager = new NSLayoutManager();
            textStorage.AddLayoutManager(layoutManager);

            var textContainer = new NSTextContainer(size: new SizeF(float.MaxValue, float.MaxValue))
            {
                LineFragmentPadding = 0
            };
            layoutManager.AddTextContainer(textContainer);

            var rect = GetCharacterBounds(new NSRange(0, 1), layoutManager, textContainer);
            return(rect.Bottom - rect.Top);
        }
        public void Defaults()
        {
            TestRuntime.AssertSystemVersion(ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false);

            using (var lm = new NSLayoutManager()) {
                Assert.False(lm.AllowsNonContiguousLayout, "AllowsNonContiguousLayout");
                Assert.True(lm.ExtraLineFragmentRect.IsEmpty, "ExtraLineFragmentRect");
                Assert.Null(lm.ExtraLineFragmentTextContainer, "ExtraLineFragmentTextContainer");
                Assert.True(lm.ExtraLineFragmentUsedRect.IsEmpty, "ExtraLineFragmentUsedRect");
                Assert.That(lm.FirstUnlaidCharacterIndex, Is.EqualTo((nuint)0), "FirstUnlaidCharacterIndex");
                Assert.That(lm.FirstUnlaidGlyphIndex, Is.EqualTo((nuint)0), "FirstUnlaidGlyphIndex");
                Assert.False(lm.HasNonContiguousLayout, "HasNonContiguousLayout");
#if !__MACCATALYST__
                Assert.That(lm.HyphenationFactor, Is.EqualTo((nfloat)0), "HyphenationFactor");
#endif
                Assert.That(lm.NumberOfGlyphs, Is.EqualTo((nuint)0), "NumberOfGlyphs");
                Assert.False(lm.ShowsControlCharacters, "ShowsControlCharacters");
                Assert.False(lm.ShowsInvisibleCharacters, "ShowsInvisibleCharacters");
                Assert.Null(lm.TextStorage, "TextStorage");
                Assert.True(lm.UsesFontLeading, "UsesFontLeading");
                if (TestRuntime.CheckXcodeVersion(10, 0))
                {
                    Assert.False(lm.LimitsLayoutForSuspiciousContents, "LimitsLayoutForSuspiciousContents");
                }
            }
        }
Example #5
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            textStorage = new InteractiveTextColoringTextStorage();
            CGRect newTextViewRect = View.Bounds;

            newTextViewRect.X     += 8;
            newTextViewRect.Width -= 16;

            var layoutManager = new NSLayoutManager();
            var container     = new NSTextContainer(new CGSize(newTextViewRect.Size.Width, float.MaxValue));

            container.WidthTracksTextView = true;

            layoutManager.AddTextContainer(container);
            textStorage.AddLayoutManager(layoutManager);

            var newTextView = new UITextView(newTextViewRect, container);

            newTextView.AutoresizingMask    = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
            newTextView.ScrollEnabled       = true;
            newTextView.KeyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag;

            View.Add(newTextView);

            var tokens = new Dictionary <string, NSDictionary> ();

            tokens.Add("Alice", new NSDictionary(UIStringAttributeKey.ForegroundColor, UIColor.Red));
            tokens.Add("Rabbit", new NSDictionary(UIStringAttributeKey.ForegroundColor, UIColor.Orange));
            tokens.Add("DefaultTokenName", new NSDictionary(UIStringAttributeKey.ForegroundColor, UIColor.Black));
            textStorage.Tokens = tokens;

            SetText();
        }
Example #6
0
        private void UpdateHyperlinkLayout()
        {
            // Configure textContainer
            var textContainer = new NSTextContainer();

            textContainer.LineFragmentPadding  = 0;
            textContainer.LineBreakMode        = LineBreakMode;
            textContainer.MaximumNumberOfLines = (nuint)Lines;
            textContainer.Size = _drawRect.Size;

            // Configure layoutManager
            _layoutManager = new NSLayoutManager();
            _layoutManager.AddTextContainer(textContainer);

            // Configure textStorage
            var textStorage = new NSTextStorage();

            textStorage.SetString(GetAttributedText(NSAttributedStringTarget.NSTextStorage));
            textStorage.AddLayoutManager(_layoutManager);

            if (FeatureConfiguration.TextBlock.ShowHyperlinkLayouts)
            {
                textStorage.AddAttributes(
                    new UIStringAttributes()
                {
                    ForegroundColor = UIColor.Red
                },
                    new NSRange(0, textStorage.Length)
                    );
            }
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			textStorage = new InteractiveTextColoringTextStorage ();
			CGRect newTextViewRect = View.Bounds;
			newTextViewRect.X += 8;
			newTextViewRect.Width -= 16;

			var layoutManager = new NSLayoutManager ();
			var container = new NSTextContainer (new CGSize (newTextViewRect.Size.Width, float.MaxValue));
			container.WidthTracksTextView = true;

			layoutManager.AddTextContainer (container);
			textStorage.AddLayoutManager (layoutManager);

			var newTextView = new UITextView (newTextViewRect, container);
			newTextView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
			newTextView.ScrollEnabled  = true;
			newTextView.KeyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag;

			View.Add (newTextView);

			var tokens = new Dictionary<string, NSDictionary> ();
			tokens.Add ("Alice", new NSDictionary (UIStringAttributeKey.ForegroundColor, UIColor.Red));
			tokens.Add ("Rabbit", new NSDictionary (UIStringAttributeKey.ForegroundColor, UIColor.Orange));
			tokens.Add ("DefaultTokenName", new NSDictionary (UIStringAttributeKey.ForegroundColor, UIColor.Black));
			textStorage.Tokens = tokens;

			SetText ();
		}
        private static string DetectTappedUrl(UIGestureRecognizer tap, UILabel control)
        {
            CGRect             bounds         = control.Bounds;
            NSAttributedString attributedText = control.AttributedText;

            // Setup containers
            using var textContainer = new NSTextContainer(bounds.Size)
                  {
                      LineFragmentPadding  = 0,
                      LineBreakMode        = control.LineBreakMode,
                      MaximumNumberOfLines = (nuint)control.Lines
                  };

            using var layoutManager = new NSLayoutManager();
            layoutManager.AddTextContainer(textContainer);

            using var textStorage = new NSTextStorage();
            textStorage.SetString(attributedText);

            using var fontAttributeName = new NSString("NSFont");
            var textRange = new NSRange(0, control.AttributedText.Length);

            textStorage.AddAttribute(fontAttributeName, control.Font, textRange);
            textStorage.AddLayoutManager(layoutManager);
            CGRect textBoundingBox = layoutManager.GetUsedRectForTextContainer(textContainer);
Example #9
0
        public static double GetLineHeight(string fontName)
        {
            var editorFont = Xwt.Drawing.Font.FromName(fontName);

            using (var nsFont = NSFont.FromFontName(editorFont.Family, (nfloat)editorFont.Size))
                using (var lm = new NSLayoutManager())
                    return(lm.DefaultLineHeightForFont(nsFont));
        }
Example #10
0
        static CGRect GetCharacterBounds(NSRange characterRange, NSLayoutManager layoutManager, NSTextContainer textContainer)
        {
            var glyphRange = new NSRange();

            layoutManager.GetCharacterRange(characterRange, out glyphRange);

            return(layoutManager.GetBoundingRect(glyphRange, textContainer));
        }
        private string DetectTappedUrl(UIGestureRecognizer tap, UILabel label, IEnumerable <LinkData> linkList)
        {
            // Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
            var layoutManager = new NSLayoutManager();
            var textContainer = new NSTextContainer();
            var textStorage   = new NSTextStorage();

            textStorage.SetString(label.AttributedText);

            // Configure layoutManager and textStorage
            layoutManager.AddTextContainer(textContainer);
            textStorage.AddLayoutManager(layoutManager);

            // Configure textContainer
            textContainer.LineFragmentPadding  = 0;
            textContainer.LineBreakMode        = label.LineBreakMode;
            textContainer.MaximumNumberOfLines = (nuint)label.Lines;
            var labelSize = label.Bounds.Size;

            textContainer.Size = labelSize;

            // Find the tapped character location and compare it to the specified range
            var locationOfTouchInLabel = tap.LocationInView(label);
            var textBoundingBox        = layoutManager.GetUsedRectForTextContainer(textContainer);
            var textContainerOffset    = new CGPoint((labelSize.Width - textBoundingBox.Size.Width) * 0.0 - textBoundingBox.Location.X,
                                                     (labelSize.Height - textBoundingBox.Size.Height) * 0.0 - textBoundingBox.Location.Y);

            nfloat labelX;

            switch (Element.HorizontalTextAlignment)
            {
            case TextAlignment.End:
                labelX = locationOfTouchInLabel.X - (labelSize.Width - textBoundingBox.Size.Width);
                break;

            case TextAlignment.Center:
                labelX = locationOfTouchInLabel.X - (labelSize.Width - textBoundingBox.Size.Width) / 2;
                break;

            default:
                labelX = locationOfTouchInLabel.X;
                break;
            }
            var locationOfTouchInTextContainer = new CGPoint(labelX - textContainerOffset.X, locationOfTouchInLabel.Y - textContainerOffset.Y);

            nfloat partialFraction  = 0;
            var    indexOfCharacter = (nint)layoutManager.CharacterIndexForPoint(locationOfTouchInTextContainer, textContainer, ref partialFraction);

            foreach (var link in linkList)
            {
                // Xamarin version of NSLocationInRange?
                if ((indexOfCharacter >= link.Range.Location) && (indexOfCharacter < link.Range.Location + link.Range.Length))
                {
                    return(link.Url);
                }
            }
            return(null);
        }
Example #12
0
        // NOTE: this method only works with single line UILabels, or multi-line labels with left aligned text
        // Potential fix found on timbroder's comment on https://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedstring-of-a-uilabel
        // Based on https://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedstring-of-a-uilabel
        // Based on https://samwize.com/2016/03/04/how-to-create-multiple-tappable-links-in-a-uilabel/
        /// <summary>
        /// Determines whether the tap is within the NSRange targetRange. Returns true if so, otherwise returns false.
        /// </summary>
        /// <returns><c>true</c>, if tap was within the targetRange of the label, <c>false</c> otherwise.</returns>
        /// <param name="label">The label containing the text.</param>
        /// <param name="targetRange">The target range of the tappable text within the label.</param>
        /// <param name="gestureRecognizer">Gesture recognizer.</param>
        /// <param name="textAlignment">Text alignment of the label.</param>
        public static bool DidTapAttributedTextInLabel(UILabel label, NSRange targetRange, UIGestureRecognizer gestureRecognizer, UITextAlignment textAlignment)
        {
            NSLayoutManager layoutManager = new NSLayoutManager();
            NSTextContainer textContainer = new NSTextContainer(CGSize.Empty);
            NSTextStorage   textStorage   = new NSTextStorage();

            textStorage.SetString(label.AttributedText);

            // Configure layoutManager and textStorage
            layoutManager.AddTextContainer(textContainer);
            textStorage.AddLayoutManager(layoutManager);

            // Configure textContainer
            textContainer.LineFragmentPadding  = 0.0f;
            textContainer.LineBreakMode        = label.LineBreakMode;
            textContainer.MaximumNumberOfLines = (System.nuint)label.Lines;

            CGSize labelSize = label.Bounds.Size;

            textContainer.Size = labelSize;

            // Find the tapped character location and compare it to the specified range
            CGPoint locationOfTouchInLabel = gestureRecognizer.LocationInView(label);
            CGRect  textBoundingBox        = layoutManager.GetUsedRectForTextContainer(textContainer);

            // Change based on the UITextAlignment enum
            float multiplier;

            if (textAlignment == UITextAlignment.Center)
            {
                multiplier = 0.5f;
            }
            else if (textAlignment == UITextAlignment.Right)
            {
                multiplier = 1.0f;
            }
            else
            {
                // textAlignment is Left, Natural, or Justified
                multiplier = 0.0f;
            }

            CGPoint textContainerOffset = new CGPoint(
                ((labelSize.Width - textBoundingBox.Size.Width) * multiplier - textBoundingBox.Location.X),
                ((labelSize.Height - textBoundingBox.Size.Height) * multiplier - textBoundingBox.Location.Y)
                );
            CGPoint locationOfTouchInTextContainer = new CGPoint(locationOfTouchInLabel.X - textContainerOffset.X, locationOfTouchInLabel.Y - textContainerOffset.Y);
            nfloat  partialFraction  = 0;
            int     indexOfCharacter = (int)layoutManager.CharacterIndexForPoint(locationOfTouchInTextContainer, textContainer, ref partialFraction);

            // Xamarin version of the function NSLocationInRange (Swift equivalent is to call ```NSLocationInRange(indexOfCharacter, targetRange);``` )
            // Credit to https://forums.xamarin.com/discussion/56484/need-to-put-html-into-a-label
            bool isInRange = (indexOfCharacter >= targetRange.Location) && (indexOfCharacter <= targetRange.Location + targetRange.Length);

            return(isInRange);
        }
Example #13
0
        nfloat HeightWrappedToViewWidth(NSTextView textView, float width)
        {
            NSLayoutManager layoutManager = textView.LayoutManager;
            NSTextContainer container     = textView.TextContainer;

            layoutManager.GetGlyphRange(container);              //force layout
            nfloat height = layoutManager.GetUsedRectForTextContainer(container).Height;

            return(height);
        }
Example #14
0
        public static double GetLineHeight(Xwt.Drawing.Font font)
        {
            if (font is null)
            {
                throw new ArgumentNullException(nameof(font));
            }

            using (var lm = new NSLayoutManager())
                return(lm.DefaultLineHeightForFont(font.ToNSFont()));
        }
Example #15
0
        static CGRect GetCharacterBounds(NSRange characterRange, NSLayoutManager layoutManager, NSTextContainer textContainer)
        {
            var glyphRange = new NSRange();

#if __MOBILE__
            layoutManager.CharacterRangeForGlyphRange(characterRange, ref glyphRange);
#else
            layoutManager.CharacterRangeForGlyphRange(characterRange, out glyphRange);
#endif
            return(layoutManager.BoundingRectForGlyphRange(glyphRange, textContainer));
        }
Example #16
0
        int IndexAtPoint(Point point)
        {
            var cgPoint = new CGPoint(point.X, point.Y - Control.Frame.Y);

            // init text storage
            var textStorage = new NSTextStorage();
            //if (Control.AttributedText != null)
            var attrText = new NSAttributedString(Control.AttributedText);

            textStorage.SetString(attrText);

            /*
             *          else
             *          {
             *                  var attrString = new NSMutableAttributedString(Control.Text);
             *                  attrString.AddAttribute(UIStringAttributeKey.Font, Control.Font, new NSRange(0, Control.Text.Length));
             *                  textStorage.SetString(attrString);
             *          }
             */

            // init layout manager
            var layoutManager = new NSLayoutManager();

            textStorage.AddLayoutManager(layoutManager);

            // init text container
            var textContainer = new NSTextContainer(new CGSize(Control.Frame.Width, Control.Frame.Height * 2));

            textContainer.LineFragmentPadding  = 0;
            textContainer.MaximumNumberOfLines = (nuint)ControlLines;
            textContainer.LineBreakMode        = UILineBreakMode.WordWrap;//Control.LineBreakMode;

            //if (Control.LineBreakMode == UILineBreakMode.TailTruncation || Control.LineBreakMode == UILineBreakMode.HeadTruncation || Control.LineBreakMode == UILineBreakMode.MiddleTruncation)
            //	textContainer.LineBreakMode = UILineBreakMode.WordWrap;

            textContainer.Size = new CGSize(Control.Frame.Width, Control.Frame.Height * 2);
            layoutManager.AddTextContainer(textContainer);
            layoutManager.AllowsNonContiguousLayout = true;

            //layoutManager.SetTextContainer(textContainer,new NSRange(0,Control.AttributedText.Length));

            //layoutManager.UsesFontLeading = true;
            //layoutManager.EnsureLayoutForCharacterRange(new NSRange(0,Control.AttributedText.Length));
            //layoutManager.EnsureLayoutForTextContainer(textContainer);
            nfloat partialFraction = 0;
            var    characterIndex  = layoutManager.CharacterIndexForPoint(cgPoint, textContainer, ref partialFraction);

            //[self.layoutManager drawGlyphsForGlyphRange:NSMakeRange(0, self.textStorage.length) atPoint:CGPointMake(0, 0)];
            //layoutManager.DrawGlyphs(new NSRange(0,Control.AttributedText.Length),Control.Frame.Location);

            return((int)characterIndex);
        }
Example #17
0
        static CGRect GetCharacterBounds(NSRange characterRange, NSLayoutManager layoutManager, NSTextContainer textContainer)
        {
            var glyphRange = new NSRange();

#if __MOBILE__
            layoutManager.CharacterRangeForGlyphRange(characterRange, ref glyphRange);
#else
#pragma warning disable CS0618 // Type or member is obsolete
            layoutManager.CharacterRangeForGlyphRange(characterRange, out glyphRange);
#pragma warning restore CS0618 // Type or member is obsolete
#endif
            return(layoutManager.BoundingRectForGlyphRange(glyphRange, textContainer));
        }
Example #18
0
 public CGSize GetSize()
 {
     using (var TextLayout = new NSLayoutManager())
     {
         TextLayout.AddTextContainer(TextContainer);
         TextStorage.AddLayoutManager(TextLayout);
         TextLayout.GlyphRangeForBoundingRect(new CGRect(CGPoint.Empty, TextContainer.Size), TextContainer);
         var s = TextLayout.GetUsedRectForTextContainer(TextContainer);
         TextStorage.RemoveLayoutManager(TextLayout);
         TextLayout.RemoveTextContainer(0);
         return(s.Size);
     }
 }
        public void GetGlyphsTest()
        {
            TestRuntime.AssertSystemVersion(ApplePlatform.iOS, 7, 0, throwIfOtherPlatform: false);

            using (var txt = new NSTextStorage()) {
                var str = "hello world\n\t";
                txt.SetString(new NSAttributedString(str));
                using (var lm = new NSLayoutManager()) {
                    lm.TextStorage = txt;
                    var glyphs          = new short[str.Length];
                    var props           = new NSGlyphProperty [glyphs.Length];
                    var charIndexBuffer = new nuint [glyphs.Length];
                    var bidiLevelBuffer = new byte [glyphs.Length];
                    lm.GetGlyphs(new NSRange(0, str.Length), glyphs, props, charIndexBuffer, bidiLevelBuffer);
                    Assert.That(glyphs, Is.EqualTo(new short [] { 75, 72, 79, 79, 82, 3, 90, 82, 85, 79, 71, -1, -1 }), "glyphs");
                    Assert.That(props, Is.EqualTo(new NSGlyphProperty [] {
                        0,
                        0,
                        0,
                        0,
                        0,
                        NSGlyphProperty.Elastic,
                        0,
                        0,
                        0,
                        0,
                        0,
                        NSGlyphProperty.ControlCharacter,
                        NSGlyphProperty.ControlCharacter
                    }), "props");
                    Assert.That(charIndexBuffer, Is.EqualTo(new nuint [] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }), "charIndexBuffer");
                    Assert.That(bidiLevelBuffer, Is.EqualTo(new byte [str.Length]), "bidiLevelBuffer");
                }
            }

            using (var txt = new NSTextStorage()) {
                var str = "hello world\n\t";
                txt.SetString(new NSAttributedString(str));
                using (var lm = new NSLayoutManager()) {
                    lm.TextStorage = txt;
                    var glyphs          = new short[str.Length];
                    var charIndexBuffer = new nuint [glyphs.Length];
                    var bidiLevelBuffer = new byte [glyphs.Length];
                    lm.GetGlyphs(new NSRange(0, str.Length), glyphs, null, charIndexBuffer, bidiLevelBuffer);
                    Assert.That(glyphs, Is.EqualTo(new short [] { 75, 72, 79, 79, 82, 3, 90, 82, 85, 79, 71, -1, -1 }), "glyphs");

                    Assert.That(charIndexBuffer, Is.EqualTo(new nuint [] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }), "charIndexBuffer");
                    Assert.That(bidiLevelBuffer, Is.EqualTo(new byte [str.Length]), "bidiLevelBuffer");
                }
            }
        }
Example #20
0
 public nuint GetIndexFromCoordinates(double x, double y)
 {
     using (var TextLayout = new NSLayoutManager())
     {
         TextLayout.AddTextContainer(TextContainer);
         TextStorage.AddLayoutManager(TextLayout);
         TextLayout.GlyphRangeForBoundingRect(new CGRect(CGPoint.Empty, TextContainer.Size), TextContainer);
         nfloat fraction = 0;
         var    index    = TextLayout.CharacterIndexForPoint(new CGPoint(x, y), TextContainer, ref fraction);
         TextStorage.RemoveLayoutManager(TextLayout);
         TextLayout.RemoveTextContainer(0);
         return(index);
     }
 }
Example #21
0
 public CGPoint GetCoordinateFromIndex(int index)
 {
     using (var TextLayout = new NSLayoutManager())
     {
         TextLayout.AddTextContainer(TextContainer);
         TextStorage.AddLayoutManager(TextLayout);
         TextLayout.GlyphRangeForBoundingRect(new CGRect(CGPoint.Empty, TextContainer.Size), TextContainer);
         var glyphIndex = TextLayout.GlyphIndexForCharacterAtIndex(index);
         var p          = TextLayout.LocationForGlyphAtIndex((nint)glyphIndex);
         TextStorage.RemoveLayoutManager(TextLayout);
         TextLayout.RemoveTextContainer(0);
         return(p);
     }
 }
Example #22
0
        NSRange LineRange(NSTextView textView)
        {
            NSLayoutManager layoutManager = textView.LayoutManager;

            var    charRane = new NSRange(0, 1);
            CGRect charRect = layoutManager.BoundingRectForGlyphRange(charRane, textView.TextContainer);

            var lRect = new CGRect(charRect.Left, charRect.Size.Height * 6, charRect.Size.Width, charRect.Size.Height);

            NSRange lRange  = layoutManager.GlyphRangeForBoundingRect(lRect, textView.TextContainer);
            var     nOrange = new NSRange(0, lRange.Location - 1);

            return(nOrange);
        }
 public void LowLevelGetAttributesOverrideTest()
 {
     using var storage   = new MyTextStorage("Hello World");
     using var container = new NSTextContainer {
               Size = new CGSize(100, float.MaxValue),
               WidthTracksTextView = true
           };
     using var layoutManager = new NSLayoutManager();
     layoutManager.AddTextContainer(container);
     storage.AddLayoutManager(layoutManager);
     layoutManager.EnsureLayoutForCharacterRange(new NSRange(0, 1));
     Assert.That(storage.LowLevelGetAttributes_Called, Is.GreaterThan(0), "LowLevelGetAttributes #called");
     Assert.That(storage.LowLevelValue_Called, Is.GreaterThan(0), "LowLevelValue #called");
 }
Example #24
0
        protected override void OnElementChanged(ElementChangedEventArgs <MyLabel> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
                if (Control == null)
                {
                    var uiLabel = new UILabel
                    {
                        UserInteractionEnabled = true,
                        LineBreakMode          = UILineBreakMode.WordWrap,
                        Lines = 0,
                        Text  = "عندما يريد العالم أن ‪يتكلّم ‬ ، فهو يتحدّث بلغة يونيكود. تسجّل الآن لحضور المؤتمر الدولي العاشر ليونيكود (Unicode Conference)، الذي سيعقد في 10-12 آذار 1997 بمدينة مَايِنْتْس، ألمانيا. و سيجمع المؤتمر بين خبراء من كافة قطاعات الصناعة على الشبكة العالمية انترنيت ويونيكود، حيث ستتم، على الصعيدين الدولي والمحلي على حد سواء مناقشة سبل استخدام يونكود في النظم القائمة وفيما يخص التطبيقات الحاسوبية، الخطوط، تصميم النصوص والحوسبة متعددة اللغات...TapMe"
                    };

                    var uiTapGestureRecognizer = new UITapGestureRecognizer();
                    uiTapGestureRecognizer.AddTarget(() =>
                    {
                        var label      = uiLabel;
                        var recognizer = uiTapGestureRecognizer;
                        var range      = new NSRange(uiLabel.Text.Length - "TapMe".Length, "TapMe".Length);

                        using (var ts = new NSTextStorage())
                        {
                            var lm = new NSLayoutManager();
                            var tc = new NSTextContainer(new CGSize(label.Frame.Width, double.MaxValue));

                            lm.AddTextContainer(tc);
                            ts.Append(label.AttributedText);
                            ts.AddLayoutManager(lm);

                            tc.LineFragmentPadding  = (float)0.0;
                            tc.LineBreakMode        = label.LineBreakMode;
                            tc.MaximumNumberOfLines = (uint)label.Lines;
                            tc.Size = label.Bounds.Size;

                            var index         = lm.GetCharacterIndex(recognizer.LocationOfTouch(0, label), tc);
                            var isWithinRange = (nint)index >= range.Location && (nint)index < range.Location + range.Length;

                            App.Current.MainPage.DisplayAlert("Alert", "Character count: " + label.Text.Length + "\nRange location: " + range.Location + "\nRange length:" + range.Length + "\nCharacter index: " + index + "\nIs within range: " + isWithinRange, "Dismiss");
                        }
                    });
                    uiLabel.AddGestureRecognizer(uiTapGestureRecognizer);

                    SetNativeControl(uiLabel);
                }
            }
        }
Example #25
0
        public void CreateManager()
        {
            // This sets up the global context so our drawing doesn't produce error messages
            NSBitmapImageRep bitmap = new NSBitmapImageRep(IntPtr.Zero, 1000, 1000, 16, 4, true, false, NSColorSpace.DeviceRGB, 0, 0);

            NSGraphicsContext.CurrentContext = NSGraphicsContext.FromBitmap(bitmap);

            NSTextStorage   storage   = new NSTextStorage("Hello World");
            NSTextContainer container = new NSTextContainer();

            manager = new NSLayoutManager();

            manager.AddTextContainer(container);
            storage.AddLayoutManager(manager);
        }
Example #26
0
        nfloat HeightWrappedToWidth(float width)
        {
            nfloat          height        = 0;
            NSTextStorage   storage       = new NSTextStorage();
            NSLayoutManager layoutManager = new NSLayoutManager();
            CGSize          size          = new CGSize(width, 100);
            NSTextContainer container     = new NSTextContainer(size);

            layoutManager.AddTextContainer(container);
            storage.AddLayoutManager(layoutManager);
            layoutManager.GetGlyphRange(container);              //force layout
            height = layoutManager.GetUsedRectForTextContainer(container).Height;

            return(height);
        }
Example #27
0
        uint LineNumber(NSTextView textView)
        {
            NSLayoutManager layoutManager = textView.LayoutManager;

            nint lineCharacterRange = layoutManager.NumberOfGlyphs;

            var    lineRange = new NSRange(0, lineCharacterRange);
            var    charRane  = new NSRange(0, 1);
            CGRect lineRect  = layoutManager.BoundingRectForGlyphRange(lineRange, textView.TextContainer);
            CGRect charRect  = layoutManager.BoundingRectForGlyphRange(charRane, textView.TextContainer);

            uint lineNum = (uint)(lineRect.Bottom / charRect.Bottom);

            return(lineNum);
        }
Example #28
0
 static FontExtensions()
 {
     storage = new NSTextStorage();
     layout  = new NSLayoutManager {
         UsesFontLeading = true
     };
                 #if OSX
     layout.BackgroundLayoutEnabled = false;
                 #endif
     container = new NSTextContainer {
         LineFragmentPadding = 0f
     };
     layout.UsesFontLeading = true;
     layout.AddTextContainer(container);
     storage.AddLayoutManager(layout);
 }
Example #29
0
            public void Draw(CGContext ctx, CGColor foregroundColor, double x, double y)
            {
                bool tempForegroundSet = false;

                // if no color attribute is set for the whole string,
                // NSLayoutManager will use the default control foreground color.
                // To override the default color we need to apply the current CGContext stroke color
                // before all other attributes are set, otherwise it will remove all other foreground colors.
                if (foregroundColor != null && !Attributes.Any(a => a is ColorTextAttribute && a.StartIndex == 0 && a.Count == Text.Length))
                {
                    // FIXME: we need to find a better way to accomplish this without the need to reset all attributes.
                    ResetAttributes(NSColor.FromCGColor(foregroundColor));
                    tempForegroundSet = true;
                }

                ctx.SaveState();
                NSGraphicsContext.GlobalSaveGraphicsState();
                var nsContext = NSGraphicsContext.FromCGContext(ctx, true);

                NSGraphicsContext.CurrentContext = nsContext;

                using (var TextLayout = new NSLayoutManager())
                {
                    TextLayout.AddTextContainer(TextContainer);
                    TextStorage.AddLayoutManager(TextLayout);

                    TextLayout.DrawBackgroundForGlyphRange(new NSRange(0, Text.Length), new CGPoint(x, y));
                    TextLayout.DrawGlyphsForGlyphRange(new NSRange(0, Text.Length), new CGPoint(x, y));
                    TextStorage.RemoveLayoutManager(TextLayout);
                    TextLayout.RemoveTextContainer(0);
                }

                // reset foreground color change
                if (tempForegroundSet)
                {
                    ResetAttributes();
                }

                NSGraphicsContext.GlobalRestoreGraphicsState();
                ctx.RestoreState();
            }
Example #30
0
        private CGSize textSize(string str, NSDictionary attributes)
        {
            // The three components
            var storage   = new NSTextStorage();
            var layout    = new NSLayoutManager();
            var container = new NSTextContainer();

            // Bind them
            layout.AddTextContainer(container);
            storage.AddLayoutManager(layout);

            storage.SetString(new NSAttributedString(str, attributes));

            // Compute
            layout.GetGlyphRange(container);

            // Get size
            CGSize size = layout.GetUsedRectForTextContainer(container).Size;

            return(size);
        }
Example #31
0
        private int GetCharacterIndexAtPoint(Point point)
        {
            if (!_drawRect.Contains(point))
            {
                return(-1);
            }

            // Configure textContainer
            var textContainer = new NSTextContainer();

            textContainer.LineFragmentPadding  = 0;
            textContainer.LineBreakMode        = LineBreakMode;
            textContainer.MaximumNumberOfLines = (nuint)Lines;
            textContainer.Size = _drawRect.Size;

            // Configure layoutManager
            var layoutManager = new NSLayoutManager();

            layoutManager.AddTextContainer(textContainer);

            // Configure textStorage
            var textStorage = new NSTextStorage();

            textStorage.SetString(AttributedText);
            textStorage.AddLayoutManager(layoutManager);
            textStorage.SetAttributes(
                new UIStringAttributes()
            {
                Font = Font
            },
                new NSRange(0, textStorage.Length)
                );

            // Find the tapped character's index
            var partialFraction      = (nfloat)0;
            var pointInTextContainer = new CGPoint(point.X - _drawRect.X, point.Y - _drawRect.Y);
            var characterIndex       = (int)layoutManager.CharacterIndexForPoint(pointInTextContainer, textContainer, ref partialFraction);

            return(characterIndex);
        }
Example #32
0
        private void UpdateTypography()
        {
            _attributedString = GetAttributedText();

            if (UseLayoutManager)
            {
                // Configure textContainer
                _textContainer = new NSTextContainer();
                _textContainer.LineFragmentPadding  = 0;
                _textContainer.LineBreakMode        = GetLineBreakMode();
                _textContainer.MaximumNumberOfLines = (nuint)GetLines();

                // Configure layoutManager
                _layoutManager = new NSLayoutManager();
                _layoutManager.AddTextContainer(_textContainer);

                // Configure textStorage
                _textStorage = new NSTextStorage();
                _textStorage.AddLayoutManager(_layoutManager);
                _textStorage.SetString(_attributedString);
            }
        }
Example #33
0
        public ApplyStyles(TextController controller, NSTextView text)
        {
            Contract.Requires(text.textStorage().layoutManagers().count() == 1, "expected one layout not " + text.textStorage().layoutManagers().count());

            m_controller = controller;
            m_storage = text.textStorage();
            m_layout = m_storage.layoutManagers().objectAtIndex(0).To<NSLayoutManager>();

            m_current = new CurrentStyles(controller, m_storage);

            Broadcaster.Register("tab stops changed", this);
            Broadcaster.Register("selected line color changed", this);
            Broadcaster.Register("computed style runs", this);
            Broadcaster.Register("text changed", this);

            if (ms_selectedLineColor == null)
                DoSetTempAttrs();

            DoResetTabStops();
            DoApplyParagraphStyles(true);

            ActiveObjects.Add(this);
        }
		private SCNNode NodeWithText (string message, TextType type, int level)
		{
			var textNode = SCNNode.Create ();

			// Bullet
			if (type == TextType.Bullet) {
				if (level == 0)
					message = "• " + message;
				else {
					var bullet = SCNNode.Create ();
					bullet.Geometry = SCNPlane.Create (10.0f, 10.0f);
					bullet.Geometry.FirstMaterial.Diffuse.Contents = NSColor.FromDeviceRgba ((float)(160 / 255.0), (float)(182 / 255.0), (float)(203 / 255.0), 1);
					bullet.Position = new SCNVector3 (80, 30, 0);
					bullet.Geometry.FirstMaterial.LightingModelName = SCNLightingModel.Constant;
					bullet.Geometry.FirstMaterial.WritesToDepthBuffer = false;
					bullet.RenderingOrder = 1;
					textNode.AddChildNode (bullet);
					message = "\t\t\t\t" + message;
				}
			}

			// Text attributes
			var extrusion = ExtrusionDepthForTextType (type);
			var text = SCNText.Create (message, extrusion);
			textNode.Geometry = text;
			text.Flatness = TEXT_FLATNESS;
			text.ChamferRadius = (extrusion == 0 ? 0 : TEXT_CHAMFER);
			text.Font = FontForTextType (type, level);

			// Layout
			var layoutManager = new NSLayoutManager ();
			var leading = layoutManager.DefaultLineHeightForFont (text.Font);
			var descender = text.Font.Descender;
			int newlineCount = ((string[])(((string)text.String.ToString ()).Split ('\n'))).Length;
			textNode.Pivot = SCNMatrix4.CreateTranslation (0, -descender + newlineCount * leading, 0);

			if (type == TextType.Chapter) {
				var min = new SCNVector3 ();
				var max = new SCNVector3 ();
				textNode.GetBoundingBox (ref min, ref max);
				textNode.Position = new SCNVector3 (-11, (-min.Y + textNode.Pivot.M42) * TEXT_SCALE, 7);
				textNode.Scale = new SCNVector3 (TEXT_SCALE, TEXT_SCALE, TEXT_SCALE);
				textNode.Rotation = new SCNVector4 (0, 1, 0, (float)(Math.PI / 270.0));
			} else {
				textNode.Position = new SCNVector3 (-16, CurrentBaseline, 0);
				textNode.Scale = new SCNVector3 (TEXT_SCALE, TEXT_SCALE, TEXT_SCALE);
			}

			// Material
			if (type == TextType.Chapter) {
				var frontMaterial = SCNMaterial.Create ();
				var sideMaterial = SCNMaterial.Create ();

				frontMaterial.Emission.Contents = NSColor.DarkGray;
				frontMaterial.Diffuse.Contents = ColorForTextType (type, level);
				sideMaterial.Diffuse.Contents = NSColor.LightGray;
				textNode.Geometry.Materials = new SCNMaterial[] {
					frontMaterial,
					frontMaterial,
					sideMaterial,
					frontMaterial,
					frontMaterial
				};
			} else {
				// Full white emissive material (visible even when there is no light)
				textNode.Geometry.FirstMaterial = SCNMaterial.Create ();
				textNode.Geometry.FirstMaterial.Diffuse.Contents = NSColor.Black;
				textNode.Geometry.FirstMaterial.Emission.Contents = ColorForTextType (type, level);

				// Don't write to the depth buffer because we don't want the text to be reflected
				textNode.Geometry.FirstMaterial.WritesToDepthBuffer = false;

				// Render last
				textNode.RenderingOrder = 1;
			}

			return textNode;
		}
Example #35
0
        // We can't restore the scoller until layout has completed (because the scroller
        // doesn't know how many lines there are until this happens).
        public void layoutManager_didCompleteLayoutForTextContainer_atEnd(NSLayoutManager layout, NSTextContainer container, bool atEnd)
        {
            if (!m_closed)
            {
                if (m_restorer != null && (m_applier.Applied || m_language == null))
                    if (m_restorer.OnCompletedLayout(layout, atEnd))
                        m_restorer = null;

                if (atEnd)
                {
                    Broadcaster.Invoke("layout completed", m_boss);
                    DoPruneRanges();
                }
            }
        }
Example #36
0
        public override void DrawRect(RectangleF dirtyRect)
        {
            var height = base.Bounds.Height;
            var calcValue = base.Bounds.Width * (Value * 0.01f);

            var context = NSGraphicsContext.CurrentContext.GraphicsPort;
            context.SetStrokeColor("#999999".ToCGColor());
            context.SetLineWidth (1.0F);

            context.StrokeRect(new RectangleF(0, 0, base.Bounds.Width, height));

            context.SetFillColor("#999999".ToCGColor());
            context.FillRect(new RectangleF(0, 0, base.Bounds.Width, height));

            context.SetFillColor(BackgroundColor.ToCGColor());
            context.FillRect(new RectangleF(0, 0, calcValue, height));

            var attrStr = "{0}".ToFormat(Label).CreateString("#ffffff".ToNSColor(), Font);

            var storage   = new NSTextStorage();
            storage.SetString(attrStr);

            var layout    = new NSLayoutManager();
            var container = new NSTextContainer();

            layout.AddTextContainer(container);
            storage.AddLayoutManager(layout);

            // Get size
            //			var size = layout.GetUsedRectForTextContainer (container).Size;
            //			var width = size.Width / 2.0f;
            var width = (base.Bounds.Width / 2.0f) - (TextOffset.X);

            storage.DrawString(new PointF(width, TextOffset.Y));
        }