public static void Run()
        {
            // ExStart:DefineAlignment
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();

            // Instantiate Document object with input file
            Document doc = new Document(dataDir+ "DefineAlignment.pdf");
            // Instantiate FormattedText object with sample string
            FormattedText text = new FormattedText("This");
            // Add new text line to FormattedText
            text.AddNewLineText("is sample");
            text.AddNewLineText("Center Aligned");
            text.AddNewLineText("TextStamp");
            text.AddNewLineText("Object");
            // Create TextStamp object using FormattedText
            TextStamp stamp = new TextStamp(text);
            // Specify the Horizontal Alignment of text stamp as Center aligned
            stamp.HorizontalAlignment = HorizontalAlignment.Center;
            // Specify the Vertical Alignment of text stamp as Center aligned
            stamp.VerticalAlignment = VerticalAlignment.Center;
            // Specify the Text Horizontal Alignment of TextStamp as Center aligned
            stamp.TextAlignment = HorizontalAlignment.Center;
            // Set top margin for stamp object
            stamp.TopMargin = 20;
            // Add the stamp object over first page of document
            doc.Pages[1].AddStamp(stamp);

            dataDir = dataDir + "StampedPDF_out.pdf";
            // Save the udpated document
            doc.Save(dataDir);
            // ExEnd:DefineAlignment            
            Console.WriteLine("\nAlignment defined successfully for text stamp.\nFile saved at " + dataDir);
        }
Example #2
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_Text();

            //open document
            PdfFileMend mender = new PdfFileMend();

            //create PdfFileMend object to add text
            mender.BindPdf(dataDir + "AddText.pdf");

            //create formatted text
            FormattedText text = new FormattedText("Aspose - Your File Format Experts!", System.Drawing.Color.AliceBlue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, true, 14);

            //set whether to use Word Wrap or not and using which mode
            mender.IsWordWrap = true;
            mender.WrapMode = WordWrapMode.Default;

            //add text in the PDF file
            mender.AddText(text, 1, 100, 200, 200, 400);

            //save changes
            mender.Save(dataDir + "AddText_out.pdf");

            //close PdfFileMend object
            mender.Close();
            
        }
Example #3
0
		private void WriteInputStats(ref FormattedText target, MouseInput input)
		{
			// Initialize the formatted text block we'll write to
			this.PrepareFormattedText(ref target);

			// Determine all pressed mouse buttons
			string activeButtons = "";
			foreach (MouseButton button in Enum.GetValues(typeof(MouseButton)))
			{
				if (input.ButtonPressed(button))
				{
					if (activeButtons.Length != 0)
						activeButtons += ", ";
					activeButtons += button.ToString();
				}
			}

			// Compose the formatted text to display
			target.SourceText = 
				"/f[1]Mouse Stats/f[0]/n/n" +
				string.Format("Description: /cFF8800FF{0}/cFFFFFFFF/n", input.Description) +
				string.Format("IsAvailable: /cFF8800FF{0}/cFFFFFFFF/n", input.IsAvailable) +
				string.Format("X:     /c44AAFFFF{0,4}/cFFFFFFFF | XSpeed:     /c44AAFFFF{1,4}/cFFFFFFFF/n", input.X, input.XSpeed) +
				string.Format("Y:     /c44AAFFFF{0,4}/cFFFFFFFF | YSpeed:     /c44AAFFFF{1,4}/cFFFFFFFF/n", input.Y, input.YSpeed) +
				string.Format("Wheel: /c44AAFFFF{0,4}/cFFFFFFFF | WheelSpeed: /c44AAFFFF{1,4}/cFFFFFFFF/n", input.WheelPrecise, input.WheelSpeedPrecise) +
				string.Format("Buttons: /c44AAFFFF{0}/cFFFFFFFF/n", activeButtons);
		}
 public PasswordConsumer(FormattedText desiredPassword)
 {
     if (desiredPassword == null)
         throw new NullReferenceException();
     this.desiredPassword = desiredPassword;
     IsConsumtionInProgress = false;
 }
        public static void Run()
        {
            // ExStart:AddPageNumber
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_StampsWatermarks();

            // Create PdfFileStamp object
            PdfFileStamp fileStamp = new PdfFileStamp();

            // Open Document
            fileStamp.BindPdf(dataDir + "AddPageNumber.pdf");
            
            // Get total number of pages
            int totalPages = new PdfFileInfo(dataDir + "AddPageNumber.pdf").NumberOfPages;

            // Create formatted text for page number
            FormattedText formattedText = new FormattedText("Page # Of " + totalPages, System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14);

            // Set starting number for first page; you might want to start from 2 or more
            fileStamp.StartingNumber = 1;

            // Add page number
            fileStamp.AddPageNumber(formattedText, 0);

            // Save updated PDF file
            fileStamp.Save(dataDir + "AddPageNumber_out.pdf");

            // Close fileStamp
            fileStamp.Close();
            // ExEnd:AddPageNumber
            
        }
 public void ThrowsExceptionWhenPassingStringWithCharactersThatOccursMoreThanOneTimeToConstructor()
 {
     Assert.Throws(typeof(ArgumentException), delegate()
     {
         FormattedText p = new FormattedText("aa");
     });
 }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();

            // Instantiate Document object with input file
            Document doc = new Document(dataDir+ "DefineAlignment.pdf");
            // instantiate FormattedText object with sample string
            FormattedText text = new FormattedText("This");
            // add new text line to FormattedText
            text.AddNewLineText("is sample");
            text.AddNewLineText("Center Aligned");
            text.AddNewLineText("TextStamp");
            text.AddNewLineText("Object");
            // create TextStamp object using FormattedText
            TextStamp stamp = new TextStamp(text);
            // specify the Horizontal Alignment of text stamp as Center aligned
            stamp.HorizontalAlignment = HorizontalAlignment.Center;
            // specify the Vertical Alignment of text stamp as Center aligned
            stamp.VerticalAlignment = VerticalAlignment.Center;
            // specify the Text Horizontal Alignment of TextStamp as Center aligned
            stamp.TextAlignment = HorizontalAlignment.Center;
            // set top margin for stamp object
            stamp.TopMargin = 20;
            // add the stamp object over first page of document
            doc.Pages[1].AddStamp(stamp);
            // save the udpated document
            doc.Save(dataDir+ "StampedPDF.pdf");
            
            
        }
        public static void Run()
        {
            // ExStart:AddHeader
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_StampsWatermarks();

            // Create PdfFileStamp object
            PdfFileStamp fileStamp = new PdfFileStamp();

            // Open Document
            fileStamp.BindPdf(dataDir + "AddHeader.pdf");
         
            // Create formatted text for page number
            FormattedText formattedText = new FormattedText("Aspose - Your File Format Experts!", System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14);

            // Add header
            fileStamp.AddHeader(formattedText, 10);
           
            // Save updated PDF file
            fileStamp.Save(dataDir + "AddHeader_out.pdf");
            
            // Close fileStamp
            fileStamp.Close();
            // ExEnd:AddHeader
        }
        public PermutationGenerator(FormattedText alphabet)
        {
            if (alphabet == null)
                throw new NullReferenceException();

            this.alphabet = alphabet;
            this.FormattedText = alphabet.Text.ToArray();
        }
 public void ThrowsExceptionWhenPassingNullReferenceToConstructor()
 {
     string testString = null;
     Assert.Throws(typeof(NullReferenceException), delegate()
     {
         FormattedText p = new FormattedText(testString);
     });
 }
        public void ReturnsPasswordProducerObject()
        {
            FormattedText alphabet = new FormattedText("abc");
            PasswordProducer pp = new PasswordProducer(alphabet);
            Assert.IsNotNull(pp);

            PermutationGenerator generator = new PermutationGenerator(alphabet);
            pp = new PasswordProducer(generator);
            Assert.IsNotNull(pp);
        }
Example #12
0
 /// <summary>
 /// Applies the formatting specified in a FormattedText to a GUI style. If the formatting
 /// contains any emphases, currently only applies the first emphasis.
 /// </summary>
 /// <returns>
 /// The same GUI style (not a copy) with formatting applied.
 /// </returns>
 /// <param name='formattingToApply'>
 /// Formatting to apply.
 /// </param>
 /// <param name='guiStyle'>
 /// GUI style.
 /// </param>
 public static GUIStyle ApplyFormatting(FormattedText formattingToApply, GUIStyle guiStyle)
 {
     if ((guiStyle != null) && (formattingToApply != null)) {
         if (formattingToApply.italic) guiStyle.fontStyle = ApplyItalic(guiStyle.fontStyle);
         if ((formattingToApply.emphases != null) && (formattingToApply.emphases.Length > 0)) {
             guiStyle.normal.textColor = formattingToApply.emphases[0].color;
             if (formattingToApply.emphases[0].bold) guiStyle.fontStyle = ApplyBold(guiStyle.fontStyle);
             if (formattingToApply.emphases[0].italic) guiStyle.fontStyle = ApplyItalic(guiStyle.fontStyle);
         }
     }
     return guiStyle;
 }
        public void GenerateNext_GeneratesPasswordFromAlphabet()
        {
            FormattedText alphabet = new FormattedText("ab");
            PermutationGenerator generator = new PermutationGenerator(alphabet);
            FormattedText password = generator.GenerateNext();

            Assert.IsNotNull(password);
            Assert.AreEqual("ab", password.Text);
            password = generator.GenerateNext();
            Assert.AreEqual("ba", password.Text);
            password = generator.GenerateNext();
            Assert.AreEqual("ab", password.Text);
        }
    /// <summary>
    /// Returns formatted text for status information.
    /// </summary>
    /// <param name="status">MVTestStatusEnum status</param>
    private string FormattedStatusText(MVTestStatusEnum status)
    {
        var formattedText = new FormattedText(GetString("mvtest.status." + status));

        if (status == MVTestStatusEnum.Running)
        {
            formattedText.ColorGreen();
        }
        if (status == MVTestStatusEnum.Disabled)
        {
            formattedText.ColorRed();
        }

        return formattedText.ToString();
    }
Example #15
0
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_StampsWatermarks();
            //open document
            PdfFileStamp fileStamp = new PdfFileStamp(dataDir+ "AddFooter.pdf", dataDir+ "AddFooter_out.pdf");

            //create formatted text for page number
            FormattedText formattedText = new FormattedText("Aspose - Your File Format Experts!", System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14);

            //add footer
            fileStamp.AddFooter(formattedText, 10);

            //save updated PDF file
            fileStamp.Close();
        }
        public static void Main()
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");

            //open document
            PdfFileStamp fileStamp = new PdfFileStamp(dataDir+ "input.pdf", dataDir+ "output.pdf");

            //create formatted text for page number
            FormattedText formattedText = new FormattedText("Aspose - Your File Format Experts!", System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14);

            //add header
            fileStamp.AddHeader(formattedText, 10);

            //save updated PDF file
            fileStamp.Close();
        }
Example #17
0
        internal override void VisitFormattedText(FormattedText formattedText)
        {
            Document document = formattedText.Document;
            ParagraphFormat format = null;

            Style style = document._styles[formattedText._style.Value];
            if (style != null)
                format = style._paragraphFormat;
            else if (formattedText._style.Value != "")
                format = document._styles[StyleNames.InvalidStyleName]._paragraphFormat;

            if (format != null)
            {
                if (formattedText._font == null)
                    formattedText.Font = format._font.Clone();
                else if (format._font != null)
                    FlattenFont(formattedText._font, format._font);
            }
        }
        public static void Run()
        {
            // ExStart:AddTextImagesUsingPdfFileMend
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();

            // Specify input and output PDF file paths
            string inputFile = dataDir + "inFile.pdf";
            string outputFile = dataDir + "AddTextImagesUsingPdfFileMend_out.pdf";

            // Specify image file path
            string imageName = dataDir + "aspose-logo.jpg";

            // Create file streams for all of the files to be used in the example           
            FileStream inImgStream = new FileStream(@imageName, FileMode.Open);
            FileStream outputStream = new FileStream(@outputFile, FileMode.Create);

            Document doc = new Document(inputFile);
            // Create instance of PdfFileMend class
            PdfFileMend mendor = new PdfFileMend(doc);

            // Add image to the input PDF file on page number 1 at specified location
            mendor.AddImage(inImgStream, 1, 50, 50, 100, 100);

            // Create new FormattedText type object to add text in the PDF file
            FormattedText ft = new FormattedText(
            "PdfFileMend testing! 0 rotation.",
            System.Drawing.Color.FromArgb(0, 200, 0),
            FontStyle.TimesRoman,
            EncodingType.Winansi,
            false,
            12);

            // Add text in the existing PDF file
            mendor.AddText(ft, 1, 50, 100, 100, 200);

            // Claose the PdfFileMend type object
            mendor.Close();
            // Close output file stream
            outputStream.Close();
            // ExEnd:AddTextImagesUsingPdfFileMend                      
        }
        public static void Main()
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");
            //create PdfFileMend object to add text
            PdfFileMend mender = new PdfFileMend(dataDir+ "input.pdf", dataDir+ "output.pdf");

            //create formatted text
            FormattedText text = new FormattedText("Aspose - Your File Format Experts!", System.Drawing.Color.AliceBlue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, true, 14);

            //set whether to use Word Wrap or not and using which mode
            mender.IsWordWrap = true;
            mender.WrapMode = WordWrapMode.Default;

            //add text in the PDF file
            mender.AddText(text, 1, 100, 200, 200, 400);

            //close PdfFileMend object
            mender.Close();
        }
