1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 *******************************************************************************
6 * Copyright (C) 2011-2014 International Business Machines
7 * Corporation and others. All Rights Reserved.
9 *******************************************************************************
15 #include "unicode/utypes.h"
16 #include "unicode/uobject.h"
17 #include "unicode/locid.h"
18 #include "unicode/unistr.h"
20 #if !UCONFIG_NO_COLLATION
24 * \brief C++ API: Index Characters
30 * Constants for Alphabetic Index Label Types.
31 * The form of these enum constants anticipates having a plain C API
32 * for Alphabetic Indexes that will also use them.
35 typedef enum UAlphabeticIndexLabelType
{
37 * Normal Label, typically the starting letter of the names
38 * in the bucket with this label.
41 U_ALPHAINDEX_NORMAL
= 0,
44 * Undeflow Label. The bucket with this label contains names
45 * in scripts that sort before any of the bucket labels in this index.
48 U_ALPHAINDEX_UNDERFLOW
= 1,
51 * Inflow Label. The bucket with this label contains names
52 * in scripts that sort between two of the bucket labels in this index.
53 * Inflow labels are created when an index contains normal labels for
54 * multiple scripts, and skips other scripts that sort between some of the
58 U_ALPHAINDEX_INFLOW
= 2,
61 * Overflow Label. Te bucket with this label contains names in scripts
62 * that sort after all of the bucket labels in this index.
65 U_ALPHAINDEX_OVERFLOW
= 3
66 } UAlphabeticIndexLabelType
;
72 #if U_SHOW_CPLUSPLUS_API
75 // Forward Declarations
79 class RuleBasedCollator
;
80 class StringEnumeration
;
85 * AlphabeticIndex supports the creation of a UI index appropriate for a given language.
86 * It can support either direct use, or use with a client that doesn't support localized collation.
87 * The following is an example of what an index might look like in a UI:
90 * <b>... A B C D E F G H I J K L M N O P Q R S T U V W X Y Z ...</b>
101 * The class can generate a list of labels for use as a UI "index", that is, a list of
102 * clickable characters (or character sequences) that allow the user to see a segment
103 * (bucket) of a larger "target" list. That is, each label corresponds to a bucket in
104 * the target list, where everything in the bucket is greater than or equal to the character
105 * (according to the locale's collation). Strings can be added to the index;
106 * they will be in sorted order in the right bucket.
108 * The class also supports having buckets for strings before the first (underflow),
109 * after the last (overflow), and between scripts (inflow). For example, if the index
110 * is constructed with labels for Russian and English, Greek characters would fall
111 * into an inflow bucket between the other two scripts.
113 * The AlphabeticIndex class is not intended for public subclassing.
115 * <p><em>Note:</em> If you expect to have a lot of ASCII or Latin characters
116 * as well as characters from the user's language,
117 * then it is a good idea to call addLabels(Locale::getEnglish(), status).</p>
119 * <h2>Direct Use</h2>
120 * <p>The following shows an example of building an index directly.
121 * The "show..." methods below are just to illustrate usage.
124 * // Create a simple index. "Item" is assumed to be an application
125 * // defined type that the application's UI and other processing knows about,
126 * // and that has a name.
128 * UErrorCode status = U_ZERO_ERROR;
129 * AlphabeticIndex index = new AlphabeticIndex(desiredLocale, status);
130 * index->addLabels(additionalLocale, status);
131 * for (Item *item in some source of Items ) {
132 * index->addRecord(item->name(), item, status);
135 * // Show index at top. We could skip or gray out empty buckets
137 * while (index->nextBucket(status)) {
138 * if (showAll || index->getBucketRecordCount() != 0) {
139 * showLabelAtTop(UI, index->getBucketLabel());
143 * // Show the buckets with their contents, skipping empty buckets
145 * index->resetBucketIterator(status);
146 * while (index->nextBucket(status)) {
147 * if (index->getBucketRecordCount() != 0) {
148 * showLabelInList(UI, index->getBucketLabel());
149 * while (index->nextRecord(status)) {
150 * showIndexedItem(UI, static_cast<Item *>(index->getRecordData()))
153 * The caller can build different UIs using this class.
154 * For example, an index character could be omitted or grayed-out
155 * if its bucket is empty. Small buckets could also be combined based on size, such as:
158 * <b>... A-F G-N O-Z ...</b>
161 * <h2>Client Support</h2>
162 * <p>Callers can also use the AlphabeticIndex::ImmutableIndex, or the AlphabeticIndex itself,
163 * to support sorting on a client that doesn't support AlphabeticIndex functionality.
165 * <p>The ImmutableIndex is both immutable and thread-safe.
166 * The corresponding AlphabeticIndex methods are not thread-safe because
167 * they "lazily" build the index buckets.
169 * <li>ImmutableIndex.getBucket(index) provides random access to all
170 * buckets and their labels and label types.
171 * <li>The AlphabeticIndex bucket iterator or ImmutableIndex.getBucket(0..getBucketCount-1)
172 * can be used to get a list of the labels,
173 * such as "...", "A", "B",..., and send that list to the client.
174 * <li>When the client has a new name, it sends that name to the server.
175 * The server needs to call the following methods,
176 * and communicate the bucketIndex and collationKey back to the client.
179 * int32_t bucketIndex = index.getBucketIndex(name, status);
180 * const UnicodeString &label = immutableIndex.getBucket(bucketIndex)->getLabel(); // optional
181 * int32_t skLength = collator.getSortKey(name, sk, skCapacity);
184 * <li>The client would put the name (and associated information) into its bucket for bucketIndex. The sort key sk is a
185 * sequence of bytes that can be compared with a binary compare, and produce the right localized result.</li>
190 class U_I18N_API AlphabeticIndex
: public UObject
{
193 * An index "bucket" with a label string and type.
194 * It is referenced by getBucketIndex(),
195 * and returned by ImmutableIndex.getBucket().
197 * The Bucket class is not intended for public subclassing.
200 class U_I18N_API Bucket
: public UObject
{
209 * Returns the label string.
211 * @return the label string for the bucket
214 const UnicodeString
&getLabel() const { return label_
; }
216 * Returns whether this bucket is a normal, underflow, overflow, or inflow bucket.
218 * @return the bucket label type
221 UAlphabeticIndexLabelType
getLabelType() const { return labelType_
; }
224 friend class AlphabeticIndex
;
225 friend class BucketList
;
227 UnicodeString label_
;
228 UnicodeString lowerBoundary_
;
229 UAlphabeticIndexLabelType labelType_
;
230 Bucket
*displayBucket_
;
231 int32_t displayIndex_
;
232 UVector
*records_
; // Records are owned by the inputList_ vector.
234 Bucket(const UnicodeString
&label
, // Parameter strings are copied.
235 const UnicodeString
&lowerBoundary
,
236 UAlphabeticIndexLabelType type
);
240 * Immutable, thread-safe version of AlphabeticIndex.
241 * This class provides thread-safe methods for bucketing,
242 * and random access to buckets and their properties,
243 * but does not offer adding records to the index.
245 * The ImmutableIndex class is not intended for public subclassing.
249 class U_I18N_API ImmutableIndex
: public UObject
{
255 virtual ~ImmutableIndex();
258 * Returns the number of index buckets and labels, including underflow/inflow/overflow.
260 * @return the number of index buckets
263 int32_t getBucketCount() const;
266 * Finds the index bucket for the given name and returns the number of that bucket.
267 * Use getBucket() to get the bucket's properties.
269 * @param name the string to be sorted into an index bucket
270 * @return the bucket number for the name
273 int32_t getBucketIndex(const UnicodeString
&name
, UErrorCode
&errorCode
) const;
276 * Returns the index-th bucket. Returns NULL if the index is out of range.
278 * @param index bucket number
279 * @return the index-th bucket
282 const Bucket
*getBucket(int32_t index
) const;
285 friend class AlphabeticIndex
;
287 ImmutableIndex(BucketList
*bucketList
, Collator
*collatorPrimaryOnly
)
288 : buckets_(bucketList
), collatorPrimaryOnly_(collatorPrimaryOnly
) {}
290 BucketList
*buckets_
;
291 Collator
*collatorPrimaryOnly_
;
295 * Construct an AlphabeticIndex object for the specified locale. If the locale's
296 * data does not include index characters, a set of them will be
297 * synthesized based on the locale's exemplar characters. The locale
298 * determines the sorting order for both the index characters and the
299 * user item names appearing under each Index character.
301 * @param locale the desired locale.
302 * @param status Error code, will be set with the reason if the construction
303 * of the AlphabeticIndex object fails.
306 AlphabeticIndex(const Locale
&locale
, UErrorCode
&status
);
309 * Construct an AlphabeticIndex that uses a specific collator.
311 * The index will be created with no labels; the addLabels() function must be called
312 * after creation to add the desired labels to the index.
314 * The index adopts the collator, and is responsible for deleting it.
315 * The caller should make no further use of the collator after creating the index.
317 * @param collator The collator to use to order the contents of this index.
318 * @param status Error code, will be set with the reason if the
322 AlphabeticIndex(RuleBasedCollator
*collator
, UErrorCode
&status
);
325 * Add Labels to this Index. The labels are additions to those
326 * that are already in the index; they do not replace the existing
328 * @param additions The additional characters to add to the index, such as A-Z.
329 * @param status Error code, will be set with the reason if the
331 * @return this, for chaining
334 virtual AlphabeticIndex
&addLabels(const UnicodeSet
&additions
, UErrorCode
&status
);
337 * Add the index characters from a Locale to the index. The labels
338 * are added to those that are already in the index; they do not replace the
339 * existing index characters. The collation order for this index is not
340 * changed; it remains that of the locale that was originally specified
341 * when creating this Index.
343 * @param locale The locale whose index characters are to be added.
344 * @param status Error code, will be set with the reason if the
346 * @return this, for chaining
349 virtual AlphabeticIndex
&addLabels(const Locale
&locale
, UErrorCode
&status
);
355 virtual ~AlphabeticIndex();
358 * Builds an immutable, thread-safe version of this instance, without data records.
360 * @return an immutable index instance
363 ImmutableIndex
*buildImmutableIndex(UErrorCode
&errorCode
);
366 * Get the Collator that establishes the ordering of the items in this index.
367 * Ownership of the collator remains with the AlphabeticIndex instance.
369 * The returned collator is a reference to the internal collator used by this
370 * index. It may be safely used to compare the names of items or to get
371 * sort keys for names. However if any settings need to be changed,
372 * or other non-const methods called, a cloned copy must be made first.
374 * @return The collator
377 virtual const RuleBasedCollator
&getCollator() const;
381 * Get the default label used for abbreviated buckets <i>between</i> other index characters.
382 * For example, consider the labels when Latin and Greek are used:
383 * X Y Z ... Α Β Γ.
385 * @return inflow label
388 virtual const UnicodeString
&getInflowLabel() const;
391 * Set the default label used for abbreviated buckets <i>between</i> other index characters.
392 * An inflow label will be automatically inserted if two otherwise-adjacent label characters
393 * are from different scripts, e.g. Latin and Cyrillic, and a third script, e.g. Greek,
394 * sorts between the two. The default inflow character is an ellipsis (...)
396 * @param inflowLabel the new Inflow label.
397 * @param status Error code, will be set with the reason if the operation fails.
401 virtual AlphabeticIndex
&setInflowLabel(const UnicodeString
&inflowLabel
, UErrorCode
&status
);
405 * Get the special label used for items that sort after the last normal label,
406 * and that would not otherwise have an appropriate label.
408 * @return the overflow label
411 virtual const UnicodeString
&getOverflowLabel() const;
415 * Set the label used for items that sort after the last normal label,
416 * and that would not otherwise have an appropriate label.
418 * @param overflowLabel the new overflow label.
419 * @param status Error code, will be set with the reason if the operation fails.
423 virtual AlphabeticIndex
&setOverflowLabel(const UnicodeString
&overflowLabel
, UErrorCode
&status
);
426 * Get the special label used for items that sort before the first normal label,
427 * and that would not otherwise have an appropriate label.
429 * @return underflow label
432 virtual const UnicodeString
&getUnderflowLabel() const;
435 * Set the label used for items that sort before the first normal label,
436 * and that would not otherwise have an appropriate label.
438 * @param underflowLabel the new underflow label.
439 * @param status Error code, will be set with the reason if the operation fails.
443 virtual AlphabeticIndex
&setUnderflowLabel(const UnicodeString
&underflowLabel
, UErrorCode
&status
);
447 * Get the limit on the number of labels permitted in the index.
448 * The number does not include over, under and inflow labels.
450 * @return maxLabelCount maximum number of labels.
453 virtual int32_t getMaxLabelCount() const;
456 * Set a limit on the number of labels permitted in the index.
457 * The number does not include over, under and inflow labels.
458 * Currently, if the number is exceeded, then every
459 * nth item is removed to bring the count down.
460 * A more sophisticated mechanism may be available in the future.
462 * @param maxLabelCount the maximum number of labels.
463 * @param status error code
464 * @return This, for chaining
467 virtual AlphabeticIndex
&setMaxLabelCount(int32_t maxLabelCount
, UErrorCode
&status
);
471 * Add a record to the index. Each record will be associated with an index Bucket
472 * based on the record's name. The list of records for each bucket will be sorted
473 * based on the collation ordering of the names in the index's locale.
474 * Records with duplicate names are permitted; they will be kept in the order
475 * that they were added.
477 * @param name The display name for the Record. The Record will be placed in
478 * a bucket based on this name.
479 * @param data An optional pointer to user data associated with this
480 * item. When iterating the contents of a bucket, both the
481 * data pointer the name will be available for each Record.
482 * @param status Error code, will be set with the reason if the operation fails.
483 * @return This, for chaining.
486 virtual AlphabeticIndex
&addRecord(const UnicodeString
&name
, const void *data
, UErrorCode
&status
);
489 * Remove all Records from the Index. The set of Buckets, which define the headings under
490 * which records are classified, is not altered.
492 * @param status Error code, will be set with the reason if the operation fails.
493 * @return This, for chaining.
496 virtual AlphabeticIndex
&clearRecords(UErrorCode
&status
);
499 /** Get the number of labels in this index.
500 * Note: may trigger lazy index construction.
502 * @param status Error code, will be set with the reason if the operation fails.
503 * @return The number of labels in this index, including any under, over or
507 virtual int32_t getBucketCount(UErrorCode
&status
);
510 /** Get the total number of Records in this index, that is, the number
511 * of <name, data> pairs added.
513 * @param status Error code, will be set with the reason if the operation fails.
514 * @return The number of records in this index, that is, the total number
515 * of (name, data) items added with addRecord().
518 virtual int32_t getRecordCount(UErrorCode
&status
);
523 * Given the name of a record, return the zero-based index of the Bucket
524 * in which the item should appear. The name need not be in the index.
525 * A Record will not be added to the index by this function.
526 * Bucket numbers are zero-based, in Bucket iteration order.
528 * @param itemName The name whose bucket position in the index is to be determined.
529 * @param status Error code, will be set with the reason if the operation fails.
530 * @return The bucket number for this name.
534 virtual int32_t getBucketIndex(const UnicodeString
&itemName
, UErrorCode
&status
);
538 * Get the zero based index of the current Bucket from an iteration
539 * over the Buckets of this index. Return -1 if no iteration is in process.
540 * @return the index of the current Bucket
543 virtual int32_t getBucketIndex() const;
547 * Advance the iteration over the Buckets of this index. Return FALSE if
548 * there are no more Buckets.
550 * @param status Error code, will be set with the reason if the operation fails.
551 * U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while
552 * an enumeration of its contents are in process.
554 * @return TRUE if success, FALSE if at end of iteration
557 virtual UBool
nextBucket(UErrorCode
&status
);
560 * Return the name of the Label of the current bucket from an iteration over the buckets.
561 * If the iteration is before the first Bucket (nextBucket() has not been called),
562 * or after the last, return an empty string.
564 * @return the bucket label.
567 virtual const UnicodeString
&getBucketLabel() const;
570 * Return the type of the label for the current Bucket (selected by the
571 * iteration over Buckets.)
573 * @return the label type.
576 virtual UAlphabeticIndexLabelType
getBucketLabelType() const;
579 * Get the number of <name, data> Records in the current Bucket.
580 * If the current bucket iteration position is before the first label or after the
583 * @return the number of Records.
586 virtual int32_t getBucketRecordCount() const;
590 * Reset the Bucket iteration for this index. The next call to nextBucket()
591 * will restart the iteration at the first label.
593 * @param status Error code, will be set with the reason if the operation fails.
594 * @return this, for chaining.
597 virtual AlphabeticIndex
&resetBucketIterator(UErrorCode
&status
);
600 * Advance to the next record in the current Bucket.
601 * When nextBucket() is called, Record iteration is reset to just before the
602 * first Record in the new Bucket.
604 * @param status Error code, will be set with the reason if the operation fails.
605 * U_ENUM_OUT_OF_SYNC_ERROR will be reported if the index is modified while
606 * an enumeration of its contents are in process.
607 * @return TRUE if successful, FALSE when the iteration advances past the last item.
610 virtual UBool
nextRecord(UErrorCode
&status
);
613 * Get the name of the current Record.
614 * Return an empty string if the Record iteration position is before first
617 * @return The name of the current index item.
620 virtual const UnicodeString
&getRecordName() const;
624 * Return the data pointer of the Record currently being iterated over.
625 * Return NULL if the current iteration position before the first item in this Bucket,
628 * @return The current Record's data pointer.
631 virtual const void *getRecordData() const;
635 * Reset the Record iterator position to before the first Record in the current Bucket.
637 * @return This, for chaining.
640 virtual AlphabeticIndex
&resetRecordIterator();
644 * No Copy constructor.
647 AlphabeticIndex(const AlphabeticIndex
&other
);
652 AlphabeticIndex
&operator =(const AlphabeticIndex
& /*other*/) { return *this;};
655 * No Equality operators.
658 virtual UBool
operator==(const AlphabeticIndex
& other
) const;
661 * Inequality operator.
664 virtual UBool
operator!=(const AlphabeticIndex
& other
) const;
666 // Common initialization, for use from all constructors.
667 void init(const Locale
*locale
, UErrorCode
&status
);
670 * This method is called to get the index exemplars. Normally these come from the locale directly,
671 * but if they aren't available, we have to synthesize them.
673 void addIndexExemplars(const Locale
&locale
, UErrorCode
&status
);
675 * Add Chinese index characters from the tailoring.
677 UBool
addChineseIndexCharacters(UErrorCode
&errorCode
);
679 UVector
*firstStringsInScript(UErrorCode
&status
);
681 static UnicodeString
separated(const UnicodeString
&item
);
684 * Determine the best labels to use.
685 * This is based on the exemplars, but we also process to make sure that they are unique,
686 * and sort differently, and that the overall list is small enough.
688 void initLabels(UVector
&indexCharacters
, UErrorCode
&errorCode
) const;
689 BucketList
*createBucketList(UErrorCode
&errorCode
) const;
690 void initBuckets(UErrorCode
&errorCode
);
692 void internalResetBucketIterator();
696 // The Record is declared public only to allow access from
697 // implementation code written in plain C.
698 // It is not intended for public use.
700 #ifndef U_HIDE_INTERNAL_API
702 * A (name, data) pair, to be sorted by name into one of the index buckets.
703 * The user data is not used by the index implementation.
706 struct Record
: public UMemory
{
707 const UnicodeString name_
;
709 Record(const UnicodeString
&name
, const void *data
);
712 #endif /* U_HIDE_INTERNAL_API */
717 * Holds all user records before they are distributed into buckets.
718 * Type of contents is (Record *)
723 int32_t labelsIterIndex_
; // Index of next item to return.
724 int32_t itemsIterIndex_
;
725 Bucket
*currentBucket_
; // While an iteration of the index in underway,
726 // point to the bucket for the current label.
727 // NULL when no iteration underway.
729 int32_t maxLabelCount_
; // Limit on # of labels permitted in the index.
731 UnicodeSet
*initialLabels_
; // Initial (unprocessed) set of Labels. Union
732 // of those explicitly set by the user plus
733 // those from locales. Raw values, before
734 // crunching into bucket labels.
736 UVector
*firstCharsInScripts_
; // The first character from each script,
737 // in collation order.
739 RuleBasedCollator
*collator_
;
740 RuleBasedCollator
*collatorPrimaryOnly_
;
742 // Lazy evaluated: null means that we have not built yet.
743 BucketList
*buckets_
;
745 UnicodeString inflowLabel_
;
746 UnicodeString overflowLabel_
;
747 UnicodeString underflowLabel_
;
748 UnicodeString overflowComparisonString_
;
750 UnicodeString emptyString_
;
754 #endif // U_SHOW_CPLUSPLUS_API
756 #endif // !UCONFIG_NO_COLLATION