bidi.c 39.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/*
 * Uniscribe BiDirectional handling
 *
 * Copyright 2003 Shachar Shemesh
 * Copyright 2007 Maarten Lankhorst
 * Copyright 2010 CodeWeavers, Aric Stewart
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 *
 * Code derived from the modified reference implementation
 * that was found in revision 17 of http://unicode.org/reports/tr9/
 * "Unicode Standard Annex #9: THE BIDIRECTIONAL ALGORITHM"
 *
 * -- Copyright (C) 1999-2005, ASMUS, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of the Unicode data files and any associated documentation (the
 * "Data Files") or Unicode software and any associated documentation (the
 * "Software") to deal in the Data Files or Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, and/or sell copies of the Data Files or Software,
 * and to permit persons to whom the Data Files or Software are furnished
 * to do so, provided that (a) the above copyright notice(s) and this
 * permission notice appear with all copies of the Data Files or Software,
 * (b) both the above copyright notice(s) and this permission notice appear
 * in associated documentation, and (c) there is clear notice in each
 * modified Data File or in the Software as well as in the documentation
 * associated with the Data File(s) or Software that the data or software
 * has been modified.
 */

#include "config.h"

#include <stdarg.h>
47
#include <stdlib.h>
48 49 50 51 52
#include "windef.h"
#include "winbase.h"
#include "wingdi.h"
#include "winnls.h"
#include "usp10.h"
53
#include "wine/unicode.h"
54
#include "wine/debug.h"
55
#include "wine/list.h"
56 57 58

#include "usp10_internal.h"

59 60
extern const unsigned short bidi_bracket_table[];

61 62 63
WINE_DEFAULT_DEBUG_CHANNEL(bidi);

#define ASSERT(x) do { if (!(x)) FIXME("assert failed: %s\n", #x); } while(0)
64
#define MAX_DEPTH 125
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

/* HELPER FUNCTIONS AND DECLARATIONS */

/*------------------------------------------------------------------------
    Bidirectional Character Types

    as defined by the Unicode Bidirectional Algorithm Table 3-7.

    Note:

      The list of bidirectional character types here is not grouped the
      same way as the table 3-7, since the numberic values for the types
      are chosen to keep the state and action tables compact.
------------------------------------------------------------------------*/
enum directions
{
    /* input types */
82
             /* ON MUST be zero, code relies on ON = NI = 0 */
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    ON = 0,  /* Other Neutral */
    L,       /* Left Letter */
    R,       /* Right Letter */
    AN,      /* Arabic Number */
    EN,      /* European Number */
    AL,      /* Arabic Letter (Right-to-left) */
    NSM,     /* Non-spacing Mark */
    CS,      /* Common Separator */
    ES,      /* European Separator */
    ET,      /* European Terminator (post/prefix e.g. $ and %) */

    /* resolved types */
    BN,      /* Boundary neutral (type of RLE etc after explicit levels) */

    /* input types, */
    S,       /* Segment Separator (TAB)        // used only in L1 */
    WS,      /* White space                    // used only in L1 */
    B,       /* Paragraph Separator (aka as PS) */

    /* types for explicit controls */
    RLO,     /* these are used only in X1-X9 */
    RLE,
    LRO,
    LRE,
    PDF,

109 110 111 112 113
    LRI, /* Isolate formatting characters new with 6.3 */
    RLI,
    FSI,
    PDI,

114
    /* resolved types, also resolved directions */
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
    NI = ON,  /* alias, where ON, WS, S  and Isolates are treated the same */
};

static const char debug_type[][4] =
{
    "ON",      /* Other Neutral */
    "L",       /* Left Letter */
    "R",       /* Right Letter */
    "AN",      /* Arabic Number */
    "EN",      /* European Number */
    "AL",      /* Arabic Letter (Right-to-left) */
    "NSM",     /* Non-spacing Mark */
    "CS",      /* Common Separator */
    "ES",      /* European Separator */
    "ET",      /* European Terminator (post/prefix e.g. $ and %) */
    "BN",      /* Boundary neutral (type of RLE etc after explicit levels) */
    "S",       /* Segment Separator (TAB)        // used only in L1 */
    "WS",      /* White space                    // used only in L1 */
    "B",       /* Paragraph Separator (aka as PS) */
    "RLO",     /* these are used only in X1-X9 */
    "RLE",
    "LRO",
    "LRE",
    "PDF",
    "LRI",     /* Isolate formatting characters new with 6.3 */
    "RLI",
    "FSI",
    "PDI",
143 144 145 146
};

/* HELPER FUNCTIONS */

147 148
static inline void dump_types(const char* header, WORD *types, int start, int end)
{
149
    int i, len = 0;
150
    TRACE("%s:",header);
151 152
    for (i = start; i < end && len < 200; i++)
    {
153
        TRACE(" %s",debug_type[types[i]]);
154 155 156 157
        len += strlen(debug_type[types[i]])+1;
    }
    if (i != end)
        TRACE("...");
158 159 160
    TRACE("\n");
}

