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
21 * @ingroup MaintenanceLanguage
24 require_once( __DIR__
.'/../Maintenance.php' );
27 * Generate first letter data files for Collation.php
29 * @ingroup MaintenanceLanguage
31 class GenerateCollationData
extends Maintenance
{
32 /** The directory with source data files in it */
35 /** The primary weights, indexed by codepoint */
39 * A hashtable keyed by codepoint, where presence indicates that a character
40 * has a decomposition mapping. This makes it non-preferred for group header
48 * Important tertiary weights from UTS #10 section 7.2
50 const NORMAL_UPPERCASE
= 0x08;
51 const NORMAL_HIRAGANA
= 0X0E;
53 public function __construct() {
54 parent
::__construct();
55 $this->addOption( 'data-dir', 'A directory on the local filesystem ' .
56 'containing allkeys.txt and ucd.all.grouped.xml from unicode.org',
58 $this->addOption( 'debug-output', 'Filename for sending debug output to',
62 public function execute() {
63 $this->dataDir
= $this->getOption( 'data-dir', '.' );
64 if ( !file_exists( "{$this->dataDir}/allkeys.txt" ) ) {
65 $this->error( "Unable to find allkeys.txt. Please download it from " .
66 "http://www.unicode.org/Public/UCA/latest/allkeys.txt and specify " .
67 "its location with --data-dir=<DIR>" );
70 if ( !file_exists( "{$this->dataDir}/ucd.all.grouped.xml" ) ) {
71 $this->error( "Unable to find ucd.all.grouped.xml. Please download it " .
72 "from http://www.unicode.org/Public/6.0.0/ucdxml/ucd.all.grouped.zip " .
73 "and specify its location with --data-dir=<DIR>" );
76 $debugOutFileName = $this->getOption( 'debug-output' );
77 if ( $debugOutFileName ) {
78 $this->debugOutFile
= fopen( $debugOutFileName, 'w' );
79 if ( !$this->debugOutFile
) {
80 $this->error( "Unable to open debug output file for writing" );
85 $this->generateFirstChars();
89 $uxr = new UcdXmlReader( "{$this->dataDir}/ucd.all.grouped.xml" );
90 $uxr->readChars( array( $this, 'charCallback' ) );
93 function charCallback( $data ) {
94 // Skip non-printable characters,
95 // but do not skip a normal space (U+0020) since
96 // people like to use that as a fake no header symbol.
97 $category = substr( $data['gc'], 0, 1 );
98 if ( strpos( 'LNPS', $category ) === false
99 && $data['cp'] !== '0020' ) {
102 $cp = hexdec( $data['cp'] );
104 // Skip the CJK ideograph blocks, as an optimisation measure.
105 // UCA doesn't sort them properly anyway, without tailoring.
106 if ( IcuCollation
::isCjk( $cp ) ) {
110 // Skip the composed Hangul syllables, we will use the bare Jamo
112 if ( $data['block'] == 'Hangul Syllables' ) {
116 // Calculate implicit weight per UTS #10 v6.0.0, sec 7.1.3
117 if ( $data['UIdeo'] === 'Y' ) {
118 if ( $data['block'] == 'CJK Unified Ideographs'
119 ||
$data['block'] == 'CJK Compatibility Ideographs' )
128 $a = $base +
( $cp >> 15 );
129 $b = ( $cp & 0x7fff ) |
0x8000;
131 $this->weights
[$cp] = sprintf( ".%04X.%04X", $a, $b );
133 if ( $data['dm'] !== '#' ) {
134 $this->mappedChars
[$cp] = true;
137 if ( $cp %
4096 == 0 ) {
138 print "{$data['cp']}\n";
142 function generateFirstChars() {
143 $file = fopen( "{$this->dataDir}/allkeys.txt", 'r' );
145 $this->error( "Unable to open allkeys.txt" );
149 $outFile = fopen( "$IP/serialized/first-letters-root.ser", 'w' );
151 $this->error( "Unable to open output file first-letters-root.ser" );
155 $goodTertiaryChars = array();
157 // For each character with an entry in allkeys.txt, overwrite the implicit
158 // entry in $this->weights that came from the UCD.
159 // Also gather a list of tertiary weights, for use in selecting the group header
160 while ( false !== ( $line = fgets( $file ) ) ) {
161 // We're only interested in single-character weights, pick them out with a regex
162 $line = trim( $line );
163 if ( !preg_match( '/^([0-9A-F]+)\s*;\s*([^#]*)/', $line, $m ) ) {
167 $cp = hexdec( $m[1] );
168 $allWeights = trim( $m[2] );
172 if ( !isset( $this->weights
[$cp] ) ) {
173 // Non-printable, ignore
176 foreach ( StringUtils
::explode( '[', $allWeights ) as $weightStr ) {
177 preg_match_all( '/[*.]([0-9A-F]+)/', $weightStr, $m );
178 if ( !empty( $m[1] ) ) {
179 if ( $m[1][0] !== '0000' ) {
180 $primary .= '.' . $m[1][0];
182 if ( $m[1][2] !== '0000' ) {
183 $tertiary .= '.' . $m[1][2];
187 $this->weights
[$cp] = $primary;
188 if ( $tertiary === '.0008'
189 ||
$tertiary === '.000E' )
191 $goodTertiaryChars[$cp] = true;
196 // Identify groups of characters with the same primary weight
197 $this->groups
= array();
198 asort( $this->weights
, SORT_STRING
);
199 $prevWeight = reset( $this->weights
);
201 foreach ( $this->weights
as $cp => $weight ) {
202 if ( $weight !== $prevWeight ) {
203 $this->groups
[$prevWeight] = $group;
204 $prevWeight = $weight;
205 if ( isset( $this->groups
[$weight] ) ) {
206 $group = $this->groups
[$weight];
214 $this->groups
[$prevWeight] = $group;
217 // If one character has a given primary weight sequence, and a second
218 // character has a longer primary weight sequence with an initial
219 // portion equal to the first character, then remove the second
220 // character. This avoids having characters like U+A732 (double A)
221 // polluting the basic latin sort area.
223 foreach ( $this->groups
as $weight => $group ) {
224 if ( preg_match( '/(\.[0-9A-F]*)\./', $weight, $m ) ) {
225 if ( isset( $this->groups
[$m[1]] ) ) {
226 unset( $this->groups
[$weight] );
231 ksort( $this->groups
, SORT_STRING
);
233 // Identify the header character in each group
234 $headerChars = array();
236 $tertiaryCollator = new Collator( 'root' );
237 $primaryCollator = new Collator( 'root' );
238 $primaryCollator->setStrength( Collator
::PRIMARY
);
240 foreach ( $this->groups
as $weight => $group ) {
241 $uncomposedChars = array();
242 $goodChars = array();
243 foreach ( $group as $cp ) {
244 if ( isset( $goodTertiaryChars[$cp] ) ) {
247 if ( !isset( $this->mappedChars
[$cp] ) ) {
248 $uncomposedChars[] = $cp;
251 $x = array_intersect( $goodChars, $uncomposedChars );
253 $x = $uncomposedChars;
259 // Use ICU to pick the lowest sorting character in the selection
260 $tertiaryCollator->sort( $x );
263 $char = codepointToUtf8( $cp );
264 $headerChars[] = $char;
265 if ( $primaryCollator->compare( $char, $prevChar ) <= 0 ) {
268 printf( "Out of order: U+%05X > U+%05X\n",
269 utf8ToCodepoint( $prevChar ),
270 utf8ToCodepoint( $char ) );
275 if ( $this->debugOutFile
) {
276 fwrite( $this->debugOutFile
, sprintf( "%05X %s %s (%s)\n", $cp, $weight, $char,
277 implode( ' ', array_map( 'codepointToUtf8', $group ) ) ) );
281 print "Out of order: $numOutOfOrder / " . count( $headerChars ) . "\n";
283 fwrite( $outFile, serialize( $headerChars ) );
292 public $blocks = array();
293 public $currentBlock;
295 function __construct( $fileName ) {
296 $this->fileName
= $fileName;
299 public function readChars( $callback ) {
301 $this->currentBlock
= reset( $this->blocks
);
302 $xml = $this->open();
303 $this->callback
= $callback;
305 while ( $xml->name
!== 'repertoire' && $xml->next() );
307 while ( $xml->read() ) {
308 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
309 if ( $xml->name
=== 'group' ) {
310 $this->groupAttrs
= $this->readAttributes();
311 } elseif ( $xml->name
=== 'char' ) {
314 } elseif ( $xml->nodeType
=== XMLReader
::END_ELEMENT
) {
315 if ( $xml->name
=== 'group' ) {
316 $this->groupAttrs
= array();
323 protected function open() {
324 $this->xml
= new XMLReader
;
325 $this->xml
->open( $this->fileName
);
327 throw new MWException( __METHOD__
.": unable to open {$this->fileName}" );
329 while ( $this->xml
->name
!== 'ucd' && $this->xml
->read() );
335 * Read the attributes of the current element node and return them
339 protected function readAttributes() {
341 while ( $this->xml
->moveToNextAttribute() ) {
342 $attrs[$this->xml
->name
] = $this->xml
->value
;
347 protected function handleChar() {
348 $attrs = $this->readAttributes() +
$this->groupAttrs
;
349 if ( isset( $attrs['cp'] ) ) {
350 $first = $last = hexdec( $attrs['cp'] );
352 $first = hexdec( $attrs['first-cp'] );
353 $last = hexdec( $attrs['last-cp'] );
354 unset( $attrs['first-cp'] );
355 unset( $attrs['last-cp'] );
358 for ( $cp = $first; $cp <= $last; $cp++
) {
359 $hexCp = sprintf( "%04X", $cp );
360 foreach ( array( 'na', 'na1' ) as $nameProp ) {
361 if ( isset( $attrs[$nameProp] ) ) {
362 $attrs[$nameProp] = str_replace( '#', $hexCp, $attrs[$nameProp] );
366 while ( $this->currentBlock
) {
367 if ( $cp < $this->currentBlock
[0] ) {
369 } elseif ( $cp <= $this->currentBlock
[1] ) {
370 $attrs['block'] = key( $this->blocks
);
373 $this->currentBlock
= next( $this->blocks
);
377 $attrs['cp'] = $hexCp;
378 call_user_func( $this->callback
, $attrs );
382 public function getBlocks() {
383 if ( $this->blocks
) {
384 return $this->blocks
;
387 $xml = $this->open();
388 while ( $xml->name
!== 'blocks' && $xml->read() );
390 while ( $xml->read() ) {
391 if ( $xml->nodeType
== XMLReader
::ELEMENT
) {
392 if ( $xml->name
=== 'block' ) {
393 $attrs = $this->readAttributes();
394 $first = hexdec( $attrs['first-cp'] );
395 $last = hexdec( $attrs['last-cp'] );
396 $this->blocks
[$attrs['name']] = array( $first, $last );
401 return $this->blocks
;
406 $maintClass = 'GenerateCollationData';
407 require_once( RUN_MAINTENANCE_IF_MAIN
);