Example #20
0
            protected override void OnRender(DrawingContext dc)
            {
                string testString = "Formatted MML Document is displayed here!\nPlease implement the user oriented layout logic.";

                FormattedText formattedText = new FormattedText(testString, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Verdana"), 30, Brushes.Black);

                formattedText.MaxTextWidth = 280;
                formattedText.MaxTextHeight = 280;

                formattedText.SetForegroundBrush(new LinearGradientBrush(Colors.Blue, Colors.Teal, 90.0), 10, 12);

                formattedText.SetFontStyle(FontStyles.Italic, 36, 5);
                formattedText.SetForegroundBrush(new LinearGradientBrush(Colors.Pink, Colors.Crimson, 90.0), 36, 5);
                formattedText.SetFontSize(36, 36, 5);

                formattedText.SetFontWeight(FontWeights.Bold, 42, 48);

                dc.DrawRectangle(Brushes.White, null, new Rect(0, 0, 300, 300));

                dc.DrawText(formattedText, new Point(10, 10));
            }
        public static void Main()
        {
            // The path to the documents directory.
            string dataDir = Path.GetFullPath("../../../Data/");
            //open document
            PdfFileStamp fileStamp = new PdfFileStamp(dataDir+ "Input_new.pdf", dataDir+ "output.pdf");

            //get total number of pages

            int totalPages = new PdfFileInfo(dataDir+ "Input_new.pdf").NumberOfPages;
            //create formatted text for page number
            FormattedText formattedText = new FormattedText("Page # Of " + totalPages, System.Drawing.Color.Blue, System.Drawing.Color.Gray, Aspose.Pdf.Facades.FontStyle.Courier, EncodingType.Winansi, false, 14);

            //set starting number for first page; you might want to start from 2 or more
            fileStamp.StartingNumber = 1;
            //add page number
            fileStamp.AddPageNumber(formattedText, 0);

            //save updated PDF file
            fileStamp.Close();
        }
Example #22
0
            public void EmitText(FormattedText markup)
            {
                var iterEnd = EndIter;
                var textmark = CreateMark (null, iterEnd, true);
                Insert (ref iterEnd, markup.Text);

                foreach (var attr in markup.Attributes) {
                    var iterEndAttr = GetIterAtMark (textmark);
                    iterEndAttr.ForwardChars (attr.StartIndex);
                    var attrStart = CreateMark (null, iterEndAttr, true);
                    iterEndAttr.ForwardChars (attr.Count);

                    var tag = new Gtk.TextTag (null);

                    if (attr is BackgroundTextAttribute) {
                        var xa = (BackgroundTextAttribute)attr;
                        tag.BackgroundGdk = xa.Color.ToGtkValue ();
                    } else if (attr is ColorTextAttribute) {
                        var xa = (ColorTextAttribute)attr;
                        tag.ForegroundGdk = xa.Color.ToGtkValue ();
                    } else if (attr is FontWeightTextAttribute) {
                        var xa = (FontWeightTextAttribute)attr;
                        tag.Weight = (Pango.Weight)(int)xa.Weight;
                    } else if (attr is FontStyleTextAttribute) {
                        var xa = (FontStyleTextAttribute)attr;
                        tag.Style = (Pango.Style)(int)xa.Style;
                    } else if (attr is UnderlineTextAttribute) {
                        var xa = (UnderlineTextAttribute)attr;
                        tag.Underline = xa.Underline ? Pango.Underline.Single : Pango.Underline.None;
                    } else if (attr is StrikethroughTextAttribute) {
                        var xa = (StrikethroughTextAttribute)attr;
                        tag.Strikethrough = xa.Strikethrough;
                    } else if (attr is FontTextAttribute) {
                        var xa = (FontTextAttribute)attr;
                        tag.FontDesc = (Pango.FontDescription)Toolkit.GetBackend (xa.Font);
                    } else if (attr is LinkTextAttribute) {
                        var xa = (LinkTextAttribute)attr;
                        Uri uri = xa.Target;
                        if (uri == null)
                            Uri.TryCreate (markup.Text.Substring (xa.StartIndex, xa.Count), UriKind.RelativeOrAbsolute, out uri);
                        var link = new Link { Href = uri };
                        tag.Underline = Pango.Underline.Single;
                        tag.ForegroundGdk = Toolkit.CurrentEngine.Defaults.FallbackLinkColor.ToGtkValue ();
                        Links [tag] = link;
                    }

                    TagTable.Add (tag);
                    ApplyTag (tag, GetIterAtMark (attrStart), iterEndAttr);
                    DeleteMark (attrStart);
                }
                DeleteMark (textmark);
            }
Example #23
0
        /// <summary>
        /// Задаёт как можно больший размер шрифта текстового блока исходя из доступной для него области
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void MeasureFontSize(object sender, EventArgs e)
        {
            var textBlock = sender as TextBlock;

            if (!(VisualTreeHelper.GetParent(textBlock) is FrameworkElement parent))
            {
                return;
            }

            var width  = parent.ActualWidth - textBlock.Margin.Left - textBlock.Margin.Right;
            var height = parent.ActualHeight - textBlock.Margin.Top - textBlock.Margin.Bottom;

            if (textBlock.Text.Length == 0 || width < double.Epsilon || height < double.Epsilon)
            {
                return;
            }

            if (textBlock.DataContext != null && textBlock.DataContext.ToString() == "{DisconnectedItem}")
            {
                return;
            }

            var ft = new FormattedText(textBlock.Text, CultureInfo.CurrentUICulture, textBlock.FlowDirection, new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch), 1.0, textBlock.Foreground)
            {
                TextAlignment = textBlock.TextAlignment, Trimming = textBlock.TextTrimming
            };

            var lineHeight = GetInterlinyage(textBlock);

            if (lineHeight < textBlock.FontFamily.LineSpacing)
            {
                lineHeight = textBlock.FontFamily.LineSpacing;
            }

            var coef = lineHeight / textBlock.FontFamily.LineSpacing;

            double fontSize;

            if (textBlock.TextWrapping == TextWrapping.NoWrap)
            {
                fontSize = GetMaxFontSize(textBlock);
            }
            else
            {
                // Предскажем количество строк текста, исходя из полученных параметров

                // Количество блоков, получаемое при "разрезании" всего текста (с размером шрифта 1) на куски, равные по длина доступной ширине текстового блока
                var numOfLines     = Math.Max(1.0, Math.Floor(ft.Height / textBlock.FontFamily.LineSpacing));
                var fullTextLength = ft.WidthIncludingTrailingWhitespace * numOfLines;
                var numberOfLinesPredictedByWidth = fullTextLength / width;

                // Количество строк как отношение всей доступной высоты к высоте 1 строки текста (с размером шрифта 1)
                var numberOfLinesPredictedByHeight = height / lineHeight;
                var numberOfLines = Math.Max(1.0, Math.Max(numOfLines, Math.Floor(Math.Sqrt(numberOfLinesPredictedByWidth * numberOfLinesPredictedByHeight))));

                fontSize = Math.Min(numberOfLinesPredictedByHeight / numberOfLines, GetMaxFontSize(textBlock) / textBlock.FontFamily.LineSpacing);

                ft.MaxTextWidth = width * 0.97;
            }

            do
            {
                fontSize = Math.Max(fontSize, 1.0);

                ft.SetFontSize(fontSize);
                double textHeight = ft.Height * coef;

                if (fontSize > 1.0 && (textHeight > height || (textBlock.TextWrapping == TextWrapping.NoWrap ? ft.Width > width * 0.97 : ft.MinWidth > ft.MaxTextWidth)))
                {
                    var lower = 1.0;

                    if (textHeight > height && textBlock.TextWrapping == TextWrapping.NoWrap)
                    {
                        lower = Math.Max(lower, (textHeight - height) / lineHeight);
                    }

                    fontSize -= lower;
                    continue;
                }
                else
                {
                    break;
                }
            } while (true);

            textBlock.FontSize   = fontSize;
            textBlock.LineHeight = textBlock.FontSize * lineHeight;
        }
Example #24
0
        /// <summary>
        /// Parses the keyword «\fontcolor».
        /// </summary>
        private void ParseFontColor(FormattedText formattedText, int nestingLevel)
        {
            AssertSymbol(Symbol.FontColor);
            ReadCode();  // read '('

            AssertSymbol(Symbol.ParenLeft);
            ReadCode();  // read color token
            Color color = ParseColor();
            formattedText.Font.Color = color;
            AssertSymbol(Symbol.ParenRight);
            ReadCode();
            AssertSymbol(Symbol.BraceLeft);
            ParseFormattedText(formattedText.Elements, nestingLevel);
            AssertSymbol(Symbol.BraceRight);
        }
Example #25
0
 public void SetFormattedText(FormattedText text)
 {
     Widget.AllowsEditingTextAttributes = true;
     Widget.AttributedStringValue       = text.ToAttributedString();
 }