161
/* Convert the libwine information to the direction enum */
162 163
static void classify(LPCWSTR lpString, WORD *chartype, DWORD uCount, const SCRIPT_CONTROL *c)
{
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    static const enum directions dir_map[16] =
    {
        L,  /* unassigned defaults to L */
        L,
        R,
        EN,
        ES,
        ET,
        AN,
        CS,
        B,
        S,
        WS,
        ON,
        AL,
        NSM,
        BN,
        PDF  /* also LRE, LRO, RLE, RLO */
    };

    unsigned i;

186
    for (i = 0; i < uCount; ++i)
187 188
    {
        chartype[i] = dir_map[get_char_typeW(lpString[i]) >> 12];
189 190
        switch (chartype[i])
        {
191 192 193 194 195
        case ES:
            if (!c->fLegacyBidiClass) break;
            switch (lpString[i])
            {
            case '-':
196
            case '+': chartype[i] = NI; break;
197 198 199 200 201 202 203 204 205 206 207
            case '/': chartype[i] = CS; break;
            }
            break;
        case PDF:
            switch (lpString[i])
            {
            case 0x202A: chartype[i] = LRE; break;
            case 0x202B: chartype[i] = RLE; break;
            case 0x202C: chartype[i] = PDF; break;
            case 0x202D: chartype[i] = LRO; break;
            case 0x202E: chartype[i] = RLO; break;
208 209 210 211
            case 0x2066: chartype[i] = LRI; break;
            case 0x2067: chartype[i] = RLI; break;
            case 0x2068: chartype[i] = FSI; break;
            case 0x2069: chartype[i] = PDI; break;
212 213
            }
            break;
214
        }
215
    }
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
}

/* RESOLVE EXPLICIT */

static WORD GreaterEven(int i)
{
    return odd(i) ? i + 1 : i + 2;
}

static WORD GreaterOdd(int i)
{
    return odd(i) ? i + 2 : i + 1;
}

static WORD EmbeddingDirection(int level)
{
    return odd(level) ? R : L;
}

/*------------------------------------------------------------------------
    Function: resolveExplicit

    Recursively resolves explicit embedding levels and overrides.
    Implements rules X1-X9, of the Unicode Bidirectional Algorithm.

    Input: Base embedding level and direction
           Character count

    Output: Array of embedding levels

    In/Out: Array of direction classes


    Note: The function uses two simple counters to keep track of
          matching explicit codes and PDF. Use the default argument for
          the outermost call. The nesting counter counts the recursion
          depth and not the embedding level.
------------------------------------------------------------------------*/
254 255 256 257 258 259 260 261 262 263 264
typedef struct tagStackItem {
    int level;
    int override;
    BOOL isolate;
} StackItem;

#define push_stack(l,o,i)  \
  do { stack_top--; \
  stack[stack_top].level = l; \
  stack[stack_top].override = o; \
  stack[stack_top].isolate = i;} while(0)
265

266 267 268 269 270
#define pop_stack() do { stack_top++; } while(0)

#define valid_level(x) (x <= MAX_DEPTH && overflow_isolate_count == 0 && overflow_embedding_count == 0)

