Esempio n. 1
0
        /// <summary>
        /// Tests the string mapping.
        /// </summary>
        /// <param name="failures">The number of failures.</param>
        /// <param name="successes">The number of successes.</param>
        /// <param name="expected">The expected output mapped string.</param>
        /// <param name="input">The input string.</param>
        /// <param name="options">The options.</param>
        private static void TestMap(
            ref int failures,
            ref int successes,
            string expected,
            string input,
            TextOptions options)
        {
            Trace.WriteLine(new string('=', 80));

            Assert.IsNotNull(input);
            Assert.IsNotNull(expected);
            // Generate map
            StringMap map = input.ToMapped(options);
            string output = map.Mapped;
            Trace.WriteLine($"Options:'{options}' String:'{input.Escape()}' Map: '{output.Escape()}'");

            bool failed = false;
            if (!string.Equals(expected, output, StringComparison.Ordinal))
            {
                Trace.WriteLine($"FAILED - Expected a mapped string of '{expected.Escape()}'");
                failed = true;
            }
            else
                for (int i = 0; i < map.Count; i++)
                {
                    char o = output[i];
                    int j = map.GetOriginalIndex(i);
                    if (j < 0 || j >= input.Length)
                    {
                        Trace.WriteLine(
                            $"FAILED - Mapped character '{o.ToString().Escape()}' at index '{i}' has invalid mapping to index '{j}'.");
                        failed = true;
                        continue;
                    }
                    char m = input[j];
                    if (o != m)
                    {
                        Trace.WriteLine(
                            $"FAILED - Expected mapped character '{o.ToString().Escape()}' at index '{i}' to equal '{m.ToString().Escape()}' at index '{j}'.");
                        failed = true;
                    }
                }

            Trace.WriteLine(string.Empty);

            if (failed) failures++;
            else successes++;
        }
        // <summary>
        // HandleHeadings
        // Function that handles Heading Options for the text
        // </summary>
        // \param headingOption(TextOptions)
        // \return void
        public void HandleHeadings(TextOptions headingOption)
        {
            string headingType = "";
            // find the appropiate header
            switch(headingOption)
            {
                case TextOptions.Heading1:
                    headingType = "#";
                    break;
                case TextOptions.Heading2:
                    headingType = "##";
                    break;
                case TextOptions.Heading3:
                    headingType = "###";
                    break;
            }

            // check if the user wants to add the header to an existing text
            // this.SelectedText.Length > 0: true  -- adding to an existing(selected) text
            //                               false -- no text is selected
            if (this.SelectedText.Length > 0)
            {
                TextOptions headingFound = new TextOptions();

                // clean the current headers from the existing text
                string selectedText = CleanHeaders(this.SelectedText,ref headingFound);
                string newText = "";

                // check if the user wants to remove the header or replace it
                if(headingFound == headingOption)
                {
                    newText = selectedText;
                }
                else
                {
                    newText = headingType + selectedText;
                }

                // replace the text with the appropiate option
                this.SelectedText = this.SelectedText.Replace(this.SelectedText, newText);
            }
            else
            {
                //simply add the apropiate header option
                this.SelectedText = headingType;
            }
        }
Esempio n. 3
0
        public override void Render(Node node, Context context)
        {
            LabelNode label = node as LabelNode;
            Cairo.Engine engine = node.Canvas.Engine as Cairo.Engine;

            var options = new TextOptions ();
            options.Color = label.Color.MultiplyAlpha (node.Opacity);
            options.MaxWidth = label.Width;

            var size = GetExtents (label.Text, options, engine);

            double x = label.Width - size.Width;
            x = (int) (x * label.XAlign);

            double y = label.Height - size.Height;
            y = (int) (y * label.YAlign);

            engine.RenderText (context, label.Text, options, new Point (x, y));
        }
