示例#1
0
        /// <summary>
        /// Updates the <code>TextMeasurer</code> after a single character has
        /// been deleted
        /// from the paragraph currently represented by this
        /// <code>TextMeasurer</code>.  After this call, this
        /// <code>TextMeasurer</code> is equivalent to a new <code>TextMeasurer</code>
        /// created from the text;  however, it will usually be more efficient
        /// to update an existing <code>TextMeasurer</code> than to create a new one
        /// from scratch.
        /// </summary>
        /// <param name="newParagraph"> the text of the paragraph after performing
        /// the deletion.  Cannot be null. </param>
        /// <param name="deletePos"> the position in the text where the character was removed.
        /// Must not be less than
        /// the start of <code>newParagraph</code>, and must not be greater than the
        /// end of <code>newParagraph</code>. </param>
        /// <exception cref="IndexOutOfBoundsException"> if <code>deletePos</code> is
        ///         less than the start of <code>newParagraph</code> or greater
        ///         than the end of <code>newParagraph</code> </exception>
        /// <exception cref="NullPointerException"> if <code>newParagraph</code> is
        ///         <code>null</code> </exception>
        public void DeleteChar(AttributedCharacterIterator newParagraph, int deletePos)
        {
            FStart = newParagraph.BeginIndex;
            int end = newParagraph.EndIndex;

            if (end - FStart != FChars.Length - 1)
            {
                InitAll(newParagraph);
            }

            char[] newChars     = new char[end - FStart];
            int    changedIndex = deletePos - FStart;

            System.Array.Copy(FChars, 0, newChars, 0, deletePos - FStart);
            System.Array.Copy(FChars, changedIndex + 1, newChars, changedIndex, end - deletePos);
            FChars = newChars;

            if (FBidi != null)
            {
                FBidi = new Bidi(newParagraph);
                if (FBidi.LeftToRight)
                {
                    FBidi = null;
                }
            }

            FParagraph = StyledParagraph.DeleteChar(newParagraph, FChars, deletePos, FParagraph);
            InvalidateComponents();
        }
示例#2
0
        private void _testManyAddedPoints()
        {
            Bidi bidi = new Bidi();

            char[] text = new char[90];
            for (int i = 0; i < text.Length; i += 3)
            {
                text[i]     = 'a';
                text[i + 1] = '\u05d0';
                text[i + 2] = '3';
            }
            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_INVERSE_LIKE_DIRECT);
            bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_INSERT_MARKS);
            bidi.SetPara(text, IBM.ICU.Text.Bidi.LTR, null);
            String xout = bidi.WriteReordered(0);

            char[] expected = new char[120];
            for (int i_0 = 0; i_0 < expected.Length; i_0 += 4)
            {
                expected[i_0]     = 'a';
                expected[i_0 + 1] = '\u05d0';
                expected[i_0 + 2] = '\u200e';
                expected[i_0 + 3] = '3';
            }
            AssertEquals("\nInvalid output with many added points", ILOG.J2CsMapping.Util.StringUtil.NewString(expected), xout);
        }
示例#3
0
        private void _testManyInverseBidi(Bidi bidi, int direction)
        {
            char[] text = { (char)0, (char)0, (char)0x20, (char)0, (char)0, (char)0x20, (char)0, (char)0 };
            int    i, j, k;

            Log("inverse Bidi: testManyInverseBiDi("
                + ((direction == IBM.ICU.Text.Bidi.DIRECTION_LEFT_TO_RIGHT) ? 'L' : 'R')
                + ") - test permutations of text snippets ---\n");
            for (i = 0; i < COUNT_REPEAT_SEGMENTS; ++i)
            {
                text[0] = repeatSegments[i][0];
                text[1] = repeatSegments[i][1];
                for (j = 0; j < COUNT_REPEAT_SEGMENTS; ++j)
                {
                    text[3] = repeatSegments[j][0];
                    text[4] = repeatSegments[j][1];
                    for (k = 0; k < COUNT_REPEAT_SEGMENTS; ++k)
                    {
                        text[6] = repeatSegments[k][0];
                        text[7] = repeatSegments[k][1];

                        Log("inverse Bidi: testManyInverseBiDi()[" + i + " " + j
                            + " " + k + "]\n");
                        _testInverseBidi(bidi, ILOG.J2CsMapping.Util.StringUtil.NewString(text), direction);
                    }
                }
            }
        }
        private bool CheckResultLength(Bidi bidi, String src, String dest,
                                       String mode, String option, sbyte level)
        {
            int actualLen;

            if (mode.Equals("REORDER_INVERSE_NUMBERS_AS_L"))
            {
                actualLen = dest.Length;
            }
            else
            {
                actualLen = bidi.GetResultLength();
            }
            if (actualLen != dest.Length)
            {
                Errln("\nBidi.getResultLength failed." + "\nExpected:           "
                      + dest.Length + "\nActual:             " + actualLen
                      + "\nInput:              " + src + "\nOutput:             "
                      + dest + "\nReordering mode:    " + mode
                      + "\nReordering option:  " + option
                      + "\nParagraph level:    " + level);
                return(false);
            }
            return(true);
        }
示例#5
0
        private void DoTests(Bidi bidi, Bidi bidiLine, bool countRunsFirst)
        {
            int    testNumber;
            String str0;
            int    lineStart;
            sbyte  paraLevel;
            int    bidiTestCount = IBM.ICU.Charset.TestData.TestCount();

            for (testNumber = 0; testNumber < bidiTestCount; ++testNumber)
            {
                TestData test = IBM.ICU.Charset.TestData.GetTestData(testNumber);
                str0      = GetStringFromDirProps(test.dirProps);
                paraLevel = test.paraLevel;
                try {
                    bidi.SetPara(str0, paraLevel, null);
                    Logln("Bidi.setPara(tests[" + testNumber + "] OK, direction "
                          + bidi.GetDirection() + " paraLevel " + paraLevel);
                } catch (Exception e) {
                    Errln("Bidi.setPara(tests[" + testNumber
                          + "] failed, direction " + bidi.GetDirection()
                          + " paraLevel " + paraLevel);
                }
                lineStart = test.lineStart;
                if (lineStart == -1)
                {
                    DoTest(bidi, testNumber, test, 0, countRunsFirst);
                }
                else
                {
                    try {
                        bidiLine = bidi.SetLine(lineStart, test.lineLimit);
                        Logln("Bidi.setLine(" + lineStart + ", " + test.lineLimit
                              + "), in tests[" + testNumber + "] OK, direction "
                              + bidiLine.GetDirection() + " paraLevel "
                              + bidiLine.GetBaseLevel());
                        DoTest(bidiLine, testNumber, test, lineStart,
                               countRunsFirst);
                    } catch (Exception e_0) {
                        Errln("Bidi.setLine(" + lineStart + ", " + test.lineLimit
                              + "), in runAll test[" + testNumber + "] failed");
                    }
                    /* do it again using createLineBidi instead of setLine */
                    try {
                        bidiLine = bidi.CreateLineBidi(lineStart, test.lineLimit);
                        Logln("Bidi.createLineBidi(" + lineStart + ", "
                              + test.lineLimit + "), in tests[" + testNumber
                              + "] OK, direction " + bidiLine.GetDirection()
                              + " paraLevel " + bidiLine.GetBaseLevel());
                        DoTest(bidiLine, testNumber, test, lineStart,
                               countRunsFirst);
                    } catch (Exception e_1) {
                        Errln("Bidi.createLineBidi(" + lineStart + ", "
                              + test.lineLimit + "), in runAll test["
                              + testNumber + "] failed");
                    }
                }
            }
        }
示例#6
0
        private void _testMisc()
        {
            Bidi bidi = new Bidi();

            bidi.SetInverse(true);
            bidi.SetPara("   ", IBM.ICU.Text.Bidi.RTL, null);
            String xout = bidi.WriteReordered(IBM.ICU.Text.Bidi.OUTPUT_REVERSE
                                              | IBM.ICU.Text.Bidi.INSERT_LRM_FOR_NUMERIC);

            AssertEquals("\nInvalid output with RLM at both sides",
                         "\u200f   \u200f", xout);
        }
示例#7
0
        public void TestBidi2()
        {
            Bidi bidi;
            Bidi bidiLine;

            Logln("\nEntering TestBidi");
            bidi     = new Bidi(MAXLEN, 0);
            bidiLine = new Bidi();

            DoTests(bidi, bidiLine, false);
            DoTests(bidi, bidiLine, true);
            DoMisc();
            Logln("\nExiting TestBidi");
        }
        private void VerifyClassifier(Bidi bidi)
        {
            BidiClassifier actualClassifier = bidi.GetCustomClassifier();

            if (this.classifier == null)
            {
                if (actualClassifier != null)
                {
                    Errln("Bidi classifier is not yet set, but reported as not null");
                }
            }
            else
            {
                Type expectedClass = this.classifier.GetType();
                AssertTrue("null Bidi classifier", actualClassifier != null);
                if (actualClassifier == null)
                {
                    return;
                }
                if (expectedClass.IsInstanceOfType(actualClassifier))
                {
                    Object context = classifier.GetContext();
                    if (context == null)
                    {
                        if (actualClassifier.GetContext() != null)
                        {
                            Errln("Unexpected context, should be null");
                        }
                    }
                    else
                    {
                        AssertEquals("Unexpected classifier context", context,
                                     actualClassifier.GetContext());
                        AssertEquals("Unexpected context's content",
                                     ((Int32)context),
                                     bidi.GetCustomizedClass('a'));
                    }
                }
                else
                {
                    Errln("Bidi object reports classifier is an instance of "
                          + actualClassifier.GetType().FullName
                          + ",\nwhile the expected classifier should be an "
                          + "instance of " + expectedClass);
                }
            }
        }
        internal String InverseBasic(Bidi bidi, String src, int option, sbyte level)
        {
            String dest2;

            if (bidi == null || src == null)
            {
                return(null);
            }
            bidi.SetReorderingOptions(option);
            bidi.SetPara(IBM.ICU.Charset.BidiTest.PseudoToU16(src), level, null);
            dest2 = IBM.ICU.Charset.BidiTest.U16ToPseudo(bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING));
            if (!(option == IBM.ICU.Text.Bidi.OPTION_INSERT_MARKS))
            {
                CheckWhatYouCan(bidi, src, dest2);
            }
            return(dest2);
        }
示例#10
0
        private TextLine MakeTextLineOnRange(int startPos, int limitPos)
        {
            int[]   charsLtoV  = null;
            sbyte[] charLevels = null;

            if (FBidi != null)
            {
                Bidi lineBidi = FBidi.CreateLineBidi(startPos, limitPos);
                charLevels = BidiUtils.getLevels(lineBidi);
                int[] charsVtoL = BidiUtils.createVisualToLogicalMap(charLevels);
                charsLtoV = BidiUtils.createInverseMap(charsVtoL);
            }

            TextLineComponent[] components = MakeComponentsOnRange(startPos, limitPos);

            return(new TextLine(FFrc, components, FBaselineOffsets, FChars, startPos, limitPos, charsLtoV, charLevels, FIsDirectionLTR));
        }
示例#11
0
        internal void PrintCaseInfo(Bidi bidi, String src, String dst)
        {
            int length = bidi.GetProcessedLength();

            sbyte[] levels     = bidi.GetLevels();
            char[]  levelChars = new char[length];
            sbyte   lev;
            int     runCount = bidi.CountRuns();

            Errcontln("========================================");
            Errcontln("Processed length: " + length);
            for (int i = 0; i < length; i++)
            {
                lev = levels[i];
                if (lev < 0)
                {
                    levelChars[i] = '-';
                }
                else if (lev < columns.Length)
                {
                    levelChars[i] = columns[lev];
                }
                else
                {
                    levelChars[i] = '+';
                }
            }
            Errcontln("Levels: " + ILOG.J2CsMapping.Util.StringUtil.NewString(levelChars));
            Errcontln("Source: " + src);
            Errcontln("Result: " + dst);
            Errcontln("Direction: " + bidi.GetDirection());
            Errcontln("paraLevel: " + bidi.GetParaLevel().ToString());
            Errcontln("reorderingMode: " + ModeToString(bidi.GetReorderingMode()));
            Errcontln("reorderingOptions: "
                      + SpOptionsToString(bidi.GetReorderingOptions()));
            Errcont("Runs: " + runCount + " => logicalStart.length/level: ");
            for (int i_0 = 0; i_0 < runCount; i_0++)
            {
                BidiRun run;
                run = bidi.GetVisualRun(i_0);
                Errcont(" " + run.GetStart() + "." + run.GetLength() + "/"
                        + run.GetEmbeddingLevel());
            }
            Errcont("\n");
        }