static void resolveExplicit(int level, WORD *pclass, WORD *poutLevel, int count)
271
{
272 273 274 275 276
    /* X1 */
    int overflow_isolate_count = 0;
    int overflow_embedding_count = 0;
    int valid_isolate_count = 0;
    int i;
277

278 279
    StackItem stack[MAX_DEPTH+2];
    int stack_top = MAX_DEPTH+1;
280

281 282 283 284 285
    stack[stack_top].level = level;
    stack[stack_top].override = NI;
    stack[stack_top].isolate = FALSE;

    for (i = 0; i < count; i++)
286
    {
287 288 289 290 291 292 293 294 295 296 297 298
        /* X2 */
        if (pclass[i] == RLE)
        {
            int least_odd = GreaterOdd(stack[stack_top].level);
            poutLevel[i] = stack[stack_top].level;
            if (valid_level(least_odd))
                push_stack(least_odd, NI, FALSE);
            else if (overflow_isolate_count == 0)
                overflow_embedding_count++;
        }
        /* X3 */
        else if (pclass[i] == LRE)
299
        {
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
            int least_even = GreaterEven(stack[stack_top].level);
            poutLevel[i] = stack[stack_top].level;
            if (valid_level(least_even))
                push_stack(least_even, NI, FALSE);
            else if (overflow_isolate_count == 0)
                overflow_embedding_count++;
        }
        /* X4 */
        else if (pclass[i] == RLO)
        {
            int least_odd = GreaterOdd(stack[stack_top].level);
            poutLevel[i] = stack[stack_top].level;
            if (valid_level(least_odd))
                push_stack(least_odd, R, FALSE);
            else if (overflow_isolate_count == 0)
                overflow_embedding_count++;
        }
        /* X5 */
        else if (pclass[i] == LRO)
        {
            int least_even = GreaterEven(stack[stack_top].level);
            poutLevel[i] = stack[stack_top].level;
            if (valid_level(least_even))
                push_stack(least_even, L, FALSE);
            else if (overflow_isolate_count == 0)
                overflow_embedding_count++;
        }
        /* X5a */
        else if (pclass[i] == RLI)
        {
            int least_odd = GreaterOdd(stack[stack_top].level);
            poutLevel[i] = stack[stack_top].level;
            if (valid_level(least_odd))
333
            {
334 335
                valid_isolate_count++;
                push_stack(least_odd, NI, TRUE);
336
            }
337 338 339 340 341 342 343 344 345
            else
                overflow_isolate_count++;
        }
        /* X5b */
        else if (pclass[i] == LRI)
        {
            int least_even = GreaterEven(stack[stack_top].level);
            poutLevel[i] = stack[stack_top].level;
            if (valid_level(least_even))
346
            {
347 348
                valid_isolate_count++;
                push_stack(least_even, NI, TRUE);
349
            }
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
            else
                overflow_isolate_count++;
        }
        /* X5c */
        else if (pclass[i] == FSI)
        {
            int j;
            int new_level = 0;
            int skipping = 0;
            poutLevel[i] = stack[stack_top].level;
            for (j = i+1; j < count; j++)
            {
                if (pclass[j] == LRI || pclass[j] == RLI || pclass[j] == FSI)
                {
                    skipping++;
                    continue;
                }
                else if (pclass[j] == PDI)
                {
                    if (skipping)
                        skipping --;
                    else
                        break;
                    continue;
                }
375

376 377 378 379 380 381 382 383 384 385 386 387 388 389
                if (skipping) continue;

                if (pclass[j] == L)
                {
                    new_level = 0;
                    break;
                }
                else if (pclass[j] == R || pclass[j] == AL)
                {
                    new_level = 1;
                    break;
                }
            }
            if (odd(new_level))
390
            {
391 392
                int least_odd = GreaterOdd(stack[stack_top].level);
                if (valid_level(least_odd))
393
                {
394 395
                    valid_isolate_count++;
                    push_stack(least_odd, NI, TRUE);
396 397
                }
                else
398 399 400 401 402 403
                    overflow_isolate_count++;
            }
            else
            {
                int least_even = GreaterEven(stack[stack_top].level);
                if (valid_level(least_even))
404
                {
405 406
                    valid_isolate_count++;
                    push_stack(least_even, NI, TRUE);
407
                }
408 409
                else
                    overflow_isolate_count++;
410 411
            }
        }
412 413 414 415 416 417 418 419 420
        /* X6 */
        else if (pclass[i] != B && pclass[i] != BN && pclass[i] != PDI && pclass[i] != PDF)
        {
            poutLevel[i] = stack[stack_top].level;
            if (stack[stack_top].override != NI)
                pclass[i] = stack[stack_top].override;
        }
        /* X6a */
        else if (pclass[i] == PDI)
421
        {
422 423 424 425 426 427 428 429 430 431
            if (overflow_isolate_count) overflow_isolate_count--;
            else if (!valid_isolate_count) {/* do nothing */}
            else
            {
                overflow_embedding_count = 0;
                while (!stack[stack_top].isolate) pop_stack();
                pop_stack();
                valid_isolate_count --;
            }
            poutLevel[i] = stack[stack_top].level;
432
        }
433 434 435 436 437 438 439 440 441 442
        /* X7 */
        else if (pclass[i] == PDF)
        {
            poutLevel[i] = stack[stack_top].level;
            if (overflow_isolate_count) {/* do nothing */}
            else if (overflow_embedding_count) overflow_embedding_count--;
            else if (!stack[stack_top].isolate && stack_top < (MAX_DEPTH+1))
                pop_stack();
        }
        /* X8: Nothing */
443
    }
444 445 446 447
    /* X9: Based on 5.2 Retaining Explicit Formatting Characters */
    for (i = 0; i < count ; i++)
        if (pclass[i] == RLE || pclass[i] == LRE || pclass[i] == RLO || pclass[i] == LRO || pclass[i] == PDF)
            pclass[i] = BN;
448 449
}

450 451 452 453 454 455 456
static inline int previousValidChar(const WORD *pcls, int index, int back_fence)
{
    if (index == -1 || index == back_fence) return index;
    index --;
    while (index > back_fence && pcls[index] == BN) index --;
    return index;
}
457

458
static inline int nextValidChar(const WORD *pcls, int index, int front_fence)
459
{
460 461 462 463 464
    if (index == front_fence) return index;
    index ++;
    while (index < front_fence && pcls[index] == BN) index ++;
    return index;
}
465

466
typedef struct tagRun
467
{
468 469 470 471
    int start;
    int end;
    WORD e;
} Run;
472

473 474 475 476 477 478
typedef struct tagRunChar
{
    WCHAR ch;
    WORD *pcls;
} RunChar;

479
typedef struct tagIsolatedRun
480
{
481 482 483 484 485 486
    struct list entry;
    int length;
    WORD sos;
    WORD eos;
    WORD e;

487
    RunChar item[1];
488 489 490
} IsolatedRun;

static inline int iso_nextValidChar(IsolatedRun *iso_run, int index)
491
{
492 493
    if (index >= (iso_run->length-1)) return -1;
    index ++;
494
    while (index < iso_run->length && *iso_run->item[index].pcls == BN) index++;
495 496 497
    if (index == iso_run->length) return -1;
    return index;
}
498

499
static inline int iso_previousValidChar(IsolatedRun *iso_run, int index)
500
{
501 502 503

    if (index <= 0) return -1;
    index --;
504
    while (index > -1 && *iso_run->item[index].pcls == BN) index--;
505
    return index;
506 507
}

508
static inline int iso_previousChar(IsolatedRun *iso_run, int index)
509
{
510 511
    if (index <= 0) return -1;
    return index --;
512 513
}

514 515
static inline void iso_dump_types(const char* header, IsolatedRun *iso_run)
{
516
    int i, len = 0;
517 518
    TRACE("%s:",header);
    TRACE("[ ");
519 520
    for (i = 0; i < iso_run->length && len < 200; i++)
    {
521
        TRACE(" %s",debug_type[*iso_run->item[i].pcls]);
522 523 524 525
        len += strlen(debug_type[*iso_run->item[i].pcls])+1;
    }
    if (i != iso_run->length)
        TRACE("...");
526 527
    TRACE(" ]\n");
}
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544