Esempio n. 4
0
        public ChildWindow(UserControl content = null)
        {
            TextOptions.SetTextRenderingMode(this, TextRenderingMode.Auto);
            TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);

            this.SnapsToDevicePixels = true;
            this.UseLayoutRounding   = true;
            this.ShowInTaskbar       = false;
            this.Width  = double.NaN;
            this.Height = double.NaN;
            this.VerticalContentAlignment   = VerticalAlignment.Stretch;
            this.HorizontalContentAlignment = HorizontalAlignment.Stretch;
            this.ShowInTaskbar         = false;
            this.SizeToContent         = SizeToContent.WidthAndHeight;
            this.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            this.MinHeight             = 150;
            this.MinWidth   = 150;
            this.Content    = content;
            this.Activated += ChildWindow_Activated;
        }
        public void TestExtractFormattedPage()
        {
            var testFile = TestFiles.FormattedDocument;
            var options  = new TextOptions
            {
                FileInfo             = testFile.ToFileInfo(),
                FormattedTextOptions = new FormattedTextOptions
                {
                    Mode = "Markdown"
                },
                StartPageNumber     = 1,
                CountPagesToExtract = 1
            };
            var request = new TextRequest(options);
            var result  = ParseApi.Text(request);

            Assert.IsNotEmpty(result.Pages);
            Assert.IsTrue(result.Pages[0].Text.Contains("**Second page bold text**"));
            Assert.IsTrue(result.Pages[0].Text.Contains("# Second page heading"));
        }
		/// <summary>
		/// Creates a <see cref="TextFormatter"/> using the formatting mode used by the specified owner object.
		/// </summary>
		public static TextFormatter Create(DependencyObject owner)
		{
			if (owner == null)
				throw new ArgumentNullException("owner");

			return TextFormatter.Create(TextOptions.GetTextFormattingMode(owner));
			#else
			if (TextFormattingModeProperty != null) {
				object formattingMode = owner.GetValue(TextFormattingModeProperty);
				return (TextFormatter)typeof(TextFormatter).InvokeMember(
					"Create",
					BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
					null, null,
					new object[] { formattingMode },
					CultureInfo.InvariantCulture);
			} else {
				return TextFormatter.Create();
			}

		}
Esempio n. 7
0
        public void TextBuilder_Bounds_AreCorrect()
        {
            Vector2 position = new(5, 5);
            var     options  = new TextOptions(TestFontUtilities.GetFont(TestFonts.OpenSans, 16))
            {
                Origin = position
            };

            string text = "Hello World";

            IPathCollection glyphs = TextBuilder.GenerateGlyphs(text, options);

            RectangleF    builderBounds  = glyphs.Bounds;
            FontRectangle measuredBounds = TextMeasurer.MeasureBounds(text, options);

            Assert.Equal(measuredBounds.X, builderBounds.X);
            Assert.Equal(measuredBounds.Y, builderBounds.Y);
            Assert.Equal(measuredBounds.Width, builderBounds.Width);
            Assert.Equal(measuredBounds.Height, builderBounds.Height);
        }
Esempio n. 8
0
 public BaseImageOperationsExtensionTest()
 {
     this.options = new GraphicsOptions {
         Antialias = false
     };
     this.textOptions = new TextOptions
     {
         TabWidth = 99
     };
     this.shapeOptions = new ShapeOptions {
         IntersectionRule = IntersectionRule.Nonzero
     };
     this.source             = new Image <Rgba32>(91 + 324, 123 + 56);
     this.rect               = new Rectangle(91, 123, 324, 56); // make this random?
     this.internalOperations = new FakeImageOperationsProvider.FakeImageOperations <Rgba32>(this.source.GetConfiguration(), this.source, false);
     this.internalOperations.SetShapeOptions(this.shapeOptions);
     this.internalOperations.SetTextOptions(this.textOptions);
     this.internalOperations.SetGraphicsOptions(this.options);
     this.operations = this.internalOperations;
 }
Esempio n. 9
0
    public static IText Create(
        string text,
        Point position,
        TextOptions options,
        IJSInProcessRuntime jsRuntime)
    {
        var textKey = Guid.NewGuid().ToString();

        jsRuntime.InvokeVoid(
            PhaserConstants.Functions.AddText,
            textKey,
            position,
            text,
            options);

        return(new PhaserText(
                   textKey,
                   position,
                   jsRuntime));
    }
Esempio n. 10
0
        public TimeStampMargin(IWpfTextView textView, TimeStampMarginProvider timeStampMarginProvider)
        {
            _textView = textView;

            _formatMap = timeStampMarginProvider.ClassificationFormatMappingService
                         .GetClassificationFormatMap(_textView);

            _timestampClassification = timeStampMarginProvider.ClassificationTypeRegistryService
                                       .GetClassificationType(ClassificationTypeDefinitions.TimeStamp);

            ClipToBounds     = true;
            IsHitTestVisible = false;
            Children.Add(_translatedCanvas);
            TextOptions.SetTextHintingMode(this, TextHintingMode.Fixed);

            IsVisibleChanged             += OnVisibleChanged;
            _textView.TextBuffer.Changed += TextBufferOnChanged;
            Settings.SettingsUpdated     += OnSettingsOnSettingsUpdated;
            UpdateFormatMap();
        }