示例#12
0
        /// <summary>
        /// Updates the <code>TextMeasurer</code> after a single character has
        /// been inserted
        /// into the paragraph currently represented by this
        /// <code>TextMeasurer</code>.  After this call, this
        /// <code>TextMeasurer</code> is equivalent to a new
        /// <code>TextMeasurer</code> created from the text;  however, it will
        /// usually be more efficient to update an existing
        /// <code>TextMeasurer</code> than to create a new one from scratch.
        /// </summary>
        /// <param name="newParagraph"> the text of the paragraph after performing
        /// the insertion.  Cannot be null. </param>
        /// <param name="insertPos"> the position in the text where the character was
        /// inserted.  Must not be less than the start of
        /// <code>newParagraph</code>, and must be less than the end of
        /// <code>newParagraph</code>. </param>
        /// <exception cref="IndexOutOfBoundsException"> if <code>insertPos</code> is less
        ///         than the start of <code>newParagraph</code> or greater than
        ///         or equal to the end of <code>newParagraph</code> </exception>
        /// <exception cref="NullPointerException"> if <code>newParagraph</code> is
        ///         <code>null</code> </exception>
        public void InsertChar(AttributedCharacterIterator newParagraph, int insertPos)
        {
            if (CollectStats)
            {
                PrintStats();
            }
            if (WantStats)
            {
                CollectStats = true;
            }

            FStart = newParagraph.BeginIndex;
            int end = newParagraph.EndIndex;

            if (end - FStart != FChars.Length + 1)
            {
                InitAll(newParagraph);
            }

            char[] newChars     = new char[end - FStart];
            int    newCharIndex = insertPos - FStart;

            System.Array.Copy(FChars, 0, newChars, 0, newCharIndex);

            char newChar = newParagraph.setIndex(insertPos);

            newChars[newCharIndex] = newChar;
            System.Array.Copy(FChars, newCharIndex, newChars, newCharIndex + 1, end - insertPos - 1);
            FChars = newChars;

            if (FBidi != null || Bidi.RequiresBidi(newChars, newCharIndex, newCharIndex + 1) || newParagraph.GetAttribute(TextAttribute.BIDI_EMBEDDING) != null)
            {
                FBidi = new Bidi(newParagraph);
                if (FBidi.LeftToRight)
                {
                    FBidi = null;
                }
            }

            FParagraph = StyledParagraph.InsertChar(newParagraph, FChars, insertPos, FParagraph);
            InvalidateComponents();
        }
示例#13
0
        public void TestInverse2()
        {
            Bidi bidi;
            int  i;

            Logln("\nEntering TestInverse\n");
            bidi = new Bidi();
            Log("inverse Bidi: testInverse(L) with " + testCases.Length
                + " test cases ---\n");
            for (i = 0; i < testCases.Length; ++i)
            {
                Logln("Testing case " + i);
                _testInverseBidi(bidi, testCases[i], IBM.ICU.Text.Bidi.DIRECTION_LEFT_TO_RIGHT);
            }

            Log("inverse Bidi: testInverse(R) with " + testCases.Length
                + " test cases ---\n");
            for (i = 0; i < testCases.Length; ++i)
            {
                Logln("Testing case " + i);
                _testInverseBidi(bidi, testCases[i], IBM.ICU.Text.Bidi.DIRECTION_RIGHT_TO_LEFT);
            }

            _testManyInverseBidi(bidi, IBM.ICU.Text.Bidi.DIRECTION_LEFT_TO_RIGHT);
            _testManyInverseBidi(bidi, IBM.ICU.Text.Bidi.DIRECTION_RIGHT_TO_LEFT);

            Logln("inverse Bidi: rountrips: " + countRoundtrips
                  + "   non-roundtrips: " + countNonRoundtrips);

            _testWriteReverse();

            _testManyAddedPoints();

            _testMisc();

            Logln("\nExiting TestInverse\n");
        }
示例#14
0
        public void TestClassOverride2()
        {
            Bidi bidi;

            Logln("\nEntering TestClassOverride\n");

            bidi = new Bidi();
            VerifyClassifier(bidi);

            classifier = new TestClassOverride.CustomClassifier(((int)(IBM.ICU.Charset.TestData.R)));
            bidi.SetCustomClassifier(classifier);
            VerifyClassifier(bidi);

            classifier.SetContext(null);
            VerifyClassifier(bidi);

            bidi.SetPara(textIn, IBM.ICU.Text.Bidi.LTR, null);

            String xout = bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING);

            AssertEquals("Actual and expected output mismatch", textOut, xout);

            Logln("\nExiting TestClassOverride\n");
        }
示例#15
0
        internal bool MatchingPair(Bidi bidi, int i, char c1, char c2)
        {
            if (c1 == c2)
            {
                return(true);
            }

            /*
             * For REORDER_RUNS_ONLY, it would not be correct to check levels[i], so
             * we use the appropriate run's level, which is good for all cases.
             */
            if (bidi.GetLogicalRun(i).GetDirection() == 0)
            {
                return(false);
            }
            for (int k = 0; k < mates1Chars.Length; k++)
            {
                if ((c1 == mates1Chars[k]) && (c2 == mates2Chars[k]))
                {
                    return(true);
                }
            }
            return(false);
        }
示例#16
0
        public void TestStreaming2()
        {
            String        src, subsrc;
            Bidi          bidi;
            int           srcLen, processedLen, chunk_0, len, nPortions_1, offset;
            int           i, j, levelIndex;
            sbyte         level;
            int           nTests = testCases.Length, nLevels = paraLevels.Length;
            bool          mismatch, testOK = true;
            StringBuilder processedLenStr = new StringBuilder(MAXLOOPS * 5);

            Logln("\nEntering TestStreaming\n");

            bidi = new Bidi();

            bidi.OrderParagraphsLTR(true);

            for (levelIndex = 0; levelIndex < nLevels; levelIndex++)
            {
                for (i = 0; i < nTests; i++)
                {
                    src                    = testCases[i].textIn;
                    srcLen                 = src.Length;
                    chunk_0                = testCases[i].chunk;
                    nPortions_1            = testCases[i].nPortions[levelIndex];
                    level                  = paraLevels[levelIndex];
                    processedLenStr.Length = 0;
                    Logln("Testing level " + level + ", case " + i);

                    mismatch = false;

                    bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_STREAMING);
                    for (j = 0; j < MAXPORTIONS && srcLen > 0; j++)
                    {
                        len    = (chunk_0 < srcLen) ? chunk_0 : srcLen;
                        offset = src.Length - srcLen;
                        subsrc = src.Substring(offset, (offset + len) - (offset));
                        bidi.SetPara(subsrc, level, null);

                        processedLen = bidi.GetProcessedLength();
                        if (processedLen == 0)
                        {
                            bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_DEFAULT);
                            j--;
                            continue;
                        }
                        bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_STREAMING);

                        mismatch |= j >= nPortions_1 ||
                                    processedLen != testCases[i].portionLens[levelIndex][j];

                        processedLenStr
                        .Append(ILOG.J2CsMapping.Util.IlNumber.ToString(processedLen) + " ");
                        srcLen -= processedLen;
                    }

                    if (mismatch || j != nPortions_1)
                    {
                        testOK = false;
                        Errln("\nProcessed lengths mismatch for"
                              + "\n\tParagraph level = " + level
                              + "\n\tInput string: " + IBM.ICU.Impl.Utility.Escape(src)
                              + "\n\tChunk = " + chunk_0
                              + "\n\tActually processed portion lengths: { "
                              + processedLenStr + " }"
                              + "\n\tExpected portion lengths          : { "
                              + testCases[i].message[levelIndex] + " }\n");
                    }
                }
            }
            if (testOK)
            {
                Logln("\nBidi streaming test OK");
            }
            Logln("\nExiting TestStreaming\n");
        }
示例#17
0
        public void TestReorderRunsOnly2()
        {
            Bidi   bidi = new Bidi();
            Bidi   bidiL2V = new Bidi();
            String src, dest, visual1, visual2;
            String srcU16, destU16, visual1U16, visual2U16;
            int    option, i, j, nCases;
            sbyte  level;

            Logln("\nEntering TestReorderRunsOnly\n");
            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_RUNS_ONLY);
            bidiL2V.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_REMOVE_CONTROLS);

            for (option = 0; option < 2; option++)
            {
                bidi.SetReorderingOptions((option == 0) ? IBM.ICU.Text.Bidi.OPTION_REMOVE_CONTROLS
                            : IBM.ICU.Text.Bidi.OPTION_INSERT_MARKS);
                for (i = 0, nCases = testCases.Length; i < nCases; i++)
                {
                    src    = testCases[i].textIn;
                    srcU16 = IBM.ICU.Charset.BidiTest.PseudoToU16(src);
                    for (j = 0; j < 2; j++)
                    {
                        Logln("Now doing test for option " + option + ", case " + i
                              + ", level " + j);
                        level = (sbyte)j;
                        bidi.SetPara(srcU16, level, null);
                        destU16 = bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING);
                        dest    = IBM.ICU.Charset.BidiTest.U16ToPseudo(destU16);
                        CheckWhatYouCan(bidi, src, dest);
                        AssertEquals("Reorder runs only failed for case " + i,
                                     testCases[i].textOut[option][level], dest, src,
                                     null, null, level.ToString());

                        if ((option == 0) && (testCases[i].noroundtrip[level] > 0))
                        {
                            continue;
                        }
                        bidiL2V.SetPara(srcU16, level, null);
                        visual1U16 = bidiL2V.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING);
                        visual1    = IBM.ICU.Charset.BidiTest.U16ToPseudo(visual1U16);
                        CheckWhatYouCan(bidiL2V, src, visual1);
                        bidiL2V.SetPara(destU16, (sbyte)(level ^ 1), null);
                        visual2U16 = bidiL2V.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING);
                        visual2    = IBM.ICU.Charset.BidiTest.U16ToPseudo(visual2U16);
                        CheckWhatYouCan(bidiL2V, dest, visual2);
                        AssertEquals("Round trip failed for case " + i, visual1,
                                     visual2, src, "REORDER_RUNS_ONLY (2)",
                                     (option == 0) ? "0" : "OPTION_INSERT_MARKS",
                                     level.ToString());
                    }
                }
            }

            /* test with null or empty text */
            int paras;

            bidi.SetPara((String)null, IBM.ICU.Text.Bidi.LTR, null);
            paras = bidi.CountParagraphs();
            AssertEquals("\nInvalid number of paras #1 (should be 0): ", 0, paras);
            bidi.SetPara((char[])null, IBM.ICU.Text.Bidi.LTR, null);
            paras = bidi.CountParagraphs();
            AssertEquals("\nInvalid number of paras #2 (should be 0): ", 0, paras);
            bidi.SetPara("", IBM.ICU.Text.Bidi.LTR, null);
            paras = bidi.CountParagraphs();
            AssertEquals("\nInvalid number of paras #3 (should be 0): ", 0, paras);
            bidi.SetPara(new char[0], IBM.ICU.Text.Bidi.LTR, null);
            paras = bidi.CountParagraphs();
            AssertEquals("\nInvalid number of paras #4 (should be 0): ", 0, paras);

            Logln("\nExiting TestReorderRunsOnly\n");
        }