Example #26
0
        private void UpdateChallengeCustomTheme()
        {
            bool   watermarkEnabled = (bool)bCustomChallenge.IsChecked;
            string watermark        = WatermarkChallenge_TextBox.Text;
            string path             = FProp.Default.FBannerFilePath;
            int    opacity          = Convert.ToInt32(OpacityBanner_Slider.Value);

            string[]        primaryParts   = FProp.Default.FPrimaryColor.Split(':');
            string[]        secondaryParts = FProp.Default.FSecondaryColor.Split(':');
            SolidColorBrush PrimaryColor   = new SolidColorBrush(Color.FromRgb(Convert.ToByte(primaryParts[0]), Convert.ToByte(primaryParts[1]), Convert.ToByte(primaryParts[2])));
            SolidColorBrush SecondaryColor = new SolidColorBrush(Color.FromRgb(Convert.ToByte(secondaryParts[0]), Convert.ToByte(secondaryParts[1]), Convert.ToByte(secondaryParts[2])));

            if (watermarkEnabled)
            {
                DrawingVisual drawingVisual = new DrawingVisual();
                double        PPD           = VisualTreeHelper.GetDpi(drawingVisual).PixelsPerDip;
                using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                {
                    //INITIALIZATION
                    drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(new Point(0, 0), new Size(1024, 410)));

                    Point         dStart    = new Point(0, 256);
                    LineSegment[] dSegments = new[]
                    {
                        new LineSegment(new Point(1024, 256), true),
                        new LineSegment(new Point(1024, 241), true),
                        new LineSegment(new Point(537, 236), true),
                        new LineSegment(new Point(547, 249), true),
                        new LineSegment(new Point(0, 241), true)
                    };
                    PathFigure   dFigure = new PathFigure(dStart, dSegments, true);
                    PathGeometry dGeo    = new PathGeometry(new[] { dFigure });

                    Typeface      typeface      = new Typeface(TextsUtility.Burbank, FontStyles.Normal, FontWeights.Black, FontStretches.Normal);
                    FormattedText formattedText =
                        new FormattedText(
                            "{BUNDLE DISPLAY NAME HERE}",
                            CultureInfo.CurrentUICulture,
                            FlowDirection.LeftToRight,
                            typeface,
                            55,
                            Brushes.White,
                            PPD
                            );
                    formattedText.TextAlignment = TextAlignment.Left;
                    formattedText.MaxTextWidth  = 768;
                    formattedText.MaxLineCount  = 1;
                    Point textLocation = new Point(50, 165 - formattedText.Height);

                    drawingContext.DrawRectangle(PrimaryColor, null, new Rect(0, 0, 1024, 256));
                    if (!string.IsNullOrEmpty(path))
                    {
                        BitmapImage bmp = new BitmapImage(new Uri(path));
                        drawingContext.DrawImage(ImagesUtility.CreateTransparency(bmp, opacity), new Rect(0, 0, 1024, 256));
                    }
                    drawingContext.DrawGeometry(SecondaryColor, null, dGeo);
                    drawingContext.DrawText(formattedText, textLocation);

                    formattedText =
                        new FormattedText(
                            "{LAST FOLDER HERE}",
                            CultureInfo.CurrentUICulture,
                            FlowDirection.LeftToRight,
                            typeface,
                            30,
                            SecondaryColor,
                            IconCreator.PPD
                            );
                    formattedText.TextAlignment = TextAlignment.Left;
                    formattedText.MaxTextWidth  = 768;
                    formattedText.MaxLineCount  = 1;
                    textLocation = new Point(50, 100 - formattedText.Height);
                    Geometry geometry = formattedText.BuildGeometry(textLocation);
                    Pen      pen      = new Pen(ChallengesUtility.DarkBrush(SecondaryColor, 0.3f), 1);
                    pen.LineJoin = PenLineJoin.Round;
                    drawingContext.DrawGeometry(SecondaryColor, pen, geometry);

                    typeface      = new Typeface(TextsUtility.FBurbank, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
                    formattedText =
                        new FormattedText(
                            watermark,
                            CultureInfo.CurrentUICulture,
                            FlowDirection.LeftToRight,
                            typeface,
                            20,
                            new SolidColorBrush(Color.FromArgb(150, 255, 255, 255)),
                            IconCreator.PPD
                            );
                    formattedText.TextAlignment = TextAlignment.Right;
                    formattedText.MaxTextWidth  = 1014;
                    formattedText.MaxLineCount  = 1;
                    textLocation = new Point(0, 205);
                    drawingContext.DrawText(formattedText, textLocation);

                    LinearGradientBrush linGrBrush = new LinearGradientBrush();
                    linGrBrush.StartPoint = new Point(0, 0);
                    linGrBrush.EndPoint   = new Point(0, 1);
                    linGrBrush.GradientStops.Add(new GradientStop(Color.FromArgb(75, SecondaryColor.Color.R, SecondaryColor.Color.G, SecondaryColor.Color.B), 0));
                    linGrBrush.GradientStops.Add(new GradientStop(Color.FromArgb(25, PrimaryColor.Color.R, PrimaryColor.Color.G, PrimaryColor.Color.B), 0.15));
                    linGrBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 1));

                    drawingContext.DrawRectangle(ChallengesUtility.DarkBrush(PrimaryColor, 0.3f), null, new Rect(0, 256, 1024, 144));
                    drawingContext.DrawRectangle(linGrBrush, null, new Rect(0, 256, 1024, 144));

                    typeface = new Typeface(TextsUtility.Burbank, FontStyles.Normal, FontWeights.Black, FontStretches.Normal);
                    int y = 300;

                    drawingContext.DrawRectangle(ChallengesUtility.DarkBrush(PrimaryColor, 0.3f), null, new Rect(0, y, 1024, 90));
                    drawingContext.DrawRectangle(PrimaryColor, null, new Rect(25, y, 1024 - 50, 70));

                    dStart    = new Point(32, y + 5);
                    dSegments = new[]
                    {
                        new LineSegment(new Point(29, y + 67), true),
                        new LineSegment(new Point(1024 - 160, y + 62), true),
                        new LineSegment(new Point(1024 - 150, y + 4), true)
                    };
                    dFigure = new PathFigure(dStart, dSegments, true);
                    dGeo    = new PathGeometry(new[] { dFigure });
                    drawingContext.DrawGeometry(ChallengesUtility.LightBrush(PrimaryColor, 0.04f), null, dGeo);

                    drawingContext.DrawRectangle(SecondaryColor, null, new Rect(60, y + 47, 500, 7));

                    dStart    = new Point(39, y + 35);
                    dSegments = new[]
                    {
                        new LineSegment(new Point(45, y + 32), true),
                        new LineSegment(new Point(48, y + 37), true),
                        new LineSegment(new Point(42, y + 40), true)
                    };
                    dFigure = new PathFigure(dStart, dSegments, true);
                    dGeo    = new PathGeometry(new[] { dFigure });
                    drawingContext.DrawGeometry(SecondaryColor, null, dGeo);
                }

                if (drawingVisual != null)
                {
                    RenderTargetBitmap RTB = new RenderTargetBitmap(1024, 410, 96, 96, PixelFormats.Pbgra32);
                    RTB.Render(drawingVisual);
                    RTB.Freeze(); //We freeze to apply the RTB to our imagesource from the UI Thread

                    FWindow.FMain.Dispatcher.InvokeAsync(() =>
                    {
                        ImageBox_ChallengePreview.Source = BitmapFrame.Create(RTB); //thread safe and fast af
                    });
                }
            }
            else
            {
                BitmapImage source = new BitmapImage(new Uri(CHALLENGE_TEMPLATE_ICON));
                ImageBox_ChallengePreview.Source = source;
            }
        }
        public static FormattedText GetFormattedText(string text, Font font)
        {
            var formattedText = new FormattedText(text, CultureInfo.InvariantCulture, System.Windows.FlowDirection.LeftToRight, font.GetTypeface(), font.Size, null);

            return(formattedText);
        }
Example #28
0
 internal void Format(FormattedText text, int index, int length)
 {
     text.SetForegroundBrush(Foreground, index, length);
     text.SetFontWeight(FontWeight, index, length);
     text.SetFontStyle(FontStyle, index, length);
 }
Example #29
0
        private Size MeasureString(string candidate)
        {
            var formattedText = new FormattedText(candidate, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), FontSize, Brushes.Black, new NumberSubstitution(), TextFormattingMode.Display);

            return(new Size(formattedText.Width, formattedText.Height));
        }
Example #30
0
        /// <summary>
        /// Returns the desired height for the entire header
        /// </summary>
        /// <returns>double</returns>
        protected virtual double GetHeaderHeight()
        {
            var ft = new FormattedText("X", CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(FontFamily, FontStyle, FontWeight, FontStretches.Normal), FontSize, Foreground);

            return(ft.Height + 7d);
        }
Example #31
0
        public override DocumentPage GetPage(int pageNumber)//This is the method that creates the printed document,
        {
            //Modify the method to display the report using the data objects that you passed to the class.



            FormattedText ft = GetFormattedText("A");// new FormattedText("A", System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, fontsize, Brushes.Black);

            float tabspace = (float)(pagesize.Width - 2 * margin) / 5.0f;

            DrawingVisual visual = new DrawingVisual();//This is the "blank slate" that we're going to write the report on.

            PrintPointCummulative = new Point(margin, margin);
            PrintPointCurrent     = PrintPointCummulative;


            using (DrawingContext dc = visual.RenderOpen())
            {
                //TPReportData rd1 = new TPReportData();
                //rd1.SetDemoDate(1);

                //TPReportData rd2 = new TPReportData();
                //rd2.SetDemoDate(2);

                Typeface columnHeaderTypeface = new Typeface(typeface.FontFamily, FontStyles.Normal, FontWeights.Bold, FontStretches.Normal);//Typeface for Headers
                ft = GetFormattedText("Treatment Plans Comparasion Report", columnHeaderTypeface);
                if (IsOnPage(ft.Height, pageNumber))
                {
                    dc.DrawText(ft, PrintPointCurrent);
                }

                //IsOnPage(ft.Height, pageNumber);
                if (IsOnPage(ft.Height, pageNumber))
                {
                    dc.DrawLine(new Pen(Brushes.Blue, 2), new Point(margin, PrintPointCurrent.Y), new Point(pagesize.Width - margin, PrintPointCurrent.Y));
                }

                // build general info
                string outputline = string.Empty;
                AddSubTitle("General Info:", ft, dc, pageNumber, columnHeaderTypeface);
                outputline = "Patients\tPatient Name\tPatientID\t\tCourseID\t\tPlanID";
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);
                outputline  = "Patient1";
                outputline += "\t" + rd1.CurPatientInfo.LastName + ", " + rd1.CurPatientInfo.FirstName;
                outputline += "\t\t" + rd1.CurPatientInfo.PatientID;
                outputline += "\t\t" + rd1.CurPlanInfo.CourseID + "\t\t" + rd1.CurPlanInfo.PlaneID;
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);

                outputline  = "Patient2";
                outputline += "\t" + rd2.CurPatientInfo.LastName + ", " + rd2.CurPatientInfo.FirstName;
                outputline += "\t\t" + rd2.CurPatientInfo.PatientID;
                outputline += "\t\t" + rd2.CurPlanInfo.CourseID + "\t\t" + rd2.CurPlanInfo.PlaneID;
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);

                // build Dose Presciption info
                AddSpace(ft, dc, pageNumber, columnHeaderTypeface);
                AddSubTitle("Dose Presciption Info:", ft, dc, pageNumber, columnHeaderTypeface);
                outputline = "Patients\t\tNormalization\t\tNFractions\tDose/fx\t\tTotalDose";
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);
                outputline  = "Patient1";
                outputline += "\t\t" + rd1.GetDosePrescriptionString();
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);

                outputline  = "Patient2";
                outputline += "\t\t" + rd2.GetDosePrescriptionString();
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);

                // build Field Info
                AddSpace(ft, dc, pageNumber, columnHeaderTypeface);
                AddSubTitle("Treatment Beams(Patient1)", ft, dc, pageNumber, columnHeaderTypeface);
                AddFiedTable(rd1.CurFieldInfoList, ft, dc, pageNumber, columnHeaderTypeface);

                AddSpace(ft, dc, pageNumber, columnHeaderTypeface);
                AddSubTitle("Treatment Beams(Patient2)", ft, dc, pageNumber, columnHeaderTypeface);
                AddFiedTable(rd2.CurFieldInfoList, ft, dc, pageNumber, columnHeaderTypeface);

                // build structure info
                AddSpace(ft, dc, pageNumber, columnHeaderTypeface);
                AddSubTitle("Structure Info (Patient1/Patient2):", ft, dc, pageNumber, columnHeaderTypeface);
                outputline = "StructureID\t\tType\t\tVolume\t\tMinDos\t\tMaxDose";
                AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);


                // foreach (StructureData sd1 in rd1.CurStructureDataList)
                // {
                //     if (rd2.CurStructureDataList.Where(x => x.StructureID == sd1.StructureID).Any())
                //     {
                //         StructureData sd2 = rd2.CurStructureDataList.Where(x => x.StructureID == sd1.StructureID).First();
                //         outputline = sd1.StructureID
                //     }
                // }



                bool bHasStructureSetPatient1 = rd1.CurStructureDataList != null && rd1.CurStructureDataList.Count > 0;
                bool bHasStructureSetPatient2 = rd2.CurStructureDataList != null && rd2.CurStructureDataList.Count > 0;
                int  iCountP1  = rd1.CurStructureDataList != null ? rd1.CurStructureDataList.Count:0;
                int  iCountP2  = rd2.CurStructureDataList != null ? rd2.CurStructureDataList.Count:0;
                int  iMinCount = Math.Min(iCountP1, iCountP2);
                if (iMinCount > 0)
                {
                    for (int i = 0; i < iMinCount; i++)
                    {
                        if (rd1.CurStructureDataList[i].StructureID == rd2.CurStructureDataList[0].StructureID)
                        {
                            outputline  = rd1.CurStructureDataList[i].StructureID;
                            outputline += "\t\t" + rd1.CurStructureDataList[i].Type + "/" + rd2.CurStructureDataList[i].Type;
                            string strTemp = rd1.CurStructureDataList[i].Volume + "/" + rd2.CurStructureDataList[i].Volume;
                            outputline += "\t\t" + rd1.CurStructureDataList[i].Volume + "/" + rd2.CurStructureDataList[i].Volume;
                            string strFormat = strTemp.Length > 12 ? "\t" : "\t\t";
                            outputline += strFormat + rd1.CurStructureDataList[i].MinDose + "/" + rd2.CurStructureDataList[i].MinDose;
                            outputline += "\t\t" + rd1.CurStructureDataList[i].MaxDose + "/" + rd2.CurStructureDataList[i].MaxDose;
                            AddNewContent(outputline, ft, dc, pageNumber, columnHeaderTypeface);
                        }
                    }
                }
            }


            return(new DocumentPage(visual, pagesize, new Rect(pagesize), new Rect(pagesize)));
        }