Esempio n. 11
0
        private static void SetListBoxStyle([NotNull] ListBox listBox, [CanBeNull] IDocument document)
        {
            if (!(listBox.GetValue(_originalStylesProperty) is OriginalStyles))
            {
                listBox.SetValue(_originalStylesProperty, new OriginalStyles {
                    Style = listBox.Style,
                    ItemContainerStyle = listBox.ItemContainerStyle,
                    ItemTemplate       = listBox.ItemTemplate
                });
            }

            IContextBoundSettingsStore settings = document.TryGetSettings();

            listBox.Style              = UIResources.Instance.QuickInfoListBoxStyle;
            listBox.ItemTemplate       = UIResources.Instance.QuickInfoItemDataTemplate;
            listBox.ItemContainerStyle = CreateItemContainerStyle(settings);
            listBox.MaxWidth           = ComputeListBoxMaxWidth(listBox, settings);
            TextOptions.SetTextFormattingMode(listBox, GetTextFormattingMode(settings));
            TextOptions.SetTextRenderingMode(listBox, TextRenderingMode.Auto);
        }
Esempio n. 12
0
        private static void SaveImage(
            TextOptions options,
            string text,
            int width,
            int height,
            params string[] path)
        {
            string fullPath = CreatePath(path);

            using var img = new Image <Rgba32>(width, height);
            img.Mutate(x => x.Fill(Color.Black));

            img.Mutate(x => x.DrawText(options, text, Color.White));

            // Ensure directory exists
            Directory.CreateDirectory(IOPath.GetDirectoryName(fullPath));

            using FileStream fs = File.Create(fullPath);
            img.SaveAsPng(fs);
        }
Esempio n. 13
0
        public ContextActionsBulbPopup(UIElement parent) : base(parent)
        {
            UseLayoutRounding = true;
            TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);

            StaysOpen          = true;
            AllowsTransparency = true;
            _mainItem          = new MenuItem
            {
                ItemContainerStyle = CreateItemContainerStyle(),
                Header             = new Image
                {
                    Source = TryFindResource("Bulb") as ImageSource,
                    Width  = 16,
                    Height = 16
                }
            };
            _mainItem.SubmenuOpened += (sender, args) =>
            {
                if (ReferenceEquals(args.OriginalSource, _mainItem))
                {
                    MenuOpened?.Invoke(this, EventArgs.Empty);
                }
            };
            _mainItem.SubmenuClosed += (sender, args) =>
            {
                if (ReferenceEquals(args.OriginalSource, _mainItem))
                {
                    MenuClosed?.Invoke(this, EventArgs.Empty);
                }
            };
            var menu = new Menu
            {
                Background      = Brushes.Transparent,
                BorderBrush     = _mainItem.BorderBrush,
                BorderThickness = _mainItem.BorderThickness,
                Items           = { _mainItem }
            };

            Child = menu;
        }
Esempio n. 14
0
        public static TextBox SuperGridTitle()
        {
            var label = new TextBox();

            label.FontFamily        = Fonts.OpenSans;
            label.FontSize          = Fonts.Size.SuperGridHeader;
            label.Foreground        = EasyColour.BrushFromHex("#34282C");
            label.Text              = "Table Header";
            label.VerticalAlignment = VerticalAlignment.Center;
            label.Background        = null;
            label.BorderBrush       = null;
            label.Padding           = new Thickness(5, 0, 0, 0);
            label.BorderThickness   = new Thickness(0, 0, 0, 0);

            RenderOptions.SetBitmapScalingMode(label, BitmapScalingMode.NearestNeighbor);
            TextOptions.SetTextFormattingMode(label, TextFormattingMode.Display);
            Setter effectSetter = new Setter();

            effectSetter.Property = ScrollViewer.EffectProperty;
            effectSetter.Value    = new DropShadowEffect
            {
                ShadowDepth = 1,
                Direction   = 270,
                Color       = Colors.White,
                Opacity     = 1,
                BlurRadius  = 0.0
            };
            Style dropShadowScrollViewerStyle = new Style(typeof(ScrollViewer));

            dropShadowScrollViewerStyle.Setters.Add(effectSetter);

            label.Resources.Add(typeof(ScrollViewer), dropShadowScrollViewerStyle);

            label.IsReadOnly        = true;
            label.MouseDoubleClick += clix;
            label.KeyUp            += StopEditingTextBox;
            label.LostFocus        += TextBoxLostFocus;


            return(label);
        }
