Example #1
0
        /// <summary>
        /// Odczytuje i zwraca kolejny wpis z timingiem, z edytowanej zawartości tekstowej napisów.
        /// </summary>
        /// <returns>Zwraca kolejną wpis, a jeśli nie ma już więcej wpisów to null.</returns>
        public override TimedEntry NextTimedEntry()
        {
            if (entryReadingDirection == ReadingDirection.Backward)
            {
                UpdateContent();
            }
            entryReadingDirection = ReadingDirection.Forward;

            //(Optymalizacja) Kolejne wpisy są dopasowywane w orygianlnym content, aby zapobiec każdorazowemu wywoływaniu
            //ToString() zmiennej modifiedContent. Jedak aby wpisy zawierały poprawne informacje o pozycji w rzeczywistej zmodyfikowanej zawartości (modifiedContent),
            //konieczne jest dodanie delty długości (modifiedContentLengthDelta) do pozycji zwaracanego wpisu.
            AssEventEntry nextEntry  = null;
            Match         entryMatch = timedEntryExpressionForward.Match(content, nextEntryIndex);

            if (entryMatch.Success)
            {
                nextEntry = new AssEventEntry(entryMatch.Value, entryMatch.Index + modifiedContentLengthDelta);
                currentEntryInitialStart  = entryMatch.Index;
                currentEntryInitialLength = entryMatch.Value.Length;
                currentEntryNumber++;
            }

            CurrentEntry = nextEntry;
            if (CurrentEntry != null)
            {
                nextEntryIndex = currentEntryInitialStart + currentEntryInitialLength;
            }

            return(nextEntry);
        }
 public TextAnalysis(String Text, String localName, ReadingDirection readingDirection, NumberSubstitution numberSubstitution)
 {
     text_ = Text;
     localeName_ = localName;
     readingDirection_ = readingDirection;
     numberSubstitution_ = numberSubstitution;
 }
        internal RtfImage(System.IO.MemoryStream imageStream, ReadingDirection direction)
        {
            ReadingDirection = direction;
            _alignment       = Align.Left;
            _margins         = new Margins();
            _keepAspectRatio = true;
            _blockHead       = @"{\pard";
            _blockTail       = @"}";
            _startNewPage    = false;
            _startNewPara    = false;

            _imgByte = imageStream.ToArray();

            Image image = Image.FromStream(imageStream);

            _width  = (image.Width / image.HorizontalResolution) * 72;
            _height = (image.Height / image.VerticalResolution) * 72;

            if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png))
            {
                _imgType = ImageFileType.Png;
            }
            else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg))
            {
                _imgType = ImageFileType.Jpg;
            }
            else if (image.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif))
            {
                _imgType = ImageFileType.Gif;
            }
            else
            {
                throw new Exception("Image format is not supported: " + image.RawFormat.ToString());
            }
        }
Example #4
0
 public TextAnalysis(String Text, String localName, ReadingDirection readingDirection, NumberSubstitution numberSubstitution)
 {
     text_               = Text;
     localeName_         = localName;
     readingDirection_   = readingDirection;
     numberSubstitution_ = numberSubstitution;
 }
Example #5
0
        /// <summary>
        /// Odczytuje i zwraca kolejny wpis z timingiem, z edytowanej zawartości tekstowej napisów.
        /// </summary>
        /// <returns>Zwraca kolejną wpis, a jeśli nie ma już więcej wpisów to null.</returns>
        public override TimedEntry NextTimedEntry()
        {
            if (entryReadingDirection == ReadingDirection.Backward)
            {
                UpdateContent();
            }
            entryReadingDirection = ReadingDirection.Forward;

            TMPlayerEntry nextEntry  = null;
            Match         entryMatch = entryExpressionForward.Match(content, nextEntryIndex);

            if (entryMatch.Success)
            {
                nextEntry = new TMPlayerEntry(entryMatch.Value, entryMatch.Index + modifiedContentLengthDelta);
                currentEntryInitialStart  = entryMatch.Index;
                currentEntryInitialLength = entryMatch.Value.Length;
                currentEntryNumber++;
            }

            CurrentEntry = nextEntry;
            if (CurrentEntry != null)
            {
                nextEntryIndex = currentEntryInitialStart + currentEntryInitialLength;
            }

            return(nextEntry);
        }
Example #6
0
 /// <summary>
 /// Konstruktor.
 /// </summary>
 /// <param name="editedContent">Edytowana zawartość tekstowa napisów.</param>
 public SubripEditStrategy(String editedContent)
     : base(editedContent)
 {
     //this.nextEntryIndex = 0;
     this.modifiedContentLengthDelta = 0;
     this.entryReadingDirection      = ReadingDirection.None;
 }