Example #32
0
        private void DrawEndAlignedTextPath(DrawingContext dc, PathGeometry pathGeometry,
                                            ISvgAnimatedLength startOffset)
        {
            if (pathGeometry == null || pathGeometry.Figures == null ||
                pathGeometry.Figures.Count != 1)
            {
                return;
            }

            _pathLength = GetPathFigureLength(pathGeometry.Figures[0]);
            if (_pathLength == 0 || _textLength == 0)
            {
                return;
            }

            //double scalingFactor = pathLength / textLength;
            double scalingFactor = 1.0;   // Not scaling the text to fit...
            double progress      = 1.0;
            //PathGeometry pathGeometry =
            //    new PathGeometry(new PathFigure[] { PathFigure });

            Point ptOld = new Point(0, 0);

            int itemCount = _formattedChars.Count - 1;

            for (int i = itemCount; i >= 0; i--)
            {
                FormattedText formText = _formattedChars[i];

                double width = scalingFactor *
                               formText.WidthIncludingTrailingWhitespace;
                double baseline = scalingFactor * formText.Baseline;
                progress -= width / 2 / _pathLength;
                Point point, tangent;

                pathGeometry.GetPointAtFractionLength(progress,
                                                      out point, out tangent);

                if (i != itemCount)
                {
                    if (point == ptOld)
                    {
                        break;
                    }
                }

                dc.PushTransform(
                    new TranslateTransform(point.X - width / 2,
                                           point.Y - baseline));
                dc.PushTransform(
                    new RotateTransform(Math.Atan2(tangent.Y, tangent.X)
                                        * 180 / Math.PI, width / 2, baseline));
                //dc.PushTransform(
                //    new ScaleTransform(scalingFactor, scalingFactor));

                dc.DrawText(formText, _formattedOrigins[i]);
                dc.Pop();
                dc.Pop();
                //dc.Pop();

                progress -= width / 2 / _pathLength;

                ptOld = point;
            }
        }
Example #33
0
        private void DrawStartAlignedTextPath(DrawingContext dc, PathGeometry pathGeometry,
                                              ISvgAnimatedLength startOffset, TextAlignment alignment)
        {
            if (pathGeometry == null || pathGeometry.Figures == null ||
                pathGeometry.Figures.Count != 1)
            {
                return;
            }

            _pathLength = GetPathFigureLength(pathGeometry.Figures[0]);
            if (_pathLength == 0 || _textLength == 0)
            {
                return;
            }

            //double scalingFactor = pathLength / textLength;
            double scalingFactor = 1.0;   // Not scaling the text to fit...
            double progress      = 0;

            if (startOffset != null)
            {
                ISvgLength offsetLength = startOffset.AnimVal;
                if (offsetLength != null)
                {
                    switch (offsetLength.UnitType)
                    {
                    case SvgLengthType.Percentage:
                        if ((float)offsetLength.ValueInSpecifiedUnits != 0)
                        {
                            progress += offsetLength.ValueInSpecifiedUnits / 100d;
                        }
                        break;
                    }
                }
            }
            //PathGeometry pathGeometry =
            //    new PathGeometry(new PathFigure[] { PathFigure });

            Point ptOld = new Point(0, 0);

            for (int i = 0; i < _formattedChars.Count; i++)
            {
                FormattedText formText = _formattedChars[i];

                double width = scalingFactor *
                               formText.WidthIncludingTrailingWhitespace;
                double baseline = scalingFactor * formText.Baseline;
                progress += width / 2 / _pathLength;
                Point point, tangent;

                pathGeometry.GetPointAtFractionLength(progress,
                                                      out point, out tangent);

                if (i != 0)
                {
                    if (point == ptOld)
                    {
                        break;
                    }
                }

                dc.PushTransform(
                    new TranslateTransform(point.X - width / 2,
                                           point.Y - baseline));
                dc.PushTransform(
                    new RotateTransform(Math.Atan2(tangent.Y, tangent.X)
                                        * 180 / Math.PI, width / 2, baseline));
                //dc.PushTransform(
                //    new ScaleTransform(scalingFactor, scalingFactor));

                dc.DrawText(formText, _formattedOrigins[i]);
                dc.Pop();
                dc.Pop();
                //dc.Pop();

                progress += width / 2 / _pathLength;

                ptOld = point;
            }
        }
Example #34
0
        public virtual void DrawText(double x, double y, FormattedText formattedText)
        {
            Point origin = new Point(x, y);

            DrawText(m_drawingContext, formattedText, origin);
        }
Example #35
0
 protected virtual void DrawText(DrawingContext drawingContext, FormattedText formattedText, Point origin)
 {
     drawingContext.DrawText(formattedText, origin);
 }
