PageRenderTime 19ms CodeModel.GetById 2ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/ocr/textscanner/src/com/google/marvin/textscanner/ScannerActivity.java

http://eyes-free.googlecode.com/
Java | 299 lines | 221 code | 49 blank | 29 comment | 37 complexity | 677b717d6657959130e1a70234fe3589 MD5 | raw file
  1/*
  2 * Copyright (C) 2009 Google Inc.
  3 * 
  4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5 * use this file except in compliance with the License. You may obtain a copy of
  6 * 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, WITHOUT
 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 13 * License for the specific language governing permissions and limitations under
 14 * the License.
 15 */
 16package com.google.marvin.textscanner;
 17
 18import android.app.Activity;
 19import android.content.Context;
 20import android.content.Intent;
 21import android.content.SharedPreferences;
 22import android.os.Bundle;
 23import android.os.Parcelable;
 24import android.preference.PreferenceManager;
 25import android.text.ClipboardManager;
 26import android.text.Editable;
 27import android.util.Log;
 28import android.view.Menu;
 29import android.view.MenuItem;
 30import android.view.View;
 31import android.view.Window;
 32import android.view.WindowManager;
 33import android.view.View.OnClickListener;
 34import android.widget.Button;
 35import android.widget.EditText;
 36import android.widget.Toast;
 37
 38import com.android.ocr.client.Config;
 39import com.android.ocr.client.Intents;
 40import com.android.ocr.client.Ocr;
 41import com.android.ocr.client.Result;
 42
 43import java.util.Set;
 44
 45/**
 46 * Demonstration application for using Intents. Can load text from the camera
 47 * and copy it to the clipboard.
 48 * 
 49 * @author alanv@google.com (Alan Viverette)
 50 */
 51public class ScannerActivity extends Activity implements OnClickListener {
 52  private static final String TAG = "ScannerActivity";
 53
 54  private static final int REQUEST_CAPTURE = 0;
 55  private static final int REQUEST_RECOGNIZE = 1;
 56
 57  private static final int PREFS_ID = Menu.FIRST;
 58
 59  private Ocr mOcr;
 60
 61  @Override
 62  public void onCreate(Bundle savedInstanceState) {
 63    Log.i(TAG, "Creating ScannerActivity...");
 64
 65    super.onCreate(savedInstanceState);
 66
 67    setContentView(R.layout.main);
 68
 69    Window window = getWindow();
 70    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 71
 72    final Button capture = (Button) findViewById(R.id.capture);
 73    capture.setEnabled(false);
 74    
 75    Button clipboard = (Button) findViewById(R.id.clipboard);
 76
 77    View.OnClickListener onCapture = new View.OnClickListener() {
 78      @Override
 79      public void onClick(View v) {
 80        requestCapture();
 81      }
 82    };
 83    
 84    Ocr.InitCallback onInit = new Ocr.InitCallback() {
 85      @Override
 86      public void onInitialized(int status) {
 87        switch (status) {
 88          case Ocr.STATUS_SUCCESS: {
 89            capture.setEnabled(true);
 90            break;
 91          }
 92          case Ocr.STATUS_MISSING:
 93          case Ocr.STATUS_FAILURE: {
 94            finish();
 95            break;
 96          }
 97        }
 98      }
 99    };
100
101    // Load OCR library in this Activity so that we don't have to
102    // start & stop the service every time we open RecognizeActivity
103    mOcr = new Ocr(this, onInit);
104
105    capture.setOnClickListener(onCapture);
106    clipboard.setOnClickListener(this);
107  }
108
109  @Override
110  protected void onDestroy() {
111    mOcr.release();
112    
113    super.onDestroy();
114  }
115
116  @Override
117  public boolean onCreateOptionsMenu(Menu menu) {
118    super.onCreateOptionsMenu(menu);
119    menu.add(0, PREFS_ID, 0, R.string.menu_prefs);
120
121    return true;
122  }
123
124  @Override
125  public boolean onOptionsItemSelected(MenuItem item) {
126    switch (item.getItemId()) {
127      case PREFS_ID: {
128        Intent intent = new Intent(this, PrefsActivity.class);
129        startActivity(intent);
130        break;
131      }
132    }
133
134    return super.onOptionsItemSelected(item);
135  }
136
137  public void requestCapture() {
138    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
139    String resolution = prefs.getString(PrefsActivity.RESOLUTION, PrefsActivity.DEFAULT_RESOLUTION);
140
141    Intent capture = new Intent(Intents.Capture.ACTION);
142
143    if (resolution != null) {
144      String[] values = resolution.split("x");
145      int width = Integer.parseInt(values[0]);
146      int height = Integer.parseInt(values[1]);
147      capture.putExtra(Intents.Capture.WIDTH, width);
148      capture.putExtra(Intents.Capture.HEIGHT, height);
149    }
150
151    startActivityForResult(capture, REQUEST_CAPTURE);
152  }
153
154  public void requestRecognize(Intent data) {
155    Parcelable extra = data.getParcelableExtra(Intents.Capture.CONFIG);
156
157    if (!(extra instanceof Config)) {
158      Log.e(TAG, "requestRecognize received wrong parcelable type (was " + extra + ")");
159      return;
160    }
161
162    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
163
164    Config config = (Config) extra;
165    config.pageSegMode = Config.PSM_AUTO;
166    config.language = prefs.getString(PrefsActivity.LANGUAGE, PrefsActivity.DEFAULT_LANGUAGE);
167    config.debug = prefs.getBoolean(PrefsActivity.DEBUG, PrefsActivity.DEFAULT_DEBUG);
168
169    boolean textdetect =
170        prefs.getBoolean(PrefsActivity.TEXTDETECT, PrefsActivity.DEFAULT_TEXTDETECT);
171    if (textdetect) {
172      config.options |= Config.OPT_DETECT_TEXT;
173    }
174
175    boolean normalize = prefs.getBoolean(PrefsActivity.NORMALIZE, PrefsActivity.DEFAULT_NORMALIZE);
176    if (normalize) {
177      config.options |= Config.OPT_NORMALIZE_BG;
178    }
179
180    if (config.image != null) {
181      Intent recognize = new Intent(Intents.Recognize.ACTION);
182      recognize.putExtra(Intents.Recognize.CONFIG, config);
183      startActivityForResult(recognize, REQUEST_RECOGNIZE);
184    } else {
185      Log.e(TAG, "requestRecognize received null image");
186    }
187  }
188
189  public void handleCompleted(Intent data) {
190    if (!data.hasExtra(Intents.Recognize.RESULTS)) {
191      Log.e(TAG, "handleCompleted received empty intent");
192
193      Set<String> keys = data.getExtras().keySet();
194      for (String key : keys) {
195        Log.e(TAG, "    Contains '" + key + "'");
196      }
197    }
198
199    Parcelable[] results = data.getParcelableArrayExtra(Intents.Recognize.RESULTS);
200
201    if (results == null) {
202      Log.e(TAG, "handleCompleted received null results");
203    } else if (results.length <= 0) {
204      Log.e(TAG, "handleCompleted received empty results");
205    } else {
206      EditText textresult = (EditText) findViewById(R.id.textresult);
207      textresult.setText("");
208
209      for (int i = 0; i < results.length; i++) {
210        String result = postProcess(((Result) results[i]).getString());
211        if (result.length() > 0) {
212          textresult.append(result.trim() + "\n");
213        }
214      }
215    }
216
217    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
218
219    boolean clipboard = prefs.getBoolean(PrefsActivity.CLIPBOARD, PrefsActivity.DEFAULT_CLIPBOARD);
220    if (clipboard) {
221      copyToClipboard();
222    }
223  }
224
225  /**
226   * Removes words that consist of more than 1/3 non-word characters.
227   * 
228   * @param text the text to process
229   * @return the processed text
230   */
231  private String postProcess(String text) {
232    String[] input = text.split(" ");
233    String output = "";
234
235    for (int i = 0; i < input.length; i++) {
236      if (input[i].length() <= 0) {
237        continue;
238      }
239      int letterCount = 0;
240      for (int j = 0; j < input[i].length(); j++) {
241        char chr = input[i].charAt(j);
242        if (chr == '\n' || Character.isLetterOrDigit(chr)) {
243          letterCount++;
244        }
245      }
246      if (10 * letterCount / input[i].length() > 6) {
247        output += input[i] + " ";
248      }
249    }
250
251    return output;
252  }
253
254  @Override
255  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
256    switch (requestCode) {
257      case REQUEST_CAPTURE: {
258        if (resultCode == RESULT_OK) {
259          requestRecognize(data);
260        } else {
261          Toast.makeText(this, R.string.capture_failed, 5).show();
262          Log.e(TAG, "REQUEST_CAPTURE received unexpected resultCode (" + resultCode + ")");
263        }
264        break;
265      }
266      case REQUEST_RECOGNIZE: {
267        if (resultCode == RESULT_OK) {
268          handleCompleted(data);
269        } else if (resultCode == RESULT_CANCELED) {
270          Toast.makeText(this, R.string.recognize_canceled, 3).show();
271          Log.i(TAG, "REQUEST_RECOGNIZED received RESULT_CANCELED");
272        } else {
273          Toast.makeText(this, R.string.recognize_failed, 5).show();
274          Log.e(TAG, "REQUEST_RECOGNIZE received unexpected resultCode (" + resultCode + ")");
275        }
276        break;
277      }
278      default: {
279        Log.i(TAG, "Received unknown activity request code (" + requestCode + ")");
280        super.onActivityResult(requestCode, resultCode, data);
281      }
282    }
283  }
284
285  @Override
286  public void onClick(View v) {
287    copyToClipboard();
288  }
289
290  private void copyToClipboard() {
291    EditText textresult = (EditText) findViewById(R.id.textresult);
292    Editable text = textresult.getText();
293
294    ClipboardManager manager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
295    manager.setText(text.toString());
296
297    Toast.makeText(this, R.string.clipboard, 3).show();
298  }
299}