/*------------------------------------------------------------------------
    Function: resolveWeak

    Resolves the directionality of numeric and other weak character types

    Implements rules X10 and W1-W6 of the Unicode Bidirectional Algorithm.

    Input: Array of embedding levels
           Character count

    In/Out: Array of directional classes

    Note: On input only these directional classes are expected
          AL, HL, R, L,  ON, BN, NSM, AN, EN, ES, ET, CS,
------------------------------------------------------------------------*/

545 546 547
static void resolveWeak(IsolatedRun * iso_run)
{
    int i;
548

549 550
    /* W1 */
    for (i=0; i < iso_run->length; i++)
551
    {
552
        if (*iso_run->item[i].pcls == NSM)
553
        {
554 555
            int j = iso_previousValidChar(iso_run, i);
            if (j == -1)
556 557 558
                *iso_run->item[i].pcls = iso_run->sos;
            else if (*iso_run->item[j].pcls >= LRI)
                *iso_run->item[i].pcls = ON;
559
            else
560
                *iso_run->item[i].pcls = *iso_run->item[j].pcls;
561 562 563 564 565 566
        }
    }

    /* W2 */
    for (i = 0; i < iso_run->length; i++)
    {
567
        if (*iso_run->item[i].pcls == EN)
568 569 570
        {
            int j = iso_previousValidChar(iso_run, i);
            while (j > -1)
571
            {
572
                if (*iso_run->item[j].pcls == R || *iso_run->item[j].pcls == L || *iso_run->item[j].pcls == AL)
573
                {
574 575
                    if (*iso_run->item[j].pcls == AL)
                        *iso_run->item[i].pcls = AN;
576
                    break;
577
                }
578
                j = iso_previousValidChar(iso_run, j);
579 580
            }
        }
581
    }
582

583 584 585
    /* W3 */
    for (i = 0; i < iso_run->length; i++)
    {
586 587
        if (*iso_run->item[i].pcls == AL)
            *iso_run->item[i].pcls = R;
588
    }
589

590 591 592
    /* W4 */
    for (i = 0; i < iso_run->length; i++)
    {
593
        if (*iso_run->item[i].pcls == ES)
594
        {
595 596
            int b = iso_previousValidChar(iso_run, i);
            int f = iso_nextValidChar(iso_run, i);
597

598 599
            if (b > -1 && f > -1 && *iso_run->item[b].pcls == EN && *iso_run->item[f].pcls == EN)
                *iso_run->item[i].pcls = EN;
600
        }
601
        else if (*iso_run->item[i].pcls == CS)
602 603 604
        {
            int b = iso_previousValidChar(iso_run, i);
            int f = iso_nextValidChar(iso_run, i);
605

606 607 608 609
            if (b > -1 && f > -1 && *iso_run->item[b].pcls == EN && *iso_run->item[f].pcls == EN)
                *iso_run->item[i].pcls = EN;
            else if (b > -1 && f > -1 && *iso_run->item[b].pcls == AN && *iso_run->item[f].pcls == AN)
                *iso_run->item[i].pcls = AN;
610 611
        }
    }
612

613 614 615
    /* W5 */
    for (i = 0; i < iso_run->length; i++)
    {
616
        if (*iso_run->item[i].pcls == ET)
617 618 619 620
        {
            int j;
            for (j = i-1 ; j > -1; j--)
            {
621 622 623
                if (*iso_run->item[j].pcls == BN) continue;
                if (*iso_run->item[j].pcls == ET) continue;
                else if (*iso_run->item[j].pcls == EN) *iso_run->item[i].pcls = EN;
624 625
                else break;
            }
626
            if (*iso_run->item[i].pcls == ET)
627 628 629
            {
                for (j = i+1; j < iso_run->length; j++)
                {
630 631 632
                    if (*iso_run->item[j].pcls == BN) continue;
                    if (*iso_run->item[j].pcls == ET) continue;
                    else if (*iso_run->item[j].pcls == EN) *iso_run->item[i].pcls = EN;
633 634 635 636
                    else break;
                }
            }
        }
637 638
    }

639 640 641
    /* W6 */
    for (i = 0; i < iso_run->length; i++)
    {
642
        if (*iso_run->item[i].pcls == ET || *iso_run->item[i].pcls == ES || *iso_run->item[i].pcls == CS || *iso_run->item[i].pcls == ON)
643 644 645
        {
            int b = i-1;
            int f = i+1;
646 647 648 649
            if (b > -1 && *iso_run->item[b].pcls == BN)
                *iso_run->item[b].pcls = ON;
            if (f < iso_run->length && *iso_run->item[f].pcls == BN)
                *iso_run->item[f].pcls = ON;
650

651
            *iso_run->item[i].pcls = ON;
652 653
        }
    }
654

655 656 657
    /* W7 */
    for (i = 0; i < iso_run->length; i++)
    {
658
        if (*iso_run->item[i].pcls == EN)
659 660 661
        {
            int j;
            for (j = iso_previousValidChar(iso_run, i); j > -1; j = iso_previousValidChar(iso_run, j))
662
                if (*iso_run->item[j].pcls == R || *iso_run->item[j].pcls == L)
663
                {
664 665
                    if (*iso_run->item[j].pcls == L)
                        *iso_run->item[i].pcls = L;
666 667 668
                    break;
                }
            if (iso_run->sos == L &&  j == -1)
669
                *iso_run->item[i].pcls = L;
670 671
        }
    }
672 673
}