Esempio n. 15
0
        public override void BeginInit()
        {
            base.BeginInit();

            base.Document.UndoStack.SizeLimit = 1600;

            this.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C++");
            this.ShowLineNumbers    = true;
            this.FontFamily         = new FontFamily("Consolas");
            this.FontSize           = 13.3; // 10pt
            TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);

            this.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(this.Options);
            foldingManager  = FoldingManager.Install(this.TextArea);
            foldingStrategy = new BraceFoldingStrategy();
            foldingStrategy.UpdateFoldings(foldingManager, this.Document);

            // var search = new SearchInputHandler(this.TextArea);
            //this.TextArea.DefaultInputHandler.NestedInputHandlers.Add(search);
            SearchPanel.Install(this.TextArea);
        }
        public RelativeNumber(IWpfTextView textView, IEditorFormatMap formatMap, IWpfTextViewMargin containerMargin, IOutliningManager outliningManager)
        {
            this.textView         = textView;
            this.formatMap        = formatMap;
            this.containerMargin  = containerMargin;
            this.outliningManager = outliningManager;

            this.ClipToBounds = true;
            TextOptions.SetTextFormattingMode(this, TextFormattingMode.Ideal);
            TextOptions.SetTextRenderingMode(this, TextRenderingMode.ClearType);

            textView.Caret.PositionChanged += OnCaretPositionChanged;
            textView.Options.OptionChanged += OnOptionChanged;
            textView.LayoutChanged         += OnLayoutChanged;
            textView.ViewportHeightChanged += (sender, args) => ApplyNumbers();
            formatMap.FormatMappingChanged += (sender, args) => ApplyNumbers();
            textView.ViewportWidthChanged  += OnViewportWidthChanged;
            textView.GotAggregateFocus     += GotFocusHandler;
            textView.LostAggregateFocus    += LostFocusHandler;
            HideVSLineNumbers();
        }
Esempio n. 17
0
        protected override Size MeasureOverride(Size availableSize)
        {
            // always call the base class, it creates the typeface and enSize
            var size = base.MeasureOverride(availableSize);

            if (LineNumbers.Count > 0)
            {
                double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;
                int    digits       = (int)Math.Floor(Math.Log10(LineNumbers.Max()) + 1);

                FormattedText text = new FormattedText(
                    new string('9', digits), CultureInfo.CurrentCulture, TextView.FlowDirection,
                    typeface, emSize, Brushes.Black, null,
                    TextOptions.GetTextFormattingMode(this), pixelsPerDip);
                return(new Size(text.Width, 0));
            }
            else
            {
                return(size);
            }
        }
        public void CloneIsDeep()
        {
            var         expected = new TextOptions();
            TextOptions actual   = expected.DeepClone();

            actual.ApplyKerning        = false;
            actual.DpiX                = 46F;
            actual.DpiY                = 52F;
            actual.HorizontalAlignment = HorizontalAlignment.Center;
            actual.TabWidth            = 3F;
            actual.VerticalAlignment   = VerticalAlignment.Bottom;
            actual.WrapTextWidth       = 42F;

            Assert.NotEqual(expected.ApplyKerning, actual.ApplyKerning);
            Assert.NotEqual(expected.DpiX, actual.DpiX);
            Assert.NotEqual(expected.DpiY, actual.DpiY);
            Assert.NotEqual(expected.HorizontalAlignment, actual.HorizontalAlignment);
            Assert.NotEqual(expected.TabWidth, actual.TabWidth);
            Assert.NotEqual(expected.VerticalAlignment, actual.VerticalAlignment);
            Assert.NotEqual(expected.WrapTextWidth, actual.WrapTextWidth);
        }
Esempio n. 19
0
        public void ConstructorTest_FontOnly_WithFallbackFonts()
        {
            Font font = FakeFont.CreateFont("ABC");

            FontFamily[] fontFamilies = new[]
            {
                FakeFont.CreateFont("DEF").Family,
                FakeFont.CreateFont("GHI").Family
            };

            var options = new TextOptions(font)
            {
                FallbackFontFamilies = fontFamilies
            };

            Assert.Equal(72, options.Dpi);
            Assert.Equal(fontFamilies, options.FallbackFontFamilies);
            Assert.Equal(font, options.Font);
            Assert.Equal(Vector2.Zero, options.Origin);
            VerifyPropertyDefault(options);
        }
        public void UpdateDefaultOptionsOnConfiguration_AlwaysNewInstance()
        {
            var option = new TextOptions()
            {
                TabWidth = 99
            };
            var config = new Configuration();

            config.SetTextOptions(option);

            config.SetTextOptions(o =>
            {
                Assert.Equal(99, o.TabWidth); // has origional values
                o.TabWidth = 9;
            });

            TextOptions returnedOption = config.GetTextOptions();

            Assert.Equal(9, returnedOption.TabWidth);
            Assert.Equal(99, option.TabWidth); // hasn't been mutated
        }