Example #36
0
        protected override void OnRender(DrawingContext dc)
        {
            Matrix m         = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
            double dpiFactor = 1 / m.M11;

            RenderOptions.SetEdgeMode(this, EdgeMode.Unspecified);

            const double verticalPadding   = 20;
            const double horizontalPadding = 10;

            Brush brushBackground = new SolidColorBrush(Color.FromRgb(20, 20, 20));
            Brush brushGround     = IsDarkMode ? Brushes.DarkRed : Brushes.DarkGreen;

            Brush brushTextLabel       = new SolidColorBrush((Color)FindResource("ColorControlLightBackground"));
            Brush brushHourLine        = new SolidColorBrush(Color.FromArgb(50, 255, 255, 255));
            Brush brushBodyLine        = IsDarkMode ? Brushes.Red : Brushes.Yellow;
            Color colorDaylight        = IsDarkMode ? Colors.DarkRed : Color.FromRgb(0, 114, 196);
            Pen   penHourLine          = new Pen(brushHourLine, dpiFactor);
            Pen   penBodyLine          = new Pen(brushBodyLine, dpiFactor);
            Pen   penObservationLimits = new Pen(new SolidColorBrush(Color.FromRgb(155, 0, 0)), dpiFactor * 2);

            var bounds = new Rect(0, 0, ActualWidth, ActualHeight);

            dc.PushClip(new RectangleGeometry(bounds));

            dc.PushClip(new RectangleGeometry(new Rect(horizontalPadding, verticalPadding, Math.Max(0, ActualWidth - 2 * horizontalPadding), ActualHeight - 2 * verticalPadding)));

            // background
            dc.DrawRectangle(brushBackground, null, bounds);

            // daylight/night background
            if (sunCoordinatesInterpolated != null)
            {
                double sunAltitudesCount = sunCoordinatesInterpolated.Length;
                LinearGradientBrush linearGradientBrush = new LinearGradientBrush();
                linearGradientBrush.StartPoint  = new Point(horizontalPadding, ActualHeight / 2);
                linearGradientBrush.EndPoint    = new Point(ActualWidth - horizontalPadding, ActualHeight / 2);
                linearGradientBrush.MappingMode = BrushMappingMode.Absolute;
                for (int i = 0; i < sunCoordinatesInterpolated.Length; i++)
                {
                    // -18 degrees is an astronomical night
                    double transp = sunCoordinatesInterpolated[i].Altitude <= -18 ? 0 : (sunCoordinatesInterpolated[i].Altitude < 0 ? (sunCoordinatesInterpolated[i].Altitude + 18) / 18.0 : 1);
                    Color  c      = Color.FromArgb((byte)(transp * 255), colorDaylight.R, colorDaylight.G, colorDaylight.B);
                    double f      = (i / (sunAltitudesCount - 1) + 0.5) % 1;
                    linearGradientBrush.GradientStops.Add(new GradientStop(c, f));
                }
                dc.DrawRectangle(linearGradientBrush, null, bounds);
            }

            // ground overlay
            dc.DrawRectangle(brushGround, null, new Rect(0, ActualHeight / 2, ActualWidth, ActualHeight / 2));

            if (ShowChart && bodyCoordinatesInterpolated != null)
            {
                // body altitude line
                for (int j = 0; j < 2; j++)
                {
                    var figure = new PathFigure();

                    for (int i = 0; i <= bodyCoordinatesInterpolated.Length; i++)
                    {
                        double k      = i;
                        double x      = horizontalPadding + k / (double)bodyCoordinatesInterpolated.Length * (ActualWidth - 2 * horizontalPadding);
                        double alt    = i == bodyCoordinatesInterpolated.Length ? bodyCoordinatesInterpolated[i - 1].Altitude : bodyCoordinatesInterpolated[i].Altitude;
                        double y      = (ActualHeight / 2) - alt / 90.0 * (ActualHeight / 2 - verticalPadding);
                        double offset = -Math.Sign(j - 0.5) * (ActualWidth - 2 * horizontalPadding) / 2;

                        var point = new Point(x + offset, y);
                        if (i == 0)
                        {
                            figure.StartPoint = point;
                        }
                        figure.Segments.Add(new LineSegment(point, true));
                    }

                    var geometry = new PathGeometry();
                    geometry.Figures.Add(figure);
                    dc.DrawGeometry(null, penBodyLine, geometry);
                }
            }

            // dim the body path below horizon
            dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(150, 0, 0, 0)), null, new Rect(0, ActualHeight / 2, ActualWidth, ActualHeight / 2));;

            // time grid
            for (int i = 0; i <= 24; i++)
            {
                double       x          = horizontalPadding + i / 24.0 * (ActualWidth - 2 * horizontalPadding);
                GuidelineSet guidelines = new GuidelineSet();
                guidelines.GuidelinesX.Add(x);
                dc.PushGuidelineSet(guidelines);
                dc.DrawLine(penHourLine, new Point(x, 0), new Point(x, ActualHeight));
                dc.Pop();
            }

            // pop the vertical offset margins
            dc.Pop();

            // visibility box
            {
                double from = horizontalPadding + (FromTime.TotalDays + 0.5) % 1 * (ActualWidth - 2 * horizontalPadding);
                double to   = horizontalPadding + (ToTime.TotalDays + 0.5) % 1 * (ActualWidth - 2 * horizontalPadding);

                var guidelines = new GuidelineSet();
                guidelines.GuidelinesX.Add(to);
                guidelines.GuidelinesX.Add(ActualWidth - 2 * horizontalPadding - from + to);
                dc.PushGuidelineSet(guidelines);
                dc.DrawLine(penObservationLimits, new Point(from, verticalPadding), new Point(from, ActualHeight - verticalPadding));
                dc.DrawLine(penObservationLimits, new Point(to, verticalPadding), new Point(to, ActualHeight - verticalPadding));
                dc.Pop();

                double[] x     = new double[] { from, to };
                string[] label = new string[] { "Begin", "End" };
                for (int i = 0; i < 2; i++)
                {
                    var    text   = new FormattedText(Text.Get($"Planner.VisibilityChart.{label[i]}"), System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Arial"), 10, brushTextLabel);
                    double offset = -text.WidthIncludingTrailingWhitespace / 2;
                    dc.DrawText(text, new Point(x[i] + offset, ActualHeight - verticalPadding / 2 - text.Height / 2));
                }
            }

            // time grid labels
            for (int i = 0; i <= 24; i++)
            {
                double x    = horizontalPadding + i / 24.0 * (ActualWidth - 2 * horizontalPadding);
                var    text = new FormattedText($"{(i + 12) % 24}", System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Arial"), 10, brushTextLabel);
                dc.DrawText(text, new Point(x - text.WidthIncludingTrailingWhitespace / 2, (verticalPadding - text.Height) / 2));
            }
        }
Example #37
0
 public abstract void Highlight(FormattedText text);
Example #38
0
 public abstract void DrawText(FormattedText formattedText, Point origin);
Example #39
0
        public void MovingText_execute()
        {
            switch (mode)
            {
            case "Links nach Rechts":
                counter++;
                textBox.Foreground = new SolidColorBrush(colors[counter % 360]);
                if (Pos.X > -text.Width)
                {
                    Pos.X--;
                }
                else
                {
                    Pos.X = 68;
                }
                break;

            case "Rechts nach Links":
            {
                counter++;
                textBox.Foreground = new SolidColorBrush(colors[counter % 360]);
                if (Pos.X < 68)
                {
                    Pos.X++;
                }
                else
                {
                    Pos.X = -text.Width;
                }
                break;
            }

            case "Oben/Unten":
                counter++;
                textBox.Foreground = new SolidColorBrush(colors[counter % 360]);
                if (Pos.Y < 42)
                {
                    Pos.Y++;
                }
                else
                {
                    Pos.Y = -text.Height;
                }
                break;
            }

            renderTargetBitmap.Clear();
            using (monitor.GetBitmapContext())
            {
                //string time = DateTime.Now.Hour + " : " + DateTime.Now.Minute + " : " + DateTime.Now.Second;

                text = new FormattedText(textBox.Text,
                                         new CultureInfo("de-de"),
                                         FlowDirection.LeftToRight,
                                         new Typeface(textBox.FontFamily, FontStyles.Normal, textBox.FontWeight, new FontStretch()),
                                         textBox.FontSize,
                                         textBox.Foreground);

                text.LineHeight = textBox.FontSize;
                drawingContext  = drawingVisual.RenderOpen();
                drawingContext.DrawText(text, Pos);
                drawingContext.Close();

                renderTargetBitmap.Render(drawingVisual);
                renderTargetBitmap.CopyPixels(new Int32Rect(0, 0, renderTargetBitmap.PixelWidth, renderTargetBitmap.PixelHeight),
                                              monitor.BackBuffer, monitor.BackBufferStride * monitor.PixelHeight, monitor.BackBufferStride);
            }
        }
 public static void SetFormattedText(DependencyObject obj, FormattedText value)
 {
     obj.SetValue(FormattedTextProperty, value);
 }
Example #41
0
        // rendering
        protected override void OnRender(DrawingContext drawingContext)
        {
            // draw background
            drawingContext.PushClip(new RectangleGeometry(new Rect(0, 0, this.ActualWidth, this.ActualHeight)));
            drawingContext.DrawRectangle(this.BackgroundBrush, new Pen(), new Rect(0, 0, this.ActualWidth, this.ActualHeight));

            // draw text
            if (this.Text != String.Empty)
            {
                FormattedText ft = new FormattedText(
                    this.Text,
                    System.Globalization.CultureInfo.CurrentCulture,
                    FlowDirection.LeftToRight,
                    new Typeface(this.FontFamily.Source),
                    this.FontSize, ForegroundBrush);

                var left_margin = 4.0 + this.BorderThickness.Left + LineNumberMarginWidth;
                var top_margin  = 2.0 + this.BorderThickness.Top;

                // Background highlight
                //if (HighlightText != null && HighlightText.Count > 0)
                //{
                //    foreach (string text in HighlightText)
                //    {
                //        int txtEnd = this.Text.Length;
                //        int index = 0;
                //        int lastIndex = this.Text.LastIndexOf(text, StringComparison.OrdinalIgnoreCase);

                //        while (index <= lastIndex)
                //        {
                //            index = this.Text.IndexOf(text, index, StringComparison.OrdinalIgnoreCase);

                //            Geometry geom = ft.BuildHighlightGeometry(new Point(left_margin, top_margin - this.VerticalOffset), index, text.Length);
                //            if (geom != null)
                //            {
                //                drawingContext.DrawGeometry(HighlightBrush, null, geom);
                //            }
                //            index += 1;
                //        }
                //    }
                //}

                //if (SyntaxLexer != null)
                //{
                //    // set color of tokens by syntax rules
                //    foreach (var t in SyntaxLexer.Tokens)
                //    {
                //        SyntaxRuleItem rule = GetSyntaxRule(t.TokenType);
                //        if (rule != null)
                //        {
                //            ft.SetForegroundBrush(rule.Foreground, t.Start, t.Length);
                //        }
                //    }
                //}
                ft.Trimming = TextTrimming.None;

                // left from first char boundary

                double left_border = GetRectFromCharacterIndex(0).Left;
                if (!Double.IsInfinity(left_border))
                {
                    _left_text_border = left_border;
                }

                drawingContext.DrawText(ft, new Point(_left_text_border - this.HorizontalOffset, top_margin - this.VerticalOffset));


                // draw lines
                if (this.GetLastVisibleLineIndex() != -1)
                {
                    LastLineNumberFormat = GetLineNumbers();
                }
                if (LastLineNumberFormat != null)
                {
                    LastLineNumberFormat.SetForegroundBrush(LineNumberBrush);
                    drawingContext.DrawText(LastLineNumberFormat, new Point(3, top_margin));
                }
            }
        }
Example #42
0
        public static BitmapSource DrawFaces(BitmapSource baseImage, Microsoft.ProjectOxford.Face.Contract.Face[] faces, Scores[] emotionScores, string[] celebName)
        {
            if (faces == null)
            {
                return(baseImage);
            }

            Action <DrawingContext, double> drawAction = (drawingContext, annotationScale) =>
            {
                for (int i = 0; i < faces.Length; i++)
                {
                    var face = faces[i];
                    if (face.FaceRectangle == null)
                    {
                        continue;
                    }

                    Rect faceRect = new Rect(
                        face.FaceRectangle.Left, face.FaceRectangle.Top,
                        face.FaceRectangle.Width, face.FaceRectangle.Height);
                    string text = "";

                    if (face.FaceAttributes != null)
                    {
                        text += Aggregation.SummarizeFaceAttributes(face.FaceAttributes);
                    }

                    if (emotionScores?[i] != null)
                    {
                        text += Aggregation.SummarizeEmotion(emotionScores[i]);
                    }

                    if (celebName?[i] != null)
                    {
                        text += celebName[i];
                    }

                    faceRect.Inflate(6 * annotationScale, 6 * annotationScale);

                    double lineThickness = 4 * annotationScale;

                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(s_lineBrush, lineThickness),
                        faceRect);

                    if (text != "")
                    {
                        FormattedText ft = new FormattedText(text,
                                                             CultureInfo.CurrentCulture, FlowDirection.LeftToRight, s_typeface,
                                                             16 * annotationScale, Brushes.Black);

                        var pad = 3 * annotationScale;

                        var ypad   = pad;
                        var xpad   = pad + 4 * annotationScale;
                        var origin = new Point(
                            faceRect.Left + xpad - lineThickness / 2,
                            faceRect.Top - ft.Height - ypad + lineThickness / 2);
                        var rect = ft.BuildHighlightGeometry(origin).GetRenderBounds(null);
                        rect.Inflate(xpad, ypad);

                        drawingContext.DrawRectangle(s_lineBrush, null, rect);
                        drawingContext.DrawText(ft, origin);
                    }
                }
            };

            return(DrawOverlay(baseImage, drawAction));
        }
        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            // 刻度线宽宽度 1 个像素

            Matrix mtx       = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
            double dpiFactor = 1 / mtx.M11;
            Pen    pixelPen  = new Pen(TickColor, 1 * dpiFactor);

            // 绘制标尺

            Point a = new Point(ActualWidth, Start);
            Point b = new Point(ActualWidth - 4, Start);  // 短刻度
            Point c = new Point(ActualWidth - 8, Start);  // 长刻度
            Point t = new Point(ActualWidth - 16, Start);

            int i = 0;

            while (Start + i * MinorTickSpacing <= ActualHeight)
            {
                a.Y = b.Y = c.Y = t.Y = Start + i * MinorTickSpacing;

                GuidelineSet guideline = new GuidelineSet(null, new double[] { a.Y - pixelPen.Thickness / 2 });

                drawingContext.PushGuidelineSet(guideline);

                if (i % MinorTickCount == 0)
                {
                    drawingContext.DrawLine(pixelPen, a, c);

                    FormattedText ft = new FormattedText(
                        Math.Round(StartValue + i * MinorTickSpacingValue, 4).ToString(),
                        CultureInfo.CurrentCulture,
                        FlowDirection.LeftToRight,
                        new Typeface("Arial"),
                        (6 * 96.0 / 72.0),
                        TickTextColor);
                    ft.SetFontWeight(FontWeights.Regular);
                    ft.TextAlignment = TextAlignment.Center;

                    drawingContext.PushTransform(new RotateTransform(-90, t.X, t.Y));
                    drawingContext.DrawText(ft, t);
                    drawingContext.Pop();
                }
                else
                {
                    drawingContext.DrawLine(pixelPen, a, b);
                }

                drawingContext.Pop();

                i++;
            }

            drawingContext.PushGuidelineSet(
                new GuidelineSet(
                    new double[] { ActualWidth - 1 - pixelPen.Thickness / 2 },
                    new double[] { 0 - pixelPen.Thickness / 2, ActualHeight - pixelPen.Thickness / 2 }));

            drawingContext.DrawLine(pixelPen, new Point(0, 0), new Point(ActualWidth, 0));
            drawingContext.DrawLine(pixelPen, new Point(0, ActualHeight), new Point(ActualWidth, ActualHeight));
            drawingContext.DrawLine(pixelPen, new Point(ActualWidth - 1, 0), new Point(ActualWidth - 1, ActualHeight));
            drawingContext.Pop();
        }
 protected AbstractLogEntryValueFormatter(TextSettings textSettings)
 {
     _textSettings  = textSettings;
     _formattedText = null;
 }