674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
typedef struct tagBracketPair
{
    int start;
    int end;
} BracketPair;

static int compr(const void *a, const void* b)
{
    return ((BracketPair*)a)->start - ((BracketPair*)b)->start;
}

static BracketPair *computeBracketPairs(IsolatedRun *iso_run)
{
    WCHAR *open_stack;
    int *stack_index;
    int stack_top = iso_run->length;
    BracketPair *out = NULL;
    int pair_count = 0;
    int i;

    open_stack = HeapAlloc(GetProcessHeap(), 0, sizeof(WCHAR) * iso_run->length);
    stack_index = HeapAlloc(GetProcessHeap(), 0, sizeof(int) * iso_run->length);

    for (i = 0; i < iso_run->length; i++)
    {
        unsigned short ubv = get_table_entry(bidi_bracket_table, iso_run->item[i].ch);
        if (ubv)
        {
            if (!out)
            {
                out = HeapAlloc(GetProcessHeap(),0,sizeof(BracketPair));
                out[0].start = -1;
            }

            if ((ubv >> 8) == 0)
            {
                stack_top --;
                open_stack[stack_top] = iso_run->item[i].ch + (signed char)(ubv & 0xff);
                /* deal with canonical equivalent U+2329/232A and U+3008/3009 */
                if (open_stack[stack_top] == 0x232A)
                    open_stack[stack_top] = 0x3009;
                stack_index[stack_top] = i;
            }
            else if ((ubv >> 8) == 1)
            {
                int j;
                if (stack_top == iso_run->length) continue;
                for (j = stack_top; j < iso_run->length; j++)
                {
                    WCHAR c = iso_run->item[i].ch;
                    if (c == 0x232A) c = 0x3009;
                    if (c == open_stack[j])
                    {
                        out[pair_count].start = stack_index[j];
                        out[pair_count].end = i;
                        pair_count++;
                        out = HeapReAlloc(GetProcessHeap(), 0, out, sizeof(BracketPair) * (pair_count+1));
                        out[pair_count].start = -1;
                        stack_top = j+1;
                        break;
                    }
                }
            }
        }
    }
    if (pair_count == 0)
    {
        HeapFree(GetProcessHeap(),0,out);
        out = NULL;
    }
    else if (pair_count > 1)
        qsort(out, pair_count, sizeof(BracketPair), compr);

    HeapFree(GetProcessHeap(), 0, open_stack);
    HeapFree(GetProcessHeap(), 0, stack_index);
    return out;
}

#define N0_TYPE(a) ((a == AN || a == EN)?R:a)

754 755 756 757 758
/*------------------------------------------------------------------------
    Function: resolveNeutrals

    Resolves the directionality of neutral character types.

759
    Implements rules N1 and N2 of the Unicode Bidi Algorithm.
760 761 762 763 764 765 766 767

    Input: Array of embedding levels
           Character count
           Baselevel

    In/Out: Array of directional classes

    Note: On input only these directional classes are expected
768
          R,  L,  NI, AN, EN and BN
769 770 771

          W8 resolves a number of ENs to L
------------------------------------------------------------------------*/
772
static void resolveNeutrals(IsolatedRun *iso_run)
773
{
774
    int i;
775
    BracketPair *pairs = NULL;
776

777 778
    /* Translate isolates into NI */
    for (i = 0; i < iso_run->length; i++)
779
    {
780 781
        if (*iso_run->item[i].pcls >= LRI)
            *iso_run->item[i].pcls = NI;
782

783
        switch(*iso_run->item[i].pcls)
784 785 786
        {
            case B:
            case S:
787
            case WS: *iso_run->item[i].pcls = NI;
788 789
        }

790
        ASSERT(*iso_run->item[i].pcls < 5 || *iso_run->item[i].pcls == BN); /* "Only NI, L, R,  AN, EN and BN are allowed" */
791
    }
792

793
    /* N0: Skipping bracketed pairs for now */
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
    pairs = computeBracketPairs(iso_run);
    if (pairs)
    {
        BracketPair *p = &pairs[0];
        int i = 0;
        while (p->start >= 0)
        {
            int j;
            int e = EmbeddingDirection(iso_run->e);
            int o = EmbeddingDirection(iso_run->e+1);
            BOOL flag_o = FALSE;
            TRACE("Bracket Pair [%i - %i]\n",p->start, p->end);

            /* N0.b */
            for (j = p->start+1; j < p->end; j++)
            {
                if (N0_TYPE(*iso_run->item[j].pcls) == e)
                {
                    *iso_run->item[p->start].pcls = e;
                    *iso_run->item[p->end].pcls = e;
                    break;
                }
                else if (N0_TYPE(*iso_run->item[j].pcls) == o)
                    flag_o = TRUE;
            }
            /* N0.c */
            if (j == p->end && flag_o)
            {
                for (j = p->start; j >= 0; j--)
                {
                    if (N0_TYPE(*iso_run->item[j].pcls) == o)
                    {
                        *iso_run->item[p->start].pcls = o;
                        *iso_run->item[p->end].pcls = o;
                        break;
                    }
                    else if (N0_TYPE(*iso_run->item[j].pcls) == e)
                    {
                        *iso_run->item[p->start].pcls = e;
                        *iso_run->item[p->end].pcls = e;
                        break;
                    }
                }
                if ( j < 0 )
                {
                    *iso_run->item[p->start].pcls = iso_run->sos;
                    *iso_run->item[p->end].pcls = iso_run->sos;
                }
            }

            i++;
            p = &pairs[i];
        }
        HeapFree(GetProcessHeap(),0,pairs);
    }
849

850 851 852 853
    /* N1 */
    for (i = 0; i < iso_run->length; i++)
    {
        WORD l,r;
854

855
        if (*iso_run->item[i].pcls == NI)
856 857 858
        {
            int j;
            int b = iso_previousValidChar(iso_run, i);
859

860 861 862 863 864 865 866
            if (b == -1)
            {
                l = iso_run->sos;
                b = 0;
            }
            else
            {
867
                if (*iso_run->item[b].pcls == R || *iso_run->item[b].pcls == AN || *iso_run->item[b].pcls == EN)
868
                    l = R;
869
                else if (*iso_run->item[b].pcls == L)
870 871 872 873 874
                    l = L;
                else /* No string type */
                    continue;
            }
            j = iso_nextValidChar(iso_run, i);
875
            while (j > -1 && *iso_run->item[j].pcls == NI) j = iso_nextValidChar(iso_run, j);
876

877 878 879 880 881
            if (j == -1)
            {
                r = iso_run->eos;
                j = iso_run->length;
            }
882
            else if (*iso_run->item[j].pcls == R || *iso_run->item[j].pcls == AN || *iso_run->item[j].pcls == EN)
883
                r = R;
884
            else if (*iso_run->item[j].pcls == L)
885 886 887 888 889 890 891
                r = L;
            else /* No string type */
                continue;

            if (r == l)
            {
                for (b = i; b < j && b < iso_run->length; b++)
892
                    *iso_run->item[b].pcls = r;
893 894
            }
        }
895 896
    }

897 898 899
    /* N2 */
    for (i = 0; i < iso_run->length; i++)
    {
900
        if (*iso_run->item[i].pcls == NI)
901 902 903
        {
            int b = i-1;
            int f = i+1;
904 905 906 907 908
            *iso_run->item[i].pcls = EmbeddingDirection(iso_run->e);
            if (b > -1 && *iso_run->item[b].pcls == BN)
                *iso_run->item[b].pcls = EmbeddingDirection(iso_run->e);
            if (f < iso_run->length && *iso_run->item[f].pcls == BN)
                *iso_run->item[f].pcls = EmbeddingDirection(iso_run->e);
909 910
        }
    }
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
}