Esempio n. 21
0
        public void AssertString(string expected, string actual, string message = null, TextOptions options = TextOptions.None, StringComparer comparer = null)
        {
            StringBuilder builder = new StringBuilder();
            if (expected == null)
            {
                if (actual != null)
                    builder.AppendLine($"Expected null, got <{actual.Escape()}>");
            }
            else if (actual == null)
                builder.AppendLine($"Expected <{expected.Escape()}>, got null");
            else
            {
                StringDifferences differences = expected.Diff(
                    actual,
                    options,
                    comparer ?? StringComparer.CurrentCultureIgnoreCase);
                if (!differences.AreEqual)
                {
                    builder.AppendLine($"Expected <{expected}>, got <{actual}>");

                    foreach (StringChunk difference in differences.Where(c => !c.AreEqual))
                    {
                        if (difference.A != null)
                        builder.AppendLine(
                            difference.B != null
                                ? $"Expected '{difference.A.Escape()}' at Offset '{difference.OffsetA}' - got '{difference.B.Escape()}' at Offset '{difference.OffsetB}'"
                                : $"The string '{difference.A.Escape()}' at Offset '{difference.OffsetA}' was expected.");
                        else
                            builder.AppendLine($"The string '{difference.B.Escape()}' at Offset '{difference.OffsetB}' was unexpected.");
                    }
                }
            }

            if (builder.Length < 1) return;

            if (message != null)
                builder.AppendLine(message);

            Assert.Fail(builder.ToString());
        }
Esempio n. 22
0
        public TickPanel()
        {
            this.InitializeComponent();
            this.InitializeLeadersBrushes();
            this.m_LevelPen   = new Pen(this.m_LevelBrush, 0.75);
            this.m_EllipsePen = new Pen(Brushes.Gray, 1.0);
            //this.StringHeight = 13;
            if (this.m_TypeFace == null)
            {
                this.m_TypeFace = new Typeface(this.m_TxtFontFam, FontStyles.Normal, FontWeights.SemiBold, new FontStretch());
            }
            //KAA 2016-06-01
            this.m_TxtSign = new FormattedText("!", this.m_CultureInfo, FlowDirection.LeftToRight, this.m_TypeFace,
                                               /*this.m_dTxtFontSize*/ this.FontSize * 1.25, Brushes.Black);
            this.m_Timer_Ticks          = new Timer(100.0);//KAA was 45
            this.m_Timer_Ticks.Elapsed += new ElapsedEventHandler(this.m_TicksTimer_Elapsed);
            this.m_Timer_Ticks.Start();
            this.m_Timer_Leaders          = new Timer(250.0);
            this.m_Timer_Leaders.Elapsed += new ElapsedEventHandler(this.m_LeadersTimer_Elapsed);
            this.m_Timer_Leaders.Start();
            this.m_Timer_Levels          = new Timer(60.0);
            this.m_Timer_Levels.Elapsed += new ElapsedEventHandler(this.m_LevelsTimer_Elapsed);
            this.m_Timer_Levels.Start();
            RenderOptions.SetEdgeMode(this.TickPanel_TicksImage, EdgeMode.Aliased);
            RenderOptions.SetBitmapScalingMode(this.TickPanel_TicksImage, BitmapScalingMode.NearestNeighbor);
            TextOptions.SetTextRenderingMode(this.TickPanel_TicksImage, TextRenderingMode.ClearType);
            TextOptions.SetTextFormattingMode(this.TickPanel_TicksImage, TextFormattingMode.Display);



            WorkAmountGrid = new ControlWorkAmount();

            Canvas.SetBottom(WorkAmountGrid, 20);
            Canvas.SetLeft(WorkAmountGrid, 1);
            //   Canvas.SetZIndex(WorkAmountGrid, Int32.MaxValue);


            TickPanel_Canvas.Children.Add(WorkAmountGrid);
        }
        public void TestExtractFormatted()
        {
            var testFile = TestFiles.FormattedDocument;
            var options  = new TextOptions
            {
                FileInfo             = testFile.ToFileInfo(),
                FormattedTextOptions = new FormattedTextOptions
                {
                    Mode = "Html"
                }
            };
            var request = new TextRequest(options);
            var result  = ParseApi.Text(request);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Text.Contains("<b>Bold text</b>"));
            Assert.IsTrue(result.Text.Contains("<i>Italic text</i>"));
            Assert.IsTrue(result.Text.Contains("<h1>Heading 1</h1>"));
            Assert.IsTrue(result.Text.Contains("<tr><td><p>table</p></td>"));
            Assert.IsTrue(result.Text.Contains("<ol><li><i>First element</i>"));
            Assert.IsTrue(result.Text.Contains("<a href=\"http://targetwebsite.domain\">Hyperlink </a>"));
        }