Example #45
0
        /// <summary>
        /// Parses the keyword «\fontsize».
        /// </summary>
        private void ParseFontSize(FormattedText formattedText, int nestingLevel)
        {
            AssertSymbol(Symbol.FontSize);
            ReadCode();

            AssertSymbol(Symbol.ParenLeft);
            ReadCode();
            //NYI: Check token for correct Unit format
            formattedText.Font.Size = Token;
            ReadCode();
            AssertSymbol(Symbol.ParenRight);
            ReadCode();

            AssertSymbol(Symbol.BraceLeft);
            ParseFormattedText(formattedText.Elements, nestingLevel);
            AssertSymbol(Symbol.BraceRight);
        }
        public static BitmapSource DrawFaces(BitmapSource baseImage, Microsoft.ProjectOxford.Face.Contract.Face[] faces, EmotionScores[] emotionScores, string[] celebName, Control form)
        {
            if (faces == null)
            {
                return(baseImage);
            }

            Action <DrawingContext, double> drawAction = (drawingContext, annotationScale) =>
            {
                //ImageSource imgsrc = null;
                for (int i = 0; i < faces.Length; i++)
                {
                    var face = faces[i];
                    if (face.FaceRectangle == null)
                    {
                        continue;
                    }

                    Rect faceRect = new Rect(
                        face.FaceRectangle.Left, face.FaceRectangle.Top,
                        face.FaceRectangle.Width, face.FaceRectangle.Height);

                    string text = "";

                    if (face.FaceAttributes != null)
                    {
                        text += Aggregation.SummarizeFaceAttributes(face.FaceAttributes);
                    }

                    if (emotionScores?[i] != null)
                    {
                        text += Aggregation.SummarizeEmotion(emotionScores[i]);
                    }

                    if (celebName?[i] != null)
                    {
                        text += celebName[i];
                    }

                    faceRect.Inflate(6 * annotationScale, 6 * annotationScale);

                    double lineThickness = 4 * annotationScale;

                    drawingContext.DrawRectangle(
                        Brushes.Transparent,
                        new Pen(s_lineBrush, lineThickness),
                        faceRect);


                    ClearEmojis(form);

                    if (text != "")
                    {
                        text = GetEmotionName(text);
                        FormattedText ft = new FormattedText(text,
                                                             CultureInfo.CurrentCulture, System.Windows.FlowDirection.LeftToRight, s_typeface,
                                                             16 * annotationScale, Brushes.Black);

                        var pad = 6 * annotationScale;

                        var ypad   = pad;
                        var xpad   = pad + 10 * annotationScale;
                        var origin = new System.Windows.Point(
                            faceRect.Left + xpad - lineThickness / 2,
                            faceRect.Top - ft.Height - ypad + lineThickness / 2);

                        var rect = ft.BuildHighlightGeometry(origin).GetRenderBounds(null);
                        rect.Inflate(xpad, ypad);

                        drawingContext.DrawRectangle(s_lineBrush, null, rect);


                        drawingContext.DrawText(ft, origin);

                        var x = baseImage.DpiX + faceRect.X;
                        var y = baseImage.DpiY + faceRect.Y;



                        Console.WriteLine("------------------");
                        Console.WriteLine("baseImage width:  " + baseImage.Width);
                        Console.WriteLine("form width:  " + form.Width);
                        Console.WriteLine("faceRect width:  " + faceRect.Width);
                        Console.WriteLine("ft width:  " + ft.Width);
                        Console.WriteLine("x:  " + x);
                        Console.WriteLine("y:  " + y);
                        Console.WriteLine("------------------");


                        var originEmoji = new System.Windows.Point(
                            faceRect.Left + lineThickness,
                            faceRect.Top - ((ft.Height - ypad + lineThickness / 2) * 8));

                        Rect rectEmoji = new Rect(originEmoji, new Size(90, 90));
                        drawingContext.DrawRectangle(null, null, rectEmoji);

                        var displayEmoji = new DisplayEmotion();
                        displayEmoji.ShowEmoji(drawingContext, rectEmoji, text);
                    }
                }
            };

            return(DrawOverlay(baseImage, drawAction));
        }
        public void Invalidate()
        {
            GraphCanvas.Children.Clear();
            GraphCanvas.Children.Add(graphHost);

            graphHost.Children.Clear();
            var drawingVisual  = new DrawingVisual();
            var drawingContext = drawingVisual.RenderOpen();

            foreach (var edge in Globals.EdgesData)
            {
                Point from = edge.From.Coordinates;
                Point to   = edge.To.Coordinates;

                var center       = new Point((from.X + to.X) / 2, (from.Y + to.Y) / 2);
                var centerSecond = new Point((from.X + to.X) / 2, (from.Y + to.Y) / 2);

                Pen pen = new Pen(edge.Color, edge.Thickness);

                if (edge.Directed)
                {
                    double d = Math.Sqrt(Math.Pow(to.X - from.X, 2) + Math.Pow(to.Y - from.Y, 2));

                    double X = to.X - from.X;
                    double Y = to.Y - from.Y;

                    centerSecond.X = center.X - (X / d) * 15;
                    centerSecond.Y = center.Y - (Y / d) * 15;

                    double Xp = to.Y - from.Y;
                    double Yp = from.X - to.X;

                    var left  = new Point((centerSecond.X + (Xp / d) * 6), (centerSecond.Y + (Yp / d) * 6));
                    var right = new Point((centerSecond.X - (Xp / d) * 6), (centerSecond.Y - (Yp / d) * 6));

                    drawingContext.DrawLine(pen, center, left);
                    drawingContext.DrawLine(pen, center, right);
                }

                drawingContext.DrawLine(pen, edge.From.Coordinates, edge.To.Coordinates);

                if (edge.Weight > 1)
                {
                    if (edge.Directed && (Globals.Matrix[edge.To.Index, edge.From.Index] > 0))
                    {
                        drawingContext.DrawText(new FormattedText(edge.Weight.ToString(),
                                                                  CultureInfo.GetCultureInfo("en-us"),
                                                                  ((from.X < to.X && from.Y < to.Y) || (from.X > to.X && from.Y > to.Y)) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight,
                                                                  new Typeface("Romanic"),
                                                                  30, Brushes.Red), new Point((from.X + center.X) / 2, (from.Y + center.Y) / 2));
                    }
                    else
                    {
                        drawingContext.DrawText(new FormattedText(edge.Weight.ToString(),
                                                                  CultureInfo.GetCultureInfo("en-us"),
                                                                  ((from.X < to.X && from.Y < to.Y) || (from.X > to.X && from.Y > to.Y)) ? FlowDirection.RightToLeft : FlowDirection.LeftToRight,
                                                                  new Typeface("Romanic"),
                                                                  30, Brushes.Red),
                                                center);
                    }
                }
            }

            foreach (var vertex in Globals.VertexData)
            {
                drawingContext.DrawEllipse(vertex.Color, Globals.BasePen, vertex.Coordinates, Globals.VertRadius, Globals.VertRadius);

                FormattedText txt = new FormattedText((vertex.Text == "") ? vertex.Index.ToString() : vertex.Text,
                                                      CultureInfo.GetCultureInfo("en-us"),
                                                      FlowDirection.LeftToRight,
                                                      new Typeface("Romanic"),
                                                      20, Themes.ColorOfTheTextOfVertex);

                drawingContext.DrawText(txt, new Point(vertex.Coordinates.X + ((vertex.Text == "") ? vertex.Index.ToString().Length *(-5) : vertex.Text.Length * (-5)), vertex.Coordinates.Y - 10));
            }

            drawingContext.Close();
            graphHost.Children.Add(drawingVisual);
        }
        public override void RenderText(SvgTextContentElement element, ref Point ctp,
                                        string text, double rotate, WpfTextPlacement placement)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            double emSize         = GetComputedFontSize(element);
            var    fontFamilyInfo = GetTextFontFamilyInfo(element);

            WpfTextStringFormat stringFormat = GetTextStringFormat(element);

            if (fontFamilyInfo.FontFamilyType == WpfFontFamilyType.Svg)
            {
                WpfTextTuple textInfo = new WpfTextTuple(fontFamilyInfo, emSize, stringFormat, element);
                this.RenderText(textInfo, ref ctp, text, rotate, placement);
                return;
            }

            FontFamily  fontFamily  = fontFamilyInfo.Family;
            FontStyle   fontStyle   = fontFamilyInfo.Style;
            FontWeight  fontWeight  = fontFamilyInfo.Weight;
            FontStretch fontStretch = fontFamilyInfo.Stretch;

            // Fix the use of Postscript fonts...
            WpfFontFamilyVisitor fontFamilyVisitor = _context.FontFamilyVisitor;

            if (!string.IsNullOrWhiteSpace(_actualFontName) && fontFamilyVisitor != null)
            {
                WpfFontFamilyInfo familyInfo = fontFamilyVisitor.Visit(_actualFontName,
                                                                       fontFamilyInfo, _context);
                if (familyInfo != null && !familyInfo.IsEmpty)
                {
                    fontFamily  = familyInfo.Family;
                    fontWeight  = familyInfo.Weight;
                    fontStyle   = familyInfo.Style;
                    fontStretch = familyInfo.Stretch;
                }
            }

            WpfSvgPaint fillPaint = new WpfSvgPaint(_context, element, "fill");
            Brush       textBrush = fillPaint.GetBrush();

            WpfSvgPaint strokePaint = new WpfSvgPaint(_context, element, "stroke");
            Pen         textPen     = strokePaint.GetPen();

            if (textBrush == null && textPen == null)
            {
                return;
            }
            bool isForcedPathMode = false;

            if (textBrush == null)
            {
                // If here, then the pen is not null, and so the fill cannot be null.
                // We set this to transparent for stroke only text path...
                textBrush = Brushes.Transparent;
            }
            else
            {
                // WPF gradient fill does not work well on text, use geometry to render it
                isForcedPathMode = (fillPaint.FillType == WpfFillType.Gradient);
            }
            if (textPen != null)
            {
                textPen.LineJoin = PenLineJoin.Round; // Better for text rendering
                isForcedPathMode = true;
            }

            TextDecorationCollection textDecors = GetTextDecoration(element);
            TextAlignment            alignment  = stringFormat.Alignment;

            bool   hasWordSpacing = false;
            string wordSpaceText  = element.GetAttribute("word-spacing");
            double wordSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(wordSpaceText) &&
                double.TryParse(wordSpaceText, out wordSpacing) && !wordSpacing.Equals(0))
            {
                hasWordSpacing = true;
            }

            bool   hasLetterSpacing = false;
            string letterSpaceText  = element.GetAttribute("letter-spacing");
            double letterSpacing    = 0;

            if (!string.IsNullOrWhiteSpace(letterSpaceText) &&
                double.TryParse(letterSpaceText, out letterSpacing) && !letterSpacing.Equals(0))
            {
                hasLetterSpacing = true;
            }

            bool isRotatePosOnly = false;

            IList <WpfTextPosition> textPositions = null;
            int textPosCount = 0;

            if ((placement != null && placement.HasPositions))
            {
                textPositions   = placement.Positions;
                textPosCount    = textPositions.Count;
                isRotatePosOnly = placement.IsRotateOnly;
            }

            var typeFace = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);

            if (hasLetterSpacing || hasWordSpacing || textPositions != null)
            {
                for (int i = 0; i < text.Length; i++)
                {
                    var           nextText      = new string(text[i], 1);
                    FormattedText formattedText = new FormattedText(nextText,
                                                                    _context.CultureInfo, stringFormat.Direction, typeFace, emSize, textBrush);

                    formattedText.TextAlignment = stringFormat.Alignment;
                    formattedText.Trimming      = stringFormat.Trimming;

                    if (textDecors != null && textDecors.Count != 0)
                    {
                        formattedText.SetTextDecorations(textDecors);
                    }

                    WpfTextPosition?textPosition = null;
                    if (textPositions != null && i < textPosCount)
                    {
                        textPosition = textPositions[i];
                    }

                    //float xCorrection = 0;
                    //if (alignment == TextAlignment.Left)
                    //    xCorrection = emSize * 1f / 6f;
                    //else if (alignment == TextAlignment.Right)
                    //    xCorrection = -emSize * 1f / 6f;

                    double yCorrection = formattedText.Baseline;

                    float rotateAngle = (float)rotate;
                    if (textPosition != null)
                    {
                        if (!isRotatePosOnly)
                        {
                            Point pt = textPosition.Value.Location;
                            ctp.X = pt.X;
                            ctp.Y = pt.Y;
                        }
                        rotateAngle = (float)textPosition.Value.Rotation;
                    }
                    Point textStart = ctp;

                    RotateTransform rotateAt = null;
                    if (!rotateAngle.Equals(0))
                    {
                        rotateAt = new RotateTransform(rotateAngle, textStart.X, textStart.Y);
                        _drawContext.PushTransform(rotateAt);
                    }

                    Point textPoint = new Point(textStart.X, textStart.Y - yCorrection);

                    if (_context.TextAsGeometry || isForcedPathMode)
                    {
                        Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                        if (textGeometry != null && !textGeometry.IsEmpty())
                        {
                            _drawContext.DrawGeometry(textBrush, textPen, ExtractTextPathGeometry(textGeometry));

                            this.IsTextPath = true;
                        }
                        else
                        {
                            _drawContext.DrawText(formattedText, textPoint);
                        }
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }

                    //float bboxWidth = (float)formattedText.Width;
                    double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                    if (alignment == TextAlignment.Center)
                    {
                        bboxWidth /= 2f;
                    }
                    else if (alignment == TextAlignment.Right)
                    {
                        bboxWidth = 0;
                    }

                    //ctp.X += bboxWidth + emSize / 4 + spacing;
                    if (hasLetterSpacing)
                    {
                        ctp.X += bboxWidth + letterSpacing;
                    }
                    if (hasWordSpacing && char.IsWhiteSpace(text[i]))
                    {
                        if (hasLetterSpacing)
                        {
                            ctp.X += wordSpacing;
                        }
                        else
                        {
                            ctp.X += bboxWidth + wordSpacing;
                        }
                    }
                    else
                    {
                        if (!hasLetterSpacing)
                        {
                            ctp.X += bboxWidth;
                        }
                    }

                    if (rotateAt != null)
                    {
                        _drawContext.Pop();
                    }
                }
            }
            else
            {
                FormattedText formattedText = new FormattedText(text, _context.CultureInfo,
                                                                stringFormat.Direction, typeFace, emSize, textBrush);

                formattedText.TextAlignment = stringFormat.Alignment;
                formattedText.Trimming      = stringFormat.Trimming;

                if (textDecors != null && textDecors.Count != 0)
                {
                    formattedText.SetTextDecorations(textDecors);
                }

                //float xCorrection = 0;
                //if (alignment == TextAlignment.Left)
                //    xCorrection = emSize * 1f / 6f;
                //else if (alignment == TextAlignment.Right)
                //    xCorrection = -emSize * 1f / 6f;

                double yCorrection = formattedText.Baseline;

                float rotateAngle = (float)rotate;
                Point textPoint   = new Point(ctp.X, ctp.Y - yCorrection);

                RotateTransform rotateAt = null;
                if (!rotateAngle.Equals(0))
                {
                    rotateAt = new RotateTransform(rotateAngle, ctp.X, ctp.Y);
                    _drawContext.PushTransform(rotateAt);
                }

                if (_context.TextAsGeometry || isForcedPathMode)
                {
                    Geometry textGeometry = formattedText.BuildGeometry(textPoint);
                    if (textGeometry != null && !textGeometry.IsEmpty())
                    {
                        _drawContext.DrawGeometry(textBrush, textPen,
                                                  ExtractTextPathGeometry(textGeometry));

                        this.IsTextPath = true;
                    }
                    else
                    {
                        _drawContext.DrawText(formattedText, textPoint);
                    }
                }
                else
                {
                    _drawContext.DrawText(formattedText, textPoint);
                }

                //float bboxWidth = (float)formattedText.Width;
                double bboxWidth = formattedText.WidthIncludingTrailingWhitespace;
                if (alignment == TextAlignment.Center)
                {
                    bboxWidth /= 2f;
                }
                else if (alignment == TextAlignment.Right)
                {
                    bboxWidth = 0;
                }

                //ctp.X += bboxWidth + emSize / 4;
                ctp.X += bboxWidth;

                if (rotateAt != null)
                {
                    _drawContext.Pop();
                }
            }
        }
