3 require_once( dirname( __FILE__ ) .'/../Maintenance.php' );
6 * Generate first letter data files for Collation.php
8 class GenerateCollationData extends Maintenance {
9 /** The directory with source data files in it */
12 /** The primary weights, indexed by codepoint */
16 * A hashtable keyed by codepoint, where presence indicates that a character
17 * has a decomposition mapping. This makes it non-preferred for group header
25 * Important tertiary weights from UTS #10 section 7.2
27 const NORMAL_UPPERCASE = 0x08;
28 const NORMAL_HIRAGANA = 0X0E;
30 public function __construct() {
31 parent::__construct();
32 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
33 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
35 $this->addOption( 'debug-output', 'Filename for sending debug output to',
39 public function execute() {
40 $this->dataDir = $this->getOption( 'data-dir', '.' );
41 if ( !file_exists( "{$this->dataDir}/allkeys.txt" ) ) {
42 $this->error( "Unable to find allkeys.txt. Please download it from " .
43 "http://www.unicode.org/Public/UCA/latest/allkeys.txt and specify " .
44 "its location with --data-dir=<DIR>" );
47 if ( !file_exists( "{$this->dataDir}/ucd.all.grouped.xml" ) ) {
48 $this->error( "Unable to find ucd.all.grouped.xml. Please download it " .
49 "from http://www.unicode.org/Public/6.0.0/ucdxml/ucd.all.grouped.zip " .
50 "and specify its location with --data-dir=<DIR>" );
53 $debugOutFileName = $this->getOption( 'debug-output' );
54 if ( $debugOutFileName ) {
55 $this->debugOutFile = fopen( $debugOutFileName, 'w' );
56 if ( !$this->debugOutFile ) {
57 $this->error( "Unable to open debug output file for writing" );
62 $this->generateFirstChars();
66 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
67 $uxr->readChars( array( $this, 'charCallback' ) );
70 function charCallback( $data ) {
71 // Skip non-printable characters
72 $category = substr( $data['gc'], 0, 1 );
73 if ( strpos( 'LNPS', $category ) === false ) {
76 $cp = hexdec( $data['cp'] );
78 // Skip the CJK ideograph blocks, as an optimisation measure.
79 // UCA doesn't sort them properly anyway, without tailoring.
80 if ( IcuCollation::isCjk( $cp ) ) {
84 // Skip the composed Hangul syllables, we will use the bare Jamo
86 if ( $data['block'] == 'Hangul Syllables' ) {
90 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
91 if ( $data['UIdeo'] === 'Y' ) {
92 if ( $data['block'] == 'CJK Unified Ideographs'
93 || $data['block'] == 'CJK Compatibility Ideographs' )
102 $a = $base + ( $cp >> 15 );
103 $b = ( $cp & 0x7fff ) | 0x8000;
105 $this->weights[$cp] = sprintf( ".%04X.%04X", $a, $b );
107 if ( $data['dm'] !== '#' ) {
108 $this->mappedChars[$cp] = true;
111 if ( $cp % 4096 == 0 ) {
112 print "{$data['cp']}\n";
116 function generateFirstChars() {
117 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
119 $this->error( "Unable to open allkeys.txt" );
123 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
125 $this->error( "Unable to open output file first-letters-root.ser" );
129 $goodTertiaryChars = array();
131 // For each character with an entry in allkeys.txt, overwrite the implicit
132 // entry in $this->weights that came from the UCD.
133 // Also gather a list of tertiary weights, for use in selecting the group header
134 while ( false !== ( $line = fgets( $file ) ) ) {
135 // We're only interested in single-character weights, pick them out with a regex
136 $line = trim( $line );
137 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
141 $cp = hexdec( $m[1] );
142 $allWeights = trim( $m[2] );
146 if ( !isset( $this->weights[$cp] ) ) {
147 // Non-printable, ignore
150 foreach ( StringUtils::explode( '[', $allWeights ) as $weightStr ) {
151 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
152 if ( !empty( $m[1] ) ) {
153 if ( $m[1][0] !== '0000' ) {
154 $primary .= '.' . $m[1][0];
156 if ( $m[1][2] !== '0000' ) {
157 $tertiary .= '.' . $m[1][2];
161 $this->weights[$cp] = $primary;
162 if ( $tertiary === '.0008'
163 || $tertiary === '.000E' )
165 $goodTertiaryChars[$cp] = true;
170 // Identify groups of characters with the same primary weight
171 $this->groups = array();
172 asort( $this->weights, SORT_STRING );
173 $prevWeight = reset( $this->weights );
175 foreach ( $this->weights as $cp => $weight ) {
176 if ( $weight !== $prevWeight ) {
177 $this->groups[$prevWeight] = $group;
178 $prevWeight = $weight;
179 if ( isset( $this->groups[$weight] ) ) {
180 $group = $this->groups[$weight];
188 $this->groups[$prevWeight] = $group;
191 // If one character has a given primary weight sequence, and a second
192 // character has a longer primary weight sequence with an initial
193 // portion equal to the first character, then remove the second
194 // character. This avoids having characters like U+A732 (double A)
195 // polluting the basic latin sort area.
196 $prevWeights = array();
197 foreach ( $this->groups as $weight => $group ) {
198 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
199 if ( isset( $this->groups[$m[1]] ) ) {
200 unset( $this->groups[$weight] );
205 ksort( $this->groups, SORT_STRING );
207 // Identify the header character in each group
208 $headerChars = array();
210 $tertiaryCollator = new Collator( 'root' );
211 $primaryCollator = new Collator( 'root' );
212 $primaryCollator->setStrength( Collator::PRIMARY );
214 foreach ( $this->groups as $weight => $group ) {
215 $uncomposedChars = array();
216 $goodChars = array();
217 foreach ( $group as $cp ) {
218 if ( isset( $goodTertiaryChars[$cp] ) ) {
221 if ( !isset( $this->mappedChars[$cp] ) ) {
222 $uncomposedChars[] = $cp;
225 $x = array_intersect( $goodChars, $uncomposedChars );
227 $x = $uncomposedChars;
233 // Use ICU to pick the lowest sorting character in the selection
234 $tertiaryCollator->sort( $x );
237 $char = codepointToUtf8( $cp );
238 $headerChars[] = $char;
239 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
242 printf( "Out of order: U+%05X > U+%05X\n",
243 utf8ToCodepoint( $prevChar ),
244 utf8ToCodepoint( $char ) );
249 if ( $this->debugOutFile ) {
250 fwrite( $this->debugOutFile, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
251 implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
255 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
257 fwrite( $outFile, serialize( $headerChars ) );
266 var $blocks = array();
269 function __construct( $fileName ) {
270 $this->fileName = $fileName;
273 public function readChars( $callback ) {
275 $this->currentBlock = reset( $this->blocks );
276 $xml = $this->open();
277 $this->callback = $callback;
279 while ( $xml->name !== 'repertoire' && $xml->next() );
281 while ( $xml->read() ) {
282 if ( $xml->nodeType == XMLReader::ELEMENT ) {
283 if ( $xml->name === 'group' ) {
284 $this->groupAttrs = $this->readAttributes();
285 } elseif ( $xml->name === 'char' ) {
288 } elseif ( $xml->nodeType === XMLReader::END_ELEMENT ) {
289 if ( $xml->name === 'group' ) {
290 $this->groupAttrs = array();
297 protected function open() {
298 $this->xml = new XMLReader;
299 $this->xml->open( $this->fileName );
301 throw new MWException( __METHOD__.": unable to open {$this->fileName}" );
303 while ( $this->xml->name !== 'ucd' && $this->xml->read() );
309 * Read the attributes of the current element node and return them
312 protected function readAttributes() {
314 while ( $this->xml->moveToNextAttribute() ) {
315 $attrs[$this->xml->name] = $this->xml->value;
320 protected function handleChar() {
321 $attrs = $this->readAttributes() + $this->groupAttrs;
322 if ( isset( $attrs['cp'] ) ) {
323 $first = $last = hexdec( $attrs['cp'] );
325 $first = hexdec( $attrs['first-cp'] );
326 $last = hexdec( $attrs['last-cp'] );
327 unset( $attrs['first-cp'] );
328 unset( $attrs['last-cp'] );
331 for ( $cp = $first; $cp <= $last; $cp++ ) {
332 $hexCp = sprintf( "%04X", $cp );
333 foreach ( array( 'na', 'na1' ) as $nameProp ) {
334 if ( isset( $attrs[$nameProp] ) ) {
335 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
339 while ( $this->currentBlock ) {
340 if ( $cp < $this->currentBlock[0] ) {
342 } elseif ( $cp <= $this->currentBlock[1] ) {
343 $attrs['block'] = key( $this->blocks );
346 $this->currentBlock = next( $this->blocks );
350 $attrs['cp'] = $hexCp;
351 call_user_func( $this->callback, $attrs );
355 public function getBlocks() {
356 if ( $this->blocks ) {
357 return $this->blocks;
360 $xml = $this->open();
361 while ( $xml->name !== 'blocks' && $xml->read() );
363 while ( $xml->read() ) {
364 if ( $xml->nodeType == XMLReader::ELEMENT ) {
365 if ( $xml->name === 'block' ) {
366 $attrs = $this->readAttributes();
367 $first = hexdec( $attrs['first-cp'] );
368 $last = hexdec( $attrs['last-cp'] );
369 $this->blocks[$attrs['name']] = array( $first, $last );
374 return $this->blocks;
379 $maintClass = 'GenerateCollationData';
380 require_once( DO_MAINTENANCE );