Esempio n. 24
0
        /// <summary>
        /// ウィンドウオプションを指定して SitrineWindow クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="options">ウィンドウオプション。</param>
        public SitrineWindow(WindowOptions options)
            : base(options.WindowSize.Width, options.WindowSize.Height, GraphicsMode.Default, options.Title)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            this.music       = new MusicPlayer(new MusicOptions());
            this.textures    = new TextureList();
            this.TargetSize  = options.TargetSize;
            this.textOptions = options.TextOptions;

            this.stories         = new List <Storyboard>();
            this.renderStories   = new List <RenderStoryboard>();
            this.reservedStories = new List <Storyboard>();
            this.removingStories = new List <Storyboard>();

            this.debugText = new DebugText(options.DebugTextOptions, this);
            Trace.Listeners.Add(new DebugTextListener(this.debugText));
            Trace.WriteLine("Window", "Init");
        }
Esempio n. 25
0
        private static UIElement WrapInHeading(UIElement child, string heading)
        {
            if (string.IsNullOrEmpty(heading))
            {
                return(child);
            }
            DockPanel panel2 = new DockPanel {
                Margin = new Thickness(0.0, 1.0, 3.0, 1.0)
            };
            TextBlock element = new TextBlock {
                Text       = heading,
                Padding    = new Thickness(4.0, 0.0, 4.0, 1.0),
                Margin     = new Thickness(0.0, 0.0, 3.0, 0.0),
                Background = new SolidColorBrush(Color.FromRgb(0xdd, 0xee, 0xff))
            };

            TextOptions.SetTextFormattingMode(element, TextFormattingMode.Display);
            element.SetValue(DockPanel.DockProperty, Dock.Left);
            panel2.Children.Add(element);
            panel2.Children.Add(child);
            return(panel2);
        }
        public void TestText_WithPassword()
        {
            var testFile = TestFiles.PasswordProtected;
            var options  = new TextOptions
            {
                FileInfo             = testFile.ToFileInfo(),
                StartPageNumber      = 0,
                CountPagesToExtract  = 1,
                FormattedTextOptions = new FormattedTextOptions
                {
                    Mode = "PlainText"
                }
            };

            var request = new TextRequest(options);
            var result  = ParseApi.Text(request);

            Assert.IsNull(result.Text);
            Assert.AreEqual(
                "Text inside a bookmark 1\r\n\r\nPage 1 heading!\r\n\r\nSample test text - Page 1!\r\n\r\n\fText inside a bookmark 2\r\n\r\n",
                result.Pages[0].Text);
        }
        public void UpdateDefaultOptionsOnProcessingContext_AlwaysNewInstance()
        {
            var option = new TextOptions()
            {
                TabWidth = 99
            };
            var config  = new Configuration();
            var context = new FakeImageOperationsProvider.FakeImageOperations <Rgba32>(config, null, true);

            context.SetTextOptions(option);

            context.SetTextOptions(o =>
            {
                Assert.Equal(99, o.TabWidth); // has origional values
                o.TabWidth = 9;
            });

            TextOptions returnedOption = context.GetTextOptions();

            Assert.Equal(9, returnedOption.TabWidth);
            Assert.Equal(99, option.TabWidth); // hasn't been mutated
        }
Esempio n. 28
0
        /// <summary>
        /// Measures the size of the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="fontFamily">The font family.</param>
        /// <param name="fontSize">Size of the font (in device independent units, 1/96 inch).</param>
        /// <param name="fontWeight">The font weight.</param>
        /// <returns>
        /// The size of the text (in device independent units, 1/96 inch).
        /// </returns>
        public OxySize MeasureText(string text, string fontFamily, double fontSize, double fontWeight)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(OxySize.Empty);
            }

            if (this.TextMeasurementMethod == TextMeasurementMethod.GlyphTypeface)
            {
                return(this.MeasureTextByGlyphTypeface(text, fontFamily, fontSize, fontWeight));
            }

            var tb = new TextBlock {
                Text = text
            };

#if !NET35
            TextOptions.SetTextFormattingMode(tb, this.TextFormattingMode);