示例#18
0
        public static bool Run()
        {
            Console.WriteLine("Bidi Character Tests");
            Console.WriteLine("--------------------");
            Console.WriteLine();

            // Read the test file
            var location = System.IO.Path.GetDirectoryName(typeof(BidiCharacterTest).Assembly.Location);
            var lines    = System.IO.File.ReadAllLines(System.IO.Path.Combine(location,
                                                                              System.IO.Path.Combine("TestData", "BidiCharacterTest.txt")));

            // Parse lines
            var tests = new List <Test>();

            for (int lineNumber = 1; lineNumber < lines.Length + 1; lineNumber++)
            {
                // Get the line, remove comments
                var line = lines[lineNumber - 1].Split('#')[0].Trim();

                // Ignore blank/comment only lines
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                // Split into fields
                var fields = line.Split(';');

                var test = new Test();
                test.LineNumber = lineNumber;

                // Parse field 0 - code points
                test.CodePoints = fields[0].Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).Select(x => Convert.ToInt32(x, 16)).ToArray();

                // Parse field 1 - paragraph level
                test.ParagraphLevel = sbyte.Parse(fields[1]);

                // Parse field 2 - resolved paragraph level
                test.ResolvedParagraphLevel = sbyte.Parse(fields[2]);

                // Parse field 3 - resolved levels
                test.ResolvedLevels = fields[3].Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).Select(x => x == "x" ? (sbyte)-1 : Convert.ToSByte(x)).ToArray();

                // Parse field 4 - resolved levels
                test.ResolvedOrder = fields[4].Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).Select(x => Convert.ToInt32(x)).ToArray();

                tests.Add(test);
            }

            Console.WriteLine($"Test data loaded: {tests.Count} test cases");

            var bidi     = new Bidi();
            var bidiData = new BidiData();

            // Run tests...
            var tr = new TestResults();

            for (int testNumber = 0; testNumber < tests.Count; testNumber++)
            {
                var t = tests[testNumber];

                // Arrange
                bidiData.Init(new Slice <int>(t.CodePoints), t.ParagraphLevel);

                // Act

                tr.EnterTest();
                for (int i = 0; i < 10; i++)
                {
                    bidi.Process(bidiData);
                }
                tr.LeaveTest();
                var resultLevels         = bidi.ResolvedLevels;
                int resultParagraphLevel = bidi.ResolvedParagraphEmbeddingLevel;

                // Assert
                bool passed = true;
                if (t.ResolvedParagraphLevel != resultParagraphLevel)
                {
                    passed = false;
                }
                for (int i = 0; i < t.ResolvedLevels.Length; i++)
                {
                    if (t.ResolvedLevels[i] == -1)
                    {
                        continue;
                    }

                    if (t.ResolvedLevels[i] != resultLevels[i])
                    {
                        passed = false;
                        break;
                    }
                }

                /*
                 * if (!passed)
                 * {
                 *  Console.WriteLine($"Failed line {t.LineNumber}");
                 *  Console.WriteLine();
                 *  Console.WriteLine($"             Code Points: {string.Join(" ", t.CodePoints.Select(x => x.ToString("X4")))}");
                 *  Console.WriteLine($"      Pair Bracket Types: {string.Join(" ", bidiData.PairedBracketTypes.Select(x => "   " + x.ToString()))}");
                 *  Console.WriteLine($"     Pair Bracket Values: {string.Join(" ", bidiData.PairedBracketValues.Select(x => x.ToString("X4")))}");
                 *  Console.WriteLine($"             Embed Level: {t.ParagraphLevel}");
                 *  Console.WriteLine($"    Expected Embed Level: {t.ResolvedParagraphLevel}");
                 *  Console.WriteLine($"      Actual Embed Level: {resultParagraphLevel}");
                 *  Console.WriteLine($"          Directionality: {string.Join(" ", bidiData.Types)}");
                 *  Console.WriteLine($"         Expected Levels: {string.Join(" ", t.ResolvedLevels)}");
                 *  Console.WriteLine($"           Actual Levels: {string.Join(" ", resultLevels)}");
                 *  Console.WriteLine();
                 *  return false;
                 * }
                 */

                // Record it
                tr.TestPassed(passed);
            }

            tr.Dump();

            return(tr.AllPassed);
        }