Example #7
0
        /// <summary>
        /// Odczytuje i zwraca poprzedni wpis z timingiem, w stosunku do bieżącego, z edytowanej zawartości tekstowej napisów.
        /// </summary>
        /// <returns>Zwraca poprzedni wpis, a jeśli nie ma już więcej wpisów to null.</returns>
        public override TimedEntry PreviousTimedEntry()
        {
            if (entryReadingDirection == ReadingDirection.Forward)
            {
                UpdateContent();
            }
            entryReadingDirection = ReadingDirection.Backward;

            MicroDVDEntry previousEntry = null;
            Match         entryMatch    = entryExpressionBackward.Match(content, nextEntryIndex);

            if (entryMatch.Success)
            {
                previousEntry             = new MicroDVDEntry(entryMatch.Value, entryMatch.Index + modifiedContentLengthDelta);
                currentEntryInitialStart  = entryMatch.Index;
                currentEntryInitialLength = entryMatch.Value.Length;
                currentEntryNumber--;
            }

            CurrentEntry = previousEntry;
            if (CurrentEntry != null)
            {
                nextEntryIndex = currentEntryInitialStart;
            }

            return(previousEntry);
        }
 internal RtfHeaderFooter(HeaderFooterType type, ReadingDirection direction)
     : base(true, false, true, true, false)
 {
     _magicWords      = new Hashtable();
     _type            = type;
     ReadingDirection = direction;
 }
Example #9
0
        /// <summary>
        /// Odczytuje i zwraca poprzedni wpis z timingiem, w stosunku do bieżącego, z edytowanej zawartości tekstowej napisów.
        /// </summary>
        /// <returns>Zwraca poprzedni wpis, a jeśli nie ma już więcej wpisów to null.</returns>
        public override TimedEntry PreviousTimedEntry()
        {
            if (entryReadingDirection == ReadingDirection.Forward)
            {
                UpdateContent();
            }
            entryReadingDirection = ReadingDirection.Backward;

            SubripEntry entry = null;

            if (currentEntryNumber > 1)
            {
                using (StringReader reader = new StringReader(content))
                {
                    int           entryStartIndex     = 0;
                    int           previousEntryNumber = currentEntryNumber - 1;
                    bool          entryFound          = false;
                    StringBuilder entryContentBuilder = new StringBuilder();
                    String        lineContent         = String.Empty;

                    while ((lineContent = reader.ReadLine()) != null)
                    {
                        if ((!entryFound) && (IsLineNumber(lineContent)) && ((int.Parse(lineContent) == previousEntryNumber)))
                        {
                            entryFound = true;
                        }

                        if (!entryFound)
                        {
                            entryStartIndex += lineContent.Length + Environment.NewLine.Length;
                        }

                        if (entryFound)
                        {
                            entryContentBuilder.AppendLine(lineContent);
                            //Jeśli doszliśmy do lini pustej oznaczającej ostatnią lienie
                            //wykonujemy czynności kończące przeskok do następnego wpisu.
                            if (lineContent == String.Empty)
                            {
                                entry = new SubripEntry(entryContentBuilder.ToString(), entryStartIndex + modifiedContentLengthDelta);

                                currentEntryNumber        = previousEntryNumber;
                                currentEntryInitialLength = entryContentBuilder.Length;
                                currentEntryInitialStart  = entryStartIndex;
                                break;
                            }
                        }
                    }
                }
            }
            else if (currentEntryNumber <= 1)
            {
                currentEntryNumber = 0;
            }

            CurrentEntry = entry;

            return(entry);
        }
        protected bool isTextAnalysisComplete_;   // text analysis was done.

        public FlowLayout(Factory dwriteFactory)
        {
            dwriteFactory_          = dwriteFactory;
            readingDirection_       = ReadingDirection.LeftToRight;
            fontEmSize_             = 12;
            maxSpaceWidth_          = 8;
            isTextAnalysisComplete_ = false;
        }
Example #11
0
        protected bool isTextAnalysisComplete_;   // text analysis was done.

        public FlowLayout(Factory dwriteFactory)
        {
            dwriteFactory_ = dwriteFactory;
            readingDirection_ = ReadingDirection.LeftToRight;
            fontEmSize_ = 12;
            maxSpaceWidth_ = 8;
            isTextAnalysisComplete_ = false;
        }
 internal RtfSectionFooter(RtfSection parent, ReadingDirection direction)
     : base(true, true, true, true, true)
 {
     ReadingDirection = direction;
     if (parent == null)
     {
         throw new Exception("Section footer can only be placed within a section ");
     }
 }
Example #13
0
 /// <summary>
 /// Konstruktor.
 /// </summary>
 /// <param name="editedContent">Edytowana zawartość tekstowa napisów.</param>
 public TMPlayerEditStrategy(String editedContent)
     : base(editedContent)
 {
     this.nextEntryIndex             = 0;
     this.modifiedContentLengthDelta = 0;
     this.entryReadingDirection      = ReadingDirection.None;
     this.entryPattern            = CreateTimedEntryPattern();
     this.entryExpressionForward  = new Regex(entryPattern, RegexOptions.Compiled);
     this.entryExpressionBackward = new Regex(entryPattern, RegexOptions.Compiled | RegexOptions.RightToLeft);
 }
 internal RtfFootnote(int position, int textLength, ReadingDirection direction)
     : base(true, false, false, true, false)
 {
     ReadingDirection = direction;
     if (position < 0 || position >= textLength)
     {
         throw new Exception("Invalid footnote position: " + position
                             + " (text length=" + textLength + ")");
     }
     _position = position;
 }