#endif

            if (fontFamily != null)
            {
                tb.FontFamily = new FontFamily(fontFamily);
            }

            if (fontSize > 0)
            {
                tb.FontSize = fontSize;
            }

            if (fontWeight > 0)
            {
                tb.FontWeight = GetFontWeight(fontWeight);
            }

            tb.Measure(new Size(1000, 1000));

            return(new OxySize(tb.DesiredSize.Width, tb.DesiredSize.Height));
        }
        public IndexWriterTests()
        {
            using (var builder = new SchemaBuilder())
            {
                using (var primaryKeyOptions = new IntOptions().Stored().Fast(Cardinality.SingleValue).Indexed())
                {
                    Id = builder.AddI64Field(nameof(Id), primaryKeyOptions);
                }

                using (var textFieldOptions = new TextFieldIndexing {
                    Tokenizer = DefaultTokenizers.EnglishStemming
                })
                    using (var textOptions = new TextOptions {
                        IndexingOptions = textFieldOptions
                    })
                    {
                        Text = builder.AddTextField(nameof(Text), textOptions);
                    }

                Index = Index.CreateInRam(builder.Build());
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Given a SixLabours ImageSharp image context, applies a watermark text overlay
        /// to the bottom right corner in the given font and colour.
        /// </summary>
        /// <param name="processingContext"></param>
        /// <param name="font"></param>
        /// <param name="text"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        private static IImageProcessingContext ApplyWaterMark(IImageProcessingContext processingContext,
                                                              Font font, string text, Color color)
        {
            Size imgSize = processingContext.GetCurrentSize();

            // measure the text size
            FontRectangle size = TextMeasurer.Measure(text, new TextOptions(font));

            int ratio = 4; // Landscape, we make the text 25% of the width

            if (imgSize.Width >= imgSize.Height)
            {
                // Landscape - make it 1/6 of the width
                ratio = 6;
            }

            float quarter = imgSize.Width / ratio;

            // We want the text width to be 25% of the width of the image
            float scalingFactor = quarter / size.Width;

            // create a new font
            Font scaledFont = new Font(font, scalingFactor * font.Size);

            // 5% padding from the edge
            float fivePercent = quarter / 20;

            // 5% from the bottom right.
            var position = new PointF(imgSize.Width - fivePercent, imgSize.Height - fivePercent);

            TextOptions textOptions = new TextOptions(scaledFont)
            {
                VerticalAlignment   = VerticalAlignment.Bottom,
                HorizontalAlignment = HorizontalAlignment.Right,
            };

            return(processingContext.DrawText(textOptions, text, color));
        }
Esempio n. 31
0
        protected override void OnRender(DrawingContext drawingContext)
        {
            if (LineNumbers.Count > 0)
            {
                TextView textView   = TextView;
                Size     renderSize = RenderSize;
                if (textView != null && textView.VisualLinesValid)
                {
                    var    foreground   = (Brush)GetValue(Control.ForegroundProperty);
                    double pixelsPerDip = VisualTreeHelper.GetDpi(this).PixelsPerDip;

                    foreach (VisualLine line in textView.VisualLines)
                    {
                        int lineIndex = line.FirstDocumentLine.LineNumber - 1;

                        if (lineIndex >= 0 && lineIndex < LineNumbers.Count)
                        {
                            FormattedText text = new FormattedText(
                                LineNumbers[lineIndex].ToString(),
                                CultureInfo.CurrentCulture,
                                FlowDirection.LeftToRight,
                                typeface,
                                emSize,
                                foreground,
                                null,
                                TextOptions.GetTextFormattingMode(this),
                                pixelsPerDip);
                            double y = line.GetTextLineVisualYPosition(line.TextLines[0], VisualYPosition.TextTop);
                            drawingContext.DrawText(text, new Point(renderSize.Width - text.Width, y - textView.VerticalOffset));
                        }
                    }
                }
            }
            else
            {
                base.OnRender(drawingContext);
            }
        }
Esempio n. 32
0
        public override void LayoutOutline(Node node, Context context)
        {
            LabelNode label = node as LabelNode;
            Cairo.Engine engine = node.Canvas.Engine as Cairo.Engine;

            if (label.ClipInputToTextExtents) {
                var options = new TextOptions ();
                options.Color = label.Color.MultiplyAlpha (node.Opacity);
                options.MaxWidth = label.Width;

                var size = GetExtents (label.Text, options, engine);

                double x = label.Width - size.Width;
                x = (int) (x * label.XAlign);

                double y = label.Height - size.Height;
                y = (int) (y * label.YAlign);

                context.Rectangle (x, y, size.Width, size.Height);
            } else {
                context.Rectangle (0, 0, label.Width, label.Height);
            }
        }
        public void NonDefaultClone()
        {
            var expected = new TextOptions
            {
                ApplyKerning        = false,
                DpiX                = 46F,
                DpiY                = 52F,
                HorizontalAlignment = HorizontalAlignment.Center,
                TabWidth            = 3F,
                VerticalAlignment   = VerticalAlignment.Bottom,
                WrapTextWidth       = 42F
            };

            TextOptions actual = expected.DeepClone();

            Assert.Equal(expected.ApplyKerning, actual.ApplyKerning);
            Assert.Equal(expected.DpiX, actual.DpiX);
            Assert.Equal(expected.DpiY, actual.DpiY);
            Assert.Equal(expected.HorizontalAlignment, actual.HorizontalAlignment);
            Assert.Equal(expected.TabWidth, actual.TabWidth);
            Assert.Equal(expected.VerticalAlignment, actual.VerticalAlignment);
            Assert.Equal(expected.WrapTextWidth, actual.WrapTextWidth);
        }
Esempio n. 34
0
            public FlowDocumentTooltip(FlowDocument document)
            {
                TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);
                double fontSize = DisplaySettingsPanel.CurrentDisplaySettings.SelectedFontSize;

                viewer = new FlowDocumentScrollViewer()
                {
                    Width    = document.MinPageWidth + fontSize * 5,
                    MaxWidth = MainWindow.Instance.ActualWidth
                };
                viewer.Document = document;
                Border border = new Border {
                    Background      = SystemColors.ControlBrush,
                    BorderBrush     = SystemColors.ControlDarkBrush,
                    BorderThickness = new Thickness(1),
                    MaxHeight       = 400,
                    Child           = viewer
                };

                this.Child        = border;
                viewer.Foreground = SystemColors.InfoTextBrush;
                document.FontSize = fontSize;
            }