示例#19
0
    public Example_27()
    {
        PDF pdf = new PDF(new BufferedStream(
                              new FileStream("Example_27.pdf", FileMode.Create)));

        Page page = new Page(pdf, Letter.PORTRAIT);

        // Thai font
        Font f1 = new Font(pdf,
                           new FileStream(
                               "fonts/Noto/NotoSansThai-Regular.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f1.SetSize(14f);

        // Latin font
        Font f2 = new Font(pdf,
                           new FileStream(
                               "fonts/Droid/DroidSans.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f2.SetSize(12f);

        // Hebrew font
        Font f3 = new Font(pdf,
                           new FileStream(
                               "fonts/Noto/NotoSansHebrew-Regular.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f3.SetSize(12f);

        // Arabic font
        Font f4 = new Font(pdf,
                           new FileStream(
                               "fonts/Noto/NotoNaskhArabic-Regular.ttf",
                               FileMode.Open,
                               FileAccess.Read));

        f4.SetSize(12f);

        float x = 50f;
        float y = 50f;

        TextLine text = new TextLine(f1);

        text.SetFallbackFont(f2);
        text.SetLocation(x, y);

        StringBuilder buf = new StringBuilder();

        for (int i = 0x0E01; i < 0x0E5B; i++)
        {
            if (i % 16 == 0)
            {
                text.SetText(buf.ToString());
                text.SetLocation(x, y += 24f);
                text.DrawOn(page);
                buf = new StringBuilder();
            }
            if (i > 0x0E30 && i < 0x0E3B)
            {
                buf.Append("\u0E01");
            }
            if (i > 0x0E46 && i < 0x0E4F)
            {
                buf.Append("\u0E2D");
            }
            buf.Append((char)i);
        }

        text.SetText(buf.ToString());
        text.SetLocation(x, y += 20f);
        text.DrawOn(page);

        y += 20f;

        String str = "\u0E1C\u0E1C\u0E36\u0E49\u0E07 abc 123";

        text.SetText(str);
        text.SetLocation(x, y);
        text.DrawOn(page);

        y += 20f;

        str = "כך נראית תחתית הטבלה עם סיום הפלייאוף התחתון:";
        str = Bidi.ReorderVisually(str);
        TextLine textLine = new TextLine(f3, str);

        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "10. הפועל כפר סבא 38 נקודות (הפרש שערים 14-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "11. הפועל קריית שמונה 36 נקודות (הפרש שערים 7-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "12. הפועל חיפה 34 נקודות (הפרש שערים 10-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str      = "13. הפועל עכו 34 נקודות (הפרש שערים 21-)";
        str      = Bidi.ReorderVisually(str);
        textLine = new TextLine(f3, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f3.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        y += 40f;

        str = Bidi.ReorderVisually(
            "قالت شركة PSA بيجو ستروين الفرنسية وشريكتها الصينية شركة دونغفينغ موترز الاربعاء إنهما اتفقتا");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "على التعاون في تطوير السيارات التي تعمل بالطاقة الكهربائية اعتبارا من عام 2019.");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "وجاء في تصريح اصدرته في باريس الشركة الفرنسية ان الشركتين ستنتجان نموذجا كهربائيا مشتركا تستخدمه كل");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "من بيجو وسيتروين ودونغفينغ.");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        str = Bidi.ReorderVisually(
            "وقالت إن الخطة تهدف الى تحقيق عائد يزيد على 100 مليار يوان (15,4 مليار دولار) بحلول عام 2020.");
        textLine = new TextLine(f4, str);
        textLine.SetFallbackFont(f2);
        textLine.SetLocation(600f - f4.StringWidth(f2, str), y += 20f);
        textLine.DrawOn(page);

        pdf.Close();
    }
示例#20
0
        public void TestMultipleParagraphs2()
        {
            sbyte gotLevel;

            sbyte[] gotLevels;
            bool    orderParagraphsLTR;
            String  src;
            Bidi    bidi = new Bidi();
            Bidi    bidiLine;
            int     count, paraStart, paraLimit, paraIndex, length;
            int     i, j, k;

            Logln("\nEntering TestMultipleParagraphs\n");
            try {
                bidi.SetPara(text, IBM.ICU.Text.Bidi.LTR, null);
            } catch (ArgumentException e) {
                Errln("1st Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.LTR);
            }

            /* check paragraph count and boundaries */
            if (paraCount != (count = bidi.CountParagraphs()))
            {
                Errln("1st Bidi.countParagraphs returned " + count + ", should be "
                      + paraCount);
            }
            BidiRun run;

            for (i = 0; i < paraCount; i++)
            {
                run       = bidi.GetParagraphByIndex(i);
                paraStart = run.GetStart();
                paraLimit = run.GetLimit();
                if ((paraStart != paraBounds[i]) ||
                    (paraLimit != paraBounds[i + 1]))
                {
                    Errln("Found boundaries of paragraph " + i + ": " + paraStart
                          + "-" + paraLimit + "; expected: " + paraBounds[i]
                          + "-" + paraBounds[i + 1]);
                }
            }

            /* check with last paragraph not terminated by B */
            char[] chars = text.ToCharArray();
            chars[chars.Length - 1] = 'L';
            src = ILOG.J2CsMapping.Util.StringUtil.NewString(chars);
            try {
                bidi.SetPara(src, IBM.ICU.Text.Bidi.LTR, null);
            } catch (ArgumentException e_0) {
                Errln("2nd Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.LTR);
            }
            if (paraCount != (count = bidi.CountParagraphs()))
            {
                Errln("2nd Bidi.countParagraphs returned " + count + ", should be "
                      + paraCount);
            }
            i         = paraCount - 1;
            run       = bidi.GetParagraphByIndex(i);
            paraStart = run.GetStart();
            paraLimit = run.GetLimit();
            if ((paraStart != paraBounds[i]) || (paraLimit != paraBounds[i + 1]))
            {
                Errln("2nd Found boundaries of paragraph " + i + ": " + paraStart
                      + "-" + paraLimit + "; expected: " + paraBounds[i] + "-"
                      + paraBounds[i + 1]);
            }

            /* check paraLevel for all paragraphs under various paraLevel specs */
            for (k = 0; k < 6; k++)
            {
                try {
                    bidi.SetPara(src, paraLevels[k], null);
                } catch (ArgumentException e_1) {
                    Errln("3nd Bidi.setPara failed, paraLevel = " + paraLevels[k]);
                }
                for (i = 0; i < paraCount; i++)
                {
                    paraIndex = bidi.GetParagraphIndex(paraBounds[i]);
                    run       = bidi.GetParagraph(paraBounds[i]);
                    if (paraIndex != i)
                    {
                        Errln("#1 For paraLevel = " + paraLevels[k]
                              + " paragraph = " + i + ", found paragraph"
                              + " index = " + paraIndex + " expected = " + i);
                    }
                    gotLevel = run.GetEmbeddingLevel();
                    if (gotLevel != multiLevels[k][i])
                    {
                        Errln("#2 For paraLevel = " + paraLevels[k]
                              + " paragraph = " + i + ", found level = "
                              + gotLevel + ", expected = " + multiLevels[k][i]);
                    }
                }
                gotLevel = bidi.GetParaLevel();
                if (gotLevel != multiLevels[k][0])
                {
                    Errln("#3 For paraLevel = " + paraLevels[k]
                          + " getParaLevel = " + gotLevel + ", expected "
                          + multiLevels[k][0]);
                }
            }

            /*
             * check that the result of Bidi.getParaLevel changes if the first
             * paragraph has a different level
             */
            chars[0] = '\u05d2';     /* Hebrew letter Gimel */
            src      = ILOG.J2CsMapping.Util.StringUtil.NewString(chars);
            try {
                bidi.SetPara(src, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, null);
            } catch (ArgumentException e_2) {
                Errln("Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR);
            }
            gotLevel = bidi.GetParaLevel();
            if (gotLevel != IBM.ICU.Text.Bidi.RTL)
            {
                Errln("#4 For paraLevel = Bidi.LEVEL_DEFAULT_LTR getParaLevel = "
                      + gotLevel + ", expected = " + IBM.ICU.Text.Bidi.RTL);
            }

            /* check that line cannot overlap paragraph boundaries */
            bidiLine = new Bidi();
            i        = paraBounds[1];
            k        = paraBounds[2] + 1;
            try {
                bidiLine = bidi.SetLine(i, k);
                Errln("For line limits " + i + "-" + k
                      + " got success, while expected failure");
            } catch (Exception e_3) {
            }

            i = paraBounds[1];
            k = paraBounds[2];
            try {
                bidiLine = bidi.SetLine(i, k);
            } catch (Exception e_4) {
                Errln("For line limits " + i + "-" + k + " got failure");
            }

            /*
             * check level of block separator at end of paragraph when
             * orderParagraphsLTR==FALSE
             */
            try {
                bidi.SetPara(src, IBM.ICU.Text.Bidi.RTL, null);
            } catch (ArgumentException e_5) {
                Errln("Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.RTL);
            }
            /* get levels through para Bidi block */
            try {
                gotLevels = bidi.GetLevels();
            } catch (Exception e_6) {
                Errln("Error on Bidi.getLevels");
                gotLevels = new sbyte[bidi.GetLength()];
                ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
            }
            for (i = 26; i < 32; i++)
            {
                if (gotLevels[i] != IBM.ICU.Text.Bidi.RTL)
                {
                    Errln("For char " + i + "(0x" + IBM.ICU.Impl.Utility.Hex(chars[i])
                          + "), level = " + gotLevels[i] + ", expected = "
                          + IBM.ICU.Text.Bidi.RTL);
                }
            }
            /* get levels through para Line block */
            i = paraBounds[1];
            k = paraBounds[2];
            try {
                bidiLine = bidi.SetLine(i, k);
            } catch (Exception e_7) {
                Errln("For line limits " + i + "-" + k + " got failure");
                return;
            }
            paraIndex = bidiLine.GetParagraphIndex(i);
            run       = bidiLine.GetParagraph(i);
            try {
                gotLevels = bidiLine.GetLevels();
            } catch (Exception e_8) {
                Errln("Error on bidiLine.getLevels");
                gotLevels = new sbyte[bidiLine.GetLength()];
                ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
            }
            length   = bidiLine.GetLength();
            gotLevel = run.GetEmbeddingLevel();
            if ((gotLevel != IBM.ICU.Text.Bidi.RTL) || (gotLevels[length - 1] != IBM.ICU.Text.Bidi.RTL))
            {
                Errln("For paragraph " + paraIndex + " with limits "
                      + run.GetStart() + "-" + run.GetLimit() + ", paraLevel = "
                      + gotLevel + "expected = " + IBM.ICU.Text.Bidi.RTL
                      + ", level of separator = " + gotLevels[length - 1]
                      + " expected = " + IBM.ICU.Text.Bidi.RTL);
            }
            orderParagraphsLTR = bidi.IsOrderParagraphsLTR();
            AssertFalse("orderParagraphsLTR is true", orderParagraphsLTR);
            bidi.OrderParagraphsLTR(true);
            orderParagraphsLTR = bidi.IsOrderParagraphsLTR();
            AssertTrue("orderParagraphsLTR is false", orderParagraphsLTR);

            /*
             * check level of block separator at end of paragraph when
             * orderParagraphsLTR==TRUE
             */
            try {
                bidi.SetPara(src, IBM.ICU.Text.Bidi.RTL, null);
            } catch (ArgumentException e_9) {
                Errln("Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.RTL);
            }
            /* get levels through para Bidi block */
            try {
                gotLevels = bidi.GetLevels();
            } catch (Exception e_10) {
                Errln("Error on Bidi.getLevels");
                gotLevels = new sbyte[bidi.GetLength()];
                ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
            }
            for (i = 26; i < 32; i++)
            {
                if (gotLevels[i] != 0)
                {
                    Errln("For char " + i + "(0x" + IBM.ICU.Impl.Utility.Hex(chars[i])
                          + "), level = " + gotLevels[i] + ", expected = 0");
                }
            }
            /* get levels through para Line block */
            i         = paraBounds[1];
            k         = paraBounds[2];
            paraStart = run.GetStart();
            paraLimit = run.GetLimit();
            try {
                bidiLine = bidi.SetLine(paraStart, paraLimit);
            } catch (Exception e_11) {
                Errln("For line limits " + paraStart + "-" + paraLimit
                      + " got failure");
            }
            paraIndex = bidiLine.GetParagraphIndex(i);
            run       = bidiLine.GetParagraph(i);
            try {
                gotLevels = bidiLine.GetLevels();
            } catch (Exception e_12) {
                Errln("Error on bidiLine.getLevels");
                gotLevels = new sbyte[bidiLine.GetLength()];
                ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
            }
            length   = bidiLine.GetLength();
            gotLevel = run.GetEmbeddingLevel();
            if ((gotLevel != IBM.ICU.Text.Bidi.RTL) || (gotLevels[length - 1] != 0))
            {
                Err("\nFor paragraph " + paraIndex + " with limits "
                    + run.GetStart() + "-" + run.GetLimit() + ", paraLevel = "
                    + gotLevel + "expected = " + IBM.ICU.Text.Bidi.RTL
                    + ", level of separator = " + gotLevels[length - 1]
                    + " expected = 0\nlevels = ");
                for (count = 0; count < length; count++)
                {
                    Errcont(gotLevels[count] + "  ");
                }
                Errcont("\n");
            }

            /*
             * test that the concatenation of separate invocations of the bidi code
             * on each individual paragraph in order matches the levels array that
             * results from invoking bidi once over the entire multiparagraph tests
             * (with orderParagraphsLTR false, of course)
             */
            src = text;     /* restore original content */
            bidi.OrderParagraphsLTR(false);
            try {
                bidi.SetPara(src, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            } catch (ArgumentException e_13) {
                Errln("Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL);
            }
            try {
                gotLevels = bidi.GetLevels();
            } catch (Exception e_14) {
                Errln("Error on bidiLine.getLevels");
                gotLevels = new sbyte[bidi.GetLength()];
                ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
            }
            for (i = 0; i < paraCount; i++)
            {
                /* use pLine for individual paragraphs */
                paraStart = paraBounds[i];
                length    = paraBounds[i + 1] - paraStart;
                try {
                    bidiLine.SetPara(src.Substring(paraStart, (paraStart + length) - (paraStart)),
                                     IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
                } catch (ArgumentException e_15) {
                    Errln("Bidi.setPara failed, paraLevel = "
                          + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL);
                }
                for (j = 0; j < length; j++)
                {
                    if ((k = bidiLine.GetLevelAt(j)) != (gotLevel = gotLevels[paraStart
                                                                              + j]))
                    {
                        Errln("Checking paragraph concatenation: for paragraph["
                              + i + "], char[" + j + "] = 0x"
                              + IBM.ICU.Impl.Utility.Hex(src[paraStart + j])
                              + ", level = " + k + ", expected = " + gotLevel);
                    }
                }
            }

            /*
             * ensure that leading numerics in a paragraph are not treated as arabic
             * numerals because of arabic text in a preceding paragraph
             */
            src = text2;
            bidi.OrderParagraphsLTR(true);
            try {
                bidi.SetPara(src, IBM.ICU.Text.Bidi.RTL, null);
            } catch (ArgumentException e_16) {
                Errln("Bidi.setPara failed, paraLevel = " + IBM.ICU.Text.Bidi.RTL);
            }
            try {
                gotLevels = bidi.GetLevels();
            } catch (Exception e_17) {
                Errln("Error on Bidi.getLevels");
                gotLevels = new sbyte[bidi.GetLength()];
                ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
            }
            for (i = 0, length = src.Length; i < length; i++)
            {
                if (gotLevels[i] != levels2[i])
                {
                    Errln("Checking leading numerics: for char " + i + "(0x"
                          + IBM.ICU.Impl.Utility.Hex(src[i]) + "), level = "
                          + gotLevels[i] + ", expected = " + levels2[i]);
                }
            }

            /*
             * check handling of whitespace before end of paragraph separator when
             * orderParagraphsLTR==TRUE, when last paragraph has, and lacks, a
             * terminating B
             */
            chars = src.ToCharArray();
            ILOG.J2CsMapping.Collections.Arrays.Fill(chars, '\u0020');
            bidi.OrderParagraphsLTR(true);
            for (i = 0x001c; i <= 0x0020; i += (0x0020 - 0x001c))
            {
                chars[4] = (char)i;      /* with and without terminating B */
                for (j = 0x0041; j <= 0x05d0; j += (0x05d0 - 0x0041))
                {
                    chars[0] = (char)j;      /* leading 'A' or Alef */
                    src      = ILOG.J2CsMapping.Util.StringUtil.NewString(chars);
                    for (gotLevel = 4; gotLevel <= 5; gotLevel++)
                    {
                        /* test even and odd paraLevel */
                        try {
                            bidi.SetPara(src, gotLevel, null);
                        } catch (ArgumentException e_18) {
                            Errln("Bidi.setPara failed, paraLevel = " + gotLevel);
                        }
                        try {
                            gotLevels = bidi.GetLevels();
                        } catch (Exception e_19) {
                            Errln("Error on Bidi.getLevels");
                            gotLevels = new sbyte[bidi.GetLength()];
                            ILOG.J2CsMapping.Collections.Arrays.Fill(gotLevels, (sbyte)-1);
                        }
                        for (k = 1; k <= 3; k++)
                        {
                            if (gotLevels[k] != gotLevel)
                            {
                                Errln("Checking trailing spaces for leading char 0x"
                                      + IBM.ICU.Impl.Utility.Hex(chars[0])
                                      + ", last_char = "
                                      + IBM.ICU.Impl.Utility.Hex(chars[4])
                                      + ", index = "
                                      + k
                                      + "level = "
                                      + gotLevels[k]
                                      + ", expected = " + gotLevel);
                            }
                        }
                    }
                }
            }

            /*
             * check default orientation when inverse bidi and paragraph starts with
             * LTR strong char and ends with RTL strong char, with and without a
             * terminating B
             */
            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_INVERSE_LIKE_DIRECT);
            bidi.SetPara("abc \u05d2\u05d1\n", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, null);
            String xout = bidi.WriteReordered(0);

            AssertEquals("\nInvalid output", "\u05d1\u05d2 abc\n", xout);
            bidi.SetPara("abc \u05d2\u05d1", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nInvalid output #1", "\u05d1\u05d2 abc", xout);

            /*
             * check multiple paragraphs together with explicit levels
             */
            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_DEFAULT);
            gotLevels = new sbyte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            bidi.SetPara("ab\u05d1\u05d2\n\u05d3\u05d4123", IBM.ICU.Text.Bidi.LTR, gotLevels);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nInvalid output #2", "ab\u05d2\u05d1\n123\u05d4\u05d3",
                         xout);
            AssertEquals("\nInvalid number of paras", 2, bidi.CountParagraphs());

            Logln("\nExiting TestMultipleParagraphs\n");
        }
        private bool CheckMaps(Bidi bidi, int stringIndex, String src,
                               String dest, String mode, String option, sbyte level, bool forward)
        {
            int[] actualLogicalMap;
            int[] actualVisualMap;
            int[] getIndexMap;
            int   i, srcLen, resLen, index;

            int[] expectedLogicalMap, expectedVisualMap;
            bool  testOK = true;

            if (forward)
            {
                expectedLogicalMap = forwardMap[stringIndex];
                expectedVisualMap  = inverseMap[stringIndex];
            }
            else
            {
                expectedLogicalMap = inverseMap[stringIndex];
                expectedVisualMap  = forwardMap[stringIndex];
            }
            actualLogicalMap = bidi.GetLogicalMap();
            srcLen           = bidi.GetProcessedLength();
            if (!ILOG.J2CsMapping.Collections.Arrays.Equals(expectedLogicalMap, actualLogicalMap))
            {
                Err("Bidi.getLogicalMap returned unexpected map for output "
                    + "string index "
                    + stringIndex
                    + "\n"
                    + "source: "
                    + src
                    + "\n"
                    + "dest  : "
                    + dest
                    + "\n"
                    + "Scale : "
                    + IBM.ICU.Charset.BidiTest.columnString
                    + "\n"
                    + "ExpMap: "
                    + FormatMap(expectedLogicalMap)
                    + "\n"
                    + "Actual: "
                    + FormatMap(actualLogicalMap)
                    + "\n"
                    + "Paragraph level  : "
                    + level
                    + " == "
                    + bidi.GetParaLevel()
                    + "\n"
                    + "Reordering mode  : "
                    + mode
                    + " == "
                    + bidi.GetReorderingMode()
                    + "\n"
                    + "Reordering option: "
                    + option
                    + " == "
                    + bidi.GetReorderingOptions()
                    + "\n"
                    + "Forward flag     : " + forward + "\n");
                testOK = false;
            }
            resLen          = bidi.GetResultLength();
            actualVisualMap = bidi.GetVisualMap();
            if (!ILOG.J2CsMapping.Collections.Arrays.Equals(expectedVisualMap, actualVisualMap))
            {
                Err("Bidi.getVisualMap returned unexpected map for output "
                    + "string index "
                    + stringIndex
                    + "\n"
                    + "source: "
                    + src
                    + "\n"
                    + "dest  : "
                    + dest
                    + "\n"
                    + "Scale : "
                    + IBM.ICU.Charset.BidiTest.columnString
                    + "\n"
                    + "ExpMap: "
                    + FormatMap(expectedVisualMap)
                    + "\n"
                    + "Actual: "
                    + FormatMap(actualVisualMap)
                    + "\n"
                    + "Paragraph level  : "
                    + level
                    + " == "
                    + bidi.GetParaLevel()
                    + "\n"
                    + "Reordering mode  : "
                    + mode
                    + " == "
                    + bidi.GetReorderingMode()
                    + "\n"
                    + "Reordering option: "
                    + option
                    + " == "
                    + bidi.GetReorderingOptions()
                    + "\n"
                    + "Forward flag     : " + forward + "\n");
                testOK = false;
            }
            getIndexMap = new int[srcLen];
            for (i = 0; i < srcLen; i++)
            {
                index          = bidi.GetVisualIndex(i);
                getIndexMap[i] = index;
            }
            if (!ILOG.J2CsMapping.Collections.Arrays.Equals(actualLogicalMap, getIndexMap))
            {
                Err("Mismatch between getLogicalMap and getVisualIndex for output "
                    + "string index "
                    + stringIndex
                    + "\n"
                    + "source: "
                    + src
                    + "\n"
                    + "dest  : "
                    + dest
                    + "\n"
                    + "Scale : "
                    + IBM.ICU.Charset.BidiTest.columnString
                    + "\n"
                    + "ActMap: "
                    + FormatMap(actualLogicalMap)
                    + "\n"
                    + "IdxMap: "
                    + FormatMap(getIndexMap)
                    + "\n"
                    + "Paragraph level  : "
                    + level
                    + " == "
                    + bidi.GetParaLevel()
                    + "\n"
                    + "Reordering mode  : "
                    + mode
                    + " == "
                    + bidi.GetReorderingMode()
                    + "\n"
                    + "Reordering option: "
                    + option
                    + " == "
                    + bidi.GetReorderingOptions()
                    + "\n"
                    + "Forward flag     : " + forward + "\n");
                testOK = false;
            }
            getIndexMap = new int[resLen];
            for (i = 0; i < resLen; i++)
            {
                index          = bidi.GetLogicalIndex(i);
                getIndexMap[i] = index;
            }
            if (!ILOG.J2CsMapping.Collections.Arrays.Equals(actualVisualMap, getIndexMap))
            {
                Err("Mismatch between getVisualMap and getLogicalIndex for output "
                    + "string index "
                    + stringIndex
                    + "\n"
                    + "source: "
                    + src
                    + "\n"
                    + "dest  : "
                    + dest
                    + "\n"
                    + "Scale : "
                    + IBM.ICU.Charset.BidiTest.columnString
                    + "\n"
                    + "ActMap: "
                    + FormatMap(actualVisualMap)
                    + "\n"
                    + "IdxMap: "
                    + FormatMap(getIndexMap)
                    + "\n"
                    + "Paragraph level  : "
                    + level
                    + " == "
                    + bidi.GetParaLevel()
                    + "\n"
                    + "Reordering mode  : "
                    + mode
                    + " == "
                    + bidi.GetReorderingMode()
                    + "\n"
                    + "Reordering option: "
                    + option
                    + " == "
                    + bidi.GetReorderingOptions()
                    + "\n"
                    + "Forward flag     : " + forward + "\n");
                testOK = false;
            }
            return(testOK);
        }
        private bool AssertRoundTrip(Bidi bidi, int tc, int outIndex,
                                     String src, String dest, int mode, int option, sbyte level)
        {
            String descMode, descOption;
            String dest2;

            switch (modes[mode])
            {
            case IBM.ICU.Text.Bidi.REORDER_NUMBERS_SPECIAL:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_INVERSE_FOR_NUMBERS_SPECIAL);
                break;

            case IBM.ICU.Text.Bidi.REORDER_GROUP_NUMBERS_WITH_R:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_GROUP_NUMBERS_WITH_R);
                break;

            case IBM.ICU.Text.Bidi.REORDER_RUNS_ONLY:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_RUNS_ONLY);
                break;

            case IBM.ICU.Text.Bidi.REORDER_INVERSE_NUMBERS_AS_L:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_DEFAULT);
                break;

            case IBM.ICU.Text.Bidi.REORDER_INVERSE_LIKE_DIRECT:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_DEFAULT);
                break;

            case IBM.ICU.Text.Bidi.REORDER_INVERSE_FOR_NUMBERS_SPECIAL:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_NUMBERS_SPECIAL);
                break;

            default:
                bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_INVERSE_LIKE_DIRECT);
                break;
            }
            bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_REMOVE_CONTROLS);

            bidi.SetPara(IBM.ICU.Charset.BidiTest.PseudoToU16(dest), level, null);
            dest2 = bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING);

            dest2 = IBM.ICU.Charset.BidiTest.U16ToPseudo(dest2);
            CheckWhatYouCan(bidi, dest, dest2);
            descMode   = IBM.ICU.Charset.BidiTest.ModeToString(modes[mode]);
            descOption = IBM.ICU.Charset.BidiTest.SpOptionsToString(options[option]);
            if (!src.Equals(dest2))
            {
                if (roundtrip[tc][mode][option][level] == 1)
                {
                    Errln("\nRound trip failed for case=" + tc + " mode=" + mode
                          + " option=" + option + "\nOriginal text:      " + src
                          + "\nRound-tripped text: " + dest2
                          + "\nIntermediate text:  " + dest
                          + "\nReordering mode:    " + descMode
                          + "\nReordering option:  " + descOption
                          + "\nParagraph level:    " + level);
                }
                else
                {
                    Logln("\nExpected round trip failure for case=" + tc + " mode="
                          + mode + " option=" + option + "\nOriginal text:      "
                          + src + "\nRound-tripped text: " + dest2
                          + "\nIntermediate text:  " + dest
                          + "\nReordering mode:    " + descMode
                          + "\nReordering option:  " + descOption
                          + "\nParagraph level:    " + level);
                }
                return(false);
            }
            if (!CheckResultLength(bidi, dest, dest2, descMode,
                                   "OPTION_REMOVE_CONTROLS", level))
            {
                return(false);
            }
            if ((outIndex > -1) &&
                !CheckMaps(bidi, outIndex, src, dest, descMode,
                           "OPTION_REMOVE_CONTROLS", level, false))
            {
                return(false);
            }
            return(true);
        }
示例#23
0
        private void DoTest(Bidi bidi, int testNumber, TestData test,
                            int lineStart, bool countRunsFirst)
        {
            short[] dirProps = test.dirProps;
            byte[]  levels = test.levels;
            int[]   visualMap = test.visualMap;
            int     i, len = bidi.GetLength(), logicalIndex = -1, runCount = 0;
            sbyte   level, level2;

            if (countRunsFirst)
            {
                Logln("Calling Bidi.countRuns() first.");
                try {
                    runCount = bidi.CountRuns();
                } catch (InvalidOperationException e) {
                    Errln("Bidi.countRuns(test[" + testNumber + "]) failed");
                }
            }
            else
            {
                Logln("Calling Bidi.getLogicalMap() first.");
            }

            _testReordering(bidi, testNumber);

            for (i = 0; i < len; ++i)
            {
                Logln(i + "  " + bidi.GetLevelAt(i) + "  " + levelString
                      + IBM.ICU.Charset.TestData.dirPropNames[dirProps[lineStart + i]] + "  "
                      + bidi.GetVisualIndex(i));
            }

            Log("\n-----levels:");
            for (i = 0; i < len; ++i)
            {
                if (i > 0)
                {
                    Log(",");
                }
                Log(" " + bidi.GetLevelAt(i));
            }

            Log("\n--reordered:");
            for (i = 0; i < len; ++i)
            {
                if (i > 0)
                {
                    Log(",");
                }
                Log(" " + bidi.GetVisualIndex(i));
            }
            Log("\n");

            AssertEquals(
                "\nFailure in Bidi.getDirection(test[" + testNumber + "])",
                test.direction, bidi.GetDirection());
            AssertEquals(
                "\nFailure in Bidi.getParaLevel(test[" + testNumber + "])",
                test.resultLevel, bidi.GetParaLevel());

            for (i = 0; i < len; ++i)
            {
                AssertEquals("\nFailure in Bidi.getLevelAt(" + i + ") in test["
                             + testNumber + "]", levels[i], bidi.GetLevelAt(i));
            }

            for (i = 0; i < len; ++i)
            {
                try {
                    logicalIndex = bidi.GetVisualIndex(i);
                } catch (Exception th) {
                    Errln("Bidi.getVisualIndex(" + i + ") in test[" + testNumber
                          + "] failed");
                }
                if (visualMap[i] != logicalIndex)
                {
                    AssertEquals("\nFailure in Bidi.getVisualIndex(" + i
                                 + ") in test[" + testNumber + "])", visualMap[i],
                                 logicalIndex);
                }
            }

            if (!countRunsFirst)
            {
                try {
                    runCount = bidi.CountRuns();
                } catch (InvalidOperationException e_0) {
                    Errln("Bidi.countRuns(test[" + testNumber + "]) failed");
                }
            }

            BidiRun run;

            for (logicalIndex = 0; logicalIndex < len;)
            {
                level        = bidi.GetLevelAt(logicalIndex);
                run          = bidi.GetLogicalRun(logicalIndex);
                logicalIndex = run.GetLimit();
                level2       = run.GetEmbeddingLevel();
                AssertEquals("Logical " + run.ToString() + " in test[" + testNumber
                             + "]: wrong level", level, level2);
                if (--runCount < 0)
                {
                    Errln("Bidi.getLogicalRun(test["
                          + testNumber
                          + "]): wrong number of runs compared to Bidi.countRuns() = "
                          + bidi.CountRuns());
                }
            }
            if (runCount != 0)
            {
                Errln("Bidi.getLogicalRun(test["
                      + testNumber
                      + "]): wrong number of runs compared to Bidi.countRuns() = "
                      + bidi.CountRuns());
            }

            Log("\n\n");
        }
        public void TestReorderingMode2()
        {
            String src, dest;
            Bidi   bidi = new Bidi();
            Bidi   bidi2 = new Bidi();
            Bidi   bidi3 = new Bidi();
            int    tc, mode, option, level;
            int    modeValue, modeBack;
            int    optionValue, optionBack;
            int    index;
            String expected;
            bool   testOK = true;

            Logln("\nEntering TestReorderingMode\n");

            bidi2.SetInverse(true);

            for (tc = 0; tc < TC_COUNT; tc++)
            {
                src = textIn[tc];

                for (mode = 0; mode < MODES_COUNT; mode++)
                {
                    modeValue = modes[mode];
                    bidi.SetReorderingMode(modeValue);
                    modeBack = bidi.GetReorderingMode();
                    if (modeValue != modeBack)
                    {
                        Errln("Error while setting reordering mode to " + modeValue
                              + ", returned " + modeBack);
                    }

                    for (option = 0; option < OPTIONS_COUNT; option++)
                    {
                        optionValue = options[option];
                        bidi.SetReorderingOptions(optionValue);
                        optionBack = bidi.GetReorderingOptions();
                        if (optionValue != optionBack)
                        {
                            Errln("Error while setting reordering options to "
                                  + modeValue + ", returned " + modeBack);
                        }

                        for (level = 0; level < LEVELS_COUNT; level++)
                        {
                            Logln("starting test " + tc + " mode=" + modeValue
                                  + " option=" + optionValue + " level=" + level);
                            bidi.SetPara(IBM.ICU.Charset.BidiTest.PseudoToU16(src), paraLevels[level], null);

                            dest = bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING);
                            dest = IBM.ICU.Charset.BidiTest.U16ToPseudo(dest);
                            if (!((modeValue == IBM.ICU.Text.Bidi.REORDER_INVERSE_NUMBERS_AS_L) && (optionValue == IBM.ICU.Text.Bidi.OPTION_INSERT_MARKS)))
                            {
                                CheckWhatYouCan(bidi, src, dest);
                            }
                            String modeDesc = IBM.ICU.Charset.BidiTest.ModeToString(modeValue);
                            String optDesc  = IBM.ICU.Charset.BidiTest.SpOptionsToString(optionValue);

                            if (modeValue == IBM.ICU.Text.Bidi.REORDER_INVERSE_NUMBERS_AS_L)
                            {
                                index    = -1;
                                expected = InverseBasic(bidi2, src, optionValue,
                                                        paraLevels[level]);
                            }
                            else
                            {
                                index    = outIndices[tc][mode][option][level];
                                expected = textOut[index];
                            }
                            if (!AssertEquals(
                                    "Actual and expected output mismatch",
                                    expected, dest, src, modeDesc, optDesc,
                                    level.ToString()))
                            {
                                testOK = false;
                                continue;
                            }
                            if ((optionValue == IBM.ICU.Text.Bidi.OPTION_INSERT_MARKS) &&
                                !AssertRoundTrip(bidi3, tc, index, src,
                                                 dest, mode, option, paraLevels[level]))
                            {
                                testOK = false;
                                continue;
                            }
                            if (!CheckResultLength(bidi, src, dest, modeDesc,
                                                   optDesc, paraLevels[level]))
                            {
                                testOK = false;
                                continue;
                            }
                            if ((index > -1) &&
                                !CheckMaps(bidi, index, src, dest, modeDesc,
                                           optDesc, paraLevels[level], true))
                            {
                                testOK = false;
                            }
                        }
                    }
                }
            }
            if (testOK)
            {
                Logln("Reordering mode test OK");
            }

            Logln("\nExiting TestReorderingMode\n");
        }
示例#25
0
        private void _testReordering(Bidi bidi, int testNumber)
        {
            int[]   logicalMap1;
            int[]   logicalMap2;
            int[]   logicalMap3;
            int[]   visualMap1;
            int[]   visualMap2;
            int[]   visualMap3;
            int[]   visualMap4 = new int[MAXLEN];
            sbyte[] levels;
            int     i, length = bidi.GetLength(), destLength = bidi.GetResultLength();
            int     runCount, visualIndex, logicalIndex = -1, logicalStart, runLength;
            bool    odd;

            if (length <= 0)
            {
                return;
            }
            /* get the logical and visual maps from the object */
            logicalMap1 = bidi.GetLogicalMap();
            if (logicalMap1 == null)
            {
                Errln("getLogicalMap in test " + testNumber + " is null");
                logicalMap1 = new int[0];
            }

            visualMap1 = bidi.GetVisualMap();

            if (visualMap1 == null)
            {
                Errln("getVisualMap() in test " + testNumber + " is null");
                visualMap1 = new int[0];
            }

            /* invert them both */
            visualMap2  = IBM.ICU.Text.Bidi.InvertMap(logicalMap1);
            logicalMap2 = IBM.ICU.Text.Bidi.InvertMap(visualMap1);

            /* get them from the levels array, too */
            levels = bidi.GetLevels();

            if (levels == null || levels.Length != length)
            {
                Errln("getLevels() in test " + testNumber + " failed");
            }

            logicalMap3 = IBM.ICU.Text.Bidi.ReorderLogical(levels);
            visualMap3  = IBM.ICU.Text.Bidi.ReorderVisual(levels);

            /* get the visual map from the runs, too */
            try {
                runCount = bidi.CountRuns();
            } catch (InvalidOperationException e) {
                Errln("countRuns() in test " + testNumber + " failed");
                runCount = 0;
            }

            Logln("\n---- " + runCount + " runs");
            visualIndex = 0;
            BidiRun run;

            for (i = 0; i < runCount; ++i)
            {
                run = bidi.GetVisualRun(i);
                if (run == null)
                {
                    Errln("null visual run encountered at index " + i
                          + ", in test " + testNumber);
                    continue;
                }
                odd          = run.IsOddRun();
                logicalStart = run.GetStart();
                runLength    = run.GetLength();
                Log("(" + ((run.IsOddRun()) ? "R" : "L"));
                Log(" @" + run.GetStart() + '[' + run.GetLength() + "])\n");
                if (!odd)
                {
                    do       /* LTR */
                    {
                        visualMap4[visualIndex++] = logicalStart++;
                    } while (--runLength > 0);
                }
                else
                {
                    logicalStart += runLength; /* logicalLimit */
                    do                         /* RTL */
                    {
                        visualMap4[visualIndex++] = --logicalStart;
                    } while (--runLength > 0);
                }
            }
            Log("\n");

            /* print all the maps */
            Logln("logical maps:");
            for (i = 0; i < length; ++i)
            {
                Log(logicalMap1[i] + " ");
            }
            Log("\n");
            for (i = 0; i < length; ++i)
            {
                Log(logicalMap2[i] + " ");
            }
            Log("\n");
            for (i = 0; i < length; ++i)
            {
                Log(logicalMap3[i] + " ");
            }

            Log("\nvisual maps:\n");
            for (i = 0; i < destLength; ++i)
            {
                Log(visualMap1[i] + " ");
            }
            Log("\n");
            for (i = 0; i < destLength; ++i)
            {
                Log(visualMap2[i] + " ");
            }
            Log("\n");
            for (i = 0; i < length; ++i)
            {
                Log(visualMap3[i] + " ");
            }
            Log("\n");
            for (i = 0; i < length; ++i)
            {
                Log(visualMap4[i] + " ");
            }
            Log("\n");

            /*
             * check that the indexes are the same between these and
             * Bidi.getLogical/VisualIndex()
             */
            for (i = 0; i < length; ++i)
            {
                if (logicalMap1[i] != logicalMap2[i])
                {
                    Errln("Error in tests[" + testNumber + "]: (logicalMap1[" + i
                          + "] == " + logicalMap1[i] + ") != (logicalMap2[" + i
                          + "] == " + logicalMap2[i] + ")");
                }
                if (logicalMap1[i] != logicalMap3[i])
                {
                    Errln("Error in tests[" + testNumber + "]: (logicalMap1[" + i
                          + "] == " + logicalMap1[i] + ") != (logicalMap3[" + i
                          + "] == " + logicalMap3[i] + ")");
                }
                if (visualMap1[i] != visualMap2[i])
                {
                    Errln("Error in tests[" + testNumber + "]: (visualMap1[" + i
                          + "] == " + visualMap1[i] + ") != (visualMap2[" + i
                          + "] == " + visualMap2[i] + ")");
                }
                if (visualMap1[i] != visualMap3[i])
                {
                    Errln("Error in tests[" + testNumber + "]: (visualMap1[" + i
                          + "] == " + visualMap1[i] + ") != (visualMap3[" + i
                          + "] == " + visualMap3[i] + ")");
                }
                if (visualMap1[i] != visualMap4[i])
                {
                    Errln("Error in tests[" + testNumber + "]: (visualMap1[" + i
                          + "] == " + visualMap1[i] + ") != (visualMap4[" + i
                          + "] == " + visualMap4[i] + ")");
                }
                try {
                    visualIndex = bidi.GetVisualIndex(i);
                } catch (Exception e_0) {
                    Errln("Bidi.getVisualIndex(" + i + ") failed in tests["
                          + testNumber + "]");
                }
                if (logicalMap1[i] != visualIndex)
                {
                    Errln("Error in tests[" + testNumber + "]: (logicalMap1[" + i
                          + "] == " + logicalMap1[i]
                          + ") != (Bidi.getVisualIndex(" + i + ") == "
                          + visualIndex + ")");
                }
                try {
                    logicalIndex = bidi.GetLogicalIndex(i);
                } catch (Exception e_1) {
                    Errln("Bidi.getLogicalIndex(" + i + ") failed in tests["
                          + testNumber + "]");
                }
                if (visualMap1[i] != logicalIndex)
                {
                    Errln("Error in tests[" + testNumber + "]: (visualMap1[" + i
                          + "] == " + visualMap1[i]
                          + ") != (Bidi.getLogicalIndex(" + i + ") == "
                          + logicalIndex + ")");
                }
            }
        }
示例#26
0
        private void DoMisc()
        {
            /* Miscellaneous tests to exercize less popular code paths */
            Bidi bidi = new Bidi(120, 66), bidiLine;

            AssertEquals("\nwriteReverse should return an empty string", "",
                         IBM.ICU.Text.Bidi.WriteReverse("", 0));

            bidi.SetPara("", IBM.ICU.Text.Bidi.LTR, null);
            AssertEquals("\nwriteReordered should return an empty string", "",
                         bidi.WriteReordered(0));

            bidi.SetPara("abc", IBM.ICU.Text.Bidi.LTR, null);
            AssertEquals("\ngetRunStart should return 0", 0, bidi.GetRunStart(0));
            AssertEquals("\ngetRunLimit should return 3", 3, bidi.GetRunLimit(0));

            bidi.SetPara("abc          ", IBM.ICU.Text.Bidi.RTL, null);
            bidiLine = bidi.SetLine(0, 6);
            for (int i = 3; i < 6; i++)
            {
                AssertEquals("\nTrailing space at " + i
                             + " should get paragraph level", IBM.ICU.Text.Bidi.RTL,
                             bidiLine.GetLevelAt(i));
            }

            bidi.SetPara("abc       def", IBM.ICU.Text.Bidi.RTL, null);
            bidiLine = bidi.SetLine(0, 6);
            for (int i_0 = 3; i_0 < 6; i_0++)
            {
                AssertEquals("\nTrailing space at " + i_0
                             + " should get paragraph level", IBM.ICU.Text.Bidi.RTL,
                             bidiLine.GetLevelAt(i_0));
            }

            bidi.SetPara("abcdefghi    ", IBM.ICU.Text.Bidi.RTL, null);
            bidiLine = bidi.SetLine(0, 6);
            for (int i_1 = 3; i_1 < 6; i_1++)
            {
                AssertEquals("\nTrailing char at " + i_1 + " should get level 2", 2,
                             bidiLine.GetLevelAt(i_1));
            }

            bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_REMOVE_CONTROLS);
            bidi.SetPara("\u200eabc       def", IBM.ICU.Text.Bidi.RTL, null);
            bidiLine = bidi.SetLine(0, 6);
            AssertEquals("\nWrong result length", 5, bidiLine.GetResultLength());

            bidi.SetPara("abcdefghi", IBM.ICU.Text.Bidi.LTR, null);
            bidiLine = bidi.SetLine(0, 6);
            AssertEquals("\nWrong direction #1", IBM.ICU.Text.Bidi.LTR, bidiLine.GetDirection());

            bidi.SetPara("", IBM.ICU.Text.Bidi.LTR, null);
            sbyte[] levels = bidi.GetLevels();
            AssertEquals("\nWrong number of level elements", 0, levels.Length);
            AssertEquals("\nWrong number of runs #1", 0, bidi.CountRuns());

            bidi.SetPara("          ", IBM.ICU.Text.Bidi.RTL, null);
            bidiLine = bidi.SetLine(0, 6);
            AssertEquals("\nWrong number of runs #2", 1, bidiLine.CountRuns());

            bidi.SetPara("a\u05d0        bc", IBM.ICU.Text.Bidi.RTL, null);
            bidiLine = bidi.SetLine(0, 6);
            AssertEquals("\nWrong direction #2", IBM.ICU.Text.Bidi.MIXED, bidi.GetDirection());
            AssertEquals("\nWrong direction #3", IBM.ICU.Text.Bidi.MIXED,
                         bidiLine.GetDirection());
            AssertEquals("\nWrong number of runs #3", 2, bidiLine.CountRuns());

            int[] map = IBM.ICU.Text.Bidi.ReorderLogical(null);
            AssertTrue("\nWe should have got a null map #1", map == null);
            map = IBM.ICU.Text.Bidi.ReorderLogical(new sbyte[] { 0, 99, 99 });
            AssertTrue("\nWe should have got a null map #2", map == null);
            map = IBM.ICU.Text.Bidi.ReorderVisual(null);
            AssertTrue("\nWe should have got a null map #3", map == null);

            map = IBM.ICU.Text.Bidi.InvertMap(null);
            AssertTrue("\nWe should have got a null map #4", map == null);
            map = IBM.ICU.Text.Bidi.InvertMap(new int[] { 0, 1, -1, 5, 4 });
            AssertTrue("\nUnexpected inverted Map",
                       ILOG.J2CsMapping.Collections.Arrays.Equals(map, new int[] { 0, 1, -1, -1, 4, 3 }));

            bidi.SetPara("", IBM.ICU.Text.Bidi.LTR, null);
            map = bidi.GetLogicalMap();
            AssertTrue("\nMap should have length==0 #1", map.Length == 0);
            map = bidi.GetVisualMap();
            AssertTrue("\nMap should have length==0 #2", map.Length == 0);

            /* test BidiRun.toString and allocation of run memory > 1 */
            bidi.SetPara("abc", IBM.ICU.Text.Bidi.LTR, null);
            AssertEquals("\nWrong run display", "BidiRun 0 - 3 @ 0", bidi
                         .GetLogicalRun(0).ToString());

            /* test REMOVE_BIDI_CONTROLS together with DO_MIRRORING */
            bidi.SetPara("abc\u200e", IBM.ICU.Text.Bidi.LTR, null);
            String xout = bidi.WriteReordered(IBM.ICU.Text.Bidi.REMOVE_BIDI_CONTROLS
                                              | IBM.ICU.Text.Bidi.DO_MIRRORING);

            AssertEquals("\nWrong result #1", "abc", xout);

            /* test inverse Bidi with marks and contextual orientation */
            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_INVERSE_LIKE_DIRECT);
            bidi.SetReorderingOptions(IBM.ICU.Text.Bidi.OPTION_INSERT_MARKS);
            bidi.SetPara("", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #2", "", xout);
            bidi.SetPara("   ", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #3", "   ", xout);
            bidi.SetPara("abc", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #4", "abc", xout);
            bidi.SetPara("\u05d0\u05d1", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #5", "\u05d1\u05d0", xout);
            bidi.SetPara("abc \u05d0\u05d1", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #6", "\u05d1\u05d0 abc", xout);
            bidi.SetPara("\u05d0\u05d1 abc", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #7", "\u200fabc \u05d1\u05d0", xout);
            bidi.SetPara("\u05d0\u05d1 abc .-=", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #8", "\u200f=-. abc \u05d1\u05d0", xout);
            bidi.OrderParagraphsLTR(true);
            bidi.SetPara("\n\r   \n\rabc\n\u05d0\u05d1\rabc \u05d2\u05d3\n\r"
                         + "\u05d4\u05d5 abc\n\u05d6\u05d7 abc .-=\r\n"
                         + "-* \u05d8\u05d9 abc .-=", IBM.ICU.Text.Bidi.LEVEL_DEFAULT_RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals(
                "\nWrong result #9",
                "\n\r   \n\rabc\n\u05d1\u05d0\r\u05d3\u05d2 abc\n\r"
                + "\u200fabc \u05d5\u05d4\n\u200f=-. abc \u05d7\u05d6\r\n"
                + "\u200f=-. abc \u05d9\u05d8 *-", xout);

            bidi.SetPara("\u05d0 \t", IBM.ICU.Text.Bidi.LTR, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #10", "\u05D0\u200e \t", xout);
            bidi.SetPara("\u05d0 123 \t\u05d1 123 \u05d2", IBM.ICU.Text.Bidi.LTR, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #11",
                         "\u05d0 \u200e123\u200e \t\u05d2 123 \u05d1", xout);
            bidi.SetPara("\u05d0 123 \u0660\u0661 ab", IBM.ICU.Text.Bidi.LTR, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #12",
                         "\u05d0 \u200e123 \u200e\u0660\u0661 ab", xout);
            bidi.SetPara("ab \t", IBM.ICU.Text.Bidi.RTL, null);
            xout = bidi.WriteReordered(0);
            AssertEquals("\nWrong result #13", "\u200f\t ab", xout);

            /* check exceeding para level */
            bidi = new Bidi();
            bidi.SetPara("A\u202a\u05d0\u202aC\u202c\u05d1\u202cE",
                         (sbyte)(IBM.ICU.Text.Bidi.MAX_EXPLICIT_LEVEL - 1), null);
            AssertEquals("\nWrong level at index 2", 61, bidi.GetLevelAt(2));

            /* check 1-char runs with RUNS_ONLY */
            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_RUNS_ONLY);
            bidi.SetPara("a \u05d0 b \u05d1 c \u05d2 d ", IBM.ICU.Text.Bidi.LTR, null);
            AssertEquals("\nWrong number of runs #4", 14, bidi.CountRuns());
        }
示例#27
0
        public static bool Run()
        {
            Console.WriteLine("Bidi Class Tests");
            Console.WriteLine("----------------");
            Console.WriteLine();

            // Read the test file
            var location = System.IO.Path.GetDirectoryName(typeof(BidiTest).Assembly.Location);
            var lines    = System.IO.File.ReadAllLines(System.IO.Path.Combine(location, "TestData\\BidiTest.txt"));

            var bidi = new Bidi();

            List <Test> tests = new List <Test>();

            // Process each line
            int[] levels = null;
            for (int lineNumber = 1; lineNumber < lines.Length + 1; lineNumber++)
            {
                // Get the line, remove comments
                var line = lines[lineNumber - 1].Split('#')[0].Trim();

                // Ignore blank/comment only lines
                if (string.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                // Directive?
                if (line.StartsWith("@"))
                {
                    if (line.StartsWith("@Levels:"))
                    {
                        levels = line.Substring(8).Trim().Split(' ').Where(x => x.Length > 0).Select(x =>
                        {
                            if (x == "x")
                            {
                                return(-1);
                            }
                            else
                            {
                                return(int.Parse(x));
                            }
                        }).ToArray();
                    }
                    continue;
                }

                // Split data line
                var parts = line.Split(';');
                System.Diagnostics.Debug.Assert(parts.Length == 2);

                // Get the directions
                var directions = parts[0].Split(' ').Select(x => DirectionalityFromName(x)).ToArray();

                // Get the bit set
                var bitset = Convert.ToInt32(parts[1].Trim(), 16);

                var pairTypes  = Enumerable.Repeat(PairedBracketType.n, directions.Length).ToArray();
                var pairValues = Enumerable.Repeat(0, directions.Length).ToArray();

                for (int bit = 1; bit < 8; bit <<= 1)
                {
                    if ((bitset & bit) == 0)
                    {
                        continue;
                    }

                    sbyte paragraphEmbeddingLevel;
                    switch (bit)
                    {
                    case 1:
                        paragraphEmbeddingLevel = 2;            // Auto
                        break;

                    case 2:
                        paragraphEmbeddingLevel = 0;            // LTR
                        break;

                    case 4:
                        paragraphEmbeddingLevel = 1;            // RTL
                        break;

                    default:
                        throw new NotImplementedException();
                    }


                    tests.Add(new Test()
                    {
                        Types = new Slice <Directionality>(directions),
                        ParagraphEmbeddingLevel = paragraphEmbeddingLevel,
                        ExpectedLevels          = levels,
                        LineNumber = lineNumber,
                    });
                }
            }

            Console.WriteLine($"Test data loaded: {tests.Count} test cases");

            var tr = new TestResults();

#if FOR_PROFILING
            for (int repeat = 0; repeat < 50; repeat++)
#endif
            for (int testNumber = 0; testNumber < tests.Count; testNumber++)
            {
                var t = tests[testNumber];

                // Run the algorithm...
                Slice <sbyte> resultLevels;
                tr.EnterTest();
                bidi.Process(t.Types, Slice <PairedBracketType> .Empty, Slice <int> .Empty, t.ParagraphEmbeddingLevel, false, null, null, null);
                tr.LeaveTest();
                resultLevels = bidi.ResolvedLevels;


                // Check the results match
                bool pass = true;
                if (resultLevels.Length == t.ExpectedLevels.Length)
                {
                    for (int i = 0; i < t.ExpectedLevels.Length; i++)
                    {
                        if (t.ExpectedLevels[i] == -1)
                        {
                            continue;
                        }

                        if (resultLevels[i] != t.ExpectedLevels[i])
                        {
                            pass = false;
                            break;
                        }
                    }
                }
                else
                {
                    pass = false;
                }

                tr.TestPassed(pass);

                if (pass)
                {
//                    Console.WriteLine($"Passed line {t.LineNumber} {t.ParagraphEmbeddingLevel}");
                }
                else
                {
                    Console.WriteLine($"Failed line {t.LineNumber}");
                    Console.WriteLine();
                    Console.WriteLine($"        Data: {string.Join(" ", t.Types)}");
                    Console.WriteLine($" Embed Level: {t.ParagraphEmbeddingLevel}");
                    Console.WriteLine($"    Expected: {string.Join(" ", t.ExpectedLevels)}");
                    Console.WriteLine($"      Actual: {string.Join(" ", resultLevels)}");
                    Console.WriteLine();
                    return(false);
                }
            }

            tr.Dump();

            return(tr.AllPassed);
        }
示例#28
0
        /// <summary>
        /// Initialize state, including fChars array, direction, and
        /// fBidi.
        /// </summary>
        private void InitAll(AttributedCharacterIterator text)
        {
            FStart = text.BeginIndex;

            // extract chars
            FChars = new char[text.EndIndex - FStart];

            int n = 0;

            for (char c = text.First(); c != java.text.CharacterIterator_Fields.DONE; c = text.Next())
            {
                FChars[n++] = c;
            }

            text.First();

            FBidi = new Bidi(text);
            if (FBidi.LeftToRight)
            {
                FBidi = null;
            }

            text.First();
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: java.util.Map<? extends java.text.AttributedCharacterIterator_Attribute, ?> paragraphAttrs = text.getAttributes();
            IDictionary <?, ?> paragraphAttrs = text.Attributes;
            NumericShaper      shaper         = AttributeValues.getNumericShaping(paragraphAttrs);

            if (shaper != null)
            {
                shaper.Shape(FChars, 0, FChars.Length);
            }

            FParagraph = new StyledParagraph(text, FChars);

            {
                // set paragraph attributes
                // If there's an embedded graphic at the start of the
                // paragraph, look for the first non-graphic character
                // and use it and its font to initialize the paragraph.
                // If not, use the first graphic to initialize.
                FJustifyRatio = AttributeValues.getJustification(paragraphAttrs);

                bool haveFont = TextLine.AdvanceToFirstFont(text);

                if (haveFont)
                {
                    Font        defaultFont = TextLine.GetFontAtCurrentPos(text);
                    int         charsStart  = text.Index - text.BeginIndex;
                    LineMetrics lm          = defaultFont.GetLineMetrics(FChars, charsStart, charsStart + 1, FFrc);
                    FBaseline        = (sbyte)lm.BaselineIndex;
                    FBaselineOffsets = lm.BaselineOffsets;
                }
                else
                {
                    // hmmm what to do here?  Just try to supply reasonable
                    // values I guess.

                    GraphicAttribute graphic = (GraphicAttribute)paragraphAttrs[TextAttribute.CHAR_REPLACEMENT];
                    FBaseline = TextLayout.GetBaselineFromGraphic(graphic);
//JAVA TO C# CONVERTER TODO TASK: Java wildcard generics are not converted to .NET:
//ORIGINAL LINE: java.util.Hashtable<java.text.AttributedCharacterIterator_Attribute, ?> fmap = new java.util.Hashtable<>(5, (float)0.9);
                    Dictionary <AttributedCharacterIterator_Attribute, ?> fmap = new Dictionary <AttributedCharacterIterator_Attribute, ?>(5, (float)0.9);
                    Font        dummyFont = new Font(fmap);
                    LineMetrics lm        = dummyFont.GetLineMetrics(" ", 0, 1, FFrc);
                    FBaselineOffsets = lm.BaselineOffsets;
                }
                FBaselineOffsets = TextLine.GetNormalizedOffsets(FBaselineOffsets, FBaseline);
            }

            InvalidateComponents();
        }
示例#29
0
        public void TestReorder2()
        {
            Bidi   bidi = new Bidi();
            int    testNumber;
            int    nTests = logicalOrder.Length;
            String src, srcU16, dest = "";

            Logln("\nEntering TestReorder\n");

            for (testNumber = 0; testNumber < nTests; testNumber++)
            {
                Logln("Testing L2V #1 for case " + testNumber);
                src    = logicalOrder[testNumber];
                srcU16 = IBM.ICU.Charset.BidiTest.PseudoToU16(src);
                try {
                    bidi.SetPara(srcU16, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, null);
                } catch (Exception e) {
                    Errln("Bidi.setPara(tests[" + testNumber + "], paraLevel "
                          + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                try {
                    dest = IBM.ICU.Charset.BidiTest.U16ToPseudo(bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING));
                } catch (Exception e_0) {
                    Errln("Bidi.writeReordered(tests[" + testNumber
                          + "], paraLevel " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                if (!visualOrder[testNumber].Equals(dest))
                {
                    AssertEquals(
                        "Failure #1 in Bidi.writeReordered(), test number "
                        + testNumber, visualOrder[testNumber], dest,
                        src, null, "Bidi.DO_MIRRORING",
                        "Bidi.LEVEL_DEFAULT_LTR");
                }
                CheckWhatYouCan(bidi, src, dest);
            }

            for (testNumber = 0; testNumber < nTests; testNumber++)
            {
                Logln("Testing L2V #2 for case " + testNumber);
                src    = logicalOrder[testNumber];
                srcU16 = IBM.ICU.Charset.BidiTest.PseudoToU16(src);
                try {
                    bidi.SetPara(srcU16, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, null);
                } catch (Exception e_1) {
                    Errln("Bidi.setPara(tests[" + testNumber + "], paraLevel "
                          + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                try {
                    dest = IBM.ICU.Charset.BidiTest.U16ToPseudo(bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING
                                                                                    + IBM.ICU.Text.Bidi.OUTPUT_REVERSE));
                } catch (Exception e_2) {
                    Errln("Bidi.writeReordered(test[" + testNumber
                          + "], paraLevel " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                AssertEquals("Failure #2 in Bidi.writeReordered() at index "
                             + testNumber, visualOrder1[testNumber], dest,
                             logicalOrder[testNumber], null,
                             "DO_MIRRORING + OUTPUT_REVERSE", "Bidi.LEVEL_DEFAULT_LTR");
            }

            for (testNumber = 0; testNumber < nTests; testNumber++)
            {
                Logln("Testing V2L #3 for case " + testNumber);
                src    = logicalOrder[testNumber];
                srcU16 = IBM.ICU.Charset.BidiTest.PseudoToU16(src);
                bidi.SetInverse(true);
                try {
                    bidi.SetPara(srcU16, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, null);
                } catch (Exception e_3) {
                    Errln("Bidi.setPara(tests[" + testNumber + "], paraLevel "
                          + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                try {
                    dest = IBM.ICU.Charset.BidiTest.U16ToPseudo(bidi.WriteReordered(IBM.ICU.Text.Bidi.OUTPUT_REVERSE
                                                                                    | IBM.ICU.Text.Bidi.INSERT_LRM_FOR_NUMERIC));
                } catch (Exception e_4) {
                    Errln("Bidi.writeReordered(test[" + testNumber
                          + "], paraLevel " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                AssertEquals("Failure #3 in Bidi.writeReordered(test[" + testNumber
                             + "])", visualOrder2[testNumber], dest,
                             logicalOrder[testNumber], null,
                             "INSERT_LRM_FOR_NUMERIC + OUTPUT_REVERSE",
                             "Bidi.LEVEL_DEFAULT_LTR");
            }

            /* Max Explicit level */
            for (testNumber = 0; testNumber < nTests; testNumber++)
            {
                Logln("Testing V2L #4 for case " + testNumber);
                src    = logicalOrder[testNumber];
                srcU16 = IBM.ICU.Charset.BidiTest.PseudoToU16(src);
                sbyte[] levels = new sbyte[IBM.ICU.Text.Bidi.MAX_EXPLICIT_LEVEL];
                for (int i = 0; i < 10; i++)
                {
                    levels[i] = (sbyte)(i + 1);
                }
                try {
                    bidi.SetPara(srcU16, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, levels);
                } catch (Exception e_5) {
                    Errln("Bidi.setPara(tests[" + testNumber
                          + "], paraLevel = MAX_EXPLICIT_LEVEL = "
                          + IBM.ICU.Text.Bidi.MAX_EXPLICIT_LEVEL + " failed.");
                }
                try {
                    dest = IBM.ICU.Charset.BidiTest.U16ToPseudo(bidi.WriteReordered(IBM.ICU.Text.Bidi.OUTPUT_REVERSE));
                } catch (Exception e_6) {
                    Errln("Bidi.writeReordered(test[" + testNumber
                          + "], paraLevel " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                AssertEquals("Failure #4 in Bidi.writeReordered(test[" + testNumber
                             + "])", visualOrder3[testNumber], dest,
                             logicalOrder[testNumber], null, "OUTPUT_REVERSE",
                             "Bidi.LEVEL_DEFAULT_LTR");
            }

            for (testNumber = 0; testNumber < nTests; testNumber++)
            {
                Logln("Testing V2L #5 for case " + testNumber);
                src    = logicalOrder[testNumber];
                srcU16 = IBM.ICU.Charset.BidiTest.PseudoToU16(src);
                sbyte[] levels_7 = new sbyte[IBM.ICU.Text.Bidi.MAX_EXPLICIT_LEVEL];
                for (int i_8 = 0; i_8 < 10; i_8++)
                {
                    levels_7[i_8] = (sbyte)(i_8 + 1);
                }
                try {
                    bidi.SetPara(srcU16, IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR, levels_7);
                } catch (Exception e_9) {
                    Errln("Bidi.setPara(tests[" + testNumber + "], paraLevel "
                          + IBM.ICU.Text.Bidi.MAX_EXPLICIT_LEVEL + " failed.");
                }
                try {
                    dest = IBM.ICU.Charset.BidiTest.U16ToPseudo(bidi.WriteReordered(IBM.ICU.Text.Bidi.DO_MIRRORING
                                                                                    | IBM.ICU.Text.Bidi.REMOVE_BIDI_CONTROLS));
                } catch (Exception e_10) {
                    Errln("Bidi.writeReordered(test[" + testNumber
                          + "], paraLevel " + IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR + " failed.");
                }
                AssertEquals("Failure #5 in Bidi.writeReordered(test[" + testNumber
                             + "])", visualOrder4[testNumber], dest,
                             logicalOrder[testNumber], null,
                             "DO_MIRRORING + REMOVE_BIDI_CONTROLS",
                             "Bidi.LEVEL_DEFAULT_LTR");
            }

            Logln("\nExiting TestReorder\n");
        }
示例#30
0
        public void TestFailureRecovery2()
        {
            Logln("\nEntering TestFailureRecovery\n");
            Bidi bidi = new Bidi();

            try
            {
                bidi.SetPara("abc", (sbyte)(IBM.ICU.Text.Bidi.LEVEL_DEFAULT_LTR - 1), null);
                Errln("Bidi.setPara did not fail when passed too big para level");
            }
            catch (ArgumentException e)
            {
                Logln("OK: Got exception for bidi.setPara(..., Bidi.LEVEL_DEFAULT_LTR - 1, ...)"
                      + " as expected: " + e.Message);
            }
            try
            {
                bidi.SetPara("abc", (sbyte)(-1), null);
                Errln("Bidi.setPara did not fail when passed negative para level");
            }
            catch (ArgumentException e_0)
            {
                Logln("OK: Got exception for bidi.setPara(..., -1, ...)"
                      + " as expected: " + e_0.Message);
            }
            try
            {
                IBM.ICU.Text.Bidi.WriteReverse(null, 0);
                Errln("Bidi.writeReverse did not fail when passed a null string");
            }
            catch (ArgumentException e_1)
            {
                Logln("OK: Got exception for Bidi.writeReverse(null) as expected: "
                      + e_1.Message);
            }
            bidi = new Bidi();
            try
            {
                bidi.SetLine(0, 1);
                Errln("bidi.setLine did not fail when called before valid setPara()");
            }
            catch (InvalidOperationException e_2)
            {
                Logln("OK: Got exception for Bidi.setLine(0, 1) as expected: "
                      + e_2.Message);
            }
            try
            {
                bidi.GetDirection();
                Errln("bidi.getDirection did not fail when called before valid setPara()");
            }
            catch (InvalidOperationException e_3)
            {
                Logln("OK: Got exception for Bidi.getDirection() as expected: "
                      + e_3.Message);
            }
            bidi.SetPara("abc", IBM.ICU.Text.Bidi.LTR, null);
            try
            {
                bidi.GetLevelAt(3);
                Errln("bidi.getLevelAt did not fail when called with bad argument");
            }
            catch (ArgumentException e_4)
            {
                Logln("OK: Got exception for Bidi.getLevelAt(3) as expected: "
                      + e_4.Message);
            }
            try
            {
                bidi = new Bidi(-1, 0);
                Errln("Bidi constructor did not fail when called with bad argument");
            }
            catch (ArgumentException e_5)
            {
                Logln("OK: Got exception for Bidi(-1,0) as expected: "
                      + e_5.Message);
            }
            bidi = new Bidi(2, 1);
            try
            {
                bidi.SetPara("abc", IBM.ICU.Text.Bidi.LTR, null);
                Errln("setPara did not fail when called with text too long");
            }
            catch (Exception e_6)
            {
                Logln("OK: Got exception for setPara(\"abc\") as expected: "
                      + e_6.Message);
            }
            try
            {
                bidi.SetPara("=2", IBM.ICU.Text.Bidi.RTL, null);
                bidi.CountRuns();
                Errln("countRuns did not fail when called for too many runs");
            }
            catch (Exception e_7)
            {
                Logln("OK: Got exception for countRuns as expected: "
                      + e_7.Message);
            }
            int rm = bidi.GetReorderingMode();

            bidi.SetReorderingMode(IBM.ICU.Text.Bidi.REORDER_DEFAULT - 1);
            if (rm != bidi.GetReorderingMode())
            {
                Errln("setReorderingMode with bad argument #1 should have no effect");
            }
            bidi.SetReorderingMode(9999);
            if (rm != bidi.GetReorderingMode())
            {
                Errln("setReorderingMode with bad argument #2 should have no effect");
            }
            /* Try a surrogate char */
            bidi = new Bidi();
            bidi.SetPara("\uD800\uDC00", IBM.ICU.Text.Bidi.RTL, null);
            if (bidi.GetDirection() != IBM.ICU.Text.Bidi.MIXED)
            {
                Errln("getDirection for 1st surrogate char should be MIXED");
            }
            sbyte[] levels = new sbyte[] { 6, 5, 4 };
            try
            {
                bidi.SetPara("abc", (sbyte)5, levels);
                Errln("setPara did not fail when called with bad levels");
            }
            catch (ArgumentException e_8)
            {
                Logln("OK: Got exception for setPara(..., levels) as expected: "
                      + e_8.Message);
            }

            Logln("\nExiting TestFailureRecovery\n");
        }