Example #15
0
 internal RtfSection(SectionStartEnd startEnd, RtfDocument doc, ReadingDirection direction)
 {
     ReadingDirection             = direction;
     ParentDocument               = doc;
     _align                       = Align.None;
     PageOrientation              = PaperOrientation.Portrait;
     StartEnd                     = startEnd;
     FooterPositionFromPageBottom = 720;
     _sectionFooter               = null;
     _margins                     = new Margins();
 }
Example #16
0
 internal RtfTableCell(float width, int rowIndex, int colIndex, RtfTable parentTable, ReadingDirection direction)
     : base(true, false)
 {
     ReadingDirection = direction;
     _width           = width;
     _halign          = Align.None;
     _valign          = AlignVertical.Top;
     _borders         = new Borders();
     _mergeInfo       = null;
     _rowIndex        = rowIndex;
     _colIndex        = colIndex;
     BackgroundColour = null;
     ParentTable      = parentTable;
 }
Example #17
0
        /// <summary>Initializes a new instance of the <see cref="Window" /> class.</summary>
        /// <param name="windowProvider">The <see cref="WindowProvider" /> for the instance.</param>
        internal Window(WindowProvider windowProvider)
        {
            _handle = new Lazy <UIntPtr>(CreateWindowHandle, isThreadSafe: true);

            _parentThread     = Thread.CurrentThread;
            _properties       = new PropertySet();
            _title            = typeof(Window).FullName;
            _bounds           = new Rectangle(float.NaN, float.NaN, float.NaN, float.NaN);
            _flowDirection    = FlowDirection.TopToBottom;
            _readingDirection = ReadingDirection.LeftToRight;

            _windowProvider = windowProvider;
            _state.Transition(to: Initialized);
        }
Example #18
0
        internal XlibWindow(XlibWindowProvider windowProvider)
            : base(windowProvider, Thread.CurrentThread)
        {
            _handle = new ValueLazy <nuint>(CreateWindowHandle);

            _properties       = new PropertySet();
            _title            = typeof(XlibWindow).FullName !;
            _bounds           = new Rectangle(float.NaN, float.NaN, float.NaN, float.NaN);
            _flowDirection    = FlowDirection.TopToBottom;
            _readingDirection = ReadingDirection.LeftToRight;
            _isEnabled        = true;

            _ = _state.Transition(to: Initialized);
        }
Example #19
0
        internal Win32Window(Win32WindowService windowService)
            : base(windowService, Thread.CurrentThread)
        {
            _flowDirection    = FlowDirection.TopToBottom;
            _readingDirection = ReadingDirection.LeftToRight;

            _handle     = new ValueLazy <IntPtr>(CreateWindowHandle);
            _properties = new ValueLazy <PropertySet>(CreateProperties);

            _title         = typeof(Win32Window).FullName !;
            _bounds        = new Rectangle(float.NaN, float.NaN, float.NaN, float.NaN);
            _clientBounds  = new Rectangle(float.NaN, float.NaN, float.NaN, float.NaN);
            _extendedStyle = WS_EX_OVERLAPPEDWINDOW;
            _style         = WS_OVERLAPPEDWINDOW;

            _ = _state.Transition(to: Initialized);
        }
Example #20
0
        internal Window(WindowProvider windowProvider)
        {
            Assert(windowProvider != null, Resources.ArgumentNullExceptionMessage, nameof(windowProvider));

            _handle = new ResettableLazy <UIntPtr>(CreateWindowHandle);

            _parentThread     = Thread.CurrentThread;
            _properties       = new PropertySet();
            _title            = typeof(Window).FullName !;
            _bounds           = new Rectangle(float.NaN, float.NaN, float.NaN, float.NaN);
            _flowDirection    = FlowDirection.TopToBottom;
            _readingDirection = ReadingDirection.LeftToRight;
            _isEnabled        = true;

            _windowProvider = windowProvider;
            _ = _state.Transition(to: Initialized);
        }
 public RtfParagraph(bool allowFootnote, bool allowControlWord, ReadingDirection direction)
 {
     _text              = new StringBuilder();
     _linespacing       = -1;
     _margins           = new Margins();
     _align             = Align.Left; //Changed default to .Left as .None was spreading text accross page.
     _charFormats       = new List <RtfCharFormat>();
     _allowFootnote     = allowFootnote;
     _allowControlWord  = allowControlWord;
     _footnotes         = new List <RtfFootnote>();
     _controlWords      = new List <RtfFieldControlWord>();
     _blockHead         = @"{\pard";
     _blockTail         = @"\par}";
     _startNewPage      = false;
     _firstLineIndent   = 0;
     _defaultCharFormat = null;
     ReadingDirection   = direction;
 }
