3 * Maintenance script to generate first letter data files for Collation.php.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @ingroup Maintenance
24 require_once( dirname( __FILE__
) .'/../Maintenance.php' );
27 * Generate first letter data files for Collation.php
29 class GenerateCollationData
extends Maintenance
{
30 /** The directory with source data files in it */
33 /** The primary weights, indexed by codepoint */
37 * A hashtable keyed by codepoint, where presence indicates that a character
38 * has a decomposition mapping. This makes it non-preferred for group header
46 * Important tertiary weights from UTS #10 section 7.2
48 const NORMAL_UPPERCASE
= 0x08;
49 const NORMAL_HIRAGANA
= 0X0E;
51 public function __construct() {
52 parent
::__construct();
53 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
54 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
56 $this->addOption( 'debug-output', 'Filename for sending debug output to',
60 public function execute() {
61 $this->dataDir
= $this->getOption( 'data-dir', '.' );
62 if ( !file_exists( "{$this->dataDir}/allkeys.txt" ) ) {
63 $this->error( "Unable to find allkeys.txt. Please download it from " .
64 "http://www.unicode.org/Public/UCA/latest/allkeys.txt and specify " .
65 "its location with --data-dir=<DIR>" );
68 if ( !file_exists( "{$this->dataDir}/ucd.all.grouped.xml" ) ) {
69 $this->error( "Unable to find ucd.all.grouped.xml. Please download it " .
70 "from http://www.unicode.org/Public/6.0.0/ucdxml/ucd.all.grouped.zip " .
71 "and specify its location with --data-dir=<DIR>" );
74 $debugOutFileName = $this->getOption( 'debug-output' );
75 if ( $debugOutFileName ) {
76 $this->debugOutFile
= fopen( $debugOutFileName, 'w' );
77 if ( !$this->debugOutFile
) {
78 $this->error( "Unable to open debug output file for writing" );
83 $this->generateFirstChars();
87 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
88 $uxr->readChars( array( $this, 'charCallback' ) );
91 function charCallback( $data ) {
92 // Skip non-printable characters,
93 // but do not skip a normal space (U+0020) since
94 // people like to use that as a fake no header symbol.
95 $category = substr( $data['gc'], 0, 1 );
96 if ( strpos( 'LNPS', $category ) === false
97 && $data['cp'] !== '0020' ) {
100 $cp = hexdec( $data['cp'] );
102 // Skip the CJK ideograph blocks, as an optimisation measure.
103 // UCA doesn't sort them properly anyway, without tailoring.
104 if ( IcuCollation
::isCjk( $cp ) ) {
108 // Skip the composed Hangul syllables, we will use the bare Jamo
110 if ( $data['block'] == 'Hangul Syllables' ) {
114 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
115 if ( $data['UIdeo'] === 'Y' ) {
116 if ( $data['block'] == 'CJK Unified Ideographs'
117 ||
$data['block'] == 'CJK Compatibility Ideographs' )
126 $a = $base +
( $cp >> 15 );
127 $b = ( $cp & 0x7fff ) |
0x8000;
129 $this->weights
[$cp] = sprintf( ".%04X.%04X", $a, $b );
131 if ( $data['dm'] !== '#' ) {
132 $this->mappedChars
[$cp] = true;
135 if ( $cp %
4096 == 0 ) {
136 print "{$data['cp']}\n";
140 function generateFirstChars() {
141 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
143 $this->error( "Unable to open allkeys.txt" );
147 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
149 $this->error( "Unable to open output file first-letters-root.ser" );
153 $goodTertiaryChars = array();
155 // For each character with an entry in allkeys.txt, overwrite the implicit
156 // entry in $this->weights that came from the UCD.
157 // Also gather a list of tertiary weights, for use in selecting the group header
158 while ( false !== ( $line = fgets( $file ) ) ) {
159 // We're only interested in single-character weights, pick them out with a regex
160 $line = trim( $line );
161 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
165 $cp = hexdec( $m[1] );
166 $allWeights = trim( $m[2] );
170 if ( !isset( $this->weights
[$cp] ) ) {
171 // Non-printable, ignore
174 foreach ( StringUtils
::explode( '[', $allWeights ) as $weightStr ) {
175 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
176 if ( !empty( $m[1] ) ) {
177 if ( $m[1][0] !== '0000' ) {
178 $primary .= '.' . $m[1][0];
180 if ( $m[1][2] !== '0000' ) {
181 $tertiary .= '.' . $m[1][2];
185 $this->weights
[$cp] = $primary;
186 if ( $tertiary === '.0008'
187 ||
$tertiary === '.000E' )
189 $goodTertiaryChars[$cp] = true;
194 // Identify groups of characters with the same primary weight
195 $this->groups
= array();
196 asort( $this->weights
, SORT_STRING
);
197 $prevWeight = reset( $this->weights
);
199 foreach ( $this->weights
as $cp => $weight ) {
200 if ( $weight !== $prevWeight ) {
201 $this->groups
[$prevWeight] = $group;
202 $prevWeight = $weight;
203 if ( isset( $this->groups
[$weight] ) ) {
204 $group = $this->groups
[$weight];
212 $this->groups
[$prevWeight] = $group;
215 // If one character has a given primary weight sequence, and a second
216 // character has a longer primary weight sequence with an initial
217 // portion equal to the first character, then remove the second
218 // character. This avoids having characters like U+A732 (double A)
219 // polluting the basic latin sort area.
221 foreach ( $this->groups
as $weight => $group ) {
222 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
223 if ( isset( $this->groups
[$m[1]] ) ) {
224 unset( $this->groups
[$weight] );
229 ksort( $this->groups
, SORT_STRING
);
231 // Identify the header character in each group
232 $headerChars = array();
234 $tertiaryCollator = new Collator( 'root' );
235 $primaryCollator = new Collator( 'root' );
236 $primaryCollator->setStrength( Collator
::PRIMARY
);
238 foreach ( $this->groups
as $weight => $group ) {
239 $uncomposedChars = array();
240 $goodChars = array();
241 foreach ( $group as $cp ) {
242 if ( isset( $goodTertiaryChars[$cp] ) ) {
245 if ( !isset( $this->mappedChars
[$cp] ) ) {
246 $uncomposedChars[] = $cp;
249 $x = array_intersect( $goodChars, $uncomposedChars );
251 $x = $uncomposedChars;
257 // Use ICU to pick the lowest sorting character in the selection
258 $tertiaryCollator->sort( $x );
261 $char = codepointToUtf8( $cp );
262 $headerChars[] = $char;
263 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
266 printf( "Out of order: U+%05X > U+%05X\n",
267 utf8ToCodepoint( $prevChar ),
268 utf8ToCodepoint( $char ) );
273 if ( $this->debugOutFile
) {
274 fwrite( $this->debugOutFile
, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
275 implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
279 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
281 fwrite( $outFile, serialize( $headerChars ) );
290 var $blocks = array();
293 function __construct( $fileName ) {
294 $this->fileName
= $fileName;
297 public function readChars( $callback ) {
299 $this->currentBlock
= reset( $this->blocks
);
300 $xml = $this->open();
301 $this->callback
= $callback;
303 while ( $xml->name
!== 'repertoire' && $xml->next() );
305 while ( $xml->read() ) {
306 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
307 if ( $xml->name
=== 'group' ) {
308 $this->groupAttrs
= $this->readAttributes();
309 } elseif ( $xml->name
=== 'char' ) {
312 } elseif ( $xml->nodeType
=== XMLReader
::END_ELEMENT
) {
313 if ( $xml->name
=== 'group' ) {
314 $this->groupAttrs
= array();
321 protected function open() {
322 $this->xml
= new XMLReader
;
323 $this->xml
->open( $this->fileName
);
325 throw new MWException( __METHOD__
.": unable to open {$this->fileName}" );
327 while ( $this->xml
->name
!== 'ucd' && $this->xml
->read() );
333 * Read the attributes of the current element node and return them
337 protected function readAttributes() {
339 while ( $this->xml
->moveToNextAttribute() ) {
340 $attrs[$this->xml
->name
] = $this->xml
->value
;
345 protected function handleChar() {
346 $attrs = $this->readAttributes() +
$this->groupAttrs
;
347 if ( isset( $attrs['cp'] ) ) {
348 $first = $last = hexdec( $attrs['cp'] );
350 $first = hexdec( $attrs['first-cp'] );
351 $last = hexdec( $attrs['last-cp'] );
352 unset( $attrs['first-cp'] );
353 unset( $attrs['last-cp'] );
356 for ( $cp = $first; $cp <= $last; $cp++
) {
357 $hexCp = sprintf( "%04X", $cp );
358 foreach ( array( 'na', 'na1' ) as $nameProp ) {
359 if ( isset( $attrs[$nameProp] ) ) {
360 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
364 while ( $this->currentBlock
) {
365 if ( $cp < $this->currentBlock
[0] ) {
367 } elseif ( $cp <= $this->currentBlock
[1] ) {
368 $attrs['block'] = key( $this->blocks
);
371 $this->currentBlock
= next( $this->blocks
);
375 $attrs['cp'] = $hexCp;
376 call_user_func( $this->callback
, $attrs );
380 public function getBlocks() {
381 if ( $this->blocks
) {
382 return $this->blocks
;
385 $xml = $this->open();
386 while ( $xml->name
!== 'blocks' && $xml->read() );
388 while ( $xml->read() ) {
389 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
390 if ( $xml->name
=== 'block' ) {
391 $attrs = $this->readAttributes();
392 $first = hexdec( $attrs['first-cp'] );
393 $last = hexdec( $attrs['last-cp'] );
394 $this->blocks
[$attrs['name']] = array( $first, $last );
399 return $this->blocks
;
404 $maintClass = 'GenerateCollationData';
405 require_once( RUN_MAINTENANCE_IF_MAIN
);