Example #49
0
 /// <summary>
 /// Sets the control's text and formatting. Also resets the rich text tag count.
 /// </summary>
 /// <param name="formattedText">Formatted text.</param>
 public override void SetFormattedText(FormattedText formattedText)
 {
     base.SetFormattedText (formattedText);
     ResetClosureTags ();
 }
Example #50
0
 private void UpdateText()
 {
     formattedText = new FormattedText("Text!", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Helvetica"), 12, BrushCache.GetBrush(Colors.White));
 }
Example #51
0
 async Task IConsoleHost.Write(FormattedText text)
 {
     foreach (var run in text.Runs)
     {
         await Write(run);
     }
 }
        private DrawingVisual CreateCurveDrawingVisual(
            NormalizerEngine engine)
        {
            DrawingVisual drawingVisual = new DrawingVisual();

            // Create a drawing and draw it in the DrawingContext.
            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
            {
                Pen  pen  = new Pen(Brushes.Black, 1);
                Rect rect =
                    new Rect(new Point(40, 40), new Point(660, 300)); // range of (600, 260)
                drawingContext.DrawRectangle(Brushes.Transparent, pen, rect);
                List <double> x = engine.Retention;
                List <double> y = engine.Guis;

                // draw points
                Pen    p     = new Pen(Brushes.Blue, 3);
                double max_x = Math.Ceiling(x.Max() / 10) * 10;
                for (int i = 0; i < x.Count; i++)
                {
                    double x1    = x[i] * 600.0 / max_x + 40;
                    double y1    = 300.0 - y[i] * 20.0;
                    Point  point = new Point(x1, y1);
                    drawingContext.DrawEllipse(Brushes.Black, p, point, 1, 1);
                }

                // draw xtics per 5 min
                Pen    line    = new Pen(Brushes.Black, 1);
                double max_min = Math.Ceiling(max_x / 5) * 5;
                for (int i = 5; i <= max_min; i += 5)
                {
                    double x1 = i * 600.0 / max_x + 40;
                    double y1 = 300;
                    double y2 = 290;
                    double y3 = 310;
                    Point  p1 = new Point(x1, y1);
                    Point  p2 = new Point(x1, y2);
                    Point  p3 = new Point(x1 - 5, y3);
                    drawingContext.DrawLine(line, p1, p2);
                    if (i % 2 == 0)
                    {
                        FormattedText formattedText = new FormattedText(
                            i.ToString(),
                            CultureInfo.GetCultureInfo("en-us"),
                            FlowDirection.LeftToRight,
                            new Typeface("Times New Roman"),
                            11,
                            Brushes.Black);
                        drawingContext.DrawText(formattedText, p3);
                    }
                }
                FormattedText x_title = new FormattedText(
                    "Time (min)",
                    CultureInfo.GetCultureInfo("en-us"),
                    FlowDirection.LeftToRight,
                    new Typeface("Times New Roman"),
                    11,
                    Brushes.Black);
                drawingContext.DrawText(x_title, new Point(320, 330));

                // draw ytics per 1 unit
                for (int i = 1; i <= 12; i++)
                {
                    double x1 = 40;
                    double x2 = 50;
                    double x3 = 26;
                    double y1 = 300.0 - i * 20.0;
                    Point  p1 = new Point(x1, y1);
                    Point  p2 = new Point(x2, y1);
                    Point  p3 = new Point(x3, y1 - 5);
                    drawingContext.DrawLine(line, p1, p2);
                    if (i % 2 == 0)
                    {
                        FormattedText formattedText = new FormattedText(
                            i.ToString(),
                            CultureInfo.GetCultureInfo("en-us"),
                            FlowDirection.LeftToRight,
                            new Typeface("Times New Roman"),
                            11,
                            Brushes.Black);
                        drawingContext.DrawText(formattedText, p3);
                    }
                }

                FormattedText y_title = new FormattedText(
                    "Units",
                    CultureInfo.GetCultureInfo("en-us"),
                    FlowDirection.LeftToRight,
                    new Typeface("Times New Roman"),
                    11,
                    Brushes.Black);
                drawingContext.DrawText(y_title, new Point(10, 40));


                // draw curve
                List <Point> points = new List <Point>();
                Pen          curve  = new Pen(Brushes.Red, 1);
                double       min_x  = Math.Floor(x.Min());
                for (double i = min_x; i <= max_min; i += 0.01)
                {
                    double x1 = i * 600 / max_x + 40;
                    double y1 = 300.0 - engine.Normalize(i) * 20.0;
                    points.Add(new Point(x1, y1));
                }
                for (int i = 0; i < points.Count - 1; i++)
                {
                    drawingContext.DrawLine(curve, points[i], points[i + 1]);
                }
            }
            return(drawingVisual);
        }
Example #53
0
		public void SetFormattedText (FormattedText text)
		{
			Label.Text = text.Text;
			var list = new FastPangoAttrList ();
			indexer = new TextIndexer (text.Text);
			list.AddAttributes (indexer, text.Attributes);
			gtk_label_set_attributes (Label.Handle, list.Handle);

			if (links != null)
				links.Clear ();

			foreach (var attr in text.Attributes.OfType<LinkTextAttribute> ()) {
				LabelLink ll = new LabelLink () {
					StartIndex = indexer.IndexToByteIndex (attr.StartIndex),
					EndIndex = indexer.IndexToByteIndex (attr.StartIndex + attr.Count),
					Target = attr.Target
				};
				if (links == null) {
					links = new List<LabelLink> ();
					EnableLinkEvents ();
				}
				links.Add (ll);
			}

			if (links == null || links.Count == 0) {
				links = null;
				indexer = null;
			}
		}
Example #54
0
        protected override void OnRefresh()
        {
            RotarySwitch rotarySwitch = Visual as RotarySwitch;

            if (rotarySwitch != null)
            {
                _imageRect.Width  = rotarySwitch.Width;
                _imageRect.Height = rotarySwitch.Height;
                _image            = ConfigManager.ImageManager.LoadImage(rotarySwitch.KnobImage);
                _imageBrush       = new ImageBrush(_image);
                _center           = new Point(rotarySwitch.Width / 2d, rotarySwitch.Height / 2d);

                _lines     = new GeometryDrawing();
                _lines.Pen = new Pen(new SolidColorBrush(rotarySwitch.LineColor), rotarySwitch.LineThickness);

                _labels.Clear();

                Vector v1            = new Point(_center.X, 0) - _center;
                double lineLength    = v1.Length * rotarySwitch.LineLength;
                double labelDistance = v1.Length * rotarySwitch.LabelDistance;
                v1.Normalize();
                GeometryGroup lineGroup  = new GeometryGroup();
                Brush         labelBrush = new SolidColorBrush(rotarySwitch.LabelColor);
                foreach (RotarySwitchPosition position in rotarySwitch.Positions)
                {
                    Matrix m1 = new Matrix();
                    m1.Rotate(position.Rotation);

                    if (rotarySwitch.DrawLines)
                    {
                        Vector v2 = v1 * m1;

                        Point startPoint = _center;
                        Point endPoint   = startPoint + (v2 * lineLength);

                        lineGroup.Children.Add(new LineGeometry(startPoint, endPoint));
                    }

                    if (rotarySwitch.DrawLabels)
                    {
                        FormattedText labelText = rotarySwitch.LabelFormat.GetFormattedText(labelBrush, position.Name);
                        labelText.TextAlignment = TextAlignment.Center;
                        labelText.MaxTextWidth  = rotarySwitch.Width;
                        labelText.MaxTextHeight = rotarySwitch.Height;

                        if (rotarySwitch.MaxLabelHeight > 0d && rotarySwitch.MaxLabelHeight < rotarySwitch.Height)
                        {
                            labelText.MaxTextHeight = rotarySwitch.MaxLabelHeight;
                        }
                        if (rotarySwitch.MaxLabelWidth > 0d && rotarySwitch.MaxLabelWidth < rotarySwitch.Width)
                        {
                            labelText.MaxTextWidth = rotarySwitch.MaxLabelWidth;
                        }

                        Point location = _center + (v1 * m1 * labelDistance);
                        if (position.Rotation <= 10d || position.Rotation >= 350d)
                        {
                            location.X -= labelText.MaxTextWidth / 2d;
                            location.Y -= labelText.Height;
                        }
                        else if (position.Rotation < 170d)
                        {
                            location.X -= (labelText.MaxTextWidth - labelText.Width) / 2d;
                            location.Y -= labelText.Height / 2d;
                        }
                        else if (position.Rotation <= 190d)
                        {
                            location.X -= labelText.MaxTextWidth / 2d;
                        }
                        else
                        {
                            location.X -= (labelText.MaxTextWidth + labelText.Width) / 2d;
                            location.Y -= labelText.Height / 2d;
                        }

                        _labels.Add(new SwitchPositionLabel(labelText, location));
                    }
                }
                _lines.Geometry = lineGroup;
                _lines.Freeze();
            }
            else
            {
                _image      = null;
                _imageBrush = null;
                _lines      = null;
                _labels.Clear();
            }
        }
Example #55
0
 public void SetFormattedText(FormattedText text)
 {
 }
Example #56
0
 public SwitchPositionLabel(FormattedText text, Point location)
 {
     Location = location;
     Text     = text;
 }
Example #57
0
 void ForceUpdateText()
 {
     FText     = new FormattedText(text, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Font, FontSize, Foreground);
     IsChanged = true;
 }
Example #58
0
        private void PlotRow()
        {
            var stackedChart = Chart as IStackedBar;

            if (stackedChart == null)
            {
                return;
            }

            var stackedSeries = Chart.Series.OfType <StackedBarSeries>().ToList();

            var serieIndex = stackedSeries.IndexOf(this);
            var unitW      = ToPlotArea(Chart.Max.Y - 1, AxisTags.Y) - Chart.PlotArea.Y + 5;
            var overflow   = unitW - stackedChart.MaxColumnWidth > 0 ? unitW - stackedChart.MaxColumnWidth : 0;

            unitW = unitW > stackedChart.MaxColumnWidth ? stackedChart.MaxColumnWidth : unitW;
            var       pointPadding  = .1 * unitW;
            const int seriesPadding = 2;
            var       h             = unitW - 2 * pointPadding;

            var f = Chart.GetFormatter(Chart.Invert ? Chart.AxisX : Chart.AxisY);

            foreach (var point in Values.Points)
            {
                var visual = GetVisual(point);

                var helper = stackedChart.IndexTotals[(int)point.Y];
                var w      = ToPlotArea(helper.Total, AxisTags.X) - ToPlotArea(Chart.Min.X, AxisTags.X);
                var rh     = w * (point.X / helper.Total);
                if (double.IsNaN(rh))
                {
                    return;
                }
                var stackedW = w * (helper.Stacked.ContainsKey(serieIndex) ? (helper.Stacked[serieIndex].Stacked / helper.Total) : 0);

                var height = Math.Max(0, h - seriesPadding);

                visual.PointShape.Height = height;
                visual.HoverShape.Height = height;
                visual.HoverShape.Width  = rh;

                Canvas.SetTop(visual.PointShape, ToPlotArea(point.Y, AxisTags.Y) + pointPadding + overflow / 2);
                Canvas.SetTop(visual.HoverShape, ToPlotArea(point.Y, AxisTags.Y) + pointPadding + overflow / 2);
                Canvas.SetLeft(visual.HoverShape, ToPlotArea(Chart.Min.X, AxisTags.X) + stackedW);
                Panel.SetZIndex(visual.HoverShape, int.MaxValue);

                if (!Chart.DisableAnimation)
                {
                    var wAnim = new DoubleAnimation
                    {
                        From     = visual.IsNew ? 0 : visual.PointShape.Width,
                        To       = rh,
                        Duration = TimeSpan.FromMilliseconds(500)
                    };
                    var leftAnim = new DoubleAnimation
                    {
                        From     = visual.IsNew ? ToPlotArea(Chart.Min.X, AxisTags.X) : Canvas.GetLeft(visual.PointShape),
                        To       = ToPlotArea(Chart.Min.X, AxisTags.X) + stackedW,
                        Duration = TimeSpan.FromMilliseconds(500)
                    };
                    visual.PointShape.BeginAnimation(WidthProperty, wAnim);
                    visual.PointShape.BeginAnimation(Canvas.LeftProperty, leftAnim);
                }
                else
                {
                    visual.PointShape.Width = rh;
                    Canvas.SetLeft(visual.PointShape, ToPlotArea(Chart.Min.X, AxisTags.X) + stackedW);
                }

                if (DataLabels)
                {
                    var tb = BuildATextBlock(0);
                    var te = f(Chart.Invert ? point.X : point.Y);
                    var ft = new FormattedText(
                        te,
                        CultureInfo.CurrentCulture,
                        FlowDirection.LeftToRight,
                        new Typeface(FontFamily, FontStyle, FontWeight, FontStretch), FontSize, Brushes.Black);
                    Canvas.SetLeft(tb, Canvas.GetLeft(visual.HoverShape) + visual.HoverShape.Width * .5 - ft.Width * .5);
                    Canvas.SetTop(tb, Canvas.GetTop(visual.HoverShape) + visual.HoverShape.Height * .5 - ft.Height * .5);
                    Panel.SetZIndex(tb, int.MaxValue - 1);

                    tb.Text       = te;
                    tb.Visibility = Visibility.Hidden;
                    Chart.Canvas.Children.Add(tb);
                    Chart.Shapes.Add(tb);
                    if (!Chart.DisableAnimation)
                    {
                        var t = new DispatcherTimer {
                            Interval = TimeSpan.FromMilliseconds(animationSpeed)
                        };
                        t.Tick += (sender, args) =>
                        {
                            tb.Visibility = Visibility.Visible;
                            var fadeIn = new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(animationSpeed));
                            tb.BeginAnimation(OpacityProperty, fadeIn);
                            t.Stop();
                        };
                        t.Start();
                    }
                    else
                    {
                        tb.Visibility = Visibility.Visible;
                    }
                }

                if (visual.IsNew)
                {
                    Chart.ShapesMapper.Add(new ShapeMap
                    {
                        Series     = this,
                        HoverShape = visual.HoverShape,
                        Shape      = visual.PointShape,
                        ChartPoint = point
                    });
                    Chart.Canvas.Children.Add(visual.PointShape);
                    Chart.Canvas.Children.Add(visual.HoverShape);
                    Shapes.Add(visual.PointShape);
                    Shapes.Add(visual.HoverShape);
                    Panel.SetZIndex(visual.HoverShape, int.MaxValue);
                    Panel.SetZIndex(visual.PointShape, int.MaxValue - 2);
                    visual.HoverShape.MouseDown  += Chart.DataMouseDown;
                    visual.HoverShape.MouseEnter += Chart.DataMouseEnter;
                    visual.HoverShape.MouseLeave += Chart.DataMouseLeave;
                }
            }
        }