Example #22
0
        public Page(System.Drawing.Bitmap page, ReadingDirection direction, ICellsSegmentation extractor, ICellReadingOrder order)
        {
            this.Content = page;
            this.Direction = direction;

            var ExtractedCells = extractor.Extract(page);

            if (ExtractedCells.FullPage)
            {
                this.Cells = new List<IPolygon>(new Polygon[] { Polygon.Rectangle(0, 0, page.Width, page.Height) });
                this.TransformedCells = (from cell in this.Cells select (new TransformedPolygon(cell, ReadingDirectionToMatrix(this.Direction))));
            }
            else
            {
                var transformedCells = (from cell in ExtractedCells.Polygons
                                        select new TransformedPolygon(cell, ReadingDirectionToMatrix(direction)));

                this.TransformedCells = order.GetReadingOrder(transformedCells);
                this.Cells = (from cell in this.TransformedCells select ((TransformedPolygon)cell).BasePolygon);
            }
        }
Example #23
0
        public RtfTable(int rowCount, int colCount, float horizontalWidth, float fontSize, ReadingDirection direction)
        {
            ReadingDirection    = direction;
            _fontSize           = fontSize;
            _alignment          = Align.None;
            _margins            = new Margins();
            _rowCount           = rowCount;
            _colCount           = colCount;
            _representativeList = new List <RtfTableCell>();
            _startNewPage       = false;
            _titleRowCount      = 0;
            _cellPadding        = new Margins[_rowCount];
            if (_rowCount < 1 || _colCount < 1)
            {
                throw new Exception("The number of rows or columns is less than 1.");
            }

            HeaderBackgroundColour = null;
            RowBackgroundColour    = null;
            RowAltBackgroundColour = null;

            // Set cell default width according to paper width
            _defaultCellWidth  = horizontalWidth / (float)colCount;
            _cells             = new RtfTableCell[_rowCount][];
            _rowHeight         = new float[_rowCount];
            _rowKeepInSamePage = new bool[_rowCount];
            for (int i = 0; i < _rowCount; i++)
            {
                _cells[i]             = new RtfTableCell[_colCount];
                _rowHeight[i]         = 0F;
                _rowKeepInSamePage[i] = false;
                _cellPadding[i]       = new Margins();
                for (int j = 0; j < _colCount; j++)
                {
                    _cells[i][j] = new RtfTableCell(_defaultCellWidth, i, j, this, direction);
                }
            }
        }
        public void SetTextFormat(TextFormat textFormat)
        {
            // Initializes properties using a text format, like font family, font size,
            // and reading direction. For simplicity, this custom layout supports
            // minimal formatting. No mixed formatting or alignment modes are supported.
            readingDirection_ = textFormat.ReadingDirection;
            fontEmSize_       = textFormat.FontSize;
            localName_        = textFormat.LocaleName;

            // Map font and style to fontFace.
            FontCollection fontCollection = textFormat.FontCollection;// Need the font collection to map from font name to actual font.

            if (fontCollection == null)
            {
                fontCollection = dwriteFactory_.GetSystemFontCollection(false);// No font collection was set in the format, so use the system default.
            }
            // Find matching family name in collection.
            String fontFamilyName = textFormat.FontFamilyName;

            int fontIndex;

            // If the given font does not exist, take what we can get
            // (displaying something instead nothing), choosing the foremost
            // font in the collection.
            if (!fontCollection.FindFamilyName(fontFamilyName, out fontIndex))
            {
                fontIndex = 0;
            }

            FontFamily fontFamily = fontCollection.GetFontFamily(fontIndex);
            Font       font       = fontFamily.GetFirstMatchingFont(textFormat.FontWeight, textFormat.FontStretch, textFormat.FontStyle);

            fontFace_ = new FontFace(font);

            font.Dispose();
            fontFamily.Dispose();
            fontCollection.Dispose();
        }
        internal RtfImage(string fileName, ImageFileType type, ReadingDirection direction)
        {
            ReadingDirection = direction;
            _imgFname        = fileName;
            _imgType         = type;
            _alignment       = Align.None;
            _margins         = new Margins();
            _keepAspectRatio = true;
            _blockHead       = @"{\pard";
            _blockTail       = @"}";
            _startNewPage    = false;
            _startNewPara    = false;

            Image image = Image.FromFile(fileName);

            _width  = (image.Width / image.HorizontalResolution) * 72;
            _height = (image.Height / image.VerticalResolution) * 72;

            using (MemoryStream mStream = new MemoryStream())
            {
                image.Save(mStream, image.RawFormat);
                _imgByte = mStream.ToArray();
            }
        }