/*------------------------------------------------------------------------
    Function: resolveImplicit

    Recursively resolves implicit embedding levels.
    Implements rules I1 and I2 of the Unicode Bidirectional Algorithm.

    Input: Array of direction classes
           Character count
           Base level

    In/Out: Array of embedding levels

    Note: levels may exceed 15 on output.
          Accepted subset of direction classes
          R, L, AN, EN
------------------------------------------------------------------------*/
929
static void resolveImplicit(const WORD * pcls, WORD *plevel, int sos, int eos)
930
{
931
    int i;
932

933 934
    /* I1/2 */
    for (i = sos; i <= eos; i++)
935
    {
936
        if (pcls[i] == BN)
937
            continue;
938 939 940 941 942 943 944 945 946 947

        ASSERT(pcls[i] > 0); /* "No Neutrals allowed to survive here." */
        ASSERT(pcls[i] < 5); /* "Out of range." */

        if (odd(plevel[i]) && (pcls[i] == L || pcls[i] == EN || pcls [i] == AN))
            plevel[i]++;
        else if (!odd(plevel[i]) && pcls[i] == R)
            plevel[i]++;
        else if (!odd(plevel[i]) && (pcls[i] == EN || pcls [i] == AN))
            plevel[i]+=2;
948 949 950
    }
}

951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
static void resolveResolved(unsigned baselevel, const WORD * pcls, WORD *plevel, int sos, int eos)
{
    int i;

    /* L1 */
    for (i = sos; i <= eos; i++)
    {
        if (pcls[i] == B || pcls[i] == S)
        {
            int j = i -1;
            while (i > sos  && j >= sos &&
                   (pcls[j] == WS || pcls[j] == FSI || pcls[j] == LRI || pcls[j] == RLI ||
                    pcls[j] == PDI || pcls[j] == LRE || pcls[j] == RLE || pcls[j] == LRO ||
                    pcls[j] == RLO || pcls[j] == PDF || pcls[j] == BN))
                plevel[j--] = baselevel;
            plevel[i] = baselevel;
        }
        if (i == eos &&
            (pcls[i] == WS || pcls[i] == FSI || pcls[i] == LRI || pcls[i] == RLI ||
             pcls[i] == PDI || pcls[i] == LRE || pcls[i] == RLE || pcls[i] == LRO ||
             pcls[i] == RLO || pcls[i] == PDF || pcls[i] == BN ))
        {
            int j = i;
            while (j >= sos && (pcls[j] == WS || pcls[j] == FSI || pcls[j] == LRI || pcls[j] == RLI ||
                                pcls[j] == PDI || pcls[j] == LRE || pcls[j] == RLE || pcls[j] == LRO ||
                                pcls[j] == RLO || pcls[j] == PDF || pcls[j] == BN))
                plevel[j--] = baselevel;
        }
    }
}