Example #59
0
		void ICmpRenderer.Draw(IDrawDevice device)
		{
			Profile.BeginMeasure(@"ProfileRenderer");
			Canvas canvas = new Canvas(device);
			canvas.CurrentState.SetMaterial(new BatchInfo(DrawTechnique.Alpha, ColorRgba.White, null));
			
			bool anyTextReport = this.textReportPerf || this.textReportStat;
			bool anyGraph = this.drawGraphs && this.counterGraphs.Count > 0;

			// Determine geometry
			int areaWidth = (int)device.TargetSize.X - 20;
			if (anyGraph && anyTextReport)
				areaWidth = (areaWidth - 10) / 2;
			Rect textReportRect = new Rect(
				10, 
				10, 
				anyTextReport ? areaWidth : 0, 
				(int)device.TargetSize.Y - 20);
			Rect graphRect = new Rect(
				anyTextReport ? (textReportRect.MaximumX + 10) : 10, 
				10, 
				anyGraph ? areaWidth : 0, 
				(int)device.TargetSize.Y - 20);

			// Text Reports
			if (anyTextReport)
			{
				// Update Report
				IEnumerable<ProfileCounter> counters = Profile.GetUsedCounters();
				if (!this.textReportPerf) counters = counters.Where(c => !(c is TimeCounter));
				if (!this.textReportStat) counters = counters.Where(c => !(c is StatCounter));
				if (this.textReport == null || (Time.MainTimer - this.textReportLast).TotalMilliseconds > this.updateInterval)
				{
					string report = Profile.GetTextReport(counters, this.textReportOptions | ReportOptions.FormattedText);

					if (this.textReport == null)
					{
						this.textReport = new FormattedText();
						this.textReport.Fonts = new[] { Font.GenericMonospace8 };
					}
					this.textReport.MaxWidth = (int)textReportRect.W;
					this.textReport.SourceText = report;
					this.textReportLast = Time.MainTimer;
				}

				// Draw Report
				canvas.DrawTextBackground(textReport, textReportRect.X, textReportRect.Y);
				canvas.DrawText(textReport, ref textReportTextVert, ref textReportIconVert, textReportRect.X, textReportRect.Y);
			}

			// Counter Graphs
			if (anyGraph)
			{
				// Mark graph cache as unused
				foreach (GraphCacheEntry entry in this.graphCache.Values)
				{
					entry.WasUsed = false;
				}

				int space = 5;
				int graphY = (int)graphRect.Y;
				int graphH = MathF.Min((int)(graphRect.H / this.counterGraphs.Count) - space, (int)graphRect.W / 2);
				foreach (string counterName in this.counterGraphs)
				{
					ProfileCounter counter = Profile.GetCounter<ProfileCounter>(counterName);
					if (counter == null) return;

					// Create or retrieve graph cache entry
					GraphCacheEntry cache = null;
					if (!this.graphCache.TryGetValue(counterName, out cache))
					{
						cache = new GraphCacheEntry();
						cache.GraphValues = new float[ProfileCounter.ValueHistoryLen];
						cache.GraphColors = new ColorRgba[ProfileCounter.ValueHistoryLen];
						this.graphCache[counterName] = cache;
					}
					cache.WasUsed = true;

					float cursorRatio = 0.0f;
					if (counter is TimeCounter)
					{
						TimeCounter timeCounter = counter as TimeCounter;
						for (int i = 0; i < ProfileCounter.ValueHistoryLen; i++)
						{
							float factor = timeCounter.ValueGraph[i] / Time.MsPFMult;
							cache.GraphValues[i] = factor * 0.75f;
							cache.GraphColors[i] = ColorRgba.Lerp(ColorRgba.White, ColorRgba.Red, factor);
						}
						canvas.CurrentState.ColorTint = ColorRgba.Black.WithAlpha(0.5f);
						canvas.FillRect(graphRect.X, graphY, graphRect.W, graphH);
						canvas.CurrentState.ColorTint = ColorRgba.White;
						canvas.DrawHorizontalGraph(cache.GraphValues, cache.GraphColors, ref cache.VertGraph, graphRect.X, graphY, graphRect.W, graphH);
						cursorRatio = (float)timeCounter.ValueGraphCursor / (float)ProfileCounter.ValueHistoryLen;
					}
					else if (counter is StatCounter)
					{
						StatCounter statCounter = counter as StatCounter;
						for (int i = 0; i < ProfileCounter.ValueHistoryLen; i++)
						{
							cache.GraphValues[i] = (float)(statCounter.ValueGraph[i] - statCounter.MinValue) / statCounter.MaxValue;
							cache.GraphColors[i] = ColorRgba.White;
						}
						canvas.CurrentState.ColorTint = ColorRgba.Black.WithAlpha(0.5f);
						canvas.FillRect(graphRect.X, graphY, graphRect.W, graphH);
						canvas.CurrentState.ColorTint = ColorRgba.White;
						canvas.DrawHorizontalGraph(cache.GraphValues, cache.GraphColors, ref cache.VertGraph, graphRect.X, graphY, graphRect.W, graphH);
						cursorRatio = (float)statCounter.ValueGraphCursor / (float)ProfileCounter.ValueHistoryLen;
					}
					
					canvas.DrawText(new string[] { counter.FullName }, ref cache.VertText, graphRect.X, graphY);
					canvas.DrawLine(graphRect.X + graphRect.W * cursorRatio, graphY, graphRect.X + graphRect.W * cursorRatio, graphY + graphH);

					graphY += graphH + space;
				}

				// Remove unused graph cache entries
				foreach (var pair in this.graphCache.ToArray())
				{
					if (!pair.Value.WasUsed)
					{
						pair.Value.GraphColors = null;
						pair.Value.GraphValues = null;
						pair.Value.VertGraph = null;
						pair.Value.VertText = null;
						this.graphCache.Remove(pair.Key);
					}
				}
			}

			Profile.EndMeasure(@"ProfileRenderer");
		}
        /// <summary>
        /// Draws a path as document title.
        /// </summary>
        private void DrawPath(DrawingContext ctx, double yPos, string text, TextAlignment alignment)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            if (!File.Exists(text))
            {
                DrawText(ctx, yPos, text, alignment);
                return;
            }

            if (m_Typeface == null)
            {
                m_Typeface = new Typeface("Times New Roman");
            }

            double textWidth;

            FormattedText formattedText = new FormattedText(text,
                                                            System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                                            m_Typeface, 12, Brushes.Black);

            textWidth = formattedText.Width;

            double maxTextLength = m_PageSize.Width * 2 / 3;

            if (textWidth < maxTextLength)
            {
                ctx.DrawText(formattedText, new Point(m_Margins.Left, yPos));
                return;
            }

            //
            // if someone has a more clever solution
            // to do WordEllipsis trimming for paths, please shout
            //
            string path     = Path.GetDirectoryName(text);
            string fileName = "\\" + Path.GetFileName(text);

            // get the length of the trimmed file name
            formattedText = new FormattedText(fileName,
                                              System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                              m_Typeface, 12, Brushes.Black);

            formattedText.MaxTextWidth  = maxTextLength - 100;
            formattedText.MaxTextHeight = 16;
            formattedText.Trimming      = TextTrimming.WordEllipsis;
            textWidth = formattedText.Width;

            // draw the path
            formattedText = new FormattedText(path,
                                              System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                              m_Typeface, 12, Brushes.Black);

            formattedText.MaxTextWidth  = maxTextLength - textWidth;
            formattedText.MaxTextHeight = 16;
            formattedText.Trimming      = TextTrimming.WordEllipsis;
            ctx.DrawText(formattedText, new Point(m_Margins.Left, yPos));
            textWidth = formattedText.Width;

            // draw the file name
            formattedText = new FormattedText(fileName,
                                              System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
                                              m_Typeface, 12, Brushes.Black);

            formattedText.MaxTextWidth  = maxTextLength - textWidth;
            formattedText.MaxTextHeight = 16;
            formattedText.Trimming      = TextTrimming.WordEllipsis;
            ctx.DrawText(formattedText, new Point(m_Margins.Left + textWidth, yPos));
        }