code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Creates a skeleton C2B file when an appropriate media object is opened. */ public class CreateC2BFile extends Activity { private String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); setContentView(R.layout.c2b_creator_form); Button create = ((Button) findViewById(R.id.CreateButton)); create.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { String title = ((EditText) findViewById(R.id.TitleEditText)).getText().toString(); String author = ((EditText) findViewById(R.id.AuthorEditText)).getText().toString(); if (!title.equals("") && !author.equals("")) { createC2BSkeleton(title, author, dataSource); finish(); } } }); Button cancel = ((Button) findViewById(R.id.CancelButton)); cancel.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); } }); } private void createC2BSkeleton(String title, String author, String media) { String c2bDirStr = "/sdcard/c2b/"; String sanitizedTitle = title.replaceAll("'", " "); String sanitizedAuthor = author.replaceAll("'", " "); String filename = sanitizedTitle.replaceAll("[^a-zA-Z0-9,\\s]", ""); filename = c2bDirStr + filename + ".c2b"; String contents = "<c2b title='" + title + "' level='1' author='" + author + "' media='" + media + "'></c2b>"; File c2bDir = new File(c2bDirStr); boolean directoryExists = c2bDir.isDirectory(); if (!directoryExists) { c2bDir.mkdir(); } try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); Toast.makeText(CreateC2BFile.this, getString(R.string.STAGE_CREATED), 5000).show(); } catch (IOException e) { Toast.makeText(CreateC2BFile.this, getString(R.string.NEED_SD_CARD), 30000).show(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.util.ArrayList; /** * Adjusts the times for the beat targets using a linear least-squares fit. */ public class BeatTimingsAdjuster { private double[] adjustedBeatTimes; public void setRawBeatTimes(ArrayList<Integer> rawBeatTimes) { double[] beatTimes = new double[rawBeatTimes.size()]; for (int i = 0; i < beatTimes.length; i++) { beatTimes[i] = rawBeatTimes.get(i); } adjustedBeatTimes = new double[beatTimes.length]; double[] beatNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double n = beatNumbers.length; // Some things can be computed once and never computed again double[] beatNumbersXNumbers = multiplyArrays(beatNumbers, beatNumbers); double sumOfBeatNumbersXNumbers = sum(beatNumbersXNumbers); double sumOfBeatNumbers = sum(beatNumbers); // The divisor is: // (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))) // Since these are all constants, they can be computed first for better // efficiency. double divisor = (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))); // Not enough data to adjust for the first 5 beats for (int i = 0; (i < beatTimes.length) && (i < 5); i++) { adjustedBeatTimes[i] = beatTimes[i]; } // Adjust time for beat i by using timings for beats i-5 through i+5 double[] beatWindow = new double[beatNumbers.length]; for (int i = 0; i < beatTimes.length - 10; i++) { System.arraycopy(beatTimes, i, beatWindow, 0, beatNumbers.length); double[] beatNumbersXTimes = multiplyArrays(beatNumbers, beatWindow); double a = (sum(beatTimes) * sumOfBeatNumbersXNumbers - sumOfBeatNumbers * sum(beatNumbersXTimes)) / divisor; double b = (n * sum(beatNumbersXTimes) - sumOfBeatNumbers * sum(beatTimes)) / divisor; adjustedBeatTimes[i + 5] = a + b * beatNumbers[5]; } if (beatTimes.length - 10 < 0) { return; } // Not enough data to adjust for the last 5 beats for (int i = beatTimes.length - 10; i < beatTimes.length; i++) { adjustedBeatTimes[i] = beatTimes[i]; } } public ArrayList<Target> adjustBeatTargets(ArrayList<Target> rawTargets) { ArrayList<Target> adjustedTargets = new ArrayList<Target>(); int j = 0; double threshold = 200; for (int i = 0; i < rawTargets.size(); i++) { Target t = rawTargets.get(i); while ((j < adjustedBeatTimes.length) && (adjustedBeatTimes[j] < t.time)) { j++; } double prevTime = 0; if (j > 0) { prevTime = adjustedBeatTimes[j - 1]; } double postTime = -1; if (j < adjustedBeatTimes.length) { postTime = adjustedBeatTimes[j]; } if ((Math.abs(t.time - prevTime) < Math.abs(t.time - postTime)) && Math.abs(t.time - prevTime) < threshold) { t.time = prevTime; } else if ((Math.abs(t.time - prevTime) > Math.abs(t.time - postTime)) && Math.abs(t.time - postTime) < threshold) { t.time = postTime; } adjustedTargets.add(t); } return adjustedTargets; } private double sum(double[] numbers) { double sum = 0; for (int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } return sum; } private double[] multiplyArrays(double[] numberSetA, double[] numberSetB) { double[] sqArray = new double[numberSetA.length]; for (int i = 0; i < numberSetA.length; i++) { sqArray[i] = numberSetA[i] * numberSetB[i]; } return sqArray; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.widget.FrameLayout; import android.widget.Toast; import android.widget.VideoView; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * A rhythm/music game for Android that can use any video as the background. */ public class C2B extends Activity { public static final int GAME_MODE = 0; public static final int TWOPASS_MODE = 1; public static final int ONEPASS_MODE = 2; public int mode; public boolean wasEditMode; private boolean forceEditMode; private VideoView background; private GameView foreground; private FrameLayout layout; private String c2bFileName; private String[] filenames; private String marketId; // These are parsed in from the C2B file private String title; private String author; private String level; private String media; private Uri videoUri; public ArrayList<Target> targets; public ArrayList<Integer> beatTimes; private BeatTimingsAdjuster timingAdjuster; private boolean busyProcessing; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); UpdateChecker checker = new UpdateChecker(); int latestVersion = checker.getLatestVersionCode(); String packageName = C2B.class.getPackage().getName(); int currentVersion = 0; try { currentVersion = getPackageManager().getPackageInfo(packageName, 0).versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (latestVersion > currentVersion){ marketId = checker.marketId; displayUpdateMessage(); } else { resetGame(); } } private void resetGame() { targets = new ArrayList<Target>(); mode = GAME_MODE; forceEditMode = false; wasEditMode = false; busyProcessing = false; c2bFileName = ""; title = ""; author = ""; level = ""; media = ""; background = null; foreground = null; layout = null; background = new VideoView(this); foreground = new GameView(this); layout = new FrameLayout(this); layout.addView(background); layout.setPadding(30, 0, 0, 0); // Is there a better way to do layout? beatTimes = null; timingAdjuster = null; background.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mp) { background.start(); } }); background.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer arg0, int arg1, int arg2) { background.setVideoURI(videoUri); return true; } }); background.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { if (mode == ONEPASS_MODE) { Toast waitMessage = Toast.makeText(C2B.this, getString(R.string.PROCESSING), 5000); waitMessage.show(); (new Thread(new BeatsWriter())).start(); } else if (mode == TWOPASS_MODE) { mode = ONEPASS_MODE; (new Thread(new BeatsTimingAdjuster())).start(); displayCreateLevelInfo(); return; } displayStats(); } }); layout.addView(foreground); setContentView(layout); setVolumeControlStream(AudioManager.STREAM_MUSIC); displayStartupMessage(); } private void writeC2BFile(String filename) { String contents = "<c2b title='" + title + "' level='" + level + "' author='" + author + "' media='" + media + "'>"; ArrayList<Target> targets = foreground.recordedTargets; if (timingAdjuster != null) { targets = timingAdjuster.adjustBeatTargets(foreground.recordedTargets); } for (int i = 0; i < targets.size(); i++) { Target t = targets.get(i); contents = contents + "<beat time='" + Double.toString(t.time) + "' "; contents = contents + "x='" + Integer.toString(t.x) + "' "; contents = contents + "y='" + Integer.toString(t.y) + "' "; contents = contents + "color='" + Integer.toHexString(t.color) + "'/>"; } contents = contents + "</c2b>"; try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); } catch (IOException e) { // TODO(clchen): Do better error handling here e.printStackTrace(); } } private void loadC2B(String fileUriString) { try { FileInputStream fis = new FileInputStream(fileUriString); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void runC2B(Document c2b) { Node root = c2b.getElementsByTagName("c2b").item(0); title = root.getAttributes().getNamedItem("title").getNodeValue(); author = root.getAttributes().getNamedItem("author").getNodeValue(); level = root.getAttributes().getNamedItem("level").getNodeValue(); media = root.getAttributes().getNamedItem("media").getNodeValue(); NodeList beats = c2b.getElementsByTagName("beat"); targets = new ArrayList<Target>(); for (int i = 0; i < beats.getLength(); i++) { NamedNodeMap attribs = beats.item(i).getAttributes(); double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue()); int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue()); int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue()); String colorStr = attribs.getNamedItem("color").getNodeValue(); targets.add(new Target(time, x, y, colorStr)); } if ((beats.getLength() == 0) || forceEditMode) { displayCreateLevelAlert(); } else { videoUri = Uri.parse(media); background.setVideoURI(videoUri); } } private void displayCreateLevelAlert() { mode = ONEPASS_MODE; Builder createLevelAlert = new Builder(this); String titleText = getString(R.string.NO_BEATS) + " \"" + title + "\""; createLevelAlert.setTitle(titleText); String[] choices = new String[2]; choices[0] = getString(R.string.ONE_PASS); choices[1] = getString(R.string.TWO_PASS); createLevelAlert.setSingleChoiceItems(choices, 0, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { mode = ONEPASS_MODE; } else { mode = TWOPASS_MODE; } } }); createLevelAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } wasEditMode = true; if (mode == TWOPASS_MODE) { beatTimes = new ArrayList<Integer>(); timingAdjuster = new BeatTimingsAdjuster(); } displayCreateLevelInfo(); } }); createLevelAlert.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } displayC2BFiles(); } }); createLevelAlert.setCancelable(false); createLevelAlert.show(); } private void displayC2BFiles() { Builder c2bFilesAlert = new Builder(this); String titleText = getString(R.string.CHOOSE_STAGE); c2bFilesAlert.setTitle(titleText); File c2bDir = new File("/sdcard/c2b/"); filenames = c2bDir.list(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(".c2b"); } }); if (filenames == null) { displayNoFilesMessage(); return; } if (filenames.length == 0) { displayNoFilesMessage(); return; } c2bFilesAlert.setSingleChoiceItems(filenames, -1, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { c2bFileName = "/sdcard/c2b/" + filenames[which]; } }); c2bFilesAlert.setPositiveButton("Go!", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadC2B(c2bFileName); dialog.dismiss(); } }); /* c2bFilesAlert.setNeutralButton("Set new beats", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); displaySetNewBeatsConfirmation(); } }); */ final Activity self = this; c2bFilesAlert.setNeutralButton(getString(R.string.MOAR_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); c2bFilesAlert.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); c2bFilesAlert.setCancelable(false); c2bFilesAlert.show(); } /* private void displaySetNewBeatsConfirmation() { Builder setNewBeatsConfirmation = new Builder(this); String titleText = getString(R.string.EDIT_CONFIRMATION); setNewBeatsConfirmation.setTitle(titleText); String message = getString(R.string.EDIT_WARNING); setNewBeatsConfirmation.setMessage(message); setNewBeatsConfirmation.setPositiveButton("Continue", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { forceEditMode = true; loadC2B(c2bFileName); dialog.dismiss(); } }); setNewBeatsConfirmation.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); dialog.dismiss(); } }); setNewBeatsConfirmation.setCancelable(false); setNewBeatsConfirmation.show(); } */ private void displayCreateLevelInfo() { Builder createLevelInfoAlert = new Builder(this); String titleText = getString(R.string.BEAT_SETTING_INFO); createLevelInfoAlert.setTitle(titleText); String message = ""; if (mode == TWOPASS_MODE) { message = getString(R.string.TWO_PASS_INFO); } else { message = getString(R.string.ONE_PASS_INFO); } createLevelInfoAlert.setMessage(message); createLevelInfoAlert.setPositiveButton("Start", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); videoUri = Uri.parse(media); background.setVideoURI(videoUri); } }); createLevelInfoAlert.setCancelable(false); createLevelInfoAlert.show(); } private void displayStats() { Builder statsAlert = new Builder(this); String titleText = ""; if (!wasEditMode) { titleText = "Game Over"; } else { titleText = "Stage created!"; } statsAlert.setTitle(titleText); int longestCombo = foreground.longestCombo; if (foreground.comboCount > longestCombo) { longestCombo = foreground.comboCount; } String message = ""; if (!wasEditMode) { message = "Longest combo: " + Integer.toString(longestCombo); } else { message = "Beats recorded!"; } statsAlert.setMessage(message); statsAlert.setPositiveButton("Play", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } resetGame(); } }); statsAlert.setNegativeButton("Quit", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } finish(); } }); statsAlert.setCancelable(false); statsAlert.show(); } private void displayNoFilesMessage() { Builder noFilesMessage = new Builder(this); String titleText = getString(R.string.NO_STAGES_FOUND); noFilesMessage.setTitle(titleText); String message = getString(R.string.NO_STAGES_INFO); noFilesMessage.setMessage(message); noFilesMessage.setPositiveButton(getString(R.string.SHUT_UP), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadHardCodedRickroll(); } }); final Activity self = this; noFilesMessage.setNeutralButton(getString(R.string.ILL_GET_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); noFilesMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); noFilesMessage.setCancelable(false); noFilesMessage.show(); } private void loadHardCodedRickroll() { try { Resources res = getResources(); InputStream fis = res.openRawResource(R.raw.rickroll); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void displayStartupMessage() { Builder startupMessage = new Builder(this); String titleText = getString(R.string.WELCOME); startupMessage.setTitle(titleText); String message = getString(R.string.BETA_MESSAGE); startupMessage.setMessage(message); startupMessage.setPositiveButton(getString(R.string.START_GAME), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); } }); final Activity self = this; startupMessage.setNeutralButton(getString(R.string.VISIT_WEBSITE), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat"); i.setData(uri); self.startActivity(i); finish(); } }); startupMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); startupMessage.setCancelable(false); startupMessage.show(); } private void displayUpdateMessage() { Builder updateMessage = new Builder(this); String titleText = getString(R.string.UPDATE_AVAILABLE); updateMessage.setTitle(titleText); String message = getString(R.string.UPDATE_MESSAGE); updateMessage.setMessage(message); updateMessage.setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri marketUri = Uri.parse("market://details?id=" + marketId); Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri); startActivity(marketIntent); finish(); } }); final Activity self = this; updateMessage.setNegativeButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { resetGame(); } }); updateMessage.setCancelable(false); updateMessage.show(); } public int getCurrentTime() { try { return background.getCurrentPosition(); } catch (IllegalStateException e) { // This will be thrown if the player is exiting mid-game and the video // view is going away at the same time as the foreground is trying to get // the position. This error can be safely ignored without doing anything. e.printStackTrace(); return 0; } } // Do beats processing in another thread to avoid hogging the UI thread and // generating a "not responding" error public class BeatsWriter implements Runnable { public void run() { writeC2BFile(c2bFileName); busyProcessing = false; } } public class BeatsTimingAdjuster implements Runnable { public void run() { timingAdjuster.setRawBeatTimes(beatTimes); busyProcessing = false; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.media.AudioManager; import android.media.SoundPool; import android.os.Vibrator; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; /** * Draws the beat targets and takes user input. * This view is used as the foreground; the background is the video * being played. */ public class GameView extends View { private static final long[] VIBE_PATTERN = {0, 1, 40, 41}; private static final int INTERVAL = 10; // in ms private static final int PRE_THRESHOLD = 1000; // in ms private static final int POST_THRESHOLD = 500; // in ms private static final int TOLERANCE = 100; // in ms private static final int POINTS_FOR_PERFECT = 100; private static final double PENALTY_FACTOR = .25; private static final double COMBO_FACTOR = .1; private static final float TARGET_RADIUS = 50; public static final String LAST_RATING_OK = "(^_')"; public static final String LAST_RATING_PERFECT = "(^_^)/"; public static final String LAST_RATING_MISS = "(X_X)"; private C2B parent; private Vibrator vibe; private SoundPool snd; private int hitOkSfx; private int hitPerfectSfx; private int missSfx; public int comboCount; public int longestCombo; public String lastRating; Paint innerPaint; Paint borderPaint; Paint haloPaint; private ArrayList<Target> drawnTargets; private int lastTarget; public ArrayList<Target> recordedTargets; private int score; public GameView(Context context) { super(context); parent = (C2B) context; lastTarget = 0; score = 0; comboCount = 0; longestCombo = 0; lastRating = ""; drawnTargets = new ArrayList<Target>(); recordedTargets = new ArrayList<Target>(); vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); snd = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0); missSfx = snd.load(context, R.raw.miss, 0); hitOkSfx = snd.load(context, R.raw.ok, 0); hitPerfectSfx = snd.load(context, R.raw.perfect, 0); innerPaint = new Paint(); innerPaint.setColor(Color.argb(127, 0, 0, 0)); innerPaint.setStyle(Paint.Style.FILL); borderPaint = new Paint(); borderPaint.setStyle(Paint.Style.STROKE); borderPaint.setAntiAlias(true); borderPaint.setStrokeWidth(2); haloPaint = new Paint(); haloPaint.setStyle(Paint.Style.STROKE); haloPaint.setAntiAlias(true); haloPaint.setStrokeWidth(4); Thread monitorThread = (new Thread(new Monitor())); monitorThread.setPriority(Thread.MIN_PRIORITY); monitorThread.start(); } private void updateTargets() { int i = lastTarget; int currentTime = parent.getCurrentTime(); // Add any targets that are within the pre-threshold to the list of // drawnTargets boolean cont = true; while (cont && (i < parent.targets.size())) { if (parent.targets.get(i).time < currentTime + PRE_THRESHOLD) { drawnTargets.add(parent.targets.get(i)); i++; } else { cont = false; } } lastTarget = i; // Move any expired targets out of drawn targets for (int j = 0; j < drawnTargets.size(); j++) { Target t = drawnTargets.get(j); if (t == null) { // Do nothing - this is a concurrency issue where // the target is already gone, so just ignore it } else if (t.time + POST_THRESHOLD < currentTime) { try { drawnTargets.remove(j); } catch (IndexOutOfBoundsException e){ // Do nothing here, j is already gone } if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; lastRating = LAST_RATING_MISS; } } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int currentTime = parent.getCurrentTime(); float x = event.getX(); float y = event.getY(); boolean hadHit = false; if (parent.mode == C2B.ONEPASS_MODE) { // Record this point as a target hadHit = true; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); Target targ = new Target(currentTime, (int) x, (int) y, ""); recordedTargets.add(targ); } else if (parent.mode == C2B.TWOPASS_MODE) { hadHit = true; parent.beatTimes.add(currentTime); } else { // Play the game normally for (int i = 0; i < drawnTargets.size(); i++) { if (hitTarget(x, y, drawnTargets.get(i))) { Target t = drawnTargets.get(i); int points; double timeDiff = Math.abs(currentTime - t.time); if (timeDiff < TOLERANCE) { points = POINTS_FOR_PERFECT; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_PERFECT; } else { points = (int) (POINTS_FOR_PERFECT - (timeDiff * PENALTY_FACTOR)); points = points + (int) (points * (comboCount * COMBO_FACTOR)); snd.play(hitOkSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_OK; } if (points > 0) { score = score + points; hadHit = true; } drawnTargets.remove(i); break; } } } if (hadHit) { comboCount++; } else { if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; snd.play(missSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_MISS; } vibe.vibrate(VIBE_PATTERN, -1); } return true; } private boolean hitTarget(float x, float y, Target t) { if (t == null) { return false; } // Use the pythagorean theorem to solve this. float xSquared = (t.x - x) * (t.x - x); float ySquared = (t.y - y) * (t.y - y); if ((xSquared + ySquared) < (TARGET_RADIUS * TARGET_RADIUS)) { return true; } return false; } @Override public void onDraw(Canvas canvas) { if (parent.mode != C2B.GAME_MODE) { return; } int currentTime = parent.getCurrentTime(); // Draw the circles for (int i = 0; i < drawnTargets.size(); i++) { Target t = drawnTargets.get(i); if (t == null) { break; } // Insides should be semi-transparent canvas.drawCircle(t.x, t.y, TARGET_RADIUS, innerPaint); // Set colors for the target borderPaint.setColor(t.color); haloPaint.setColor(t.color); // Perfect timing == hitting the halo inside the borders canvas.drawCircle(t.x, t.y, TARGET_RADIUS - 5, borderPaint); canvas.drawCircle(t.x, t.y, TARGET_RADIUS, borderPaint); // Draw timing halos - may need to change the formula here float percentageOff = ((float) (t.time - currentTime)) / PRE_THRESHOLD; int haloSize = (int) (TARGET_RADIUS + (percentageOff * TARGET_RADIUS)); canvas.drawCircle(t.x, t.y, haloSize, haloPaint); } // Score and Combo info String scoreText = "Score: " + Integer.toString(score); int x = getWidth() - 100; // Fudge factor for making it on the top right // corner int y = 30; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(24); paint.setTypeface(Typeface.DEFAULT_BOLD); y -= paint.ascent() / 2; canvas.drawText(scoreText, x, y, paint); x = getWidth() / 2; canvas.drawText(lastRating, x, y, paint); String comboText = "Combo: " + Integer.toString(comboCount); x = 60; canvas.drawText(comboText, x, y, paint); } private class Monitor implements Runnable { public void run() { while (true) { try { Thread.sleep(INTERVAL); } catch (InterruptedException e) { // This should not be interrupted. If it is, just dump the stack // trace. e.printStackTrace(); } updateTargets(); postInvalidate(); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.zip.ZipFile; public class Unzipper { public static String download(String fileUrl) { URLConnection cn; try { fileUrl = (new URL(new URL(fileUrl), fileUrl)).toString(); URL url = new URL(fileUrl); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); File outputDir = new File("/sdcard/c2b/"); outputDir.mkdirs(); String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); filename = filename.substring(0, filename.indexOf("c2b.zip") + 7); File outputFile = new File("/sdcard/c2b/", filename); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = stream.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); stream.close(); out.close(); return "/sdcard/c2b/" + filename; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } } public static void unzip(String fileUrl) { try { String filename = download(fileUrl); ZipFile zip = new ZipFile(filename); Enumeration<? extends ZipEntry> zippedFiles = zip.entries(); while (zippedFiles.hasMoreElements()) { ZipEntry entry = zippedFiles.nextElement(); InputStream is = zip.getInputStream(entry); String name = entry.getName(); File outputFile = new File("/sdcard/c2b/" + name); String outputPath = outputFile.getCanonicalPath(); name = outputPath.substring(outputPath.lastIndexOf("/") + 1); outputPath = outputPath.substring(0, outputPath.lastIndexOf("/")); File outputDir = new File(outputPath); outputDir.mkdirs(); outputFile = new File(outputPath, name); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = is.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); is.close(); out.close(); } File theZipFile = new File(filename); theZipFile.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; public class Sphere extends Shape { public Sphere(boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, emitTextureCoordinates, emitNormals, emitColors); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TimeZone; /** * A class representing a city, with an associated position, time zone name, * and raw offset from UTC. */ public class City implements Comparable<City> { private static Map<String,City> cities = new HashMap<String,City>(); private static City[] citiesByRawOffset; private String name; private String timeZoneID; private TimeZone timeZone = null; private int rawOffset; private float latitude, longitude; private float x, y, z; /** * Loads the city database. The cities must be stored in order by raw * offset from UTC. */ public static void loadCities(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); int numCities = dis.readInt(); citiesByRawOffset = new City[numCities]; byte[] buf = new byte[24]; for (int i = 0; i < numCities; i++) { String name = dis.readUTF(); String tzid = dis.readUTF(); dis.read(buf); // The code below is a faster version of: // int rawOffset = dis.readInt(); // float latitude = dis.readFloat(); // float longitude = dis.readFloat(); // float cx = dis.readFloat(); // float cy = dis.readFloat(); // float cz = dis.readFloat(); int rawOffset = (buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) | ((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff); int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) | ((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff); int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) | ((buf[10] & 0xff) << 8) | (buf[11] & 0xff); int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) | ((buf[14] & 0xff) << 8) | (buf[15] & 0xff); int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) | ((buf[18] & 0xff) << 8) | (buf[19] & 0xff); int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) | ((buf[22] & 0xff) << 8) | (buf[23] & 0xff); float latitude = Float.intBitsToFloat(ilat); float longitude = Float.intBitsToFloat(ilon); float cx = Float.intBitsToFloat(icx); float cy = Float.intBitsToFloat(icy); float cz = Float.intBitsToFloat(icz); City city = new City(name, tzid, rawOffset, latitude, longitude, cx, cy, cz); cities.put(name, city); citiesByRawOffset[i] = city; } } /** * Returns the cities, ordered by name. */ public static City[] getCitiesByName() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This requires reading the entire time zone database * behind the scenes. */ public static City[] getCitiesByOffset() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities, new Comparator<City>() { public int compare(City c1, City c2) { long now = System.currentTimeMillis(); TimeZone tz1 = c1.getTimeZone(); TimeZone tz2 = c2.getTimeZone(); int off1 = tz1.getOffset(now); int off2 = tz2.getOffset(now); if (off1 == off2) { float dlat = c2.getLatitude() - c1.getLatitude(); if (dlat < 0.0f) return -1; if (dlat > 0.0f) return 1; return 0; } return off1 - off2; } }); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This does not require reading the time zone database * since the cities are pre-sorted. */ public static City[] getCitiesByRawOffset() { return citiesByRawOffset; } /** * Returns an Iterator over all cities, in raw offset order. */ public static Iterator<City> iterator() { return cities.values().iterator(); } /** * Returns the total number of cities. */ public static int numCities() { return cities.size(); } /** * Constructs a city with the given name, time zone name, raw offset, * latitude, longitude, and 3D (X, Y, Z) coordinate. */ public City(String name, String timeZoneID, int rawOffset, float latitude, float longitude, float x, float y, float z) { this.name = name; this.timeZoneID = timeZoneID; this.rawOffset = rawOffset; this.latitude = latitude; this.longitude = longitude; this.x = x; this.y = y; this.z = z; } public String getName() { return name; } public TimeZone getTimeZone() { if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone; } public float getLongitude() { return longitude; } public float getLatitude() { return latitude; } public float getX() { return x; } public float getY() { return y; } public float getZ() { return z; } public float getRawOffset() { return rawOffset / 3600000.0f; } public int getRawOffsetMillis() { return rawOffset; } /** * Returns this city's offset from UTC, taking summer/daylight savigns * time into account. */ public float getOffset() { long now = System.currentTimeMillis(); if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone.getOffset(now) / 3600000.0f; } /** * Compares this city to another by name. */ public int compareTo(City o) { return name.compareTo(o.name); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.text.DateFormat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.text.format.DateUtils; //import android.text.format.DateFormat; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; /** * A class that draws an analog clock face with information about the current * time in a given city. */ public class Clock { static final int MILLISECONDS_PER_MINUTE = 60 * 1000; static final int MILLISECONDS_PER_HOUR = 60 * 60 * 1000; private City mCity = null; private long mCitySwitchTime; private long mTime; private float mColorRed = 1.0f; private float mColorGreen = 1.0f; private float mColorBlue = 1.0f; private long mOldOffset; private Interpolator mClockHandInterpolator = new AccelerateDecelerateInterpolator(); public Clock() { // Empty constructor } /** * Adds a line to the given Path. The line extends from * radius r0 to radius r1 about the center point (cx, cy), * at an angle given by pos. * * @param path the Path to draw to * @param radius the radius of the outer rim of the clock * @param pos the angle, with 0 and 1 at 12:00 * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param r0 the starting radius for the line * @param r1 the ending radius for the line */ private static void drawLine(Path path, float radius, float pos, float cx, float cy, float r0, float r1) { float theta = pos * Shape.TWO_PI - Shape.PI_OVER_TWO; float dx = (float) Math.cos(theta); float dy = (float) Math.sin(theta); float p0x = cx + dx * r0; float p0y = cy + dy * r0; float p1x = cx + dx * r1; float p1y = cy + dy * r1; float ox = (p1y - p0y); float oy = -(p1x - p0x); float norm = (radius / 2.0f) / (float) Math.sqrt(ox * ox + oy * oy); ox *= norm; oy *= norm; path.moveTo(p0x - ox, p0y - oy); path.lineTo(p1x - ox, p1y - oy); path.lineTo(p1x + ox, p1y + oy); path.lineTo(p0x + ox, p0y + oy); path.close(); } /** * Adds a vertical arrow to the given Path. * * @param path the Path to draw to */ private static void drawVArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx - width / 2.0f, cy); path.lineTo(cx, cy + height); path.lineTo(cx + width / 2.0f, cy); path.close(); } /** * Adds a horizontal arrow to the given Path. * * @param path the Path to draw to */ private static void drawHArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx, cy - height / 2.0f); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height / 2.0f); path.close(); } /** * Returns an offset in milliseconds to be subtracted from the current time * in order to obtain an smooth interpolation between the previously * displayed time and the current time. */ private long getOffset(float lerp) { long doffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR - mOldOffset); int sign; if (doffset < 0) { doffset = -doffset; sign = -1; } else { sign = 1; } while (doffset > 12L * MILLISECONDS_PER_HOUR) { doffset -= 12L * MILLISECONDS_PER_HOUR; } if (doffset > 6L * MILLISECONDS_PER_HOUR) { doffset = 12L * MILLISECONDS_PER_HOUR - doffset; sign = -sign; } // Interpolate doffset towards 0 doffset = (long)((1.0f - lerp)*doffset); // Keep the same seconds count long dh = doffset / (MILLISECONDS_PER_HOUR); doffset -= dh * MILLISECONDS_PER_HOUR; long dm = doffset / MILLISECONDS_PER_MINUTE; doffset = sign * (60 * dh + dm) * MILLISECONDS_PER_MINUTE; return doffset; } /** * Set the city to be displayed. setCity(null) resets things so the clock * hand animation won't occur next time. */ public void setCity(City city) { if (mCity != city) { if (mCity != null) { mOldOffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR); } else if (city != null) { mOldOffset = (long) (city.getOffset() * (float) MILLISECONDS_PER_HOUR); } else { mOldOffset = 0L; // this will never be used } this.mCitySwitchTime = System.currentTimeMillis(); this.mCity = city; } } public void setTime(long time) { this.mTime = time; } /** * Draws the clock face. * * @param canvas the Canvas to draw to * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param radius the radius of the clock face * @param alpha the translucency of the clock face * @param textAlpha the translucency of the text * @param showCityName if true, display the city name * @param showTime if true, display the time digitally * @param showUpArrow if true, display an up arrow * @param showDownArrow if true, display a down arrow * @param showLeftRightArrows if true, display left and right arrows * @param prefixChars number of characters of the city name to draw in bold */ public void drawClock(Canvas canvas, float cx, float cy, float radius, float alpha, float textAlpha, boolean showCityName, boolean showTime, boolean showUpArrow, boolean showDownArrow, boolean showLeftRightArrows, int prefixChars) { Paint paint = new Paint(); paint.setAntiAlias(true); int iradius = (int)radius; TimeZone tz = mCity.getTimeZone(); // Compute an interpolated time to animate between the previously // displayed time and the current time float lerp = Math.min(1.0f, (System.currentTimeMillis() - mCitySwitchTime) / 500.0f); lerp = mClockHandInterpolator.getInterpolation(lerp); long doffset = lerp < 1.0f ? getOffset(lerp) : 0L; // Determine the interpolated time for the given time zone Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(mTime - doffset); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); int milli = cal.get(Calendar.MILLISECOND); float offset = tz.getRawOffset() / (float) MILLISECONDS_PER_HOUR; float daylightOffset = tz.inDaylightTime(new Date(mTime)) ? tz.getDSTSavings() / (float) MILLISECONDS_PER_HOUR : 0.0f; float absOffset = offset < 0 ? -offset : offset; int offsetH = (int) absOffset; int offsetM = (int) (60.0f * (absOffset - offsetH)); hour %= 12; // Get the city name and digital time strings String cityName = mCity.getName(); cal.setTimeInMillis(mTime); //java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(this.getApplicationContext()); DateFormat mTimeFormat = DateFormat.getTimeInstance(); String time = mTimeFormat.format(cal.getTimeInMillis()) + " " + DateUtils.getDayOfWeekString(cal.get(Calendar.DAY_OF_WEEK), DateUtils.LENGTH_SHORT) + " " + " (UTC" + (offset >= 0 ? "+" : "-") + offsetH + (offsetM == 0 ? "" : ":" + offsetM) + (daylightOffset == 0 ? "" : "+" + daylightOffset) + ")"; float th = paint.getTextSize(); float tw; // Set the text color paint.setARGB((int) (textAlpha * 255.0f), (int) (mColorRed * 255.0f), (int) (mColorGreen * 255.0f), (int) (mColorBlue * 255.0f)); tw = paint.measureText(cityName); if (showCityName) { // Increment prefixChars to include any spaces for (int i = 0; i < prefixChars; i++) { if (cityName.charAt(i) == ' ') { ++prefixChars; } } // Draw the city name canvas.drawText(cityName, cx - tw / 2, cy - radius - th, paint); // Overstrike the first 'prefixChars' characters canvas.drawText(cityName.substring(0, prefixChars), cx - tw / 2 + 1, cy - radius - th, paint); } tw = paint.measureText(time); if (showTime) { canvas.drawText(time, cx - tw / 2, cy + radius + th + 5, paint); } paint.setARGB((int)(alpha * 255.0f), (int)(mColorRed * 255.0f), (int)(mColorGreen * 255.0f), (int)(mColorBlue * 255.0f)); paint.setStyle(Paint.Style.FILL); canvas.drawOval(new RectF(cx - 2, cy - 2, cx + 2, cy + 2), paint); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(radius * 0.12f); canvas.drawOval(new RectF(cx - iradius, cy - iradius, cx + iradius, cy + iradius), paint); float r0 = radius * 0.1f; float r1 = radius * 0.4f; float r2 = radius * 0.6f; float r3 = radius * 0.65f; float r4 = radius * 0.7f; float r5 = radius * 0.9f; Path path = new Path(); float ss = second + milli / 1000.0f; float mm = minute + ss / 60.0f; float hh = hour + mm / 60.0f; // Tics for the hours for (int i = 0; i < 12; i++) { drawLine(path, radius * 0.12f, i / 12.0f, cx, cy, r4, r5); } // Hour hand drawLine(path, radius * 0.12f, hh / 12.0f, cx, cy, r0, r1); // Minute hand drawLine(path, radius * 0.12f, mm / 60.0f, cx, cy, r0, r2); // Second hand drawLine(path, radius * 0.036f, ss / 60.0f, cx, cy, r0, r3); if (showUpArrow) { drawVArrow(path, cx + radius * 1.13f, cy - radius, radius * 0.15f, -radius * 0.1f); } if (showDownArrow) { drawVArrow(path, cx + radius * 1.13f, cy + radius, radius * 0.15f, radius * 0.1f); } if (showLeftRightArrows) { drawHArrow(path, cx - radius * 1.3f, cy, -radius * 0.1f, radius * 0.15f); drawHArrow(path, cx + radius * 1.3f, cy, radius * 0.1f, radius * 0.15f); } paint.setStyle(Paint.Style.FILL); canvas.drawPath(path, paint); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class representing a set of GL_POINT objects. GlobalTime uses this class * to draw city lights on the night side of the earth. */ public class PointCloud extends Shape { /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. */ public PointCloud(int[] vertices) { this(vertices, 0, vertices.length); } /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. * @param off the starting offset of the vertices array * @param len the number of elements of the vertices array to use */ public PointCloud(int[] vertices, int off, int len) { super(GL10.GL_POINTS, GL10.GL_UNSIGNED_SHORT, false, false, false); int numPoints = len / 3; short[] indices = new short[numPoints]; for (int i = 0; i < numPoints; i++) { indices[i] = (short)i; } allocateBuffers(vertices, null, null, null, indices); this.mNumIndices = mIndexBuffer.capacity(); } @Override public int getNumTriangles() { return mNumIndices * 2; } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL10; /** * An abstract superclass for various three-dimensional objects to be drawn * using OpenGL ES. Each subclass is responsible for setting up NIO buffers * containing vertices, texture coordinates, colors, normals, and indices. * The {@link #draw(GL10)} method draws the object to the given OpenGL context. */ public abstract class Shape { public static final int INT_BYTES = 4; public static final int SHORT_BYTES = 2; public static final float DEGREES_TO_RADIANS = (float) Math.PI / 180.0f; public static final float PI = (float) Math.PI; public static final float TWO_PI = (float) (2.0 * Math.PI); public static final float PI_OVER_TWO = (float) (Math.PI / 2.0); protected int mPrimitive; protected int mIndexDatatype; protected boolean mEmitTextureCoordinates; protected boolean mEmitNormals; protected boolean mEmitColors; protected IntBuffer mVertexBuffer; protected IntBuffer mTexcoordBuffer; protected IntBuffer mColorBuffer; protected IntBuffer mNormalBuffer; protected Buffer mIndexBuffer; protected int mNumIndices = -1; /** * Constructs a Shape. * * @param primitive a GL primitive type understood by glDrawElements, * such as GL10.GL_TRIANGLES * @param indexDatatype the GL datatype for the index buffer, such as * GL10.GL_UNSIGNED_SHORT * @param emitTextureCoordinates true to enable use of the texture * coordinate buffer * @param emitNormals true to enable use of the normal buffer * @param emitColors true to enable use of the color buffer */ protected Shape(int primitive, int indexDatatype, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { mPrimitive = primitive; mIndexDatatype = indexDatatype; mEmitTextureCoordinates = emitTextureCoordinates; mEmitNormals = emitNormals; mEmitColors = emitColors; } /** * Converts the given floating-point value to fixed-point. */ public static int toFixed(float x) { return (int) (x * 65536.0); } /** * Converts the given fixed-point value to floating-point. */ public static float toFloat(int x) { return (float) (x / 65536.0); } /** * Computes the cross-product of two vectors p and q and places * the result in out. */ public static void cross(float[] p, float[] q, float[] out) { out[0] = p[1] * q[2] - p[2] * q[1]; out[1] = p[2] * q[0] - p[0] * q[2]; out[2] = p[0] * q[1] - p[1] * q[0]; } /** * Returns the length of a vector, given as three floats. */ public static float length(float vx, float vy, float vz) { return (float) Math.sqrt(vx * vx + vy * vy + vz * vz); } /** * Returns the length of a vector, given as an array of three floats. */ public static float length(float[] v) { return length(v[0], v[1], v[2]); } /** * Normalizes the given vector of three floats to have length == 1.0. * Vectors with length zero are unaffected. */ public static void normalize(float[] v) { float length = length(v); if (length != 0.0f) { float norm = 1.0f / length; v[0] *= norm; v[1] *= norm; v[2] *= norm; } } /** * Returns the number of triangles associated with this shape. */ public int getNumTriangles() { if (mPrimitive == GL10.GL_TRIANGLES) { return mIndexBuffer.capacity() / 3; } else if (mPrimitive == GL10.GL_TRIANGLE_STRIP) { return mIndexBuffer.capacity() - 2; } return 0; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of short indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, short[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * SHORT_BYTES); ibb.order(ByteOrder.nativeOrder()); ShortBuffer shortIndexBuffer = ibb.asShortBuffer(); shortIndexBuffer.put(indices); shortIndexBuffer.position(0); this.mIndexBuffer = shortIndexBuffer; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of int indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, int[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * INT_BYTES); ibb.order(ByteOrder.nativeOrder()); IntBuffer intIndexBuffer = ibb.asIntBuffer(); intIndexBuffer.put(indices); intIndexBuffer.position(0); this.mIndexBuffer = intIndexBuffer; } /** * Allocate the vertex, texture coordinate, normal, and color buffer. */ private void allocate(int[] vertices, int[] texcoords, int[] normals, int[] colors) { ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * INT_BYTES); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer = vbb.asIntBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); if ((texcoords != null) && mEmitTextureCoordinates) { ByteBuffer tbb = ByteBuffer.allocateDirect(texcoords.length * INT_BYTES); tbb.order(ByteOrder.nativeOrder()); mTexcoordBuffer = tbb.asIntBuffer(); mTexcoordBuffer.put(texcoords); mTexcoordBuffer.position(0); } if ((normals != null) && mEmitNormals) { ByteBuffer nbb = ByteBuffer.allocateDirect(normals.length * INT_BYTES); nbb.order(ByteOrder.nativeOrder()); mNormalBuffer = nbb.asIntBuffer(); mNormalBuffer.put(normals); mNormalBuffer.position(0); } if ((colors != null) && mEmitColors) { ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * INT_BYTES); cbb.order(ByteOrder.nativeOrder()); mColorBuffer = cbb.asIntBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); } } /** * Draws the shape to the given OpenGL ES 1.0 context. Texture coordinates, * normals, and colors are emitted according the the preferences set for * this shape. */ public void draw(GL10 gl) { gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (mEmitTextureCoordinates) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexcoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (mEmitNormals) { gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_FIXED, 0, mNormalBuffer); } else { gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } if (mEmitColors) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } gl.glDrawElements(mPrimitive, mNumIndices > 0 ? mNumIndices : mIndexBuffer.capacity(), mIndexDatatype, mIndexBuffer); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class that draws a ring with a given center and inner and outer radii. * The inner and outer rings each have a color and the remaining pixels are * colored by interpolation. GlobalTime uses this class to simulate an * "atmosphere" around the earth. */ public class Annulus extends Shape { /** * Constructs an annulus. * * @param centerX the X coordinate of the center point * @param centerY the Y coordinate of the center point * @param Z the fixed Z for the entire ring * @param innerRadius the inner radius * @param outerRadius the outer radius * @param rInner the red channel of the color of the inner ring * @param gInner the green channel of the color of the inner ring * @param bInner the blue channel of the color of the inner ring * @param aInner the alpha channel of the color of the inner ring * @param rOuter the red channel of the color of the outer ring * @param gOuter the green channel of the color of the outer ring * @param bOuter the blue channel of the color of the outer ring * @param aOuter the alpha channel of the color of the outer ring * @param sectors the number of sectors used to approximate curvature */ public Annulus(float centerX, float centerY, float Z, float innerRadius, float outerRadius, float rInner, float gInner, float bInner, float aInner, float rOuter, float gOuter, float bOuter, float aOuter, int sectors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, false, false, true); int radii = sectors + 1; int[] vertices = new int[2 * 3 * radii]; int[] colors = new int[2 * 4 * radii]; short[] indices = new short[2 * 3 * radii]; int vidx = 0; int cidx = 0; int iidx = 0; for (int i = 0; i < radii; i++) { float theta = (i * TWO_PI) / (radii - 1); float cosTheta = (float) Math.cos(theta); float sinTheta = (float) Math.sin(theta); vertices[vidx++] = toFixed(centerX + innerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + innerRadius * sinTheta); vertices[vidx++] = toFixed(Z); vertices[vidx++] = toFixed(centerX + outerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + outerRadius * sinTheta); vertices[vidx++] = toFixed(Z); colors[cidx++] = toFixed(rInner); colors[cidx++] = toFixed(gInner); colors[cidx++] = toFixed(bInner); colors[cidx++] = toFixed(aInner); colors[cidx++] = toFixed(rOuter); colors[cidx++] = toFixed(gOuter); colors[cidx++] = toFixed(bOuter); colors[cidx++] = toFixed(aOuter); } for (int i = 0; i < sectors; i++) { indices[iidx++] = (short) (2 * i); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 2); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 3); indices[iidx++] = (short) (2 * i + 2); } allocateBuffers(vertices, null, null, colors, indices); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.microedition.khronos.egl.*; import javax.microedition.khronos.opengles.*; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Canvas; import android.opengl.Object3D; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.MessageQueue; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; /** * The main View of the GlobalTime Activity. */ class GTView extends SurfaceView implements SurfaceHolder.Callback { /** * A TimeZone object used to compute the current UTC time. */ private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("utc"); /** * The Sun's color is close to that of a 5780K blackbody. */ private static final float[] SUNLIGHT_COLOR = { 1.0f, 0.9375f, 0.91015625f, 1.0f }; /** * The inclination of the earth relative to the plane of the ecliptic * is 23.45 degrees. */ private static final float EARTH_INCLINATION = 23.45f * Shape.PI / 180.0f; /** Seconds in a day */ private static final int SECONDS_PER_DAY = 24 * 60 * 60; /** Flag for the depth test */ private static final boolean PERFORM_DEPTH_TEST= false; /** Use raw time zone offsets, disregarding "summer time." If false, * current offsets will be used, which requires a much longer startup time * in order to sort the city database. */ private static final boolean USE_RAW_OFFSETS = true; /** * The earth's atmosphere. */ private static final Annulus ATMOSPHERE = new Annulus(0.0f, 0.0f, 1.75f, 0.9f, 1.08f, 0.4f, 0.4f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 50); /** * The tesselation of the earth by latitude. */ private static final int SPHERE_LATITUDES = 25; /** * The tesselation of the earth by longitude. */ private static int SPHERE_LONGITUDES = 25; /** * A flattened version of the earth. The normals are computed identically * to those of the round earth, allowing the day/night lighting to be * applied to the flattened surface. */ private static Sphere worldFlat = new LatLongSphere(0.0f, 0.0f, 0.0f, 1.0f, SPHERE_LATITUDES, SPHERE_LONGITUDES, 0.0f, 360.0f, true, true, false, true); /** * The earth. */ private Object3D mWorld; /** * Geometry of the city lights */ private PointCloud mLights; /** * True if the activiy has been initialized. */ boolean mInitialized = false; /** * True if we're in alphabetic entry mode. */ private boolean mAlphaKeySet = false; private EGLContext mEGLContext; private EGLSurface mEGLSurface; private EGLDisplay mEGLDisplay; private EGLConfig mEGLConfig; GLView mGLView; // Rotation and tilt of the Earth private float mRotAngle = 0.0f; private float mTiltAngle = 0.0f; // Rotational velocity of the orbiting viewer private float mRotVelocity = 1.0f; // Rotation of the flat view private float mWrapX = 0.0f; private float mWrapVelocity = 0.0f; private float mWrapVelocityFactor = 0.01f; // Toggle switches private boolean mDisplayAtmosphere = true; private boolean mDisplayClock = false; private boolean mClockShowing = false; private boolean mDisplayLights = false; private boolean mDisplayWorld = true; private boolean mDisplayWorldFlat = false; private boolean mSmoothShading = true; // City search string private String mCityName = ""; // List of all cities private List<City> mClockCities; // List of cities matching a user-supplied prefix private List<City> mCityNameMatches = new ArrayList<City>(); private List<City> mCities; // Start time for clock fade animation private long mClockFadeTime; // Interpolator for clock fade animation private Interpolator mClockSizeInterpolator = new DecelerateInterpolator(1.0f); // Index of current clock private int mCityIndex; // Current clock private Clock mClock; // City-to-city flight animation parameters private boolean mFlyToCity = false; private long mCityFlyStartTime; private float mCityFlightTime; private float mRotAngleStart, mRotAngleDest; private float mTiltAngleStart, mTiltAngleDest; // Interpolator for flight motion animation private Interpolator mFlyToCityInterpolator = new AccelerateDecelerateInterpolator(); private static int sNumLights; private static int[] sLightCoords; // static Map<Float,int[]> cityCoords = new HashMap<Float,int[]>(); // Arrays for GL calls private float[] mClipPlaneEquation = new float[4]; private float[] mLightDir = new float[4]; // Calendar for computing the Sun's position Calendar mSunCal = Calendar.getInstance(UTC_TIME_ZONE); // Triangles drawn per frame private int mNumTriangles; private long startTime; private static final int MOTION_NONE = 0; private static final int MOTION_X = 1; private static final int MOTION_Y = 2; private static final int MIN_MANHATTAN_DISTANCE = 20; private static final float ROTATION_FACTOR = 1.0f / 30.0f; private static final float TILT_FACTOR = 0.35f; // Touchscreen support private float mMotionStartX; private float mMotionStartY; private float mMotionStartRotVelocity; private float mMotionStartTiltAngle; private int mMotionDirection; public void surfaceCreated(SurfaceHolder holder) { EGL10 egl = (EGL10)EGLContext.getEGL(); mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, this, null); egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext); } public void surfaceDestroyed(SurfaceHolder holder) { // nothing to do } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // nothing to do } /** * Set up the view. * * @param context the Context * @param am an AssetManager to retrieve the city database from */ public GTView(Context context) { super(context); getHolder().addCallback(this); getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU); AssetManager am = context.getAssets(); startTime = System.currentTimeMillis(); EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE }; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config); mEGLConfig = configs[0]; mEGLContext = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null); mEGLDisplay = dpy; mClock = new Clock(); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); try { loadAssets(am); } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException(ioe); } catch (ArrayIndexOutOfBoundsException aioobe) { aioobe.printStackTrace(); throw new RuntimeException(aioobe); } } /** * Destroy the view. */ public void destroy() { EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglMakeCurrent(mEGLDisplay, egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT); egl.eglDestroyContext(mEGLDisplay, mEGLContext); egl.eglDestroySurface(mEGLDisplay, mEGLSurface); egl.eglTerminate(mEGLDisplay); mEGLContext = null; } /** * Begin animation. */ public void startAnimating() { mHandler.sendEmptyMessage(INVALIDATE); } /** * Quit animation. */ public void stopAnimating() { mHandler.removeMessages(INVALIDATE); } /** * Read a two-byte integer from the input stream. */ private int readInt16(InputStream is) throws IOException { int lo = is.read(); int hi = is.read(); return (hi << 8) | lo; } /** * Returns the offset from UTC for the given city. If USE_RAW_OFFSETS * is true, summer/daylight savings is ignored. */ private static float getOffset(City c) { return USE_RAW_OFFSETS ? c.getRawOffset() : c.getOffset(); } private InputStream cache(InputStream is) throws IOException { int nbytes = is.available(); byte[] data = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += is.read(data, nread, nbytes - nread); } return new ByteArrayInputStream(data); } /** * Load the city and lights databases. * * @param am the AssetManager to load from. */ private void loadAssets(final AssetManager am) throws IOException { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); InputStream cis = null; try { // Look for (e.g.) cities_fr_FR.dat or cities_fr_CA.dat cis = am.open("cities_" + language + "_" + country + ".dat"); } catch (FileNotFoundException e1) { try { // Look for (e.g.) cities_fr.dat or cities_fr.dat cis = am.open("cities_" + language + ".dat"); } catch (FileNotFoundException e2) { try { // Use English city names by default cis = am.open("cities_en.dat"); } catch (FileNotFoundException e3) { throw e3; } } } cis = cache(cis); City.loadCities(cis); City[] cities; if (USE_RAW_OFFSETS) { cities = City.getCitiesByRawOffset(); } else { cities = City.getCitiesByOffset(); } mClockCities = new ArrayList<City>(cities.length); for (int i = 0; i < cities.length; i++) { mClockCities.add(cities[i]); } mCities = mClockCities; mCityIndex = 0; this.mWorld = new Object3D() { @Override public InputStream readFile(String filename) throws IOException { return cache(am.open(filename)); } }; mWorld.load("world.gles"); // lights.dat has the following format. All integers // are 16 bits, low byte first. // // width // height // N [# of lights] // light 0 X [in the range 0 to (width - 1)] // light 0 Y ]in the range 0 to (height - 1)] // light 1 X [in the range 0 to (width - 1)] // light 1 Y ]in the range 0 to (height - 1)] // ... // light (N - 1) X [in the range 0 to (width - 1)] // light (N - 1) Y ]in the range 0 to (height - 1)] // // For a larger number of lights, it could make more // sense to store the light positions in a bitmap // and extract them manually InputStream lis = am.open("lights.dat"); lis = cache(lis); int lightWidth = readInt16(lis); int lightHeight = readInt16(lis); sNumLights = readInt16(lis); sLightCoords = new int[3 * sNumLights]; int lidx = 0; float lightRadius = 1.009f; float lightScale = 65536.0f * lightRadius; float[] cosTheta = new float[lightWidth]; float[] sinTheta = new float[lightWidth]; float twoPi = (float) (2.0 * Math.PI); float scaleW = twoPi / lightWidth; for (int i = 0; i < lightWidth; i++) { float theta = twoPi - i * scaleW; cosTheta[i] = (float)Math.cos(theta); sinTheta[i] = (float)Math.sin(theta); } float[] cosPhi = new float[lightHeight]; float[] sinPhi = new float[lightHeight]; float scaleH = (float) (Math.PI / lightHeight); for (int j = 0; j < lightHeight; j++) { float phi = j * scaleH; cosPhi[j] = (float)Math.cos(phi); sinPhi[j] = (float)Math.sin(phi); } int nbytes = 4 * sNumLights; byte[] ilights = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += lis.read(ilights, nread, nbytes - nread); } int idx = 0; for (int i = 0; i < sNumLights; i++) { int lx = (((ilights[idx + 1] & 0xff) << 8) | (ilights[idx ] & 0xff)); int ly = (((ilights[idx + 3] & 0xff) << 8) | (ilights[idx + 2] & 0xff)); idx += 4; float sin = sinPhi[ly]; float x = cosTheta[lx]*sin; float y = cosPhi[ly]; float z = sinTheta[lx]*sin; sLightCoords[lidx++] = (int) (x * lightScale); sLightCoords[lidx++] = (int) (y * lightScale); sLightCoords[lidx++] = (int) (z * lightScale); } mLights = new PointCloud(sLightCoords); } /** * Returns true if two time zone offsets are equal. We assume distinct * time zone offsets will differ by at least a few minutes. */ private boolean tzEqual(float o1, float o2) { return Math.abs(o1 - o2) < 0.001; } /** * Move to a different time zone. * * @param incr The increment between the current and future time zones. */ private void shiftTimeZone(int incr) { // If only 1 city in the current set, there's nowhere to go if (mCities.size() <= 1) { return; } float offset = getOffset(mCities.get(mCityIndex)); do { mCityIndex = (mCityIndex + mCities.size() + incr) % mCities.size(); } while (tzEqual(getOffset(mCities.get(mCityIndex)), offset)); offset = getOffset(mCities.get(mCityIndex)); locateCity(true, offset); goToCity(); } /** * Returns true if there is another city within the current time zone * that is the given increment away from the current city. * * @param incr the increment, +1 or -1 * @return */ private boolean atEndOfTimeZone(int incr) { if (mCities.size() <= 1) { return true; } float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { return false; } return true; } /** * Shifts cities within the current time zone. * * @param incr the increment, +1 or -1 */ private void shiftWithinTimeZone(int incr) { float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { mCityIndex = nindex; goToCity(); } } /** * Returns true if the city name matches the given prefix, ignoring spaces. */ private boolean nameMatches(City city, String prefix) { String cityName = city.getName().replaceAll("[ ]", ""); return prefix.regionMatches(true, 0, cityName, 0, prefix.length()); } /** * Returns true if there are cities matching the given name prefix. */ private boolean hasMatches(String prefix) { for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, prefix)) { return true; } } return false; } /** * Shifts to the nearest city that matches the new prefix. */ private void shiftByName() { // Attempt to keep current city if it matches City finalCity = null; City currCity = mCities.get(mCityIndex); if (nameMatches(currCity, mCityName)) { finalCity = currCity; } mCityNameMatches.clear(); for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, mCityName)) { mCityNameMatches.add(city); } } mCities = mCityNameMatches; if (finalCity != null) { for (int i = 0; i < mCityNameMatches.size(); i++) { if (mCityNameMatches.get(i) == finalCity) { mCityIndex = i; break; } } } else { // Find the closest matching city locateCity(false, 0.0f); } goToCity(); } /** * Increases or decreases the rotational speed of the earth. */ private void incrementRotationalVelocity(float incr) { if (mDisplayWorldFlat) { mWrapVelocity -= incr; } else { mRotVelocity -= incr; } } /** * Clears the current matching prefix, while keeping the focus on * the current city. */ private void clearCityMatches() { // Determine the global city index that matches the current city if (mCityNameMatches.size() > 0) { City city = mCityNameMatches.get(mCityIndex); for (int i = 0; i < mClockCities.size(); i++) { City ncity = mClockCities.get(i); if (city.equals(ncity)) { mCityIndex = i; break; } } } mCityName = ""; mCityNameMatches.clear(); mCities = mClockCities; goToCity(); } /** * Fade the clock in or out. */ private void enableClock(boolean enabled) { mClockFadeTime = System.currentTimeMillis(); mDisplayClock = enabled; mClockShowing = true; mAlphaKeySet = enabled; if (enabled) { // Find the closest matching city locateCity(false, 0.0f); } clearCityMatches(); } /** * Use the touchscreen to alter the rotational velocity or the * tilt of the earth. */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mMotionStartX = event.getX(); mMotionStartY = event.getY(); mMotionStartRotVelocity = mDisplayWorldFlat ? mWrapVelocity : mRotVelocity; mMotionStartTiltAngle = mTiltAngle; // Stop the rotation if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_MOVE: // Disregard motion events when the clock is displayed float dx = event.getX() - mMotionStartX; float dy = event.getY() - mMotionStartY; float delx = Math.abs(dx); float dely = Math.abs(dy); // Determine the direction of motion (major axis) // Once if has been determined, it's locked in until // we receive ACTION_UP or ACTION_CANCEL if ((mMotionDirection == MOTION_NONE) && (delx + dely > MIN_MANHATTAN_DISTANCE)) { if (delx > dely) { mMotionDirection = MOTION_X; } else { mMotionDirection = MOTION_Y; } } // If the clock is displayed, don't actually rotate or tilt; // just use mMotionDirection to record whether motion occurred if (!mDisplayClock) { if (mMotionDirection == MOTION_X) { if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } else { mRotVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } mClock.setCity(null); } else if (mMotionDirection == MOTION_Y && !mDisplayWorldFlat) { mTiltAngle = mMotionStartTiltAngle + dy * TILT_FACTOR; if (mTiltAngle < -90.0f) { mTiltAngle = -90.0f; } if (mTiltAngle > 90.0f) { mTiltAngle = 90.0f; } mClock.setCity(null); } } break; case MotionEvent.ACTION_UP: mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_CANCEL: mTiltAngle = mMotionStartTiltAngle; if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity; } else { mRotVelocity = mMotionStartRotVelocity; } mMotionDirection = MOTION_NONE; break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mInitialized && mGLView.processKey(keyCode)) { boolean drawing = (mClockShowing || mGLView.hasMessages()); this.setWillNotDraw(!drawing); return true; } boolean handled = false; // If we're not in alphabetical entry mode, convert letters // to their digit equivalents if (!mAlphaKeySet) { char numChar = event.getNumber(); if (numChar >= '0' && numChar <= '9') { keyCode = KeyEvent.KEYCODE_0 + (numChar - '0'); } } switch (keyCode) { // The 'space' key toggles the clock case KeyEvent.KEYCODE_SPACE: mAlphaKeySet = !mAlphaKeySet; enableClock(mAlphaKeySet); handled = true; break; // The 'left' and 'right' buttons shift time zones if the clock is // displayed, otherwise they alters the rotational speed of the earthh case KeyEvent.KEYCODE_DPAD_LEFT: if (mDisplayClock) { shiftTimeZone(-1); } else { mClock.setCity(null); incrementRotationalVelocity(1.0f); } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (mDisplayClock) { shiftTimeZone(1); } else { mClock.setCity(null); incrementRotationalVelocity(-1.0f); } handled = true; break; // The 'up' and 'down' buttons shift cities within a time zone if the // clock is displayed, otherwise they tilt the earth case KeyEvent.KEYCODE_DPAD_UP: if (mDisplayClock) { shiftWithinTimeZone(-1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle += 360.0f / 48.0f; } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: if (mDisplayClock) { shiftWithinTimeZone(1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle -= 360.0f / 48.0f; } } handled = true; break; // The center key stops the earth's rotation, then toggles between the // round and flat views of the earth case KeyEvent.KEYCODE_DPAD_CENTER: if ((!mDisplayWorldFlat && mRotVelocity == 0.0f) || (mDisplayWorldFlat && mWrapVelocity == 0.0f)) { mDisplayWorldFlat = !mDisplayWorldFlat; } else { if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } } handled = true; break; // The 'L' key toggles the city lights case KeyEvent.KEYCODE_L: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayLights = !mDisplayLights; handled = true; } break; // The 'W' key toggles the earth (just for fun) case KeyEvent.KEYCODE_W: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayWorld = !mDisplayWorld; handled = true; } break; // The 'A' key toggles the atmosphere case KeyEvent.KEYCODE_A: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayAtmosphere = !mDisplayAtmosphere; handled = true; } break; // The '2' key zooms out case KeyEvent.KEYCODE_2: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(-2); handled = true; } break; // The '8' key zooms in case KeyEvent.KEYCODE_8: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(2); handled = true; } break; } // Handle letters in city names if (!handled && mAlphaKeySet) { switch (keyCode) { // Add a letter to the city name prefix case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_B: case KeyEvent.KEYCODE_C: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_F: case KeyEvent.KEYCODE_G: case KeyEvent.KEYCODE_H: case KeyEvent.KEYCODE_I: case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_K: case KeyEvent.KEYCODE_L: case KeyEvent.KEYCODE_M: case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_O: case KeyEvent.KEYCODE_P: case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_R: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_T: case KeyEvent.KEYCODE_U: case KeyEvent.KEYCODE_V: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_X: case KeyEvent.KEYCODE_Y: case KeyEvent.KEYCODE_Z: char c = (char)(keyCode - KeyEvent.KEYCODE_A + 'A'); if (hasMatches(mCityName + c)) { mCityName += c; shiftByName(); } handled = true; break; // Remove a letter from the city name prefix case KeyEvent.KEYCODE_DEL: if (mCityName.length() > 0) { mCityName = mCityName.substring(0, mCityName.length() - 1); shiftByName(); } else { clearCityMatches(); } handled = true; break; // Clear the city name prefix case KeyEvent.KEYCODE_ENTER: clearCityMatches(); handled = true; break; } } boolean drawing = (mClockShowing || ((mGLView != null) && (mGLView.hasMessages()))); this.setWillNotDraw(!drawing); // Let the system handle other keypresses if (!handled) { return super.onKeyDown(keyCode, event); } return true; } /** * Initialize OpenGL ES drawing. */ private synchronized void init(GL10 gl) { mGLView = new GLView(); mGLView.setNearFrustum(5.0f); mGLView.setFarFrustum(50.0f); mGLView.setLightModelAmbientIntensity(0.225f); mGLView.setAmbientIntensity(0.0f); mGLView.setDiffuseIntensity(1.5f); mGLView.setDiffuseColor(SUNLIGHT_COLOR); mGLView.setSpecularIntensity(0.0f); mGLView.setSpecularColor(SUNLIGHT_COLOR); if (PERFORM_DEPTH_TEST) { gl.glEnable(GL10.GL_DEPTH_TEST); } gl.glDisable(GL10.GL_SCISSOR_TEST); gl.glClearColor(0, 0, 0, 1); gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); mInitialized = true; } /** * Computes the vector from the center of the earth to the sun for a * particular moment in time. */ private void computeSunDirection() { mSunCal.setTimeInMillis(System.currentTimeMillis()); int day = mSunCal.get(Calendar.DAY_OF_YEAR); int seconds = 3600 * mSunCal.get(Calendar.HOUR_OF_DAY) + 60 * mSunCal.get(Calendar.MINUTE) + mSunCal.get(Calendar.SECOND); day += (float) seconds / SECONDS_PER_DAY; // Approximate declination of the sun, changes sinusoidally // during the year. The winter solstice occurs 10 days before // the start of the year. float decl = (float) (EARTH_INCLINATION * Math.cos(Shape.TWO_PI * (day + 10) / 365.0)); // Subsolar latitude, convert from (-PI/2, PI/2) -> (0, PI) form float phi = decl + Shape.PI_OVER_TWO; // Subsolar longitude float theta = Shape.TWO_PI * seconds / SECONDS_PER_DAY; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); // Convert from polar to rectangular coordinates float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; // Directional light -> w == 0 mLightDir[0] = x; mLightDir[1] = y; mLightDir[2] = z; mLightDir[3] = 0.0f; } /** * Computes the approximate spherical distance between two * (latitude, longitude) coordinates. */ private float distance(float lat1, float lon1, float lat2, float lon2) { lat1 *= Shape.DEGREES_TO_RADIANS; lat2 *= Shape.DEGREES_TO_RADIANS; lon1 *= Shape.DEGREES_TO_RADIANS; lon2 *= Shape.DEGREES_TO_RADIANS; float r = 6371.0f; // Earth's radius in km float dlat = lat2 - lat1; float dlon = lon2 - lon1; double sinlat2 = Math.sin(dlat / 2.0f); sinlat2 *= sinlat2; double sinlon2 = Math.sin(dlon / 2.0f); sinlon2 *= sinlon2; double a = sinlat2 + Math.cos(lat1) * Math.cos(lat2) * sinlon2; double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return (float) (r * c); } /** * Locates the closest city to the currently displayed center point, * optionally restricting the search to cities within a given time zone. */ private void locateCity(boolean useOffset, float offset) { float mindist = Float.MAX_VALUE; int minidx = -1; for (int i = 0; i < mCities.size(); i++) { City city = mCities.get(i); if (useOffset && !tzEqual(getOffset(city), offset)) { continue; } float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); if (dist < mindist) { mindist = dist; minidx = i; } } mCityIndex = minidx; } /** * Animates the earth to be centered at the current city. */ private void goToCity() { City city = mCities.get(mCityIndex); float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); mFlyToCity = true; mCityFlyStartTime = System.currentTimeMillis(); mCityFlightTime = dist / 5.0f; // 5000 km/sec mRotAngleStart = mRotAngle; mRotAngleDest = city.getLongitude() + 90; if (mRotAngleDest - mRotAngleStart > 180.0f) { mRotAngleDest -= 360.0f; } else if (mRotAngleStart - mRotAngleDest > 180.0f) { mRotAngleDest += 360.0f; } mTiltAngleStart = mTiltAngle; mTiltAngleDest = city.getLatitude(); mRotVelocity = 0.0f; } /** * Returns a linearly interpolated value between two values. */ private float lerp(float a, float b, float lerp) { return a + (b - a)*lerp; } /** * Draws the city lights, using a clip plane to restrict the lights * to the night side of the earth. */ private void drawCityLights(GL10 gl, float brightness) { gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_DITHER); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glPointSize(1.0f); float ls = lerp(0.8f, 0.3f, brightness); gl.glColor4f(ls * 1.0f, ls * 1.0f, ls * 0.8f, 1.0f); if (mDisplayWorld) { mClipPlaneEquation[0] = -mLightDir[0]; mClipPlaneEquation[1] = -mLightDir[1]; mClipPlaneEquation[2] = -mLightDir[2]; mClipPlaneEquation[3] = 0.0f; // Assume we have glClipPlanef() from OpenGL ES 1.1 ((GL11) gl).glClipPlanef(GL11.GL_CLIP_PLANE0, mClipPlaneEquation, 0); gl.glEnable(GL11.GL_CLIP_PLANE0); } mLights.draw(gl); if (mDisplayWorld) { gl.glDisable(GL11.GL_CLIP_PLANE0); } mNumTriangles += mLights.getNumTriangles()*2; } /** * Draws the atmosphere. */ private void drawAtmosphere(GL10 gl) { gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_CULL_FACE); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); // Draw the atmospheric layer float tx = mGLView.getTranslateX(); float ty = mGLView.getTranslateY(); float tz = mGLView.getTranslateZ(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(tx, ty, tz); // Blend in the atmosphere a bit gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); ATMOSPHERE.draw(gl); mNumTriangles += ATMOSPHERE.getNumTriangles(); } /** * Draws the world in a 2D map view. */ private void drawWorldFlat(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); gl.glTranslatef(mWrapX - 2, 0.0f, 0.0f); worldFlat.draw(gl); gl.glTranslatef(2.0f, 0.0f, 0.0f); worldFlat.draw(gl); mNumTriangles += worldFlat.getNumTriangles() * 2; mWrapX += mWrapVelocity * mWrapVelocityFactor; while (mWrapX < 0.0f) { mWrapX += 2.0f; } while (mWrapX > 2.0f) { mWrapX -= 2.0f; } } /** * Draws the world in a 2D round view. */ private void drawWorldRound(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); mWorld.draw(gl); mNumTriangles += mWorld.getNumTriangles(); } /** * Draws the clock. * * @param canvas the Canvas to draw to * @param now the current time * @param w the width of the screen * @param h the height of the screen * @param lerp controls the animation, between 0.0 and 1.0 */ private void drawClock(Canvas canvas, long now, int w, int h, float lerp) { float clockAlpha = lerp(0.0f, 0.8f, lerp); mClockShowing = clockAlpha > 0.0f; if (clockAlpha > 0.0f) { City city = mCities.get(mCityIndex); mClock.setCity(city); mClock.setTime(now); float cx = w / 2.0f; float cy = h / 2.0f; float smallRadius = 18.0f; float bigRadius = 0.75f * 0.5f * Math.min(w, h); float radius = lerp(smallRadius, bigRadius, lerp); // Only display left/right arrows if we are in a name search boolean scrollingByName = (mCityName.length() > 0) && (mCities.size() > 1); mClock.drawClock(canvas, cx, cy, radius, clockAlpha, 1.0f, lerp == 1.0f, lerp == 1.0f, !atEndOfTimeZone(-1), !atEndOfTimeZone(1), scrollingByName, mCityName.length()); } } /** * Draws the 2D layer. */ @Override protected void onDraw(Canvas canvas) { long now = System.currentTimeMillis(); if (startTime != -1) { startTime = -1; } int w = getWidth(); int h = getHeight(); // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); // we don't need to make sure OpenGL rendering is done because // we're drawing in to a different surface drawClock(canvas, now, w, h, lerp); mGLView.showMessages(canvas); mGLView.showStatistics(canvas, w); } /** * Draws the 3D layer. */ protected void drawOpenGLScene() { long now = System.currentTimeMillis(); mNumTriangles = 0; EGL10 egl = (EGL10)EGLContext.getEGL(); GL10 gl = (GL10)mEGLContext.getGL(); if (!mInitialized) { init(gl); } int w = getWidth(); int h = getHeight(); gl.glViewport(0, 0, w, h); gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0); gl.glEnable(GL10.GL_CULL_FACE); gl.glFrontFace(GL10.GL_CCW); float ratio = (float) w / h; mGLView.setAspectRatio(ratio); mGLView.setTextureParameters(gl); if (PERFORM_DEPTH_TEST) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } else { gl.glClear(GL10.GL_COLOR_BUFFER_BIT); } if (mDisplayWorldFlat) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-1.0f, 1.0f, -1.0f / ratio, 1.0f / ratio, 1.0f, 2.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0.0f, 0.0f, -1.0f); } else { mGLView.setProjection(gl); mGLView.setView(gl); } if (!mDisplayWorldFlat) { if (mFlyToCity) { float lerp = (now - mCityFlyStartTime)/mCityFlightTime; if (lerp >= 1.0f) { mFlyToCity = false; } lerp = Math.min(lerp, 1.0f); lerp = mFlyToCityInterpolator.getInterpolation(lerp); mRotAngle = lerp(mRotAngleStart, mRotAngleDest, lerp); mTiltAngle = lerp(mTiltAngleStart, mTiltAngleDest, lerp); } // Rotate the viewpoint around the earth gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glRotatef(mTiltAngle, 1, 0, 0); gl.glRotatef(mRotAngle, 0, 1, 0); // Increment the rotation angle mRotAngle += mRotVelocity; if (mRotAngle < 0.0f) { mRotAngle += 360.0f; } if (mRotAngle > 360.0f) { mRotAngle -= 360.0f; } } // Draw the world with lighting gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, mLightDir, 0); mGLView.setLights(gl, GL10.GL_LIGHT0); if (mDisplayWorldFlat) { drawWorldFlat(gl); } else if (mDisplayWorld) { drawWorldRound(gl); } if (mDisplayLights && !mDisplayWorldFlat) { // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); drawCityLights(gl, lerp); } if (mDisplayAtmosphere && !mDisplayWorldFlat) { drawAtmosphere(gl); } mGLView.setNumTriangles(mNumTriangles); egl.eglSwapBuffers(mEGLDisplay, mEGLSurface); if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) { // we lost the gpu, quit immediately Context c = getContext(); if (c instanceof Activity) { ((Activity)c).finish(); } } } private static final int INVALIDATE = 1; private static final int ONE_MINUTE = 60000; /** * Controls the animation using the message queue. Every time we receive * an INVALIDATE message, we redraw and place another message in the queue. */ private final Handler mHandler = new Handler() { private long mLastSunPositionTime = 0; @Override public void handleMessage(Message msg) { if (msg.what == INVALIDATE) { // Use the message's time, it's good enough and // allows us to avoid a system call. if ((msg.getWhen() - mLastSunPositionTime) >= ONE_MINUTE) { // Recompute the sun's position once per minute // Place the light at the Sun's direction computeSunDirection(); mLastSunPositionTime = msg.getWhen(); } // Draw the GL scene drawOpenGLScene(); // Send an update for the 2D overlay if needed if (mInitialized && (mClockShowing || mGLView.hasMessages())) { invalidate(); } // Just send another message immediately. This works because // drawOpenGLScene() does the timing for us -- it will // block until the last frame has been processed. // The invalidate message we're posting here will be // interleaved properly with motion/key events which // guarantee a prompt reaction to the user input. sendEmptyMessage(INVALIDATE); } } }; } /** * The main activity class for GlobalTime. */ public class GlobalTime extends Activity { GTView gtView = null; private void setGTView() { if (gtView == null) { gtView = new GTView(this); setContentView(gtView); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setGTView(); } @Override protected void onResume() { super.onResume(); setGTView(); Looper.myQueue().addIdleHandler(new Idler()); } @Override protected void onPause() { super.onPause(); gtView.stopAnimating(); } @Override protected void onStop() { super.onStop(); gtView.stopAnimating(); gtView.destroy(); gtView = null; } // Allow the activity to go idle before its animation starts class Idler implements MessageQueue.IdleHandler { public Idler() { super(); } public final boolean queueIdle() { if (gtView != null) { gtView.startAnimating(); } return false; } } }
Java
/* * Copyright (C) 2006-2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import android.graphics.Canvas; import android.graphics.Paint; import android.view.KeyEvent; class Message { private String mText; private long mExpirationTime; public Message(String text, long expirationTime) { this.mText = text; this.mExpirationTime = expirationTime; } public String getText() { return mText; } public long getExpirationTime() { return mExpirationTime; } } /** * A helper class to simplify writing an Activity that renders using * OpenGL ES. * * <p> A GLView object stores common elements of GL state and allows * them to be modified interactively. This is particularly useful for * determining the proper settings of parameters such as the view * frustum and light intensities during application development. * * <p> A GLView is not an actual View; instead, it is meant to be * called from within a View to perform event processing on behalf of the * actual View. * * <p> By passing key events to the GLView object from the View, * the application can automatically allow certain parameters to * be user-controlled from the keyboard. Key events may be passed as * shown below: * * <pre> * GLView mGlView = new GLView(); * * public boolean onKeyDown(int keyCode, KeyEvent event) { * // Hand the key to the GLView object first * if (mGlView.processKey(keyCode)) { * return; * } * * switch (keyCode) { * case KeyEvent.KEY_CODE_X: * // perform app processing * break; * * default: * super.onKeyDown(keyCode, event); * break; * } * } * </pre> * * <p> During drawing of a frame, the GLView object should be given the * opportunity to manage GL parameters as shown below: * * OpenGLContext mGLContext; // initialization not shown * int mNumTrianglesDrawn = 0; * * protected void onDraw(Canvas canvas) { * int w = getWidth(); * int h = getHeight(); * * float ratio = (float) w / h; * mGLView.setAspectRatio(ratio); * * GL10 gl = (GL10) mGLContext.getGL(); * mGLContext.waitNative(canvas, this); * * // Enable a light for the GLView to manipulate * gl.glEnable(GL10.GL_LIGHTING); * gl.glEnable(GL10.GL_LIGHT0); * * // Allow the GLView to set GL parameters * mGLView.setTextureParameters(gl); * mGLView.setProjection(gl); * mGLView.setView(gl); * mGLView.setLights(gl, GL10.GL_LIGHT0); * * // Draw some stuff (not shown) * mNumTrianglesDrawn += <num triangles just drawn>; * * // Wait for GL drawing to complete * mGLContext.waitGL(); * * // Inform the GLView of what was drawn, and ask it to display statistics * mGLView.setNumTriangles(mNumTrianglesDrawn); * mGLView.showMessages(canvas); * mGLView.showStatistics(canvas, w); * } * </pre> * * <p> At the end of each frame, following the call to * GLContext.waitGL, the showStatistics and showMessages methods * will cause additional information to be displayed. * * <p> To enter the interactive command mode, the 'tab' key must be * pressed twice in succession. A subsequent press of the 'tab' key * exits the interactive command mode. Entering a multi-letter code * sets the parameter to be modified. The 'newline' key erases the * current code, and the 'del' key deletes the last letter of * the code. The parameter value may be modified by pressing the * keypad left or up to decrement the value and right or down to * increment the value. The current value will be displayed as an * overlay above the GL rendered content. * * <p> The supported keyboard commands are as follows: * * <ul> * <li> h - display a list of commands * <li> fn - near frustum * <li> ff - far frustum * <li> tx - translate x * <li> ty - translate y * <li> tz - translate z * <li> z - zoom (frustum size) * <li> la - ambient light (all RGB channels) * <li> lar - ambient light red channel * <li> lag - ambient light green channel * <li> lab - ambient light blue channel * <li> ld - diffuse light (all RGB channels) * <li> ldr - diffuse light red channel * <li> ldg - diffuse light green channel * <li> ldb - diffuse light blue channel * <li> ls - specular light (all RGB channels) * <li> lsr - specular light red channel * <li> lsg - specular light green channel * <li> lsb - specular light blue channel * <li> lma - light model ambient (all RGB channels) * <li> lmar - light model ambient light red channel * <li> lmag - light model ambient green channel * <li> lmab - light model ambient blue channel * <li> tmin - texture min filter * <li> tmag - texture mag filter * <li> tper - texture perspective correction * </ul> * * {@hide} */ public class GLView { private static final int DEFAULT_DURATION_MILLIS = 1000; private static final int STATE_KEY = KeyEvent.KEYCODE_TAB; private static final int HAVE_NONE = 0; private static final int HAVE_ONE = 1; private static final int HAVE_TWO = 2; private static final float MESSAGE_Y_SPACING = 12.0f; private int mState = HAVE_NONE; private static final int NEAR_FRUSTUM = 0; private static final int FAR_FRUSTUM = 1; private static final int TRANSLATE_X = 2; private static final int TRANSLATE_Y = 3; private static final int TRANSLATE_Z = 4; private static final int ZOOM_EXPONENT = 5; private static final int AMBIENT_INTENSITY = 6; private static final int AMBIENT_RED = 7; private static final int AMBIENT_GREEN = 8; private static final int AMBIENT_BLUE = 9; private static final int DIFFUSE_INTENSITY = 10; private static final int DIFFUSE_RED = 11; private static final int DIFFUSE_GREEN = 12; private static final int DIFFUSE_BLUE = 13; private static final int SPECULAR_INTENSITY = 14; private static final int SPECULAR_RED = 15; private static final int SPECULAR_GREEN = 16; private static final int SPECULAR_BLUE = 17; private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18; private static final int LIGHT_MODEL_AMBIENT_RED = 19; private static final int LIGHT_MODEL_AMBIENT_GREEN = 20; private static final int LIGHT_MODEL_AMBIENT_BLUE = 21; private static final int TEXTURE_MIN_FILTER = 22; private static final int TEXTURE_MAG_FILTER = 23; private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24; private static final String[] commands = { "fn", "ff", "tx", "ty", "tz", "z", "la", "lar", "lag", "lab", "ld", "ldr", "ldg", "ldb", "ls", "lsr", "lsg", "lsb", "lma", "lmar", "lmag", "lmab", "tmin", "tmag", "tper" }; private static final String[] labels = { "Near Frustum", "Far Frustum", "Translate X", "Translate Y", "Translate Z", "Zoom", "Ambient Intensity", "Ambient Red", "Ambient Green", "Ambient Blue", "Diffuse Intensity", "Diffuse Red", "Diffuse Green", "Diffuse Blue", "Specular Intenstity", "Specular Red", "Specular Green", "Specular Blue", "Light Model Ambient Intensity", "Light Model Ambient Red", "Light Model Ambient Green", "Light Model Ambient Blue", "Texture Min Filter", "Texture Mag Filter", "Texture Perspective Correction", }; private static final float[] defaults = { 5.0f, 100.0f, 0.0f, 0.0f, -50.0f, 0, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_FASTEST }; private static final float[] increments = { 0.01f, 0.5f, 0.125f, 0.125f, 0.125f, 1.0f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0, 0, 0 }; private float[] params = new float[commands.length]; private static final float mZoomScale = 0.109f; private static final float mZoomBase = 1.01f; private int mParam = -1; private float mIncr = 0; private Paint mPaint = new Paint(); private float mAspectRatio = 1.0f; private float mZoom; // private boolean mPerspectiveCorrection = false; // private int mTextureMinFilter = GL10.GL_NEAREST; // private int mTextureMagFilter = GL10.GL_NEAREST; // Counters for FPS calculation private boolean mDisplayFPS = false; private boolean mDisplayCounts = false; private int mFramesFPS = 10; private long[] mTimes = new long[mFramesFPS]; private int mTimesIdx = 0; private Map<String,Message> mMessages = new HashMap<String,Message>(); /** * Constructs a new GLView. */ public GLView() { mPaint.setColor(0xffffffff); reset(); } /** * Sets the aspect ratio (width/height) of the screen. * * @param aspectRatio the screen width divided by the screen height */ public void setAspectRatio(float aspectRatio) { this.mAspectRatio = aspectRatio; } /** * Sets the overall ambient light intensity. This intensity will * be used to modify the ambient light value for each of the red, * green, and blue channels passed to glLightfv(...GL_AMBIENT...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setAmbientIntensity(float intensity) { params[AMBIENT_INTENSITY] = intensity; } /** * Sets the light model ambient intensity. This intensity will be * used to modify the ambient light value for each of the red, * green, and blue channels passed to * glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value * is 0.125f. * * @param intensity a floating-point value controlling the overall * light model ambient intensity. */ public void setLightModelAmbientIntensity(float intensity) { params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity; } /** * Sets the ambient color for the red, green, and blue channels * that will be multiplied by the value of setAmbientIntensity and * passed to glLightfv(...GL_AMBIENT...). The default values are * {1, 1, 1}. * * @param ambient an arry of three floats containing ambient * red, green, and blue intensity values. */ public void setAmbientColor(float[] ambient) { params[AMBIENT_RED] = ambient[0]; params[AMBIENT_GREEN] = ambient[1]; params[AMBIENT_BLUE] = ambient[2]; } /** * Sets the overall diffuse light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_DIFFUSE...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setDiffuseIntensity(float intensity) { params[DIFFUSE_INTENSITY] = intensity; } /** * Sets the diffuse color for the red, green, and blue channels * that will be multiplied by the value of setDiffuseIntensity and * passed to glLightfv(...GL_DIFFUSE...). The default values are * {1, 1, 1}. * * @param diffuse an array of three floats containing diffuse * red, green, and blue intensity values. */ public void setDiffuseColor(float[] diffuse) { params[DIFFUSE_RED] = diffuse[0]; params[DIFFUSE_GREEN] = diffuse[1]; params[DIFFUSE_BLUE] = diffuse[2]; } /** * Sets the overall specular light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_SPECULAR...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setSpecularIntensity(float intensity) { params[SPECULAR_INTENSITY] = intensity; } /** * Sets the specular color for the red, green, and blue channels * that will be multiplied by the value of setSpecularIntensity and * passed to glLightfv(...GL_SPECULAR...). The default values are * {1, 1, 1}. * * @param specular an array of three floats containing specular * red, green, and blue intensity values. */ public void setSpecularColor(float[] specular) { params[SPECULAR_RED] = specular[0]; params[SPECULAR_GREEN] = specular[1]; params[SPECULAR_BLUE] = specular[2]; } /** * Returns the current X translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the X modelview translation as a float. */ public float getTranslateX() { return params[TRANSLATE_X]; } /** * Returns the current Y translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the Y modelview translation as a float. */ public float getTranslateY() { return params[TRANSLATE_Y]; } /** * Returns the current Z translation of the modelview * transformation as passed to glTranslatef. The default value is * -50.0f. * * @return the Z modelview translation as a float. */ public float getTranslateZ() { return params[TRANSLATE_Z]; } /** * Sets the position of the near frustum clipping plane as passed * to glFrustumf. The default value is 5.0f; * * @param nearFrustum the near frustum clipping plane distance as * a float. */ public void setNearFrustum(float nearFrustum) { params[NEAR_FRUSTUM] = nearFrustum; } /** * Sets the position of the far frustum clipping plane as passed * to glFrustumf. The default value is 100.0f; * * @param farFrustum the far frustum clipping plane distance as a * float. */ public void setFarFrustum(float farFrustum) { params[FAR_FRUSTUM] = farFrustum; } private void computeZoom() { mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]); } /** * Resets all parameters to their default values. */ public void reset() { for (int i = 0; i < params.length; i++) { params[i] = defaults[i]; } computeZoom(); } private void removeExpiredMessages() { long now = System.currentTimeMillis(); List<String> toBeRemoved = new ArrayList<String>(); Iterator<String> keyIter = mMessages.keySet().iterator(); while (keyIter.hasNext()) { String key = keyIter.next(); Message msg = mMessages.get(key); if (msg.getExpirationTime() < now) { toBeRemoved.add(key); } } Iterator<String> tbrIter = toBeRemoved.iterator(); while (tbrIter.hasNext()) { String key = tbrIter.next(); mMessages.remove(key); } } /** * Displays the message overlay on the given Canvas. The * GLContext.waitGL method should be called prior to calling this * method. The interactive command display is drawn by this * method. * * @param canvas the Canvas on which messages are to appear. */ public void showMessages(Canvas canvas) { removeExpiredMessages(); float y = 10.0f; List<String> l = new ArrayList<String>(); l.addAll(mMessages.keySet()); Collections.sort(l); Iterator<String> iter = l.iterator(); while (iter.hasNext()) { String key = iter.next(); String text = mMessages.get(key).getText(); canvas.drawText(text, 10.0f, y, mPaint); y += MESSAGE_Y_SPACING; } } private int mTriangles; /** * Sets the number of triangles drawn in the previous frame for * display by the showStatistics method. The number of triangles * is not computed by GLView but must be supplied by the * calling Activity. * * @param triangles an Activity-supplied estimate of the number of * triangles drawn in the previous frame. */ public void setNumTriangles(int triangles) { this.mTriangles = triangles; } /** * Displays statistics on frames and triangles per second. The * GLContext.waitGL method should be called prior to calling this * method. * * @param canvas the Canvas on which statistics are to appear. * @param width the width of the Canvas. */ public void showStatistics(Canvas canvas, int width) { long endTime = mTimes[mTimesIdx] = System.currentTimeMillis(); mTimesIdx = (mTimesIdx + 1) % mFramesFPS; float th = mPaint.getTextSize(); if (mDisplayFPS) { // Use end time from mFramesFPS frames ago long startTime = mTimes[mTimesIdx]; String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime)); // Normalize fps to XX.XX format if (fps.indexOf(".") == 1) { fps = " " + fps; } int len = fps.length(); if (len == 2) { fps += ".00"; } else if (len == 4) { fps += "0"; } else if (len > 5) { fps = fps.substring(0, 5); } canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint); } if (mDisplayCounts) { canvas.drawText(mTriangles + " triangles", width - 100.0f, 10.0f + th + 5, mPaint); } } private void addMessage(String key, String text, int durationMillis) { long expirationTime = System.currentTimeMillis() + durationMillis; mMessages.put(key, new Message(text, expirationTime)); } private void addMessage(String key, String text) { addMessage(key, text, DEFAULT_DURATION_MILLIS); } private void addMessage(String text) { addMessage(text, text, DEFAULT_DURATION_MILLIS); } private void clearMessages() { mMessages.clear(); } String command = ""; private void toggleFilter() { if (params[mParam] == GL10.GL_NEAREST) { params[mParam] = GL10.GL_LINEAR; } else { params[mParam] = GL10.GL_NEAREST; } addMessage(commands[mParam], "Texture " + (mParam == TEXTURE_MIN_FILTER ? "min" : "mag") + " filter = " + (params[mParam] == GL10.GL_NEAREST ? "nearest" : "linear")); } private void togglePerspectiveCorrection() { if (params[mParam] == GL10.GL_NICEST) { params[mParam] = GL10.GL_FASTEST; } else { params[mParam] = GL10.GL_NICEST; } addMessage(commands[mParam], "Texture perspective correction = " + (params[mParam] == GL10.GL_FASTEST ? "fastest" : "nicest")); } private String valueString() { if (mParam == TEXTURE_MIN_FILTER || mParam == TEXTURE_MAG_FILTER) { if (params[mParam] == GL10.GL_NEAREST) { return "nearest"; } if (params[mParam] == GL10.GL_LINEAR) { return "linear"; } } if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { if (params[mParam] == GL10.GL_FASTEST) { return "fastest"; } if (params[mParam] == GL10.GL_NICEST) { return "nicest"; } } return "" + params[mParam]; } /** * * @return true if the view */ public boolean hasMessages() { return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts; } /** * Process a key stroke. The calling Activity should pass all * keys from its onKeyDown method to this method. If the key is * part of a GLView command, true is returned and the calling * Activity should ignore the key event. Otherwise, false is * returned and the calling Activity may process the key event * normally. * * @param keyCode the key code as passed to Activity.onKeyDown. * * @return true if the key is part of a GLView command sequence, * false otherwise. */ public boolean processKey(int keyCode) { // Pressing the state key twice enters the UI // Pressing it again exits the UI if ((keyCode == STATE_KEY) || (keyCode == KeyEvent.KEYCODE_SLASH) || (keyCode == KeyEvent.KEYCODE_PERIOD)) { mState = (mState + 1) % 3; if (mState == HAVE_NONE) { clearMessages(); } if (mState == HAVE_TWO) { clearMessages(); addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("aaab", "", Integer.MAX_VALUE); command = ""; } return true; } else { if (mState == HAVE_ONE) { mState = HAVE_NONE; return false; } } // If we're not in the UI, exit without handling the key if (mState != HAVE_TWO) { return false; } if (keyCode == KeyEvent.KEYCODE_ENTER) { command = ""; } else if (keyCode == KeyEvent.KEYCODE_DEL) { if (command.length() > 0) { command = command.substring(0, command.length() - 1); } } else if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) { command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a'); } addMessage("aaaa", "GL " + command, Integer.MAX_VALUE); if (command.equals("h")) { addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("h - help"); addMessage("fn/ff - frustum near/far clip Z"); addMessage("la/lar/lag/lab - abmient intensity/r/g/b"); addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b"); addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b"); addMessage("s - toggle statistics display"); addMessage("tmin/tmag - texture min/mag filter"); addMessage("tpersp - texture perspective correction"); addMessage("tx/ty/tz - view translate x/y/z"); addMessage("z - zoom"); command = ""; return true; } else if (command.equals("s")) { mDisplayCounts = !mDisplayCounts; mDisplayFPS = !mDisplayFPS; command = ""; return true; } mParam = -1; for (int i = 0; i < commands.length; i++) { if (command.equals(commands[i])) { mParam = i; mIncr = increments[i]; } } if (mParam == -1) { return true; } boolean addMessage = true; // Increment or decrement if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (mParam == ZOOM_EXPONENT) { params[mParam] += mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] += mIncr; } } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { if (mParam == ZOOM_EXPONENT) { params[mParam] -= mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] -= mIncr; } } if (addMessage) { addMessage(commands[mParam], labels[mParam] + ": " + valueString()); } return true; } /** * Zoom in by a given number of steps. A negative value of steps * zooms out. Each step zooms in by 1%. * * @param steps the number of steps to zoom by. */ public void zoom(int steps) { params[ZOOM_EXPONENT] += steps; computeZoom(); } /** * Set the projection matrix using glFrustumf. The left and right * clipping planes are set at -+(aspectRatio*zoom), the bottom and * top clipping planes are set at -+zoom, and the near and far * clipping planes are set to the values set by setNearFrustum and * setFarFrustum or interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the projection matrix</li> * </ul> * * @param gl a GL10 instance whose projection matrix is to be modified. */ public void setProjection(GL10 gl) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); if (mAspectRatio >= 1.0f) { gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom, -mZoom, mZoom, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } else { gl.glFrustumf(-mZoom, mZoom, -mZoom / mAspectRatio, mZoom / mAspectRatio, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } } /** * Set the modelview matrix using glLoadIdentity and glTranslatef. * The translation values are set interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the modelview matrix</li> * </ul> * * @param gl a GL10 instance whose modelview matrix is to be modified. */ public void setView(GL10 gl) { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Move the viewpoint backwards gl.glTranslatef(params[TRANSLATE_X], params[TRANSLATE_Y], params[TRANSLATE_Z]); } /** * Sets texture parameters. * * <p> GL side effects: * <ul> * <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li> * <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li> * <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setTextureParameters(GL10 gl) { gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, (int)params[TEXTURE_PERSPECTIVE_CORRECTION]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, params[TEXTURE_MIN_FILTER]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, params[TEXTURE_MAG_FILTER]); } /** * Sets the lighting parameters for the given light. * * <p> GL side effects: * <ul> * <li>sets the GL_LIGHT_MODEL_AMBIENT intensities * <li>sets the GL_AMBIENT intensities for the given light</li> * <li>sets the GL_DIFFUSE intensities for the given light</li> * <li>sets the GL_SPECULAR intensities for the given light</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setLights(GL10 gl, int lightNum) { float[] light = new float[4]; light[3] = 1.0f; float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY]; light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi; light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi; light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi; gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0); float ai = params[AMBIENT_INTENSITY]; light[0] = params[AMBIENT_RED]*ai; light[1] = params[AMBIENT_GREEN]*ai; light[2] = params[AMBIENT_BLUE]*ai; gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0); float di = params[DIFFUSE_INTENSITY]; light[0] = params[DIFFUSE_RED]*di; light[1] = params[DIFFUSE_GREEN]*di; light[2] = params[DIFFUSE_BLUE]*di; gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0); float si = params[SPECULAR_INTENSITY]; light[0] = params[SPECULAR_RED]*si; light[1] = params[SPECULAR_GREEN]*si; light[2] = params[SPECULAR_BLUE]*si; gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 0); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; public class LatLongSphere extends Sphere { public LatLongSphere(float centerX, float centerY, float centerZ, float radius, int lats, int longs, float minLongitude, float maxLongitude, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors, boolean flatten) { super(emitTextureCoordinates, emitNormals, emitColors); int tris = 2 * (lats - 1) * (longs - 1); int[] vertices = new int[3 * lats * longs]; int[] texcoords = new int[2 * lats * longs]; int[] colors = new int[4 * lats * longs]; int[] normals = new int[3 * lats * longs]; short[] indices = new short[3 * tris]; int vidx = 0; int tidx = 0; int nidx = 0; int cidx = 0; int iidx = 0; minLongitude *= DEGREES_TO_RADIANS; maxLongitude *= DEGREES_TO_RADIANS; for (int i = 0; i < longs; i++) { float fi = (float) i / (longs - 1); // theta is the longitude float theta = (maxLongitude - minLongitude) * (1.0f - fi) + minLongitude; float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); for (int j = 0; j < lats; j++) { float fj = (float) j / (lats - 1); // phi is the latitude float phi = PI * fj; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; if (flatten) { // Place vertices onto a flat projection vertices[vidx++] = toFixed(2.0f * fi - 1.0f); vertices[vidx++] = toFixed(0.5f - fj); vertices[vidx++] = toFixed(0.0f); } else { // Place vertices onto the surface of a sphere // with the given center and radius vertices[vidx++] = toFixed(x * radius + centerX); vertices[vidx++] = toFixed(y * radius + centerY); vertices[vidx++] = toFixed(z * radius + centerZ); } if (emitTextureCoordinates) { texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI))); texcoords[tidx++] = toFixed(fj); } if (emitNormals) { float norm = 1.0f / Shape.length(x, y, z); normals[nidx++] = toFixed(x * norm); normals[nidx++] = toFixed(y * norm); normals[nidx++] = toFixed(z * norm); } // 0 == black, 65536 == white if (emitColors) { colors[cidx++] = (i % 2) * 65536; colors[cidx++] = 0; colors[cidx++] = (j % 2) * 65536; colors[cidx++] = 65536; } } } for (int i = 0; i < longs - 1; i++) { for (int j = 0; j < lats - 1; j++) { int base = i * lats + j; // Ensure both triangles have the same final vertex // since this vertex carries the color for flat // shading indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + 1); indices[iidx++] = (short) (base + lats + 1); indices[iidx++] = (short) (base + lats); indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + lats + 1); } } allocateBuffers(vertices, texcoords, normals, colors, indices); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.ByteBuffer; public class Texture { private ByteBuffer data; private int width, height; public Texture(ByteBuffer data, int width, int height) { this.data = data; this.width = width; this.height = height; } public ByteBuffer getData() { return data; } public int getWidth() { return width; } public int getHeight() { return height; } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.TextView; /** * A dialog-like floating activity * @author Kevin Yuan * */ public class Floating extends Activity { private static final int[] BUTTONS = {R.id.button1, R.id.button2, R.id.button3}; private View mView; private ViewGroup mContentViewContainer; private Content mContent; @Override public void onCreate(Bundle savedInstanceState) { // It will not work if we setTheme here. // Please add android:theme="@android:style/Theme.Dialog" to any descendant class in AndroidManifest.xml! // See http://code.google.com/p/android/issues/detail?id=4394 // setTheme(android.R.style.Theme_Dialog); getWindow().requestFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); mView = View.inflate(this, R.layout.floating, null); final DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); mView.setMinimumWidth(Math.min(dm.widthPixels, dm.heightPixels) - 20); setContentView(mView); mContentViewContainer = (ViewGroup) mView.findViewById(R.id.content); } private void setDialogContentView(final View contentView) { mContentViewContainer.removeAllViews(); mContentViewContainer.addView(contentView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); } public void setContent(Content content) { mContent = content; refreshContent(); } public void refreshContent() { setDialogContentView(mContent.getView()); ((TextView)findViewById(R.id.title)).setText(mContent.getTitle()); final int btnCount = mContent.getButtonCount(); if(btnCount > BUTTONS.length) { throw new RuntimeException(String.format("%d exceeds maximum button count: %d!", btnCount, BUTTONS.length)); } findViewById(R.id.buttons_view).setVisibility(btnCount > 0 ? View.VISIBLE : View.GONE); for(int buttonId:BUTTONS) { final Button btn = (Button) findViewById(buttonId); btn.setOnClickListener(null); btn.setVisibility(View.GONE); } for(int btnIndex = 0; btnIndex < btnCount; btnIndex++){ final Button btn = (Button)findViewById(BUTTONS[btnIndex]); btn.setText(mContent.getButtonText(btnIndex)); btn.setVisibility(View.VISIBLE); btn.setOnClickListener(mContent.getButtonOnClickListener(btnIndex)); } } public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { if(mContent != null) { mContent.onCreateContextMenu(menu, v, menuInfo); } } public boolean onContextItemSelected (MenuItem item) { if(mContent != null) { return mContent.onContextItemSelected(item); } return false; } public interface Content { CharSequence getTitle(); View getView(); int getButtonCount(); CharSequence getButtonText(int index); OnClickListener getButtonOnClickListener(int index); void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo); boolean onContextItemSelected (MenuItem item); } }
Java
package com.farproc.wifi.connecter; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.AuthAlgorithm; import android.net.wifi.WifiConfiguration.GroupCipher; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiConfiguration.PairwiseCipher; import android.net.wifi.WifiConfiguration.Protocol; import android.text.TextUtils; import android.util.Log; public class ConfigurationSecuritiesOld extends ConfigurationSecurities { // Constants used for different security types public static final String WPA2 = "WPA2"; public static final String WPA = "WPA"; public static final String WEP = "WEP"; public static final String OPEN = "Open"; // For EAP Enterprise fields public static final String WPA_EAP = "WPA-EAP"; public static final String IEEE8021X = "IEEE8021X"; public static final String[] EAP_METHOD = { "PEAP", "TLS", "TTLS" }; public static final int WEP_PASSWORD_AUTO = 0; public static final int WEP_PASSWORD_ASCII = 1; public static final int WEP_PASSWORD_HEX = 2; static final String[] SECURITY_MODES = { WEP, WPA, WPA2, WPA_EAP, IEEE8021X }; private static final String TAG = "ConfigurationSecuritiesOld"; @Override public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { if (wifiConfig.allowedKeyManagement.get(KeyMgmt.NONE)) { // If we never set group ciphers, wpa_supplicant puts all of them. // For open, we don't set group ciphers. // For WEP, we specifically only set WEP40 and WEP104, so CCMP // and TKIP should not be there. if (!wifiConfig.allowedGroupCiphers.get(GroupCipher.CCMP) && (wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP40) || wifiConfig.allowedGroupCiphers.get(GroupCipher.WEP104))) { return WEP; } else { return OPEN; } } else if (wifiConfig.allowedProtocols.get(Protocol.RSN)) { return WPA2; } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.WPA_EAP)) { return WPA_EAP; } else if (wifiConfig.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { return IEEE8021X; } else if (wifiConfig.allowedProtocols.get(Protocol.WPA)) { return WPA; } else { Log.w(TAG, "Unknown security type from WifiConfiguration, falling back on open."); return OPEN; } } @Override public String getScanResultSecurity(ScanResult scanResult) { final String cap = scanResult.capabilities; for (int i = SECURITY_MODES.length - 1; i >= 0; i--) { if (cap.contains(SECURITY_MODES[i])) { return SECURITY_MODES[i]; } } return OPEN; } @Override public String getDisplaySecirityString(final ScanResult scanResult) { return getScanResultSecurity(scanResult); } private static boolean isHexWepKey(String wepKey) { final int len = wepKey.length(); // WEP-40, WEP-104, and some vendors using 256-bit WEP (WEP-232?) if (len != 10 && len != 26 && len != 58) { return false; } return isHex(wepKey); } private static boolean isHex(String key) { for (int i = key.length() - 1; i >= 0; i--) { final char c = key.charAt(i); if (!(c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f')) { return false; } } return true; } @Override public void setupSecurity(WifiConfiguration config, String security, final String password) { config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); if (TextUtils.isEmpty(security)) { security = OPEN; Log.w(TAG, "Empty security, assuming open"); } if (security.equals(WEP)) { int wepPasswordType = WEP_PASSWORD_AUTO; // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (wepPasswordType == WEP_PASSWORD_AUTO) { if (isHexWepKey(password)) { config.wepKeys[0] = password; } else { config.wepKeys[0] = Wifi.convertToQuotedString(password); } } else { config.wepKeys[0] = wepPasswordType == WEP_PASSWORD_ASCII ? Wifi.convertToQuotedString(password) : password; } } config.wepTxKeyIndex = 0; config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); config.allowedKeyManagement.set(KeyMgmt.NONE); config.allowedGroupCiphers.set(GroupCipher.WEP40); config.allowedGroupCiphers.set(GroupCipher.WEP104); } else if (security.equals(WPA) || security.equals(WPA2)){ config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP); config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP); config.allowedProtocols.set(security.equals(WPA2) ? Protocol.RSN : Protocol.WPA); // If password is empty, it should be left untouched if (!TextUtils.isEmpty(password)) { if (password.length() == 64 && isHex(password)) { // Goes unquoted as hex config.preSharedKey = password; } else { // Goes quoted as ASCII config.preSharedKey = Wifi.convertToQuotedString(password); } } } else if (security.equals(OPEN)) { config.allowedKeyManagement.set(KeyMgmt.NONE); } else if (security.equals(WPA_EAP) || security.equals(IEEE8021X)) { config.allowedGroupCiphers.set(GroupCipher.TKIP); config.allowedGroupCiphers.set(GroupCipher.CCMP); if (security.equals(WPA_EAP)) { config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); } else { config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); } if (!TextUtils.isEmpty(password)) { config.preSharedKey = Wifi.convertToQuotedString(password); } } } @Override public boolean isOpenNetwork(String security) { return OPEN.equals(security); } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class NewNetworkContent extends BaseContent { private boolean mIsOpenNetwork = false; public NewNetworkContent(final Floating floating, final WifiManager wifiManager, ScanResult scanResult) { super(floating, wifiManager, scanResult); mView.findViewById(R.id.Status).setVisibility(View.GONE); mView.findViewById(R.id.Speed).setVisibility(View.GONE); mView.findViewById(R.id.IPAddress).setVisibility(View.GONE); if(Wifi.ConfigSec.isOpenNetwork(mScanResultSecurity)) { mIsOpenNetwork = true; mView.findViewById(R.id.Password).setVisibility(View.GONE); } else { ((TextView)mView.findViewById(R.id.Password_TextView)).setText(R.string.please_type_passphrase); } } private OnClickListener mConnectOnClick = new OnClickListener() { @Override public void onClick(View v) { boolean connResult; if(mIsOpenNetwork) { connResult = Wifi.connectToNewNetwork(mFloating, mWifiManager, mScanResult, null, mNumOpenNetworksKept); } else { connResult = Wifi.connectToNewNetwork(mFloating, mWifiManager, mScanResult , ((EditText)mView.findViewById(R.id.Password_EditText)).getText().toString() , mNumOpenNetworksKept); } if(!connResult) { Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show(); } mFloating.finish(); } }; private OnClickListener mOnClickListeners[] = {mConnectOnClick, mCancelOnClick}; @Override public int getButtonCount() { return 2; } @Override public OnClickListener getButtonOnClickListener(int index) { return mOnClickListeners[index]; } @Override public CharSequence getButtonText(int index) { switch(index) { case 0: return mFloating.getText(R.string.connect); case 1: return getCancelString(); default: return null; } } @Override public CharSequence getTitle() { return mFloating.getString(R.string.wifi_connect_to, mScanResult.SSID); } @Override public boolean onContextItemSelected(MenuItem item) { return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class ChangePasswordContent extends BaseContent { private ChangingAwareEditText mPasswordEditText; public ChangePasswordContent(Floating floating, WifiManager wifiManager, ScanResult scanResult) { super(floating, wifiManager, scanResult); mView.findViewById(R.id.Status).setVisibility(View.GONE); mView.findViewById(R.id.Speed).setVisibility(View.GONE); mView.findViewById(R.id.IPAddress).setVisibility(View.GONE); mPasswordEditText = ((ChangingAwareEditText)mView.findViewById(R.id.Password_EditText)); ((TextView)mView.findViewById(R.id.Password_TextView)).setText(R.string.please_type_passphrase); ((EditText)mView.findViewById(R.id.Password_EditText)).setHint(R.string.wifi_password_unchanged); } @Override public int getButtonCount() { return 2; } @Override public OnClickListener getButtonOnClickListener(int index) { return mOnClickListeners[index]; } @Override public CharSequence getButtonText(int index) { switch(index) { case 0: return mFloating.getString(R.string.wifi_save_config); case 1: return getCancelString(); default: return null; } } @Override public CharSequence getTitle() { return mScanResult.SSID; } private OnClickListener mSaveOnClick = new OnClickListener() { @Override public void onClick(View v) { if(mPasswordEditText.getChanged()) { final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity); boolean saveResult = false; if(config != null) { saveResult = Wifi.changePasswordAndConnect(mFloating, mWifiManager, config , mPasswordEditText.getText().toString() , mNumOpenNetworksKept); } if(!saveResult) { Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show(); } } mFloating.finish(); } }; OnClickListener mOnClickListeners[] = {mSaveOnClick, mCancelOnClick}; @Override public boolean onContextItemSelected(MenuItem item) { return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { } }
Java
package com.farproc.wifi.connecter; import java.lang.reflect.Field; import android.os.Build.VERSION;; /** * Get Android version in different Android versions. :) * @author yuanxiaohui * */ public class Version { public final static int SDK = get(); private static int get() { final Class<VERSION> versionClass = VERSION.class; try { // First try to read the recommended field android.os.Build.VERSION.SDK_INT. final Field sdkIntField = versionClass.getField("SDK_INT"); return sdkIntField.getInt(null); }catch (NoSuchFieldException e) { // If SDK_INT does not exist, read the deprecated field SDK. return Integer.valueOf(VERSION.SDK); } catch (Exception e) { throw new RuntimeException(e); } } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.provider.Settings; import android.text.InputType; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; public abstract class BaseContent implements Floating.Content, OnCheckedChangeListener { protected final WifiManager mWifiManager; protected final Floating mFloating; protected final ScanResult mScanResult; protected final String mScanResultSecurity; protected final boolean mIsOpenNetwork ; protected int mNumOpenNetworksKept; protected View mView; protected OnClickListener mCancelOnClick = new OnClickListener() { @Override public void onClick(View v) { mFloating.finish(); } }; protected String getCancelString() { return mFloating.getString(android.R.string.cancel); } private static final int[] SIGNAL_LEVEL = {R.string.wifi_signal_0, R.string.wifi_signal_1, R.string.wifi_signal_2, R.string.wifi_signal_3}; public BaseContent(final Floating floating, final WifiManager wifiManager, final ScanResult scanResult) { super(); mWifiManager = wifiManager; mFloating = floating; mScanResult = scanResult; mScanResultSecurity = Wifi.ConfigSec.getScanResultSecurity(mScanResult); mIsOpenNetwork = Wifi.ConfigSec.isOpenNetwork(mScanResultSecurity); mView = View.inflate(mFloating, R.layout.base_content, null); ((TextView)mView.findViewById(R.id.SignalStrength_TextView)).setText(SIGNAL_LEVEL[WifiManager.calculateSignalLevel(mScanResult.level, SIGNAL_LEVEL.length)]); final String rawSecurity = Wifi.ConfigSec.getDisplaySecirityString(mScanResult); final String readableSecurity = Wifi.ConfigSec.isOpenNetwork(rawSecurity) ? mFloating.getString(R.string.wifi_security_open) : rawSecurity; ((TextView)mView.findViewById(R.id.Security_TextView)).setText(readableSecurity); ((CheckBox)mView.findViewById(R.id.ShowPassword_CheckBox)).setOnCheckedChangeListener(this); mNumOpenNetworksKept = Settings.Secure.getInt(floating.getContentResolver(), Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT, 10); } @Override public View getView() { return mView; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { ((EditText)mView.findViewById(R.id.Password_EditText)).setInputType( InputType.TYPE_CLASS_TEXT | (isChecked ? InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD :InputType.TYPE_TEXT_VARIATION_PASSWORD)); } public OnClickListener mChangePasswordOnClick = new OnClickListener() { @Override public void onClick(View v) { changePassword(); } }; public void changePassword() { mFloating.setContent(new ChangePasswordContent(mFloating, mWifiManager, mScanResult)); } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import android.content.Context; import android.util.AttributeSet; import android.widget.EditText; public class ChangingAwareEditText extends EditText { public ChangingAwareEditText(Context context, AttributeSet attrs) { super(context, attrs); } private boolean mChanged = false; public boolean getChanged() { return mChanged; } protected void onTextChanged (CharSequence text, int start, int before, int after) { mChanged = true; } }
Java
package com.farproc.wifi.connecter; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; public abstract class ConfigurationSecurities { /** * @return The security of a given {@link WifiConfiguration}. */ public abstract String getWifiConfigurationSecurity(WifiConfiguration wifiConfig); /** * @return The security of a given {@link ScanResult}. */ public abstract String getScanResultSecurity(ScanResult scanResult); /** * Fill in the security fields of WifiConfiguration config. * @param config The object to fill. * @param security If is OPEN, password is ignored. * @param password Password of the network if security is not OPEN. */ public abstract void setupSecurity(WifiConfiguration config, String security, final String password); public abstract String getDisplaySecirityString(final ScanResult scanResult); public abstract boolean isOpenNetwork(final String security); public static ConfigurationSecurities newInstance() { if(Version.SDK < 8) { return new ConfigurationSecuritiesOld(); } else { return new ConfigurationSecuritiesV8(); } } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import java.util.List; import android.app.Activity; import android.app.ListActivity; import android.content.ActivityNotFoundException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.net.wifi.ScanResult; import android.net.wifi.WifiManager; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Toast; import android.widget.TwoLineListItem; import android.widget.AdapterView.OnItemClickListener; public class TestWifiScan extends ListActivity { private WifiManager mWifiManager; private List<ScanResult> mScanResults; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWifiManager = (WifiManager)getSystemService(WIFI_SERVICE); setListAdapter(mListAdapter); getListView().setOnItemClickListener(mItemOnClick); } @Override public void onResume() { super.onResume(); final IntentFilter filter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); registerReceiver(mReceiver, filter); mWifiManager.startScan(); } @Override public void onPause() { super.onPause(); unregisterReceiver(mReceiver); } private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { mScanResults = mWifiManager.getScanResults(); mListAdapter.notifyDataSetChanged(); mWifiManager.startScan(); } } }; private BaseAdapter mListAdapter = new BaseAdapter() { @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null || !(convertView instanceof TwoLineListItem)) { convertView = View.inflate(getApplicationContext(), android.R.layout.simple_list_item_2, null); } final ScanResult result = mScanResults.get(position); ((TwoLineListItem)convertView).getText1().setText(result.SSID); ((TwoLineListItem)convertView).getText2().setText( String.format("%s %d", result.BSSID, result.level) ); return convertView; } @Override public long getItemId(int position) { return position; } @Override public Object getItem(int position) { return null; } @Override public int getCount() { return mScanResults == null ? 0 : mScanResults.size(); } }; private OnItemClickListener mItemOnClick = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final ScanResult result = mScanResults.get(position); launchWifiConnecter(TestWifiScan.this, result); } }; /** * Try to launch Wifi Connecter with {@link #hostspot}. Prompt user to download if Wifi Connecter is not installed. * @param activity * @param hotspot */ private static void launchWifiConnecter(final Activity activity, final ScanResult hotspot) { final Intent intent = new Intent("com.farproc.wifi.connecter.action.CONNECT_OR_EDIT"); intent.putExtra("com.farproc.wifi.connecter.extra.HOTSPOT", hotspot); try { activity.startActivity(intent); } catch(ActivityNotFoundException e) { // Wifi Connecter Library is not installed. Toast.makeText(activity, "Wifi Connecter is not installed.", Toast.LENGTH_LONG).show(); downloadWifiConnecter(activity); } } private static void downloadWifiConnecter(final Activity activity) { Intent downloadIntent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("market://details?id=com.farproc.wifi.connecter")); try { activity.startActivity(downloadIntent); Toast.makeText(activity, "Please install this app.", Toast.LENGTH_LONG).show(); } catch (ActivityNotFoundException e) { // Market app is not available in this device. // Show download page of this project. try { downloadIntent.setData(Uri.parse("http://code.google.com/p/android-wifi-connecter/downloads/list")); activity.startActivity(downloadIntent); Toast.makeText(activity, "Please download the apk and install it manully.", Toast.LENGTH_LONG).show(); } catch (ActivityNotFoundException e2) { // Even the Browser app is not available!!!!! // Show a error message! Toast.makeText(activity, "Fatel error! No web browser app in your device!!!", Toast.LENGTH_LONG).show(); } } } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.Toast; public class ConfiguredNetworkContent extends BaseContent { public ConfiguredNetworkContent(Floating floating, WifiManager wifiManager, ScanResult scanResult) { super(floating, wifiManager, scanResult); mView.findViewById(R.id.Status).setVisibility(View.GONE); mView.findViewById(R.id.Speed).setVisibility(View.GONE); mView.findViewById(R.id.IPAddress).setVisibility(View.GONE); mView.findViewById(R.id.Password).setVisibility(View.GONE); } @Override public int getButtonCount() { return 3; } @Override public OnClickListener getButtonOnClickListener(int index) { switch(index) { case 0: return mConnectOnClick; case 1: if(mIsOpenNetwork) { return mForgetOnClick; } else { return mOpOnClick; } case 2: return mCancelOnClick; default: return null; } } @Override public CharSequence getButtonText(int index) { switch(index) { case 0: return mFloating.getString(R.string.connect); case 1: if(mIsOpenNetwork) { return mFloating.getString(R.string.forget_network); } else { return mFloating.getString(R.string.buttonOp); } case 2: return getCancelString(); default: return null; } } @Override public CharSequence getTitle() { return mFloating.getString(R.string.wifi_connect_to, mScanResult.SSID); } private OnClickListener mConnectOnClick = new OnClickListener() { @Override public void onClick(View v) { final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity); boolean connResult = false; if(config != null) { connResult = Wifi.connectToConfiguredNetwork(mFloating, mWifiManager, config, false); } if(!connResult) { Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show(); } mFloating.finish(); } }; private OnClickListener mOpOnClick = new OnClickListener() { @Override public void onClick(View v) { mFloating.registerForContextMenu(v); mFloating.openContextMenu(v); mFloating.unregisterForContextMenu(v); } }; private OnClickListener mForgetOnClick = new OnClickListener() { @Override public void onClick(View v) { forget(); } }; private void forget() { final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity); boolean result = false; if(config != null) { result = mWifiManager.removeNetwork(config.networkId) && mWifiManager.saveConfiguration(); } if(!result) { Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show(); } mFloating.finish(); } private static final int MENU_FORGET = 0; private static final int MENU_CHANGE_PASSWORD = 1; @Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_FORGET: forget(); break; case MENU_CHANGE_PASSWORD: changePassword(); break; } return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(Menu.NONE, MENU_FORGET, Menu.NONE, R.string.forget_network); menu.add(Menu.NONE, MENU_CHANGE_PASSWORD, Menu.NONE, R.string.wifi_change_password); } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import java.util.List; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.NetworkInfo; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.os.IBinder; public class ReenableAllApsWhenNetworkStateChanged { public static void schedule(final Context ctx) { ctx.startService(new Intent(ctx, BackgroundService.class)); } private static void reenableAllAps(final Context ctx) { final WifiManager wifiMgr = (WifiManager)ctx.getSystemService(Context.WIFI_SERVICE); final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); if(configurations != null) { for(final WifiConfiguration config:configurations) { wifiMgr.enableNetwork(config.networkId, false); } } } public static class BackgroundService extends Service { private boolean mReenabled; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if(WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) { final NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); final NetworkInfo.DetailedState detailed = networkInfo.getDetailedState(); if(detailed != NetworkInfo.DetailedState.DISCONNECTED && detailed != NetworkInfo.DetailedState.DISCONNECTING && detailed != NetworkInfo.DetailedState.SCANNING) { if(!mReenabled) { mReenabled = true; reenableAllAps(context); stopSelf(); } } } } }; private IntentFilter mIntentFilter; @Override public IBinder onBind(Intent intent) { return null; // We need not bind to it at all. } @Override public void onCreate() { super.onCreate(); mReenabled = false; mIntentFilter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION); registerReceiver(mReceiver, mIntentFilter); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mReceiver); } } }
Java
package com.farproc.wifi.connecter; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.AuthAlgorithm; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.util.Log; public class ConfigurationSecuritiesV8 extends ConfigurationSecurities { static final int SECURITY_NONE = 0; static final int SECURITY_WEP = 1; static final int SECURITY_PSK = 2; static final int SECURITY_EAP = 3; enum PskType { UNKNOWN, WPA, WPA2, WPA_WPA2 } private static final String TAG = "ConfigurationSecuritiesV14"; private static int getSecurity(WifiConfiguration config) { if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { return SECURITY_PSK; } if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { return SECURITY_EAP; } return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; } private static int getSecurity(ScanResult result) { if (result.capabilities.contains("WEP")) { return SECURITY_WEP; } else if (result.capabilities.contains("PSK")) { return SECURITY_PSK; } else if (result.capabilities.contains("EAP")) { return SECURITY_EAP; } return SECURITY_NONE; } @Override public String getWifiConfigurationSecurity(WifiConfiguration wifiConfig) { return String.valueOf(getSecurity(wifiConfig)); } @Override public String getScanResultSecurity(ScanResult scanResult) { return String.valueOf(getSecurity(scanResult)); } @Override public void setupSecurity(WifiConfiguration config, String security, String password) { config.allowedAuthAlgorithms.clear(); config.allowedGroupCiphers.clear(); config.allowedKeyManagement.clear(); config.allowedPairwiseCiphers.clear(); config.allowedProtocols.clear(); final int sec = security == null ? SECURITY_NONE : Integer.valueOf(security); final int passwordLen = password == null ? 0 : password.length(); switch (sec) { case SECURITY_NONE: config.allowedKeyManagement.set(KeyMgmt.NONE); break; case SECURITY_WEP: config.allowedKeyManagement.set(KeyMgmt.NONE); config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN); config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED); if (passwordLen != 0) { // WEP-40, WEP-104, and 256-bit WEP (WEP-232?) if ((passwordLen == 10 || passwordLen == 26 || passwordLen == 58) && password.matches("[0-9A-Fa-f]*")) { config.wepKeys[0] = password; } else { config.wepKeys[0] = '"' + password + '"'; } } break; case SECURITY_PSK: config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); if (passwordLen != 0) { if (password.matches("[0-9A-Fa-f]{64}")) { config.preSharedKey = password; } else { config.preSharedKey = '"' + password + '"'; } } break; case SECURITY_EAP: config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); // config.eap.setValue((String) mEapMethodSpinner.getSelectedItem()); // // config.phase2.setValue((mPhase2Spinner.getSelectedItemPosition() == 0) ? "" : // "auth=" + mPhase2Spinner.getSelectedItem()); // config.ca_cert.setValue((mEapCaCertSpinner.getSelectedItemPosition() == 0) ? "" : // KEYSTORE_SPACE + Credentials.CA_CERTIFICATE + // (String) mEapCaCertSpinner.getSelectedItem()); // config.client_cert.setValue((mEapUserCertSpinner.getSelectedItemPosition() == 0) ? // "" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE + // (String) mEapUserCertSpinner.getSelectedItem()); // config.private_key.setValue((mEapUserCertSpinner.getSelectedItemPosition() == 0) ? // "" : KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY + // (String) mEapUserCertSpinner.getSelectedItem()); // config.identity.setValue((mEapIdentityView.length() == 0) ? "" : // mEapIdentityView.getText().toString()); // config.anonymous_identity.setValue((mEapAnonymousView.length() == 0) ? "" : // mEapAnonymousView.getText().toString()); // if (mPasswordView.length() != 0) { // config.password.setValue(mPasswordView.getText().toString()); // } break; default: Log.e(TAG, "Invalid security type: " + sec); } // config.proxySettings = mProxySettings; // config.ipAssignment = mIpAssignment; // config.linkProperties = new LinkProperties(mLinkProperties); } private static PskType getPskType(ScanResult result) { boolean wpa = result.capabilities.contains("WPA-PSK"); boolean wpa2 = result.capabilities.contains("WPA2-PSK"); if (wpa2 && wpa) { return PskType.WPA_WPA2; } else if (wpa2) { return PskType.WPA2; } else if (wpa) { return PskType.WPA; } else { Log.w(TAG, "Received abnormal flag string: " + result.capabilities); return PskType.UNKNOWN; } } @Override public String getDisplaySecirityString(final ScanResult scanResult) { final int security = getSecurity(scanResult); if(security == SECURITY_PSK) { switch(getPskType(scanResult)) { case WPA: return "WPA"; case WPA_WPA2: case WPA2: return "WPA2"; default: return "?"; } } else { switch(security) { case SECURITY_NONE: return "OPEN"; case SECURITY_WEP: return "WEP"; case SECURITY_EAP: return "EAP"; } } return "?"; } @Override public boolean isOpenNetwork(String security) { return String.valueOf(SECURITY_NONE).equals(security); } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import java.util.Comparator; import java.util.List; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiManager; import android.text.TextUtils; import android.util.Log; public class Wifi { public static final ConfigurationSecurities ConfigSec = ConfigurationSecurities.newInstance(); private static final String TAG = "Wifi Connecter"; /** * Change the password of an existing configured network and connect to it * @param wifiMgr * @param config * @param newPassword * @return */ public static boolean changePasswordAndConnect(final Context ctx, final WifiManager wifiMgr, final WifiConfiguration config, final String newPassword, final int numOpenNetworksKept) { ConfigSec.setupSecurity(config, ConfigSec.getWifiConfigurationSecurity(config), newPassword); final int networkId = wifiMgr.updateNetwork(config); if(networkId == -1) { // Update failed. return false; } // Force the change to apply. wifiMgr.disconnect(); return connectToConfiguredNetwork(ctx, wifiMgr, config, true); } /** * Configure a network, and connect to it. * @param wifiMgr * @param scanResult * @param password Password for secure network or is ignored. * @return */ public static boolean connectToNewNetwork(final Context ctx, final WifiManager wifiMgr, final ScanResult scanResult, final String password, final int numOpenNetworksKept) { final String security = ConfigSec.getScanResultSecurity(scanResult); if(ConfigSec.isOpenNetwork(security)) { checkForExcessOpenNetworkAndSave(wifiMgr, numOpenNetworksKept); } WifiConfiguration config = new WifiConfiguration(); config.SSID = convertToQuotedString(scanResult.SSID); config.BSSID = scanResult.BSSID; ConfigSec.setupSecurity(config, security, password); int id = -1; try { id = wifiMgr.addNetwork(config); } catch(NullPointerException e) { Log.e(TAG, "Weird!! Really!! What's wrong??", e); // Weird!! Really!! // This exception is reported by user to Android Developer Console(https://market.android.com/publish/Home) } if(id == -1) { return false; } if(!wifiMgr.saveConfiguration()) { return false; } config = getWifiConfiguration(wifiMgr, config, security); if(config == null) { return false; } return connectToConfiguredNetwork(ctx, wifiMgr, config, true); } /** * Connect to a configured network. * @param wifiManager * @param config * @param numOpenNetworksKept Settings.Secure.WIFI_NUM_OPEN_NETWORKS_KEPT * @return */ public static boolean connectToConfiguredNetwork(final Context ctx, final WifiManager wifiMgr, WifiConfiguration config, boolean reassociate) { final String security = ConfigSec.getWifiConfigurationSecurity(config); int oldPri = config.priority; // Make it the highest priority. int newPri = getMaxPriority(wifiMgr) + 1; if(newPri > MAX_PRIORITY) { newPri = shiftPriorityAndSave(wifiMgr); config = getWifiConfiguration(wifiMgr, config, security); if(config == null) { return false; } } // Set highest priority to this configured network config.priority = newPri; int networkId = wifiMgr.updateNetwork(config); if(networkId == -1) { return false; } // Do not disable others if(!wifiMgr.enableNetwork(networkId, false)) { config.priority = oldPri; return false; } if(!wifiMgr.saveConfiguration()) { config.priority = oldPri; return false; } // We have to retrieve the WifiConfiguration after save. config = getWifiConfiguration(wifiMgr, config, security); if(config == null) { return false; } ReenableAllApsWhenNetworkStateChanged.schedule(ctx); // Disable others, but do not save. // Just to force the WifiManager to connect to it. if(!wifiMgr.enableNetwork(config.networkId, true)) { return false; } final boolean connect = reassociate ? wifiMgr.reassociate() : wifiMgr.reconnect(); if(!connect) { return false; } return true; } private static void sortByPriority(final List<WifiConfiguration> configurations) { java.util.Collections.sort(configurations, new Comparator<WifiConfiguration>() { @Override public int compare(WifiConfiguration object1, WifiConfiguration object2) { return object1.priority - object2.priority; } }); } /** * Ensure no more than numOpenNetworksKept open networks in configuration list. * @param wifiMgr * @param numOpenNetworksKept * @return Operation succeed or not. */ private static boolean checkForExcessOpenNetworkAndSave(final WifiManager wifiMgr, final int numOpenNetworksKept) { final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); sortByPriority(configurations); boolean modified = false; int tempCount = 0; for(int i = configurations.size() - 1; i >= 0; i--) { final WifiConfiguration config = configurations.get(i); if(ConfigSec.isOpenNetwork(ConfigSec.getWifiConfigurationSecurity(config))) { tempCount++; if(tempCount >= numOpenNetworksKept) { modified = true; wifiMgr.removeNetwork(config.networkId); } } } if(modified) { return wifiMgr.saveConfiguration(); } return true; } private static final int MAX_PRIORITY = 99999; private static int shiftPriorityAndSave(final WifiManager wifiMgr) { final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); sortByPriority(configurations); final int size = configurations.size(); for(int i = 0; i < size; i++) { final WifiConfiguration config = configurations.get(i); config.priority = i; wifiMgr.updateNetwork(config); } wifiMgr.saveConfiguration(); return size; } private static int getMaxPriority(final WifiManager wifiManager) { final List<WifiConfiguration> configurations = wifiManager.getConfiguredNetworks(); int pri = 0; for(final WifiConfiguration config : configurations) { if(config.priority > pri) { pri = config.priority; } } return pri; } public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final ScanResult hotsopt, String hotspotSecurity) { final String ssid = convertToQuotedString(hotsopt.SSID); if(ssid.length() == 0) { return null; } final String bssid = hotsopt.BSSID; if(bssid == null) { return null; } if(hotspotSecurity == null) { hotspotSecurity = ConfigSec.getScanResultSecurity(hotsopt); } final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); if(configurations == null) { return null; } for(final WifiConfiguration config : configurations) { if(config.SSID == null || !ssid.equals(config.SSID)) { continue; } if(config.BSSID == null || bssid.equals(config.BSSID)) { final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config); if(hotspotSecurity.equals(configSecurity)) { return config; } } } return null; } public static WifiConfiguration getWifiConfiguration(final WifiManager wifiMgr, final WifiConfiguration configToFind, String security) { final String ssid = configToFind.SSID; if(ssid.length() == 0) { return null; } final String bssid = configToFind.BSSID; if(security == null) { security = ConfigSec.getWifiConfigurationSecurity(configToFind); } final List<WifiConfiguration> configurations = wifiMgr.getConfiguredNetworks(); for(final WifiConfiguration config : configurations) { if(config.SSID == null || !ssid.equals(config.SSID)) { continue; } if(config.BSSID == null || bssid == null || bssid.equals(config.BSSID)) { final String configSecurity = ConfigSec.getWifiConfigurationSecurity(config); if(security.equals(configSecurity)) { return config; } } } return null; } public static String convertToQuotedString(String string) { if (TextUtils.isEmpty(string)) { return ""; } final int lastPos = string.length() - 1; if(lastPos > 0 && (string.charAt(0) == '"' && string.charAt(lastPos) == '"')) { return string; } return "\"" + string + "\""; } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import android.content.Intent; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends Floating { public static final String EXTRA_HOTSPOT = "com.farproc.wifi.connecter.extra.HOTSPOT"; private ScanResult mScanResult; private Floating.Content mContent; private WifiManager mWifiManager; @Override protected void onNewIntent (Intent intent) { setIntent(intent); // This activity has "singleInstance" launch mode. // Update content to reflect the newest intent. doNewIntent(intent); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mWifiManager = (WifiManager)getSystemService(WIFI_SERVICE); doNewIntent(getIntent()); } private boolean isAdHoc(final ScanResult scanResule) { return scanResule.capabilities.indexOf("IBSS") != -1; } private void doNewIntent(final Intent intent) { mScanResult = intent.getParcelableExtra(EXTRA_HOTSPOT); if(mScanResult == null) { Toast.makeText(this, "No data in Intent!", Toast.LENGTH_LONG).show(); finish(); return; } if(isAdHoc(mScanResult)) { Toast.makeText(this, R.string.adhoc_not_supported_yet, Toast.LENGTH_LONG).show(); finish(); return; } final String security = Wifi.ConfigSec.getScanResultSecurity(mScanResult); final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, security); if(config == null) { mContent = new NewNetworkContent(this, mWifiManager, mScanResult); } else { final boolean isCurrentNetwork_ConfigurationStatus = config.status == WifiConfiguration.Status.CURRENT; final WifiInfo info = mWifiManager.getConnectionInfo(); final boolean isCurrentNetwork_WifiInfo = info != null && android.text.TextUtils.equals(info.getSSID(), mScanResult.SSID) && android.text.TextUtils.equals(info.getBSSID(), mScanResult.BSSID); if(isCurrentNetwork_ConfigurationStatus || isCurrentNetwork_WifiInfo) { mContent = new CurrentNetworkContent(this, mWifiManager, mScanResult); } else { mContent = new ConfiguredNetworkContent(this, mWifiManager, mScanResult); } } setContent(mContent); } }
Java
/* * Wifi Connecter * * Copyright (c) 20101 Kevin Yuan (farproc@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * **/ package com.farproc.wifi.connecter; import com.farproc.wifi.connecter.R; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.SupplicantState; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnClickListener; import android.widget.TextView; import android.widget.Toast; public class CurrentNetworkContent extends BaseContent { public CurrentNetworkContent(Floating floating, WifiManager wifiManager, ScanResult scanResult) { super(floating, wifiManager, scanResult); mView.findViewById(R.id.Status).setVisibility(View.GONE); mView.findViewById(R.id.Speed).setVisibility(View.GONE); mView.findViewById(R.id.IPAddress).setVisibility(View.GONE); mView.findViewById(R.id.Password).setVisibility(View.GONE); final WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); if(wifiInfo == null) { Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show(); } else { final SupplicantState state = wifiInfo.getSupplicantState(); final NetworkInfo.DetailedState detailedState = WifiInfo.getDetailedStateOf(state); if(detailedState == NetworkInfo.DetailedState.CONNECTED || (detailedState == NetworkInfo.DetailedState.OBTAINING_IPADDR && wifiInfo.getIpAddress() != 0)) { mView.findViewById(R.id.Status).setVisibility(View.VISIBLE); mView.findViewById(R.id.Speed).setVisibility(View.VISIBLE); mView.findViewById(R.id.IPAddress).setVisibility(View.VISIBLE); ((TextView)mView.findViewById(R.id.Status_TextView)).setText(R.string.status_connected); ((TextView)mView.findViewById(R.id.LinkSpeed_TextView)).setText(wifiInfo.getLinkSpeed() + " " + WifiInfo.LINK_SPEED_UNITS); ((TextView)mView.findViewById(R.id.IPAddress_TextView)).setText(getIPAddress(wifiInfo.getIpAddress())); } else if(detailedState == NetworkInfo.DetailedState.AUTHENTICATING || detailedState == NetworkInfo.DetailedState.CONNECTING || detailedState == NetworkInfo.DetailedState.OBTAINING_IPADDR) { mView.findViewById(R.id.Status).setVisibility(View.VISIBLE); ((TextView)mView.findViewById(R.id.Status_TextView)).setText(R.string.status_connecting); } } } @Override public int getButtonCount() { // No Modify button for open network. return mIsOpenNetwork ? 2 : 3; } @Override public OnClickListener getButtonOnClickListener(int index) { if(mIsOpenNetwork && index == 1) { // No Modify button for open network. // index 1 is Cancel(index 2). return mOnClickListeners[2]; } return mOnClickListeners[index]; } @Override public CharSequence getButtonText(int index) { switch(index) { case 0: return mFloating.getString(R.string.forget_network); case 1: if(mIsOpenNetwork) { // No Modify button for open network. // index 1 is Cancel. return getCancelString(); } return mFloating.getString(R.string.button_change_password); case 2: return getCancelString(); default: return null; } } @Override public CharSequence getTitle() { return mScanResult.SSID; } private OnClickListener mForgetOnClick = new OnClickListener() { @Override public void onClick(View v) { final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity); boolean result = false; if(config != null) { result = mWifiManager.removeNetwork(config.networkId) && mWifiManager.saveConfiguration(); } if(!result) { Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show(); } mFloating.finish(); } }; private OnClickListener mOnClickListeners[] = {mForgetOnClick, mChangePasswordOnClick, mCancelOnClick}; private String getIPAddress(int address) { StringBuilder sb = new StringBuilder(); sb.append(address & 0x000000FF).append(".") .append((address & 0x0000FF00) >> 8).append(".") .append((address & 0x00FF0000) >> 16).append(".") .append((address & 0xFF000000L) >> 24); return sb.toString(); } @Override public boolean onContextItemSelected(MenuItem item) { return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ExternalStorage.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.commons; import android.os.Environment; /** * The class Geometry contains external storage functions. * * @author Pierre Malarme * @version 1.O * */ public class ExternalStorage { // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * @return True if the external storage is available. * False otherwise. */ public static boolean checkAvailable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if available if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } /** * @return True if the external storage is writable. * False otherwise. */ public static boolean checkWritable() { // Retrieving the external storage state String state = Environment.getExternalStorageState(); // Check if writable if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMViewerData.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.data; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ScaleMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ToolMode; /** * Class containing the data specific * to the DICOM Viewer. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMViewerData { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * The tool mode. */ private short mToolMode = ToolMode.DIMENSION; /** * CLUT mode. */ private short mCLUTMode = CLUTMode.NORMAL; /** * The scale mode: fit in or real size. */ private short mScaleMode = ScaleMode.FITIN; /** * Grayscale window width. */ private int mWindowWidth = -1; /** * Grayscale window center */ private int mWindowCenter = -1; /** * @return the mToolMode */ public short getToolMode() { return mToolMode; } /** * @return the mCLUTMode */ public short getCLUTMode() { return mCLUTMode; } /** * @return the mScaleMode */ public short getScaleMode() { return mScaleMode; } /** * @return the mWindowWidth */ public int getWindowWidth() { return mWindowWidth; } /** * @return the mWindowCenter */ public int getWindowCenter() { return mWindowCenter; } /** * @param mToolMode the mToolMode to set */ public void setToolMode(short mToolMode) { this.mToolMode = mToolMode; } /** * @param mCLUTMode the mCLUTMode to set */ public void setCLUTMode(short mCLUTMode) { this.mCLUTMode = mCLUTMode; } /** * @param mScaleMode the mScaleMode to set */ public void setScaleMode(short mScaleMode) { this.mScaleMode = mScaleMode; } /** * @param mWindowWidth the mWindowWidth to set */ public void setWindowWidth(int mWindowWidth) { // The minimum window width is 1 // cf. DICOM documentation if (mWindowWidth <= 0) this.mWindowWidth = 1; else this.mWindowWidth = mWindowWidth; } /** * @param mWindowCenter the mWindowCenter to set */ public void setWindowCenter(int mWindowCenter) { this.mWindowCenter = mWindowCenter; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ScaleMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class ScaleMode contains the image scale modes. * * @author Pierre Malarme * @version 1.0 * */ public final class ScaleMode { /** * Fit in. */ public static final short FITIN = 0; /** * Image real size (1:1). */ public static final short REALSIZE = 1; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <TouchMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class TouchMode contains the touch modes. * * @author Pierre Malarme * @version 1.0 * */ public final class TouchMode { /** * No touch mode. */ public static final short NONE = 0; /** * One finger mode. */ public static final short ONE_FINGER = 1; /** * Two fingers mode. */ public static final short TWO_FINGERS = 2; /** * Three fingers mode. */ public static final short THREE_FINGERS = 3; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <CLUTMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class CLUTMode contains the LUT/CLUT modes. * * @author Pierre Malarme * @version 1.0 * */ public final class CLUTMode { /** * Normal grayscale LUT. */ public static final short NORMAL = 0; /** * Inverse LUT. */ public static final short INVERSE = 1; /** * Color rainbow CLUT. */ public static final short RAINBOW = 2; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ToolMode.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.mode; /** * The class ToolMode contains the tool modes. * * @author Pierre Malarme * @version 1.0 * */ public final class ToolMode { /** * Change the size and the position of the image. */ public static final short DIMENSION = 0; /** * Change the grayscale window center and position. */ public static final short GRAYSCALE = 1; /** * Rotate the image. */ public static final short ROTATION = 2; /** * Crop the image. */ public static final short CROP = 3; /** * Make measurement on the image. */ public static final short MEASURE = 4; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMViewer.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.1 * */ package be.ac.ulb.lisa.idot.android.dicomviewer; import java.io.File; import java.io.FileNotFoundException; import java.util.Arrays; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import be.ac.ulb.lisa.idot.android.commons.ExternalStorage; import be.ac.ulb.lisa.idot.android.dicomviewer.data.DICOMViewerData; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ScaleMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ToolMode; import be.ac.ulb.lisa.idot.android.dicomviewer.thread.DICOMImageCacher; import be.ac.ulb.lisa.idot.android.dicomviewer.thread.ThreadState; import be.ac.ulb.lisa.idot.android.dicomviewer.view.DICOMImageView; import be.ac.ulb.lisa.idot.android.dicomviewer.view.GrayscaleWindowView; import be.ac.ulb.lisa.idot.dicom.data.DICOMImage; import be.ac.ulb.lisa.idot.dicom.file.DICOMFileFilter; import be.ac.ulb.lisa.idot.dicom.file.DICOMImageReader; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; import be.ac.ulb.lisa.idot.image.file.LISAImageGray16BitReader; import be.ac.ulb.lisa.idot.image.file.LISAImageGray16BitWriter; /** * DicomViewer activity that shows an image. * * @author Pierre Malarme * @version 1.1 * */ public class DICOMViewer extends Activity implements SeekBar.OnSeekBarChangeListener { // --------------------------------------------------------------- // - <static> VARIABLES // --------------------------------------------------------------- // DIALOG /** * Define the progress dialog id for the loading of a DICOM image. */ private static final short PROGRESS_DIALOG_LOAD = 0; /** * Define the progress dialog id for the caching of * DICOM image. */ private static final short PROGRESS_DIALOG_CACHE = 1; // SAVED INSTANCE STATE KEY /** * Define the key for savedInstanceState */ private static final String FILE_NAME = "file_name"; // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- // UI VARIABLES /** * The image view. */ private DICOMImageView mImageView; /** * The tool bar linear layout. */ private LinearLayout mToolBar; /** * Set if the tool bar is locked or not. */ private boolean mLockToolBar = false; /** * The button to set the mToolMode to * ToolMode.DIMENSION. */ private Button mDimensionToolButton; /** * The button to set the mToolMode to * ToolMode.GRAYSCALE. */ private Button mGrayscaleToolButton; /** * Normal CLUT button. */ private Button mCLUTNormalButton; /** * Inverse CLUT button. */ private Button mCLUTInverseButton; /** * Rainbow CLUT button. */ private Button mCLUTRainbowButton; /** * Lock/unlock tool bar button. */ private Button mLockUnlockToolBar; /** * Current tool button. */ private Button mCurrentToolButton; /** * The grayscale window (ImageView). */ private GrayscaleWindowView mGrayscaleWindow; /** * Previous button. */ private Button mPreviousButton; /** * Next button. */ private Button mNextButton; /** * Image index TextView. */ private TextView mIndexTextView; /** * Series seek bar. */ private SeekBar mIndexSeekBar; /** * Layout representing the series * navigation bar. */ private LinearLayout mNavigationBar; /** * Row orientation TextView. */ private TextView mRowOrientation; /** * Column orientation TextView. */ private TextView mColumnOrientation; // MENU VARIABLE /** * DICOM Viewer menu. */ private Menu mMenu; // DICOM FILE LOADER THREAD /** * File loader thread. */ private DICOMFileLoader mDICOMFileLoader = null; // WAIT VARIABLE /** * Progress dialog for file loading. */ private ProgressDialog loadingDialog; /** * Progress dialog for file caching. */ private ProgressDialog cachingDialog; /** * Set if the activity is busy (true) or not (false). * When a DICOM image is parsed or a LISA 16-Bit grayscale * image is loaded, the activity is in waiting mode * => busy = true. */ private boolean mBusy = false; // TODO needed ? or wait for the end of the loading thread // is enough ? // FILE VARIABLE /** * The array of DICOM image in the * folder. */ private File[] mFileArray = null; /** * The LISA 16-Bit image. */ private LISAImageGray16Bit mImage = null; /** * The index of the current file. */ private int mCurrentFileIndex; // INITIALIZATION VARIABLE /** * Set if the DICOM Viewer is initialized or not. */ private boolean mIsInitialized = false; // DATA VARIABLE /** * DICOM Viewer data. */ private DICOMViewerData mDICOMViewerData = null; // --------------------------------------------------------------- // # <override> FUNCTIONS // --------------------------------------------------------------- @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content view setContentView(R.layout.dicom_viewer); // Declare the UI variables mImageView = (DICOMImageView) findViewById(R.id.imageView); mToolBar = (LinearLayout) findViewById(R.id.toolBar); mDimensionToolButton = (Button) findViewById(R.id.dimensionMode); mGrayscaleToolButton = (Button) findViewById(R.id.grayscaleMode); mCLUTNormalButton = (Button) findViewById(R.id.clutNormal); mCLUTInverseButton = (Button) findViewById(R.id.clutInverse); mCLUTRainbowButton = (Button) findViewById(R.id.clutRainbow); mLockUnlockToolBar = (Button) findViewById(R.id.lockUnlockToolbar); mCurrentToolButton = (Button) findViewById(R.id.currentToolButton); mGrayscaleWindow = (GrayscaleWindowView) findViewById(R.id.grayscaleImageView); mPreviousButton = (Button) findViewById(R.id.previousImageButton); mNextButton = (Button) findViewById(R.id.nextImageButton); mIndexTextView = (TextView) findViewById(R.id.imageIndexView); mIndexSeekBar = (SeekBar) findViewById(R.id.serieSeekBar); mNavigationBar = (LinearLayout) findViewById(R.id.navigationToolbar); mRowOrientation = (TextView) findViewById(R.id.rowTextView); mColumnOrientation = (TextView) findViewById(R.id.columnTextView); // Get the file name from the savedInstanceState or from the intent String fileName = null; // If the saved instance state is not null get the file name if (savedInstanceState != null) { fileName = savedInstanceState.getString(FILE_NAME); // Get the intent } else { Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); fileName = extras == null ? null : extras.getString("DICOMFileName"); } } // If the file name is null, alert the user and close // the activity if (fileName == null) { showExitAlertDialog("[ERROR] Loading file", "The file cannot be loaded.\n\n" + "Cannot retrieve its name."); // Load the file } else { // Get the File object for the current file File currentFile = new File(fileName); // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, currentFile); mDICOMFileLoader.start(); mBusy = true; // Get the files array = get the files contained // in the parent of the current file mFileArray = currentFile.getParentFile().listFiles(new DICOMFileFilter()); // Sort the files array Arrays.sort(mFileArray); // If the files array is null or its length is less than 1, // there is an error because it must at least contain 1 file: // the current file if (mFileArray == null || mFileArray.length < 1) { showExitAlertDialog("[ERROR] Loading file", "The file cannot be loaded.\n\n" + "The directory containing normally the file contains" + " no DICOM files."); } else { // Get the file index in the array mCurrentFileIndex = getIndex(currentFile); // If the current file index is negative // or greater or equal to the files array // length there is an error if (mCurrentFileIndex < 0 || mCurrentFileIndex >= mFileArray.length) { showExitAlertDialog("[ERROR] Loading file", "The file cannot be loaded.\n\n" + "The file is not in the directory."); // Else initialize views and navigation bar } else { // Check if the seek bar must be shown or not if (mFileArray.length == 1) { mNavigationBar.setVisibility(View.INVISIBLE); } else { // Display the current file index mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); // Display the files count and set the seek bar maximum TextView countTextView = (TextView) findViewById(R.id.imageCountView); countTextView.setText(String.valueOf(mFileArray.length)); mIndexSeekBar.setMax(mFileArray.length - 1); mIndexSeekBar.setProgress(mCurrentFileIndex); // Set the visibility of the previous button if (mCurrentFileIndex == 0) { mPreviousButton.setVisibility(View.INVISIBLE); } else if (mCurrentFileIndex == (mFileArray.length - 1)) { mNextButton.setVisibility(View.INVISIBLE); } } } } } // Set the seek bar change index listener mIndexSeekBar.setOnSeekBarChangeListener(this); // Set onLongClickListener mIndexSeekBar.setOnLongClickListener(onLongClickListener); mNavigationBar.setOnLongClickListener(onLongClickListener); mPreviousButton.setOnLongClickListener(onLongClickListener); mNextButton.setOnLongClickListener(onLongClickListener); mToolBar.setOnLongClickListener(onLongClickListener); mGrayscaleWindow.setOnLongClickListener(onLongClickListener); // Create the DICOMViewerData and set // the tool mode to dimension mDICOMViewerData = new DICOMViewerData(); mDICOMViewerData.setToolMode(ToolMode.DIMENSION); mDimensionToolButton.setBackgroundResource(R.drawable.ruler_select); mCurrentToolButton.setBackgroundResource(R.drawable.ruler_select); mCLUTNormalButton.setVisibility(View.GONE); mCLUTNormalButton.setBackgroundResource(R.drawable.clut_normal_select); mCLUTInverseButton.setVisibility(View.GONE); mCLUTRainbowButton.setVisibility(View.GONE); mToolBar.setVisibility(View.GONE); // Set the tool mode too the DICOMImageView and // the GrayscaleWindow mImageView.setDICOMViewerData(mDICOMViewerData); mGrayscaleWindow.setDICOMViewerData(mDICOMViewerData); } /* (non-Javadoc) * @see android.app.Activity#onResume() */ @Override protected void onResume() { // If there is no external storage available, quit the application if (!ExternalStorage.checkAvailable()) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("There is no external storage.\n" + "1) There is no external storage : add one.\n" + "2) Your external storage is used by a computer:" + " Disconnect the it from the computer.") .setTitle("[ERROR] No External Storage") .setCancelable(false) .setPositiveButton("Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DICOMViewer.this.finish(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } super.onResume(); } /* (non-Javadoc) * @see android.app.Activity#onPause() */ @Override protected void onPause() { // We wait until the end of the loading thread // before putting the activity in pause mode if (mDICOMFileLoader != null) { // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } } super.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mImage = null; mDICOMViewerData = null; mFileArray = null; mDICOMFileLoader = null; // Free the drawable callback if (mImageView != null) { Drawable drawable = mImageView.getDrawable(); if (drawable != null) drawable.setCallback(null); } } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Save the current file name String currentFileName = mFileArray[mCurrentFileIndex].getAbsolutePath(); outState.putString(FILE_NAME, currentFileName); } @Override protected Dialog onCreateDialog(int id) { // TODO : cancelable dialog ? switch(id) { // Create image cache dialog case PROGRESS_DIALOG_CACHE: cachingDialog = new ProgressDialog(this); cachingDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); cachingDialog.setMessage("Caching image..."); cachingDialog.setCancelable(false); return cachingDialog; // Create image load dialog case PROGRESS_DIALOG_LOAD: loadingDialog = new ProgressDialog(this); loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); loadingDialog.setMessage("Loading image..."); loadingDialog.setCancelable(false); return loadingDialog; default: return null; } } // --------------------------------------------------------------- // + <override> FUNCTIONS // --------------------------------------------------------------- @Override public void onLowMemory() { // Hint the garbage collector System.gc(); // Show the exit alert dialog showExitAlertDialog("[ERROR] LowMemory", "[ERROR] LowMemory"); super.onLowMemory(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // It's safer to hold the menu (cf. Android // documentation) mMenu = menu; // Inflate the currently selected menu XML resource. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.dicom_viewer_menu, menu); // Set the show/hide grayscale window state MenuItem grayscaleShowHide = menu.findItem(R.id.showHide_grayscaleWindow); if (mGrayscaleWindow.getVisibility() == View.INVISIBLE) grayscaleShowHide.setChecked(false); else grayscaleShowHide.setChecked(true); // Set the show/hide series navigation bar MenuItem serieNavigationBar = menu.findItem(R.id.showHide_serieSeekBar); if (mNavigationBar.getVisibility() == View.INVISIBLE) serieNavigationBar.setChecked(false); else serieNavigationBar.setChecked(true); // If there is at most one file if (mFileArray.length <= 1) serieNavigationBar.setEnabled(false); else serieNavigationBar.setEnabled(true); // Set the show/hide tool bar MenuItem toolBar = menu.findItem(R.id.showHide_toolbar); if (mToolBar.getVisibility() == View.GONE && mCurrentToolButton.getVisibility() == View.INVISIBLE) toolBar.setChecked(false); else toolBar.setChecked(true); // Set the CLUT mode switch (mDICOMViewerData.getCLUTMode()) { case CLUTMode.NORMAL: MenuItem clutMode = menu.findItem(R.id.show_normalLUT); clutMode.setChecked(true); break; case CLUTMode.INVERSE: clutMode = menu.findItem(R.id.show_inverseLUT); clutMode.setChecked(true); break; case CLUTMode.RAINBOW: clutMode = menu.findItem(R.id.show_rainbowCLUT); clutMode.setChecked(true); break; } // Set the lock/unlock tool bar menu time MenuItem lockUnlockToolBar = menu.findItem(R.id.lock_toolbar); if (mLockToolBar) lockUnlockToolBar.setChecked(true); else lockUnlockToolBar.setChecked(false); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // SHOW/HIDE case R.id.showHide_grayscaleWindow: if (mGrayscaleWindow.getVisibility() == View.INVISIBLE) { item.setChecked(true); mGrayscaleWindow.setVisibility(View.VISIBLE); } else { item.setChecked(false); mGrayscaleWindow.setVisibility(View.INVISIBLE); } return true; case R.id.showHide_serieSeekBar: if(mNavigationBar.getVisibility() == View.INVISIBLE) { item.setChecked(true); mNavigationBar.setVisibility(View.VISIBLE); } else { item.setChecked(false); mNavigationBar.setVisibility(View.INVISIBLE); } return true; case R.id.showHide_toolbar: if(mToolBar.getVisibility() == View.VISIBLE || mCurrentToolButton.getVisibility() == View.VISIBLE) { item.setChecked(false); hideToolBar(null); mCurrentToolButton.setVisibility(View.INVISIBLE); } else { item.setChecked(false); if (mLockToolBar) showToolBar(null); else mCurrentToolButton.setVisibility(View.VISIBLE); } return true; case R.id.lock_toolbar: if (mLockToolBar) { item.setChecked(false); mLockToolBar = false; mLockUnlockToolBar.setBackgroundResource(R.drawable.unlock); hideToolBar(null); } else { item.setChecked(true); mLockToolBar = true; mLockUnlockToolBar.setBackgroundResource(R.drawable.lock); showToolBar(null); } return true; // LUT/CLUT case R.id.show_normalLUT: item.setChecked(true); mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal_select); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.NORMAL); mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); return true; case R.id.show_inverseLUT: item.setChecked(true); mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse_select); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.INVERSE); mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); return true; case R.id.show_rainbowCLUT: item.setChecked(true); mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow_select); mDICOMViewerData.setCLUTMode(CLUTMode.RAINBOW); mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); return true; // GRAYSCALE WINDOW case R.id.grayscaleWindow_CTBone: mDICOMViewerData.setWindowWidth(1500); mDICOMViewerData.setWindowCenter(300 + 1024); mImageView.draw(); return true; case R.id.grayscaleWindow_CTCrane: mDICOMViewerData.setWindowWidth(100); mDICOMViewerData.setWindowCenter(50 + 1024); mImageView.draw(); return true; case R.id.grayscaleWindow_CTLung: mDICOMViewerData.setWindowWidth(1400); mDICOMViewerData.setWindowCenter(1024 - 400); mImageView.draw(); return true; case R.id.grayscaleWindow_CTAbdomen: mDICOMViewerData.setWindowWidth(350); mDICOMViewerData.setWindowCenter(40 + 1024); mImageView.draw(); return true; // IMAGE SCALE MODE case R.id.fit_to_screen: item.setChecked(true); mDICOMViewerData.setScaleMode(ScaleMode.FITIN); mImageView.resetSize(); return true; case R.id.real_size: item.setChecked(true); mDICOMViewerData.setScaleMode(ScaleMode.REALSIZE); mImageView.resetSize(); return true; // CACHE ALL IMAGES case R.id.ddv_CacheAllImage: cacheImages(); return true; // ABOUT DIALOG case R.id.ddv_DialogAbout: Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.dialog_about); dialog.setTitle("Droid Dicom Viewer: About"); dialog.show(); return true; } return super.onOptionsItemSelected(item); } // --------------------------------------------------------------- // + <implements> FUNCTION // --------------------------------------------------------------- /* (non-Javadoc) * @see android.widget.SeekBar.OnSeekBarChangeListener#onProgressChanged(android.widget.SeekBar, int, boolean) */ public synchronized void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { try { // If it is busy, do nothing if (mBusy) return; // It is busy now mBusy = true; // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } // Set the current file index mCurrentFileIndex = progress; // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, mFileArray[mCurrentFileIndex]); mDICOMFileLoader.start(); // Update the UI mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); // Set the visibility of the previous button if (mCurrentFileIndex == 0) { mPreviousButton.setVisibility(View.INVISIBLE); mNextButton.setVisibility(View.VISIBLE); } else if (mCurrentFileIndex == (mFileArray.length - 1)) { mNextButton.setVisibility(View.INVISIBLE); mPreviousButton.setVisibility(View.VISIBLE); } else { mPreviousButton.setVisibility(View.VISIBLE); mNextButton.setVisibility(View.VISIBLE); } } catch (OutOfMemoryError ex) { System.gc(); showExitAlertDialog("[ERROR] Out Of Memory", "This series contains images that are too big" + " and that cause out of memory error. The best is to don't" + " use the series seek bar. If the error occurs again" + " it is because this series is not adapted to your" + " Android(TM) device."); } } // Needed to implement the SeekBar.OnSeekBarChangeListener public void onStartTrackingTouch(SeekBar seekBar) { // Do nothing. } // Needed to implement the SeekBar.OnSeekBarChangeListener public void onStopTrackingTouch(SeekBar seekBar) { System.gc(); // TODO needed ? // Do nothing. } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Set mToolMode to ToolMode.DIMENSION. * * @param view The view that call the handler. Can be null */ public void dimensionMode(View view) { if (mDICOMViewerData.getToolMode() != ToolMode.DIMENSION) { mDICOMViewerData.setToolMode(ToolMode.DIMENSION); mDimensionToolButton.setBackgroundResource(R.drawable.ruler_select); mCurrentToolButton.setBackgroundResource(R.drawable.ruler_select); mGrayscaleToolButton.setBackgroundResource(R.drawable.grayscale); mCLUTNormalButton.setVisibility(View.GONE); mCLUTInverseButton.setVisibility(View.GONE); mCLUTRainbowButton.setVisibility(View.GONE); } if (!mLockToolBar) hideToolBar(view); } /** * Set mToolMode to ToolMode.GRAYSCALE. * * @param view The view that call the handler. Can be null */ public void grayscaleMode(View view) { if (mDICOMViewerData.getToolMode() != ToolMode.GRAYSCALE) { mDICOMViewerData.setToolMode(ToolMode.GRAYSCALE); mGrayscaleToolButton.setBackgroundResource(R.drawable.grayscale_select); mCurrentToolButton.setBackgroundResource(R.drawable.grayscale_select); mDimensionToolButton.setBackgroundResource(R.drawable.ruler); mCLUTNormalButton.setVisibility(View.VISIBLE); mCLUTInverseButton.setVisibility(View.VISIBLE); mCLUTRainbowButton.setVisibility(View.VISIBLE); } if (!mLockToolBar) hideToolBar(view); } // --------------------------------------------------------------- // + <synchronized> FUNCTIONS // --------------------------------------------------------------- /** * Handle touch on the previousButton. * @param view */ public synchronized void previousImage(View view) { // If it is busy, do nothing if (mBusy) return; // It is busy now mBusy = true; // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } // If the current file index is 0, there is // no previous file in the files array // We add the less or equal to zero because it is // safer if (mCurrentFileIndex <= 0) { // Not necessary but safer, because we don't know // how the code will be used in the future mCurrentFileIndex = 0; // If for a unknown reason the previous button is // visible => hide it if (mPreviousButton.getVisibility() == View.VISIBLE) mPreviousButton.setVisibility(View.INVISIBLE); mBusy = false; return; } // Decrease the file index mCurrentFileIndex--; // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, mFileArray[mCurrentFileIndex]); mDICOMFileLoader.start(); // Update the UI mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); mIndexSeekBar.setProgress(mCurrentFileIndex); if (mCurrentFileIndex == 0) mPreviousButton.setVisibility(View.INVISIBLE); // The next button is automatically set to visible // because if there is a previous image, there is // a next image mNextButton.setVisibility(View.VISIBLE); } /** * Handle touch on next button. * @param view */ public synchronized void nextImage(View view) { // If it is busy, do nothing if (mBusy) return; // It is busy now mBusy = true; // Wait until the loading thread die while (mDICOMFileLoader.isAlive()) { try { synchronized(this) { wait(10); } } catch (InterruptedException e) { // Do nothing } } // If the current file index is the last file index, // there is no next file in the files array // We add the greater or equal to (mFileArray.length - 1) // because it is safer if (mCurrentFileIndex >= (mFileArray.length - 1)) { // Not necessary but safer, because we don't know // how the code will be used in the future mCurrentFileIndex = (mFileArray.length - 1); // If for a unknown reason the previous button is // visible => hide it if (mNextButton.getVisibility() == View.VISIBLE) mNextButton.setVisibility(View.INVISIBLE); mBusy = false; return; } // Increase the file index mCurrentFileIndex++; // Start the loading thread to load the DICOM image mDICOMFileLoader = new DICOMFileLoader(loadingHandler, mFileArray[mCurrentFileIndex]); mDICOMFileLoader.start(); // Update the UI mIndexTextView.setText(String.valueOf(mCurrentFileIndex + 1)); mIndexSeekBar.setProgress(mCurrentFileIndex); if (mCurrentFileIndex == (mFileArray.length - 1)) mNextButton.setVisibility(View.INVISIBLE); // The previous button is automatically set to visible // because if there is a next image, there is // a previous image mPreviousButton.setVisibility(View.VISIBLE); } /** * Hide navigation tool bar if it is visible. * @param view */ public void hideNavigationBar(View view) { if (mNavigationBar.getVisibility() == View.VISIBLE) { mNavigationBar.setVisibility(View.INVISIBLE); if (mMenu != null) { MenuItem showHideNavigationBar = mMenu.findItem(R.id.showHide_serieSeekBar); if (showHideNavigationBar != null) { showHideNavigationBar.setChecked(false); } } } } /** * Hide navigation tool bar if it is visible. * @param view */ public void hideGrayscaleWindow(View view) { if (mGrayscaleWindow.getVisibility() == View.VISIBLE) { mGrayscaleWindow.setVisibility(View.INVISIBLE); if (mMenu != null) { MenuItem showHideGrayscaleWindow = mMenu.findItem(R.id.showHide_grayscaleWindow); if (showHideGrayscaleWindow != null) { showHideGrayscaleWindow.setChecked(false); } } } } /** * Hide tool bar if it is visible. * @param view */ public void hideToolBar(View view) { if (mToolBar.getVisibility() == View.VISIBLE) { mToolBar.setVisibility(View.GONE); // If the tool bar is locked then the current icon // is invisible too if (!mLockToolBar) { mCurrentToolButton.setVisibility(View.VISIBLE); } else { if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.showHide_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(false); } } } } } /** * Hide tool bar if it is visible. * @param view */ public void showToolBar(View view) { if (mToolBar.getVisibility() == View.GONE) { mCurrentToolButton.setVisibility(View.INVISIBLE); mToolBar.setVisibility(View.VISIBLE); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.showHide_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } } } /** * Set the CLUT mode. * @param view */ public synchronized void setCLUTMode(View view) { if (view == null) return; switch (view.getId()) { case R.id.clutNormal: mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal_select); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.NORMAL); // Update the menu if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.show_normalLUT); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } break; case R.id.clutInverse: mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse_select); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow); mDICOMViewerData.setCLUTMode(CLUTMode.INVERSE); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.show_inverseLUT); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } break; case R.id.clutRainbow: mCLUTNormalButton.setBackgroundResource( R.drawable.clut_normal); mCLUTInverseButton.setBackgroundResource( R.drawable.clut_inverse); mCLUTRainbowButton.setBackgroundResource( R.drawable.clut_rainbow_select); mDICOMViewerData.setCLUTMode(CLUTMode.RAINBOW); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.show_rainbowCLUT); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } break; } mGrayscaleWindow.updateCLUTMode(); mImageView.draw(); if (!mLockToolBar) hideToolBar(null); } /** * Lock/unlock the tool bar. * @param view */ public void lockUnlockToolBar(View view) { if (mLockToolBar) { mLockToolBar = false; mLockUnlockToolBar.setBackgroundResource(R.drawable.unlock); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.lock_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(false); } } hideToolBar(view); } else { mLockToolBar = true; mLockUnlockToolBar.setBackgroundResource(R.drawable.lock); if (mMenu != null) { MenuItem showHideToolBar = mMenu.findItem(R.id.lock_toolbar); if (showHideToolBar != null) { showHideToolBar.setChecked(true); } } } } // --------------------------------------------------------------- // - FUNCTIONS // --------------------------------------------------------------- /** * Get the index of the file in the files array. * @param file * @return Index of the file in the files array * or -1 if the files is not in the list. */ private int getIndex(File file) { if (mFileArray == null) throw new NullPointerException("The files array is null."); for (int i = 0; i < mFileArray.length; i++) { if (mFileArray[i].getName().equals(file.getName())) return i; } return -1; } /** * Set the currentImage * * @param image */ private void setImage(LISAImageGray16Bit image) { if (image == null) throw new NullPointerException("The LISA 16-Bit grayscale image " + "is null"); try { // Set the image mImage = null; mImage = image; mImageView.setImage(mImage); mGrayscaleWindow.setImage(mImage); setImageOrientation(); // If it is not initialized, set the window width and center // as the value set in the LISA 16-Bit grayscale image // that comes from the DICOM image file. if (!mIsInitialized) { mIsInitialized = true; mDICOMViewerData.setWindowWidth(mImage.getWindowWidth()); mDICOMViewerData.setWindowCenter(mImage.getWindowCenter()); mImageView.draw(); mImageView.fitIn(); } else { mImageView.draw(); } mBusy = false; } catch (OutOfMemoryError ex) { System.gc(); showExitAlertDialog("[ERROR] Out Of Memory", "This series contains images that are too big" + " and that cause out of memory error. The best is to don't" + " use the series seek bar. If the error occurs again" + " it is because this series is not adapted to your" + " Android(TM) device."); } catch (ArrayIndexOutOfBoundsException ex) { showExitAlertDialog("[ERROR] Image drawing", "An uncatchable error occurs while " + "drawing the DICOM image."); } } /** * Set the image orientation TextViews. */ private void setImageOrientation() { float[] imageOrientation = mImage.getImageOrientation(); if (imageOrientation == null || imageOrientation.length != 6 || imageOrientation.equals(new float[6])) // equal to a float with 6 zeros return; // Displaying the row orientation mRowOrientation.setText(getImageOrientationString(imageOrientation, 0)); // Displaying the column orientation mColumnOrientation.setText(getImageOrientationString(imageOrientation, 3)); } /** * Get the image orientation String for a 3D vector of float * that is related to a direction cosine. * * @param imageOrientation * @param offset * @return */ private String getImageOrientationString(float[] imageOrientation, int offset) { String orientation = ""; // The threshold is 0.25 // If abs(ImageOrientation.X) < threshold // and ImageOrientation.X > 0 => orientation: RL if (imageOrientation[0 + offset] >= 0.25) { orientation += "R"; // If abs(ImageOrientation.X) < threshold // and ImageOrientation.X < 0 => orientation: LR } else if (imageOrientation[0 + offset] <= -0.25) { orientation += "L"; } // If abs(ImageOrientation.Y) < threshold // and ImageOrientation.Y > 0 => orientation: AP if (imageOrientation[1 + offset] >= 0.25) { orientation += "A"; // If abs(ImageOrientation.Y) < threshold // and ImageOrientation.Y < 0 => orientation: PA } else if (imageOrientation[1 + offset] <= -0.25) { orientation += "P"; } // If abs(ImageOrientation.Z) < threshold // and ImageOrientation.Z > 0 => orientation: FH if (imageOrientation[2 + offset] >= 0.25) { orientation += "F"; // If abs(ImageOrientation.Z) < threshold // and ImageOrientation.Z < 0 => orientation: HF } else if (imageOrientation[2 + offset] <= -0.25) { orientation += "H"; } return orientation; } /** * Cache of the image in the files array */ private void cacheImages() { try { // The handler is inside the function because // normally this function is called once. final Handler cacheHandler = new Handler() { public void handleMessage(Message message) { switch (message.what) { case ThreadState.STARTED: cachingDialog.setMax(message.arg1); break; case ThreadState.PROGRESSION_UPDATE: cachingDialog.setProgress(message.arg1); break; case ThreadState.FINISHED: try { dismissDialog(PROGRESS_DIALOG_CACHE); } catch (IllegalArgumentException ex) { // Do nothing } break; case ThreadState.CATCHABLE_ERROR_OCCURRED: cachingDialog.setProgress(message.arg1); Toast.makeText(DICOMViewer.this, "[Error]: file (" + (String) message.obj + ") cannot be cached.", Toast.LENGTH_SHORT).show(); break; case ThreadState.UNCATCHABLE_ERROR_OCCURRED: try { dismissDialog(PROGRESS_DIALOG_CACHE); } catch (IllegalArgumentException ex) { // Do nothing } AlertDialog.Builder builder = new AlertDialog.Builder(DICOMViewer.this); builder.setMessage("Unknown error: An unknown error occurred during" + " images caching.") .setTitle("[ERROR] Caching file") .setCancelable(false) .setPositiveButton("Close", null); AlertDialog alertDialog = builder.create(); alertDialog.show(); break; case ThreadState.OUT_OF_MEMORY: try { dismissDialog(PROGRESS_DIALOG_CACHE); } catch (IllegalArgumentException ex) { // Do nothing } builder = new AlertDialog.Builder(DICOMViewer.this); builder.setMessage("OutOfMemoryError: During the caching of series files," + " an out of memory error occurred.\n\n" + "Your file(s) is (are) too large for your Android system. You can" + " try again in the file chooser. If the error occured again," + " then the image cannot be displayed on your device.\n" + "Try to use the Droid Dicom Viewer desktop file cacher software" + " (not available yet).") .setTitle("[ERROR] Caching file") .setCancelable(false) .setPositiveButton("Close", null); alertDialog = builder.create(); alertDialog.show(); break; }; } }; // Show the progress dialog for caching image showDialog(PROGRESS_DIALOG_CACHE); // Start the caching thread DICOMImageCacher dicomImageCacher = new DICOMImageCacher(cacheHandler, mFileArray[mCurrentFileIndex].getParent()); dicomImageCacher.start(); } catch (FileNotFoundException e) { // TODO display an error ? } } /** * Show an alert dialog (AlertDialog) to inform * the user that the activity must finish. * @param title Title of the AlertDialog. * @param message Message of the AlertDialog. */ private void showExitAlertDialog(String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message) .setTitle(title) .setCancelable(false) .setPositiveButton("Exit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DICOMViewer.this.finish(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } // --------------------------------------------------------------- // - <final> Class // --------------------------------------------------------------- /** * The OnLongClickListener. */ private final View.OnLongClickListener onLongClickListener = new View.OnLongClickListener() { public boolean onLongClick(View view) { if (view == null) return false; switch(view.getId()) { case R.id.toolBar: hideToolBar(view); return true; case R.id.grayscaleImageView: hideGrayscaleWindow(view); return true; case R.id.navigationToolbar: case R.id.previousImageButton: case R.id.nextImageButton: case R.id.serieSeekBar: hideNavigationBar(view); return true; default: return false; } } }; private final Handler loadingHandler = new Handler() { public void handleMessage(Message message) { switch (message.what) { case ThreadState.STARTED: showDialog(PROGRESS_DIALOG_LOAD); break; case ThreadState.FINISHED: try { dismissDialog(PROGRESS_DIALOG_LOAD); } catch (IllegalArgumentException ex) { // Do nothing } // Set the loaded image if (message.obj instanceof LISAImageGray16Bit) { setImage((LISAImageGray16Bit) message.obj); } break; case ThreadState.UNCATCHABLE_ERROR_OCCURRED: try { dismissDialog(PROGRESS_DIALOG_LOAD); } catch (IllegalArgumentException ex) { // Do nothing } // Get the error message String errorMessage; if (message.obj instanceof String) errorMessage = (String) message.obj; else errorMessage = "Unknown error"; // Show an alert dialog showExitAlertDialog("[ERROR] Loading file", "An error occured during the file loading.\n\n" + errorMessage); break; case ThreadState.OUT_OF_MEMORY: try { dismissDialog(PROGRESS_DIALOG_LOAD); } catch (IllegalArgumentException ex) { // Do nothing } // Show an alert dialog showExitAlertDialog("[ERROR] Loading file", "OutOfMemoryError: During the loading of image (" + mFileArray[mCurrentFileIndex].getName() + "), an out of memory error occurred.\n\n" + "Your file is too large for your Android system. You can" + " try to cache the image in the file chooser." + " If the error occured again, then the image cannot be displayed" + " on your device.\n" + "Try to use the Droid Dicom Viewer desktop file cacher software" + " (not available yet)."); break; } } }; // --------------------------------------------------------------- // - <static> CLASS // --------------------------------------------------------------- private static final class DICOMFileLoader extends Thread { // The handler to send message to the parent thread private final Handler mHandler; // The file to load private final File mFile; public DICOMFileLoader(Handler handler, File file) { if (handler == null) throw new NullPointerException("The handler is null while" + " calling the loading thread."); mHandler = handler; if (file == null) throw new NullPointerException("The file is null while" + " calling the loading thread."); mFile = file; } public void run() { // If the image data is null, do nothing. if (!mFile.exists()) { Message message = mHandler.obtainMessage(); message.what = ThreadState.UNCATCHABLE_ERROR_OCCURRED; message.obj = "The file doesn't exist."; mHandler.sendMessage(message); return; } // If image exists show image try { LISAImageGray16BitReader reader = new LISAImageGray16BitReader(mFile + ".lisa"); LISAImageGray16Bit image = reader.parseImage(); reader.close(); // Send the LISA 16-Bit grayscale image Message message = mHandler.obtainMessage(); message.what = ThreadState.FINISHED; message.obj = image; mHandler.sendMessage(message); return; } catch (Exception ex) { // Do nothing and create a LISA image } // Create a LISA image and ask to show the // progress dialog in spinner mode mHandler.sendEmptyMessage(ThreadState.STARTED); try { DICOMImageReader dicomFileReader = new DICOMImageReader(mFile); DICOMImage dicomImage = dicomFileReader.parse(); dicomFileReader.close(); // If the image is uncompressed, show it and cached it. if (dicomImage.isUncompressed()) { LISAImageGray16BitWriter out = new LISAImageGray16BitWriter(mFile + ".lisa"); out.write(dicomImage.getImage()); out.flush(); out.close(); Message message = mHandler.obtainMessage(); message.what = ThreadState.FINISHED; message.obj = dicomImage.getImage(); mHandler.sendMessage(message); // Hint the garbage collector System.gc(); } else { Message message = mHandler.obtainMessage(); message.what = ThreadState.UNCATCHABLE_ERROR_OCCURRED; message.obj = "The file is compressed. Compressed format are not" + " supported yet."; mHandler.sendMessage(message); } } catch (OutOfMemoryError ex) { Message message = mHandler.obtainMessage(); message.what = ThreadState.OUT_OF_MEMORY; message.obj = ex.getMessage(); mHandler.sendMessage(message); } catch (Exception ex) { Message message = mHandler.obtainMessage(); message.what = ThreadState.UNCATCHABLE_ERROR_OCCURRED; message.obj = ex.getMessage(); mHandler.sendMessage(message); } } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <GrayScaleWindowView.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.view; import be.ac.ulb.lisa.idot.android.dicomviewer.R; import be.ac.ulb.lisa.idot.android.dicomviewer.data.DICOMViewerData; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Rect; import android.util.AttributeSet; import android.widget.ImageView; public class GrayscaleWindowView extends ImageView { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * The LISA 16-Bit grayscale image. */ private LISAImageGray16Bit mImage = null; /** * DICOMViewer data. */ private DICOMViewerData mDICOMViewerData = null; /** * The window drawable int. */ private int mWindowDrawable = R.drawable.gradient_bar; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public GrayscaleWindowView(Context context) { super(context); } public GrayscaleWindowView(Context context, AttributeSet attrs) { super(context, attrs); } public GrayscaleWindowView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } // --------------------------------------------------------------- // # <override> FUNCTIONS // --------------------------------------------------------------- @Override protected void onDraw(Canvas canvas) { if (mImage == null || mDICOMViewerData == null) return; int imageDataMax = mImage.getDataMax() + 1; imageDataMax = (imageDataMax) == 1 ? mImage.getGrayLevel() : imageDataMax; int windowWidth = mDICOMViewerData.getWindowWidth(); int windowCenter = mDICOMViewerData.getWindowCenter(); // TO CONFIGURE int stepLength = 20; int graduationSizeBig = 10; int graduationSizeNormal = 5; int fontSize = 10; // --------------------------------------- // VARIABLE DECLARATION // --------------------------------------- // ImageView size int width = getMeasuredWidth(); int height = getMeasuredHeight(); // ImageView half size int halfWidth = width / 2; int halfHeight = height / 2; // The half height of the scroll bar int scaleBarHalfHeight = height / 4; // TO have step of the length of stepLength scaleBarHalfHeight -= scaleBarHalfHeight % stepLength; // The coordinate of the scale bar int topScaleBar = halfHeight - scaleBarHalfHeight; int middleScaleBar = halfHeight; // TODO not necessary int bottomScaleBar = halfHeight + scaleBarHalfHeight; // The size of the graduations int endGraduationBig = halfWidth + graduationSizeBig; int endGraduationNormal = halfWidth + graduationSizeNormal; // The number of graduation int countGraduation = scaleBarHalfHeight / stepLength; // The fontsize offset to center the text int fontSizeOffset = fontSize / 2 - 1; // The half size of the grays scale window int windowHalfWidth = windowWidth * (2 * scaleBarHalfHeight) / imageDataMax/*mGrayLevel*/ /2; // The window center in ImageView int windowCenterCoordinate = bottomScaleBar - (2 * scaleBarHalfHeight) * windowCenter / imageDataMax/*mGrayLevel*/; // The grayscale window bounds int topWindowBounds = windowCenterCoordinate - windowHalfWidth; int bottomWindowBounds = windowCenterCoordinate + windowHalfWidth; // Paint Paint paint = new Paint(); // TODO we can do different paint object but we do not need it paint.setColor(0xaaff0000); paint.setAntiAlias(true); // --------------------------------------- // HISTOGRAM // --------------------------------------- int[] imageHistogram = mImage.getHistogramData(); int max = mImage.getHistogramMax(); max = max > 0 ? max : 1; if (imageHistogram != null) { int imgHistLength = imageDataMax < imageHistogram.length ? imageDataMax : imageHistogram.length; int step = imgHistLength / scaleBarHalfHeight / 2; int upperBounds = (2 * scaleBarHalfHeight) - 1; for (int i = 0; i <= upperBounds; i++) { int count = 0; int upperStep = (i == upperBounds) ? (imgHistLength - i * step) : step; for (int j=0; j < upperStep; j++) { int index = (i * step) + j; if (index < imgHistLength) count += imageHistogram[index]; } long histBarWidth = (long) halfWidth + (long) graduationSizeBig * 50 * (long) count / (long) max; canvas.drawLine(halfWidth, bottomScaleBar - i, histBarWidth, bottomScaleBar - i, paint); } } paint.setColor(0xff77c1fb); // --------------------------------------- // GRAYSCALE WINDOW // --------------------------------------- // Set the paint to a stroke paint type paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(1); // Get the grayscale bitmap Bitmap grayscaleBitmap = BitmapFactory.decodeResource(this.getResources(), mWindowDrawable); // Compute the destination rect for the bitmap Rect destRect = new Rect( halfWidth - 15, topWindowBounds, halfWidth - 5, bottomWindowBounds); // Draw the bitmap and a rect around canvas.drawBitmap(grayscaleBitmap, null, destRect, null); canvas.drawRect(destRect, paint); // Set the paint to a fill paint with // a text align right and its size set to fontSize paint.setStrokeWidth(0); paint.setStyle(Paint.Style.FILL); paint.setTextAlign(Align.RIGHT); paint.setTextSize(fontSize); // Draw the upper value canvas.drawText(String.valueOf(windowCenter + windowWidth / 2 - 1024), halfWidth - 5, topWindowBounds - 5, paint); // Draw the bottom value canvas.drawText(String.valueOf(windowCenter - windowWidth / 2 - 1024), halfWidth - 5, bottomWindowBounds + 5 + fontSize, paint); // Draw the center arrow canvas.drawText(">", halfWidth - 15 - 5, windowCenterCoordinate + fontSizeOffset, paint); // Change text align to left paint.setTextAlign(Align.LEFT); // Change the center value canvas.drawText(String.valueOf(windowCenter - 1024), endGraduationBig + 5, windowCenterCoordinate + fontSizeOffset, paint); // --------------------------------------- // GRAYSCALE SCALE // --------------------------------------- // Draw the vertical line canvas.drawLine(halfWidth, topScaleBar, halfWidth, bottomScaleBar, paint); // Draw topScaleBar graduation and text canvas.drawLine(halfWidth, topScaleBar, endGraduationBig, topScaleBar, paint); canvas.drawText(String.valueOf(/*mGrayLevel*/imageDataMax - 1 - 1024), endGraduationBig + 5, topScaleBar + fontSizeOffset, paint); // Draw intermediate graduations for (int i = 1; i < countGraduation; i++) { // The middle graduation'll be drawn => < and not <= countGraduation int yCoordinate = topScaleBar + i * stepLength; canvas.drawLine(halfWidth, yCoordinate, endGraduationNormal, yCoordinate, paint); } // Draw middle graduation canvas.drawLine(halfWidth, middleScaleBar, endGraduationBig, middleScaleBar, paint); // Draw intermediate graduations for (int i = 1; i < countGraduation; i++) { // The bottom graduation'll be drawn => < and not <= countGraduation int yCoordinate = middleScaleBar + i * stepLength; canvas.drawLine(halfWidth, yCoordinate, endGraduationNormal, yCoordinate, paint); } // Draw bottomScaleBar graduation and text canvas.drawLine(halfWidth, bottomScaleBar, endGraduationBig, bottomScaleBar, paint); canvas.drawText("-1024", endGraduationBig + 5, bottomScaleBar + fontSizeOffset, paint); } /** * Set the LISA 16-Bit grayscale image. * * @param image */ public void setImage(LISAImageGray16Bit image) { mImage = image; } /** * Set the DICOMViewer data. * * @param data */ public void setDICOMViewerData(DICOMViewerData data) { mDICOMViewerData = data; } /** * Set the CLUT Mode. * * This must be set each time, the CLUT mode is changed. * * @param clutMode */ public void updateCLUTMode() { if (mDICOMViewerData == null) return; switch(mDICOMViewerData.getCLUTMode()) { default: case CLUTMode.NORMAL: mWindowDrawable = R.drawable.gradient_bar; break; case CLUTMode.INVERSE: mWindowDrawable = R.drawable.gradient_inverse_bar; break; case CLUTMode.RAINBOW: mWindowDrawable = R.drawable.gradient_color_bar; break; }; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImageView.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.1 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.view; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.PointF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; import be.ac.ulb.lisa.idot.android.dicomviewer.DICOMViewer; import be.ac.ulb.lisa.idot.android.dicomviewer.data.DICOMViewerData; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.CLUTMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ScaleMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.ToolMode; import be.ac.ulb.lisa.idot.android.dicomviewer.mode.TouchMode; import be.ac.ulb.lisa.idot.commons.Geometry; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * Dicom ImageView that extends Android ImageView objects and * implements onTouchListener. * * The DICOMViewerData must be set at the creation of the activity * that contains this View. * * @author Pierre Malarme * @version 1.1 * */ public class DICOMImageView extends ImageView implements OnTouchListener { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- // IMAGE VARIABLES /** * The LISA 16-Bit Grayscale Image. */ private LISAImageGray16Bit mImage = null; /** * The transformation matrix. */ private Matrix mMatrix; /** * The scale factor. */ private float mScaleFactor; // TOUCH EVENT VARIABLES /** * The touch mode. */ private short mTouchMode; /** * The transformation matrix saved when a touch down * dimension event is caught. */ private Matrix mSavedMatrix; /** * The time of the first touch down. */ private long mTouchTime; /** * The point where the touch start. */ private PointF mTouchStartPoint; /** * The mid point of the touch event. */ private PointF mTouchMidPoint; /** * The distance between the two point * for a TWO_FINGERS touch event. */ private float mTouchOldDist; /** * The old scaleFactor. */ private float mTouchOldScaleFactor; // INITIALIZATION VARIABLE /** * Set if the view is initialized or not. */ private boolean mIsInit = false; // DICOMVIEWER DATA /** * DICOMViewer data. */ private DICOMViewerData mDICOMViewerData = null; // CONTEXT /** * Context. */ private Context mContext; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMImageView(Context context) { super(context); mContext = context; init(); } public DICOMImageView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; init(); } public DICOMImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mContext = context; init(); } // --------------------------------------------------------------- // + <override> FUNCTIONS // --------------------------------------------------------------- /* (non-Javadoc) * @see android.widget.ImageView#setScaleType(android.widget.ImageView.ScaleType) */ @Override public void setScaleType(ImageView.ScaleType scaleType) { // Do nothing because we accept only the matrix scale type } // --------------------------------------------------------------- // # <override> FUNCTIONS // --------------------------------------------------------------- // This function is override to fit the image in the // ImageView at initialization. Because when this method // is called, the size of the ImageView is set. // The override of the onDraw method lead to a slower // display of the image. It is for that we override // this method. /* (non-Javadoc) * @see android.widget.ImageView#drawableStateChanged() */ @Override protected void drawableStateChanged() { if (mIsInit == false) { mIsInit = true; if (mImage != null) fitIn(); } super.drawableStateChanged(); } // This function is override to center the image // when the size of the screen change /* (non-Javadoc) * @see android.view.View#onSizeChanged(int, int, int, int) */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { // If the image is not null, center it if (mImage != null) center(); super.onSizeChanged(w, h, oldw, oldh); } // --------------------------------------------------------------- // + <implement> FUNCTIONS // --------------------------------------------------------------- public boolean onTouch(View v, MotionEvent event) { if (mImage == null || mDICOMViewerData == null) return false; // Get the tool mode short toolMode = mDICOMViewerData.getToolMode(); // Handle touch event switch(event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // Double tap if ((System.currentTimeMillis() - mTouchTime) < 450) { // The touch mode is set to none mTouchMode = TouchMode.NONE; mTouchTime = 0; // If toolMode is DIMENSION, fit the image // in the screen. if (toolMode == ToolMode.DIMENSION) { if (mDICOMViewerData.getScaleMode() == ScaleMode.FITIN) fitIn(); else realSize(); } else if (toolMode == ToolMode.GRAYSCALE) { mDICOMViewerData.setWindowWidth(mImage.getWindowWidth()); mDICOMViewerData.setWindowCenter(mImage.getWindowCenter()); draw(); } return true; // Single tap } else if (mTouchMode == TouchMode.NONE) { // Set the touch time mTouchTime = System.currentTimeMillis(); // Set the touch mode to ONE_FINGER mTouchMode = TouchMode.ONE_FINGER; // Set the mSavedMatrix mSavedMatrix.set(mMatrix); // Set the mTouchStartPoint value mTouchStartPoint.set(event.getX(), event.getY()); } else { mTouchTime = 0; } break; case MotionEvent.ACTION_POINTER_DOWN: // Check if there is two pointers if (event.getPointerCount() == 2) { // Set mTouchMode to TouchMode.TWO_FINGERS mTouchMode = TouchMode.TWO_FINGERS; // Reset mTouchTime mTouchTime = 0; // DIMENSION MODE if (toolMode == ToolMode.DIMENSION) { // Compute the olf dist between the two pointer. mTouchOldDist = Geometry.euclidianDistance(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); // Compute the old scale factor as the mScaleFactor // at the begining of the touch event. mTouchOldScaleFactor = mScaleFactor; // Compute the midPoint if ((mImage.getWidth() * mScaleFactor) <= getMeasuredWidth() || (mImage.getHeight() * mScaleFactor) <= getMeasuredHeight()) { mTouchMidPoint = new PointF(getMeasuredWidth() / 2f, getMeasuredHeight() / 2f); } else { mTouchMidPoint = Geometry.midPoint(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); } } } else if (event.getPointerCount() == 3) { // Set the touch mode to three fingers mTouchMode = TouchMode.THREE_FINGERS; // Reset the mTouchTime mTouchTime = 0; // The start point is the average of the three fingers // just for the x coordinate mTouchStartPoint.set( (event.getX(0) + event.getX(1) + event.getX(2)) / 3f, 0f); } break; case MotionEvent.ACTION_MOVE: // If this is a ONE_FINGER touch mode if (mTouchMode == TouchMode.ONE_FINGER) { // Switch on toolMode switch(toolMode) { case ToolMode.DIMENSION: // Set the matrix mMatrix.set(mSavedMatrix); // Variable declaration float dx = 0; float dy = 0; // Compute the translation dx = event.getX() - mTouchStartPoint.x; dy = event.getY() - mTouchStartPoint.y; // TODO center the image if width or height > this size // Set the translation mMatrix.postTranslate(dx, dy); // Set the transformation matrix setImageMatrix(mMatrix); break; case ToolMode.GRAYSCALE: // Compute the grayscale window center int center = (getMeasuredHeight() - 10 - (int) event.getY()) * /*grayscaleWindow.getGrayLevel()*/mImage.getDataMax() / (getMeasuredHeight()); // Compute the grayscale window width int width = (int) event.getX() * /*grayscaleWindow.getGrayLevel()*/mImage.getDataMax() / (getMeasuredWidth()); // Set the grayscale window attributes mDICOMViewerData.setWindowWidth(width); mDICOMViewerData.setWindowCenter(center); // Compute the RGB image draw(); break; }; } else if (mTouchMode == TouchMode.TWO_FINGERS && toolMode == ToolMode.DIMENSION) { // Compute the distance between the two finger float newDist = Geometry.euclidianDistance(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); // TODO necessary ? //if (newDist > 3f) { if (newDist != mTouchOldDist) { // Set the matrix mMatrix.set(mSavedMatrix); // Scale factor float scaleFactor = newDist / mTouchOldDist; // Compute the global scale factor mScaleFactor = mTouchOldScaleFactor * scaleFactor; // Set the scale center at the mid point of the event mMatrix.postScale(scaleFactor, scaleFactor, mTouchMidPoint.x, mTouchMidPoint.y); // Set the transformation matrix setImageMatrix(mMatrix); } } else if (mTouchMode == TouchMode.THREE_FINGERS) { // Get the current event average (3 fingers) x coordinate float eventAverageX = event.getX(0) + event.getX(1) + event.getX(2) / 3f; // If the distance is greater than 40% of the ImageView width, change // image. if (Geometry.euclidianDistance(eventAverageX, 0, mTouchStartPoint.x, 0) >= (0.4f * (float) getMeasuredWidth())) { // Get the direction of the touch event float directionX = eventAverageX - mTouchStartPoint.x; // Show next or previous image if (directionX < 0) ((DICOMViewer) mContext).nextImage(null); else ((DICOMViewer) mContext).previousImage(null); // Set the touchmode to none mTouchMode = TouchMode.NONE; } } return true; // Draw case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: // Set that this is the end of the touch event mTouchMode = TouchMode.NONE; // Check the dimension if (toolMode == ToolMode.DIMENSION) { // Compute mImageView width and height and the image // or the image size if is in ScaleMode real size // scaled width and height float imageWidth, imageHeight; // Check the scale mode to see if the image size is // smaller than the required size if (mDICOMViewerData.getScaleMode() == ScaleMode.FITIN) { imageWidth = getMeasuredWidth(); imageHeight = getMeasuredHeight(); } else { imageWidth = mImage.getWidth(); imageHeight = mImage.getHeight(); } float scaledImageWidth = (float) mImage.getWidth() * mScaleFactor; float scaledImageHeight = (float) mImage.getHeight() * mScaleFactor; // If the image fit int the window => fit in the window if (scaledImageWidth <= imageWidth && scaledImageHeight <= imageHeight) { if (mDICOMViewerData.getScaleMode() == ScaleMode.FITIN) fitIn(); else realSize(); } else { // The ImageView size is needed imageWidth = getMeasuredWidth(); imageHeight = getMeasuredHeight(); // Get the matrix for the transformation mMatrix.set(getImageMatrix()); // Set the source and destination rect points that correpond // to the upper left corner and the bottom right corner float[] srcRectPoints = { 0f, 0f, mImage.getWidth(), mImage.getHeight()}; float[] dstRectPoints = new float[4]; // Apply the image matrix transformation on these points mMatrix.mapPoints(dstRectPoints, srcRectPoints); // Init transalation variables float dx = 0f; float dy = 0f; // If the scaled image width is greater than the mImageView width if (scaledImageWidth > imageWidth) { // If there is black at the left of the screen if (dstRectPoints[0] > 0f) { dx = (-1f) * dstRectPoints[0]; // Else if there is black at the right of the screen } else if (dstRectPoints[2] < imageWidth) { dx = imageWidth - dstRectPoints[2]; } } else { // Compute the left border and the right border // to center the image float lx = (imageWidth - scaledImageWidth) / 2f; float rx = (imageWidth + scaledImageWidth) / 2f; // If the image is more left than the left border if (dstRectPoints[0] < lx) { dx = (-1f) * dstRectPoints[0] + lx; // Else if the image is more right than the right border } else if (dstRectPoints[2] > rx) { dx = rx - dstRectPoints[2]; } } // If the scaled image height is greater than the mImageView height if (scaledImageHeight > imageHeight) { // If there is black at the top of the screen if (dstRectPoints[1] > 0f) { dy = (-1f) * dstRectPoints[1]; // Else if there is black at the bottom of the screen } else if (dstRectPoints[3] < imageHeight) { dy = imageHeight - dstRectPoints[3]; } } else { // Compute the top border and the bottom border // to center the image float ty = (imageHeight - scaledImageHeight) / 2f; float by = (imageHeight + scaledImageHeight) / 2f; // If the image is upper the top border if (dstRectPoints[1] < 0f) { dy = (-1f) * dstRectPoints[1] + ty; // Else if the image is under the bottom border } else if (dstRectPoints[3] > imageHeight) { dy = by - dstRectPoints[3]; } } // If there is translation to compute if (dx != 0f || dy != 0f) { // Add the translation mMatrix.postTranslate(dx, dy); // Set the image matrix setImageMatrix(mMatrix); } } } break; }; return true; // Do not draw } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Draw the image. */ public void draw() { // Declaration output pixels vector int[] outputPixels = new int[mImage.getDataLength()]; // Get the gray scale window width int windowWidth = mDICOMViewerData.getWindowWidth(); // Compute the window offset x the number of gray levels (256) int windowOffset = ((2 * mDICOMViewerData.getWindowCenter() - windowWidth)) / 2; switch(mDICOMViewerData.getCLUTMode()) { case CLUTMode.NORMAL: computeGrayscaleRGBImage(windowWidth, windowOffset, outputPixels); break; case CLUTMode.INVERSE: computeInverseGrayscaleRGBImage(windowWidth, windowOffset, outputPixels); break; case CLUTMode.RAINBOW: computeRainbowRGBImage(windowWidth, windowOffset, outputPixels); break; }; // Create the bitmap Bitmap imageBitmap = Bitmap.createBitmap(outputPixels, mImage.getWidth(), mImage.getHeight(), Bitmap.Config.ARGB_8888); // Set the image setImageBitmap(imageBitmap); } /** * Reset size and position of the image regarding * mScaleMode variable. */ public void resetSize() { switch(mDICOMViewerData.getScaleMode()) { case ScaleMode.FITIN: fitIn(); break; case ScaleMode.REALSIZE: realSize(); break; }; } /** * Fit the image in the screen */ public void fitIn() { // Get the image width and height int imageWidth = mImage.getWidth(); int imageHeight = mImage.getHeight(); // Variable declaration float dx = 0f; float dy = 0f; // Get the image matrix mMatrix.set(getImageMatrix()); // If the width of the ImageView is smaller than the // height, the image width is set to the ImageView width. if (getMeasuredWidth() <= getMeasuredHeight()) { float measuredWidth = getMeasuredWidth(); mScaleFactor = measuredWidth / imageWidth; // Translate to center the image. dy = ((float) getMeasuredHeight() - imageHeight * mScaleFactor) / 2f; // Else the image height is set to the ImageView height. } else { float measuredHeight = getMeasuredHeight(); mScaleFactor = measuredHeight / imageHeight; // Translate to center the image. dx = ((float) getMeasuredWidth() - imageWidth * mScaleFactor) / 2f; } // Set the transformation mMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f); mMatrix.postTranslate(dx, dy); // Set the Image Matrix setImageMatrix(mMatrix); } /** * Display the real size of the image. */ public void realSize() { // Get the image width and height int imageWidth = mImage.getWidth(); int imageHeight = mImage.getHeight(); // Compute the translation float dx = ((float) getMeasuredWidth() - imageWidth) / 2f; float dy = ((float) getMeasuredHeight() - imageHeight) / 2f; mScaleFactor = 1f; mMatrix.set(getImageMatrix()); // Set the transformation mMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f); mMatrix.postTranslate(dx, dy); // Set the Image Matrix setImageMatrix(mMatrix); } /** * Center the image in X and/or Y regarding * the dimension of the scaled image and the dimension * of the ImageView. */ public void center() { // Scaled image sizes. float scaledImageWidth = (float) mImage.getWidth() * mScaleFactor; float scaledImageHeight = (float) mImage.getHeight() * mScaleFactor; if (scaledImageWidth <= getMeasuredWidth() && scaledImageHeight <= getMeasuredHeight()) { // Compute the translation float dx = ((float) getMeasuredWidth() - scaledImageWidth) / 2f; float dy = ((float) getMeasuredHeight() - scaledImageHeight) / 2f; mMatrix.set(getImageMatrix()); mMatrix.setScale(mScaleFactor, mScaleFactor, 0f, 0f); mMatrix.postTranslate(dx, dy); // Set the Image Matrix setImageMatrix(mMatrix); } } /** * Set the LISA 16-Bit grayscale image. * * @param image */ public void setImage(LISAImageGray16Bit image) { mImage = image; } /** * Get the LISA 16-Bit grayscale image. * * @param image */ public LISAImageGray16Bit getImage() { return mImage; } /** * Get the image scaled width. * * @return Image scaled width. */ public float getScaledImageWidth() { return mImage.getWidth() * mScaleFactor; } /** * Get the image scaled height. * * @return Image scaled height. */ public float getScaledImageHeight() { return mImage.getHeight() * mScaleFactor; } /** * @return Transformation matrix. */ public Matrix getMatrix() { return mMatrix; } /** * Get the scale factor. * * @return Scale factor. */ public float getScaleFactor() { return mScaleFactor; } /** * Set the scale factor and apply * it on the image. */ public void setScaleFactor(float scaleFactor) { mScaleFactor = scaleFactor; } /** * Set the DICOMViewer data. * @param data */ public void setDICOMViewerData(DICOMViewerData data) { mDICOMViewerData = data; } // --------------------------------------------------------------- // - FUNCTIONS // --------------------------------------------------------------- /** * Init this object. */ private void init() { // Set the transformation attribute super.setScaleType(ImageView.ScaleType.MATRIX); mMatrix = new Matrix(); mScaleFactor = 1f; // TOUCH mTouchMode = TouchMode.NONE; mSavedMatrix = new Matrix(); mTouchTime = 0; mTouchStartPoint = new PointF(); mTouchMidPoint = new PointF(); mTouchOldDist = 1f; // Set the onTouchListener as this object setOnTouchListener(this); } /** * Compute the RGB image using a grayscale LUT. * * @param windowWidth * @param windowOffset * @param outputPixels */ private void computeGrayscaleRGBImage(int windowWidth, int windowOffset, int[] outputPixels) { // The gray level of the current pixel int pixelGrayLevel = 0; int[] mImageData = mImage.getData(); // Compute the outputPixels vector (matrix) for (int i = 0; i < mImageData.length; i++) { pixelGrayLevel = (256 * (mImageData[i] - windowOffset) / windowWidth); pixelGrayLevel = (pixelGrayLevel > 255) ? 255 : ((pixelGrayLevel < 0) ? 0 : pixelGrayLevel); outputPixels[i] = (0xFF << 24) | // alpha (pixelGrayLevel << 16) | // red (pixelGrayLevel << 8) | // green pixelGrayLevel; // blue } } /** * Compute the RGB image using an inverse grayscale LUT. * * @param windowWidth * @param windowOffset * @param outputPixels */ private void computeInverseGrayscaleRGBImage(int windowWidth, int windowOffset, int[] outputPixels) { // The gray level of the current pixel int pixelGrayLevel = 0; int[] mImageData = mImage.getData(); // Compute the outputPixels vector (matrix) for (int i = 0; i < mImageData.length; i++) { pixelGrayLevel = 255 - (256 * (mImageData[i] - windowOffset) / windowWidth); pixelGrayLevel = (pixelGrayLevel > 255) ? 255 : ((pixelGrayLevel < 0) ? 0 : pixelGrayLevel); outputPixels[i] = (0xFF << 24) | // alpha (pixelGrayLevel << 16) | // red (pixelGrayLevel << 8) | // green pixelGrayLevel; // blue } } /** * Compute the RGB image using a rainbow CLUT. * * @param windowWidth * @param windowOffset * @param outputPixels */ private void computeRainbowRGBImage(int windowWidth, int windowMin, int[] outputPixels) { float[] pixelHSV = new float[3]; pixelHSV[0] = 0f; pixelHSV[1] = 240f; pixelHSV[2] = 1f; float mult = 0; int[] mImageData = mImage.getData(); // Compute the outputPixels vector (matrix) for (int i = 0; i < mImageData.length; i++) { mult = (mImageData[i] - windowMin) / (float) windowWidth; mult = (mult > 1f) ? 1f : ((mult < 0f) ? 0f : mult); pixelHSV[0] = 300f - 360f * mult; pixelHSV[0] = (pixelHSV[0] > 300f) ? 300f : (pixelHSV[0] < -60f) ? 360-60f : pixelHSV[0]; pixelHSV[2] = 4f * mult; outputPixels[i] = Color.HSVToColor(0xFF, pixelHSV); } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <ThreadState.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.thread; /** * Encapsulate thread states that correspond to the wath of * the Handler. * * @author Pierre Malarme * @version 1.0 * */ public class ThreadState { // --------------------------------------------------------------- // + <static> VARIABLES // --------------------------------------------------------------- /** * Thread has catch a OutOfMemoryError exception. */ public static final short OUT_OF_MEMORY = 0; /** * The thread is started. */ public static final short STARTED = 1; /** * The thread is finished. */ public static final short FINISHED = 2; /** * The thread progression update. */ public static final short PROGRESSION_UPDATE = 3; /** * An error occurred while the thread running that cannot * be managed. */ public static final short UNCATCHABLE_ERROR_OCCURRED = 4; /** * An error occurred while the thread running that can be * managed or ignored. */ public static final short CATCHABLE_ERROR_OCCURRED = 5; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImageCacher.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.thread; import java.io.File; import java.io.FileNotFoundException; import android.os.Handler; import android.os.Message; import be.ac.ulb.lisa.idot.dicom.data.DICOMImage; import be.ac.ulb.lisa.idot.dicom.file.DICOMFileFilter; import be.ac.ulb.lisa.idot.dicom.file.DICOMImageReader; import be.ac.ulb.lisa.idot.image.file.LISAImageGray16BitWriter; /** * DICOM image cacher that cached DICOM image in LISA * 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.0 * */ public final class DICOMImageCacher extends Thread { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * The handler to send message to. */ private final Handler mHandler; /** * The directory containing the DICOM image files. */ private final File mTopDirectory; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMImageCacher(Handler handler, String topDirectoryName) throws FileNotFoundException { // Set the handler if (handler == null) throw new NullPointerException("The handler is null"); mHandler = handler; // Set the top directory mTopDirectory = new File(topDirectoryName); if (!mTopDirectory.exists()) throw new FileNotFoundException("The directory (" + topDirectoryName + ") doesn't exist."); } public DICOMImageCacher(Handler handler, File topDirectory) throws FileNotFoundException { // Set the handler if (handler == null) throw new NullPointerException("The handler is null"); mHandler = handler; // Set the top directory if (!topDirectory.exists()) throw new FileNotFoundException("The directory (" + topDirectory.getPath() + ") doesn't exist."); mTopDirectory = topDirectory; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- public void run() { // Get the Files' list for the mTopDirectory File[] children = mTopDirectory.listFiles(new DICOMFileFilter()); // If the children array is null if (children == null) { mHandler.sendEmptyMessage(ThreadState.UNCATCHABLE_ERROR_OCCURRED); return; } // Get the message from the handler and send // the children list length Message message = mHandler.obtainMessage(); message.what = ThreadState.STARTED; message.arg1 = children.length; mHandler.sendMessage(message); try { for (int i = 0; i < children.length; i++) { // Load the children if (loadImage(children[i])) { // Send a progression update message message = mHandler.obtainMessage(); message.what = ThreadState.PROGRESSION_UPDATE; message.arg1 = i + 1; mHandler.sendMessage(message); } else { // Send a catchable error occurred message = mHandler.obtainMessage(); message.what = ThreadState.CATCHABLE_ERROR_OCCURRED; message.arg1 = i + 1; message.obj = children[i].getName(); mHandler.sendMessage(message); } // Hint the garbage collector System.gc(); } } catch (OutOfMemoryError ex) { // If the image can be loaded because an out of // memory error occurred, display it System.gc(); mHandler.sendEmptyMessage(ThreadState.OUT_OF_MEMORY); } // Send that the thread is finished mHandler.sendEmptyMessage(ThreadState.FINISHED); // Hint the garbage collector a last time System.gc(); } // --------------------------------------------------------------- // - <static> FUNCTIONS // --------------------------------------------------------------- /** * Load an image. * * @param currentFile * @return True if the image is cached, false otherwise. */ private static boolean loadImage(File currentFile) { // If the file doesn't exist return false if (!currentFile.exists()) return false; // Set the current LISA 16-Bit grayscale image File currentLISAFile = new File(currentFile + ".lisa"); // If current LISA 16-Bit grayscale image exists, // don't create it if (currentLISAFile.exists()) return true; // Else write it try { DICOMImageReader dicomFileReader = new DICOMImageReader(currentFile); DICOMImage dicomImage = dicomFileReader.parse(); dicomFileReader.close(); // Compressed file are not supported => do not cached it. if (dicomImage.isUncompressed()) { // Write the image LISAImageGray16BitWriter out = new LISAImageGray16BitWriter(currentFile + ".lisa"); out.write(dicomImage.getImage()); out.flush(); out.close(); } dicomImage = null; return true; } catch (Exception ex) { return false; } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <GrayscaleWindowPreset.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.android.dicomviewer.preset; /** * The class WindowPreset contains the image window presets. * * @author Pierre Malarme * @version 1.0 * */ public final class GrayscaleWindowPreset { /** * Set the window window to the CT Bone preset. */ public static final short CT_BONE = 1; /** * Set the window window to the CT Crane preset. */ public static final short CT_CRANE = 2; /** * Set the window window to the CT Lung preset. */ public static final short CT_LUNG = 3; /** * Set the window window to the CT Abdomen preset. */ public static final short CT_ABDOMEN = 4; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <Geometry.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.commons; import android.graphics.PointF; import android.util.FloatMath; /** * The class Geometry contains geometry functions. * * @author Pierre Malarme * * @version 1.0 * */ public class Geometry { // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * Get the euclidian distance between P1 (x1, y1) and P2 (x2, y2). * * @param x1 The x-coordinate of the P1. * @param y1 The y-coordinate of the P1. * @param x2 The x-coordinate of the P2. * @param y2 The y-coordinate of the P2. * @return The euclidian distance between (x1, y1) and (x2, y2). */ public static final float euclidianDistance(float x1, float y1, float x2, float y2) { // Compute coordinate subtraction float x = x2 - x1; float y = y2 - y1; // Compute the euclidian distance return FloatMath.sqrt(x * x + y * y); } /** * Get the middle point between P1 (x1, y1) and P2 (x2, y2). * * @param x1 The x-coordinate of the P1. * @param y1 The y-coordinate of the P1. * @param x2 The x-coordinate of the P2. * @param y2 The y-coordinate of the P2. * @return The middle point between (x1, y1) and (x2, y2). */ public static final PointF midPoint(float x1, float y1, float x2, float y2) { // Compute coordinate addition float x = x1 + x2; float y = y1 + y2; return new PointF(x / 2f, y / 2f); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <Memory.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.commons; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * Implements functions useful to check * Memory usage. * * @author Pierre Malarme * @version 1.0 * */ public class Memory { // --------------------------------------------------------------- // + <static> FUNCTION // --------------------------------------------------------------- /** * Function that get the size of an object. * * @param object * @return Size in bytes of the object or -1 if the object * is null. * @throws IOException */ public static final int sizeOf(Object object) throws IOException { if (object == null) return -1; // Special output stream use to write the content // of an output stream to an internal byte array. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Output stream that can write object ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); // Write object and close the output stream objectOutputStream.writeObject(object); objectOutputStream.flush(); objectOutputStream.close(); // Get the byte array byte[] byteArray = byteArrayOutputStream.toByteArray(); // TODO can the toByteArray() method return a // null array ? return byteArray == null ? 0 : byteArray.length; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMMetaInformation.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; /** * DICOM file meta informations. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMMetaInformation { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Length of the meta information. */ private long mGroupLength = -1; /** * SOP Class UID. */ private String mSOPClassUID = ""; /** * SOP Instance UID. */ private String mSOPInstanceUID = ""; /** * Transfer syntax UID. * */ private String mTransferSyntaxUID = ""; /** * Implementation Class UID. */ private String mImplementationClassUID = ""; /** * Implementation version name. */ private String mImplementationVersionName = ""; /** * Application Entity Title. */ private String mAET = ""; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMMetaInformation() { } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- // Methods generated by Eclipse. /** * @return the mGroupLength */ public long getGroupLength() { return mGroupLength; } /** * @return the mSOPClassUID */ public String getSOPClassUID() { return mSOPClassUID; } /** * @return the mSOPInstanceUID */ public String getSOPInstanceUID() { return mSOPInstanceUID; } /** * @return the mTransferSyntaxUID */ public String getTransferSyntaxUID() { return mTransferSyntaxUID; } /** * @return the mImplementationClassUID */ public String getImplementationClassUID() { return mImplementationClassUID; } /** * @return the mImplementationVersionName */ public String getImplementationVersionName() { return mImplementationVersionName; } /** * @return the mAET */ public String getAET() { return mAET; } /** * @param mGroupLength the mGroupLength to set */ public void setGroupLength(long mGroupLength) { this.mGroupLength = mGroupLength; } /** * @param mSOPClassUID the mSOPClassUID to set */ public void setSOPClassUID(String mSOPClassUID) { this.mSOPClassUID = mSOPClassUID; } /** * @param mSOPInstanceUID the mSOPInstanceUID to set */ public void setSOPInstanceUID(String mSOPInstanceUID) { this.mSOPInstanceUID = mSOPInstanceUID; } /** * @param mTransferSyntaxUID the mTransferSyntaxUID to set */ public void setTransferSyntaxUID(String mTransferSyntaxUID) { this.mTransferSyntaxUID = mTransferSyntaxUID; } /** * @param mImplementationClassUID the mImplementationClassUID to set */ public void setImplementationClassUID(String mImplementationClassUID) { this.mImplementationClassUID = mImplementationClassUID; } /** * @param mImplementationVersionName the mImplementationVersionName to set */ public void setImplementationVersionName(String mImplementationVersionName) { this.mImplementationVersionName = mImplementationVersionName; } /** * @param mAET the mAET to set */ public void setAET(String mAET) { this.mAET = mAET; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMBody.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; /** * DICOM file meta informations. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMBody { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Specific character set. */ private String mSpecificCharset = "ASCII"; /** * Image type. */ private String mImageType = ""; /** * Date of the study. */ private String mStudyDate = ""; /** * Time of the study. */ private String mStudyTime = ""; /** * Modality. */ private String mModality = ""; /** * Manufacturer. */ private String mManufacturer = ""; /** * Institution name. */ private String mInstitutionName = ""; /** * Referring physician name. */ private String mReferringPhysicianName = ""; /** * Station name. */ private String mStationName = ""; /** * Study description. */ private String mStudyDescription = ""; /** * Department name. */ private String mDepartmenName = ""; /** * Manufacturer model name. */ private String mManufacturerModelName = ""; /** * Patient name. */ private String mPatientName = ""; /** * Patient ID. */ private String mPatientId = ""; /** * Protocol name. */ private String mProtocolName = ""; /** * Patient position. */ private String mPatientPosition = ""; /** * Study ID. */ private int mStudyId = -1; /** * Series number. */ private int mSeriesNumber = -1; /** * Instance number. */ private int mInstanceNumber = -1; /** * Sample per pixel. */ private int mSamplesPerPixel = 1; /** * Photometric interpretation. */ private String mPhotometricInterpretation = "MONOCHROME2"; /** * Bits allocated. */ private int mBitsAllocated = 0; /** * Bits stored; */ private int mBitsStored = 0; /** * High bit. */ private int mHightBit = 0; /** * Pixel representation. * * 0 = unsigned, 1 = signed. * */ private int mPixelRepresentation = 1; /** * Requesting physician. */ private String mRequestingPhysician = ""; /** * Requested procedure. */ private String mRequestedProcedureDescription = ""; /** * Scheduled procedure step description. */ private String mScheduledProcedureStepDescription = ""; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMBody() { } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- // Methods generated by Eclipse. /** * @return the mSpecificCharset */ public String getSpecificCharset() { return mSpecificCharset; } /** * @return the mImageType */ public String getImageType() { return mImageType; } /** * @return the mStudyDate */ public String getStudyDate() { return mStudyDate; } /** * @return the mStudyTime */ public String getStudyTime() { return mStudyTime; } /** * @return the mModality */ public String getModality() { return mModality; } /** * @return the mManufacturer */ public String getManufacturer() { return mManufacturer; } /** * @return the mInstitutionName */ public String getInstitutionName() { return mInstitutionName; } /** * @return the mReferringPhysicianName */ public String getReferringPhysicianName() { return mReferringPhysicianName; } /** * @return the mStationName */ public String getStationName() { return mStationName; } /** * @return the mStudyDescription */ public String getStudyDescription() { return mStudyDescription; } /** * @return the mDepartmenName */ public String getDepartmenName() { return mDepartmenName; } /** * @return the mManufacturerModelName */ public String getManufacturerModelName() { return mManufacturerModelName; } /** * @return the mPatientName */ public String getPatientName() { return mPatientName; } /** * @return the mPatientID */ public String getPatientId() { return mPatientId; } /** * @return the mProtocolName */ public String getProtocolName() { return mProtocolName; } /** * @return the mPatientPosition */ public String getPatientPosition() { return mPatientPosition; } /** * @return the mStudyId */ public int getStudyId() { return mStudyId; } /** * @return the mSeriesNumber */ public int getSeriesNumber() { return mSeriesNumber; } /** * @return the mInstanceNumber */ public int getInstanceNumber() { return mInstanceNumber; } /** * @return the mSamplePerPixel */ public int getSamplesPerPixel() { return mSamplesPerPixel; } /** * @return the mPhotometricInterpretation */ public String getPhotometricInterpretation() { return mPhotometricInterpretation; } /** * @return the mBitsAllocated */ public int getBitsAllocated() { return mBitsAllocated; } /** * @return the mBitsStored */ public int getBitsStored() { return mBitsStored; } /** * @return the mHightBit */ public int getHightBit() { return mHightBit; } /** * @return the mPixelRepresentation */ public int getPixelRepresentation() { return mPixelRepresentation; } /** * @return the mRequestingPhysician */ public String getRequestingPhysician() { return mRequestingPhysician; } /** * @return the mRequestedProcedureDescription */ public String getRequestedProcedureDescription() { return mRequestedProcedureDescription; } /** * @return the mScheduledProcedureStepDescription */ public String getScheduledProcedureStepDescription() { return mScheduledProcedureStepDescription; } /** * @param mSpecificCharset the mSpecificCharset to set */ public void setSpecificCharset(String mSpecificCharset) { this.mSpecificCharset = mSpecificCharset; } /** * @param mImageType the mImageType to set */ public void setImageType(String mImageType) { this.mImageType = mImageType; } /** * @param mStudyDate the mStudyDate to set */ public void setStudyDate(String mStudyDate) { this.mStudyDate = mStudyDate; } /** * @param mStudyTime the mStudyTime to set */ public void setStudyTime(String mStudyTime) { this.mStudyTime = mStudyTime; } /** * @param mModality the mModality to set */ public void setModality(String mModality) { this.mModality = mModality; } /** * @param mManufacturer the mManufacturer to set */ public void setManufacturer(String mManufacturer) { this.mManufacturer = mManufacturer; } /** * @param mInstitutionName the mInstitutionName to set */ public void setInstitutionName(String mInstitutionName) { this.mInstitutionName = mInstitutionName; } /** * @param mReferingPhysicianName the mReferingPhysicianName to set */ public void setReferringPhysicianName(String mReferringPhysicianName) { this.mReferringPhysicianName = mReferringPhysicianName; } /** * @param mStationName the mStationName to set */ public void setStationName(String mStationName) { this.mStationName = mStationName; } /** * @param mStudyDescription the mStudyDescription to set */ public void setStudyDescription(String mStudyDescription) { this.mStudyDescription = mStudyDescription; } /** * @param mDepartmenName the mDepartmenName to set */ public void setDepartmenName(String mDepartmenName) { this.mDepartmenName = mDepartmenName; } /** * @param mManufacturerModelName the mManufacturerModelName to set */ public void setManufacturerModelName(String mManufacturerModelName) { this.mManufacturerModelName = mManufacturerModelName; } /** * @param mPatientName the mPatientName to set */ public void setPatientName(String mPatientName) { this.mPatientName = mPatientName; } /** * @param mPatientID the mPatientID to set */ public void setPatientId(String mPatientId) { this.mPatientId = mPatientId; } /** * @param mProtocolName the mProtocolName to set */ public void setProtocolName(String mProtocolName) { this.mProtocolName = mProtocolName; } /** * @param mPatientPosition the mPatientPosition to set */ public void setPatientPosition(String mPatientPosition) { this.mPatientPosition = mPatientPosition; } /** * @param mStudyId the mStudyId to set */ public void setStudyId(int mStudyId) { this.mStudyId = mStudyId; } /** * @param mSeriesNumber the mSeriesNumber to set */ public void setSeriesNumber(int mSeriesNumber) { this.mSeriesNumber = mSeriesNumber; } /** * @param mInstanceNumber the mInstanceNumber to set */ public void setInstanceNumber(int mInstanceNumber) { this.mInstanceNumber = mInstanceNumber; } /** * @param mSamplePerPixel the mSamplePerPixel to set */ public void setSamplesPerPixel(int mSamplesPerPixel) { this.mSamplesPerPixel = mSamplesPerPixel; } /** * @param mPhotometricInterpretation the mPhotometricInterpretation to set */ public void setPhotometricInterpretation(String mPhotometricInterpretation) { this.mPhotometricInterpretation = mPhotometricInterpretation; } /** * @param mBitsAllocated the mBitsAllocated to set */ public void setBitsAllocated(int mBitsAllocated) { this.mBitsAllocated = mBitsAllocated; } /** * @param mBitsStored the mBitsStored to set */ public void setBitsStored(int mBitsStored) { this.mBitsStored = mBitsStored; } /** * @param mHightBit the mHightBit to set */ public void setHightBit(int mHightBit) { this.mHightBit = mHightBit; } /** * @param mPixelRepresentation the mPixelRepresentation to set */ public void setPixelRepresentation(int mPixelRepresentation) { this.mPixelRepresentation = mPixelRepresentation; } /** * @param mRequestingPhysician the mRequestingPhysician to set */ public void setRequestingPhysician(String mRequestingPhysician) { this.mRequestingPhysician = mRequestingPhysician; } /** * @param mRequestedProcedureDescription the mRequestedProcedureDescription to set */ public void setRequestedProcedureDescription( String mRequestedProcedureDescription) { this.mRequestedProcedureDescription = mRequestedProcedureDescription; } /** * @param mScheduledProcedureStepDescription the mScheduledProcedureStepDescription to set */ public void setScheduledProcedureStepDescription( String mScheduledProcedureStepDescription) { this.mScheduledProcedureStepDescription = mScheduledProcedureStepDescription; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMFile.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; /** * DICOM file containing a meta information object (DICOMMetaInformation) * and a DICOM body object (DICOMBody). * * @author Pierre Malarme * @version 1.0 * */ public class DICOMFile { // --------------------------------------------------------------- // - <final> VARIABLES // --------------------------------------------------------------- /** * DICOM meta information. */ protected final DICOMMetaInformation mMetaInformation; /** * DICOM body. */ protected final DICOMBody mBody; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMFile(DICOMMetaInformation metaInformation, DICOMBody body) { mMetaInformation = metaInformation; mBody = body; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return DICOM meta information. */ public DICOMMetaInformation getMetaInformation() { return mMetaInformation; } /** * @return DICOM body. */ public DICOMBody getBody() { return mBody; } /** * @return True if the file has DICOM meta information. * False otherwise. */ public boolean hasMetaInformation() { return mMetaInformation != null; } /** * @return True if the file has DICOM body. * False otherwise. */ public boolean hasBody() { return mBody != null; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImage.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.data; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * DICOM image containing a compression status, a meta information * object (DICOMMetaInformation), a DICOM body object (DICOMBody) * and a LISA 16-Bit grayscale image (LISAImageGray16Bit). * * @author Pierre Malarme * @version 1.0 * */ public class DICOMImage extends DICOMFile { // --------------------------------------------------------------- // + <static> VARIABLES // --------------------------------------------------------------- /** * Unknown image status. */ public static final short UNKNOWN_STATUS = 0; /** * Uncompressed image status. */ public static final short UNCOMPRESSED = 1; /** * Compressed image status. */ public static final short COMPRESSED = 2; // --------------------------------------------------------------- // - <final> VARIABLES // --------------------------------------------------------------- /** * LISA 16-Bit grayscale image. */ private final LISAImageGray16Bit mImage; /** * The compression status. */ private final short mCompressionStatus; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMImage(DICOMMetaInformation metaInformation, DICOMBody body, LISAImageGray16Bit image, short compressionStatus) { super(metaInformation, body); mImage = image; mCompressionStatus = compressionStatus; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return DICOM image. */ public LISAImageGray16Bit getImage() { return mImage; } /** * @return Compression status. */ public short getCompressionStatus() { return mCompressionStatus; } /** * @return Check if the image is uncompressed. */ public boolean isUncompressed() { return mCompressionStatus == UNCOMPRESSED; } /** * @return Check if the image as data. */ public boolean hasImageData() { if (mImage == null) return false; return mImage.getData() != null; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMImageReader.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ // This class is based on dicom4j implementation: org.dicom4j.io.DicomReader // author: <a href="mailto:straahd@users.sourceforge.net">Laurent Lecomte // http://dicom4j.sourceforge.net/ // Dicom4j License: /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // Dicom4j License [End] package be.ac.ulb.lisa.idot.dicom.file; import java.io.EOFException; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import be.ac.ulb.lisa.idot.dicom.DICOMElement; import be.ac.ulb.lisa.idot.dicom.DICOMException; import be.ac.ulb.lisa.idot.dicom.DICOMValueRepresentation; import be.ac.ulb.lisa.idot.dicom.data.DICOMBody; import be.ac.ulb.lisa.idot.dicom.data.DICOMImage; import be.ac.ulb.lisa.idot.dicom.data.DICOMMetaInformation; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * DICOM image file reader that read only grayscale image * with the bits allocated maximum value: 16 bits. * It does not support also compressed file format. * * For RGB image or compressed image, it parse just the meta * information and the body. * * @author Pierre Malarme * @version 1.O * */ public class DICOMImageReader extends DICOMReader { // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMImageReader(File file) throws FileNotFoundException { super(file); } public DICOMImageReader(String fileName) throws FileNotFoundException { super(fileName); } // --------------------------------------------------------------- // + <final> FUNCTIONS // --------------------------------------------------------------- /** * Parse the image DICOM file. * * @throws IOException * @throws EOFException * @throws DICOMException */ public final DICOMImage parse() throws IOException, EOFException, DICOMException { // Variables declaration DICOMMetaInformation metaInformation; boolean isExplicit; short compressionStatus = DICOMImage.UNKNOWN_STATUS; // Parse meta information if (hasMetaInformation()) { metaInformation = parseMetaInformation(); String transferSyntaxUID = metaInformation.getTransferSyntaxUID(); if (transferSyntaxUID.equals("1.2.840.10008.1.2")) { isExplicit = false; setByteOrder(LITTLE_ENDIAN); compressionStatus = DICOMImage.UNCOMPRESSED; } else if (transferSyntaxUID.equals("1.2.840.10008.1.2.1")) { isExplicit = true; setByteOrder(LITTLE_ENDIAN); compressionStatus = DICOMImage.UNCOMPRESSED; } else if (transferSyntaxUID.equals("1.2.840.10008.1.2.2")) { isExplicit = true; setByteOrder(BIG_ENDIAN); compressionStatus = DICOMImage.UNCOMPRESSED; } else { isExplicit = true; setByteOrder(LITTLE_ENDIAN); compressionStatus = DICOMImage.COMPRESSED; // Compressed image are not supported yet // => throw a exception throw new DICOMException("The image is compressed." + " This is not supported yet."); } } else { metaInformation = null; isExplicit = false; setByteOrder(LITTLE_ENDIAN); } // Parse the body DICOMImageReaderFunctions dicomReaderFunctions = new DICOMImageReaderFunctions(isExplicit, compressionStatus); parse(null, 0xffffffffL, isExplicit, dicomReaderFunctions, true); DICOMImage dicomImage = new DICOMImage(metaInformation, dicomReaderFunctions.getBody(), dicomReaderFunctions.getImage(), compressionStatus); return dicomImage; } // --------------------------------------------------------------- // # CLASS // --------------------------------------------------------------- protected class DICOMImageReaderFunctions implements DICOMReaderFunctions { // TODO support encapsulated PixelData ? or throw an error DICOMBody mBody; LISAImageGray16Bit mImage; boolean mIsExplicit; short mCompressionStatus; public DICOMImageReaderFunctions(boolean isExplicit, short compressionStatus) { mBody = new DICOMBody(); mImage = new LISAImageGray16Bit(); mIsExplicit = isExplicit; mCompressionStatus = compressionStatus; } public void addDICOMElement(DICOMElement parent, DICOMElement element) { // If this is a sequence, do nothing if (parent != null) return; int tag = element.getDICOMTag().getTag(); // Specific character set if (tag == 0x00080005) { mBody.setSpecificCharset(element.getValueString()); // Set the specific character set mSpecificCharset = mBody.getSpecificCharset(); // If tag == image type } else if (tag == 0x00080008) { mBody.setImageType(element.getValueString()); // If tag == image orientation } else if (tag == 0x00200037) { mImage.setImageOrientation(getImageOrientation(element)); // If tag == samples per pixel } else if (tag == 0x00280002) { mBody.setSamplesPerPixel(element.getValueInt()); // If tag == rows } else if (tag == 0x00280010) { mImage.setHeight((short) element.getValueInt()); // If tags == columns } else if (tag == 0x00280011) { mImage.setWidth((short) element.getValueInt()); // If tag == bits allocated } else if (tag == 0x00280100) { mBody.setBitsAllocated(element.getValueInt()); // If tag == bits stored } else if (tag == 0x00280101) { mBody.setBitsStored(element.getValueInt()); // Set the image gray level mImage.setGrayLevel((int) Math.pow(2, mBody.getBitsStored())); // If tag == high bit } else if (tag == 0x00280102) { mBody.setHightBit(element.getValueInt()); // If tag == pixel representation } else if (tag == 0x00280103) { mBody.setPixelRepresentation(element.getValueInt()); // If tag == window center } else if (tag == 0x00281050) { mImage.setWindowCenter(getIntFromStringArray(element)); // If tag == window width } else if (tag == 0x00281051) { mImage.setWindowWidth(getIntFromStringArray(element)); } } public boolean isRequiredElement(int tag) { return (tag == 0x00080005) || (tag == 0x00080008) || (tag == 0x00200037) || (tag == 0x00280002) || (tag == 0x00280010) || (tag == 0x00280011) || (tag == 0x00280100) || (tag == 0x00280101) || (tag == 0x00280102) || (tag == 0x00280103) || (tag == 0x00281050) || (tag == 0x00281051); } public void computeImage(DICOMElement parent, DICOMValueRepresentation VR, long valueLength) throws IOException, EOFException, DICOMException { // If the image is compressed, or if the compression status // is unknown or if the parent exists or if the bits // allocated is not defined, skip it if (mCompressionStatus == DICOMImage.UNKNOWN_STATUS || mCompressionStatus == DICOMImage.COMPRESSED || mBody.getBitsAllocated() == 0 || parent != null) { if (valueLength == 0xffffffffL) { throw new DICOMException("Cannot skip the PixelData" + " because the length is undefined"); } else { skip(valueLength); mByteOffset += valueLength; return; } } // Check the samples per pixel, just 1 is implemented yet if (mBody.getSamplesPerPixel() != 1) throw new DICOMException("The samples per pixel (" + mBody.getSamplesPerPixel() + ") is not" + " supported yet."); // For Implicit: OW and little endian if (!mIsExplicit) { computeOWImage(valueLength); // Explicit VR } else { // If it is OB return because OB is not // supported yet if (VR.equals("OB")) { skip(valueLength); mByteOffset += valueLength; return; // TODO throw an error if bits allocated > 8 // and VR == OB because PS 3.5-2009 Pg. 66-68: // If the bits allocated > 8 => OW ! // But it's not done because we do not know // if this specification of the standard is // respected and we do not implement for now // the OB reading. } else if (VR.equals("OW")) { computeOWImage(valueLength); } else { // Unknown data pixel value representation throw new DICOMException("Unknown PixelData"); } } } public DICOMBody getBody() { return mBody; } public LISAImageGray16Bit getImage() { return mImage; } /** * Compute an * * @param bitsAllocated * @param valueLength * @throws IOException * @throws EOFException * @throws DICOMException */ private void computeOWImage(long valueLength) throws IOException, EOFException, DICOMException { // Check the value length if (valueLength == 0xffffffffL) throw new DICOMException("Cannot parse PixelData " + "because the length is undefined"); // Get the bits allocated int bitsAllocated = mBody.getBitsAllocated(); // Cf. PS 3.5-2009 Pg. 66-67 if (bitsAllocated == 8) { computeOW8BitImage(valueLength); } else if (bitsAllocated == 16) { computeOW16BitImage(valueLength); } else if (bitsAllocated == 32) { /* for (int i = 0; i < mPixelData.length; i++) { mPixelData[i] = (int) readUnsignedLong(); } mByteOffset += valueLength; */ // TODO We can sample the gray level on 16 bit but // is it compatible with the DICOM standard ? throw new DICOMException("This image cannot be parsed " + "because the bits allocated value (" + bitsAllocated + ") is not supported yet."); } else if (bitsAllocated == 64) { /* for (int i = 0; i < mPixelData.length; i++) { mPixelData[i] = (int) readUnsignedLong64(); } mByteOffset += valueLength; */ // TODO We can sample the gray level on 16 bit but // is it compatible with the DICOM standard ? throw new DICOMException("This image cannot be parsed " + "because the bits allocated value (" + bitsAllocated + ") is not supported yet."); } else { throw new DICOMException("This image cannot be parsed " + "because the bits allocated value (" + bitsAllocated + ") is not supported yet."); } // Add the value length to the byte offset mByteOffset += valueLength; } private void computeOW16BitImage(long valueLength) throws IOException, EOFException, DICOMException { // Check that the value length correspond to 2 * width * height if (valueLength != (2 * mImage.getWidth() * mImage.getHeight())) throw new DICOMException("The size of the image does not " + "correspond to the size of the Pixel Data coded " + "in byte."); // Get the bit shift (e.g.: highBit = 11, bitsStored = 12 // => 11 - 12 + 1 = 0 i.e. no bit shift), (e.g.: highBit = 15, // bitsStored = 12 => 15 - 12 + 1 = 4 int bitShift = mBody.getHightBit() - mBody.getBitsStored() + 1; int grayLevel = mImage.getGrayLevel(); int[] imageData = new int[(int) (valueLength / 2)]; int imageDataMax = 0; int[] imageHistogram = new int[grayLevel]; int imageHistogramMax = 0; if (bitShift == 0) { for (int i = 0; i < imageData.length; i++) { imageData[i] = readUnsignedInt16() & 0x0000ffff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } else { for (int i = 0; i < imageData.length; i++) { imageData[i] = (readUnsignedInt16() >> bitShift) & 0x0000ffff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } mImage.setData(imageData); mImage.setDataMax(imageDataMax); mImage.setHistogramData(imageHistogram); mImage.setHistogramMax(imageHistogramMax); } private void computeOW8BitImage(long valueLength) throws IOException, EOFException, DICOMException { // Check that the value length correspond to 2 * width * height if (valueLength != (mImage.getWidth() * mImage.getHeight())) throw new DICOMException("The size of the image does not " + "correspond to the size of the Pixel Data coded " + "in byte."); // Get the bit shift (e.g.: highBit = 4, bitsStored = 5 // => 4 - 5 + 1 = 0 i.e. no bit shift), (e.g.: highBit = 6, // bitsStored = 5 => 6 - 5 + 1 = 2 int bitShift = mBody.getHightBit() - mBody.getBitsStored() + 1; int grayLevel = mImage.getGrayLevel(); int[] imageData = new int[(int) (valueLength)]; int imageDataMax = 0; int[] imageHistogram = new int[grayLevel]; int imageHistogramMax = 0; if (bitShift == 0) { for (int i = 0; i < imageData.length; i++) { imageData[i] = read() & 0x000000ff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } else { for (int i = 0; i < imageData.length; i++) { imageData[i] = (read() >> bitShift) & 0x000000ff; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } } mImage.setData(imageData); mImage.setDataMax(imageDataMax); mImage.setHistogramData(imageHistogram); mImage.setHistogramMax(imageHistogramMax); } private int getIntFromStringArray(DICOMElement element) { // Explode the string String[] values = element.getValueString().split("\\\\"); if (values.length >= 1) { try { // We do this because if the value is coded as // a float single return Math.round(Float.parseFloat(values[0])); } catch (NumberFormatException ex) { return -1; } } return -1; } private float[] getImageOrientation(DICOMElement element) { // Explode the string String[] values = element.getValueString().split("\\\\"); if (values.length != 6) return null; float[] imageOrientation = new float[6]; for (int i = 0; i < 6; i ++) { try { imageOrientation[i] = Float.parseFloat(values[i]); } catch (NumberFormatException ex) { return null; } } return imageOrientation; } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMFileFilter.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.file; import java.io.File; import java.io.FileFilter; /** * Filter the file on the basis of their extension. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMFileFilter implements FileFilter { // --------------------------------------------------------------- // + FUNCTION // --------------------------------------------------------------- // TODO check the DICOM meta information ? // This can lead to out of memory issue or // be very slow. /* (non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ public boolean accept(File pathname) { if (pathname.isFile() && !pathname.isHidden()) { // Get the file name String fileName = pathname.getName(); // If the file is a DICOMDIR return false if (fileName.equals("DICOMDIR")) return false; // Get the dot index int dotIndex = fileName.lastIndexOf("."); // If the dotIndex is equal to -1 this is // a file without extension has are the DICOM // files if (dotIndex == -1) return true; // Check the file extension String fileExtension = fileName.substring(dotIndex + 1); if (fileExtension.equalsIgnoreCase("dcm")) return true; } return false; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMReaderFunctions.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom.file; import java.io.EOFException; import java.io.IOException; import be.ac.ulb.lisa.idot.dicom.DICOMElement; import be.ac.ulb.lisa.idot.dicom.DICOMException; import be.ac.ulb.lisa.idot.dicom.DICOMValueRepresentation; /** * Interface for DICOM Reader. * * @author Pierre Malarme * @version 1.0 * */ public interface DICOMReaderFunctions { /** * Add the DICOM element to an object (e.g. DICOMBody) * or to the parent. * * @param parent Parent if it is a sequence. * @param element Element to add. */ void addDICOMElement(DICOMElement parent, DICOMElement element); /** * Check if the DICOM element is required for DICOMTag integer value * tag. * * @param tag Integer value of the DICOMTag to check. * @return */ boolean isRequiredElement(int tag); /** * Compute the image. * * @param parent Parent if it is a sequence. * @param VR DICOM value representation of the value. * @param valueLength Length of the value. */ void computeImage(DICOMElement parent, DICOMValueRepresentation VR, long valueLength) throws IOException, EOFException, DICOMException; }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMBufferedInputStream.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ // This class is based on dicom4j implementation: org.dicom4j.io.BinaryInputStream // author: <a href="mailto:straahd@users.sourceforge.net">Laurent Lecomte // http://dicom4j.sourceforge.net/ // Dicom4j License: /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // Dicom4j License [End] package be.ac.ulb.lisa.idot.dicom.file; import java.io.BufferedInputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * DICOM BufferedInputStream needed to read a DICOM file. * * It implements protected read methods for the * DICOMImageReader. * * @author Pierre Malarme * @version 1.O * */ public class DICOMBufferedInputStream extends BufferedInputStream { // --------------------------------------------------------------- // + <static> VARIABLES // --------------------------------------------------------------- public static final short LITTLE_ENDIAN = 0; public static final short BIG_ENDIAN = 1; // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- protected short mByteOrder = LITTLE_ENDIAN; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMBufferedInputStream(File file) throws FileNotFoundException { super(new FileInputStream(file), 8192); } public DICOMBufferedInputStream(FileDescriptor fd) throws FileNotFoundException { super(new FileInputStream(fd), 8192); } public DICOMBufferedInputStream(String fileName) throws FileNotFoundException { super(new FileInputStream(fileName), 8192); } public DICOMBufferedInputStream(InputStream inputStream) { super(inputStream, 8192); } public DICOMBufferedInputStream(InputStream inputStream, int bufferSize) { super(inputStream, bufferSize); } // --------------------------------------------------------------- // # FUNCTIONS // --------------------------------------------------------------- /** * Read an unsigned short that is coded on 2 bytes. * * @return Unsigned short value. * @throws IOException */ protected final int readUnsignedShort() throws IOException { return readUnsignedInt16(); } /** * Read an unsigned integer of 16-Bit. * * @return Int16 value. * @throws IOException */ protected final int readUnsignedInt16() throws IOException { byte[] unsignedInt16 = new byte[2]; if (read(unsignedInt16) != 2) throw new IOException("Cannot read an unsigned int 16-Bit."); if (mByteOrder == LITTLE_ENDIAN) return (unsignedInt16[1] & 0xff) << 8 | (unsignedInt16[0] & 0xff); else return (unsignedInt16[0] & 0xff) << 8 | (unsignedInt16[1] & 0xff); } /** * Read an unsigned long coded on 4 bytes. * * @return Unsigned long 32-Bit value. * @throws IOException */ protected final long readUnsignedLong() throws IOException { byte[] unsignedLong = new byte[4]; if (read(unsignedLong) != 4) throw new IOException("Cannot read an unsigned long 32-Bit."); if (mByteOrder == LITTLE_ENDIAN) return ((long) unsignedLong[3] & 0xff) << 24 | ((long) unsignedLong[2] & 0xFF) << 16 | ((long) unsignedLong[1] & 0xFF) << 8 | ((long) unsignedLong[0] & 0xff); else return ((long) unsignedLong[0] & 0xff) << 24 | ((long) unsignedLong[1] & 0xFF) << 16 | ((long) unsignedLong[2] & 0xFF) << 8 | ((long) unsignedLong[3] & 0xff); } /** * Read an unsigned long coded on 8 bytes. * * @return Unsigned long 64-Bit value. * @throws IOException */ protected final long readUnsignedLong64() throws IOException { byte[] unsignedLong64 = new byte[8]; if (read(unsignedLong64) != 8) throw new IOException("Cannot read an unsigned long 64-Bit."); if (mByteOrder == LITTLE_ENDIAN) return (((long) unsignedLong64[7] & 0xff) << 56) | (((long) unsignedLong64[6] & 0xff) << 48) | (((long) unsignedLong64[5] & 0xff) << 40) | (((long) unsignedLong64[4] & 0xff) << 32) | (((long) unsignedLong64[3] & 0xff) << 24) | (((long) unsignedLong64[2] & 0xff) << 16) | (((long) unsignedLong64[1] & 0xff) << 8) | ((long) unsignedLong64[0] & 0xff); else return (((long) unsignedLong64[0] & 0xff) << 56) | (((long) unsignedLong64[1] & 0xff) << 48) | (((long) unsignedLong64[2] & 0xff) << 40) | (((long) unsignedLong64[3] & 0xff) << 32) | (((long) unsignedLong64[4] & 0xff) << 24) | (((long) unsignedLong64[5] & 0xff) << 16) | (((long) unsignedLong64[6] & 0xff) << 8) | ((long) unsignedLong64[7] & 0xff); } /** * Read a signed long coded on 4 bytes. * * @return Signed long 32-Bit (= Java int) value. * @throws IOException */ protected final int readSignedLong() throws IOException { byte[] signedLong = new byte[4]; if (read(signedLong) != 4) throw new IOException("Cannot read a signed long 32-Bit."); if (mByteOrder == LITTLE_ENDIAN) return ((signedLong[3] & 0xFF) << 24) | ((signedLong[2] & 0xff) << 16) | ((signedLong[1] & 0xff) << 8) | (signedLong[0] & 0xff); else return ((signedLong[0] & 0xFF) << 24) | ((signedLong[1] & 0xff) << 16) | ((signedLong[2] & 0xff) << 8) | (signedLong[3] & 0xff); } /** * Read a signed short coded on 2 bytes. * * @return Signed Short 16-Bit value. * @throws IOException */ protected final short readSignedShort() throws IOException { byte[] signedShort = new byte[2]; if (read(signedShort) != 2) throw new IOException("Cannot read a signed short 16-bit"); short s1 = (short) (signedShort[0] & 0xff); short s2 = (short) (signedShort[1] & 0xff); if (mByteOrder == LITTLE_ENDIAN) return (short) (s2 << 8 | s1); else return (short) (s1 << 8 | s2); } /** * Read a float single. * * @return Float single value. * @throws IOException */ protected final float readFloatSingle() throws IOException { int intBits = (int) readUnsignedLong(); return Float.intBitsToFloat(intBits); } /** * Read float double. * * @return Float double value. * @throws IOException */ protected final double readFloatDouble() throws IOException { long longBits = readUnsignedLong64(); return Double.longBitsToDouble(longBits); } /** * Read a tag and coded on 32 bit. * * @return Tag coded on 32 bit and stored as an integer. * @throws IOException */ protected final int readTag() throws IOException { int group = readUnsignedInt16(); int element = readUnsignedInt16(); return ((group & 0xffff) << 16 | (element & 0xffff)); } /** * Read byte[length] as ASCII. * * @param length The number of bytes to read. * @return String that contains the ASCII value. * @throws IOException */ protected final String readASCII(int length) throws IOException { byte[] ASCIIbyte = new byte[length]; read(ASCIIbyte); // To avoid the null char : ASCII(0) String toReturnString = new String(ASCIIbyte, "ASCII"); for (int i = 0; i < length; i++) if (ASCIIbyte[i] == 0x00) return toReturnString.substring(0, i); return toReturnString; } /** * Read byte[length] as ASCII. * @param length The number of bytes to read. * @return String that contains the ASCII value. * @throws IOException */ protected final String readString(int length, String charset) throws IOException { byte[] stringIbyte = new byte[length]; if (read(stringIbyte) != length) throw new IOException("readString: Size mismatch"); // To avoid the null char : ASCII(0) String toReturnString; try { toReturnString = new String(stringIbyte, charset); } catch (UnsupportedEncodingException ex) { toReturnString = new String(stringIbyte, "ASCII"); } for (int i = 0; i < length; i++) if (stringIbyte[i] == 0x00) if (i == (length - 1)) return toReturnString.substring(0,length - 1); return toReturnString; } /** * @return Byte order. */ protected short getByteOrder() { return mByteOrder; } /** * @param mByteOrder Byte order to set */ protected void setByteOrder(short byteOrder) { this.mByteOrder = byteOrder; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMReader.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ // This class is based on dicom4j implementation: org.dicom4j.io.DicomReader // author: <a href="mailto:straahd@users.sourceforge.net">Laurent Lecomte // http://dicom4j.sourceforge.net/ // Dicom4j License: /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // Dicom4j License [End] package be.ac.ulb.lisa.idot.dicom.file; import java.io.EOFException; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.IOException; import be.ac.ulb.lisa.idot.dicom.DICOMElement; import be.ac.ulb.lisa.idot.dicom.DICOMException; import be.ac.ulb.lisa.idot.dicom.DICOMItem; import be.ac.ulb.lisa.idot.dicom.DICOMSequence; import be.ac.ulb.lisa.idot.dicom.DICOMTag; import be.ac.ulb.lisa.idot.dicom.DICOMValueRepresentation; import be.ac.ulb.lisa.idot.dicom.data.DICOMMetaInformation; /** * DICOM file reader that can read meta information of * DICOM file. * * @author Pierre Malarme * @version 1.O * */ public class DICOMReader extends DICOMBufferedInputStream { // --------------------------------------------------------------- // - <static> VARIABLES // --------------------------------------------------------------- /** * Length of the preamble. */ private static final int PREAMBLE_LENGTH = 128; /** * Prefix of DICOM file. */ private static final String PREFIX = "DICM"; // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Byte offset. */ protected long mByteOffset = 0; /** * Specific charset set in the body of the DICOM file. */ protected String mSpecificCharset = "ASCII"; /** * File size. */ protected long mFileSize = 0; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public DICOMReader(File file) throws FileNotFoundException { super(file); mFileSize = file.length(); mark(Integer.MAX_VALUE); } public DICOMReader(String fileName) throws FileNotFoundException { super(fileName); File file = new File(fileName); mFileSize = file.length(); mark(Integer.MAX_VALUE); } // --------------------------------------------------------------- // - CONSTRUCTORS // --------------------------------------------------------------- /** * Can have the file size and the BufferedInputStream do not throw * a EOFException at the end of the file (test). * * @param fd * @throws FileNotFoundException */ private DICOMReader(FileDescriptor fd) throws FileNotFoundException { super(fd); mark(Integer.MAX_VALUE); } // --------------------------------------------------------------- // + <final> FUNCTIONS // --------------------------------------------------------------- /** * @return True if the file is a DICOM file and has meta information * false otherwise. * @throws IOException */ public final boolean hasMetaInformation() throws IOException { // Reset the BufferedInputStream if (mByteOffset > 0) { reset(); mark(Integer.MAX_VALUE); } // If the file is smaller than the preamble and prefix // length there is no meta information if (available() < (PREAMBLE_LENGTH + PREFIX.length())) return false; // Skip the preamble skip(PREAMBLE_LENGTH); // Get the prefix String prefix = readASCII(PREFIX.length()); // Check the prefix boolean toReturn = prefix.equals(PREFIX); // Reset the BufferedInputStream reset(); mark(Integer.MAX_VALUE); // Skip the byte offset (mByteOffset) if (mByteOffset > 0) skip(mByteOffset); return toReturn; } /** * Parse meta information. * * @throws IOException * @throws EOFException * @throws DICOMException */ public final DICOMMetaInformation parseMetaInformation() throws IOException, EOFException, DICOMException { // Reset the BufferedInputStream if (mByteOffset > 0) { reset(); mark(Integer.MAX_VALUE); mByteOffset = 0; } try { // Skip the preamble skip(PREAMBLE_LENGTH); mByteOffset += PREAMBLE_LENGTH; // Check the prefix if (!PREFIX.equals(readASCII(4))) throw new DICOMException("This is not a DICOM file"); mByteOffset += 4; // Create a DICOM meta information object DICOMMetaInformation metaInformation = new DICOMMetaInformation(); // Tag File Meta group length = the length of // the meta of the dicom file int tag = readTag(); mByteOffset += 4; // If this is not this tag => error because the // DICOM 7.1 (3.5-2009) tags must be ordered by increasing // data element if (tag != 0x00020000) throw new DICOMException("Meta Information has now length"); // Skip 4 byte because we now that it is an UL skip(4); mByteOffset += 4; // Get the FileMeta group length long groupLength = readUnsignedLong(); mByteOffset+= 4; // Set the group length (meta information length) metaInformation.setGroupLength(groupLength); DICOMMetaInformationReaderFunctions dicomReaderFunctions = new DICOMMetaInformationReaderFunctions(metaInformation); // Fast parsing of the header with skiping sequences parse(null, groupLength, true, dicomReaderFunctions, true); // Return the meta information return metaInformation; } catch (EOFException ex) { throw new EOFException( "Cannot read the Meta Information of the DICOM file\n\n" +ex.getMessage()); } catch (IOException ex) { throw new IOException( "Cannot read the Meta Information of the DICOM file\n\n" +ex.getMessage()); } } // --------------------------------------------------------------- // # FUNCTIONS // --------------------------------------------------------------- /** * Parse the DICOM file. * * @param parentElement If a sequence is parsed. * @param length The length to parse. 0xffffffffL is * the undefined length. * @param isExplicit Set if the content of the BufferedInputStream * has explicit (true) or implicit (false) value representation. * @param dicomReaderFunctions Implementation of the DICOMReaderFunctions * interface. * @param skipSequence Set if the sequence must be skipped (true) * or not (false). * @throws IOException * @throws EOFException If the end of the file is reached before * the end of the parsing. * @throws DICOMException */ protected void parse(DICOMItem parentElement, long length, boolean isExplicit, DICOMReaderFunctions dicomReaderFunctions, boolean skipSequence) throws IOException, EOFException, DICOMException { // Set if the the length of the element to parse is defined boolean isLengthUndefined = length == 0xffffffffL; try { // Variable declaration and initialization DICOMTag dicomTag = null; DICOMValueRepresentation VR = null; long valueLength = 0; int tag = 0; length = length & 0xffffffffL; long lastByteOffset = isLengthUndefined ? 0xffffffffL : mByteOffset + length - 1; // Loop while the length is undefined or // while the byte offset is smaller than // the last byte offset while (((isLengthUndefined) || (mByteOffset < lastByteOffset)) && (mByteOffset < mFileSize)) { DICOMElement element = null; // Read the tag tag = readTag(); mByteOffset += 4; if (tag == 0) { reset(); mark(Integer.MAX_VALUE); skip(mByteOffset - 4); tag = readTag(); } // If the tag is an item delimitation // skip 4 bytes because there are // 4 null bytes after the item delimitation tag if (tag == 0xfffee00d) { skip(4); mByteOffset += 4; return; } // If the tag is an Item, ignore it // and skip 4 bytes because there are // 4 null bytes after the item delimitation tag if (tag == 0xfffee000) { skip(4); mByteOffset += 4; continue; } // Get the value representation and length // and create the DICOMTag. if (isExplicit) { // Get the DICOM value representation code/abreviation String VRAbbreviation = readASCII(2); mByteOffset += 2; VR = DICOMValueRepresentation.c.get(VRAbbreviation); VR = (VR == null) ? DICOMValueRepresentation.c.get("UN") : VR; dicomTag = DICOMTag.createDICOMTag(tag, VR); // If the value is on 2 bytes if (hasValueLengthOn2Bytes(VR.getVR())) { valueLength = readUnsignedInt16(); mByteOffset += 2; } else { skip(2); // Because VR abbreviation is coded // on 2 bytes valueLength = readUnsignedLong(); mByteOffset += 6; // 2 for the skip and 4 for the unsigned long } } else { dicomTag = DICOMTag.createDICOMTag(tag); VR = dicomTag.getValueRepresentation(); VR = (VR == null) ? DICOMValueRepresentation.c.get("UN") : VR; // If the value lengths are implicit, the length of the value // comes directly after the tag valueLength = readUnsignedLong(); mByteOffset += 4; } valueLength = valueLength & 0xffffffffL; // Get the value // If it is a sequence, read a new sequence if (VR.equals("SQ") || VR.equals("UN") && valueLength == 0xffffffffL) { // If the attribute has undefined value length // and/or do not skip sequence if (!skipSequence || valueLength == 0xffffffffL) { // Parse the sequence element = new DICOMSequence(dicomTag); parseSequence((DICOMSequence) element, valueLength, isExplicit, dicomReaderFunctions, skipSequence); } else { // Skip the value length skip(valueLength); mByteOffset += valueLength; continue; } // Else if tag is PixelData } else if (tag == 0x7fe00010) { dicomReaderFunctions.computeImage(parentElement, VR, valueLength); continue; // Return to the while begin } else if ( valueLength != 0xffffffffL) { // If it's not a required element, skip it if (parentElement != null || !dicomReaderFunctions.isRequiredElement(tag)) { skip(valueLength); mByteOffset += valueLength; continue; } Object value = null; if (VR.equals("UL")) { if (valueLength == 4) { value = readUnsignedLong(); mByteOffset += 4; } else { int size = (int) (valueLength / 4); long[] values = new long[size]; for (int i = 0; i < size; i++) { values[i] = readUnsignedLong(); mByteOffset += 4; } value = values; } } else if (VR.equals("AT")) { value = readTag(); mByteOffset += 4; } else if (VR.equals("OB") || VR.equals("OF") || VR.equals("OW")) { String valueString = new String(); for (int i = 0; i < valueLength; i++) { valueString += (i == 0) ? "" : "\\"; valueString += String.valueOf(read()); mByteOffset++; } value = valueString; } else if (VR.equals("FL")) { // if the value length is greater // than 4 it is an array of float if (valueLength == 4) { value = readFloatSingle(); mByteOffset += 4; } else { int size = (int) (valueLength / 4); float[] values = new float[size]; for (int i = 0; i < size; i++) { values[i] = readFloatSingle(); mByteOffset += 4; } value = values; } } else if (VR.equals("FD")) { // if the value length is greater // than 8 it is an array of double if (valueLength == 8) { value = readFloatDouble(); mByteOffset += 8; } else { int size = (int) (valueLength / 8); double[] values = new double[size]; for (int i = 0; i < size; i++) { values[i] = readFloatDouble(); mByteOffset += 8; } value = values; } } else if (VR.equals("SL")) { // if the value length is greater // than 4 it is an array of int if (valueLength == 4) { value = readSignedLong(); mByteOffset += 4; } else { int size = (int) (valueLength / 4); int[] values = new int[size]; for (int i = 0; i < size; i++) { values[i] = readSignedLong(); mByteOffset += 4; } value = values; } } else if (VR.equals("SS")) { // if the value length is greater // than 2 it is an array of short if (valueLength == 2) { value = readSignedShort(); mByteOffset += 2; } else { int size = (int) (valueLength / 2); short[] values = new short[size]; for (int i = 0; i < size; i++) { values[i] = readSignedShort(); mByteOffset += 2; } value = values; } } else if (VR.equals("US")) { // if the value length is greater // than 2 it is an array of int if (valueLength == 2) { value = readUnsignedShort(); mByteOffset += 2; } else { int size = (int) (valueLength / 2); int[] values = new int[size]; for (int i = 0; i < size; i++) { values[i] = readUnsignedShort(); mByteOffset += 2; } value = values; } } else if (VR.equals("LO") || VR.equals("LT") || VR.equals("PN") || VR.equals("SH") || VR.equals("ST") || VR.equals("UT")) { value = readString((int) valueLength, mSpecificCharset); mByteOffset += valueLength; // Else interpreted as ASCII String } else { value = readASCII((int) valueLength); mByteOffset += valueLength; } // Create the element element = new DICOMElement(dicomTag, valueLength, value); } if (element != null) { // Add the DICOM element dicomReaderFunctions.addDICOMElement(parentElement, element); } } // end of the while // End of the stream exception } catch (EOFException e) { if (!isLengthUndefined) throw new EOFException(); // I/O Exception } catch (IOException e) { if (!isLengthUndefined) throw new IOException(); } } /** * Parse a DICOM sequence. * * @param sequence DICOM sequence to parse. * @param length Length of DICOM sequence. * @param isExplicit Set if the content of the BufferedInputStream * has explicit (true) or implicit (false) value representation. * @param dicomReaderFunctions Implementation of the DICOMReaderFunctions * interface. * @param skipSequence Set if the sequence must be skipped (true) * or not (false). * @throws IOException * @throws DICOMException * @throws EOFException If the end of the file is reached before * the end of the parsing. */ protected void parseSequence(DICOMSequence sequence, long length, boolean isExplicit, DICOMReaderFunctions dicomReaderFunctions, boolean skipSequence) throws IOException, EOFException, DICOMException { if (sequence == null) { throw new NullPointerException("Null Sequence"); } length = length & 0xffffffffL; boolean isLengthUndefined = length == 0xffffffffL; try { long lastByteOffset = isLengthUndefined ? 0xffffffffL : mByteOffset + length - 1; // Loop on all the items while (isLengthUndefined || mByteOffset < lastByteOffset) { // Get the tag int tag = readTag(); mByteOffset += 4; long valueLength = readUnsignedLong(); mByteOffset += 4; // If the tag is an Item if (tag == 0xfffee0dd) { break; } else if (tag == 0xfffee000) { DICOMItem item = new DICOMItem(); parse(item, valueLength, isExplicit, dicomReaderFunctions, skipSequence); sequence.addChild(item); // else if the tag is different that end // of sequence, this is not a sequence item } else { throw new DICOMException("Error Sequence: unknown tag" + (tag >> 16) + (tag & 0xffff)); } } } catch (EOFException e) { if (!isLengthUndefined) throw new EOFException(); } catch (IOException ex) { if (!isLengthUndefined) throw new IOException(ex.getMessage()); } } /** * Check if the value representation is on 2 bytes. * * @param VR DICOM value representation code on 2 bytes (character). * @return */ protected static final boolean hasValueLengthOn2Bytes(String VR) { return VR.equals("AR") || VR.equals("AE") || VR.equals("AS") || VR.equals("AT") || VR.equals("CS") || VR.equals("DA") || VR.equals("DS") || VR.equals("DT") || VR.equals("FD") || VR.equals("FL") || VR.equals("IS") || VR.equals("LO") || VR.equals("LT") || VR.equals("PN") || VR.equals("SH") || VR.equals("SL") || VR.equals("SL") || VR.equals("SS") || VR.equals("ST") || VR.equals("TM") || VR.equals("UI") || VR.equals("UL") || VR.equals("US"); } // --------------------------------------------------------------- // # CLASS // --------------------------------------------------------------- /** * Implementation of the DICOMReaderFunctions for * meta information. * * @author Pierre Malarme * @version 1.O * */ protected class DICOMMetaInformationReaderFunctions implements DICOMReaderFunctions { private DICOMMetaInformation mMetaInformation; public DICOMMetaInformationReaderFunctions() { mMetaInformation = new DICOMMetaInformation(); } public DICOMMetaInformationReaderFunctions(DICOMMetaInformation metaInformation) { mMetaInformation = metaInformation; } public void addDICOMElement(DICOMElement parent, DICOMElement element) { // If this is a sequence, do nothing if (parent != null) return; int tag = element.getDICOMTag().getTag(); // SOP Class UID if (tag == 0x00020002) { mMetaInformation.setSOPClassUID(element.getValueString()); // SOP Instance UID } else if (tag == 0x00020003) { mMetaInformation.setSOPInstanceUID(element.getValueString()); // Transfer syntax UID } else if (tag == 0x00020010) { mMetaInformation.setTransferSyntaxUID(element.getValueString()); // Implementation Class UID } else if (tag == 0x00020012) { mMetaInformation.setImplementationClassUID(element.getValueString()); // Implementation version name } else if (tag == 0x00020013) { mMetaInformation.setImplementationVersionName(element.getValueString()); // Implementation Application Entity Title } else if (tag == 0x00020016) { mMetaInformation.setAET(element.getValueString()); } } public boolean isRequiredElement(int tag) { return (tag == 0x00020002) || (tag == 0x00020003) || (tag == 0x00020010) || (tag == 0x00020012) || (tag == 0x00020013) || (tag == 0x00020016); } public void computeImage(DICOMElement parent, DICOMValueRepresentation VR, long length) throws IOException, EOFException, DICOMException { throw new IOException("PixelData in Meta Information."); } } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMTag.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.HashMap; import java.util.Map; /** * DICOM tag. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMTag { // --------------------------------------------------------------- // + <static> VARIABLE // --------------------------------------------------------------- /** * Map of defined tag. */ public static final Map<Integer, DICOMTag> c = new HashMap<Integer, DICOMTag>() { /** * Eclipse generated Serial version. */ private static final long serialVersionUID = -8652499398694995133L; // To generate each time this hashmap is modified. { put(0x00020000, new DICOMTag(0x00020000, "File Meta Information Group Length", DICOMValueRepresentation.c.get("UL"))); put(0x00020001, new DICOMTag(0x00020001, "File Meta Information Group Length", DICOMValueRepresentation.c.get("OB"))); put(0x00020002, new DICOMTag(0x00020002, "Media Storage SOP Class UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020003, new DICOMTag(0x00020003, "Media Storage SOP Instance UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020010, new DICOMTag(0x00020010, "TransferSyntax UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020012, new DICOMTag(0x00020012, "Implementation Class UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020013, new DICOMTag(0x00020013, "Implementation Version Name", DICOMValueRepresentation.c.get("SH"))); put(0x00020016, new DICOMTag(0x00020016, "Source Application Entity", DICOMValueRepresentation.c.get("AE"))); put(0x00020100, new DICOMTag(0x00020100, "Private Information creator UID", DICOMValueRepresentation.c.get("UI"))); put(0x00020102, new DICOMTag(0x00020102, "Private Information creator UID", DICOMValueRepresentation.c.get("OB"))); put(0x00280002, new DICOMTag(0x00280002, "Samples per pixel", DICOMValueRepresentation.c.get("US"))); put(0x00280010, new DICOMTag(0x00280010, "Rows", DICOMValueRepresentation.c.get("US"))); put(0x00280011, new DICOMTag(0x00280011, "Columns", DICOMValueRepresentation.c.get("US"))); put(0x00280100, new DICOMTag(0x00280100, "Bits allocated", DICOMValueRepresentation.c.get("US"))); put(0x00280101, new DICOMTag(0x00280101, "Bits stored", DICOMValueRepresentation.c.get("US"))); put(0x00280102, new DICOMTag(0x00280102, "High Bit", DICOMValueRepresentation.c.get("US"))); put(0x00280103, new DICOMTag(0x00280103, "Pixel Representation", DICOMValueRepresentation.c.get("US"))); put(0x7fe00010, new DICOMTag(0x7fe00010, "Pixel Data", DICOMValueRepresentation.c.get("UN"))); put(0xfffee000, new DICOMTag(0xfffee000, "Item", DICOMValueRepresentation.c.get("UN"))); put(0xfffee00d, new DICOMTag(0xfffee00d, "Item Delimitation Tag", DICOMValueRepresentation.c.get("UN"))); put(0xfffee0dd, new DICOMTag(0xfffee0dd, "Sequence Delimitation Tag", DICOMValueRepresentation.c.get("UN"))); }}; // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Tag integer value. */ private final int mTag; /** * Tag description. */ private final String mName; /** * Tag value representation. */ private final DICOMValueRepresentation mVR; // --------------------------------------------------------------- // + <static> FUNCTIONS // --------------------------------------------------------------- /** * Create a DICOM tag using a tag integer value. * * @param tag Tag integer value * @return */ public static final DICOMTag createDICOMTag(int tag) { // If the tag is known by Droid Dicom Viewer if (c.containsKey(tag)) { return c.get(tag); } else { int tagGroup = (tag >> 16) & 0xff; // If the tagGroup is an odd Number, the tag is // Private String name = (tagGroup % 2 == 0) ? "Unknown" : "Private"; DICOMValueRepresentation VR = DICOMValueRepresentation.c.get("UN"); return new DICOMTag(tag, name, VR); } } /** * Create a DICOM tag using a tag integer value * and a value representation. * * @param tag Tag integer value * @param VR Value representation. * @return */ public static final DICOMTag createDICOMTag(int tag, DICOMValueRepresentation VR) { String name; // If the tag is known by Droid Dicom Viewer if (c.containsKey(tag)) { // If the VR is the same as a tag in memory, return this tag if (VR.getVR().equals(c.get(tag).getValueRepresentation().getVR())) return c.get(tag); name = c.get(tag).getName(); } else { int tagGroup = (tag >> 16) & 0xff; // If the tagGroup is an odd Number, the tag is // Private name = (tagGroup % 2 == 0) ? "Unknown" : "Private"; } return new DICOMTag(tag, name, VR); } // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMTag(int tag, String name, DICOMValueRepresentation VR) { mTag = tag; mName = name; mVR = VR; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return the mTag */ public int getTag() { return mTag; } /** * @return Tag UID as a String (group + element). */ public String toString() { return getGroup() + getElement(); } /** * @return Tag group as a String. */ public String getGroup() { String toReturn = Integer.toHexString((mTag >> 16) & 0xffff); while (toReturn.length() < 4) toReturn = "0" + toReturn; return toReturn; } /** * @return Tag element as a String. */ public String getElement() { String toReturn = Integer.toHexString((mTag) & 0xffff); while (toReturn.length() < 4) toReturn = "0" + toReturn; return toReturn; } /** * @return Tag description. */ public String getName() { return mName; } /** * @return Value representation. */ public DICOMValueRepresentation getValueRepresentation() { return mVR; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMElement.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; /** * DICOM element. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMElement { // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- /** * DICOM element DICOM tag. */ protected DICOMTag mDICOMTag; /** * DICOM element value. */ protected Object mValue; /** * DICOM element length in byte. */ protected long mLength; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- /** * Construct a DICOM item with a undefined length. * @param dicomTag * @param value */ public DICOMElement(DICOMTag dicomTag, Object value) { this(dicomTag, 0xffffffffL, value); } public DICOMElement(DICOMTag dicomTag, long length, Object value) { mDICOMTag = dicomTag; mLength = length; mValue = value; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return the mDICOMTag */ public DICOMTag getDICOMTag() { return mDICOMTag; } /** * @return the mValue */ public Object getValue() { return mValue; } /** * @return DICOM element length in bytes. */ public long getLength() { return mLength; } /** * @return DICOM element value as a String or null * if there is an error. */ public String getValueString() { // If there is no value return null if (mValue == null) return "NULL"; // If no tag return a null object if (mDICOMTag == null) return null; // TODO throw a DICOM Exception // Get the value representation DICOMValueRepresentation VR = mDICOMTag.getValueRepresentation(); if (mDICOMTag.getTag() == 0x7fe00010) { if (VR.equals("OW")) return "Pixel DICOM OW"; else if (VR.equals("OB")) return "Pixel DICOM OB"; } if (VR.equals("US") || VR.equals("SS")) { if (mLength > 2) return "Array of numerical values coded in 2 bits"; } else if (VR.equals("UL") || VR.equals("FL") || VR.equals("SL")) { if (mLength > 4) return "Array of numerical values coded in 4 bits"; } else if (VR.equals("FD")) { if (mLength > 8) return "Array of numerical values coded in 8 bits"; } // Get the value class from the VR @SuppressWarnings("rawtypes") Class valueClass = VR.getReturnType(); // If type match return the string representing the value if (valueClass.equals(mValue.getClass())) { String toReturn = "" + valueClass.cast(mValue); return toReturn; } else { return null; } } /** * @param dicomTag DICOMTag to set */ public void setDICOMTag(DICOMTag dicomTag) { mDICOMTag = dicomTag; } /** * @param value the value to set */ public void setValue(Object value) { mValue = value; } /** * @param length the length to set. */ public void setLength(int length) { mLength = length; } /** * @return DICOM element value as an integer. * @throws NumberFormatException If the value is not an * integer, it throws a NumberFormatException. */ public int getValueInt() throws NumberFormatException { int toReturn = 0; if (mValue instanceof String) { toReturn = Integer.parseInt((String) mValue); } else if (mValue instanceof Short) { toReturn = (int) (Short) mValue; } else if (mValue instanceof Integer) { toReturn = (Integer) mValue; } else if (mValue instanceof Long) { toReturn = ((Long) mValue).intValue(); } else { toReturn = Integer.parseInt(getValueString()); } return toReturn; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMSequence.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.ArrayList; import java.util.List; /** * DICOM sequence. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMSequence extends DICOMElement { // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- /** * List of DICOMElement children (normally DICOMItem). */ protected List<DICOMElement> mChildrenList; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMSequence(DICOMTag dicomTag) { super(dicomTag, null); mChildrenList = new ArrayList<DICOMElement>(); } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Add a DICOMElement child to the sequence (List). * @param element */ public void addChild(DICOMElement element) { mChildrenList.add(element); } /** * Get a DICOMElement child from the List correspond to the index. * @param index Index of the child. * @return DICOMElement child. * @throws IndexOutOfBoundsException */ public DICOMElement getChild(int index) throws IndexOutOfBoundsException { return mChildrenList.get(index); } /** * @return DICOMElement children List. */ public List<DICOMElement> getChildrenList() { return mChildrenList; } /** * @return Number of children in the List. */ public int getChildrenCount() { return mChildrenList.size(); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMException.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; /** * DICOM Exception. * * DICOM exception occurs when the parsing of the DICOM file * is not possible or if the DICOM file is not supported by * the software. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMException extends Exception { /** * Generated by Eclipse */ private static final long serialVersionUID = -2837146355840633988L; public DICOMException() { super(); } public DICOMException(String msg) { super(msg); } public DICOMException(String msg, Throwable throwable) { super(msg, throwable); } public DICOMException(Throwable throwable) { super(throwable); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMValueRepresentation.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.HashMap; import java.util.Map; /** * DICOM tag. * * @author Pierre Malarme * @version 1.0 * */ /** * @author pmalarme * */ /** * @author pmalarme * */ public class DICOMValueRepresentation { // --------------------------------------------------------------- // + <static> VARIABLE // --------------------------------------------------------------- // The class raw types of the value representation. /** * Byte array set as String. */ @SuppressWarnings("rawtypes") public static final Class BYTE = String.class; /** * Double. */ @SuppressWarnings("rawtypes") public static final Class DOUBLE = Double.class; /** * Float. */ @SuppressWarnings("rawtypes") public static final Class FLOAT = Float.class; /** * Integer. */ @SuppressWarnings("rawtypes") public static final Class INT = Integer.class; /** * Long. */ @SuppressWarnings("rawtypes") public static final Class LONG = Long.class; /** * Object: just for sequence. */ @SuppressWarnings("rawtypes") public static final Class OBJECT = Object.class; /** * String. */ @SuppressWarnings("rawtypes") public static final Class STRING = String.class; /** * Short. */ @SuppressWarnings("rawtypes") public static final Class SHORT = Short.class; /** * Map of value representation. */ public static final Map<String, DICOMValueRepresentation> c = new HashMap<String, DICOMValueRepresentation>() { /** * Eclipse generated serial version UID. */ private static final long serialVersionUID = 4021611561632736549L; { put("AE", new DICOMValueRepresentation("AE", "Application Entity", STRING, 16, false)); put("AS", new DICOMValueRepresentation("AS", "Age String", STRING, 4, true)); put("AT", new DICOMValueRepresentation("AS", "Attribute Tag", INT, 4, true)); put("CS", new DICOMValueRepresentation("CS", "Code String", STRING, 16, true)); put("DA", new DICOMValueRepresentation("DA", "Date", STRING, 18, false)); // TODO DICOM 3.5-2009 page 25 : In the context of a Query with range matching // the length is 18 bytes maximum => in that case create a new ValueRepresentation ? // => not set to 18 and maximum for future instead of 8 and fixed. put("DS", new DICOMValueRepresentation("DS", "Decimal String", STRING, 16, false)); put("DT", new DICOMValueRepresentation("DT", "Date Time", STRING, 54, false)); // TODO DICOM 3.5-2009 page 26 : In the context of a Query with range matching // the length is 54 bytes maximum => in that case create a new ValueRepresentation ? // => not set to 54 and maximum for future instead of 26 and maximum. put("FL", new DICOMValueRepresentation("FL", "Floating Point Single", FLOAT, 4, true)); put("FD", new DICOMValueRepresentation("FD", "Floating Point Double", DOUBLE, 8, true)); put("IS", new DICOMValueRepresentation("IS", "Integer String", STRING, 12, false)); put("LO", new DICOMValueRepresentation("LO", "Long String", STRING, 64, false)); put("LT", new DICOMValueRepresentation("LT", "Long Text", STRING, 1024, false)); put("OB", new DICOMValueRepresentation("OB", "Other Byte String", BYTE)); put("OF", new DICOMValueRepresentation("OF", "Other Float String", STRING)); // TODO Set the max at 2^32-4 cf. pg 28 put("OW", new DICOMValueRepresentation("OW", "Other Word String", STRING)); put("PN", new DICOMValueRepresentation("PN", "Person Name", STRING)); // TODO ADD A PN OBJECT TYPE because 64-chars per component group (pg. 28) put("SH", new DICOMValueRepresentation("SH", "Short String", STRING, 16, false)); put("SL", new DICOMValueRepresentation("SL", "Signed Long", INT, 4 , true)); put("SQ", new DICOMValueRepresentation("SQ", "Sequence of Items", OBJECT)); put("SS", new DICOMValueRepresentation("SS", "Signed Short", SHORT, 2, true)); put("ST", new DICOMValueRepresentation("ST", "Short Text", STRING, 1024, false)); put("TM", new DICOMValueRepresentation("TM", "Time", STRING, 28, false)); // TODO DICOM 3.5-2009 page 31 : In the context of a Query with range matching // the length is 28 bytes maximum => in that case create a new ValueRepresentation ? // => not set to 28 and maximum for future instead of 16 and maximum. put("UI", new DICOMValueRepresentation("UI", "Unique Identifier", STRING, 64, false)); put("UL", new DICOMValueRepresentation("UL", "Unsigned Long", LONG, 4, false)); put("UN", new DICOMValueRepresentation("UN", "Unknown", STRING)); // TODO Any length valid for any of the DICOM Value representation cf. pg 32 put("US", new DICOMValueRepresentation("US", "Unsigned Short", INT, 2, false)); // Page 32 US: vale n: 0 <= n < 2^16 put("UT", new DICOMValueRepresentation("UT", "Unlimited Text", STRING)); // TODO pg. 32: maximum length 2^32-2 }}; // --------------------------------------------------------------- // - VARIABLE // --------------------------------------------------------------- /** * Value representation code on 2 bytes (character). */ private final String mVR; /** * Value representation description. */ private final String mName; /** * Raw type of the value representation. */ @SuppressWarnings("rawtypes") private final Class mReturnType; /** * The maximum byte count. * -1 = no maximum */ private final int mMaxByteCount; /** * If the number of byte is fixed or not. If it is the case, * the mMaxByteCount is the fixed number of bytes. */ private final boolean mIsFixedByteCount; // --------------------------------------------------------------- // - CONSTRUCTORS // --------------------------------------------------------------- /** * The constructor is private because only known value representation * are accepted. If the value is unknown, it is set to UN. * * @param VR * @param name * @param returnType */ @SuppressWarnings("rawtypes") private DICOMValueRepresentation(String VR, String name, Class returnType) { this(VR, name, returnType, -1, false); } /** * The constructor is private because only known value representation * are accepted. If the value is unknown, it is set to UN. * * @param VR * @param name * @param returnType * @param maxByteCount * @param isFixedByteCount */ @SuppressWarnings("rawtypes") private DICOMValueRepresentation(String VR, String name, Class returnType, int maxByteCount, boolean isFixedByteCount) { mVR = VR; mName = name; mReturnType = returnType; mMaxByteCount = maxByteCount; mIsFixedByteCount = isFixedByteCount; } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Get if this object is a value representation identical to VR. * @param VR * @return */ public boolean equals(String VR) { if (VR == null) return false; else if (mVR == VR) return true; else return false; } /** * @return Value representation code on 2 bytes (character). */ public String getVR() { return mVR; } /** * @return Value representation description. */ public String getName() { return mName; } /** * @return Raw type. */ @SuppressWarnings("rawtypes") public Class getReturnType() { return mReturnType; } /** * @return Maximum byte. */ public int getMaxByteCount() { return mMaxByteCount; } /** * @return If the number of byte is fixed or not. */ public boolean isFixedByteCount() { return mIsFixedByteCount; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <DICOMItem.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.dicom; import java.util.HashMap; import java.util.Map; /** * DICOM item. * * @author Pierre Malarme * @version 1.0 * */ public class DICOMItem extends DICOMElement { // --------------------------------------------------------------- // # VARIABLES // --------------------------------------------------------------- /** * The map of DICOMElement children. */ protected Map<Integer, DICOMElement> mChildrenMap; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public DICOMItem() { super(DICOMTag.createDICOMTag(0xfffee000), null); mChildrenMap = new HashMap<Integer, DICOMElement>(); } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * Add a DICOMElement child to the map. * * @param tag * @param element */ public void addChild(int tag, DICOMElement element) { mChildrenMap.put(tag, element); } /** * Get a DICOMElement from the map. * * @param tag The tag integer value of the child. * @return DICOMElement or null if it does * not exist. */ public DICOMElement getChild(int tag) { return mChildrenMap.get(tag); } /** * @return DICOMElement children map. */ public Map<Integer, DICOMElement> getChildrenMap() { return mChildrenMap; } /** * @return Number of DICOMElement children. */ public int getChildrenCount() { return mChildrenMap.size(); } /** * @param tag * @return True if there is a child with is DICOMTag * integer value set as tag. False otherwise. */ public boolean containsChild(int tag) { return mChildrenMap.containsKey(tag); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <LISAImageGray16Bit.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.image.data; /** * LISA 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.O * */ public class LISAImageGray16Bit { // --------------------------------------------------------------- // - VARIABLES // --------------------------------------------------------------- /** * Image width that correspond to * the number of column. */ protected short mWidth = 0; /** * Image height that correspond to * the number of row. */ protected short mHeight = 0; /** * Image data. */ protected int[] mData = null; /** * Maximum value of the data. */ protected int mDataMax = 0; /** * The histogram data. */ protected int[] mHistogramData = null; /** * Maximum value of the Histogram. */ protected int mHistogramMax = 0; /** * The total number of gray level. */ protected int mGrayLevel = 4096; /** * Window width. */ protected int mWindowWidth = -1; /** * Window center */ protected int mWindowCenter = -1; /** * Image orientation. */ protected float[] mImageOrientation = new float[6]; // --------------------------------------------------------------- // + CONSTRUCTOR // --------------------------------------------------------------- public LISAImageGray16Bit() { } // --------------------------------------------------------------- // + FUNCTIONS // --------------------------------------------------------------- /** * @return Image width. */ public short getWidth() { return mWidth; } /** * @return Image height. */ public short getHeight() { return mHeight; } /** * @return Image data. */ public int[] getData() { return mData; } /** * @return Image data length. */ public int getDataLength() { return mData == null ? 0 : mData.length; } /** * @return Maximum data value. */ public int getDataMax() { return mDataMax; } /** * @return Histogram data. */ public int[] getHistogramData() { return mHistogramData; } /** * @return Histogram length. */ public int getHistogramLength() { return mHistogramData == null ? 0 : mHistogramData.length; } /** * @return Histogram max value. */ public int getHistogramMax() { return mHistogramMax; } /** * @return The number of gray level. */ public int getGrayLevel() { return mGrayLevel; } /** * @return Window width. */ public int getWindowWidth() { return mWindowWidth; } /** * @return Window Center */ public int getWindowCenter() { return mWindowCenter; } /** * @return Window offset. */ public int getWindowOffset() { return ((2 * mWindowCenter - mWindowWidth)) / 2; } /** * @return Image orientation. */ public float[] getImageOrientation() { return mImageOrientation; } /** * @param width The width to set. */ public void setWidth(short width) { mWidth = width; } /** * @param height The height to set. */ public void setHeight(short height) { mHeight = height; } /** * @param data The data to set. */ public void setData(int[] data) { mData = data; } /** * @param dataMax The dataMax to set. */ public void setDataMax(int dataMax) { mDataMax = dataMax; } /** * @param histogramData The histogram data to set. */ public void setHistogramData(int[] histogramData) { mHistogramData = histogramData; } /** * @param histogramMax The histogram max value to set. */ public void setHistogramMax(int histogramMax) { mHistogramMax = histogramMax; } /** * @param grayLevel The maximum number of gray level to set. */ public void setGrayLevel(int grayLevel) { mGrayLevel = grayLevel; } /** * @param windowWidth The window width to set. */ public void setWindowWidth(int windowWidth) { mWindowWidth = windowWidth; } /** * @param windowCenter The window center to set. */ public void setWindowCenter(int windowCenter) { mWindowCenter = windowCenter; } /** * @param imageOrientation The image orientation array. */ public void setImageOrientation(float[] imageOrientation) { if (imageOrientation == null) return; if (imageOrientation.length == 6) mImageOrientation = imageOrientation; } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <LISAImageGray16BitWriter.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.image.file; import java.io.File; import java.io.FileDescriptor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * Writer for LISA 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.0 * */ public class LISAImageGray16BitWriter extends FileOutputStream { // --------------------------------------------------------------- // - <static> VARIABLE // --------------------------------------------------------------- protected static final String PREFIX = "LISAGRAY0016"; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public LISAImageGray16BitWriter(File file) throws FileNotFoundException { super(file); } public LISAImageGray16BitWriter(FileDescriptor fd) { super(fd); } public LISAImageGray16BitWriter(String filename) throws FileNotFoundException { super(filename); } // --------------------------------------------------------------- // # CONSTRUCTORS // --------------------------------------------------------------- /** * Function private to forbid its use. * * @param file * @param append * @throws FileNotFoundException */ private LISAImageGray16BitWriter(File file, boolean append) throws FileNotFoundException { super(file, append); } /** * Function private to forbid its use. * * @param filename * @param append * @throws FileNotFoundException */ private LISAImageGray16BitWriter(String filename, boolean append) throws FileNotFoundException { super(filename, append); } // --------------------------------------------------------------- // + FUNCTION // --------------------------------------------------------------- /** * Write a LISA 16-Bit grayscale image. * @param image A LISA 16-bit grayscale image. * @throws IOException */ public void write(LISAImageGray16Bit image) throws IOException { if (image == null) throw new NullPointerException("Image is null"); try { // PREFIX // Write the prefix write(PREFIX.getBytes()); // IMAGE SIZE // Write width writeInt16(image.getWidth()); // Write height writeInt16(image.getHeight()); // GRAY LEVELS AND WINDOW // Write the gray levels writeLong32(image.getGrayLevel()); // Write window width writeInt16(image.getWindowWidth()); // Write window center writeInt16(image.getWindowCenter()); // Write the image orientation writeImageOrientation(image); // Write image length writeLong32(image.getDataLength()); // Write the image data writeInt16Array(image.getData()); } catch (IOException e) { throw new IOException("Cannot open write LISA image.\n" + e.getMessage()); } } // --------------------------------------------------------------- // # FUNCTIONS // --------------------------------------------------------------- /** * Write an integer on 2 bytes. * @param value Integer value. * @throws IOException */ protected final void writeInt16(int value) throws IOException { byte[] int16Bytes = new byte[2]; int16Bytes[0] = (byte) ((value >> 8) & 0xff); int16Bytes[1] = (byte) ((value) & 0xff); super.write(int16Bytes); } /** * Write a long on 4 bytes. * * If the value correspond to the image length the maximum value * must be set as Integer.MAX_VALUE due to java array limitation: * the maximum length is the maximum integer value. * * @param value Long value. * @throws IOException */ protected final void writeLong32(long value) throws IOException { byte[] long32Bytes = new byte[4]; long32Bytes[0] = (byte) ((value >> 24) & 0xff); long32Bytes[1] = (byte) ((value >> 16) & 0xff); long32Bytes[2] = (byte) ((value >> 8) & 0xff); long32Bytes[3] = (byte) ((value) & 0xff); super.write(long32Bytes); } /** * Write an array of integer. * * Each integer value is coded in 2 bytes. * * @param intArray Array of integer values. * @throws IOException */ protected final void writeInt16Array(int[] intArray) throws IOException { byte[] intArrayBytes = new byte[intArray.length * 2]; for (int i = 0; i < intArray.length; i ++) { intArrayBytes[(2 * i) + 0] = (byte) ((intArray[i] >> 8) & 0xff); intArrayBytes[(2 * i) + 1] = (byte) ((intArray[i]) & 0xff); } super.write(intArrayBytes); } /** * Write an array of float values. * * @param floatArray * @throws IOException */ protected final void writeFloatArray(float[] floatArray) throws IOException { for (int i = 0; i < floatArray.length; i++) { int binaryValue = Float.floatToRawIntBits(floatArray[i]); writeLong32(binaryValue); } } /** * Write the image orientation float array. * * @param image * @throws IOException */ protected final void writeImageOrientation(LISAImageGray16Bit image) throws IOException { float[] imageOrientation = image.getImageOrientation(); // Check if the array is null or not null imageOrientation = (imageOrientation == null) ? new float[6] : imageOrientation; writeFloatArray(imageOrientation); } }
Java
/* * * Copyright (C) 2011 Pierre Malarme * * Authors: Pierre Malarme <pmalarme at ulb.ac.be> * * Institution: Laboratory of Image Synthesis and Analysis (LISA) * Faculty of Applied Science * Universite Libre de Bruxelles (U.L.B.) * * Website: http://lisa.ulb.ac.be * * This file <LISAImageGray16BitReader.java> is part of Droid Dicom Viewer. * * Droid Dicom Viewer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Droid Dicom Viewer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Droid Dicom Viewer. If not, see <http://www.gnu.org/licenses/>. * * Released date: 17-02-2011 * * Version: 1.0 * */ package be.ac.ulb.lisa.idot.image.file; import java.io.EOFException; import java.io.File; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import be.ac.ulb.lisa.idot.image.data.LISAImageGray16Bit; /** * Reader for LISA 16-Bit grayscale image. * * @author Pierre Malarme * @version 1.0 * */ public class LISAImageGray16BitReader extends FileInputStream { // --------------------------------------------------------------- // - <static> VARIABLE // --------------------------------------------------------------- protected static final String PREFIX = "LISAGRAY0016"; // --------------------------------------------------------------- // + CONSTRUCTORS // --------------------------------------------------------------- public LISAImageGray16BitReader(File file) throws FileNotFoundException { super(file); } public LISAImageGray16BitReader(FileDescriptor fd) { super(fd); } public LISAImageGray16BitReader(String fileName) throws FileNotFoundException { super(fileName); } // --------------------------------------------------------------- // + FUCTIONS // --------------------------------------------------------------- public synchronized LISAImageGray16Bit parseImage() throws IOException, EOFException { // Check the prefix if (!PREFIX.equals(readASCII(PREFIX.length()))) throw new IOException("This is not a LISA 16-Bit" + "grayscale image"); try { byte[] buffer = new byte[available()]; read(buffer); // Create the image LISAImageGray16Bit image = new LISAImageGray16Bit(); // Get the image attributes int byteOffset = 0; // Image Width image.setWidth((short) ((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff))); byteOffset += 2; // Image Height image.setHeight((short) ((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff))); byteOffset += 2; // Image gray levels count int grayLevel = (buffer[byteOffset + 0] & 0xff) << 24 | (buffer[byteOffset + 1] & 0xff) << 16 | (buffer[byteOffset + 2] & 0xff) << 8 | (buffer[byteOffset + 3] & 0xff); byteOffset += 4; image.setGrayLevel(grayLevel); // Window width image.setWindowWidth(((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff))); byteOffset += 2; // Window Height image.setWindowCenter(((buffer[byteOffset + 0] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff)));; byteOffset += 2; // Image orientation float[] imageOrientation = new float[6]; for (int i = 0; i < 6; i++) { int binaryValue = (buffer[byteOffset + 0] & 0xff) << 24 | (buffer[byteOffset + 1] & 0xff) << 16 | (buffer[byteOffset + 2] & 0xff) << 8 | (buffer[byteOffset + 3] & 0xff); byteOffset += 4; imageOrientation[i] = Float.intBitsToFloat(binaryValue); } image.setImageOrientation(imageOrientation); // Data length int dataLength = (buffer[byteOffset + 0] & 0xff) << 24 | (buffer[byteOffset + 1] & 0xff) << 16 | (buffer[byteOffset + 2] & 0xff) << 8 | (buffer[byteOffset + 3] & 0xff); byteOffset += 4; // Compute the histogram data and max // and the image data and max int[] imageData = new int[dataLength]; int imageDataMax = 0; int[] imageHistogram = new int[grayLevel]; int imageHistogramMax = 0; for (int i = 0; i < dataLength; i ++) { imageData[i] = (buffer[byteOffset] & 0xff) << 8 | (buffer[byteOffset + 1] & 0xff); byteOffset += 2; if (imageData[i] > imageDataMax) imageDataMax = imageData[i]; if (imageData[i] >= 0 && imageData[i] < grayLevel) { imageHistogram[imageData[i]] += 1; if (imageHistogram[imageData[i]] > imageHistogramMax) imageHistogramMax = imageHistogram[imageData[i]]; } } image.setData(imageData); image.setDataMax(imageDataMax); image.setHistogramData(imageHistogram); image.setHistogramMax(imageHistogramMax); return image; } catch (EOFException ex) { throw new EOFException("Reached the end of the file before " + "reading all data. \n" + ex.getMessage()); } catch (IOException ex) { throw new IOException("Cannot parse the LISA Image " + "grayscale 16-Bit. \n" + ex.getMessage()); } } // --------------------------------------------------------------- // # FUNCTION // --------------------------------------------------------------- /** * Read byte[length] as ASCII. * @param length The number of bytes to read. * @return String that contains the ASCII value. * @throws IOException */ protected synchronized final String readASCII(int length) throws IOException, EOFException { byte[] ASCIIbyte = new byte[length]; if (read(ASCIIbyte) == -1) throw new IOException(); // To avoid the null char : ASCII(0) String toReturnString = new String(ASCIIbyte, "ASCII"); for (int i = 0; i < length; i++) if (ASCIIbyte[i] == 0x00) return toReturnString.substring(0, i); return toReturnString; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package anm_banvetau; import java.net.Socket; import java.io.*; /** * * @author Admin */ public class ThreadSocket extends Thread{ Socket socket= null; public ThreadSocket(Socket socket) { this.socket=socket; } public void run() { try { DataOutputStream sendToClient= new DataOutputStream(socket.getOutputStream());// Tao output stream BufferedReader fromClient= new BufferedReader(new InputStreamReader(socket.getInputStream()));//Tao input stream while (true) { String sentence = fromClient.readLine();// Chuỗi nhận được từ Client System.out.println("FROM CLIENT: " + sentence); if (sentence.equalsIgnoreCase("quit")) break; String reverseSentence= reverse(sentence); //Thread.sleep(10000); // Giả sử khi xử lý nó mất khoảng 5s sendToClient.writeBytes(reverseSentence+'\n'); } } catch (Exception e) { e.printStackTrace(); } } public String reverse(String input) throws InterruptedException { String output=""; StringBuilder strBuilder= new StringBuilder(input); output=strBuilder.reverse().toString(); return output; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package anm_banvetau; import java.io.FileInputStream; import java.io.IOException; import java.net.ServerSocket; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author GREEN */ public class ANM_BanVeTau { /** * @param args the command line arguments */ public static String user = "sa"; public static String password = ""; public static String servername = "GREEN-PC"; public static Connection Connect(String servername,String user, String password) throws Exception { Connection con = null; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); con = DriverManager.getConnection("jdbc:sqlserver://" + servername + ";databaseName=QL_VeTau;user=" + user + ";password=" + password + ""); if(con != null) System.out.println("Connection Successful!"); return con; } int KT(Vector kt, String servername,String user, String password) throws SQLException, Exception { Connection con = Connect(servername,user, password); if (con != null) { PreparedStatement ps; String query; Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select TrangThai from HocSinh where TenDangNhap=" + "'" + kt.get(0) + "'" + " and MatKhau=" + "'" + kt.get(1) + "'" + ""); if(rs.getBoolean("TrangThai") == false){ query = ("update NGUOIDUNG set TrangThai=1 where Ten_DN= " + kt.get(0) + ""); ps = con.prepareStatement(query); //System.out.println("Đăng Nhập Thành Công!"); return 1; } //System.out.println("Đăng Nhập Thất Bại!"); } return 0; } void LayDS(DefaultTableModel mode, Vector rowData, String servername,String user, String password) throws SQLException, IOException, Exception { Connection con = Connect(servername,user, password); if (con != null) { Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select Ma_ChuyenTau,SL_Ve,KhoiHanh,GaDi,GaDen,SoVeDuocMua,SoVeConTrong from CHUYENTAU"); while (rs.next()) { int MaCT = rs.getInt("Ma_ChuyenTau"); int SLve = rs.getInt("SL_Ve"); String KhoiHanh = rs.getString("KhoiHanh"); String GaDi = rs.getString("GaDi"); String GaDen = rs.getString("GaDen"); int SoVeDuocMua = rs.getInt("SoVeDuocMua"); int SoVeTrong = rs.getInt("SoVeConTrong"); rowData = new Vector(); rowData.add(MaCT); rowData.add(SLve); rowData.add(KhoiHanh); rowData.add(GaDi); rowData.add(GaDen); rowData.add(SoVeDuocMua); rowData.add(SoVeTrong); mode.addRow(rowData); } con.close(); } } void JTable(Vector rowHeader, DefaultTableModel mode1, Vector rowData, JTable jtbDS, String servername,String user, String password) throws SQLException, IOException, Exception { Connection con = Connect(servername,user, password); if (con != null) { rowHeader = new Vector(); rowHeader.add("Mã CT"); rowHeader.add("SL Vé"); rowHeader.add("TG Chạy"); rowHeader.add("Ga Đi"); rowHeader.add("Ga Đến"); rowHeader.add("Số Vé Được Mua"); rowHeader.add("Số Vé Trống"); mode1 = new DefaultTableModel(rowHeader, 0); jtbDS.setModel(mode1); rowData = new Vector(); LayDS(mode1, rowData, servername,user, password); } con.close(); } String KT_Them(Vector ct, String servername,String user, String password) { String str = ""; if (ct.get(0).toString().compareTo("") == 0) { str = str + "\n" + "+Số lượng vé"; } if (ct.get(1).toString()== null) { str = str + "\n" + "+Thời gian chạy không được để trống"; } if (ct.get(2).toString()== null) { str = str + "\n" + "+Ga đi không được để trống"; } if (ct.get(3).toString()== null) { str = str + "\n" + "+Ga đến không được để trống"; } if (ct.get(4).toString()== null) { str = str + "\n" + "+Số vé được mua không được để trống"; } return str; } void Them(Vector rowData, FileInputStream fis, String servername,String user, String password) throws SQLException, Exception { Connection con = Connect(servername,user, password); if (con != null) { PreparedStatement ps; String query; query = "insert into CHUYENTAU(SL_Ve,KhoiHanh,GaDi,GaDen,SoVeDuocMua,SoVeConTrong) VALUES(?,?,?,?,?,?)"; ps = con.prepareStatement(query); ps.setString(1, rowData.get(0).toString()); ps.setString(2, rowData.get(1).toString()); ps.setString(3, rowData.get(2).toString()); ps.setString(4, rowData.get(3).toString()); ps.setString(5, rowData.get(4).toString()); ps.setString(6, rowData.get(5).toString()); ps.executeUpdate(); } con.close(); } public static void Server() { try { // String cau;// Cau tu client gui toi //String ketQua = "";// Cau sau khi xu ly xong tra ve client ServerSocket ss = new ServerSocket(9999);// Tao cong 9999 de server lang nghe System.out.println("Server: Đã khởi động máy chủ"); while (true)// Cho client ket noi { /* // Khong dung multithread Socket connectionSocket= ss.accept(); BufferedReader fromClient= new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));// Tao input stream DataOutputStream sendToClient= new DataOutputStream(connectionSocket.getOutputStream());// Tao output stream // Thread.sleep(5000);// Giả sử server phải xử lý mất 5s while (true) { cau = fromClient.readLine(); System.out.println("FROM CLIENT: "+cau);// In ra chuỗi server nhận đc từ client if (cau.equalsIgnoreCase("quit")) break; // Dao chuoi nhan duoc StringBuilder str = new StringBuilder(cau); ketQua = str.reverse().toString(); sendToClient.writeBytes(ketQua + '\n'); }*/ // Su dung multithread // Khi co 1 client gui yeu cau toi thi se tao ra 1 thread phuc vu client do new ThreadSocket(ss.accept()).start(); } } catch (IOException e) { System.out.println("Exception: " + e.getMessage()); } //catch (InterruptedException ie) { } } public static void main(String[] args){ // TODO code application logic here ANM_BanVeTau s = new ANM_BanVeTau(); //s.Server(); frmServer frm = new frmServer(); frm.setVisible(true); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package anm_banvetau; import java.io.FileInputStream; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author GREEN */ public class frmServer extends javax.swing.JFrame { /** * Creates new form frmServer */ ANM_BanVeTau con; static FileInputStream fis; DefaultTableModel mode1; static int len; Vector rowData; Vector rowHeader; static String servername = "GREEN-PC"; static String user = "sa"; static String password = ""; public frmServer() { con = new ANM_BanVeTau(); initComponents(); try { con.JTable(rowHeader, mode1, rowData, jtbDS, servername,user, password); } catch (Exception e) { // frmDangNhap frm = new frmDangNhap(this, true); // frm.setVisible(true); // servername = frm.getServerName(); // user = frm.getUser(); // password = frm.getPass(); try { con.JTable(rowHeader, mode1, rowData, jtbDS, servername,user, password); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Ko the ket noi toi CSDL!.", "Thong bao", JOptionPane.INFORMATION_MESSAGE); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jtbDS = new javax.swing.JTable(); jbtThoat = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jtfSLVe = new javax.swing.JTextField(); jtfTGChay = new javax.swing.JTextField(); jtfGaDi = new javax.swing.JTextField(); jtfGaDen = new javax.swing.JTextField(); jtfSOVeToiDa = new javax.swing.JTextField(); jbtThem = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("HỆ THỐNG BÁN VÉ TÀU"); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Server"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Danh sách chuyến tàu:")); jtbDS.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {}, {}, {}, {} }, new String [] { } )); jScrollPane1.setViewportView(jtbDS); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE) ); jbtThoat.setLabel("Thoát"); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Thông tin chuyến tàu:")); jLabel3.setText("Số lượng vé:"); jLabel4.setText("Thời gian chạy:"); jLabel5.setText("Ga đi:"); jLabel6.setText("Ga đến:"); jLabel7.setText("Số vé tối đa được mua:"); jbtThem.setLabel("Thêm chuyến tàu"); jbtThem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtThemActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jtfSLVe) .addComponent(jtfTGChay) .addComponent(jtfGaDi) .addComponent(jtfGaDen) .addComponent(jtfSOVeToiDa, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(67, Short.MAX_VALUE) .addComponent(jbtThem) .addGap(64, 64, 64)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jtfSLVe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jtfTGChay, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jtfGaDi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(jtfGaDen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(jtfSOVeToiDa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jbtThem) .addGap(20, 20, 20)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jbtThoat, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE) .addComponent(jbtThoat) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbtThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtThemActionPerformed // TODO add your handling code here: Vector ktct = new Vector(); //kths.add(jtfMaHS.getText()); ktct.add(jtfSLVe.getText()); ktct.add(jtfTGChay.getText()); ktct.add(jtfGaDi.getText()); ktct.add(jtfGaDen.getText()); ktct.add(jtfSOVeToiDa.getText()); con = new ANM_BanVeTau(); String kt = con.KT_Them(ktct, servername,user, password); System.out.print(kt); if (kt.compareTo("") == 0) { con = new ANM_BanVeTau(); Vector ct; ct = new Vector(); String SLve = jtfSLVe.getText(); ct.add(SLve); String TGchay = jtfTGChay.getText(); ct.add(TGchay); String Gadi = jtfGaDi.getText(); ct.add(Gadi); String Gaden = jtfGaDen.getText(); ct.add(Gaden); String SoVetoida = jtfSOVeToiDa.getText(); ct.add(SoVetoida); String SoVeTrong = jtfSLVe.getText(); ct.add(SoVeTrong); String str = con.KT_Them(ct, servername,user, password); try { con.Them(ct, fis, servername,user, password); JOptionPane.showMessageDialog(this, "Them Chuyen Tau thanh cong.", "Thong bao", JOptionPane.INFORMATION_MESSAGE); jtfSLVe.setText(""); jtfTGChay.setText(""); jtfGaDi.setText(""); jtfGaDen.setText(""); jtfSOVeToiDa.setText(""); //len = 0; } catch (Exception ex) { JOptionPane.showMessageDialog(this, "Ko the thuc hien!.", "Thong bao", JOptionPane.INFORMATION_MESSAGE); ex.printStackTrace(); } }else { JOptionPane.showMessageDialog(this, "Loi:\n" + kt, "Thong bao", JOptionPane.INFORMATION_MESSAGE); } }//GEN-LAST:event_jbtThemActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(frmServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmServer().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbtThem; private javax.swing.JButton jbtThoat; private javax.swing.JTable jtbDS; private javax.swing.JTextField jtfGaDen; private javax.swing.JTextField jtfGaDi; private javax.swing.JTextField jtfSLVe; private javax.swing.JTextField jtfSOVeToiDa; private javax.swing.JTextField jtfTGChay; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package client; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import java.net.UnknownHostException; /** * * @author GREEN */ public class Client { /** * @param args the command line arguments */ public static void Client() { try { String cau1;// Cau duoc gui toi server String ketQua;//Cau duoc server xu ly va tra lai la in hoa BufferedReader inFormUser= new BufferedReader(new InputStreamReader(System.in));// Tao input stream Socket clientSocket= new Socket("127.0.0.1",9999);// Tao clinent socket de ket noi toi server DataOutputStream sendToServer= new DataOutputStream(clientSocket.getOutputStream());// Tao output stream ket noi toi socket BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); while(true) { cau1 = inFormUser.readLine();// Nhap vao 1 cau sendToServer.writeBytes(cau1+'\n');// gui toi server if (cau1.equalsIgnoreCase("quit"))// Gap chuoi quit break; ketQua = inFromServer.readLine();// Nhan lai tu server System.out.println("FROM SERVER: "+ketQua); } clientSocket.close();//Dong ket noi } catch (IOException e) { System.out.println("Exception Client: "+e.getMessage()); } } public static void main(String[] args) { // TODO code application logic here Client c = new Client(); c.Client(); } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package helloworldmain; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.effect.DropShadow; import javafx.scene.effect.Reflection; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.StageStyle; /** * * @author L */ public class HelloWorldMain extends Application { /** * @param args the command line arguments */ public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { //primaryStage.setFullScreen(true); primaryStage.initStyle(StageStyle.UTILITY); primaryStage.setTitle("Chapter 1-7 Creating Menus"); Group root = new Group(); Scene scene = new Scene(root, 300, 250, Color.WHITE); MenuBar menuBar = new MenuBar(); // File menu - new, save, exit Menu menu = new Menu("File"); menu.getItems().add(new MenuItem("New")); menu.getItems().add(new MenuItem("Save")); menu.getItems().add(new SeparatorMenuItem()); menu.getItems().add(new MenuItem("Exit")); menuBar.getMenus().add(menu); // Cameras menu - camera 1, camera 2 Menu tools = new Menu("Cameras"); tools.getItems().add(CheckMenuItemBuilder.create().text("Show Camera 1").selected(true).build()); tools.getItems().add(CheckMenuItemBuilder.create().text("Show Camera 2").selected(true).build()); menuBar.getMenus().add(tools); // Alarm Menu alarm = new Menu("Alarm"); ToggleGroup tGroup = new ToggleGroup(); RadioMenuItem soundAlarmItem = RadioMenuItemBuilder.create().toggleGroup(tGroup).text("Sound Alarm").build(); RadioMenuItem stopAlarmItem = RadioMenuItemBuilder.create().toggleGroup(tGroup).text("Alarm Off").selected(true).build(); alarm.getItems().add(soundAlarmItem); alarm.getItems().add(stopAlarmItem); Menu contingencyPlans = new Menu("Contingent Plans"); contingencyPlans.getItems().add(new CheckMenuItem("Self Destruct in T minus 50")); contingencyPlans.getItems().add(new CheckMenuItem("Turn off the coffee machine ")); contingencyPlans.getItems().add(new CheckMenuItem("Run for your lives! ")); alarm.getItems().add(contingencyPlans); menuBar.getMenus().add(alarm); menuBar.prefWidthProperty().bind(primaryStage.widthProperty()); root.getChildren().add(menuBar); primaryStage.setScene(scene); primaryStage.show(); } }
Java
package edu.mit.csail.sls.wami.jsapi; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import edu.mit.csail.sls.wami.app.IApplicationController; import edu.mit.csail.sls.wami.app.IWamiApplication; import edu.mit.csail.sls.wami.audio.PlayServlet; import edu.mit.csail.sls.wami.log.EventPlayerException; import edu.mit.csail.sls.wami.log.IEventPlayer; import edu.mit.csail.sls.wami.log.WamiLogPlayerListener; import edu.mit.csail.sls.wami.recognition.IRecognitionResult; import edu.mit.csail.sls.wami.recognition.IRecognizer; import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException; import edu.mit.csail.sls.wami.recognition.lightweight.JSGFIncrementalAggregator; import edu.mit.csail.sls.wami.recognition.lightweight.JSGFIncrementalAggregatorListener; import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelCompilationException; import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelServerException; import edu.mit.csail.sls.wami.recognition.lm.exceptions.UnsupportedLanguageModelException; import edu.mit.csail.sls.wami.recognition.lm.jsgf.JsgfGrammar; import edu.mit.csail.sls.wami.relay.WamiRelay; import edu.mit.csail.sls.wami.util.XmlUtils; /** * This is an example implementation which allows all the logic for the * application to reside on the client. A JSGF Grammar can be updated via an * XMLHttpRequest. Recognition results are passed to the client in the form of * key-value pairs. * * Events can be logged in the following format: * * <reply type="logevents"> <event type="MyEvent" /> </reply> * * The event element can contain arbitrary XML (as long as you don't include * sub-elements called 'event'.) * * @author imcgraw * */ public class ClientControlledApplication implements IWamiApplication, JSGFIncrementalAggregatorListener { private JSGFIncrementalAggregator aggregator; private IApplicationController appController; private String splitTag = JSGFIncrementalAggregator.DEFAULT_SPLIT_TAG; private boolean sendIncrementalResults = true; private boolean sendAggregates = false; /** incremented each time a new final rec result is received */ private int utteranceId = 0; /** incremented each time a new aggregate is completed (isPartial=false) */ private int aggregateIndex = 0; /** incremented each time a new incremental result is proposed */ private int incrementalIndex = 0; /** * used to make sure we don't send the same exact message more than once in * a row **/ private String lastMessageSent = null; private IRecognitionResult currentRecResult = null; LinkedHashMap<String, String> currentAggregate = null; private boolean currentAggregateIsPartial = false; private IRecognizer recognizer; private IEventPlayer player; public static enum ErrorType { grammar_compilation, configuration, unknown_client_message, recording_not_found, not_implemented, synthesis_error, playback_error }; public void initialize(IApplicationController appController, HttpSession session, Map<String, String> paramMap) { this.appController = appController; WamiRelay wamiRelay = (WamiRelay) appController; recognizer = wamiRelay.getRecognizer(); configure(paramMap); } /** * Incoming recognition hypotheses are received in this method, both * "partial" results and "complete" results */ public void onRecognitionResult(IRecognitionResult result) { currentRecResult = result; if (sendIncrementalResults || !result.isIncremental()) { if (sendAggregates) { aggregator.update(result); } else { // Send the rec results directly Document recresult = getRecognitionResultDoc(result, false); sendMessage(recresult); } incrementalIndex++; } // Finally, increment the utterance ID and clear incremental/aggregate // indices if (!result.isIncremental()) { utteranceId++; incrementalIndex = 0; aggregateIndex = 0; } } /** * This method will be called by the JSGFIncrementalAggregator when there * are new commands to process */ public void processIncremental(LinkedHashMap<String, String> kvs, boolean isPartial) { currentAggregate = kvs; currentAggregateIsPartial = isPartial; Document doc = getRecognitionResultDoc(currentRecResult, isPartial); sendMessage(doc); if (!isPartial) { aggregateIndex++; } } public void sendMessage(Document doc) { String thisMessage = XmlUtils.toXMLString(doc); if (!thisMessage.equals(lastMessageSent)) { appController.sendMessage(doc); lastMessageSent = thisMessage; } } /** * Called when the "client" (i.e. the GUI in the web browser) sends a * message to the server. */ public void onClientMessage(Element xmlRoot) { String type = xmlRoot.getAttribute("type"); System.out.println("Got client message in ClientControlledApp..."); if (("playback").equals(type)) { handlePlayback(xmlRoot); } else if ("configure".equals(type)) { handleConfigure(xmlRoot); } else if ("speak".equals(type)) { handleSpeak(xmlRoot); } else if ("replay".equals(type)) { handleReplay(xmlRoot); } else if ("repoll".equals(type)) { handleRepoll(xmlRoot); } else if ("playrecording".equals(type)) { handlePlayRecording(xmlRoot); } else if ("playurl".equals(type)) { handlePlayURL(xmlRoot); } else if ("logevents".equals(type)) { // Nothing todo (logging is done in WamiRelay) } else if (("action").equals(type)) { // Nothing to do, actions just get logged. } else { sendError(ErrorType.unknown_client_message, "Unknown client update type: " + xmlRoot.getAttribute("type")); } } private void handlePlayback(Element xmlRoot) { String playbackSession = xmlRoot.getAttribute("playback_session"); player = appController.getLogPlayer(); player.addListener(new WamiLogPlayerListener(appController)); try { System.out.println("Playing back session: " + playbackSession); player.playSession(playbackSession); } catch (EventPlayerException e) { e.printStackTrace(); StringWriter w = new StringWriter(); e.printStackTrace(new PrintWriter(w)); sendError(ErrorType.playback_error, "Error during playback: " + w.toString()); } } protected boolean isPlayingBack() { return player != null; } private void handleRepoll(Element xmlRoot) { System.out.println("Repolling"); Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("reply"); root.setAttribute("type", "repoll"); root.setAttribute("timeout", xmlRoot.getAttribute("timeout")); doc.appendChild(root); appController.sendMessage(doc); } private void handlePlayURL(Element xmlRoot) { String urlstr = xmlRoot.getAttribute("url"); appController.play(PlayServlet.getWavFromURL(urlstr)); } protected void handleConfigure(Element xmlRoot) { List<Element> paramElems = extractElementList(xmlRoot, "param"); Map<String, String> params = new HashMap<String, String>(); for (Element e : paramElems) { String name = e.getAttribute("name"); String value = e.getAttribute("value"); params.put(name, value); } List<Element> jsgfElems = extractElementList(xmlRoot, "jsgfgrammar"); if (jsgfElems.size() > 1) { sendError(ErrorType.grammar_compilation, "Configuration cannot contain multiple jsgfgrammar elements."); } else if (jsgfElems.size() == 1) { boolean checkVocab = params.get("checkVocabulary") != null && Boolean.parseBoolean(params.get("checkVocabulary")); configureGrammarFromElement(jsgfElems.get(0), checkVocab); } configure(params); } protected void handleSpeak(Element xmlRoot) { NodeList list = xmlRoot.getElementsByTagName("synth_string"); if (list == null || list.getLength() == 0) { sendError(ErrorType.synthesis_error, "Cannot find string to speak!"); } else { Element e = (Element) list.item(0); appController.speak(e.getTextContent()); } } protected void handlePlayRecording(Element xmlRoot) { // You can implement an IAudioRetriever to handle the following: String wsessionid = xmlRoot.getAttribute("wsessionid"); int utt_id = Integer.parseInt(xmlRoot.getAttribute("uttid")); String fileName = "wami---" + wsessionid + "---" + utt_id; InputStream stream = appController.getRecording(fileName); if (stream == null) { sendError(ErrorType.recording_not_found, "The recording specified by wsessionid " + fileName + " was not found."); } else { appController.play(stream); } } protected void handleReplay(Element xmlRoot) { InputStream stream = appController.getLastRecordedAudio(); if (stream != null) { appController.play(stream); } } protected void configureGrammarFromElement(Element elem, boolean checkVocab) { String text = elem.getTextContent(); String language = elem.getAttribute("language"); if ("".equals(language) || language == null) { language = "en-us"; } JsgfGrammar jsgf = new JsgfGrammar(text, language); try { appController.setLanguageModel(jsgf); } catch (LanguageModelCompilationException e) { sendError(ErrorType.grammar_compilation, e.getMessage()); e.printStackTrace(); } catch (UnsupportedLanguageModelException e) { sendError(ErrorType.grammar_compilation, e.getMessage()); e.printStackTrace(); } catch (LanguageModelServerException e) { sendError(ErrorType.grammar_compilation, e.getMessage()); e.printStackTrace(); } } public void onRecognitionStarted() { } public void onFinishedPlayingAudio() { Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("reply"); root.setAttribute("type", "finishedplayingaudio"); doc.appendChild(root); appController.sendMessage(doc); } public void onClosed() { this.appController = null; } protected void configure(Map<String, String> paramMap) { System.out.println("Configuring with params: " + paramMap); if (paramMap.get("splitTag") != null) { String tag = paramMap.get("splitTag"); if (!tag.matches("[a-zA-Z0-9]+")) { sendError(ErrorType.configuration, "Split tag (" + tag + ") must be alphanumeric."); } else { splitTag = tag; } } if (paramMap.get("recordOnly") != null) { try { boolean recordOnly = false; // In case parse fails recordOnly = Boolean.parseBoolean(paramMap.get("recordOnly")); recognizer.setDynamicParameter("recordOnly", new Boolean( recordOnly).toString()); } catch (RecognizerException e) { e.printStackTrace(); sendError(ErrorType.configuration, e.getMessage()); } } if (paramMap.get("sendIncrementalResults") != null) { sendIncrementalResults = false; // In case parse fails sendIncrementalResults = Boolean.parseBoolean(paramMap .get("sendIncrementalResults")); try { recognizer.setDynamicParameter("incrementalResults", new Boolean(sendIncrementalResults).toString()); } catch (RecognizerException e) { e.printStackTrace(); sendError(ErrorType.configuration, e.getMessage()); } } if (paramMap.get("sendAggregates") != null) { sendAggregates = Boolean.parseBoolean(paramMap .get("sendAggregates")); } if (sendIncrementalResults) { aggregator = new JSGFIncrementalAggregator(this, splitTag); } } protected void sendError(ErrorType errorType, String message) { System.err.println("Sending ERROR: " + message); Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("reply"); root.setAttribute("type", "error"); root.setAttribute("error_type", errorType.toString()); root.setAttribute("message", message); doc.appendChild(root); appController.sendMessage(doc); } private List<Element> extractElementList(Element e, String name) { NodeList nodes = e.getElementsByTagName(name); List<Element> elements = new ArrayList<Element>(); for (int i = 0; i < nodes.getLength(); i++) { elements.add((Element) nodes.item(i)); } return elements; } protected Document getRecognitionResultDoc(IRecognitionResult result, boolean isPartial) { Document doc = XmlUtils.newXMLDocument(); Element root = createRecognitionResultElement(doc, result, utteranceId, incrementalIndex); for (int i = 0; i < result.getHyps().size(); i++) { Element hyp = createHypElement(doc, result, i); root.appendChild(hyp); } doc.appendChild(root); return doc; } private Element createHypElement(Document doc, IRecognitionResult result, int hypIndex) { if (!sendAggregates) { // Send a simple hypothesis without aggregates System.out.println("Creating hyp without aggregate."); return createBasicHypElement(doc, result, hypIndex); } else { int startIndex; List<LinkedHashMap<String, String>> aggregates; if (hypIndex == 0) { // For the first hypothesis, send only single aggregates aggregates = new ArrayList<LinkedHashMap<String, String>>(); aggregates.add(currentAggregate); startIndex = aggregateIndex; } else { // For other hypothesis, or if sendAggregates is false // Extract all the kvs from the hypothesis startIndex = 0; aggregates = JSGFIncrementalAggregator.extractCommandSets( result.getHyps().get(hypIndex), splitTag, false, false, false); } // Create a hypothesis with one or more aggregates return createHypElement(doc, result, hypIndex, aggregates, startIndex, currentAggregateIsPartial); } } private static Element createRecognitionResultElement(Document doc, IRecognitionResult result, int utteranceId, int incrementalIndex) { Element e = doc.createElement("reply"); e.setAttribute("type", "recresult"); e.setAttribute("incremental", Boolean.toString(result.isIncremental())); e.setAttribute("utt_id", Integer.toString(utteranceId)); e.setAttribute("incremental_index", Integer.toString(incrementalIndex)); return e; } private static Element createBasicHypElement(Document doc, IRecognitionResult result, int index) { String txtstr = result.getHyps().get(index); Element hyp = doc.createElement("hyp"); Element text = doc.createElement("text"); text.setTextContent(txtstr); hyp.setAttribute("index", Integer.toString(index)); hyp.appendChild(text); return hyp; } private static Element createHypElement(Document doc, IRecognitionResult result, int index, List<LinkedHashMap<String, String>> aggregates, int aggregateStartIndex, boolean lastAggregateIsPartial) { Element hyp = createBasicHypElement(doc, result, index); for (int i = 0; i < aggregates.size(); i++) { Map<String, String> aggregate = aggregates.get(i); Element e = doc.createElement("aggregate"); boolean isLastAggregate = (i == aggregates.size() - 1); boolean isPartial = isLastAggregate && lastAggregateIsPartial; int aggregateIndex = aggregateStartIndex + i; e.setAttribute("index", Integer.toString(aggregateIndex)); e.setAttribute("partial", Boolean.toString(isPartial)); for (String key : aggregate.keySet()) { Element kv = doc.createElement("kv"); kv.setAttribute("key", key); kv.setAttribute("value", aggregate.get(key)); e.appendChild(kv); } hyp.appendChild(e); } return hyp; } }
Java
package edu.mit.csail.sls.wami.jsapi; import java.io.CharArrayWriter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import edu.mit.csail.sls.wami.WamiConfig; public class WamiCrossSiteGetFilter implements Filter { class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; @Override public String toString() { return output.toString(); } public CharResponseWrapper(HttpServletResponse response) { super(response); output = new CharArrayWriter(); } @Override public PrintWriter getWriter() { return new PrintWriter(output); } } @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("get".equals(request.getParameter("jsxss"))) { // System.out.println("XXS GET: " + // WamiConfig.reconstructRequestURLandParams(request)); CharResponseWrapper wrapper = new CharResponseWrapper( (HttpServletResponse) res); chain.doFilter(req, wrapper); doResponseModifiction(request, response, wrapper); } else { chain.doFilter(req, res); } } private void doResponseModifiction(HttpServletRequest request, HttpServletResponse response, HttpServletResponse wrapper) throws IOException { PrintWriter out = response.getWriter(); String message = wrapper.toString(); // note, you must set content type before getting the writer response.setContentType("text/javascript; charset=UTF-8"); message = message.replace("\\", "\\\\").replace("'", "\\'"); String callback = request.getParameter("callback"); String command = callback + "('" + message + "');"; System.out.println("Script: " + command); out.print(command); response.setContentLength(command.length()); out.close(); } @Override public void init(FilterConfig config) throws ServletException { } }
Java
package edu.mit.csail.sls.wami.jsapi; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.w3c.dom.Document; import org.w3c.dom.Element; import edu.mit.csail.sls.wami.WamiServlet; import edu.mit.csail.sls.wami.relay.WamiRelay; import edu.mit.csail.sls.wami.util.XmlUtils; public class WamiCrossSitePostFilter implements Filter { public static final String JAVASCRIPT_POST_ID = "WAMI_JAVASCRIPT_POST_ID_ATTRIBUTE_NAME"; String desiredEncoding = "UTF-8"; String defaultEncoding = "ISO8859_1"; class CustomRequestWrapper extends HttpServletRequestWrapper { private CustomServerInputStream in; public CustomRequestWrapper(HttpServletRequest request, String str) throws IOException { super(request); in = new CustomServerInputStream(str); } @Override public ServletInputStream getInputStream() throws IOException { return in; } @Override public String getCharacterEncoding() { return desiredEncoding; } @Override public BufferedReader getReader() throws IOException { final String enc = getCharacterEncoding(); final InputStream istream = getInputStream(); final Reader r = new InputStreamReader(istream, enc); return new BufferedReader(r); } } class CustomServerInputStream extends ServletInputStream { private InputStream in; public CustomServerInputStream(String str) throws IOException { super(); in = new ByteArrayInputStream(str.getBytes(desiredEncoding)); } @Override public int read() throws IOException { return in.read(); } @Override public void close() throws IOException { in.close(); } } @Override public void destroy() { } public void printToFile(String str) { try { FileOutputStream fos = new FileOutputStream("/scratch/test.html"); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos, "UTF8")); out.write(str); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("post".equals(request.getParameter("jsxss"))) { HttpServletRequest wrapper = doRequestModification(request, response); if (wrapper == null) { response.sendRedirect("about:blank"); return; } chain.doFilter(wrapper, res); sendMessageProcessedConfirmation(request); } else { chain.doFilter(req, res); } } private HttpServletRequest doRequestModification( HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String lastJavascriptPostID = (String) session .getAttribute(JAVASCRIPT_POST_ID); String postID = request.getParameter("postID"); // System.out.println("XSS POST: " // + WamiConfig.reconstructRequestURLandParams(request)); // System.out.println("POST ID: " + postID); if (postID.equals(lastJavascriptPostID)) { // Ignore posting to duplicate form (happens on refresh) // This is the "Post Redirect Get" pattern if you want to Google // it. This solves the FF3 refresh bug. But not the back bug. return null; } session.setAttribute(JAVASCRIPT_POST_ID, postID); if (request.getParameter("wamiMessage") != null) { // This is a hack: // http://globalizer.wordpress.com/category/web-applications/ // All the fixes I've tried have failed. String message; try { String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = defaultEncoding; } System.out.println("Converting from: " + encoding + " to " + desiredEncoding); message = new String(request.getParameter("wamiMessage") .getBytes(encoding), desiredEncoding); //printToFile(message); request = new CustomRequestWrapper(request, message); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return request; } private void sendMessageProcessedConfirmation(HttpServletRequest request) { Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("reply"); root.setAttribute("type", "update_processed"); root.setAttribute("postID", request.getParameter("postID")); doc.appendChild(root); WamiRelay relay = WamiServlet.getRelay(request); relay.sendMessage(doc); } @Override public void init(FilterConfig config) throws ServletException { } }
Java
package edu.mit.csail.sls.wami.jsapi; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.w3c.dom.Document; import org.w3c.dom.Element; import edu.mit.csail.sls.wami.WamiConfig; import edu.mit.csail.sls.wami.util.Parameter; import edu.mit.csail.sls.wami.util.ServletUtils; import edu.mit.csail.sls.wami.util.XmlUtils; /** * This is not standard, but hopefully it will make it easier to distribute * WAMI. This servlet proxies resources which would normally be found under * WebContent from locations that would be otherwise inaccessible via a URL. * * The audio applet, for instance, is proxied from * /WEB-INF/lib/wami_audio_applet.jar. The javascript necessary for the JSAPI is * also accessible through this servlet. * * @author imcgraw * */ public class WamiContentProxy extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; char-set:UTF-8"); String requestURL = request.getRequestURL().toString(); String resource = requestURL.substring(requestURL.indexOf(request .getContextPath()) + request.getContextPath().length()); resource = resource.replace("//", "/"); // Replace any oddities try { if (Parameter.get(request, "debug", false)) { response.setContentType("text/html"); response.getWriter().write( "The requested resource is: " + resource); } else { InputStream stream = getRequestedResource(request, resource); if (stream == null) { throw new RuntimeException( "Could not find requested resource: " + resource); } ServletUtils.sendStream(stream, response.getOutputStream()); } } catch (IOException e) { e.printStackTrace(); } } protected InputStream getRequestedResource(HttpServletRequest request, String resource) { if ("/wami.js".equals(resource)) { return new ByteArrayInputStream(handleWamiJSAPIRequest(request) .getBytes()); } else if ("/content/wami_audio_applet.jar".equals(resource)) { return WamiConfig.getResourceAsStream(request.getSession() .getServletContext(), "/WEB-INF/lib/wami_audio_applet.jar"); } else if ("/wami.xml".equals(resource) || "/content/wami.xml".equals(resource)) { return new ByteArrayInputStream(getUrls(request).getBytes()); } else if (resource.startsWith("/content")) { String result = ""; if (resource.endsWith(".js")) { result += getUtils(request); } resource = resource.replaceFirst("/content/", ""); result += getContentResourceAsString(resource); return new ByteArrayInputStream(result.getBytes()); } return null; } private String getUrls(HttpServletRequest request) { WamiConfig wc = WamiConfig.getConfiguration(request.getSession() .getServletContext()); Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("root"); doc.appendChild(root); String wsessionid = createWamiSessionID(request); Element recordE = doc.createElement("record"); recordE.setAttribute("url", wc.recordServletURL(request, wsessionid)); root.appendChild(recordE); Element playE = doc.createElement("play"); playE.setAttribute("url", wc.audioServletURL(request, wsessionid)); root.appendChild(playE); Element controlE = doc.createElement("control"); controlE.setAttribute("url", wc.controlServletURL(request, wsessionid)); root.appendChild(controlE); return XmlUtils.toXMLString(doc); } public String getContentResourceAsString(String resource) { return "\n" + ServletUtils.convertStreamToString(WamiContentProxy.class .getClassLoader().getResourceAsStream( "edu/mit/csail/sls/wami/content/" + resource)) + "\n"; } public String createWamiSessionID(HttpServletRequest request) { return ServletUtils.getClientAddress(request) + ":" + System.currentTimeMillis(); } public String handleWamiJSAPIRequest(HttpServletRequest request) { HttpSession session = request.getSession(); Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = request.getHeader(name); System.out.println("HEADER: " + name + " " + value); } // no browser test session.setAttribute("passedBrowserTest", new Boolean(true)); String jsapi = ""; String wsessionid = createWamiSessionID(request); String serveraddress = WamiConfig .reconstructRequestURLandParams(request); request.getSession().setAttribute("serverAddress", serveraddress); try { jsapi += getJSAPI(request, wsessionid); } catch (IOException e) { jsapi += getAlert("Error setting up WAMI javascript."); } return jsapi; } protected String getJSAPI(HttpServletRequest request, String wsessionid) throws IOException { String result = getUtils(request); result += getConfigurationJSON(request, wsessionid); result += getContentResourceAsString("app.js"); return result; } protected String getUtils(HttpServletRequest request) { String baseURL = WamiConfig.getBaseURL(request); String result = ""; result += getContentResourceAsString("utils.js"); result += "\n\n"; result += "Wami.getBaseURL = function () { return '" + baseURL + "'}"; result += "\n\n"; return result; } protected String getAlert(String message) { return "alert('" + message + "');\n\n"; } private Map<String, String> getAppletParams(HttpServletRequest request, String wsessionid) { HttpSession session = request.getSession(); WamiConfig wc = WamiConfig.getConfiguration(getServletContext()); String baseUrl = WamiConfig.getBaseURL(request); String allowStopPlayingStr = request.getParameter("allowStopPlaying"); boolean allowStopPlaying = allowStopPlayingStr == null || "true".equalsIgnoreCase(allowStopPlayingStr); // todo: this should be done via WamiConfig, but I think it returns // relative paths String appletArchives = baseUrl + "/content/wami_audio_applet.jar"; Map<String, String> params = new HashMap<String, String>(); params.put("CODE", wc.getAudioAppletClass(request)); params.put("ARCHIVE", appletArchives); params.put("NAME", "AudioApplet"); params.put("type", "application/x-java-applet;version=1.5"); params.put("scriptable", "true"); params.put("mayscript", "true"); params.put("location", (String) session .getAttribute("hubLocationString")); params.put("vision", "false"); params.put("layout", "stacked"); params.put("httpOnly", "true"); params.put("recordUrl", wc.recordServletURL(request, wsessionid)); params.put("recordAudioFormat", wc.getRecordAudioFormat()); params.put("recordSampleRate", Integer.toString(wc .getRecordSampleRate())); params.put("recordIsLittleEndian", Boolean.toString(wc .getRecordIsLittleEndian())); params.put("greenOnEnableInput", Boolean.toString(wc .getGreenOnEnableInput(request))); params.put("allowStopPlaying", Boolean.toString(allowStopPlaying)); params.put("hideButton", Boolean.toString(wc .getHideAudioButton(request))); params.put("playRecordTone", Boolean.toString(wc .getPlayRecordTone(request))); params.put("useSpeechDetector", Boolean.toString(wc .getUseSpeechDetector(request))); params.put("playUrl", wc.audioServletURL(request, wsessionid)); return params; } private String getConfigurationJSON(HttpServletRequest request, String wsessionid) throws IOException { WamiConfig wc = WamiConfig.getConfiguration(getServletContext()); String result = "var _wamiParams = {\n"; result += "\t\"wsessionid\":\"" + wsessionid + "\",\n"; result += "\t\"controlUrl\":\"" + wc.controlServletURL(request, wsessionid) + "\",\n"; result += "\t\"playUrl\":\"" + wc.audioServletURL(request, wsessionid) + "\",\n"; result += "\t\"recordUrl\":\"" + wc.recordServletURL(request, wsessionid) + "\",\n"; result += getAppletJSON(request, wsessionid); result += "}\n\n"; // System.out.println("JSON FOR CONFIGURATION: \n" + result); return result; } private String getAppletJSON(HttpServletRequest request, String wsessionid) { WamiConfig wc = WamiConfig.getConfiguration(getServletContext()); Map<String, String> appletParams = getAppletParams(request, wsessionid); String result = ""; // TODO: add back in playurl and recordurl for iphone result += "\t\"applet\" : {\n"; result += "\t\t\"code\" : \"" + appletParams.get("CODE") + "\",\n"; result += "\t\t\"archive\" : \"" + appletParams.get("ARCHIVE") + "\",\n"; result += "\t\t\"name\" : \"" + appletParams.get("NAME") + "\",\n"; result += "\t\t\"width\" : \"" + Integer.toString(wc.getAppletWidth(request)) + "\",\n"; result += "\t\t\"height\" : \"" + Integer.toString(wc.getAppletHeight(request)) + "\",\n"; result += "\t\t\"params\" : "; result += getParamsJSON(appletParams); result += "\t}\n"; return result; } private String getParamsJSON(Map<String, String> params) { String result = "[\n"; Object[] paramNames = params.keySet().toArray(); for (int i = 0; i < paramNames.length; i++) { String name = (String) paramNames[i]; String value = params.get(name); result += "\t\t\t{ \"name\" : \"" + name + "\" , \"value\" : \"" + value + "\" }"; if (i < paramNames.length - 1) { result += ",\n"; } } return result += "]\n"; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; import java.util.Date; @SuppressWarnings("serial") public class ReachedCapacityException extends InitializationException { Date nextAvailable = null; public ReachedCapacityException(Date nextAvailable) { super(); this.nextAvailable = nextAvailable; } public ReachedCapacityException(String message, Date nextAvailable) { super(message); this.nextAvailable = nextAvailable; } public ReachedCapacityException(Throwable cause) { super(cause); } public ReachedCapacityException(String message, Throwable cause) { super(message, cause); } public Date getNextAvailableTime() { return nextAvailable; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import org.apache.commons.io.input.TeeInputStream; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import edu.mit.csail.sls.wami.WamiConfig; import edu.mit.csail.sls.wami.app.IApplicationController; import edu.mit.csail.sls.wami.app.IWamiApplication; import edu.mit.csail.sls.wami.audio.IAudioRetriever; import edu.mit.csail.sls.wami.log.EventLoggerException; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.IEventPlayer; import edu.mit.csail.sls.wami.log.ILoggable; import edu.mit.csail.sls.wami.recognition.IRecognitionListener; import edu.mit.csail.sls.wami.recognition.IRecognitionResult; import edu.mit.csail.sls.wami.recognition.IRecognizer; import edu.mit.csail.sls.wami.recognition.RecognitionStartedLogEvent; import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException; import edu.mit.csail.sls.wami.recognition.lm.LanguageModel; import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelCompilationException; import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelServerException; import edu.mit.csail.sls.wami.recognition.lm.exceptions.UnsupportedLanguageModelException; import edu.mit.csail.sls.wami.synthesis.ISynthesizer; import edu.mit.csail.sls.wami.synthesis.SpeakLogEvent; import edu.mit.csail.sls.wami.synthesis.SynthesizerException; import edu.mit.csail.sls.wami.util.AudioUtils; import edu.mit.csail.sls.wami.util.ServletUtils; import edu.mit.csail.sls.wami.util.XmlUtils; public class WamiRelay implements IApplicationController { private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>(); private WamiConfig wc = null; private long pollTimeout = -1; private long timeLastMessageSent = System.currentTimeMillis(); private long timeLastPollEnded = System.currentTimeMillis(); private boolean isCurrentlyPolling = false; private ISynthesizer synthesizer; private IRecognizer recognizer; private IEventPlayer logplayer; private IWamiApplication wamiApp; protected IEventLogger eventLogger; private IAudioRetriever audioRetriever = null; private byte[] lastAudioBytes = null; AudioFormat lastAudioFormat = null; private Object lastAudioLock = new Object(); private ServletContext sc; private HttpSession session; private String wsessionid; public void initialize(HttpServletRequest request, String wsessionid) throws InitializationException { this.wsessionid = wsessionid; // Must be first! session = request.getSession(); this.sc = request.getSession().getServletContext(); wc = WamiConfig.getConfiguration(session.getServletContext()); pollTimeout = wc.getPollTimeout(); eventLogger = createEventLogger(request); logEvent(new RequestHeadersLogEvent(request), System .currentTimeMillis()); synthesizer = wc.createSynthesizer(this); try { recognizer = wc.createRecognizer(request.getSession() .getServletContext(), this); } catch (RecognizerException e) { System.err.println("There was an error creating the recognizer"); InitializationException ie = new InitializationException(e); ie.setRelay(this); throw ie; } audioRetriever = wc.createAudioRetriever(sc); // If you specified a log player, you might want to start it in the app. logplayer = wc.createLogPlayer(request); // This will be null if there is no application set in the config file. wamiApp = wc.createWamiApplication(this, session); } private IEventLogger createEventLogger(HttpServletRequest request) throws InitializationException { IEventLogger logger; try { logger = wc.createEventLogger(request.getSession() .getServletContext()); if (logger != null) { addEventLoggerListeners(); final String serverAddress = (String) request.getSession() .getAttribute("serverAddress"); String clientAddress = ServletUtils.getClientAddress(request); long timestamp = System.currentTimeMillis(); final String recDomain = (String) session .getAttribute("recDomain"); logger.createSession(serverAddress, clientAddress, wsessionid, timestamp, recDomain); } } catch (EventLoggerException e) { System.err.println("There was an error creating the logger"); throw new InitializationException(e); } return logger; } protected void addEventLoggerListeners() { // Add logger listener in subclass } /** * Wait for a message to be sent from server to client via sendMessage(). * Will block indefinitely if pollTimeout=0 (set via config.xml), or it will * wait only as long as pollTimeout() and return null if nothing found */ public String waitForMessage() throws InterruptedException { try { isCurrentlyPolling = true; System.out.println("Waiting for message: " + pollTimeout); return (pollTimeout > 0) ? messageQueue.poll(pollTimeout, TimeUnit.MILLISECONDS) : messageQueue.take(); } finally { isCurrentlyPolling = false; timeLastPollEnded = System.currentTimeMillis(); } } public void sendMessage(Document xmlMessage) { sendMessage(XmlUtils.toXMLString(xmlMessage)); } public void sendMessage(String message) { try { System.out.println("Sending message: " + message); long timestampMillis = System.currentTimeMillis(); timeLastMessageSent = timestampMillis; logEvent(new SentMessageLogEvent(message), timestampMillis); messageQueue.put(message); } catch (InterruptedException e) { // LinkedBlockingQueues are not bounded, so this shouldn't occur e.printStackTrace(); } } public long getTimeLastMessageSent() { return timeLastMessageSent; } public long getPolltimeout() { return pollTimeout; } /** * If the client is still polling, return 0. Otherwise, return the number of * milliseconds since the previous poll by the client ended */ public long getTimeSinceLastPollEnded() { return isCurrentlyPolling ? 0 : (System.currentTimeMillis() - timeLastPollEnded); } /** * Default timeout functionality: send a message to the client informing it * of the timeout. */ public void timeout() { Document document = XmlUtils.newXMLDocument(); Element root = document.createElement("reply"); root.setAttribute("type", "timeout"); document.appendChild(root); sendMessage(XmlUtils.toXMLString(document)); } private class AudioElement { public InputStream stream; public AudioElement(InputStream stream) { this.stream = stream; } } BlockingQueue<AudioElement> audioQueue = new LinkedBlockingQueue<AudioElement>(); public boolean playedAudio = false; /** * Returns an input stream for audio. The stream should have * header-information already encoded in it. */ public InputStream waitForAudio(int timeInSeconds) throws InterruptedException { if (playedAudio && wamiApp != null) { // Not the first time waiting... // this means that we just finished playing. onFinishedPlayingAudio(); playedAudio = false; } System.out.println("Waiting for audio for " + timeInSeconds + " seconds."); AudioElement e = audioQueue.poll(timeInSeconds, TimeUnit.SECONDS); InputStream ais = null; if (e != null) { ais = e.stream; playedAudio = true; } return ais; } public String getWamiSessionID() { return wsessionid; } protected void onFinishedPlayingAudio() { if (wamiApp != null) { wamiApp.onFinishedPlayingAudio(); } } public void speak(String ttsString) { // TODO: error checking for null synthesizer try { logEvent(new SpeakLogEvent(ttsString), System.currentTimeMillis()); System.out.println("First Synthesizing."); InputStream stream = synthesizer.synthesize(ttsString); System.out.println("Attempting to play stream: " + stream); play(stream); } catch (SynthesizerException e) { e.printStackTrace(); } } public void play(InputStream audio) { if (audio == null) { System.out.println("WARNING: Attempted to play NULL audio"); return; } try { audioQueue.put(new AudioElement(audio)); } catch (InterruptedException e) { e.printStackTrace(); } } /** * This delegates recognition to the {@link IRecognizer} associated with * this relay, providing the appropriate callbacks * * @param audioIn * The audio input stream to recognizer * @throws RecognizerException * On recognition error * @throws IOException * on error reading from the audioIn stream */ public void recognize(AudioInputStream audioIn) throws RecognizerException, IOException { final ByteArrayOutputStream audioByteStream = new ByteArrayOutputStream(); final AudioFormat audioFormat = audioIn.getFormat(); TeeInputStream tee = new TeeInputStream(audioIn, audioByteStream, true); AudioInputStream forkedStream = new AudioInputStream(tee, audioIn .getFormat(), AudioSystem.NOT_SPECIFIED); if (recognizer == null) { throw new RecognizerException("No recognizer specified!"); } else if (wamiApp == null) { throw new RecognizerException("No wami app specified!"); } recognizer.recognize(forkedStream, new IRecognitionListener() { private long startedTimestamp; public void onRecognitionResult(final IRecognitionResult result) { // if the result is final, then before we delegate it // we switch over our audio stream so that // getLastRecordedAudio() works properly inside of // on RecognitionResult long timestampMillis = System.currentTimeMillis(); if (!result.isIncremental()) { try { audioByteStream.close(); } catch (IOException e) { e.printStackTrace(); // shouldn't occur } synchronized (lastAudioLock) { lastAudioBytes = audioByteStream.toByteArray(); lastAudioFormat = audioFormat; } } wamiApp.onRecognitionResult(result); logEvent(result, timestampMillis); if (!result.isIncremental()) { logUtterance(audioByteStream.toByteArray(), audioFormat, startedTimestamp); } } public void onRecognitionStarted() { startedTimestamp = System.currentTimeMillis(); logEvent(new RecognitionStartedLogEvent(), startedTimestamp); wamiApp.onRecognitionStarted(); } }); } public void setLanguageModel(LanguageModel lm) throws LanguageModelCompilationException, UnsupportedLanguageModelException, LanguageModelServerException { if (recognizer == null) { throw new LanguageModelServerException( "no recognizer to compile language models!"); } try { recognizer.setLanguageModel(lm); } catch (RecognizerException e) { if (e instanceof UnsupportedLanguageModelException) { throw (UnsupportedLanguageModelException) e; } else if (e instanceof LanguageModelServerException) { throw (LanguageModelServerException) e; } else if (e instanceof LanguageModelCompilationException) { throw (LanguageModelCompilationException) e; } else { throw new LanguageModelServerException(e); } } } public void handleClientUpdate(HttpSession session, String xmlUpdate) { Document doc = XmlUtils.toXMLDocument(xmlUpdate); Element root = (Element) doc.getFirstChild(); logClientEvent(xmlUpdate, root); String type = root.getAttribute("type"); if ("hotswap".equals(type)) { hotswapComponent(WamiConfig.getConfiguration(session .getServletContext()), root); } else if (wamiApp != null) { wamiApp.onClientMessage(root); } else { System.err .println("warming: handleClientUpdate called with null wami app"); } } private void hotswapComponent(WamiConfig config, Element el) { String component = el.getAttribute("component"); String className = el.getAttribute("class"); if ("recognizer".equals(component)) { hotswapRecognizer(config, className, el); } else if ("synthesizer".equals(component)) { hotswapSynthesizer(config, className, el); } else if ("wamiapp".equals(component)) { hotswapWamiApplication(config, className, el); } } private void hotswapWamiApplication(WamiConfig config, String className, Element el) { this.wamiApp = config.createWamiApplication(this, session, className, WamiConfig.getParameters(el)); } private void hotswapSynthesizer(WamiConfig config, String className, Element el) { ISynthesizer synthesizer = config.createSynthesizer(this, className, WamiConfig.getParameters(el)); setSynthesizer(synthesizer); } private void hotswapRecognizer(WamiConfig config, String className, Element el) { try { IRecognizer recognizer = config.createRecognizer(sc, this, className, WamiConfig.getParameters(el)); setRecognizer(recognizer); } catch (RecognizerException e) { sendErrorMessage("Hot Swap Error", "Encountered error swapping to the specified recognizer.", ServletUtils.getStackTrace(e)); } } private void sendErrorMessage(String type, String message, String details) { Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("reply"); root.setAttribute("type", "error"); root.setAttribute("error_type", type); root.setAttribute("message", message); root.setAttribute("details", details); doc.appendChild(root); sendMessage(doc); } private void logClientEvent(String xmlUpdate, Element root) { String type = root.getAttribute("type"); if ("logevents".equals(type)) { NodeList eventNodes = root.getElementsByTagName("event"); System.out.println("unpacking events"); for (int i = 0; i < eventNodes.getLength(); i++) { Element event = (Element) eventNodes.item(i); long timeInMillis = System.currentTimeMillis(); logEvent(new ClientMessageLogEvent(event), timeInMillis); } } else { System.out.println("logging client event"); long timestampMillis = System.currentTimeMillis(); logEvent(new ClientMessageLogEvent(xmlUpdate), timestampMillis); } } public synchronized void close() { // Run this on a separate thread to avoid delays/errors (new Thread(new Runnable() { @Override public void run() { WamiRelay.this.stopPolling(); // The poison pill WamiRelay.this.audioQueue.add(new AudioElement(null)); sc.log("ClosingRelay: " + wsessionid); if (wamiApp != null) { wamiApp.onClosed(); wamiApp = null; } if (recognizer != null) { try { sc.log("DestroyingRecognizer"); recognizer.destroy(); recognizer = null; } catch (RecognizerException e) { e.printStackTrace(); } } if (synthesizer != null) { try { sc.log("DestroyingSynthesizer"); synthesizer.destroy(); synthesizer = null; } catch (SynthesizerException e) { e.printStackTrace(); } } if (eventLogger != null) { try { sc.log("DestroyingEventLogger"); eventLogger.close(); eventLogger = null; } catch (EventLoggerException e) { e.printStackTrace(); } } // Sometimes the session is already invalid // Not sure how to check, so run in new thread. WamiRelay.this.session.setAttribute("relay", null); sc.log("DoneClosingRelay: " + wsessionid); } })).start(); } public void stopPolling() { this.sendMessage("<reply type='stop_polling' />"); } public void logEvent(final ILoggable logEvent, final long timestampMillis) { if (eventLogger != null) { try { eventLogger.logEvent(logEvent, timestampMillis); } catch (EventLoggerException e) { e.printStackTrace(); } } } public IWamiApplication getWamiApplication() { return wamiApp; } public IRecognizer getRecognizer() { return recognizer; } public void setRecognizer(IRecognizer rec) { recognizer = rec; } private void setSynthesizer(ISynthesizer synth) { this.synthesizer = synth; } /** * returns the synthesizer in use (may be null) */ public ISynthesizer getSynthesizer() { return synthesizer; } public InputStream getLastRecordedAudio() { synchronized (lastAudioLock) { AudioInputStream audioIn = AudioUtils.createAudioInputStream( lastAudioBytes, lastAudioFormat); try { return AudioUtils.createInputStreamWithWaveHeader(audioIn); } catch (IOException e) { e.printStackTrace(); return null; } } } private void logUtterance(final byte[] bytes, final AudioFormat audioFormat, final long audioTimestampMillis) { if (eventLogger != null) { try { eventLogger.logUtterance(AudioUtils.createAudioInputStream( bytes, audioFormat), audioTimestampMillis); } catch (EventLoggerException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } public IEventPlayer getLogPlayer() { return logplayer; } public WamiConfig getWamiConfig() { return wc; } public void sendReadyMessage() { Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("reply"); root.setAttribute("type", "wami_ready"); doc.appendChild(root); sendMessage(doc); } @Override public InputStream getRecording(String fileName) { if (audioRetriever == null) { throw new RuntimeException( "If you are going to try to retrieve recorded utts, you must specify a valid IAudioRetriever in the config.xml file."); } return audioRetriever.retrieveAudio(fileName); } @Override public void setEventLogger(IEventLogger logger) { this.eventLogger = logger; } public void forceRepoll() { try { long timestampMillis = System.currentTimeMillis(); String message = "<reply />"; logEvent(new SentMessageLogEvent(message), timestampMillis); messageQueue.put(message); } catch (InterruptedException e) { // LinkedBlockingQueues are not bounded, so this shouldn't occur e.printStackTrace(); } } }
Java
package edu.mit.csail.sls.wami.relay; import java.util.Enumeration; import java.util.LinkedHashMap; import javax.servlet.http.HttpServletRequest; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.ILoggable; import edu.mit.csail.sls.wami.util.XmlUtils; /** * logs the headers of a http request header */ public class RequestHeadersLogEvent implements ILoggable { private LinkedHashMap<String, String> headers = new LinkedHashMap<String, String>(); /** required empty constructor */ public RequestHeadersLogEvent() { } /** * Takes a request and logs all the headers * * @param request * @param headers */ public RequestHeadersLogEvent(HttpServletRequest request) { Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = request.getHeader(name); headers.put(name, value); } } public void fromLogEvent(String logStr, String eventType) { Document xmlDoc = XmlUtils.toXMLDocument(logStr); NodeList headerNodes = xmlDoc.getElementsByTagName("header"); for (int i = 0; i < headerNodes.getLength(); i++) { Element header = (Element) headerNodes.item(i); String name = header.getAttribute("name"); String value = header.getAttribute("value"); headers.put(name, value); } } public String getEventType() { return IEventLogger.RequestHeaders; } public String toLogEvent() { Document xmlDoc = XmlUtils.newXMLDocument(); Element root = xmlDoc.createElement("headers"); xmlDoc.appendChild(root); for (String name : headers.keySet()) { Element node = xmlDoc.createElement("header"); node.setAttribute("name", name); node.setAttribute("value", headers.get(name)); root.appendChild(node); } return XmlUtils.toXMLString(xmlDoc); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; import java.util.Map; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.ILoggable; import edu.mit.csail.sls.wami.util.WamiXmlRpcUtils; /** * For logging the creation of instantiatableT items from the config.xml * * @author alexgru * */ public class InstantiationEvent implements ILoggable { private String componentType; private String className; private Map<String, String> params; public String getComponentType() { return componentType; } public String getClassName() { return className; } public Map<String, String> getParams() { return params; } public InstantiationEvent(String componentType, String className, Map<String, String> params) { this.componentType = componentType; this.className = className; this.params = params; } /** * Empty constructor for reflection */ public InstantiationEvent() { } public String getEventType() { return IEventLogger.Instantiation; } public void fromLogEvent(String logStr, String eventType) { Object[] items = (Object[]) WamiXmlRpcUtils.parseResponse(logStr); componentType = (String) items[0]; className = (String) items[1]; params = (Map<String, String>) items[2]; } public String toLogEvent() { Object[] items = { componentType, className, params }; return WamiXmlRpcUtils.serializeResponse(items); } @Override public String toString() { return toLogEvent(); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; @SuppressWarnings("serial") public class InitializationException extends Exception { WamiRelay relay; public InitializationException() { super(); } public InitializationException(String message) { super(message); } public InitializationException(Throwable cause) { super(cause); } public InitializationException(String message, Throwable cause) { super(message, cause); } public void setRelay(WamiRelay relay) { this.relay = relay; } public WamiRelay getRelay() { return relay; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; import java.util.Map.Entry; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import edu.mit.csail.sls.wami.WamiConfig; import edu.mit.csail.sls.wami.util.ServletUtils; /** * Manages all the relays for the servlet. */ public class RelayManager { /** * parameterized via xml */ private HashMap<String, WamiRelay> activeRelays = new HashMap<String, WamiRelay>(); private int maxActiveRelays; private long nextTimeout; /** * timeout in milleseconds (set in config.xml); */ private long timeout; private long noPollFromClientTimeout; private ServletContext sc; public synchronized List<WamiRelay> getActiveRelays() { List<WamiRelay> relays = new Vector<WamiRelay>(); Iterator<WamiRelay> it = activeRelays.values().iterator(); while (it.hasNext()) { relays.add(it.next()); } return relays; } private RelayManager(int maxActiveRelays, long relayTimeout, long noPollFromClientTimeout, ServletContext servletContext) { System.out.println("New RelayManager started for " + maxActiveRelays + " simulteanous active relays"); this.maxActiveRelays = maxActiveRelays; this.timeout = relayTimeout; this.noPollFromClientTimeout = noPollFromClientTimeout; this.sc = servletContext; new Thread(new TimeoutThread()).start(); } public synchronized void remove(WamiRelay relay) { debugActive("About to remove relay " + relay.getWamiSessionID()); activeRelays.remove(relay.getWamiSessionID()); debugActive("Removed relay " + relay.getWamiSessionID()); } /** * This is *not* perfect, because you should be immediately adding a relay * after asking. But should suffice for now */ public synchronized boolean isCapacityAvailable() { return isCapacityAvailable(null); } /** * Check if capacity is available, assuming we were to remove the passed in * relay (this is useful for page reloads) */ public synchronized boolean isCapacityAvailable(WamiRelay relay) { int activeSize = activeRelays.size(); debugActive("Checking capacity"); if (relay != null && activeRelays.values().contains(relay)) { activeSize--; // assume this one will be removed } return activeSize < maxActiveRelays; } public synchronized void addRelay(WamiRelay relay, String wsessionid) throws ReachedCapacityException { WamiRelay oldRelay = getRelay(wsessionid); if (!isCapacityAvailable(oldRelay)) { int numUsers = getActiveRelays().size(); System.out.println("Already reached capacity of " + numUsers + " user(s)."); throw new ReachedCapacityException( "Relay manager reached capacity.", new Date( getNextTimeout())); } debugActive("About to add relay"); activeRelays.put(wsessionid, relay); debugActive("Added Relay " + wsessionid); long curTime = System.currentTimeMillis(); nextTimeout = curTime + timeout; } public WamiRelay getRelay(String wsessionid) { System.out.println("Getting relay at: " + wsessionid); return activeRelays.get(wsessionid); } /** * Return the earliest possible time a session might time out */ public synchronized long getNextTimeout() { return nextTimeout; } /** * closes all active relays */ public synchronized void close() { for (WamiRelay relay : activeRelays.values()) { relay.close(); } activeRelays.clear(); } private class TimeoutThread implements Runnable { public void run() { while (true) { long curTime = System.currentTimeMillis(); long sleepTime = Math.min(noPollFromClientTimeout, timeout); synchronized (RelayManager.this) { nextTimeout = curTime; debugActive("Before Timeout"); if (activeRelays.size() > 0) { Iterator<Entry<String, WamiRelay>> it = activeRelays .entrySet().iterator(); while (it.hasNext()) { Entry<String, WamiRelay> entry = it.next(); WamiRelay relay = entry.getValue(); if (timeoutSession(relay, curTime) || timeoutPolling(relay, curTime)) { relay.close(); it.remove(); } } } debugActive("After Timeout"); } try { sc.log("Timeout Thread Sleep for: " + sleepTime); Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } private boolean timeoutPolling(WamiRelay relay, long curTime) { long timeSincePoll = relay.getTimeSinceLastPollEnded(); System.out.println("timeSincePoll: " + timeSincePoll + " maxtime = " + noPollFromClientTimeout); if (timeSincePoll >= noPollFromClientTimeout) { System.out.println("TIMING OUT (no polling): " + relay); return true; } else { relay.forceRepoll(); // force repoll } return false; } private boolean timeoutSession(WamiRelay relay, long curTime) { long lastTime = relay.getTimeLastMessageSent(); long timeElapsed = curTime - lastTime; if (timeElapsed < 0) { timeElapsed = 0; } System.out.println("timeSinceMessage: " + timeElapsed + " maxtime = " + timeout); if (timeElapsed >= timeout) { System.out.println("TIMEOUT (no messages): " + relay); relay.timeout(); return true; } return false; } } private void debugActive(String message) { message = "ActiveRelays.size(" + message + "): " + getActiveRelays().size(); sc.log(message); } public static RelayManager getManager(HttpSession session) { RelayManager manager = null; synchronized (session.getServletContext()) { manager = (RelayManager) session.getServletContext().getAttribute( "relayManager"); if (manager == null) { session.getServletContext().log("Creating Relay Manager"); WamiConfig wc = WamiConfig.getConfiguration(session .getServletContext()); manager = new RelayManager(wc.getMaxRelays(), wc .getRelayTimeout(session), wc .getNoPollFromClientTimeout(), session .getServletContext()); session.getServletContext().setAttribute("relayManager", manager); } } return manager; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.StringLogEvent; /** * Represents a message sent from server to client * @author alexgru * */ public class SentMessageLogEvent extends StringLogEvent { public SentMessageLogEvent(String event) { super(event, IEventLogger.SentMessage); } public SentMessageLogEvent() { super(); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.relay; import org.w3c.dom.Element; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.StringLogEvent; import edu.mit.csail.sls.wami.util.XmlUtils; /** * Represents a message sent from client to server * * @author alexgru * */ public class ClientMessageLogEvent extends StringLogEvent { public ClientMessageLogEvent(Element event) { super(XmlUtils.toXMLString(event), IEventLogger.ClientLog); } public ClientMessageLogEvent(String event) { super(event, IEventLogger.ClientMessage); } public ClientMessageLogEvent() { super(); } // A client explicitly log events and set an event type with: // <update type="logevents"> <event type="myType" /> </update> private static String extractType(Element event) { if (!"event".equals(event.getTagName())) { return IEventLogger.ClientMessage; } String type = event.getAttribute("type"); if ("".equals(type) || type == null) { return IEventLogger.ClientMessage; } else { return IEventLogger.ClientMessage + "(" + type + ")"; } } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // This file is just for the java-doc package comments. /** * Classes for setting up a generic WAMI website. * * The edu.mit.csail.sls.wami package is a servlet and helper classes that manage * the interaction between web-clients and MIT's speech recognition technology. * * <p> * Information about using a basic version of the WAMI toolkit can be found here:<br /> * {@linkplain http://wami.csail.mit.edu} * </p> * * @see WamiConfig * @see WamiServlet * @see WamiRelay */ package edu.mit.csail.sls.wami;
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami; import java.awt.Dimension; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import edu.mit.csail.sls.wami.app.IApplicationController; import edu.mit.csail.sls.wami.app.IWamiApplication; import edu.mit.csail.sls.wami.audio.IAudioRetriever; import edu.mit.csail.sls.wami.log.EventLoggerDaemonAdapter; import edu.mit.csail.sls.wami.log.EventLoggerException; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.IEventPlayer; import edu.mit.csail.sls.wami.recognition.IRecognizer; import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException; import edu.mit.csail.sls.wami.relay.InstantiationEvent; import edu.mit.csail.sls.wami.synthesis.ISynthesizer; import edu.mit.csail.sls.wami.util.Instantiable; import edu.mit.csail.sls.wami.util.XmlUtils.ValidationErrorHandler; import edu.mit.csail.sls.wami.validation.IValidator; /** * <p> * WamiConfig manages the options that specify the components of the toolkit * (and their layouts if applicable). WAMI configuration is managed via a single * XML file as validated by the XML Schema generic/config.xsd. A single instance * of the WamiConfig class will be stored on the ServletContext during runtime. * This instance should never be accessed directly, but through the static * method <code>getConfiguration</code> provided by this class. * </p> * <p> * Configuration settings can then be accessed by the * <code>get*(HttpServletRequest)</code> methods. The request can override * configurations found within the XML file. The request can also simply be * null, and the parameter will then default to the value found in the config * file. * </p> * <p> * There is actually a further back-off mechanism. Attributes in the XML file * that are left unspecified have default values as well. These can be found in * the config.xsd file. One way to view all these defaults is to generate an XML * file from the XSD file (a feature that Eclipse includes.) * </p> * * @author imcgraw * */ public class WamiConfig { protected Document config = null; private String xmlname; public WamiConfig() { } /** * <p> * Get the singleton WamiConfig for the servlet. This is perhaps the single * most important method in this class. Any servlet wishing to use the * WamiConfig class must access it through this public method. This method * ensures that the WamiConfig is created once and only once for the * duration of the servlet's life-time. * </p> */ public static WamiConfig getConfiguration(ServletContext sc) { WamiConfig wc = null; synchronized (sc) { wc = (WamiConfig) sc.getAttribute("ajaxconfig"); if (wc == null) { // A little redundant, but that's ok. wc = new WamiConfig(sc); if (wc.getDocument() != null) { wc = getAppSpecificAjaxConfig(wc, sc); sc.setAttribute("ajaxconfig", wc); } } } return wc; } /** * Get the original, validated XML document that represents the * configuration. */ public Document getDocument() { return config; } /** * Given the className, this returns a new WamiConfig class, constructing it * via reflection. */ private static WamiConfig getAppSpecificAjaxConfig(WamiConfig ac, ServletContext sc) { String className = ac.getAjaxConfigClass(); System.out.println("Creating new WamiConfig class: " + className); if (className != null && !ac.getClass().getName().equals(className)) { try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = { ServletContext.class }; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = { sc }; ac = (WamiConfig) cons.newInstance(args); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return ac; } /** * <p> * This constructor should never be called outside the class. To access the * WamiConfig, one should always use the static method: * <code>getConfiguration(ServletContext)</code> * </p> */ public WamiConfig(final ServletContext sc) { xmlname = sc.getInitParameter("configFileName"); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(true); dbf.setNamespaceAware(true); dbf.setAttribute( "http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema"); InputStream xmlIn = getResourceAsStream(sc, xmlname); if (xmlIn == null) { String error = "ERROR: Unable to load config because couldn't resolve XML file."; throw new Exception(error); } final DocumentBuilder parser = dbf.newDocumentBuilder(); parser.setErrorHandler(new ValidationErrorHandler()); parser.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { System.out.println("RESOLVE ENTITY(" + systemId + ")"); // System.out.println("RESOLVE PUBLIC(" + publicId + ")"); String name = "edu/mit/csail/sls/wami/content" + systemId.substring(systemId.lastIndexOf("/")); System.out.println("Name: " + name); return new InputSource(this.getClass().getClassLoader() .getResourceAsStream(name)); } }); config = parser.parse(xmlIn); // System.out.println("WamiConfig(): " + // XmlUtils.toXMLString(config)); } catch (Exception e) { e.printStackTrace(); } } public String getConfigXMLName() { return xmlname; } public static InputStream getResourceAsStream(ServletContext sc, String name) { URL nameURL = null; // System.out.print("Name: " + name + " resolves to: "); try { nameURL = sc.getResource(name); } catch (MalformedURLException murle) { murle.printStackTrace(); } InputStream result = null; if (nameURL != null) { result = sc.getResourceAsStream(name); } else { ClassLoader loader = Thread.currentThread().getContextClassLoader(); nameURL = loader.getResource(name); if (nameURL != null) { result = loader.getResourceAsStream(name); } } System.out.println(nameURL); return result; } public static Element getUniqueDescendant(Node node, String name) { if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; return (Element) element.getElementsByTagName(name).item(0); } return null; } public boolean getDebug(HttpServletRequest request) { String debugStr = request.getParameter("debug"); boolean debugMode = debugStr != null && debugStr.equalsIgnoreCase("true"); return debugMode; } /** * Get class name to be used for the relay. If overriding the WamiRelay, * you'll need to specify the class in the config.xml file. Note that if you * override AjaxGalaxyControl, however, this needs to be specified in the * WebContent/WEB-INF/web.xml. This is because AjaxGalaxyControl is an */ public String getRelayClass() { Element relayE = getUniqueDescendant(getDocument().getFirstChild(), "relay"); return relayE.getAttribute("relayClass"); } public boolean getUseRelay() { Element relayE = getUniqueDescendant(getDocument().getFirstChild(), "relay"); return relayE != null; } /* * Build Configuration Accessors */ /** * Gets the ajax config class specified in the config.xml class. By default, * it's this one. */ private String getAjaxConfigClass() { Element buildE = getUniqueDescendant(config.getFirstChild(), "build"); if (buildE == null) { return this.getClass().getCanonicalName(); } return buildE.getAttribute("ajaxconfig"); } /* * Layout Configuration Accessors */ /** * The title of the AjaxGUI. This will appear many places in the pages and * emails generated. Typically it is just a short string like "City * Browser", "Shape Game", "Family Dialogue", etc. */ public String getTitle(HttpServletRequest request) { if (request != null && request.getParameter("title") != null) { return request.getParameter("title"); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); return getUniqueDescendant(layoutE, "title").getTextContent(); } /** * Return whether or not to test the browser version. If true is returned * then we test the browser to make sure that it is a version known to work * with the AjaxGUI code. The user is allowed to circumvent this test even * if their browser is not a well tested version. */ public boolean getTestBrowser(HttpServletRequest request) { if (request != null && request.getParameter("testBrowser") != null) { return Boolean.parseBoolean(request.getParameter("testBrowser")); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); return Boolean.parseBoolean(layoutE.getAttribute("testBrowser")); } /** * Returns the URL of a logo to be displayed in the upper-left of the page. */ public String getLogo(HttpServletRequest request) { String prefix = ""; if (request != null) { prefix = request.getContextPath(); if (request.getParameter("logo") != null) { return request.getParameter("logo"); } } if (getMobile(request)) { return null; } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element logoE = getUniqueDescendant(layoutE, "logo"); if (logoE == null) { return null; } return prefix + "/" + logoE.getAttribute("src"); } /** * Returns the logo width. */ public int getLogoWidth(HttpServletRequest request) { if (request != null && request.getParameter("logoImgWidth") != null) { return Integer.parseInt(request.getParameter("logoImgWidth")); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element logoE = getUniqueDescendant(layoutE, "logo"); if (logoE == null) { return 0; } return Integer.parseInt(logoE.getAttribute("width")); } /** * Returns the logo height. */ public int getLogoHeight(HttpServletRequest request) { if (request != null && request.getParameter("logoImgHeight") != null) { return Integer.parseInt(request.getParameter("logoImgHeight")); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element logoE = getUniqueDescendant(layoutE, "logo"); if (logoE == null) { return 0; } return Integer.parseInt(logoE.getAttribute("height")); } /** * Returns the class name for the audio applet. If the audio applet class * needs to be overridden, it can be specified in the XML file. This is not * typically done, however, so the value returned is usually the default * class corresponding to the AudioApplet. */ public String getAudioAppletClass(HttpServletRequest request) { String className = null; if (request != null) { className = request.getParameter("appletClassName"); } if (className == null) { Element layoutE = getUniqueDescendant( getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return null; } className = audioE.getAttribute("appletClass"); } if (!className.endsWith(".class")) { className += ".class"; } return className; } /** * Returns the archives to be used for the audio applet. If you'd like to * specify multiple archives for the applet, this can be done in the * getDocument().xml file. This is not typically overridden though. */ public String getAppletArchives(HttpServletRequest request) { if (request != null && request.getParameter("appletArchives") != null) { return request.getParameter("appletArchives"); } Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return null; } String result = audioE.getAttribute("archive"); if (result == null || "".equals(result)) { return getBaseURL(request) + "/content/wami_audio_applet.jar"; } NodeList archives = audioE.getElementsByTagName("archive"); for (int i = 0; i < archives.getLength(); i++) { result += ", "; Element archive = (Element) archives.item(i); result += archive.getAttribute("src"); } return result; } /** * Specifies the applet height. */ public int getAppletHeight(HttpServletRequest request) { if (request != null && request.getParameter("appletHeight") != null) { String height = request.getParameter("appletHeight"); return Integer.parseInt(height); } if (!getUseAudio(request)) { return 0; } Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); return Integer.parseInt(audioE.getAttribute("height")); } /** * Specified whether or not to poll for audio on /play servlet (default * true) */ public boolean getPollForAudio(HttpServletRequest request) { if (request != null && request.getParameter("pollForAudio") != null) { String height = request.getParameter("pollForAudio"); return Boolean.parseBoolean(height); } if (!getUseAudio(request)) { return false; } Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); return Boolean.parseBoolean(audioE.getAttribute("pollForAudio")); } /** * Specifies whether or not to hide the audio button on the applet (default * false) */ public boolean getHideAudioButton(HttpServletRequest request) { if (request != null && request.getParameter("hideAudioButton") != null) { String height = request.getParameter("hideAudioButton"); return Boolean.parseBoolean(height); } if (!getUseAudio(request)) { return false; } Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); return Boolean.parseBoolean(audioE.getAttribute("hideButton")); } /** * Specifies the applet width. */ public int getAppletWidth(HttpServletRequest request) { if (request != null && request.getParameter("appletWidth") != null) { String width = request.getParameter("appletWidth"); return Integer.parseInt(width); } Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (!getUseAudio(request)) { return 0; } return Integer.parseInt(audioE.getAttribute("width")); } /** * Determines whether or not we should optimize for a mobile device. Checks * the following in this order. (1) The request parameter "mobile", (2) The * configuration parameter "mobile" (3) the user agent string. Note, the * requirements for mobile devices are still in flux, this method may be * subject to change (alexgru Nov 2007) */ public boolean getMobile(HttpServletRequest request) { if (request != null && request.getParameter("mobile") != null) { String mobileStr = request.getParameter("mobile"); System.out .println("Optimizing for mobile device based on request mobile=true"); return Boolean.parseBoolean(mobileStr); } Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); Element mobileE = getUniqueDescendant(layoutE, "mobile"); if (mobileE != null) { System.out .println("Optimizing for mobile device based on config file"); return true; } String userAgent = request.getHeader("user-agent"); // for now, we only look for windows CE devices and Nokia N810 if ((userAgent != null && userAgent.contains("Windows CE")) || isNokiaN810(request)) { System.out .println("Optimizing for mobile device based on user agent string:"); System.out.println(userAgent); return true; } return false; } public int getMobileWidth(HttpServletRequest request) { int mobileWidth = -1; if (getMobile(request)) { java.awt.Dimension d = getMobileDimensions(request); if (d != null) { mobileWidth = d.width; } } return mobileWidth; } public int getMobileHeight(HttpServletRequest request) { int mobileHeight = -1; if (getMobile(request)) { java.awt.Dimension d = getMobileDimensions(request); if (d != null) { mobileHeight = d.height; } } return mobileHeight; } public boolean isNokiaN810(HttpServletRequest request) { // User agent: Mozilla/5.0 (X11; U; Linux armv6l; en-US; rv:1.9a6pre) // Gecko/20071128 Firefox/3.0a1 Tablet browser 0.2.2 // RX-34+RX-44_2008SE_2.2007.51-3 String userAgent = request.getHeader("user-agent"); return userAgent != null && userAgent.contains("Mozilla") && userAgent.contains("Linux") && userAgent.contains("Firefox") && userAgent.contains("Tablet browser"); } /** * Looks at the user agent string to try to determine the dimensions of the * mobile device screen. If this isn't a mobile device, or we can't * determine the dimensions, we return null. I'm including this method here * because we may, in the future, want to be able to override what the user * agent string reports. Note, the requirements for mobile devices are still * in flux, this method may be subject to change (alexgru Nov 2007) * * @param request * @return */ public Dimension getMobileDimensions(HttpServletRequest request) { String userAgent = request.getHeader("user-agent"); if (userAgent == null) { return null; } // this is probably mildly dangerous, just looks for e.g. 240x320 // anywhere in the string Pattern p = Pattern.compile("(\\d+)x(\\d+)"); Matcher m = p.matcher(userAgent); if (m.find()) { Dimension d = new Dimension(Integer.parseInt(m.group(1)), Integer .parseInt(m.group(2))); System.out .println("Mobile dimensions: " + d.width + "x" + d.height); return d; } return null; } /** * Determines whether or not the AjaxGUI is going to embed the AudioApplet. * The audio applet allows the user to listen and speak to interact with the * application. */ public boolean getUseAudio(HttpServletRequest request) { if (request != null && request.getParameter("audio") != null) { String audioStr = request.getParameter("audio"); return Boolean.parseBoolean(audioStr); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); return (audioE != null); } /** * Returns whether or not to use end-point detection. If returns true, then * the applet becomes click-to-talk (rather than hold-to-talk) and automatic * end-point detection is used. */ public boolean getUseSpeechDetector(HttpServletRequest request) { if (request != null && request.getParameter("useSpeechDetector") != null) { String useSpeechDetector = request .getParameter("useSpeechDetector"); return Boolean.parseBoolean(useSpeechDetector); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return false; } return Boolean.parseBoolean(audioE.getAttribute("useSpeechDetector")); } public boolean getPlayRecordTone(HttpServletRequest request) { if (request != null && request.getParameter("playRecordTone") != null) { String playRecordTone = request.getParameter("playRecordTone"); return Boolean.parseBoolean(playRecordTone); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return false; } return Boolean.parseBoolean(audioE.getAttribute("playRecordTone")); } /** * Determines if the audio applet should turn green when the hub enables * input. */ public boolean getGreenOnEnableInput(HttpServletRequest request) { if (request != null && request.getParameter("greenOnEnableInput") != null) { String greenOnEnableInput = request .getParameter("greenOnEnableInput"); return Boolean.parseBoolean(greenOnEnableInput); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return false; } return Boolean.parseBoolean(audioE.getAttribute("greenOnEnableInput")); } public String getRecordAudioFormat() { return getAudioAttribute("recordAudioFormat"); } public int getRecordSampleRate() { return Integer.parseInt(getAudioAttribute("recordSampleRate")); } public boolean getRecordIsLittleEndian() { return Boolean.parseBoolean(getAudioAttribute("recordIsLittleEndian")); } public boolean getAudioHttpOnly() { return Boolean.parseBoolean(getAudioAttribute("httpOnly")); } private String getAudioAttribute(String attributeName) { Element layoutE = getUniqueDescendant(getDocument().getFirstChild(), "layout"); if (layoutE == null) { return null; } Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return null; } return audioE.getAttribute(attributeName); } public String getRelaySetting(String name) { Element relayE = getUniqueDescendant(getDocument().getFirstChild(), "relay"); String getRelayTag = relayE.getAttribute("initialTag"); if (relayE != null) { NodeList settingsNodes = relayE.getElementsByTagName("settings"); for (int i = 0; i < settingsNodes.getLength(); i++) { Element settingsE = (Element) settingsNodes.item(i); if (getRelayTag.equals(settingsE.getAttribute("tag"))) { return settingsE.getAttribute(name); } } } return null; } public int getMaxRelays() { String maxRelaysString = getRelaySetting("maxRelays"); if (maxRelaysString == null) { throw new RuntimeException("Cannot find maxRelays!"); } return Integer.parseInt(maxRelaysString); } /** * get relay timeout (in ms) */ public long getRelayTimeout(HttpSession session) { String relayTimeoutString = getRelaySetting("relayTimeout"); if (!"default".equals(relayTimeoutString)) { session .getServletContext() .log( "WARNING: relayTimeout is now the same as session timeout, please remove this attribute from your config file.relayTimeout is now the same as session timeout, please remove this attribute from your config file"); } return session.getMaxInactiveInterval() * 1000; } /** * get maximum time (in ms) to allow between polls from a client */ public long getNoPollFromClientTimeout() { String noPollFromClientTimeoutString = getRelaySetting("noPollFromClientTimeout"); if (noPollFromClientTimeoutString == null) { throw new RuntimeException("CAnnot find noPollFromClientTimeout!"); } return Long.parseLong(noPollFromClientTimeoutString); } /** get max time to allow a poll from the client (in ms) */ public long getPollTimeout() { String timoutString = getRelaySetting("pollTimeout"); if (timoutString == null) { throw new RuntimeException("Cannot find pollTimeout!"); } return Long.parseLong(timoutString); } public String controlServletURL(HttpServletRequest request, String wsessionid) { String baseUrl = WamiConfig.getBaseURL(request); String url = baseUrl + "/ajaxcontrol;jsessionid=" + request.getSession().getId() + "?"; if (wsessionid != null) { try { url += "wsessionid=" + URLEncoder.encode(wsessionid, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return url; } public String audioServletURL(HttpServletRequest request, String wsessionid) { if (!getUseAudio(request)) { return null; } String url = getBaseURL(request, true) + "/play" + ";jsessionid=" + request.getSession().getId() + "?poll=true&playPollTimeout=" + getPlayPollTimeout(request); if (wsessionid != null) { try { url += "&wsessionid=" + URLEncoder.encode(wsessionid, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return url; } public String recordServletURL(HttpServletRequest request, String wsessionid) { if (!getUseAudio(request)) { return null; } String url = getBaseURL(request, true) + "/record" + ";jsessionid=" + request.getSession().getId() + "?recordAudioFormat=" + getRecordAudioFormat() + "&recordSampleRate=" + getRecordSampleRate() + "&recordIsLittleEndian=" + getRecordIsLittleEndian(); if (wsessionid != null) { try { url += "&wsessionid=" + URLEncoder.encode(wsessionid, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return url; } public int getPlayPollTimeout(HttpServletRequest request) { if (request != null && request.getParameter("playPollTimeout") != null) { String audioPollTimeout = request.getParameter("playPollTimeout"); return Integer.parseInt(audioPollTimeout); } Element layoutE = getUniqueDescendant(config.getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE == null) { return 0; } return Integer.parseInt(audioE.getAttribute("pollTimeout")); } public static int getAudioPort(HttpServletRequest request, boolean refusePort80) { WamiConfig wc = WamiConfig.getConfiguration(request.getSession() .getServletContext()); Element layoutE = getUniqueDescendant(wc.getDocument().getFirstChild(), "layout"); Element audioE = getUniqueDescendant(layoutE, "audio"); if (audioE != null) { int port = Integer.parseInt(audioE.getAttribute("port")); if (port != -1) { return port; } } return request.getServerPort(); } public boolean getUseSynthesizer() { return getUniqueDescendant(getDocument().getFirstChild(), "synthesizer") != null; } /** * AudioApplet can be used, but be invisible. This parameter only available * on the URL. */ public boolean getAudioAppletVisible(HttpServletRequest request) { if (request != null && request.getParameter("audioVisible") != null) { String audioStr = request.getParameter("audioVisible"); return Boolean.parseBoolean(audioStr); } return true; } public static String getBaseURL(HttpServletRequest req) { return getBaseURL(req, false); } public static String getBaseURL(HttpServletRequest req, boolean refusePort80) { // http://hostname.com:8080/mywebapp/ String scheme = req.getScheme(); // http String serverName = req.getServerName(); // hostname.com int serverPort = getAudioPort(req, refusePort80); String contextPath = req.getContextPath(); // /mywebapp // Reconstruct original requesting URL String url = scheme + "://" + serverName + ":" + serverPort + contextPath; return url; } public ISynthesizer createSynthesizer(IApplicationController appController) { String className = getClassAttribute("synthesizer"); Map<String, String> params = getParameters("synthesizer"); return createSynthesizer(appController, className, params); } public ISynthesizer createSynthesizer(IApplicationController appController, String className, Map<String, String> params) { System.out.println("Creating new synthesizer class: " + className); ISynthesizer synth = null; if (className != null) { try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = {}; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = {}; synth = (ISynthesizer) cons.newInstance(args); synth.setParameters(params); if (appController != null) { logInstantiationEvent(appController, "synthesizer", className, params); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return synth; } public static Instantiable createInstantiable(ServletContext sc, Element elem) { String className = elem.getAttribute("class"); System.out.println("Creating new instance of class: " + className); Map<String, String> params = getParameters(elem); Instantiable instance = null; if (className != null) { try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = {}; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = {}; instance = (Instantiable) cons.newInstance(args); instance.setParameters(sc, params); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return instance; } public IRecognizer createRecognizer(ServletContext sc, IApplicationController appController) throws RecognizerException { String className = getClassAttribute("recognizer"); Map<String, String> params = getParameters("recognizer"); return createRecognizer(sc, appController, className, params); } public IRecognizer createRecognizer(ServletContext sc, IApplicationController appController, String className, Map<String, String> params) throws RecognizerException { System.out.println("Creating new recognizer class: " + className); IRecognizer rec = null; if (className != null) { try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = {}; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = {}; rec = (IRecognizer) cons.newInstance(args); rec.setParameters(sc, params); if (appController != null) { logInstantiationEvent(appController, "recognizer", className, params); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return rec; } public IWamiApplication createWamiApplication( IApplicationController appController, HttpSession session) { Element appE = getUniqueDescendant(getDocument().getFirstChild(), "application"); if (appE == null) { System.err.println("No wami application specified in config file"); return null; } String className = appE.getAttribute("class"); Map<String, String> params = getParameters("application"); return createWamiApplication(appController, session, className, params); } public IWamiApplication createWamiApplication( IApplicationController appController, HttpSession session, String className, Map<String, String> params) { if (className != null) { try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = {}; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = {}; IWamiApplication app = (IWamiApplication) cons .newInstance(args); app.initialize(appController, session, params); logInstantiationEvent(appController, "application", className, params); return app; } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return null; } public IEventLogger createEventLogger(ServletContext sc) throws EventLoggerException { String className = getClassAttribute("event_logger"); System.out.println("Creating new event logger class: " + className); IEventLogger logger = null; if (className != null) { try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = {}; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = {}; logger = (IEventLogger) cons.newInstance(args); logger.setParameters(sc, getParameters("event_logger")); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } if (logger == null) { return null; } return new EventLoggerDaemonAdapter(logger); } public IAudioRetriever createAudioRetriever(ServletContext sc) { Element audioRetrieverE = getUniqueDescendant(getDocument() .getFirstChild(), "audio_retriever"); if (audioRetrieverE == null) { return null; } return (IAudioRetriever) createInstantiable(sc, audioRetrieverE); } public IValidator createValidator(ServletContext sc) { Element validatorE = getUniqueDescendant(getDocument().getFirstChild(), "validator"); if (validatorE == null) { return null; } return (IValidator) createInstantiable(sc, validatorE); } public IEventPlayer createLogPlayer(HttpServletRequest request) { ServletContext sc = request.getSession().getServletContext(); Map<String, String> params = new HashMap<String, String>(); String className = getClassAttribute("event_player"); System.out.println("Creating new event logger class: " + className); IEventPlayer logplayer = null; if (className != null) { for (Object key : request.getParameterMap().keySet()) { String paramName = (String) key; String paramValue = request.getParameter(paramName); params.put(paramName, paramValue); } params.putAll(getParameters("event_player")); try { Class<?> acClass = Class.forName(className); Class<?>[] paramTypes = {}; Constructor<?> cons = acClass.getConstructor(paramTypes); Object[] args = {}; logplayer = (IEventPlayer) cons.newInstance(args); logplayer.setParameters(sc, params); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return logplayer; } public String getClassAttribute(String elementName) { Element e = getUniqueDescendant(getDocument().getFirstChild(), elementName); if (e == null) { return null; } return e.getAttribute("class"); } /** * Arbitrary XML specific to the application. */ public Element getSpecifics() { return getUniqueDescendant(getDocument().getFirstChild(), "specifics"); } public Map<String, String> getParameters(String elementName) { Element parentE = getUniqueDescendant(getDocument().getFirstChild(), elementName); if (parentE == null) { return null; } return getParameters(parentE); } public static Map<String, String> getParameters(Element e) { Map<String, String> params = new HashMap<String, String>(); NodeList list = e.getElementsByTagName("param"); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Element paramE = (Element) node; String name = paramE.getAttribute("name"); String value = paramE.getAttribute("value"); params.put(name, value); } } return params; } public static String reconstructRequestURLandParams( HttpServletRequest request) { String url = request.getRequestURL().toString(); String params = ""; for (Object key : request.getParameterMap().keySet()) { String paramName = (String) key; String paramValue = request.getParameter(paramName); params += "&" + paramName + "=" + paramValue; } if (!"".equals(params)) { params = params.replaceFirst("&", "?"); url += params; } return url; } /** * Logs an instantiation event (e.g. the creation of a recognizer, * synthesizer, or wamiapplication with its relevant parameters) */ private void logInstantiationEvent(IApplicationController appController, String componentType, String className, Map<String, String> params) { appController.logEvent(new InstantiationEvent(componentType, className, params), System.currentTimeMillis()); } public static String getLocalHostName() { String hostname = null; try { InetAddress addr = InetAddress.getLocalHost(); hostname = addr.getHostName(); } catch (UnknownHostException e) { } return hostname; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.synthesis; import java.io.InputStream; import java.util.Map; public interface ISynthesizer { void setParameters(Map<String, String> map); /** * Some synthesizer parameters may be dynamically configurable and can be * configured here * * @param name * The name of the parameter to set * @param value * It's value, represented as a string */ void setDynamicParameter(String name, String value) throws SynthesizerException; /** * Synthesize an utterance and return an input stream representing that * utterance. Appropriate audio header information should appear in the * stream * * @param ttsString * The string to synthesize * @throws SynthesizerException */ InputStream synthesize(String ttsString) throws SynthesizerException; /** * Destroys this synthesizer. After this call, it is improper to use the * synthesizer again. */ void destroy() throws SynthesizerException; }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.synthesis; import org.w3c.dom.Document; import org.w3c.dom.Element; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.ILoggable; import edu.mit.csail.sls.wami.util.XmlUtils; public class SpeakLogEvent implements ILoggable { private String ttsStr; public SpeakLogEvent(String ttsStr) { this.ttsStr = ttsStr; } public SpeakLogEvent() { } public void fromLogEvent(String logStr, String eventType) { Document doc = XmlUtils.toXMLDocument(logStr); ttsStr = ((Element) doc.getFirstChild()).getAttribute("text"); } public String toLogEvent() { Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("speak"); root.setAttribute("text", ttsStr); doc.appendChild(root); return XmlUtils.toXMLString(doc); } public String getEventType() { return IEventLogger.Speak; } public String getText() { return ttsStr; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.synthesis; @SuppressWarnings("serial") public class SynthesizerException extends Exception { public SynthesizerException(String message) { super(message); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.synthesis; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import edu.mit.csail.sls.wami.util.XmlUtils; /** * This is an *example* implementation of the synthesizer interface that * requests audio from a URL. The URL is provided as a "param" to the * synthesizer in the config.xml file. The string to be synthesized is placed on * the request as "synth_string". * * One really easy way to test out a dummy "synthesizer" is to set the URL to * point to a .wav. Then, the "synthesizer" will ignore the input text and just * play the wav. * * A real synthesizer would actually examine the properties of the request and * produce audio based on the "synth_string" property. We leave it to you to * plug in the synthesizer of your choice. * * @author imcgraw */ public class URLSynthesizer implements ISynthesizer { String urlstr; Map<String, String> map = null; boolean asXMLPost = false; String asUrlParam = null; public InputStream synthesize(String input) throws SynthesizerException { URL url; try { InputStream stream = null; if (asUrlParam != null) { stream = getStreamGivenUrlParam(asUrlParam, urlstr, input); return stream; } url = new URL(urlstr); if (url == null) { throw new SynthesizerException("URL is null for synthesizer!"); } if (asXMLPost) { stream = getStreamViaXMLPost(input, url); } else { stream = getStreamViaNormalUrlConnection(input, url); } return stream; } catch (MalformedURLException e) { throw new SynthesizerException("Bad synthesizer URL: " + urlstr); } catch (IOException e) { throw new SynthesizerException( "Bad audio input stream returned from URL: " + urlstr); } } private InputStream getStreamGivenUrlParam(String asParam, String urlstr, String input) throws IOException { input = input.replace(" ", "%20"); URL url = new URL(urlstr + "?" + asParam + "=" + input); URLConnection c = url.openConnection(); c.addRequestProperty("Content-Type", "text/xml;charset=UTF-8"); c.addRequestProperty("synth_string", input); // Place the parameters on the request to the synthesizer for (String key : map.keySet()) { String value = map.get(key); c.addRequestProperty(key, value); } c.connect(); return c.getInputStream(); } private InputStream getStreamViaNormalUrlConnection(String input, URL url) throws IOException { URLConnection c = url.openConnection(); c.addRequestProperty("Content-Type", "text/xml;charset=UTF-8"); c.addRequestProperty("synth_string", input); // Place the parameters on the request to the synthesizer for (String key : map.keySet()) { String value = map.get(key); System.out.println("Synthe kv pair: " + key + "," + value); c.addRequestProperty(key, value); } c.connect(); return c.getInputStream(); } private InputStream getStreamViaXMLPost(String input, URL url) throws IOException { HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setRequestMethod("POST"); c.addRequestProperty("Content-Type", "text/xml;charset=UTF-8"); Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("root"); doc.appendChild(root); map.put("synth_string", input); // Place the parameters on the request to the synthesizer for (String key : map.keySet()) { Element param = doc.createElement("param"); param.setAttribute("name", key); param.setAttribute("value", map.get(key)); root.appendChild(param); } c.setDoOutput(true); c.setDoInput(true); OutputStreamWriter osw = new OutputStreamWriter(c.getOutputStream(), "UTF-8"); String xmlstr = XmlUtils.toXMLString(doc); System.out.println(xmlstr); osw.write(xmlstr); osw.close(); return c.getInputStream(); } public void setParameters(Map<String, String> map) { this.map = map; updateParameters(); } public void updateParameters() { if (map.get("asParam") != null) { asUrlParam = map.get("asParam"); } System.out.println("asParam: " + asUrlParam); String urlString = map.get("url"); if (urlString != null) { urlstr = urlString; } String asXMLString = map.get("asXML"); if (asXMLString != null) { asXMLPost = Boolean.parseBoolean(asXMLString); } } public void destroy() throws SynthesizerException { } public void setDynamicParameter(String name, String value) throws SynthesizerException { if (map == null) { throw new SynthesizerException( "Synthesizer not yet configured, cannot set dynamic parameter!"); } map.put(name, value); updateParameters(); } }
Java
/** * This package contains content accessible through a proxy servlet, if the web.xml contains * * <servlet> * <servlet-name>content</servlet-name> * <servlet-class>edu.mit.csail.sls.wami.jsapi.WamiContentProxy</servlet-class> * </servlet> * * <servlet-mapping> * <servlet-name>content</servlet-name> * <url-pattern>/content/*</url-pattern> * </servlet-mapping> * * */ package edu.mit.csail.sls.wami.content;
Java
package edu.mit.csail.sls.wami.database; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import javax.servlet.ServletContext; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import edu.mit.csail.sls.wami.WamiConfig; /** * An extension of WamiConfig for including database information in the * config.xml file, and some convenience methods for easily creating * connections. * * @author alexgru * */ public class DatabaseConfig extends WamiConfig { private Map<String, Connection> connections = new HashMap<String, Connection>(); public DatabaseConfig() { super(); } public DatabaseConfig(ServletContext sc) { super(sc); } public static DatabaseConfig getConfiguration(ServletContext sc) { return (DatabaseConfig) WamiConfig.getConfiguration(sc); } /** * You should always access the database connection through this method. The * database is lazily created it as needed. This assumes you only have one * database connected. * * @return a (lazily created) connection to the DB. */ public synchronized Connection getSingletonDatabaseConnection() { return getSingletonDatabaseConnection(getOnlyDatabaseTag()); } public synchronized Connection getSingletonDatabaseConnection( String databaseTag) { Connection dbConn = connections.get(databaseTag); if (dbConn == null) { try { dbConn = DatabaseConfig.createConnection(this, databaseTag); connections.put(databaseTag, dbConn); } catch (ClassNotFoundException e1) { System.out .println("WARNING: Database connection NOT returned!"); e1.printStackTrace(); // throw new RuntimeException(e1); } catch (SQLException e1) { System.out .println("WARNING: Database connection NOT returned!"); // e1.printStackTrace(); // hrow new RuntimeException(e1); } } return dbConn; } public synchronized void closeAllDBConnections() { Object[] keys = connections.keySet().toArray(); for (int i = 0; i < keys.length; i++) { String key = (String) keys[i]; closeConnection(key); } } public synchronized void closeDBConnection() { closeConnection(getOnlyDatabaseTag()); } public synchronized void closeConnection(String databaseTag) { Connection dbConn = connections.get(databaseTag); try { if (dbConn != null) { dbConn.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { dbConn = null; } connections.remove(databaseTag); } /* * Database Configuration Accessors */ /** * Returns whether or not database is being used at all. Note that a * database must be specified if any of the log-in features are used. */ public boolean getUseDatabase() { Element databaseE = getUniqueDescendant(getDocument().getFirstChild(), "database"); return (databaseE != null); } /** * Information necessary to log-in to the database. */ public String getDatabaseUser() { return getDatabaseUser(getOnlyDatabaseTag()); } /** * Information necessary to log-in to the database. */ public String getDatabasePassword() { return getDatabasePassword(getOnlyDatabaseTag()); } /** * Information necessary to log-in to the database. */ public String getDatabaseUser(String databaseTag) { Element databaseE = getDatabaseElementByTag(databaseTag); return databaseE.getAttribute("user"); } /** * Information necessary to log-in to the database. */ public String getDatabasePassword(String databaseTag) { Element databaseE = getDatabaseElementByTag(databaseTag); return databaseE.getAttribute("password"); } /** * Information necessary to log-in to the database. */ public String getDatabaseDriverName() { return getDatabaseDriverName(getOnlyDatabaseTag()); } /** * Information necessary to log-in to the database. */ public String getDatabaseDriverName(String databaseTag) { Element databaseE = getDatabaseElementByTag(databaseTag); return databaseE.getAttribute("driver"); } public String getDatabaseURI() { return getDatabaseURI(getOnlyDatabaseTag()); } /** * Information necessary to log-in to the database. */ public String getDatabaseURI(String databaseTag) { Element databaseE = getDatabaseElementByTag(databaseTag); String dbName = databaseE.getAttribute("name"); String dbHost = databaseE.getAttribute("host"); String dbPort = databaseE.getAttribute("port"); String dbPrefix = databaseE.getAttribute("urlPrefix"); String dbURI = String.format("%s://%s:%s/%s", dbPrefix, dbHost, dbPort, dbName); return dbURI; } /** * Open a connection to the SQL server */ public static Connection createConnection(DatabaseConfig dbConfig, String databaseTag, boolean readOnly) throws ClassNotFoundException { // only try to make a database connection if (dbConfig.getUseDatabase()) { Class.forName(dbConfig.getDatabaseDriverName(databaseTag)); System.out.println("Connecting to: " + dbConfig.getDatabaseURI(databaseTag) + " with user " + dbConfig.getDatabaseUser(databaseTag) + " and pwrd " + dbConfig.getDatabasePassword(databaseTag)); try { Connection c = DriverManager.getConnection(dbConfig .getDatabaseURI(databaseTag), dbConfig .getDatabaseUser(databaseTag), dbConfig .getDatabasePassword(databaseTag)); c.setReadOnly(readOnly); return c; } catch (SQLException e) { System.out .println("WARNING: Database connection requested but not available, null returned for the connection, make sure to handle this case robustly."); e.printStackTrace(); return null; } } else { System.out .println("DBUTILS: No DB specification set, so *not* creating a database connection"); return null; } } /** * Open a connection to the SQL server */ public static Connection createConnection(DatabaseConfig dbConfig, String databaseTag) throws ClassNotFoundException, SQLException { return createConnection(dbConfig, databaseTag, false); } /** * Deprecated in favor of creating connections with a database tag. This * will still work assuming that there is just one database specified in the * config file (regardless of its tag). */ public static Connection createConnection(DatabaseConfig dbConfig) throws ClassNotFoundException { return createConnection(dbConfig, dbConfig.getOnlyDatabaseTag(), false); } protected String getOnlyDatabaseTag() { List<Element> elements = getDatabaseElements(); if (elements.size() != 1) { String message = "Code assumes single database, however, " + elements.size() + " were found on config.xml."; if (elements.size() > 1) { message += " If you would like to use multiple databases, please " + "ensure that all relevant code makes use of database tags."; } throw new RuntimeException(message); } return elements.get(0).getAttribute("tag"); } private List<Element> getDatabaseElements() { NodeList databaseNodes = getDocument().getElementsByTagName("database"); List<Element> elements = new Vector<Element>(); for (int i = 0; i < databaseNodes.getLength(); i++) { elements.add((Element) databaseNodes.item(i)); } return elements; } private Element getDatabaseElementByTag(String databaseTag) { List<Element> elements = getDatabaseElements(); for (Element databaseElement : elements) { String tag = databaseElement.getAttribute("tag"); if (tag.equals(databaseTag)) { return databaseElement; } } throw new RuntimeException("No database with tag '" + databaseTag + "' found in the config.xml."); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.lightweight; import java.util.LinkedHashMap; public interface JSGFIncrementalAggregatorListener { /** * A set of key/value pairs. This is a complete command if isPartial is false * @param kvs The set of key/value pairs - iteration order on the hashmap is the * order they appear in the hypothesis * @param isPartial whether or not this is still a tentative, "partial" hypothesis */ public void processIncremental(LinkedHashMap<String,String> kvs, boolean isPartial); }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.lightweight; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import edu.mit.csail.sls.wami.recognition.IRecognitionResult; /** * Create an incremental agreggator, and keep giving it partials. It will * callback the requested method with whatever updates are appropriate. Some * potentially useful public static methods are provided as well. * * @author alexgru * */ public class JSGFIncrementalAggregator { public static String DEFAULT_SPLIT_TAG = "command"; private JSGFIncrementalAggregatorListener listener; private String lastPartial; List<LinkedHashMap<String, String>> lastCommandSets; private int partialPendingIndex = 0; private String splitTagName; private boolean ignoreHangingTags; private boolean includeCommandMetaInfo; public JSGFIncrementalAggregator(JSGFIncrementalAggregatorListener listener) { this(listener, DEFAULT_SPLIT_TAG, true, false); } public JSGFIncrementalAggregator( JSGFIncrementalAggregatorListener listener, String splitTag) { this(listener, splitTag, true, false); } public JSGFIncrementalAggregator( JSGFIncrementalAggregatorListener listener, String splitTag, boolean ignoreHangingTags, boolean includeCommandMetaInfo) { this.splitTagName = splitTag; this.listener = listener; this.ignoreHangingTags = ignoreHangingTags; this.includeCommandMetaInfo = includeCommandMetaInfo; reset(); } public void update(IRecognitionResult recResult) { if (recResult.getHyps().size() > 0) { update(recResult.getHyps().get(0), recResult.isIncremental()); } } private boolean equalCommandSets(List<LinkedHashMap<String, String>> set1, List<LinkedHashMap<String, String>> set2) { if (set1 == null && set2 == null) { return true; } else if (set1 == null || set2 == null) { return false; } else if (set1.size() != set2.size()) { return false; } else { for (int i = 0; i < set1.size(); i++) { LinkedHashMap<String, String> hash1 = set1.get(i); LinkedHashMap<String, String> hash2 = set2.get(i); if (!hash1.equals(hash2)) { return false; } } return true; } } public void update(String hyp, boolean isPartial) { if (hyp == null || (isPartial && hyp.equals(lastPartial))) { return; // nothing to do } else { lastPartial = hyp; } List<LinkedHashMap<String, String>> commandSets = extractCommandSets( hyp, splitTagName, isPartial, ignoreHangingTags, includeCommandMetaInfo); if (isPartial && equalCommandSets(commandSets, lastCommandSets)) { return; // same as last time, nothing to do } lastCommandSets = commandSets; if (commandSets.size() == 1) { listener.processIncremental(commandSets.get(0), isPartial); } else { if (isPartial) { for (int i = partialPendingIndex; i < commandSets.size(); i++) { listener.processIncremental(commandSets.get(i), i == (commandSets.size() - 1)); } partialPendingIndex = commandSets.size() - 1; } else { // flush out everything b/c we're done for (int i = partialPendingIndex; i < commandSets.size(); i++) { listener.processIncremental(commandSets.get(i), false); } partialPendingIndex = 0; } } if (!isPartial) { reset(); } } /** * Resets the aggregator */ public void reset() { partialPendingIndex = 0; lastPartial = null; lastCommandSets = null; } /** * extract sets of key values, grouped into commands. To avoid some command * ambiguity issues, if the hyp string ends with a tag, and that tag is a * command we ignore it * * @param includeCommandMetaInfo * * @param tags * @param endsWithTag * @return */ public static List<LinkedHashMap<String, String>> extractCommandSets( String hyp, String splitTagName, boolean isPartial, boolean ignoreHangingTags, boolean includeCommandMetaInfo) { ArrayList<LinkedHashMap<String, String>> commandSets = new ArrayList<LinkedHashMap<String, String>>(); ArrayList<Tag> tags = extractTags(hyp); boolean endsWithTag = hyp.trim().endsWith("]"); LinkedHashMap<String, String> kvs = new LinkedHashMap<String, String>(); for (int i = 0; i < tags.size(); i++) { Tag tag = tags.get(i); if (tag.getKey().equals(splitTagName)) { if (i == tags.size() - 1 && endsWithTag && ignoreHangingTags && isPartial) { break; // ignore command tag if it's hanging at the end } if (kvs.size() > 0) { commandSets.add(kvs); kvs = new LinkedHashMap<String, String>(); } if (includeCommandMetaInfo) { kvs.put("current_hypothesis", hyp); kvs.put("index_into_hypothesis", "" + tag.getIndex()); } } kvs.put(tag.getKey(), tag.getValue()); } commandSets.add(kvs); return commandSets; } private static class Tag { String key; String value; int index; public Tag(String tag, int index) { String[] kv = tag.split("="); key = kv[0].trim(); value = kv[1].trim(); this.index = index; } public String getKey() { return key; } public String getValue() { return value; } public int getIndex() { return index; } } public static ArrayList<Tag> extractTags(String hyp) { Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(hyp); ArrayList<Tag> tags = new ArrayList<Tag>(); while (m.find()) { tags.add(new Tag(m.group(1), m.start())); } return tags; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition; import java.io.IOException; import java.util.Map; import javax.servlet.ServletContext; import javax.sound.sampled.AudioInputStream; import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException; import edu.mit.csail.sls.wami.recognition.lm.LanguageModel; import edu.mit.csail.sls.wami.recognition.lm.exceptions.LanguageModelCompilationException; public interface IRecognizer { /** * Called once, just after the constructor, when the recognizer is * initialized * * @param sc * Servlet context * @param map * A map containing the parameter values * @throws RecognizerException */ void setParameters(ServletContext sc, Map<String, String> map) throws RecognizerException; /** * Some recognizer parameters may be dynamically configurable and can be * configured here * * @param name The name of the parameter to set * @param value It's value, represented as a string */ void setDynamicParameter(String name, String value) throws RecognizerException; /** * Perform speech recognition on the passed in audio input stream. * * @param audioIn * An audio input strema for the recognizer * @throws IOException * on error reading from audioIn * @throws RecognizerException * for various recognition errors. */ public void recognize(AudioInputStream audioIn, IRecognitionListener listener) throws RecognizerException, IOException; /** * Set the language model to be used by the recognizer * * @param model * The new language model * @throws RecognizerException * Of note, throws {@link LanguageModelCompilationException} if * there is an error compiling the language model. */ public void setLanguageModel(LanguageModel model) throws RecognizerException; /** * Destroys this recognizer, once this has been called the recognizer can't * be used again */ public void destroy() throws RecognizerException; }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.exceptions; public class RecognizerUnreachableException extends RecognizerException { public RecognizerUnreachableException() { super(); } public RecognizerUnreachableException(String message) { super(message); } public RecognizerUnreachableException(Throwable cause) { super(cause); } public RecognizerUnreachableException(String message, Throwable cause) { super(message, cause); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.exceptions; /** * Thrown when the language model has not yet been set * * @author alexgru * */ public class LanguageModelNotSetException extends RecognizerException { public LanguageModelNotSetException() { super( "The language model for a session must be set before recognition can occur"); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.exceptions; public class RecognizerException extends Exception { public RecognizerException(String message) { super(message); } public RecognizerException(Throwable cause) { super(cause); } public RecognizerException(String message, Throwable cause) { super(message, cause); } public RecognizerException() { super(); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.util.XmlUtils; /** * A recognition result contains a list of results. In the future, more * attributes may be added here (e.g. confidence scores) * * @author alexgru * */ public class RecognitionResult implements IRecognitionResult { private List<String> hyps; private boolean isIncremental; private String errorMessage; /** * Empty constructor which performs no initialization. Typically used for * log playback */ public RecognitionResult() { } public RecognitionResult(String errorMessage) { this.hyps = new ArrayList<String>(); this.errorMessage = errorMessage; } public RecognitionResult(boolean isIncremental, String... hyps) { this.hyps = Arrays.asList(hyps); this.isIncremental = isIncremental; } public RecognitionResult(boolean isIncremental, List<String> hyps) { this.hyps = new ArrayList<String>(hyps); this.isIncremental = isIncremental; } /* * (non-Javadoc) * * @see edu.mit.csail.sls.wami.recognition.IRecognitionResult#getHyps() */ public List<String> getHyps() { return new ArrayList<String>(hyps); } /* * (non-Javadoc) * * @see * edu.mit.csail.sls.wami.recognition.IRecognitionResult#isIncremental() */ public boolean isIncremental() { return isIncremental; } public String toLogEvent() { Document doc = XmlUtils.newXMLDocument(); Element root = doc.createElement("recognition_result"); doc.appendChild(root); root.setAttribute("is_incremental", new Boolean(isIncremental) .toString()); if (errorMessage != null) { root.setAttribute("error_message", errorMessage); } for (String hyp : hyps) { Element hypE = doc.createElement("hyp"); hypE.setAttribute("text", hyp); root.appendChild(hypE); } return XmlUtils.toXMLString(doc); } public void fromLogEvent(String logStr, String eventType) { Document doc = XmlUtils.toXMLDocument(logStr); Element root = (Element) doc.getElementsByTagName("recognition_result") .item(0); isIncremental = Boolean.parseBoolean(root .getAttribute("is_incremental")); hyps = new ArrayList<String>(); NodeList hypNodes = root.getElementsByTagName("hyp"); for (int i = 0; i < hypNodes.getLength(); i++) { Element hypE = (Element) hypNodes.item(i); hyps.add(hypE.getAttribute("text")); } errorMessage = root.getAttribute("error_message"); if ("".equals(errorMessage)) { errorMessage = null; } } public String getEventType() { return isIncremental ? IEventLogger.IncrementalRecResult : IEventLogger.FinalRecResult; } public String getError() { return errorMessage; } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition; import java.util.List; import edu.mit.csail.sls.wami.log.ILoggable; /** * Interface to recognition results. For logging, implementors must implement * toXml() and fromXml(). They must also provide a no-argument constructor to be * used to instantiate the class via reflection * * Implementors MUST have an empty constructor * * @author alexgru * */ public interface IRecognitionResult extends ILoggable { /** * Returns the hypotheses in this result */ public List<String> getHyps(); /** * Returns true if this is an incremental result, false otherwise */ public boolean isIncremental(); /** * If an error occurred, returns a string representation of that error. If no * error occurred, returns null. */ public String getError(); }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition; /** * The listener is called during recognition with incremental, and then final, * recognition results * * @author alexgru */ public interface IRecognitionListener { /** * Called when a recognition result is available. If isIncremental is true, * then this is an "incremental" result from the recognizer and it will be * revised with future calls to this method. If isIncremental is false, then * this is the final call to this method for this recognition attempt * * @param result * The recognition result */ public void onRecognitionResult(IRecognitionResult result); /** * Called when speech recognition has begun */ public void onRecognitionStarted(); }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition; import org.w3c.dom.Document; import edu.mit.csail.sls.wami.log.IEventLogger; import edu.mit.csail.sls.wami.log.ILoggable; import edu.mit.csail.sls.wami.util.XmlUtils; public class RecognitionStartedLogEvent implements ILoggable { public RecognitionStartedLogEvent() { } public void fromLogEvent(String logStr, String eventType) { } public String getEventType() { return IEventLogger.RecognitionStarted; } public String toLogEvent() { Document doc = XmlUtils.newXMLDocument(); doc.appendChild(doc.createElement("recognition_started")); return XmlUtils.toXMLString(doc); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.lm; /** * Common interface for language models to implement * * @author alexgru * */ public interface LanguageModel { /** * Returns a string description of the type of language model. E.g. "jsgf", * "n-gram" * */ public String getType(); /** * Return a string identifying the language of the * dictionary to use (e.g. "en-us" or "zh") * @return A string identifying the language * of the dictionary to use */ public String getDictionaryLanguage(); }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.lm.exceptions; import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException; /** * Thrown when there is an error with the language model. For instance, for a * JSGF language model this may be a compilation error. The error message should * contain details about the error. * * @author alexgru * */ public class LanguageModelCompilationException extends RecognizerException { public LanguageModelCompilationException(String message) { super(message); } }
Java
/* -*- Java -*- * * Copyright (c) 2009 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.sls.wami.recognition.lm.exceptions; import edu.mit.csail.sls.wami.recognition.exceptions.RecognizerException; /** * Thrown when an unexpected error occurs during compilation. This does not * indicate a problem with the language model itself, but more likely with the * server or the compilation process. More information should be found in the * message or cause * * @author alexgru * */ public class LanguageModelServerException extends RecognizerException { public LanguageModelServerException(Throwable cause) { super(cause); } public LanguageModelServerException(String message) { super(message); } }
Java