Various improvements to handling and detection of URLs in codes
[zxing.git] / javame / src / com / google / zxing / client / j2me / ZXingMIDlet.java
1 /*
2  * Copyright 2007 Google Inc.
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
17 package com.google.zxing.client.j2me;
18
19 import javax.microedition.io.ConnectionNotFoundException;
20 import javax.microedition.lcdui.Alert;
21 import javax.microedition.lcdui.AlertType;
22 import javax.microedition.lcdui.Canvas;
23 import javax.microedition.lcdui.Command;
24 import javax.microedition.lcdui.CommandListener;
25 import javax.microedition.lcdui.Display;
26 import javax.microedition.lcdui.Displayable;
27 import javax.microedition.media.Manager;
28 import javax.microedition.media.MediaException;
29 import javax.microedition.media.Player;
30 import javax.microedition.media.control.VideoControl;
31 import javax.microedition.midlet.MIDlet;
32 import javax.microedition.midlet.MIDletStateChangeException;
33 import java.io.IOException;
34
35 /**
36  * <p>The actual reader application {@link MIDlet}.</p>
37  *
38  * @author Sean Owen (srowen@google.com)
39  */
40 public final class ZXingMIDlet extends MIDlet {
41
42   private Canvas canvas;
43   private Player player;
44   private VideoControl videoControl;
45
46   Player getPlayer() {
47     return player;
48   }
49
50   VideoControl getVideoControl() {
51     return videoControl;
52   }
53
54   protected void startApp() throws MIDletStateChangeException {
55     try {
56       player = Manager.createPlayer("capture://video");
57       player.realize();
58       AdvancedMultimediaManager.setZoom(player);
59       videoControl = (VideoControl) player.getControl("VideoControl");
60       canvas = new VideoCanvas(this);
61       canvas.setFullScreenMode(true);
62       videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, canvas);
63       videoControl.setDisplayLocation(0, 0);
64       videoControl.setDisplaySize(canvas.getWidth(), canvas.getHeight());
65       videoControl.setVisible(true);
66       player.start();
67       Display.getDisplay(this).setCurrent(canvas);
68     } catch (IOException ioe) {
69       throw new MIDletStateChangeException(ioe.toString());
70     } catch (MediaException me) {
71       throw new MIDletStateChangeException(me.toString());
72     }
73   }
74
75   protected void pauseApp() {
76     if (player != null) {
77       try {
78         player.stop();
79       } catch (MediaException me) {
80         // continue?
81         showError(me);        
82       }
83     }
84   }
85
86   protected void destroyApp(boolean unconditional) {
87     if (player != null) {
88       videoControl = null;      
89       try {
90         player.stop();
91       } catch (MediaException me) {
92         // continue
93       }
94       player.deallocate();
95       player.close();
96       player = null;
97     }
98   }
99
100   void stop() {
101     destroyApp(false);
102     notifyDestroyed();
103   }
104
105   // Convenience methods to show dialogs
106
107   private void showOpenURL(final String text) {
108     Alert alert = new Alert("Open web page?", text, null, AlertType.CONFIRMATION);
109     alert.setTimeout(Alert.FOREVER);
110     final Command cancel = new Command("Cancel", Command.CANCEL, 1);
111     alert.addCommand(cancel);
112     CommandListener listener = new CommandListener() {
113       public void commandAction(Command command, Displayable displayable) {
114         if (command.getCommandType() == Command.OK) {
115           try {
116             platformRequest(text);
117           } catch (ConnectionNotFoundException cnfe) {
118             showError(cnfe);
119           } finally {
120             stop();
121           }
122         } else {
123           // cancel
124           Display.getDisplay(ZXingMIDlet.this).setCurrent(canvas);
125         }
126       }
127     };
128     alert.setCommandListener(listener);
129     showAlert(alert);
130   }
131
132   private void showAlert(String title, String text) {
133     Alert alert = new Alert(title, text, null, AlertType.INFO);
134     alert.setTimeout(Alert.FOREVER);
135     showAlert(alert);
136   }
137
138   void showError(Throwable t) {
139     showAlert(new Alert("Error", t.getMessage(), null, AlertType.ERROR));
140   }
141
142   private void showAlert(Alert alert) {
143     Display display = Display.getDisplay(this);
144     display.setCurrent(alert, canvas);
145   }
146
147   /// TODO this whole bit needs to be merged with the code in core-ext -- this is messy and duplicative
148
149   void handleDecodedText(String text) {
150     // This is a crude imitation of the code found in module core-ext, which handles the contents
151     // in a more sophisticated way. It can't be accessed from JavaME just yet because it relies
152     // on URL parsing routines in java.net. This should be somehow worked around: TODO
153     // For now, detect URLs in a simple way, and treat everything else as text
154     if (text.startsWith("http://") || text.startsWith("https://")) {
155       showOpenURL(text);
156     } else if (text.startsWith("HTTP://") || text.startsWith("HTTPS://")) {
157       showOpenURL(decapitalizeProtocol(text));
158     } else if (text.startsWith("URL:")) {
159       showOpenURL(decapitalizeProtocol(text.substring(4)));
160     } else if (text.startsWith("MEBKM:")) {
161       int urlIndex = text.indexOf("URL:", 6);
162       if (urlIndex >= 6) {
163         String url = text.substring( urlIndex + 4);
164         int semicolon = url.indexOf((int) ';');
165         if (semicolon >= 0) {
166           url = url.substring(0, semicolon);
167         }
168         showOpenURL(decapitalizeProtocol(url));
169       } else {
170         showAlert("Barcode detected", text);
171       }
172     } else if (maybeURLWithoutScheme(text)) {
173       showOpenURL("http://" + text);
174     } else {
175       showAlert("Barcode detected", text);
176     }
177   }
178
179   private static String decapitalizeProtocol(String url) {
180     int protocolEnd = url.indexOf("://");
181     if (protocolEnd >= 0) {
182       return url.substring(0, protocolEnd).toLowerCase() + url.substring(protocolEnd);
183     } else {
184       return url;
185     }
186   }
187
188   /**
189    * Crudely guesses that a string may represent a URL if it has a '.' and no spaces.
190    */
191   private static boolean maybeURLWithoutScheme(String text) {
192     return text.indexOf((int) '.') >= 0 && text.indexOf((int) ' ') < 0;
193   }
194
195 }