Example #26
0
        /// <summary>
        /// Odczytuje i zwraca kolejny wpis z timingiem, z edytowanej zawartości tekstowej napisów.
        /// </summary>
        /// <returns>Zwraca kolejną wpis, a jeśli nie ma już więcej wpisów to null.</returns>
        public override TimedEntry NextTimedEntry()
        {
            if (entryReadingDirection == ReadingDirection.Backward)
            {
                UpdateContent();
            }
            entryReadingDirection = ReadingDirection.Forward;

            SubripEntry entry = null;

            using (StringReader reader = new StringReader(content))
            {
                int           entryStartIndex     = 0;
                int           nextEntryNumber     = currentEntryNumber + 1;
                bool          entryFound          = false;
                StringBuilder entryContentBuilder = new StringBuilder();
                String        lineContent         = String.Empty;

                while ((lineContent = reader.ReadLine()) != null)
                {
                    //if ((!entryFound) && (int.TryParse(lineContent, out entryCounter)) && (entryCounter == nextEntryNumber))
                    if ((!entryFound) && (IsLineNumber(lineContent)) && ((int.Parse(lineContent) == nextEntryNumber)))
                    {
                        entryFound = true;
                    }

                    if (!entryFound)
                    {
                        entryStartIndex += lineContent.Length + Environment.NewLine.Length;
                    }

                    if (entryFound)
                    {
                        bool isLastLine = reader.Peek() == -1;
                        if (isLastLine)
                        {
                            //Jeśli jest to ostatnia linia to dodajemy zawartość bez symbola nowej lini na końcu, który dodaje AppendLine.
                            entryContentBuilder.Append(lineContent);
                        }
                        else
                        {
                            entryContentBuilder.AppendLine(lineContent);
                        }

                        //Jeśli doszliśmy do lini pustej oznaczającej koniec wpisu, lub ostatniej lini tekstu,
                        //to oznacza że właściwy wpis został znaleziony, w związku z czym można stworzyć obiekt go reprezentujący.
                        if ((lineContent == String.Empty) || isLastLine)
                        {
                            entry = new SubripEntry(entryContentBuilder.ToString(), entryStartIndex + modifiedContentLengthDelta);
                            currentEntryNumber        = nextEntryNumber;
                            currentEntryInitialLength = entryContentBuilder.Length;
                            currentEntryInitialStart  = entryStartIndex;
                            break;
                        }
                    }
                }
            }

            CurrentEntry = entry;

            return(entry);
        }
Example #27
0
        public void Analyze()
        {
            CultureInfo startingCulture;

            if(_TextShaper.Characters.Length == 0)
            {
                startingCulture = CultureInfo.InvariantCulture;
            }
            else
            {
                startingCulture = _TextShaper.Characters[0].Culture;

                if(startingCulture == null)
                {
                    startingCulture = CultureInfo.InvariantCulture;
                }
            }

            if(startingCulture.TextInfo.IsRightToLeft)
            {
                _ReadingDirection = ReadingDirection.RightToLeft;
            }
            else
            {
                _ReadingDirection = ReadingDirection.LeftToRight;
            }

            try
            {
                _TextAnalyzer.AnalyzeLineBreakpoints(this, 0, _TextShaper.Text.Length, this);

                _TextAnalyzer.AnalyzeBidi(this, 0, _TextShaper.Text.Length, this);

                _TextAnalyzer.AnalyzeScript(this, 0, _TextShaper.Text.Length, this);

                _TextAnalyzer.AnalyzeNumberSubstitution(this, 0, _TextShaper.Text.Length, this);
            }
            catch(SharpDXException e)
            {
                throw new InvalidOperationException(e.Message, e);
            }
        }
Example #28
0
 /// <summary>
 /// A matrix that transform left to right, top to bottom content into
 /// content readable in the specified direction.
 /// </summary>
 public static Matrix ReadingDirectionToInverseMatrix(ReadingDirection direction)
 {
     Matrix m = ReadingDirectionToMatrix(direction);
     m.Invert();
     return m;
 }
Example #29
0
        /// <summary>
        ///   This method prepares for analyzing the given text.
        /// </summary>
        /// <param name="text"> This parameter references the text to analyze. </param>
        /// <param name="paragraphCulture"> This parameter references the culture of the text to analyze. </param>
        public void BeginAnalysis(string text, CultureInfo paragraphCulture)
        {
            Contract.Requires(!string.IsNullOrEmpty(text));
            Contract.Requires(paragraphCulture != null);

            _FullText = text;

            if(text.Length > _Characters.Length)
            {
                _Characters = new CharacterProperties[text.Length * 2];
            }

            if(paragraphCulture.TextInfo.IsRightToLeft)
            {
                _ReadingDirection = ReadingDirection.RightToLeft;
            }
            else
            {
                _ReadingDirection = ReadingDirection.LeftToRight;
            }
        }