Esempio n. 35
0
        public override void Render(Node node, Context context)
        {
            LabelNode label = node as LabelNode;

            Cairo.Engine engine = node.Canvas.Engine as Cairo.Engine;

            var options = new TextOptions();

            options.Color    = label.Color.MultiplyAlpha(node.Opacity);
            options.MaxWidth = label.Width;

            var size = GetExtents(label.Text, options, engine);

            double x = label.Width - size.Width;

            x = (int)(x * label.XAlign);

            double y = label.Height - size.Height;

            y = (int)(y * label.YAlign);

            engine.RenderText(context, label.Text, options, new Point(x, y));
        }
Esempio n. 36
0
 public Size TextExtents(string text, TextOptions options)
 {
     TextView view = new TextView (Context);
     view.Text = text;
     view.Measure (0, 0);
     return new Size (view.MeasuredWidth, view.MeasuredHeight);
 }
Esempio n. 37
0
 public Size TextExtents(string text, TextOptions options)
 {
     return new Size ();
 }
 // <summary>
 // HandleBoldAndItalic
 // Function that handles Bold and Italic Options for the text
 // </summary>
 // \param textOption(TextOptions)
 // \return void
 public void HandleBoldAndItalic(TextOptions textOption)
 {
     // switch to the chosen option
     switch(textOption)
     {
         case TextOptions.Bold:
             HandleBold();
             break;
         case TextOptions.Italic:
             HandleItalic();
             break;
     }
 }
         // <summary>
         // CleanHeaders
         // Function that removes all existing headers from text
         // </summary>
         // \param currentString: the string that needs to be cleanead
         // \param headingFound: the heading that will be found during cleaning
         // \return string : selected text without heading format
        private string CleanHeaders(string currentString, ref TextOptions headingFound)
        {
            //counts how many "#" are removed to determine the heading type
            int numberRemovals = 0;

            // while there are headings in the selected text remove them
            while (currentString.Substring(0, 1) == "#")
            {
                currentString = currentString.Remove(0, 1);
                numberRemovals++;

            }

            //set the appropiate heading option
            switch(numberRemovals)
            {
                case 0:
                    headingFound = TextOptions.NoOption;
                    break;
                case 1:
                    headingFound = TextOptions.Heading1;
                    break;
                case 2:
                    headingFound = TextOptions.Heading2;
                    break;
                case 3:
                    headingFound = TextOptions.Heading3;
                    break;
            }
            return currentString;
        }
Esempio n. 40
0
        public void RenderText(Context context, string text, TextOptions options, Point position)
        {
            using (var layout = new Pango.Layout (pangoInitializer ())) {
                layout.SetText (text);

                layout.Width = Pango.Units.FromPixels ((int)options.MaxWidth);

                context.MoveTo (position.X, position.Y);
                context.Color = options.Color.ToCairo ();
                Pango.CairoHelper.ShowLayout (context, layout);
            }
        }
Esempio n. 41
0
 public Size TextExtents(string text, TextOptions options)
 {
     int w, h;
     using (var layout = new Pango.Layout (pangoInitializer ())) {
         layout.SetText (text);
         layout.GetPixelSize (out w, out h);
     }
     return new Size (w, h);
 }
Esempio n. 42
0
 public Size TextExtents(string text, TextOptions options)
 {
     if (text == null)
         return new Size ();
     NSString str = new NSString (text);
     var size = str.StringSize (UIFont.SystemFontOfSize (UIFont.LabelFontSize));
     return new Size (size.Width, size.Height);
 }