]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-52_1/demos/src/com/ibm/icu/dev/demo/charsetdet/DetectingViewer.java
Upgrade ICU4J.
[Dictionary.git] / jars / icu4j-52_1 / demos / src / com / ibm / icu / dev / demo / charsetdet / DetectingViewer.java
1 /*
2  **************************************************************************
3  * Copyright (C) 2005-2010, International Business Machines Corporation   *
4  * and others. All Rights Reserved.                                       *
5  **************************************************************************
6  *
7  */
8
9 package com.ibm.icu.dev.demo.charsetdet;
10
11 import java.awt.Font;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.ActionListener;
14 import java.awt.event.KeyEvent;
15 import java.awt.event.WindowAdapter;
16 import java.awt.event.WindowEvent;
17 import java.io.BufferedInputStream;
18 import java.io.File;
19 import java.io.FileInputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.net.URL;
24 import java.nio.ByteBuffer;
25 import java.nio.charset.Charset;
26 import java.security.AccessControlException;
27
28 import javax.swing.JFileChooser;
29 import javax.swing.JFrame;
30 import javax.swing.JMenu;
31 import javax.swing.JMenuBar;
32 import javax.swing.JMenuItem;
33 import javax.swing.JOptionPane;
34 import javax.swing.JScrollPane;
35 import javax.swing.JTextPane;
36 import javax.swing.KeyStroke;
37
38 import com.ibm.icu.charset.CharsetICU;
39 import com.ibm.icu.dev.demo.impl.DemoApplet;
40 import com.ibm.icu.text.CharsetDetector;
41 import com.ibm.icu.text.CharsetMatch;
42
43 /**
44  * This simple application demonstrates how to use the CharsetDetector API. It
45  * opens a file or web page, detects the encoding, and then displays it using that
46  * encoding.
47  */
48 public class DetectingViewer extends JFrame implements ActionListener
49 {
50     
51     /**
52      * For serialization
53      */
54     private static final long serialVersionUID = -2307065724464747775L;
55     private JTextPane text;
56     private JFileChooser fileChooser;
57     
58     /**
59      * @throws java.awt.HeadlessException
60      */
61     public DetectingViewer()
62     {
63         super();
64         DemoApplet.demoFrameOpened();
65         
66         try {
67             fileChooser = new JFileChooser();
68         } catch (AccessControlException ace) {
69             System.err.println("no file chooser - access control exception. Continuing without file browsing. "+ace.toString());
70             fileChooser = null; //
71         }
72         
73 //        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
74         setSize(800, 800);
75
76         setJMenuBar(makeMenus());
77         text = new JTextPane();
78         text.setContentType("text/plain");
79         text.setText("");
80         text.setSize(800, 800);
81         
82         Font font = new Font("Arial Unicode MS", Font.PLAIN, 24);
83         text.setFont(font);
84         
85         JScrollPane scrollPane = new JScrollPane(text);
86         
87         getContentPane().add(scrollPane);
88         setVisible(true);
89
90         addWindowListener(
91                 new WindowAdapter() {
92                     public void windowClosing(WindowEvent e) {
93 //                        setVisible(false);
94 //                        dispose();
95
96                           doQuit();
97                     }
98                 } );
99
100     
101     }
102
103     public void actionPerformed(ActionEvent event)
104     {
105         String cmd = event.getActionCommand();
106         
107         if (cmd.equals("New...")) {
108            doNew();
109         } else if (cmd.equals("Open File...")) {
110            doOpenFile();
111         } else if (cmd.equals("Open URL...")) {
112             doOpenURL();
113         } else if (cmd.equals("Quit")) {
114            doQuit();
115         }
116     }
117
118     public static void main(String[] args)
119     {
120         new DetectingViewer();
121     }
122     
123     private void errorDialog(String title, String msg)
124     {
125         JOptionPane.showMessageDialog(this, msg, title, JOptionPane.ERROR_MESSAGE);
126     }
127     
128     private BufferedInputStream openFile(File file)
129     {
130         FileInputStream fileStream = null;
131         
132         try {
133             fileStream = new FileInputStream(file);
134         } catch (Exception e) {
135             errorDialog("Error Opening File", e.getMessage());
136             return null;
137         }
138         
139         return new BufferedInputStream(fileStream);
140     }
141     
142 //    private void openFile(String directory, String filename)
143 //    {
144 //        openFile(new File(directory, filename));
145 //    }
146     
147     
148     private BufferedInputStream openURL(String url)
149     {
150         InputStream s = null;
151
152         try {
153             URL aURL = new URL(url);
154             s = aURL.openStream();
155         } catch (Exception e) {
156             errorDialog("Error Opening URL", e.getMessage());
157             return null;
158         }
159         
160         return new BufferedInputStream(s);
161     }
162     
163     private String encodingName(CharsetMatch match)
164     {
165         return match.getName() + " (" + match.getLanguage() + ")";
166     }
167     
168     private void setMatchMenu(CharsetMatch[] matches)
169     {
170         JMenu menu = getJMenuBar().getMenu(1);
171         JMenuItem menuItem;
172         
173         menu.removeAll();
174         
175         for (int i = 0; i < matches.length; i += 1) {
176             CharsetMatch match = matches[i];
177             
178             menuItem = new JMenuItem(encodingName(match) + " " + match.getConfidence());
179             
180             menu.add(menuItem);
181         }
182     }
183     
184     private byte[] scriptTag = {(byte) 's', (byte) 'c', (byte) 'r', (byte) 'i', (byte) 'p', (byte) 't'};
185     private byte[] styleTag  = {(byte) 's', (byte) 't', (byte) 'y', (byte) 'l', (byte) 'e'};
186     private static int BUFFER_SIZE = 100000;
187     
188     private boolean openTag(byte[] buffer, int offset, int length, byte[] tag)
189     {
190         int tagLen = tag.length;
191         int bufRem = length - offset;
192         int b;
193         
194         for (b = 0; b < tagLen && b < bufRem; b += 1) {
195             if (buffer[b + offset] != tag[b]) {
196                 return false;
197             }
198         }
199         
200         return b == tagLen;
201     }
202     
203     private boolean closedTag(byte[] buffer, int offset, int length, byte[] tag)
204     {
205         if (buffer[offset] != (byte) '/') {
206             return false;
207         }
208         
209         return openTag(buffer, offset + 1, length, tag);
210     }
211     
212     private byte[] filter(InputStream in)
213     {
214         byte[] buffer = new byte[BUFFER_SIZE];
215         int bytesRemaining = BUFFER_SIZE;
216         int bufLen = 0;
217         
218         in.mark(BUFFER_SIZE);
219         
220         try {
221             while (bytesRemaining > 0) {
222                 int bytesRead = in.read(buffer, bufLen, bytesRemaining);
223                 
224                 if (bytesRead <= 0) {
225                     break;
226                 }
227                 
228                 bufLen += bytesRead;
229                 bytesRemaining -= bytesRead;
230             }
231         } catch (Exception e) {
232             // TODO: error handling?
233             return null;
234         }
235         
236         boolean inTag = false;
237         boolean skip  = false;
238         int out = 0;
239         
240         for (int i = 0; i < bufLen; i += 1) {
241             byte b = buffer[i];
242             
243             if (b == (byte) '<') {
244                 inTag = true;
245                 
246                 if (openTag(buffer, i + 1, bufLen, scriptTag) ||
247                     openTag(buffer, i + 1, bufLen, styleTag)) {
248                     skip = true;
249                 } else if (closedTag(buffer, i + 1, bufLen, scriptTag) ||
250                            closedTag(buffer, i + 1, bufLen, styleTag)) {
251                     skip = false;
252                 }
253             } else if (b == (byte) '>') {
254                 inTag = false;
255             } else if (! (inTag || skip)) {
256                 buffer[out++] = b;
257             }
258         }
259
260         byte[] filtered = new byte[out];
261         
262         System.arraycopy(buffer, 0, filtered, 0, out);
263         return filtered;
264     }
265     
266     private CharsetMatch[] detect(byte[] bytes)
267     {
268         CharsetDetector det = new CharsetDetector();
269         
270         det.setText(bytes);
271         
272         return det.detectAll();
273     }
274     
275     private CharsetMatch[] detect(BufferedInputStream inputStream)
276     {
277         CharsetDetector det    = new CharsetDetector();
278         
279         try {
280             det.setText(inputStream);
281             
282             return det.detectAll();
283         } catch (Exception e) {
284             // TODO: error message?
285             return null;
286         }
287     }
288     
289     private void show(InputStream inputStream, CharsetMatch[] matches, String title)
290     {
291         InputStreamReader isr;
292         char[] buffer = new char[1024];
293         int bytesRead = 0;
294         
295         if (matches == null || matches.length == 0) {
296             errorDialog("Match Error", "No matches!");
297             return;
298         }
299         
300         try {
301             StringBuffer sb = new StringBuffer();
302             String encoding = matches[0].getName();
303             
304             inputStream.reset();
305             
306             if (encoding.startsWith("UTF-32")) {
307                 byte[] bytes = new byte[1024];
308                 int offset = 0;
309                 int chBytes = 0;
310                 Charset utf32 = CharsetICU.forNameICU(encoding);
311                 
312                 while ((bytesRead = inputStream.read(bytes, offset, 1024)) >= 0) {
313                     offset  = bytesRead % 4;
314                     chBytes = bytesRead - offset;
315                     
316                     sb.append(utf32.decode(ByteBuffer.wrap(bytes)).toString());
317                     
318                     if (offset != 0) {
319                         for (int i = 0; i < offset; i += 1) {
320                             bytes[i] = bytes[chBytes + i];
321                         }
322                     }
323                 }
324             } else {
325                 isr = new InputStreamReader(inputStream, encoding);
326                 
327                 while ((bytesRead = isr.read(buffer, 0, 1024)) >= 0) {
328                     sb.append(buffer, 0, bytesRead);
329                 }
330                 
331                 isr.close();
332             }
333             
334             this.setTitle(title + " - " + encodingName(matches[0]));
335             
336             setMatchMenu(matches);
337             text.setText(sb.toString());
338         } catch (IOException e) {
339             errorDialog("IO Error", e.getMessage());
340         } catch (Exception e) {
341             errorDialog("Internal Error", e.getMessage());
342         }
343     }
344     
345     private void doNew()
346     {
347         // open a new window...
348     }
349     
350     private void doOpenFile()
351     {
352         int retVal = fileChooser.showOpenDialog(this);
353         
354         if (retVal == JFileChooser.APPROVE_OPTION) {
355             File file = fileChooser.getSelectedFile();
356             BufferedInputStream inputStream = openFile(file);
357             
358             if (inputStream != null) {
359                 CharsetMatch[] matches = detect(inputStream);
360                 
361                 show(inputStream, matches, file.getName());                
362             }
363         }
364     }
365     
366     private void doOpenURL()
367     {
368         String url = (String) JOptionPane.showInputDialog(this, "URL to open:", "Open URL", JOptionPane.PLAIN_MESSAGE,
369                 null, null, null);
370         
371         if (url != null && url.length() > 0) {
372             BufferedInputStream inputStream = openURL(url);
373             
374             if (inputStream != null) {
375                 byte[] filtered = filter(inputStream);
376                 CharsetMatch[] matches = detect(filtered);
377                 
378                 show(inputStream, matches, url);                
379             }
380         }
381 }
382     
383     private void doQuit()
384     {
385         DemoApplet.demoFrameClosed();
386         this.setVisible(false);
387         this.dispose();
388     }
389     
390     private JMenuBar makeMenus()
391     {
392         JMenu menu = new JMenu("File");
393         JMenuItem mi;
394         
395         mi = new JMenuItem("Open File...");
396         mi.setAccelerator((KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK)));
397         mi.addActionListener(this);
398         menu.add(mi);
399         if(fileChooser == null) {
400             mi.setEnabled(false); // no file chooser.
401         }
402         
403         mi = new JMenuItem("Open URL...");
404         mi.setAccelerator((KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)));
405         mi.addActionListener(this);
406         menu.add(mi);
407         
408         mi = new JMenuItem("Quit");
409         mi.setAccelerator((KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)));
410         mi.addActionListener(this);
411         menu.add(mi);
412         
413         JMenuBar mbar = new JMenuBar();
414         mbar.add(menu);
415         
416         menu = new JMenu("Detected Encodings");
417         mbar.add(menu);
418         
419         return mbar;
420     }
421 }