982
static void computeIsolatingRunsSet(unsigned baselevel, WORD *pcls, WORD *pLevel, LPCWSTR lpString, int uCount, struct list *set)
983 984 985
{
    int run_start, run_end, i;
    int run_count = 0;
986
    Run *runs;
987 988
    IsolatedRun *current_isolated;

989 990 991
    runs = HeapAlloc(GetProcessHeap(), 0, uCount * sizeof(Run));
    if (!runs) return;

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
    list_init(set);

    /* Build Runs */
    run_start = 0;
    while (run_start < uCount)
    {
        run_end = nextValidChar(pcls, run_start, uCount);
        while (run_end < uCount && pLevel[run_end] == pLevel[run_start]) run_end = nextValidChar(pcls, run_end, uCount);
        run_end --;
        runs[run_count].start = run_start;
        runs[run_count].end = run_end;
        runs[run_count].e = pLevel[run_start];
        run_start = nextValidChar(pcls, run_end, uCount);
        run_count++;
    }

    /* Build Isolating Runs */
    i = 0;
    while (i < run_count)
    {
        int k = i;
        if (runs[k].start >= 0)
        {
            int type_fence, real_end;
            int j;
1017
            current_isolated = HeapAlloc(GetProcessHeap(), 0, sizeof(IsolatedRun) + sizeof(RunChar)*uCount);
1018
            if (!current_isolated) break;
1019 1020 1021 1022 1023 1024

            run_start = runs[k].start;
            current_isolated->e = runs[k].e;
            current_isolated->length = (runs[k].end - runs[k].start)+1;

            for (j = 0; j < current_isolated->length;  j++)
1025 1026 1027 1028
            {
                current_isolated->item[j].pcls = &pcls[runs[k].start+j];
                current_isolated->item[j].ch = lpString[runs[k].start+j];
            }
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

            run_end = runs[k].end;

            TRACE("{ [%i -- %i]",run_start, run_end);

            if (pcls[run_end] == BN)
                run_end = previousValidChar(pcls, run_end, runs[k].start);

            while (run_end < uCount && (pcls[run_end] == RLI || pcls[run_end] == LRI || pcls[run_end] == FSI))
            {
                j = k+1;
search:
                while (j < run_count && pcls[runs[j].start] != PDI) j++;
                if (j < run_count && runs[i].e != runs[j].e)
                {
                    j++;
                    goto search;
                }

                if (j != run_count)
                {
                    int m;
                    int l = current_isolated->length;

                    current_isolated->length += (runs[j].end - runs[j].start)+1;
                    for (m = 0; l < current_isolated->length; l++, m++)
1055 1056 1057 1058
                    {
                        current_isolated->item[l].pcls = &pcls[runs[j].start+m];
                        current_isolated->item[l].ch = lpString[runs[j].start+m];
                    }
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

                    TRACE("[%i -- %i]",runs[j].start, runs[j].end);

                    run_end = runs[j].end;
                    if (pcls[run_end] == BN)
                        run_end = previousValidChar(pcls, run_end, runs[i].start);
                    runs[j].start = -1;
                    k = j;
                }
                else
                {
                    run_end = uCount;
                    break;
                }
            }

            type_fence = previousValidChar(pcls, run_start, -1);

            if (type_fence == -1)
                current_isolated->sos = (baselevel > pLevel[run_start])?baselevel:pLevel[run_start];
            else
                current_isolated->sos = (pLevel[type_fence] > pLevel[run_start])?pLevel[type_fence]:pLevel[run_start];

            current_isolated->sos = EmbeddingDirection(current_isolated->sos);

            if (run_end == uCount)
                current_isolated->eos = current_isolated->sos;
            else
            {
                /* eos could be an BN */
                if ( pcls[run_end] == BN )
                {
                    real_end = previousValidChar(pcls, run_end, run_start-1);
                    if (real_end < run_start)
                        real_end = run_start;
                }
                else
                    real_end = run_end;

                type_fence = nextValidChar(pcls, run_end, uCount);
                if (type_fence == uCount)
                    current_isolated->eos = (baselevel > pLevel[real_end])?baselevel:pLevel[real_end];
                else
                    current_isolated->eos = (pLevel[type_fence] > pLevel[real_end])?pLevel[type_fence]:pLevel[real_end];

                current_isolated->eos = EmbeddingDirection(current_isolated->eos);
            }

            list_add_tail(set, &current_isolated->entry);
            TRACE(" } level %i {%s <--> %s}\n",current_isolated->e, debug_type[current_isolated->sos], debug_type[current_isolated->eos]);
        }
        i++;
    }
1112 1113

    HeapFree(GetProcessHeap(), 0, runs);
1114 1115
}

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
/*************************************************************
 *    BIDI_DeterminLevels
 */
