7 require_once( dirname( __FILE__
) .'/../Maintenance.php' );
10 * Generate first letter data files for Collation.php
12 class GenerateCollationData
extends Maintenance
{
13 /** The directory with source data files in it */
16 /** The primary weights, indexed by codepoint */
20 * A hashtable keyed by codepoint, where presence indicates that a character
21 * has a decomposition mapping. This makes it non-preferred for group header
29 * Important tertiary weights from UTS #10 section 7.2
31 const NORMAL_UPPERCASE
= 0x08;
32 const NORMAL_HIRAGANA
= 0X0E;
34 public function __construct() {
35 parent
::__construct();
36 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
37 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
39 $this->addOption( 'debug-output', 'Filename for sending debug output to',
43 public function execute() {
44 $this->dataDir
= $this->getOption( 'data-dir', '.' );
45 if ( !file_exists( "{$this->dataDir}/allkeys.txt" ) ) {
46 $this->error( "Unable to find allkeys.txt. Please download it from " .
47 "http://www.unicode.org/Public/UCA/latest/allkeys.txt and specify " .
48 "its location with --data-dir=<DIR>" );
51 if ( !file_exists( "{$this->dataDir}/ucd.all.grouped.xml" ) ) {
52 $this->error( "Unable to find ucd.all.grouped.xml. Please download it " .
53 "from http://www.unicode.org/Public/6.0.0/ucdxml/ucd.all.grouped.zip " .
54 "and specify its location with --data-dir=<DIR>" );
57 $debugOutFileName = $this->getOption( 'debug-output' );
58 if ( $debugOutFileName ) {
59 $this->debugOutFile
= fopen( $debugOutFileName, 'w' );
60 if ( !$this->debugOutFile
) {
61 $this->error( "Unable to open debug output file for writing" );
66 $this->generateFirstChars();
70 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
71 $uxr->readChars( array( $this, 'charCallback' ) );
74 function charCallback( $data ) {
75 // Skip non-printable characters,
76 // but do not skip a normal space (U+0020) since
77 // people like to use that as a fake no header symbol.
78 $category = substr( $data['gc'], 0, 1 );
79 if ( strpos( 'LNPS', $category ) === false
80 && $data['cp'] !== '0020' ) {
83 $cp = hexdec( $data['cp'] );
85 // Skip the CJK ideograph blocks, as an optimisation measure.
86 // UCA doesn't sort them properly anyway, without tailoring.
87 if ( IcuCollation
::isCjk( $cp ) ) {
91 // Skip the composed Hangul syllables, we will use the bare Jamo
93 if ( $data['block'] == 'Hangul Syllables' ) {
97 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
98 if ( $data['UIdeo'] === 'Y' ) {
99 if ( $data['block'] == 'CJK Unified Ideographs'
100 ||
$data['block'] == 'CJK Compatibility Ideographs' )
109 $a = $base +
( $cp >> 15 );
110 $b = ( $cp & 0x7fff ) |
0x8000;
112 $this->weights
[$cp] = sprintf( ".%04X.%04X", $a, $b );
114 if ( $data['dm'] !== '#' ) {
115 $this->mappedChars
[$cp] = true;
118 if ( $cp %
4096 == 0 ) {
119 print "{$data['cp']}\n";
123 function generateFirstChars() {
124 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
126 $this->error( "Unable to open allkeys.txt" );
130 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
132 $this->error( "Unable to open output file first-letters-root.ser" );
136 $goodTertiaryChars = array();
138 // For each character with an entry in allkeys.txt, overwrite the implicit
139 // entry in $this->weights that came from the UCD.
140 // Also gather a list of tertiary weights, for use in selecting the group header
141 while ( false !== ( $line = fgets( $file ) ) ) {
142 // We're only interested in single-character weights, pick them out with a regex
143 $line = trim( $line );
144 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
148 $cp = hexdec( $m[1] );
149 $allWeights = trim( $m[2] );
153 if ( !isset( $this->weights
[$cp] ) ) {
154 // Non-printable, ignore
157 foreach ( StringUtils
::explode( '[', $allWeights ) as $weightStr ) {
158 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
159 if ( !empty( $m[1] ) ) {
160 if ( $m[1][0] !== '0000' ) {
161 $primary .= '.' . $m[1][0];
163 if ( $m[1][2] !== '0000' ) {
164 $tertiary .= '.' . $m[1][2];
168 $this->weights
[$cp] = $primary;
169 if ( $tertiary === '.0008'
170 ||
$tertiary === '.000E' )
172 $goodTertiaryChars[$cp] = true;
177 // Identify groups of characters with the same primary weight
178 $this->groups
= array();
179 asort( $this->weights
, SORT_STRING
);
180 $prevWeight = reset( $this->weights
);
182 foreach ( $this->weights
as $cp => $weight ) {
183 if ( $weight !== $prevWeight ) {
184 $this->groups
[$prevWeight] = $group;
185 $prevWeight = $weight;
186 if ( isset( $this->groups
[$weight] ) ) {
187 $group = $this->groups
[$weight];
195 $this->groups
[$prevWeight] = $group;
198 // If one character has a given primary weight sequence, and a second
199 // character has a longer primary weight sequence with an initial
200 // portion equal to the first character, then remove the second
201 // character. This avoids having characters like U+A732 (double A)
202 // polluting the basic latin sort area.
204 foreach ( $this->groups
as $weight => $group ) {
205 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
206 if ( isset( $this->groups
[$m[1]] ) ) {
207 unset( $this->groups
[$weight] );
212 ksort( $this->groups
, SORT_STRING
);
214 // Identify the header character in each group
215 $headerChars = array();
217 $tertiaryCollator = new Collator( 'root' );
218 $primaryCollator = new Collator( 'root' );
219 $primaryCollator->setStrength( Collator
::PRIMARY
);
221 foreach ( $this->groups
as $weight => $group ) {
222 $uncomposedChars = array();
223 $goodChars = array();
224 foreach ( $group as $cp ) {
225 if ( isset( $goodTertiaryChars[$cp] ) ) {
228 if ( !isset( $this->mappedChars
[$cp] ) ) {
229 $uncomposedChars[] = $cp;
232 $x = array_intersect( $goodChars, $uncomposedChars );
234 $x = $uncomposedChars;
240 // Use ICU to pick the lowest sorting character in the selection
241 $tertiaryCollator->sort( $x );
244 $char = codepointToUtf8( $cp );
245 $headerChars[] = $char;
246 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
249 printf( "Out of order: U+%05X > U+%05X\n",
250 utf8ToCodepoint( $prevChar ),
251 utf8ToCodepoint( $char ) );
256 if ( $this->debugOutFile
) {
257 fwrite( $this->debugOutFile
, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
258 implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
262 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
264 fwrite( $outFile, serialize( $headerChars ) );
273 var $blocks = array();
276 function __construct( $fileName ) {
277 $this->fileName
= $fileName;
280 public function readChars( $callback ) {
282 $this->currentBlock
= reset( $this->blocks
);
283 $xml = $this->open();
284 $this->callback
= $callback;
286 while ( $xml->name
!== 'repertoire' && $xml->next() );
288 while ( $xml->read() ) {
289 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
290 if ( $xml->name
=== 'group' ) {
291 $this->groupAttrs
= $this->readAttributes();
292 } elseif ( $xml->name
=== 'char' ) {
295 } elseif ( $xml->nodeType
=== XMLReader
::END_ELEMENT
) {
296 if ( $xml->name
=== 'group' ) {
297 $this->groupAttrs
= array();
304 protected function open() {
305 $this->xml
= new XMLReader
;
306 $this->xml
->open( $this->fileName
);
308 throw new MWException( __METHOD__
.": unable to open {$this->fileName}" );
310 while ( $this->xml
->name
!== 'ucd' && $this->xml
->read() );
316 * Read the attributes of the current element node and return them
320 protected function readAttributes() {
322 while ( $this->xml
->moveToNextAttribute() ) {
323 $attrs[$this->xml
->name
] = $this->xml
->value
;
328 protected function handleChar() {
329 $attrs = $this->readAttributes() +
$this->groupAttrs
;
330 if ( isset( $attrs['cp'] ) ) {
331 $first = $last = hexdec( $attrs['cp'] );
333 $first = hexdec( $attrs['first-cp'] );
334 $last = hexdec( $attrs['last-cp'] );
335 unset( $attrs['first-cp'] );
336 unset( $attrs['last-cp'] );
339 for ( $cp = $first; $cp <= $last; $cp++
) {
340 $hexCp = sprintf( "%04X", $cp );
341 foreach ( array( 'na', 'na1' ) as $nameProp ) {
342 if ( isset( $attrs[$nameProp] ) ) {
343 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
347 while ( $this->currentBlock
) {
348 if ( $cp < $this->currentBlock
[0] ) {
350 } elseif ( $cp <= $this->currentBlock
[1] ) {
351 $attrs['block'] = key( $this->blocks
);
354 $this->currentBlock
= next( $this->blocks
);
358 $attrs['cp'] = $hexCp;
359 call_user_func( $this->callback
, $attrs );
363 public function getBlocks() {
364 if ( $this->blocks
) {
365 return $this->blocks
;
368 $xml = $this->open();
369 while ( $xml->name
!== 'blocks' && $xml->read() );
371 while ( $xml->read() ) {
372 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
373 if ( $xml->name
=== 'block' ) {
374 $attrs = $this->readAttributes();
375 $first = hexdec( $attrs['first-cp'] );
376 $last = hexdec( $attrs['last-cp'] );
377 $this->blocks
[$attrs['name']] = array( $first, $last );
382 return $this->blocks
;
387 $maintClass = 'GenerateCollationData';
388 require_once( RUN_MAINTENANCE_IF_MAIN
);