Example #30
0
 /// <summary>
 /// A matrix that transforms the page in such a way that it can be read 
 /// left to right, top to bottom.
 /// </summary>
 public static Matrix ReadingDirectionToMatrix(ReadingDirection direction)
 {
     switch (direction)
     {
         case ReadingDirection.DownLeft:
             return new Matrix(-1, 0, 0, 1, 0, 0);
         case ReadingDirection.RightDown:
             return new Matrix(0, 1, 1, 0, 0, 0);
         case ReadingDirection.LeftDown:
             return new Matrix(0, -1, 1, 0, 0, 0);
         default:
             break;
     }
     return new Matrix(1, 0, 0, 1, 0, 0);
 }
Example #31
0
 public Page(System.Drawing.Bitmap page, ReadingDirection direction)
     : this(page, direction, new AFThresholdBlobSegmentation(), new DefaultReadingOrder())
 {
 }
Example #32
0
        private void SetLayoutText(LayoutText layoutText)
        {
            // Selects a different text sample.

            ReadingDirection readingDirection = ReadingDirection.LeftToRight;
            String           text             = "";
            String           fontName         = "";
            String           localeName       = "";

            switch (layoutText)
            {
            case LayoutText.Latin:
                fontName         = "Segoe UI";
                localeName       = "en-us";
                readingDirection = ReadingDirection.LeftToRight;
                text             =
                    "DirectWrite provides factored layers of functionality, with each layer interacting seamlessly with the next. "
                    + "The API design gives an application the freedom and flexibility to adopt individual layers depending on their needs and schedule.\n"
                    + "\n"
                    + "The text layout API provides the highest level functionality available from DirectWrite. "
                    + "It provides services for the application to measure, display, and interact with richly formatted text strings. "
                    + "This text API can be used in applications that currently use Win32 DrawText to build a modern UI with richly formatted text.\n"
                    + "\n"
                    + "* Text-intensive applications that implement their own layout engine may use the next layer down: the script processor. "
                    + "The script processor segments text into runs of similar properties and handles the mapping from Unicode codepoints "
                    + "to the appropriate glyph in the font. "
                    + "DirectWrite's own layout is built upon this same font and script processing system. "
                    + "This sample demonstrates how a custom layout can utilize the information from script itemization, bidi analysis, line breaking analysis, and shaping, "
                    + "to accomplish text measurement/fitting, line breaking, basic justification, and drawing.\n"
                    + "\n"
                    + "The glyph-rendering layer is the lowest layer and provides glyph-rendering functionality for applications "
                    + "that implement their own complete text layout engine. The glyph rendering layer is also useful for applications that implement a custom "
                    + "renderer to modify the glyph-drawing behavior through the callback function in the DirectWrite text-formatting API.\n"
                    + "\n"
                    + "The DirectWrite font system is available to all the functional layers, and enables an application to access font and glyph information. "
                    + "It is designed to handle common font technologies and data formats. The DirectWrite font model follows the common typographic practice of "
                    + "supporting any number of weights, styles, and stretches in the same font family. This model, the same model followed by WPF and CSS, "
                    + "specifies that fonts differing only in weight (bold, light, etc.), style (upright, italic, or oblique) or stretch (narrow, condensed, wide, etc.) "
                    + "are considered to be members of a single font family.\n"
                    + "\n"
                    + "Text in DirectWrite is rendered using Microsoft ClearType, which enhances the clarity and readability of text. "
                    + "ClearType takes advantage of the fact that modern LCD displays have RGB stripes for each pixel that can be controlled individually. "
                    + "DirectWrite uses the latest enhancements to ClearType, first included with Windows Vista with Windows Presentation Foundation, "
                    + "that enables it to evaluate not just the individual letters but also the spacing between letters. "
                    + "Before these ClearType enhancements, text with a “reading” size of 10 or 12 points was difficult to display: "
                    + "we could place either 1 pixel in between letters, which was often too little, or 2 pixels, which was often too much. "
                    + "Using the extra resolution in the subpixels provides us with fractional spacing, which improves the evenness and symmetry of the entire page.\n"
                    + "\n"
                    + "The subpixel ClearType positioning offers the most accurate spacing of characters on screen, "
                    + "especially at small sizes where the difference between a sub-pixel and a whole pixel represents a significant proportion of glyph width. "
                    + "It allows text to be measured in ideal resolution space and rendered at its natural position at the LCD color stripe, subpixel granularity. "
                    + "Text measured and rendered using this technology is, by definition, "
                    + "resolution-independent—meaning the exact same layout of text is achieved across the range of various display resolutions.\n"
                    + "\n"
                    + "Unlike either flavor of GDI's ClearType rendering, sub-pixel ClearType offers the most accurate width of characters. "
                    + "The Text String API adopts sub-pixel text rendering by default, which means it measures text at its ideal resolution independent "
                    + "to the current display resolution, and produces the glyph positioning result based on the truly scaled glyph advance widths and positioning offsets.";
                break;

            case LayoutText.Arabic:
                fontName         = "Arabic Typesetting";
                localeName       = "ar-eg";
                readingDirection = ReadingDirection.RightToLeft;
                text             =
                    "الديباجة\n"
                    + "لمّا كان الاعتراف بالكرامة المتأصلة في جميع أعضاء الأسرة البشرية وبحقوقهم المتساوية الثابتة هو أساس الحرية والعدل والسلام في العالم.\n"
                    + "\n"
                    + "ولما كان تناسي حقوق الإنسان وازدراؤها قد أفضيا إلى أعمال همجية آذت الضمير الإنساني. وكان غاية ما يرنو إليه عامة البشر انبثاق عالم يتمتع فيه الفرد بحرية القول والعقيدة ويتحرر من الفزع والفاقة.\n"
                    + "\n"
                    + "ولما كان من الضروري أن يتولى القانون حماية حقوق الإنسان لكيلا يضطر المرء آخر الأمر إلى التمرد على الاستبداد والظلم.\n"
                    + "\n"
                    + "ولما كانت شعوب الأمم المتحدة قد أكدت في الميثاق من جديد إيمانها بحقوق الإنسان الأساسية وبكرامة الفرد وقدره وبما للرجال والنساء من حقوق متساوية وحزمت أمرها على أن تدفع بالرقي الاجتماعي قدمًا وأن ترفع مستوى الحياة في جو من الحرية أفسح.\n"
                    + "\n"
                    + "ولما كانت الدول الأعضاء قد تعهدت بالتعاون مع الأمم المتحدة على ضمان إطراد مراعاة حقوق الإنسان والحريات الأساسية واحترامها.\n"
                    + "\n"
                    + "ولما كان للإدراك العام لهذه الحقوق والحريات الأهمية الكبرى للوفاء التام بهذا التعهد.\n"
                    + "\n"
                    + "فإن الجمعية العامة\n"
                    + "\n"
                    + "تنادي بهذا الإعلان العالمي لحقوق الإنسان\n"
                    + "\n"
                    + "على أنه المستوى المشترك الذي ينبغي أن تستهدفه كافة الشعوب والأمم حتى يسعى كل فرد وهيئة في المجتمع، واضعين على الدوام هذا الإعلان نصب أعينهم، إلى توطيد احترام هذه الحقوق والحريات عن طريق التعليم والتربية واتخاذ إجراءات مطردة، قومية وعالمية، لضمان الإعتراف بها ومراعاتها بصورة عالمية فعالة بين الدول الأعضاء ذاتها وشعوب البقاع الخاضعة لسلطانها.\n"
                    + "\n"
                    + "المادة 1\n"
                    + "\n"
                    + "يولد جميع الناس أحرارًا متساوين في الكرامة والحقوق. وقد وهبوا عقلاً وضميرًا وعليهم أن يعامل بعضهم بعضًا بروح الإخاء.\n"
                    + "\n"
                    + "المادة 2\n"
                    + "\n"
                    + "لكل إنسان حق التمتع بكافة الحقوق والحريات الواردة في هذا الإعلان، دون أي تمييز، كالتمييز بسبب العنصر أو اللون أو الجنس أو اللغة أو الدين أو الرأي السياسي أو أي رأي آخر، أو الأصل الوطني أو الإجتماعي أو الثروة أو الميلاد أو أي وضع آخر، دون أية تفرقة بين الرجال والنساء.\n"
                    + "\n"
                    + "وفضلاً عما تقدم فلن يكون هناك أي تمييز أساسه الوضع السياسي أو القانوني أو الدولي لبلد أو البقعة التي ينتمي إليها الفرد سواء كان هذا البلد أو تلك البقعة مستقلاً أو تحت الوصاية أو غير متمتع بالحكم الذاتي أو كانت سيادته خاضعة لأي قيد من القيود.\n";
                break;

            case LayoutText.Japanese:
                fontName         = "Meiryo";
                localeName       = "jp-jp";
                readingDirection = ReadingDirection.LeftToRight;
                text             =
                    "『世界人権宣言』\n"
                    + "(1948.12.10 第3回国連総会採択)〈前文〉\n"
                    + "\n"
                    + "人類社会のすべての構成員の固有の尊厳と平等で譲ることのできない権利とを承認することは、世界における自由、正義及び平和の基礎であるので、\n"
                    + "\n"
                    + "人権の無視及び軽侮が、人類の良心を踏みにじった野蛮行為をもたらし、言論及び信仰の自由が受けられ、恐怖及び欠乏のない世界の到来が、一般の人々の最高の願望として宣言されたので、\n"
                    + "\n"
                    + "人間が専制と圧迫とに対する最後の手段として反逆に訴えることがないようにするためには、法の支配によって人権を保護することが肝要であるので、\n"
                    + "\n"
                    + "諸国間の友好関係の発展を促進することが肝要であるので、\n"
                    + "\n"
                    + "国際連合の諸国民は、国連憲章において、基本的人権、人間の尊厳及び価値並びに男女の同権についての信念を再確認し、かつ、一層大きな自由のうちで社会的進歩と生活水準の向上とを促進することを決意したので、\n"
                    + "\n"
                    + "加盟国は、国際連合と協力して、人権及び基本的自由の普遍的な尊重及び遵守の促進を達成することを誓約したので、\n"
                    + "\n"
                    + "これらの権利及び自由に対する共通の理解は、この誓約を完全にするためにもっとも重要であるので、\n"
                    + "\n"
                    + "よって、ここに、国連総会は、\n"
                    + "\n"
                    + "\n"
                    + "社会の各個人及び各機関が、この世界人権宣言を常に念頭に置きながら、加盟国自身の人民の間にも、また、加盟国の管轄下にある地域の人民の間にも、これらの権利と自由との尊重を指導及び教育によって促進すること並びにそれらの普遍的措置によって確保することに努力するように、すべての人民とすべての国とが達成すべき共通の基準として、この人権宣言を公布する。\n"
                    + "\n"
                    + "第1条\n"
                    + "すべての人間は、生まれながらにして自由であり、かつ、尊厳と権利と について平等である。人間は、理性と良心とを授けられており、互いに同 胞の精神をもって行動しなければならない。\n"
                    + "\n"
                    + "第2条"
                    + "すべて人は、人種、皮膚の色、性、言語、宗教、政治上その他の意見、\n"
                    + "\n"
                    + "国民的もしくは社会的出身、財産、門地その他の地位又はこれに類するい\n"
                    + "\n"
                    + "かなる自由による差別をも受けることなく、この宣言に掲げるすべての権\n"
                    + "\n"
                    + "利と自由とを享有することができる。\n"
                    + "\n"
                    + "さらに、個人の属する国又は地域が独立国であると、信託統治地域で\n"
                    + "\n"
                    + "あると、非自治地域であると、又は他のなんらかの主権制限の下にあると\n"
                    + "\n"
                    + "を問わず、その国又は地域の政治上、管轄上又は国際上の地位に基ずくい\n"
                    + "\n"
                    + "かなる差別もしてはならない。\n"
                    + "\n"
                    + "第3条\n"
                    + "すべての人は、生命、自由及び身体の安全に対する権利を有する。\n"
                    + "\n"
                    + "第4条\n"
                    + "何人も、奴隷にされ、又は苦役に服することはない。奴隷制度及び奴隷\n"
                    + "\n"
                    + "売買は、いかなる形においても禁止する。\n"
                    + "\n"
                    + "第5条\n"
                    + "何人も、拷問又は残虐な、非人道的なもしくは屈辱的な取扱もしくは刑\n"
                    + "\n"
                    + "罰を受けることはない。\n";

                break;
            }
            textMode_ = layoutText;

            TextFormat textFormat = null;

            try
            {
                textFormat = new TextFormat(FactoryDWrite, fontName, null, FontWeight.Normal, SharpDX.DirectWrite.FontStyle.Normal, FontStretch.Normal, 14, localeName);
                textFormat.ReadingDirection = readingDirection;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not create text format for custom layout! CreateTextFormat()" + Environment.NewLine + ex.Message, "CutomLayout", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                flowLayout.SetTextFormat(textFormat);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not set text format on custom layout! SetTextFormat()" + Environment.NewLine + ex.Message, "CutomLayout", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                flowLayout.AnalyzeText(text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Text analysis failed! FlowLayout::AnalyzeText()" + Environment.NewLine + ex.Message, "CutomLayout", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #33
0
        public void SetTextFormat(TextFormat textFormat)
        {
            // Initializes properties using a text format, like font family, font size,
            // and reading direction. For simplicity, this custom layout supports
            // minimal formatting. No mixed formatting or alignment modes are supported.
            readingDirection_ = textFormat.ReadingDirection;
            fontEmSize_ = textFormat.FontSize;
            localName_ = textFormat.LocaleName;

            // Map font and style to fontFace.
            FontCollection fontCollection = textFormat.FontCollection;// Need the font collection to map from font name to actual font.
            if (fontCollection == null)
                fontCollection = dwriteFactory_.GetSystemFontCollection(false);// No font collection was set in the format, so use the system default.

            // Find matching family name in collection.
            String fontFamilyName = textFormat.FontFamilyName;

            int fontIndex;
            // If the given font does not exist, take what we can get
            // (displaying something instead nothing), choosing the foremost
            // font in the collection.
            if (!fontCollection.FindFamilyName(fontFamilyName, out fontIndex))
                fontIndex = 0;

            FontFamily fontFamily = fontCollection.GetFontFamily(fontIndex);
            Font font = fontFamily.GetFirstMatchingFont(textFormat.FontWeight, textFormat.FontStretch, textFormat.FontStyle);
            fontFace_ = new FontFace(font);

            font.Dispose();
            fontFamily.Dispose();
            fontCollection.Dispose();
        }