BOOL BIDI_DetermineLevels(
                LPCWSTR lpString,       /* [in] The string for which information is to be returned */
                INT uCount,     /* [in] Number of WCHARs in string. */
                const SCRIPT_STATE *s,
                const SCRIPT_CONTROL *c,
                WORD *lpOutLevels /* [out] final string levels */
    )
{
    WORD *chartype;
1128
    unsigned baselevel = 0;
1129 1130 1131
    struct list IsolatingRuns;
    IsolatedRun *iso_run, *next;

1132
    TRACE("%s, %d\n", debugstr_wn(lpString, uCount), uCount);
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143

    chartype = HeapAlloc(GetProcessHeap(), 0, uCount * sizeof(WORD));
    if (!chartype)
    {
        WARN("Out of memory\n");
        return FALSE;
    }

    baselevel = s->uBidiLevel;

    classify(lpString, chartype, uCount, c);
1144
    if (TRACE_ON(bidi)) dump_types("Start ", chartype, 0, uCount);
1145 1146

    /* resolve explicit */
1147 1148
    resolveExplicit(baselevel, chartype, lpOutLevels, uCount);
    if (TRACE_ON(bidi)) dump_types("After Explicit", chartype, 0, uCount);
1149

1150
    /* X10/BD13: Computer Isolating runs */
1151
    computeIsolatingRunsSet(baselevel, chartype, lpOutLevels, lpString, uCount, &IsolatingRuns);
1152 1153 1154 1155 1156 1157 1158 1159 1160

    LIST_FOR_EACH_ENTRY_SAFE(iso_run, next, &IsolatingRuns, IsolatedRun, entry)
    {
        if (TRACE_ON(bidi)) iso_dump_types("Run", iso_run);

        /* resolve weak */
        resolveWeak(iso_run);
        if (TRACE_ON(bidi)) iso_dump_types("After Weak", iso_run);

1161 1162 1163
        /* resolve neutrals */
        resolveNeutrals(iso_run);
        if (TRACE_ON(bidi)) iso_dump_types("After Neutrals", iso_run);
1164 1165 1166 1167

        list_remove(&iso_run->entry);
        HeapFree(GetProcessHeap(),0,iso_run);
    }
1168

1169
    if (TRACE_ON(bidi)) dump_types("Before Implicit", chartype, 0, uCount);
1170
    /* resolveImplicit */
1171
    resolveImplicit(chartype, lpOutLevels, 0, uCount-1);
1172

1173 1174 1175 1176
    /* resolveResolvedLevels*/
    classify(lpString, chartype, uCount, c);
    resolveResolved(baselevel, chartype, lpOutLevels, 0, uCount-1);

1177 1178 1179
    HeapFree(GetProcessHeap(), 0, chartype);
    return TRUE;
}
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242

/* reverse cch indexes */
static void reverse(int *pidx, int cch)
{
    int temp;
    int ich = 0;
    for (; ich < --cch; ich++)
    {
        temp = pidx[ich];
        pidx[ich] = pidx[cch];
        pidx[cch] = temp;
    }
}


/*------------------------------------------------------------------------
    Functions: reorder/reorderLevel

    Recursively reorders the display string
    "From the highest level down, reverse all characters at that level and
    higher, down to the lowest odd level"

    Implements rule L2 of the Unicode bidi Algorithm.

    Input: Array of embedding levels
           Character count
           Flag enabling reversal (set to false by initial caller)

    In/Out: Text to reorder

    Note: levels may exceed 15 resp. 61 on input.

    Rule L3 - reorder combining marks is not implemented here
    Rule L4 - glyph mirroring is implemented as a display option below

    Note: this should be applied a line at a time
-------------------------------------------------------------------------*/
int BIDI_ReorderV2lLevel(int level, int *pIndexs, const BYTE* plevel, int cch, BOOL fReverse)
{
    int ich = 0;

    /* true as soon as first odd level encountered */
    fReverse = fReverse || odd(level);

    for (; ich < cch; ich++)
    {
        if (plevel[ich] < level)
        {
            break;
        }
        else if (plevel[ich] > level)
        {
            ich += BIDI_ReorderV2lLevel(level + 1, pIndexs + ich, plevel + ich,
                cch - ich, fReverse) - 1;
        }
    }
    if (fReverse)
    {
        reverse(pIndexs, ich);
    }
    return ich;
}

1243
/* Applies the reorder in reverse. Taking an already reordered string and returning the original */
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
int BIDI_ReorderL2vLevel(int level, int *pIndexs, const BYTE* plevel, int cch, BOOL fReverse)
{
    int ich = 0;
    int newlevel = -1;

    /* true as soon as first odd level encountered */
    fReverse = fReverse || odd(level);

    for (; ich < cch; ich++)
    {
        if (plevel[ich] < level)
            break;
        else if (plevel[ich] > level)
            newlevel = ich;
    }
    if (fReverse)
    {
        reverse(pIndexs, ich);
    }

1264
    if (newlevel >= 0)
1265 1266 1267
    {
        ich = 0;
        for (; ich < cch; ich++)
1268 1269 1270
            if (plevel[ich] < level)
                break;
            else if (plevel[ich] > level)
1271 1272 1273 1274 1275 1276
                ich += BIDI_ReorderL2vLevel(level + 1, pIndexs + ich, plevel + ich,
                cch - ich, fReverse) - 1;
    }

    return ich;
}
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294

BOOL BIDI_GetStrengths(LPCWSTR lpString, INT uCount, const SCRIPT_CONTROL *c,
                      WORD* lpStrength)
{
    int i;
    classify(lpString, lpStrength, uCount, c);

    for ( i = 0; i < uCount; i++)
    {
        switch(lpStrength[i])
        {
            case L:
            case LRE:
            case LRO:
            case R:
            case AL:
            case RLE:
            case RLO:
1295
                lpStrength[i] = BIDI_STRONG;
1296 1297 1298 1299 1300 1301 1302 1303
                break;
            case PDF:
            case EN:
            case ES:
            case ET:
            case AN:
            case CS:
            case BN:
1304
                lpStrength[i] = BIDI_WEAK;
1305
                break;
1306 1307 1308 1309
            case B:
            case S:
            case WS:
            case ON:
1310
            default: /* Neutrals and NSM */
1311
                lpStrength[i] = BIDI_NEUTRAL;
1312 1313 1314 1315
        }
    }
    return TRUE;
}