This repository has been archived by the owner on Oct 3, 2020. It is now read-only.
/
nsBidi.cpp
2248 lines (2024 loc) · 68.9 KB
/
nsBidi.cpp
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
109
110
111
112
113
114
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
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
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* IBM Corporation.
* Portions created by the Initial Developer are Copyright (C) 2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Simon Montagu
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifdef IBMBIDI
#include "prmem.h"
#include "nsBidi.h"
#include "nsBidiUtils.h"
#include "nsCRT.h"
// These are #defined in <sys/regset.h> under Solaris 10 x86
#undef CS
#undef ES
/* Comparing the description of the Bidi algorithm with this implementation
is easier with the same names for the Bidi types in the code as there.
*/
enum {
L = eCharType_LeftToRight,
R = eCharType_RightToLeft,
EN = eCharType_EuropeanNumber,
ES = eCharType_EuropeanNumberSeparator,
ET = eCharType_EuropeanNumberTerminator,
AN = eCharType_ArabicNumber,
CS = eCharType_CommonNumberSeparator,
B = eCharType_BlockSeparator,
S = eCharType_SegmentSeparator,
WS = eCharType_WhiteSpaceNeutral,
O_N = eCharType_OtherNeutral,
LRE = eCharType_LeftToRightEmbedding,
LRO = eCharType_LeftToRightOverride,
AL = eCharType_RightToLeftArabic,
RLE = eCharType_RightToLeftEmbedding,
RLO = eCharType_RightToLeftOverride,
PDF = eCharType_PopDirectionalFormat,
NSM = eCharType_DirNonSpacingMark,
BN = eCharType_BoundaryNeutral,
dirPropCount
};
/* to avoid some conditional statements, use tiny constant arrays */
static Flags flagLR[2]={ DIRPROP_FLAG(L), DIRPROP_FLAG(R) };
static Flags flagE[2]={ DIRPROP_FLAG(LRE), DIRPROP_FLAG(RLE) };
static Flags flagO[2]={ DIRPROP_FLAG(LRO), DIRPROP_FLAG(RLO) };
#define DIRPROP_FLAG_LR(level) flagLR[(level)&1]
#define DIRPROP_FLAG_E(level) flagE[(level)&1]
#define DIRPROP_FLAG_O(level) flagO[(level)&1]
/*
* General implementation notes:
*
* Throughout the implementation, there are comments like (W2) that refer to
* rules of the Bidi algorithm in its version 5, in this example to the second
* rule of the resolution of weak types.
*
* For handling surrogate pairs, where two UChar's form one "abstract" (or UTF-32)
* character according to UTF-16, the second UChar gets the directional property of
* the entire character assigned, while the first one gets a BN, a boundary
* neutral, type, which is ignored by most of the algorithm according to
* rule (X9) and the implementation suggestions of the Bidi algorithm.
*
* Later, AdjustWSLevels() will set the level for each BN to that of the
* following character (UChar), which results in surrogate pairs getting the
* same level on each of their surrogates.
*
* In a UTF-8 implementation, the same thing could be done: the last byte of
* a multi-byte sequence would get the "real" property, while all previous
* bytes of that sequence would get BN.
*
* It is not possible to assign all those parts of a character the same real
* property because this would fail in the resolution of weak types with rules
* that look at immediately surrounding types.
*
* As a related topic, this implementation does not remove Boundary Neutral
* types from the input, but ignores them whenever this is relevant.
* For example, the loop for the resolution of the weak types reads
* types until it finds a non-BN.
* Also, explicit embedding codes are neither changed into BN nor removed.
* They are only treated the same way real BNs are.
* As stated before, AdjustWSLevels() takes care of them at the end.
* For the purpose of conformance, the levels of all these codes
* do not matter.
*
* Note that this implementation never modifies the dirProps
* after the initial setup.
*
*
* In this implementation, the resolution of weak types (Wn),
* neutrals (Nn), and the assignment of the resolved level (In)
* are all done in one single loop, in ResolveImplicitLevels().
* Changes of dirProp values are done on the fly, without writing
* them back to the dirProps array.
*
*
* This implementation contains code that allows to bypass steps of the
* algorithm that are not needed on the specific paragraph
* in order to speed up the most common cases considerably,
* like text that is entirely LTR, or RTL text without numbers.
*
* Most of this is done by setting a bit for each directional property
* in a flags variable and later checking for whether there are
* any LTR characters or any RTL characters, or both, whether
* there are any explicit embedding codes, etc.
*
* If the (Xn) steps are performed, then the flags are re-evaluated,
* because they will then not contain the embedding codes any more
* and will be adjusted for override codes, so that subsequently
* more bypassing may be possible than what the initial flags suggested.
*
* If the text is not mixed-directional, then the
* algorithm steps for the weak type resolution are not performed,
* and all levels are set to the paragraph level.
*
* If there are no explicit embedding codes, then the (Xn) steps
* are not performed.
*
* If embedding levels are supplied as a parameter, then all
* explicit embedding codes are ignored, and the (Xn) steps
* are not performed.
*
* White Space types could get the level of the run they belong to,
* and are checked with a test of (flags&MASK_EMBEDDING) to
* consider if the paragraph direction should be considered in
* the flags variable.
*
* If there are no White Space types in the paragraph, then
* (L1) is not necessary in AdjustWSLevels().
*/
nsBidi::nsBidi()
{
Init();
mMayAllocateText=PR_TRUE;
mMayAllocateRuns=PR_TRUE;
}
nsBidi::~nsBidi()
{
Free();
}
void nsBidi::Init()
{
/* reset the object, all pointers NULL, all flags PR_FALSE, all sizes 0 */
mLength = 0;
mParaLevel = 0;
mFlags = 0;
mDirection = NSBIDI_LTR;
mTrailingWSStart = 0;
mDirPropsSize = 0;
mLevelsSize = 0;
mRunsSize = 0;
mRunCount = -1;
mDirProps=NULL;
mLevels=NULL;
mRuns=NULL;
mDirPropsMemory=NULL;
mLevelsMemory=NULL;
mRunsMemory=NULL;
mMayAllocateText=PR_FALSE;
mMayAllocateRuns=PR_FALSE;
}
/*
* We are allowed to allocate memory if aMemory==NULL or
* aMayAllocate==PR_TRUE for each array that we need.
* We also try to grow and shrink memory as needed if we
* allocate it.
*
* Assume aSizeNeeded>0.
* If *aMemory!=NULL, then assume *aSize>0.
*
* ### this realloc() may unnecessarily copy the old data,
* which we know we don't need any more;
* is this the best way to do this??
*/
PRBool nsBidi::GetMemory(void **aMemory, PRSize *aSize, PRBool aMayAllocate, PRSize aSizeNeeded)
{
/* check for existing memory */
if(*aMemory==NULL) {
/* we need to allocate memory */
if(!aMayAllocate) {
return PR_FALSE;
} else {
*aMemory=PR_MALLOC(aSizeNeeded);
if (*aMemory!=NULL) {
*aSize=aSizeNeeded;
return PR_TRUE;
} else {
*aSize=0;
return PR_FALSE;
}
}
} else {
/* there is some memory, is it enough or too much? */
if(aSizeNeeded>*aSize && !aMayAllocate) {
/* not enough memory, and we must not allocate */
return PR_FALSE;
} else if(aSizeNeeded!=*aSize && aMayAllocate) {
/* we may try to grow or shrink */
void *memory=PR_REALLOC(*aMemory, aSizeNeeded);
if(memory!=NULL) {
*aMemory=memory;
*aSize=aSizeNeeded;
return PR_TRUE;
} else {
/* we failed to grow */
return PR_FALSE;
}
} else {
/* we have at least enough memory and must not allocate */
return PR_TRUE;
}
}
}
void nsBidi::Free()
{
PR_FREEIF(mDirPropsMemory);
PR_FREEIF(mLevelsMemory);
PR_FREEIF(mRunsMemory);
}
/* SetPara ------------------------------------------------------------ */
nsresult nsBidi::SetPara(const PRUnichar *aText, PRInt32 aLength,
nsBidiLevel aParaLevel, nsBidiLevel *aEmbeddingLevels)
{
nsBidiDirection direction;
/* check the argument values */
if(aText==NULL ||
((NSBIDI_MAX_EXPLICIT_LEVEL<aParaLevel) && !IS_DEFAULT_LEVEL(aParaLevel)) ||
aLength<-1
) {
return NS_ERROR_INVALID_ARG;
}
if(aLength==-1) {
aLength=nsCRT::strlen(aText);
}
/* initialize member data */
mLength=aLength;
mParaLevel=aParaLevel;
mDirection=NSBIDI_LTR;
mTrailingWSStart=aLength; /* the levels[] will reflect the WS run */
mDirProps=NULL;
mLevels=NULL;
mRuns=NULL;
if(aLength==0) {
/*
* For an empty paragraph, create an nsBidi object with the aParaLevel and
* the flags and the direction set but without allocating zero-length arrays.
* There is nothing more to do.
*/
if(IS_DEFAULT_LEVEL(aParaLevel)) {
mParaLevel&=1;
}
if(aParaLevel&1) {
mFlags=DIRPROP_FLAG(R);
mDirection=NSBIDI_RTL;
} else {
mFlags=DIRPROP_FLAG(L);
mDirection=NSBIDI_LTR;
}
mRunCount=0;
return NS_OK;
}
mRunCount=-1;
/*
* Get the directional properties,
* the flags bit-set, and
* determine the partagraph level if necessary.
*/
if(GETDIRPROPSMEMORY(aLength)) {
mDirProps=mDirPropsMemory;
GetDirProps(aText);
} else {
return NS_ERROR_OUT_OF_MEMORY;
}
/* are explicit levels specified? */
if(aEmbeddingLevels==NULL) {
/* no: determine explicit levels according to the (Xn) rules */\
if(GETLEVELSMEMORY(aLength)) {
mLevels=mLevelsMemory;
direction=ResolveExplicitLevels();
} else {
return NS_ERROR_OUT_OF_MEMORY;
}
} else {
/* set BN for all explicit codes, check that all levels are aParaLevel..NSBIDI_MAX_EXPLICIT_LEVEL */
mLevels=aEmbeddingLevels;
nsresult rv = CheckExplicitLevels(&direction);
if(NS_FAILED(rv)) {
return rv;
}
}
/*
* The steps after (X9) in the Bidi algorithm are performed only if
* the paragraph text has mixed directionality!
*/
switch(direction) {
case NSBIDI_LTR:
/* make sure paraLevel is even */
mParaLevel=(mParaLevel+1)&~1;
/* all levels are implicitly at paraLevel (important for GetLevels()) */
mTrailingWSStart=0;
break;
case NSBIDI_RTL:
/* make sure paraLevel is odd */
mParaLevel|=1;
/* all levels are implicitly at paraLevel (important for GetLevels()) */
mTrailingWSStart=0;
break;
default:
/*
* If there are no external levels specified and there
* are no significant explicit level codes in the text,
* then we can treat the entire paragraph as one run.
* Otherwise, we need to perform the following rules on runs of
* the text with the same embedding levels. (X10)
* "Significant" explicit level codes are ones that actually
* affect non-BN characters.
* Examples for "insignificant" ones are empty embeddings
* LRE-PDF, LRE-RLE-PDF-PDF, etc.
*/
if(aEmbeddingLevels==NULL && !(mFlags&DIRPROP_FLAG_MULTI_RUNS)) {
ResolveImplicitLevels(0, aLength,
GET_LR_FROM_LEVEL(mParaLevel),
GET_LR_FROM_LEVEL(mParaLevel));
} else {
/* sor, eor: start and end types of same-level-run */
nsBidiLevel *levels=mLevels;
PRInt32 start, limit=0;
nsBidiLevel level, nextLevel;
DirProp sor, eor;
/* determine the first sor and set eor to it because of the loop body (sor=eor there) */
level=mParaLevel;
nextLevel=levels[0];
if(level<nextLevel) {
eor=GET_LR_FROM_LEVEL(nextLevel);
} else {
eor=GET_LR_FROM_LEVEL(level);
}
do {
/* determine start and limit of the run (end points just behind the run) */
/* the values for this run's start are the same as for the previous run's end */
sor=eor;
start=limit;
level=nextLevel;
/* search for the limit of this run */
while(++limit<aLength && levels[limit]==level) {}
/* get the correct level of the next run */
if(limit<aLength) {
nextLevel=levels[limit];
} else {
nextLevel=mParaLevel;
}
/* determine eor from max(level, nextLevel); sor is last run's eor */
if((level&~NSBIDI_LEVEL_OVERRIDE)<(nextLevel&~NSBIDI_LEVEL_OVERRIDE)) {
eor=GET_LR_FROM_LEVEL(nextLevel);
} else {
eor=GET_LR_FROM_LEVEL(level);
}
/* if the run consists of overridden directional types, then there
are no implicit types to be resolved */
if(!(level&NSBIDI_LEVEL_OVERRIDE)) {
ResolveImplicitLevels(start, limit, sor, eor);
}
} while(limit<aLength);
}
/* reset the embedding levels for some non-graphic characters (L1), (X9) */
AdjustWSLevels();
break;
}
mDirection=direction;
return NS_OK;
}
/* perform (P2)..(P3) ------------------------------------------------------- */
/*
* Get the directional properties for the text,
* calculate the flags bit-set, and
* determine the partagraph level if necessary.
*/
void nsBidi::GetDirProps(const PRUnichar *aText)
{
DirProp *dirProps=mDirPropsMemory; /* mDirProps is const */
PRInt32 i=0, length=mLength;
Flags flags=0; /* collect all directionalities in the text */
PRUnichar uchar;
DirProp dirProp;
if(IS_DEFAULT_LEVEL(mParaLevel)) {
/* determine the paragraph level (P2..P3) */
for(;;) {
uchar=aText[i];
if(!IS_FIRST_SURROGATE(uchar) || i+1==length || !IS_SECOND_SURROGATE(aText[i+1])) {
/* not a surrogate pair */
flags|=DIRPROP_FLAG(dirProps[i]=dirProp=GetCharType((PRUint32)uchar));
} else {
/* a surrogate pair */
dirProps[i++]=BN; /* first surrogate in the pair gets the BN type */
flags|=DIRPROP_FLAG(dirProps[i]=dirProp=GetCharType(GET_UTF_32(uchar, aText[i])))|DIRPROP_FLAG(BN);
}
++i;
if(dirProp==L) {
mParaLevel=0;
break;
} else if(dirProp==R || dirProp==AL) {
mParaLevel=1;
break;
} else if(i==length) {
/*
* see comment in nsIBidi.h:
* the DEFAULT_XXX values are designed so that
* their bit 0 alone yields the intended default
*/
mParaLevel&=1;
break;
}
}
}
/* get the rest of the directional properties and the flags bits */
while(i<length) {
uchar=aText[i];
if(!IS_FIRST_SURROGATE(uchar) || i+1==length || !IS_SECOND_SURROGATE(aText[i+1])) {
/* not a surrogate pair */
flags|=DIRPROP_FLAG(dirProps[i]=GetCharType((PRUint32)uchar));
} else {
/* a surrogate pair */
dirProps[i++]=BN; /* second surrogate in the pair gets the BN type */
flags|=DIRPROP_FLAG(dirProps[i]=GetCharType(GET_UTF_32(uchar, aText[i])))|DIRPROP_FLAG(BN);
}
++i;
}
if(flags&MASK_EMBEDDING) {
flags|=DIRPROP_FLAG_LR(mParaLevel);
}
mFlags=flags;
}
/* perform (X1)..(X9) ------------------------------------------------------- */
/*
* Resolve the explicit levels as specified by explicit embedding codes.
* Recalculate the flags to have them reflect the real properties
* after taking the explicit embeddings into account.
*
* The Bidi algorithm is designed to result in the same behavior whether embedding
* levels are externally specified (from "styled text", supposedly the preferred
* method) or set by explicit embedding codes (LRx, RLx, PDF) in the plain text.
* That is why (X9) instructs to remove all explicit codes (and BN).
* However, in a real implementation, this removal of these codes and their index
* positions in the plain text is undesirable since it would result in
* reallocated, reindexed text.
* Instead, this implementation leaves the codes in there and just ignores them
* in the subsequent processing.
* In order to get the same reordering behavior, positions with a BN or an
* explicit embedding code just get the same level assigned as the last "real"
* character.
*
* Some implementations, not this one, then overwrite some of these
* directionality properties at "real" same-level-run boundaries by
* L or R codes so that the resolution of weak types can be performed on the
* entire paragraph at once instead of having to parse it once more and
* perform that resolution on same-level-runs.
* This limits the scope of the implicit rules in effectively
* the same way as the run limits.
*
* Instead, this implementation does not modify these codes.
* On one hand, the paragraph has to be scanned for same-level-runs, but
* on the other hand, this saves another loop to reset these codes,
* or saves making and modifying a copy of dirProps[].
*
*
* Note that (Pn) and (Xn) changed significantly from version 4 of the Bidi algorithm.
*
*
* Handling the stack of explicit levels (Xn):
*
* With the Bidi stack of explicit levels,
* as pushed with each LRE, RLE, LRO, and RLO and popped with each PDF,
* the explicit level must never exceed NSBIDI_MAX_EXPLICIT_LEVEL==61.
*
* In order to have a correct push-pop semantics even in the case of overflows,
* there are two overflow counters:
* - countOver60 is incremented with each LRx at level 60
* - from level 60, one RLx increases the level to 61
* - countOver61 is incremented with each LRx and RLx at level 61
*
* Popping levels with PDF must work in the opposite order so that level 61
* is correct at the correct point. Underflows (too many PDFs) must be checked.
*
* This implementation assumes that NSBIDI_MAX_EXPLICIT_LEVEL is odd.
*/
nsBidiDirection nsBidi::ResolveExplicitLevels()
{
const DirProp *dirProps=mDirProps;
nsBidiLevel *levels=mLevels;
PRInt32 i=0, length=mLength;
Flags flags=mFlags; /* collect all directionalities in the text */
DirProp dirProp;
nsBidiLevel level=mParaLevel;
nsBidiDirection direction;
/* determine if the text is mixed-directional or single-directional */
direction=DirectionFromFlags(flags);
/* we may not need to resolve any explicit levels */
if(direction!=NSBIDI_MIXED) {
/* not mixed directionality: levels don't matter - trailingWSStart will be 0 */
} else if(!(flags&MASK_EXPLICIT)) {
/* mixed, but all characters are at the same embedding level */
/* set all levels to the paragraph level */
for(i=0; i<length; ++i) {
levels[i]=level;
}
} else {
/* continue to perform (Xn) */
/* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */
/* both variables may carry the NSBIDI_LEVEL_OVERRIDE flag to indicate the override status */
nsBidiLevel embeddingLevel=level, newLevel, stackTop=0;
nsBidiLevel stack[NSBIDI_MAX_EXPLICIT_LEVEL]; /* we never push anything >=NSBIDI_MAX_EXPLICIT_LEVEL */
PRUint32 countOver60=0, countOver61=0; /* count overflows of explicit levels */
/* recalculate the flags */
flags=0;
/* since we assume that this is a single paragraph, we ignore (X8) */
for(i=0; i<length; ++i) {
dirProp=dirProps[i];
switch(dirProp) {
case LRE:
case LRO:
/* (X3, X5) */
newLevel=(embeddingLevel+2)&~(NSBIDI_LEVEL_OVERRIDE|1); /* least greater even level */
if(newLevel<=NSBIDI_MAX_EXPLICIT_LEVEL) {
stack[stackTop]=embeddingLevel;
++stackTop;
embeddingLevel=newLevel;
if(dirProp==LRO) {
embeddingLevel|=NSBIDI_LEVEL_OVERRIDE;
} else {
embeddingLevel&=~NSBIDI_LEVEL_OVERRIDE;
}
} else if((embeddingLevel&~NSBIDI_LEVEL_OVERRIDE)==NSBIDI_MAX_EXPLICIT_LEVEL) {
++countOver61;
} else /* (embeddingLevel&~NSBIDI_LEVEL_OVERRIDE)==NSBIDI_MAX_EXPLICIT_LEVEL-1 */ {
++countOver60;
}
flags|=DIRPROP_FLAG(BN);
break;
case RLE:
case RLO:
/* (X2, X4) */
newLevel=((embeddingLevel&~NSBIDI_LEVEL_OVERRIDE)+1)|1; /* least greater odd level */
if(newLevel<=NSBIDI_MAX_EXPLICIT_LEVEL) {
stack[stackTop]=embeddingLevel;
++stackTop;
embeddingLevel=newLevel;
if(dirProp==RLO) {
embeddingLevel|=NSBIDI_LEVEL_OVERRIDE;
} else {
embeddingLevel&=~NSBIDI_LEVEL_OVERRIDE;
}
} else {
++countOver61;
}
flags|=DIRPROP_FLAG(BN);
break;
case PDF:
/* (X7) */
/* handle all the overflow cases first */
if(countOver61>0) {
--countOver61;
} else if(countOver60>0 && (embeddingLevel&~NSBIDI_LEVEL_OVERRIDE)!=NSBIDI_MAX_EXPLICIT_LEVEL) {
/* handle LRx overflows from level 60 */
--countOver60;
} else if(stackTop>0) {
/* this is the pop operation; it also pops level 61 while countOver60>0 */
--stackTop;
embeddingLevel=stack[stackTop];
/* } else { (underflow) */
}
flags|=DIRPROP_FLAG(BN);
break;
case B:
/*
* We do not really expect to see a paragraph separator (B),
* but we should do something reasonable with it,
* especially at the end of the text.
*/
stackTop=0;
countOver60=countOver61=0;
embeddingLevel=level=mParaLevel;
flags|=DIRPROP_FLAG(B);
break;
case BN:
/* BN, LRE, RLE, and PDF are supposed to be removed (X9) */
/* they will get their levels set correctly in AdjustWSLevels() */
flags|=DIRPROP_FLAG(BN);
break;
default:
/* all other types get the "real" level */
if(level!=embeddingLevel) {
level=embeddingLevel;
if(level&NSBIDI_LEVEL_OVERRIDE) {
flags|=DIRPROP_FLAG_O(level)|DIRPROP_FLAG_MULTI_RUNS;
} else {
flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG_MULTI_RUNS;
}
}
if(!(level&NSBIDI_LEVEL_OVERRIDE)) {
flags|=DIRPROP_FLAG(dirProp);
}
break;
}
/*
* We need to set reasonable levels even on BN codes and
* explicit codes because we will later look at same-level runs (X10).
*/
levels[i]=level;
}
if(flags&MASK_EMBEDDING) {
flags|=DIRPROP_FLAG_LR(mParaLevel);
}
/* subsequently, ignore the explicit codes and BN (X9) */
/* again, determine if the text is mixed-directional or single-directional */
mFlags=flags;
direction=DirectionFromFlags(flags);
}
return direction;
}
/*
* Use a pre-specified embedding levels array:
*
* Adjust the directional properties for overrides (->LEVEL_OVERRIDE),
* ignore all explicit codes (X9),
* and check all the preset levels.
*
* Recalculate the flags to have them reflect the real properties
* after taking the explicit embeddings into account.
*/
nsresult nsBidi::CheckExplicitLevels(nsBidiDirection *aDirection)
{
const DirProp *dirProps=mDirProps;
nsBidiLevel *levels=mLevels;
PRInt32 i, length=mLength;
Flags flags=0; /* collect all directionalities in the text */
nsBidiLevel level, paraLevel=mParaLevel;
for(i=0; i<length; ++i) {
level=levels[i];
if(level&NSBIDI_LEVEL_OVERRIDE) {
/* keep the override flag in levels[i] but adjust the flags */
level&=~NSBIDI_LEVEL_OVERRIDE; /* make the range check below simpler */
flags|=DIRPROP_FLAG_O(level);
} else {
/* set the flags */
flags|=DIRPROP_FLAG_E(level)|DIRPROP_FLAG(dirProps[i]);
}
if(level<paraLevel || NSBIDI_MAX_EXPLICIT_LEVEL<level) {
/* level out of bounds */
*aDirection = NSBIDI_LTR;
return NS_ERROR_INVALID_ARG;
}
}
if(flags&MASK_EMBEDDING) {
flags|=DIRPROP_FLAG_LR(mParaLevel);
}
/* determine if the text is mixed-directional or single-directional */
mFlags=flags;
*aDirection = DirectionFromFlags(flags);
return NS_OK;
}
/* determine if the text is mixed-directional or single-directional */
nsBidiDirection nsBidi::DirectionFromFlags(Flags aFlags)
{
/* if the text contains AN and neutrals, then some neutrals may become RTL */
if(!(aFlags&MASK_RTL || (aFlags&DIRPROP_FLAG(AN) && aFlags&MASK_POSSIBLE_N))) {
return NSBIDI_LTR;
} else if(!(aFlags&MASK_LTR)) {
return NSBIDI_RTL;
} else {
return NSBIDI_MIXED;
}
}
/* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */
/*
* This implementation of the (Wn) rules applies all rules in one pass.
* In order to do so, it needs a look-ahead of typically 1 character
* (except for W5: sequences of ET) and keeps track of changes
* in a rule Wp that affect a later Wq (p<q).
*
* historyOfEN is a variable-saver: it contains 4 boolean states;
* a bit in it set to 1 means:
* bit 0: the current code is an EN after W2
* bit 1: the current code is an EN after W4
* bit 2: the previous code was an EN after W2
* bit 3: the previous code was an EN after W4
* In other words, b0..1 have transitions of EN in the current iteration,
* while b2..3 have the transitions of EN in the previous iteration.
* A simple historyOfEN<<=2 suffices for the propagation.
*
* The (Nn) and (In) rules are also performed in that same single loop,
* but effectively one iteration behind for white space.
*
* Since all implicit rules are performed in one step, it is not necessary
* to actually store the intermediate directional properties in dirProps[].
*/
#define EN_SHIFT 2
#define EN_AFTER_W2 1
#define EN_AFTER_W4 2
#define EN_ALL 3
#define PREV_EN_AFTER_W2 4
#define PREV_EN_AFTER_W4 8
void nsBidi::ResolveImplicitLevels(PRInt32 aStart, PRInt32 aLimit,
DirProp aSOR, DirProp aEOR)
{
const DirProp *dirProps=mDirProps;
nsBidiLevel *levels=mLevels;
PRInt32 i, next, neutralStart=-1;
DirProp prevDirProp, dirProp, nextDirProp, lastStrong, beforeNeutral;
PRUint8 historyOfEN;
/* initialize: current at aSOR, next at aStart (it is aStart<aLimit) */
next=aStart;
beforeNeutral=dirProp=lastStrong=aSOR;
nextDirProp=dirProps[next];
historyOfEN=0;
/*
* In all steps of this implementation, BN and explicit embedding codes
* must be treated as if they didn't exist (X9).
* They will get levels set before a non-neutral character, and remain
* undefined before a neutral one, but AdjustWSLevels() will take care
* of all of them.
*/
while(DIRPROP_FLAG(nextDirProp)&MASK_BN_EXPLICIT) {
if(++next<aLimit) {
nextDirProp=dirProps[next];
} else {
nextDirProp=aEOR;
break;
}
}
/* loop for entire run */
while(next<aLimit) {
/* advance */
prevDirProp=dirProp;
dirProp=nextDirProp;
i=next;
do {
if(++next<aLimit) {
nextDirProp=dirProps[next];
} else {
nextDirProp=aEOR;
break;
}
} while(DIRPROP_FLAG(nextDirProp)&MASK_BN_EXPLICIT);
historyOfEN<<=EN_SHIFT;
/* (W1..W7) */
switch(dirProp) {
case L:
lastStrong=L;
break;
case R:
lastStrong=R;
break;
case AL:
/* (W3) */
lastStrong=AL;
dirProp=R;
break;
case EN:
/* we have to set historyOfEN correctly */
if(lastStrong==AL) {
/* (W2) */
dirProp=AN;
} else {
if(lastStrong==L) {
/* (W7) */
dirProp=L;
}
/* this EN stays after (W2) and (W4) - at least before (W7) */
historyOfEN|=EN_ALL;
}
break;
case ES:
if( historyOfEN&PREV_EN_AFTER_W2 && /* previous was EN before (W4) */
nextDirProp==EN && lastStrong!=AL /* next is EN and (W2) won't make it AN */
) {
/* (W4) */
if(lastStrong!=L) {
dirProp=EN;
} else {
/* (W7) */
dirProp=L;
}
historyOfEN|=EN_AFTER_W4;
} else {
/* (W6) */
dirProp=O_N;
}
break;
case CS:
if( historyOfEN&PREV_EN_AFTER_W2 && /* previous was EN before (W4) */
nextDirProp==EN && lastStrong!=AL /* next is EN and (W2) won't make it AN */
) {
/* (W4) */
if(lastStrong!=L) {
dirProp=EN;
} else {
/* (W7) */
dirProp=L;
}
historyOfEN|=EN_AFTER_W4;
} else if(prevDirProp==AN && /* previous was AN */
(nextDirProp==AN || /* next is AN */
(nextDirProp==EN && lastStrong==AL)) /* or (W2) will make it one */
) {
/* (W4) */
dirProp=AN;
} else {
/* (W6) */
dirProp=O_N;
}
break;
case ET:
/* get sequence of ET; advance only next, not current, previous or historyOfEN */
while(next<aLimit && DIRPROP_FLAG(nextDirProp)&MASK_ET_NSM_BN /* (W1), (X9) */) {
if(++next<aLimit) {
nextDirProp=dirProps[next];
} else {
nextDirProp=aEOR;
break;
}
}
if( historyOfEN&PREV_EN_AFTER_W4 || /* previous was EN before (W5) */
(nextDirProp==EN && lastStrong!=AL) /* next is EN and (W2) won't make it AN */
) {
/* (W5) */
if(lastStrong!=L) {
dirProp=EN;
} else {
/* (W7) */
dirProp=L;
}
} else {
/* (W6) */
dirProp=O_N;
}
/* apply the result of (W1), (W5)..(W7) to the entire sequence of ET */
break;
case NSM:
/* (W1) */
dirProp=prevDirProp;
/* set historyOfEN back to prevDirProp's historyOfEN */
historyOfEN>>=EN_SHIFT;
/*
* Technically, this should be done before the switch() in the form
* if(nextDirProp==NSM) {
* dirProps[next]=nextDirProp=dirProp;
* }
*
* - effectively one iteration ahead.
* However, whether the next dirProp is NSM or is equal to the current dirProp
* does not change the outcome of any condition in (W2)..(W7).
*/
break;
default:
break;
}
/* here, it is always [prev,this,next]dirProp!=BN; it may be next>i+1 */
/* perform (Nn) - here, only L, R, EN, AN, and neutrals are left */
/* this is one iteration late for the neutrals */
if(DIRPROP_FLAG(dirProp)&MASK_N) {
if(neutralStart<0) {
/* start of a sequence of neutrals */
neutralStart=i;
beforeNeutral=prevDirProp;
}
} else /* not a neutral, can be only one of { L, R, EN, AN } */ {
/*
* Note that all levels[] values are still the same at this
* point because this function is called for an entire
* same-level run.
* Therefore, we need to read only one actual level.
*/
nsBidiLevel level=levels[i];
if(neutralStart>=0) {
nsBidiLevel final;
/* end of a sequence of neutrals (dirProp is "afterNeutral") */
if(beforeNeutral==L) {
if(dirProp==L) {
final=0; /* make all neutrals L (N1) */
} else {
final=level; /* make all neutrals "e" (N2) */
}
} else /* beforeNeutral is one of { R, EN, AN } */ {
if(dirProp==L) {
final=level; /* make all neutrals "e" (N2) */
} else {
final=1; /* make all neutrals R (N1) */
}
}
/* perform (In) on the sequence of neutrals */
if((level^final)&1) {
/* do something only if we need to _change_ the level */
do {
++levels[neutralStart];