1   package org.daisy.pipeline.braille.liblouis.pef;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   import java.nio.charset.Charset;
6   
7   import org.daisy.dotify.api.table.BrailleConverter;
8   
9   import org.liblouis.DisplayTable;
10  
11  public class LiblouisDisplayTableBrailleConverter implements BrailleConverter {
12  	
13  	private final Map<Character,Character> b2t = new HashMap<Character,Character>();
14  	private final Map<Character,Character> t2b = new HashMap<Character,Character>();
15  	
16  	private final DisplayTable table;
17  
18  	public LiblouisDisplayTableBrailleConverter(DisplayTable table) {
19  		this.table = table;
20  		try {
21  			char[] brailleRange = new char[256];
22  			int i = 0;
23  			for (; i < 256; i++)
24  				brailleRange[i] = (char)(0x2800+i);
25  			char[] tableDef = table.encode(String.valueOf(brailleRange)).toCharArray();
26  			for (i = 255; i >= 0; i--) {
27  				t2b.put(tableDef[i], brailleRange[i]);
28  				b2t.put(brailleRange[i], tableDef[i]); }}
29  		catch (Throwable e) {
30  			throw new RuntimeException(e); }
31  	}
32  	
33  	/**
34  	 * @return Unicode braille string
35  	 */
36  	public String toBraille(String text) {
37  		StringBuffer buf = new StringBuffer();
38  		Character b;
39  		for (char t : text.toCharArray()) {
40  			b = t2b.get(t);
41  			if (b == null) {
42  				// character might map to a virtual dot pattern
43  				// DisplayTable.decode() will return the base pattern without virtual dots
44  				b = table.decode(t);
45  				// assume that blank means the table does not contain the character
46  				if (b != '\u2800')
47  					t2b.put(t, b);
48  				else
49  					throw new IllegalArgumentException("Character '" + t + "' (0x" + Integer.toHexString((int)(t)) + ") not found.");
50  			}
51  			buf.append(b); }
52  		return buf.toString();
53  	}
54  	
55  	/**
56  	 * @param braille Unicode braille string
57  	 */
58  	public String toText(String braille) {
59  		StringBuffer buf = new StringBuffer();
60  		Character t;
61  		for (char b : braille.toCharArray()) {
62  			t = b2t.get(b);
63  			if (t == null)
64  				throw new IllegalArgumentException("Braille pattern '" + b + "' (0x" + Integer.toHexString((int)(b)) + ") not found.");
65  			buf.append(t); }
66  		return buf.toString();
67  	}
68  	
69  	private static final Charset charset = Charset.forName("ISO-8859-1");
70  	
71  	public Charset getPreferredCharset() {
72  		return charset;
73  	}
74  	
75  	public boolean supportsEightDot() {
76  		return true;
77  	}
78  
79  	@Override
80  	public String toString() {
81  		return table.toString();
82  	}
83  }