1 // © 2020 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 3 package com.ibm.icu.impl.number; 4 5 import java.math.BigDecimal; 6 import java.util.List; 7 8 import com.ibm.icu.impl.units.ComplexUnitsConverter; 9 import com.ibm.icu.impl.units.MeasureUnitImpl; 10 import com.ibm.icu.impl.units.UnitsRouter; 11 import com.ibm.icu.util.MeasureUnit; 12 import com.ibm.icu.util.ULocale; 13 14 public class UsagePrefsHandler implements MicroPropsGenerator { 15 16 private final MicroPropsGenerator fParent; 17 private UnitsRouter fUnitsRouter; 18 UsagePrefsHandler(ULocale locale, MeasureUnit inputUnit, String usage, MicroPropsGenerator parent)19 public UsagePrefsHandler(ULocale locale, MeasureUnit inputUnit, String usage, MicroPropsGenerator parent) { 20 assert parent != null; 21 22 this.fParent = parent; 23 this.fUnitsRouter = new UnitsRouter(MeasureUnitImpl.forIdentifier(inputUnit.getIdentifier()), locale, usage); 24 } 25 26 /** 27 * Populates micros.mixedMeasures and modifies quantity, based on the values 28 * in measures. 29 */ 30 protected static void mixedMeasuresToMicros(ComplexUnitsConverter.ComplexConverterResult complexConverterResult, DecimalQuantity quantity, MicroProps outMicros)31 mixedMeasuresToMicros(ComplexUnitsConverter.ComplexConverterResult complexConverterResult, DecimalQuantity quantity, MicroProps outMicros) { 32 outMicros.mixedMeasures = complexConverterResult.measures; 33 outMicros.indexOfQuantity = complexConverterResult.indexOfQuantity; 34 quantity.setToBigDecimal((BigDecimal) outMicros.mixedMeasures.get(outMicros.indexOfQuantity).getNumber()); 35 } 36 37 /** 38 * Returns the list of possible output units, i.e. the full set of 39 * preferences, for the localized, usage-specific unit preferences. 40 * <p> 41 * The returned pointer should be valid for the lifetime of the 42 * UsagePrefsHandler instance. 43 */ getOutputUnits()44 public List<MeasureUnit> getOutputUnits() { 45 return fUnitsRouter.getOutputUnits(); 46 } 47 48 /** 49 * Obtains the appropriate output value, MeasureUnit and 50 * rounding/precision behaviour from the UnitsRouter. 51 * <p> 52 * The output unit is passed on to the LongNameHandler via 53 * micros.outputUnit. 54 */ 55 @Override processQuantity(DecimalQuantity quantity)56 public MicroProps processQuantity(DecimalQuantity quantity) { 57 MicroProps micros = this.fParent.processQuantity(quantity); 58 59 quantity.roundToInfinity(); // Enables toDouble 60 final UnitsRouter.RouteResult routed = fUnitsRouter.route(quantity.toBigDecimal(), micros); 61 micros.outputUnit = routed.outputUnit.build(); 62 UsagePrefsHandler.mixedMeasuresToMicros(routed.complexConverterResult, quantity, micros); 63 return micros; 64 } 65 } 66