Hyphenator.java revision 71cbc72e70a6f0e086535c51e35262eb3a4d4bd9
1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.text; 18 19import android.util.Log; 20 21import java.io.File; 22import java.io.IOException; 23import java.io.RandomAccessFile; 24import java.util.HashMap; 25import java.util.Locale; 26 27/** 28 * Hyphenator is a wrapper class for a native implementation of automatic hyphenation, 29 * in essence finding valid hyphenation opportunities in a word. 30 * 31 * @hide 32 */ 33/* package */ class Hyphenator { 34 // This class has deliberately simple lifetime management (no finalizer) because in 35 // the common case a process will use a very small number of locales. 36 37 private static String TAG = "Hyphenator"; 38 39 static HashMap<Locale, Hyphenator> sMap = new HashMap<Locale, Hyphenator>(); 40 41 private long mNativePtr; 42 43 private Hyphenator(long nativePtr) { 44 mNativePtr = nativePtr; 45 } 46 47 public static long get(Locale locale) { 48 synchronized (sMap) { 49 Hyphenator result = sMap.get(locale); 50 if (result == null) { 51 result = loadHyphenator(locale); 52 sMap.put(locale, result); 53 } 54 return result == null ? 0 : result.mNativePtr; 55 } 56 } 57 58 private static Hyphenator loadHyphenator(Locale locale) { 59 // TODO: find pattern dictionary (from system location) that best matches locale 60 if (Locale.US.equals(locale)) { 61 File f = new File("/data/local/tmp/hyph-en-us.pat.txt"); 62 try { 63 RandomAccessFile rf = new RandomAccessFile(f, "r"); 64 byte[] buf = new byte[(int)rf.length()]; 65 rf.read(buf); 66 rf.close(); 67 String patternData = new String(buf); 68 long nativePtr = StaticLayout.nLoadHyphenator(patternData); 69 return new Hyphenator(nativePtr); 70 } catch (IOException e) { 71 Log.e(TAG, "error loading hyphenation " + f); 72 } 73 } 74 return null; 75 } 76} 77