summaryrefslogtreecommitdiff
path: root/samples/quake/src/com
diff options
context:
space:
mode:
Diffstat (limited to 'samples/quake/src/com')
-rw-r--r--samples/quake/src/com/android/quake/llvm/DownloaderActivity.java1033
-rw-r--r--samples/quake/src/com/android/quake/llvm/PreconditionActivityHelper.java61
-rw-r--r--samples/quake/src/com/android/quake/llvm/QuakeActivity.java180
-rw-r--r--samples/quake/src/com/android/quake/llvm/QuakeLib.java198
-rw-r--r--samples/quake/src/com/android/quake/llvm/QuakeView.java394
-rw-r--r--samples/quake/src/com/android/quake/llvm/QuakeViewNoData.java64
6 files changed, 0 insertions, 1930 deletions
diff --git a/samples/quake/src/com/android/quake/llvm/DownloaderActivity.java b/samples/quake/src/com/android/quake/llvm/DownloaderActivity.java
deleted file mode 100644
index b07e3d0..0000000
--- a/samples/quake/src/com/android/quake/llvm/DownloaderActivity.java
+++ /dev/null
@@ -1,1033 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.quake.llvm;
-
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URL;
-//import java.nio.channels.FileLock;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-
-import org.apache.http.Header;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpHead;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.app.AlertDialog.Builder;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.SystemClock;
-import android.net.http.AndroidHttpClient;
-import android.util.Log;
-import android.util.Xml;
-import android.view.View;
-import android.view.Window;
-import android.view.WindowManager;
-import android.widget.Button;
-import android.widget.TextView;
-
-public class DownloaderActivity extends Activity {
-
- /**
- * Checks if data has been downloaded. If so, returns true. If not,
- * starts an activity to download the data and returns false. If this
- * function returns false the caller should immediately return from its
- * onCreate method. The calling activity will later be restarted
- * (using a copy of its original intent) once the data download completes.
- * @param activity The calling activity.
- * @param customText A text string that is displayed in the downloader UI.
- * @param fileConfigUrl The URL of the download configuration URL.
- * @param configVersion The version of the configuration file.
- * @param dataPath The directory on the device where we want to store the
- * data.
- * @param userAgent The user agent string to use when fetching URLs.
- * @return true if the data has already been downloaded successfully, or
- * false if the data needs to be downloaded.
- */
- public static boolean ensureDownloaded(Activity activity,
- String customText, String fileConfigUrl,
- String configVersion, String dataPath,
- String userAgent) {
- File dest = new File(dataPath);
- if (dest.exists()) {
- // Check version
- if (versionMatches(dest, configVersion)) {
- Log.i(LOG_TAG, "Versions match, no need to download.");
- return true;
- }
- }
- Intent intent = PreconditionActivityHelper.createPreconditionIntent(
- activity, DownloaderActivity.class);
- intent.putExtra(EXTRA_CUSTOM_TEXT, customText);
- intent.putExtra(EXTRA_FILE_CONFIG_URL, fileConfigUrl);
- intent.putExtra(EXTRA_CONFIG_VERSION, configVersion);
- intent.putExtra(EXTRA_DATA_PATH, dataPath);
- intent.putExtra(EXTRA_USER_AGENT, userAgent);
- PreconditionActivityHelper.startPreconditionActivityAndFinish(
- activity, intent);
- return false;
- }
-
- /**
- * Delete a directory and all its descendants.
- * @param directory The directory to delete
- * @return true if the directory was deleted successfully.
- */
- public static boolean deleteData(String directory) {
- return deleteTree(new File(directory), true);
- }
-
- private static boolean deleteTree(File base, boolean deleteBase) {
- boolean result = true;
- if (base.isDirectory()) {
- for (File child : base.listFiles()) {
- result &= deleteTree(child, true);
- }
- }
- if (deleteBase) {
- result &= base.delete();
- }
- return result;
- }
-
- private static boolean versionMatches(File dest, String expectedVersion) {
- Config config = getLocalConfig(dest, LOCAL_CONFIG_FILE);
- if (config != null) {
- return config.version.equals(expectedVersion);
- }
- return false;
- }
-
- private static Config getLocalConfig(File destPath, String configFilename) {
- File configPath = new File(destPath, configFilename);
- FileInputStream is;
- try {
- is = new FileInputStream(configPath);
- } catch (FileNotFoundException e) {
- return null;
- }
- try {
- Config config = ConfigHandler.parse(is);
- return config;
- } catch (Exception e) {
- Log.e(LOG_TAG, "Unable to read local config file", e);
- return null;
- } finally {
- quietClose(is);
- }
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Intent intent = getIntent();
- requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
- setContentView(R.layout.downloader);
- getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
- R.layout.downloader_title);
- ((TextView) findViewById(R.id.customText)).setText(
- intent.getStringExtra(EXTRA_CUSTOM_TEXT));
- mProgress = (TextView) findViewById(R.id.progress);
- mTimeRemaining = (TextView) findViewById(R.id.time_remaining);
- Button button = (Button) findViewById(R.id.cancel);
- button.setOnClickListener(new Button.OnClickListener() {
- public void onClick(View v) {
- if (mDownloadThread != null) {
- mSuppressErrorMessages = true;
- mDownloadThread.interrupt();
- }
- }
- });
- startDownloadThread();
- }
-
- private void startDownloadThread() {
- mSuppressErrorMessages = false;
- mProgress.setText("");
- mTimeRemaining.setText("");
- mDownloadThread = new Thread(new Downloader(), "Downloader");
- mDownloadThread.setPriority(Thread.NORM_PRIORITY - 1);
- mDownloadThread.start();
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- }
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- mSuppressErrorMessages = true;
- mDownloadThread.interrupt();
- try {
- mDownloadThread.join();
- } catch (InterruptedException e) {
- // Don't care.
- }
- }
-
- private void onDownloadSucceeded() {
- Log.i(LOG_TAG, "Download succeeded");
- PreconditionActivityHelper.startOriginalActivityAndFinish(this);
- }
-
- private void onDownloadFailed(String reason) {
- Log.e(LOG_TAG, "Download stopped: " + reason);
- String shortReason;
- int index = reason.indexOf('\n');
- if (index >= 0) {
- shortReason = reason.substring(0, index);
- } else {
- shortReason = reason;
- }
- AlertDialog alert = new Builder(this).create();
- alert.setTitle(R.string.download_activity_download_stopped);
-
- if (!mSuppressErrorMessages) {
- alert.setMessage(shortReason);
- }
-
- alert.setButton(getString(R.string.download_activity_retry),
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- startDownloadThread();
- }
-
- });
- alert.setButton2(getString(R.string.download_activity_quit),
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- finish();
- }
-
- });
- try {
- alert.show();
- } catch (WindowManager.BadTokenException e) {
- // Happens when the Back button is used to exit the activity.
- // ignore.
- }
- }
-
- private void onReportProgress(int progress) {
- mProgress.setText(mPercentFormat.format(progress / 10000.0));
- long now = SystemClock.elapsedRealtime();
- if (mStartTime == 0) {
- mStartTime = now;
- }
- long delta = now - mStartTime;
- String timeRemaining = getString(R.string.download_activity_time_remaining_unknown);
- if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) {
- long totalTime = 10000 * delta / progress;
- long timeLeft = Math.max(0L, totalTime - delta);
- if (timeLeft > MS_PER_DAY) {
- timeRemaining = Long.toString(
- (timeLeft + MS_PER_DAY - 1) / MS_PER_DAY)
- + " "
- + getString(R.string.download_activity_time_remaining_days);
- } else if (timeLeft > MS_PER_HOUR) {
- timeRemaining = Long.toString(
- (timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR)
- + " "
- + getString(R.string.download_activity_time_remaining_hours);
- } else if (timeLeft > MS_PER_MINUTE) {
- timeRemaining = Long.toString(
- (timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE)
- + " "
- + getString(R.string.download_activity_time_remaining_minutes);
- } else {
- timeRemaining = Long.toString(
- (timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND)
- + " "
- + getString(R.string.download_activity_time_remaining_seconds);
- }
- }
- mTimeRemaining.setText(timeRemaining);
- }
-
- private static void quietClose(InputStream is) {
- try {
- if (is != null) {
- is.close();
- }
- } catch (IOException e) {
- // Don't care.
- }
- }
-
- private static void quietClose(OutputStream os) {
- try {
- if (os != null) {
- os.close();
- }
- } catch (IOException e) {
- // Don't care.
- }
- }
-
- private static class Config {
- long getSize() {
- long result = 0;
- for(File file : mFiles) {
- result += file.getSize();
- }
- return result;
- }
- static class File {
- public File(String src, String dest, String md5, long size) {
- if (src != null) {
- this.mParts.add(new Part(src, md5, size));
- }
- this.dest = dest;
- }
- static class Part {
- Part(String src, String md5, long size) {
- this.src = src;
- this.md5 = md5;
- this.size = size;
- }
- String src;
- String md5;
- long size;
- }
- ArrayList<Part> mParts = new ArrayList<Part>();
- String dest;
- long getSize() {
- long result = 0;
- for(Part part : mParts) {
- if (part.size > 0) {
- result += part.size;
- }
- }
- return result;
- }
- }
- String version;
- ArrayList<File> mFiles = new ArrayList<File>();
- }
-
- /**
- * <config version="">
- * <file src="http:..." dest ="b.x" />
- * <file dest="b.x">
- * <part src="http:..." />
- * ...
- * ...
- * </config>
- *
- */
- private static class ConfigHandler extends DefaultHandler {
-
- public static Config parse(InputStream is) throws SAXException,
- UnsupportedEncodingException, IOException {
- ConfigHandler handler = new ConfigHandler();
- Xml.parse(is, Xml.findEncodingByName("UTF-8"), handler);
- return handler.mConfig;
- }
-
- private ConfigHandler() {
- mConfig = new Config();
- }
-
- @Override
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) throws SAXException {
- if (localName.equals("config")) {
- mConfig.version = getRequiredString(attributes, "version");
- } else if (localName.equals("file")) {
- String src = attributes.getValue("", "src");
- String dest = getRequiredString(attributes, "dest");
- String md5 = attributes.getValue("", "md5");
- long size = getLong(attributes, "size", -1);
- mConfig.mFiles.add(new Config.File(src, dest, md5, size));
- } else if (localName.equals("part")) {
- String src = getRequiredString(attributes, "src");
- String md5 = attributes.getValue("", "md5");
- long size = getLong(attributes, "size", -1);
- int length = mConfig.mFiles.size();
- if (length > 0) {
- mConfig.mFiles.get(length-1).mParts.add(
- new Config.File.Part(src, md5, size));
- }
- }
- }
-
- private static String getRequiredString(Attributes attributes,
- String localName) throws SAXException {
- String result = attributes.getValue("", localName);
- if (result == null) {
- throw new SAXException("Expected attribute " + localName);
- }
- return result;
- }
-
- private static long getLong(Attributes attributes, String localName,
- long defaultValue) {
- String value = attributes.getValue("", localName);
- if (value == null) {
- return defaultValue;
- } else {
- return Long.parseLong(value);
- }
- }
-
- public Config mConfig;
- }
-
- private class DownloaderException extends Exception {
- public DownloaderException(String reason) {
- super(reason);
- }
- }
-
- private class Downloader implements Runnable {
- public void run() {
- Intent intent = getIntent();
- mFileConfigUrl = intent.getStringExtra(EXTRA_FILE_CONFIG_URL);
- mConfigVersion = intent.getStringExtra(EXTRA_CONFIG_VERSION);
- mDataPath = intent.getStringExtra(EXTRA_DATA_PATH);
- mUserAgent = intent.getStringExtra(EXTRA_USER_AGENT);
-
- mDataDir = new File(mDataPath);
-
- try {
- // Download files.
- mHttpClient = AndroidHttpClient.newInstance(mUserAgent);
- try {
- Config config = getConfig();
- filter(config);
- persistantDownload(config);
- verify(config);
- cleanup();
- reportSuccess();
- } finally {
- mHttpClient.close();
- }
- } catch (Exception e) {
- reportFailure(e.toString() + "\n" + Log.getStackTraceString(e));
- }
- }
-
- private void persistantDownload(Config config)
- throws ClientProtocolException, DownloaderException, IOException {
- while(true) {
- try {
- download(config);
- break;
- } catch(java.net.SocketException e) {
- if (mSuppressErrorMessages) {
- throw e;
- }
- } catch(java.net.SocketTimeoutException e) {
- if (mSuppressErrorMessages) {
- throw e;
- }
- }
- Log.i(LOG_TAG, "Network connectivity issue, retrying.");
- }
- }
-
- private void filter(Config config)
- throws IOException, DownloaderException {
- File filteredFile = new File(mDataDir, LOCAL_FILTERED_FILE);
- if (filteredFile.exists()) {
- return;
- }
-
- File localConfigFile = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP);
- HashSet<String> keepSet = new HashSet<String>();
- keepSet.add(localConfigFile.getCanonicalPath());
-
- HashMap<String, Config.File> fileMap =
- new HashMap<String, Config.File>();
- for(Config.File file : config.mFiles) {
- String canonicalPath =
- new File(mDataDir, file.dest).getCanonicalPath();
- fileMap.put(canonicalPath, file);
- }
- recursiveFilter(mDataDir, fileMap, keepSet, false);
- touch(filteredFile);
- }
-
- private void touch(File file) throws FileNotFoundException {
- FileOutputStream os = new FileOutputStream(file);
- quietClose(os);
- }
-
- private boolean recursiveFilter(File base,
- HashMap<String, Config.File> fileMap,
- HashSet<String> keepSet, boolean filterBase)
- throws IOException, DownloaderException {
- boolean result = true;
- if (base.isDirectory()) {
- for (File child : base.listFiles()) {
- result &= recursiveFilter(child, fileMap, keepSet, true);
- }
- }
- if (filterBase) {
- if (base.isDirectory()) {
- if (base.listFiles().length == 0) {
- result &= base.delete();
- }
- } else {
- if (!shouldKeepFile(base, fileMap, keepSet)) {
- result &= base.delete();
- }
- }
- }
- return result;
- }
-
- private boolean shouldKeepFile(File file,
- HashMap<String, Config.File> fileMap,
- HashSet<String> keepSet)
- throws IOException, DownloaderException {
- String canonicalPath = file.getCanonicalPath();
- if (keepSet.contains(canonicalPath)) {
- return true;
- }
- Config.File configFile = fileMap.get(canonicalPath);
- if (configFile == null) {
- return false;
- }
- return verifyFile(configFile, false);
- }
-
- private void reportSuccess() {
- mHandler.sendMessage(
- Message.obtain(mHandler, MSG_DOWNLOAD_SUCCEEDED));
- }
-
- private void reportFailure(String reason) {
- mHandler.sendMessage(
- Message.obtain(mHandler, MSG_DOWNLOAD_FAILED, reason));
- }
-
- private void reportProgress(int progress) {
- mHandler.sendMessage(
- Message.obtain(mHandler, MSG_REPORT_PROGRESS, progress, 0));
- }
-
- private Config getConfig() throws DownloaderException,
- ClientProtocolException, IOException, SAXException {
- Config config = null;
- if (mDataDir.exists()) {
- config = getLocalConfig(mDataDir, LOCAL_CONFIG_FILE_TEMP);
- if ((config == null)
- || !mConfigVersion.equals(config.version)) {
- if (config == null) {
- Log.i(LOG_TAG, "Couldn't find local config.");
- } else {
- Log.i(LOG_TAG, "Local version out of sync. Wanted " +
- mConfigVersion + " but have " + config.version);
- }
- config = null;
- }
- } else {
- Log.i(LOG_TAG, "Creating directory " + mDataPath);
- mDataDir.mkdirs();
- mDataDir.mkdir();
- if (!mDataDir.exists()) {
- throw new DownloaderException(
- "Could not create the directory " + mDataPath);
- }
- }
- if (config == null) {
- File localConfig = download(mFileConfigUrl,
- LOCAL_CONFIG_FILE_TEMP);
- InputStream is = new FileInputStream(localConfig);
- try {
- config = ConfigHandler.parse(is);
- } finally {
- quietClose(is);
- }
- if (! config.version.equals(mConfigVersion)) {
- throw new DownloaderException(
- "Configuration file version mismatch. Expected " +
- mConfigVersion + " received " +
- config.version);
- }
- }
- return config;
- }
-
- private void noisyDelete(File file) throws IOException {
- if (! file.delete() ) {
- throw new IOException("could not delete " + file);
- }
- }
-
- private void download(Config config) throws DownloaderException,
- ClientProtocolException, IOException {
- mDownloadedSize = 0;
- getSizes(config);
- Log.i(LOG_TAG, "Total bytes to download: "
- + mTotalExpectedSize);
- for(Config.File file : config.mFiles) {
- downloadFile(file);
- }
- }
-
- private void downloadFile(Config.File file) throws DownloaderException,
- FileNotFoundException, IOException, ClientProtocolException {
- boolean append = false;
- File dest = new File(mDataDir, file.dest);
- long bytesToSkip = 0;
- if (dest.exists() && dest.isFile()) {
- append = true;
- bytesToSkip = dest.length();
- mDownloadedSize += bytesToSkip;
- }
- FileOutputStream os = null;
- long offsetOfCurrentPart = 0;
- try {
- for(Config.File.Part part : file.mParts) {
- // The part.size==0 check below allows us to download
- // zero-length files.
- if ((part.size > bytesToSkip) || (part.size == 0)) {
- MessageDigest digest = null;
- if (part.md5 != null) {
- digest = createDigest();
- if (bytesToSkip > 0) {
- FileInputStream is = openInput(file.dest);
- try {
- is.skip(offsetOfCurrentPart);
- readIntoDigest(is, bytesToSkip, digest);
- } finally {
- quietClose(is);
- }
- }
- }
- if (os == null) {
- os = openOutput(file.dest, append);
- }
- downloadPart(part.src, os, bytesToSkip,
- part.size, digest);
- if (digest != null) {
- String hash = getHash(digest);
- if (!hash.equalsIgnoreCase(part.md5)) {
- Log.e(LOG_TAG, "web MD5 checksums don't match. "
- + part.src + "\nExpected "
- + part.md5 + "\n got " + hash);
- quietClose(os);
- dest.delete();
- throw new DownloaderException(
- "Received bad data from web server");
- } else {
- Log.i(LOG_TAG, "web MD5 checksum matches.");
- }
- }
- }
- bytesToSkip -= Math.min(bytesToSkip, part.size);
- offsetOfCurrentPart += part.size;
- }
- } finally {
- quietClose(os);
- }
- }
-
- private void cleanup() throws IOException {
- File filtered = new File(mDataDir, LOCAL_FILTERED_FILE);
- noisyDelete(filtered);
- File tempConfig = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP);
- File realConfig = new File(mDataDir, LOCAL_CONFIG_FILE);
- tempConfig.renameTo(realConfig);
- }
-
- private void verify(Config config) throws DownloaderException,
- ClientProtocolException, IOException {
- Log.i(LOG_TAG, "Verifying...");
- String failFiles = null;
- for(Config.File file : config.mFiles) {
- if (! verifyFile(file, true) ) {
- if (failFiles == null) {
- failFiles = file.dest;
- } else {
- failFiles += " " + file.dest;
- }
- }
- }
- if (failFiles != null) {
- throw new DownloaderException(
- "Possible bad SD-Card. MD5 sum incorrect for file(s) "
- + failFiles);
- }
- }
-
- private boolean verifyFile(Config.File file, boolean deleteInvalid)
- throws FileNotFoundException, DownloaderException, IOException {
- Log.i(LOG_TAG, "verifying " + file.dest);
- File dest = new File(mDataDir, file.dest);
- if (! dest.exists()) {
- Log.e(LOG_TAG, "File does not exist: " + dest.toString());
- return false;
- }
- long fileSize = file.getSize();
- long destLength = dest.length();
- if (fileSize != destLength) {
- Log.e(LOG_TAG, "Length doesn't match. Expected " + fileSize
- + " got " + destLength);
- if (deleteInvalid) {
- dest.delete();
- return false;
- }
- }
- FileInputStream is = new FileInputStream(dest);
- try {
- for(Config.File.Part part : file.mParts) {
- if (part.md5 == null) {
- continue;
- }
- MessageDigest digest = createDigest();
- readIntoDigest(is, part.size, digest);
- String hash = getHash(digest);
- if (!hash.equalsIgnoreCase(part.md5)) {
- Log.e(LOG_TAG, "MD5 checksums don't match. " +
- part.src + " Expected "
- + part.md5 + " got " + hash);
- if (deleteInvalid) {
- quietClose(is);
- dest.delete();
- }
- return false;
- }
- }
- } finally {
- quietClose(is);
- }
- return true;
- }
-
- private void readIntoDigest(FileInputStream is, long bytesToRead,
- MessageDigest digest) throws IOException {
- while(bytesToRead > 0) {
- int chunkSize = (int) Math.min(mFileIOBuffer.length,
- bytesToRead);
- int bytesRead = is.read(mFileIOBuffer, 0, chunkSize);
- if (bytesRead < 0) {
- break;
- }
- updateDigest(digest, bytesRead);
- bytesToRead -= bytesRead;
- }
- }
-
- private MessageDigest createDigest() throws DownloaderException {
- MessageDigest digest;
- try {
- digest = MessageDigest.getInstance("MD5");
- } catch (NoSuchAlgorithmException e) {
- throw new DownloaderException("Couldn't create MD5 digest");
- }
- return digest;
- }
-
- private void updateDigest(MessageDigest digest, int bytesRead) {
- if (bytesRead == mFileIOBuffer.length) {
- digest.update(mFileIOBuffer);
- } else {
- // Work around an awkward API: Create a
- // new buffer with just the valid bytes
- byte[] temp = new byte[bytesRead];
- System.arraycopy(mFileIOBuffer, 0,
- temp, 0, bytesRead);
- digest.update(temp);
- }
- }
-
- private String getHash(MessageDigest digest) {
- StringBuilder builder = new StringBuilder();
- for(byte b : digest.digest()) {
- builder.append(Integer.toHexString((b >> 4) & 0xf));
- builder.append(Integer.toHexString(b & 0xf));
- }
- return builder.toString();
- }
-
-
- /**
- * Ensure we have sizes for all the items.
- * @param config
- * @throws ClientProtocolException
- * @throws IOException
- * @throws DownloaderException
- */
- private void getSizes(Config config)
- throws ClientProtocolException, IOException, DownloaderException {
- for (Config.File file : config.mFiles) {
- for(Config.File.Part part : file.mParts) {
- if (part.size < 0) {
- part.size = getSize(part.src);
- }
- }
- }
- mTotalExpectedSize = config.getSize();
- }
-
- private long getSize(String url) throws ClientProtocolException,
- IOException {
- url = normalizeUrl(url);
- Log.i(LOG_TAG, "Head " + url);
- HttpHead httpGet = new HttpHead(url);
- HttpResponse response = mHttpClient.execute(httpGet);
- if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
- throw new IOException("Unexpected Http status code "
- + response.getStatusLine().getStatusCode());
- }
- Header[] clHeaders = response.getHeaders("Content-Length");
- if (clHeaders.length > 0) {
- Header header = clHeaders[0];
- return Long.parseLong(header.getValue());
- }
- return -1;
- }
-
- private String normalizeUrl(String url) throws MalformedURLException {
- return (new URL(new URL(mFileConfigUrl), url)).toString();
- }
-
- private InputStream get(String url, long startOffset,
- long expectedLength)
- throws ClientProtocolException, IOException {
- url = normalizeUrl(url);
- Log.i(LOG_TAG, "Get " + url);
-
- mHttpGet = new HttpGet(url);
- int expectedStatusCode = HttpStatus.SC_OK;
- if (startOffset > 0) {
- String range = "bytes=" + startOffset + "-";
- if (expectedLength >= 0) {
- range += expectedLength-1;
- }
- Log.i(LOG_TAG, "requesting byte range " + range);
- mHttpGet.addHeader("Range", range);
- expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT;
- }
- HttpResponse response = mHttpClient.execute(mHttpGet);
- long bytesToSkip = 0;
- int statusCode = response.getStatusLine().getStatusCode();
- if (statusCode != expectedStatusCode) {
- if ((statusCode == HttpStatus.SC_OK)
- && (expectedStatusCode
- == HttpStatus.SC_PARTIAL_CONTENT)) {
- Log.i(LOG_TAG, "Byte range request ignored");
- bytesToSkip = startOffset;
- } else {
- throw new IOException("Unexpected Http status code "
- + statusCode + " expected "
- + expectedStatusCode);
- }
- }
- HttpEntity entity = response.getEntity();
- InputStream is = entity.getContent();
- if (bytesToSkip > 0) {
- is.skip(bytesToSkip);
- }
- return is;
- }
-
- private File download(String src, String dest)
- throws DownloaderException, ClientProtocolException, IOException {
- File destFile = new File(mDataDir, dest);
- FileOutputStream os = openOutput(dest, false);
- try {
- downloadPart(src, os, 0, -1, null);
- } finally {
- os.close();
- }
- return destFile;
- }
-
- private void downloadPart(String src, FileOutputStream os,
- long startOffset, long expectedLength, MessageDigest digest)
- throws ClientProtocolException, IOException, DownloaderException {
- boolean lengthIsKnown = expectedLength >= 0;
- if (startOffset < 0) {
- throw new IllegalArgumentException("Negative startOffset:"
- + startOffset);
- }
- if (lengthIsKnown && (startOffset > expectedLength)) {
- throw new IllegalArgumentException(
- "startOffset > expectedLength" + startOffset + " "
- + expectedLength);
- }
- InputStream is = get(src, startOffset, expectedLength);
- try {
- long bytesRead = downloadStream(is, os, digest);
- if (lengthIsKnown) {
- long expectedBytesRead = expectedLength - startOffset;
- if (expectedBytesRead != bytesRead) {
- Log.e(LOG_TAG, "Bad file transfer from server: " + src
- + " Expected " + expectedBytesRead
- + " Received " + bytesRead);
- throw new DownloaderException(
- "Incorrect number of bytes received from server");
- }
- }
- } finally {
- is.close();
- mHttpGet = null;
- }
- }
-
- private FileOutputStream openOutput(String dest, boolean append)
- throws FileNotFoundException, DownloaderException {
- File destFile = new File(mDataDir, dest);
- File parent = destFile.getParentFile();
- if (! parent.exists()) {
- parent.mkdirs();
- }
- if (! parent.exists()) {
- throw new DownloaderException("Could not create directory "
- + parent.toString());
- }
- FileOutputStream os = new FileOutputStream(destFile, append);
- return os;
- }
-
- private FileInputStream openInput(String src)
- throws FileNotFoundException, DownloaderException {
- File srcFile = new File(mDataDir, src);
- File parent = srcFile.getParentFile();
- if (! parent.exists()) {
- parent.mkdirs();
- }
- if (! parent.exists()) {
- throw new DownloaderException("Could not create directory "
- + parent.toString());
- }
- return new FileInputStream(srcFile);
- }
-
- private long downloadStream(InputStream is, FileOutputStream os,
- MessageDigest digest)
- throws DownloaderException, IOException {
- long totalBytesRead = 0;
- while(true){
- if (Thread.interrupted()) {
- Log.i(LOG_TAG, "downloader thread interrupted.");
- mHttpGet.abort();
- throw new DownloaderException("Thread interrupted");
- }
- int bytesRead = is.read(mFileIOBuffer);
- if (bytesRead < 0) {
- break;
- }
- if (digest != null) {
- updateDigest(digest, bytesRead);
- }
- totalBytesRead += bytesRead;
- os.write(mFileIOBuffer, 0, bytesRead);
- mDownloadedSize += bytesRead;
- int progress = (int) (Math.min(mTotalExpectedSize,
- mDownloadedSize * 10000 /
- Math.max(1, mTotalExpectedSize)));
- if (progress != mReportedProgress) {
- mReportedProgress = progress;
- reportProgress(progress);
- }
- }
- return totalBytesRead;
- }
-
- private AndroidHttpClient mHttpClient;
- private HttpGet mHttpGet;
- private String mFileConfigUrl;
- private String mConfigVersion;
- private String mDataPath;
- private File mDataDir;
- private String mUserAgent;
- private long mTotalExpectedSize;
- private long mDownloadedSize;
- private int mReportedProgress;
- private final static int CHUNK_SIZE = 32 * 1024;
- byte[] mFileIOBuffer = new byte[CHUNK_SIZE];
- }
-
- private final static String LOG_TAG = "Downloader";
- private TextView mProgress;
- private TextView mTimeRemaining;
- private final DecimalFormat mPercentFormat = new DecimalFormat("0.00 %");
- private long mStartTime;
- private Thread mDownloadThread;
- private boolean mSuppressErrorMessages;
-
- private final static long MS_PER_SECOND = 1000;
- private final static long MS_PER_MINUTE = 60 * 1000;
- private final static long MS_PER_HOUR = 60 * 60 * 1000;
- private final static long MS_PER_DAY = 24 * 60 * 60 * 1000;
-
- private final static String LOCAL_CONFIG_FILE = ".downloadConfig";
- private final static String LOCAL_CONFIG_FILE_TEMP = ".downloadConfig_temp";
- private final static String LOCAL_FILTERED_FILE = ".downloadConfig_filtered";
- private final static String EXTRA_CUSTOM_TEXT = "DownloaderActivity_custom_text";
- private final static String EXTRA_FILE_CONFIG_URL = "DownloaderActivity_config_url";
- private final static String EXTRA_CONFIG_VERSION = "DownloaderActivity_config_version";
- private final static String EXTRA_DATA_PATH = "DownloaderActivity_data_path";
- private final static String EXTRA_USER_AGENT = "DownloaderActivity_user_agent";
-
- private final static int MSG_DOWNLOAD_SUCCEEDED = 0;
- private final static int MSG_DOWNLOAD_FAILED = 1;
- private final static int MSG_REPORT_PROGRESS = 2;
-
- private final Handler mHandler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case MSG_DOWNLOAD_SUCCEEDED:
- onDownloadSucceeded();
- break;
- case MSG_DOWNLOAD_FAILED:
- onDownloadFailed((String) msg.obj);
- break;
- case MSG_REPORT_PROGRESS:
- onReportProgress(msg.arg1);
- break;
- default:
- throw new IllegalArgumentException("Unknown message id "
- + msg.what);
- }
- }
-
- };
-
-}
diff --git a/samples/quake/src/com/android/quake/llvm/PreconditionActivityHelper.java b/samples/quake/src/com/android/quake/llvm/PreconditionActivityHelper.java
deleted file mode 100644
index 4e9b26c..0000000
--- a/samples/quake/src/com/android/quake/llvm/PreconditionActivityHelper.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package com.android.quake.llvm;
-
-import android.app.Activity;
-import android.content.Intent;
-
-/**
- * Usage:
- *
- * Intent intent = PreconditionActivityHelper.createPreconditionIntent(
- * activity, WaitActivity.class);
- * // Optionally add extras to pass arguments to the intent
- * intent.putExtra(Utils.EXTRA_ACCOUNT, account);
- * PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent);
- *
- * // And in the wait activity:
- * PreconditionActivityHelper.startOriginalActivityAndFinish(this);
- *
- */
-
-public class PreconditionActivityHelper {
- /**
- * Create a precondition activity intent.
- * @param activity the original activity
- * @param preconditionActivityClazz the precondition activity's class
- * @return an intent which will launch the precondition activity.
- */
- public static Intent createPreconditionIntent(Activity activity,
- Class preconditionActivityClazz) {
- Intent newIntent = new Intent();
- newIntent.setClass(activity, preconditionActivityClazz);
- newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent());
- return newIntent;
- }
-
- /**
- * Start the precondition activity using a given intent, which should
- * have been created by calling createPreconditionIntent.
- * @param activity
- * @param intent
- */
- public static void startPreconditionActivityAndFinish(Activity activity,
- Intent intent) {
- activity.startActivity(intent);
- activity.finish();
- }
-
- /**
- * Start the original activity, and finish the precondition activity.
- * @param preconditionActivity
- */
- public static void startOriginalActivityAndFinish(
- Activity preconditionActivity) {
- preconditionActivity.startActivity(
- (Intent) preconditionActivity.getIntent()
- .getParcelableExtra(EXTRA_WRAPPED_INTENT));
- preconditionActivity.finish();
- }
-
- static private final String EXTRA_WRAPPED_INTENT =
- "PreconditionActivityHelper_wrappedIntent";
-}
diff --git a/samples/quake/src/com/android/quake/llvm/QuakeActivity.java b/samples/quake/src/com/android/quake/llvm/QuakeActivity.java
deleted file mode 100644
index a264902..0000000
--- a/samples/quake/src/com/android/quake/llvm/QuakeActivity.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.quake.llvm;
-
-import android.app.Activity;
-import android.content.res.Resources;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.WindowManager;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.MenuInflater;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import android.view.View;
-
-
-public class QuakeActivity extends Activity {
-
- QuakeView mQuakeView;
-
- static QuakeLib mQuakeLib;
-
- boolean mKeepScreenOn = true;
-
- @Override protected void onCreate(Bundle icicle) {
- Log.i("QuakeActivity", "onCreate");
- super.onCreate(icicle);
- if (USE_DOWNLOADER) {
- if (! DownloaderActivity.ensureDownloaded(this,
- getString(R.string.quake_customDownloadText), FILE_CONFIG_URL,
- CONFIG_VERSION, SDCARD_DATA_PATH, USER_AGENT)) {
- return;
- }
- }
-
- if (foundQuakeData()) {
- byte[] pgm = null;
- int pgmLength = 0;
- if (QuakeLib.gdk())
- {
- // HACK: create faked view in order to read bitcode in resource
- View view = new View(getApplication());
-
- // read bitcode in res
- InputStream is = view.getResources().openRawResource(R.raw.libquake_portable);
- try {
- try {
- pgm = new byte[1024];
- pgmLength = 0;
-
- while(true) {
- int bytesLeft = pgm.length - pgmLength;
- if (bytesLeft == 0) {
- byte[] buf2 = new byte[pgm.length * 2];
- System.arraycopy(pgm, 0, buf2, 0, pgm.length);
- pgm = buf2;
- bytesLeft = pgm.length - pgmLength;
- }
- int bytesRead = is.read(pgm, pgmLength, bytesLeft);
- if (bytesRead <= 0) {
- break;
- }
- pgmLength += bytesRead;
- }
- } finally {
- is.close();
- }
- } catch(IOException e) {
- throw new Resources.NotFoundException();
- }
- }
- //
- if (mQuakeLib == null) {
- mQuakeLib = new QuakeLib(pgm, pgmLength);
- if(! mQuakeLib.init()) {
- setContentView(new QuakeViewNoData(
- getApplication(),
- QuakeViewNoData.E_INITFAILED));
- return;
- }
- }
-
- if (mKeepScreenOn) {
- getWindow().setFlags(
- WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
- WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- }
-
- if (mQuakeView == null) {
- mQuakeView = new
- QuakeView(getApplication());
- mQuakeView.setQuakeLib(mQuakeLib);
- }
- setContentView(mQuakeView);
- }
- else {
- setContentView(new QuakeViewNoData(getApplication(),
- QuakeViewNoData.E_NODATA));
- }
- }
-
- @Override protected void onPause() {
- super.onPause();
- if (mQuakeView != null) {
- mQuakeView.onPause();
- }
- }
-
- @Override protected void onResume() {
- super.onResume();
- if (mQuakeView != null) {
- mQuakeView.onResume();
- }
- }
-
- @Override protected void onDestroy() {
- super.onDestroy();
- if (mQuakeLib != null) {
- mQuakeLib.quit();
- }
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.menu, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.switch_mode:
- if (mQuakeView != null) {
- mQuakeView.switchMode();
- }
- return true;
- default:
- return super.onOptionsItemSelected(item);
- }
- }
-
- private boolean foundQuakeData() {
- return fileExists(SDCARD_DATA_PATH + PAK0_PATH)
- || fileExists(INTERNAL_DATA_PATH + PAK0_PATH);
- }
-
- private boolean fileExists(String s) {
- File f = new File(s);
- return f.exists();
- }
-
- private final static boolean USE_DOWNLOADER = false;
-
- private final static String FILE_CONFIG_URL =
- "http://example.com/android/quake/quake11.config";
- private final static String CONFIG_VERSION = "1.1";
- private final static String SDCARD_DATA_PATH = "/sdcard/data/quake";
- private final static String INTERNAL_DATA_PATH = "/data/quake";
- private final static String PAK0_PATH = "/id1/pak0.pak";
- private final static String USER_AGENT = "Android Quake Downloader";
-
-}
diff --git a/samples/quake/src/com/android/quake/llvm/QuakeLib.java b/samples/quake/src/com/android/quake/llvm/QuakeLib.java
deleted file mode 100644
index 5bdcfc7..0000000
--- a/samples/quake/src/com/android/quake/llvm/QuakeLib.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.quake.llvm;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import android.content.res.Resources;
-
-// Wrapper for native quake application
-
-public class QuakeLib {
-
- public static final int KEY_PRESS = 1;
- public static final int KEY_RELEASE = 0;
-
- public static final int MOTION_DOWN = 0;
- public static final int MOTION_UP = 1;
- public static final int MOTION_MOVE = 2;
- public static final int MOTION_CANCEL = 3;
-
- // copied from Quake keys.h
- // these are the key numbers that should be passed to Key_Event
- //
- //
- // these are the key numbers that should be passed to Key_Event
- //
- public static final int K_TAB = 9;
- public static final int K_ENTER = 13;
- public static final int K_ESCAPE = 27;
- public static final int K_SPACE = 32;
-
- // normal keys should be passed as lowercased ascii
-
- public static final int K_BACKSPACE = 127;
- public static final int K_UPARROW = 128;
- public static final int K_DOWNARROW = 129;
- public static final int K_LEFTARROW = 130;
- public static final int K_RIGHTARROW = 131;
-
- public static final int K_ALT = 132;
- public static final int K_CTRL = 133;
- public static final int K_SHIFT = 134;
- public static final int K_F1 = 135;
- public static final int K_F2 = 136;
- public static final int K_F3 = 137;
- public static final int K_F4 = 138;
- public static final int K_F5 = 139;
- public static final int K_F6 = 140;
- public static final int K_F7 = 141;
- public static final int K_F8 = 142;
- public static final int K_F9 = 143;
- public static final int K_F10 = 144;
- public static final int K_F11 = 145;
- public static final int K_F12 = 146;
- public static final int K_INS = 147;
- public static final int K_DEL = 148;
- public static final int K_PGDN = 149;
- public static final int K_PGUP = 150;
- public static final int K_HOME = 151;
- public static final int K_END = 152;
-
- public static final int K_PAUSE = 255;
-
- //
- // mouse buttons generate virtual keys
- //
- public static final int K_MOUSE1 = 200;
- public static final int K_MOUSE2 = 201;
- public static final int K_MOUSE3 = 202;
-
- //
- // joystick buttons
- //
- public static final int K_JOY1 = 203;
- public static final int K_JOY2 = 204;
- public static final int K_JOY3 = 205;
- public static final int K_JOY4 = 206;
-
- //
- // aux keys are for multi-buttoned joysticks to generate so they can use
- // the normal binding process
- //
- public static final int K_AUX1 = 207;
- public static final int K_AUX2 = 208;
- public static final int K_AUX3 = 209;
- public static final int K_AUX4 = 210;
- public static final int K_AUX5 = 211;
- public static final int K_AUX6 = 212;
- public static final int K_AUX7 = 213;
- public static final int K_AUX8 = 214;
- public static final int K_AUX9 = 215;
- public static final int K_AUX10 = 216;
- public static final int K_AUX11 = 217;
- public static final int K_AUX12 = 218;
- public static final int K_AUX13 = 219;
- public static final int K_AUX14 = 220;
- public static final int K_AUX15 = 221;
- public static final int K_AUX16 = 222;
- public static final int K_AUX17 = 223;
- public static final int K_AUX18 = 224;
- public static final int K_AUX19 = 225;
- public static final int K_AUX20 = 226;
- public static final int K_AUX21 = 227;
- public static final int K_AUX22 = 228;
- public static final int K_AUX23 = 229;
- public static final int K_AUX24 = 230;
- public static final int K_AUX25 = 231;
- public static final int K_AUX26 = 232;
- public static final int K_AUX27 = 233;
- public static final int K_AUX28 = 234;
- public static final int K_AUX29 = 235;
- public static final int K_AUX30 = 236;
- public static final int K_AUX31 = 237;
- public static final int K_AUX32 = 238;
-
- // JACK: Intellimouse(c) Mouse Wheel Support
-
- public static final int K_MWHEELUP = 239;
- public static final int K_MWHEELDOWN = 240;
-
- static {
- System.loadLibrary("quake");
- }
-
- public QuakeLib(byte[] pgm, int pgmLength) {
- if (gdk())
- compile_bc(pgm, pgmLength);
- }
-
- public static native boolean gdk();
- private native boolean compile_bc(byte[] pgm, int pgmLength);
-
- public native boolean init();
-
- /**
- * Used to report key events
- * @param type KEY_PRESS or KEY_RELEASE
- * @param value the key code.
- * @return true if the event was handled.
- */
- public native boolean event(int type, int value);
-
- /**
- * Used to report touch-screen events
- * @param eventTime the time the event happened
- * @param action the kind of action being performed -- one of either
- * {@link #MOTION_DOWN}, {@link #MOTION_MOVE}, {@link #MOTION_UP},
- * or {@link #MOTION_CANCEL}
- * @param x the x coordinate in pixels
- * @param y the y coordinate in pixels
- * @param pressure the pressure 0..1, can be more than 1 sometimes
- * @param size the size of the area pressed (radius in X or Y)
- * @param deviceId the id of the device generating the events
- * @return true if the event was handled.
- */
- public native boolean motionEvent(long eventTime, int action,
- float x, float y, float pressure, float size, int deviceId);
-
- /**
- * Used to report trackball events
- * @param eventTime the time the event happened
- * @param action the kind of action being performed -- one of either
- * {@link #MOTION_DOWN}, {@link #MOTION_MOVE}, {@link #MOTION_UP},
- * or {@link #MOTION_CANCEL}
- * @param x the x motion in pixels
- * @param y the y motion in pixels
- * @return true if the event was handled.
- */
- public native boolean trackballEvent(long eventTime, int action,
- float x, float y);
- /**
- * @param width the current view width
- * @param height the current view height
- * @return true if quake is in "game" mode, false if it is in "menu" or
- * "typing" mode.
- */
- public native boolean step(int width, int height);
-
- /**
- * Tell Quake to quit. It will write out its config files and so forth.
- */
- public native void quit();
-}
diff --git a/samples/quake/src/com/android/quake/llvm/QuakeView.java b/samples/quake/src/com/android/quake/llvm/QuakeView.java
deleted file mode 100644
index 32e0baf..0000000
--- a/samples/quake/src/com/android/quake/llvm/QuakeView.java
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.quake.llvm;
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * 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.
- */
-
-
-import android.content.Context;
-import android.opengl.GLSurfaceView;
-import android.opengl.GLUtils;
-import android.util.AttributeSet;
-import android.util.Log;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.graphics.Paint;
-
-import javax.microedition.khronos.egl.EGL10;
-import javax.microedition.khronos.egl.EGLConfig;
-import javax.microedition.khronos.opengles.GL10;
-
-import java.io.InputStream;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.BufferedOutputStream;
-import java.io.IOException;
-
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.Color;
-import android.graphics.drawable.Drawable;
-
-/**
- * An implementation of SurfaceView that uses the dedicated surface for
- * displaying an OpenGL animation. This allows the animation to run in a
- * separate thread, without requiring that it be driven by the update mechanism
- * of the view hierarchy.
- *
- * The application-specific rendering code is delegated to a GLView.Renderer
- * instance.
- */
-class QuakeView extends GLSurfaceView {
- QuakeView(Context context) {
- super(context);
- init();
- }
-
- public QuakeView(Context context, AttributeSet attrs) {
- super(context, attrs);
- init();
- }
-
- private void init() {
- // We want events.
- setFocusable(true);
- setFocusableInTouchMode(true);
- requestFocus();
- // bitmap, canvas, and paint for fps
- mPaint = new Paint();
- mPaint.setTextSize(40);
- mBitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.RGB_565);
- mBitmap.eraseColor(Color.BLACK);
- mCanvas = new Canvas(mBitmap);
- mTextures = new int[1];
- }
-
- public void setQuakeLib(QuakeLib quakeLib) {
- mQuakeLib = quakeLib;
- setRenderer(new QuakeRenderer());
- }
-
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (!weWantThisKeyCode(keyCode)) {
- return super.onKeyDown(keyCode, event);
- }
- switch (keyCode) {
- case KeyEvent.KEYCODE_ALT_RIGHT:
- case KeyEvent.KEYCODE_ALT_LEFT:
- mAltKeyPressed = true;
- break;
- case KeyEvent.KEYCODE_SHIFT_RIGHT:
- case KeyEvent.KEYCODE_SHIFT_LEFT:
- mShiftKeyPressed = true;
- break;
- }
- queueKeyEvent(QuakeLib.KEY_PRESS,
- keyCodeToQuakeCode(keyCode));
- return true;
- }
-
- @Override
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- if (!weWantThisKeyCode(keyCode)) {
- return super.onKeyUp(keyCode, event);
- }
- switch (keyCode) {
- case KeyEvent.KEYCODE_ALT_RIGHT:
- case KeyEvent.KEYCODE_ALT_LEFT:
- mAltKeyPressed = false;
- break;
- case KeyEvent.KEYCODE_SHIFT_RIGHT:
- case KeyEvent.KEYCODE_SHIFT_LEFT:
- mShiftKeyPressed = false;
- break; }
- queueKeyEvent(QuakeLib.KEY_RELEASE,
- keyCodeToQuakeCode(keyCode));
- return true;
- }
-
- @Override
- public boolean onTrackballEvent(MotionEvent event) {
- if (!mGameMode) {
- return super.onTrackballEvent(event);
- }
- queueTrackballEvent(event);
- return true;
- }
-
- private boolean weWantThisKeyCode(int keyCode) {
- return (keyCode != KeyEvent.KEYCODE_VOLUME_UP) &&
- (keyCode != KeyEvent.KEYCODE_VOLUME_DOWN) &&
- (keyCode != KeyEvent.KEYCODE_SEARCH) &&
- (keyCode != KeyEvent.KEYCODE_MENU);
- }
-
- @Override
- public boolean dispatchTouchEvent(MotionEvent ev) {
- queueMotionEvent(ev);
- return true;
- }
-
- private int keyCodeToQuakeCode(int keyCode) {
- int key = 0;
- if (keyCode >= sKeyCodeToQuakeCode.length) {
- return 0;
- }
- if (mAltKeyPressed) {
- key = sKeyCodeToQuakeCodeAlt[keyCode];
- if (key == 0) {
- key = sKeyCodeToQuakeCodeShift[keyCode];
- if (key == 0) {
- key = sKeyCodeToQuakeCode[keyCode];
- }
- }
- } else if (mShiftKeyPressed) {
- key = sKeyCodeToQuakeCodeShift[keyCode];
- if (key == 0) {
- key = sKeyCodeToQuakeCode[keyCode];
- }
- } else {
- key = sKeyCodeToQuakeCode[keyCode];
- }
- if (key == 0) {
- key = '$';
- }
- return key;
- }
-
- public void queueKeyEvent(final int type, final int keyCode) {
- queueEvent(
- new Runnable() {
- public void run() {
- mQuakeLib.event(type, keyCode);
- }
- });
- }
-
- public void queueMotionEvent(final MotionEvent ev) {
- queueEvent(
- new Runnable() {
- public void run() {
- mQuakeLib.motionEvent(ev.getEventTime(),
- ev.getAction(),
- ev.getX(), ev.getY(),
- ev.getPressure(), ev.getSize(),
- ev.getDeviceId());
- }
- });
- }
-
- public void queueTrackballEvent(final MotionEvent ev) {
- queueEvent(
- new Runnable() {
- public void run() {
- mQuakeLib.trackballEvent(ev.getEventTime(),
- ev.getAction(),
- ev.getX(), ev.getY());
- }
- });
- }
-
- byte[] pgm;
- int pgmLength;
-
- private boolean mode = false;
- private Paint mPaint = null;
- private Bitmap mBitmap = null;
- private Canvas mCanvas = null;
- private int[] mTextures = null;
-
- public void switchMode()
- {
- mode = !mode;
- }
-
- private boolean mShiftKeyPressed;
- private boolean mAltKeyPressed;
-
- private static final int[] sKeyCodeToQuakeCode = {
- '$', QuakeLib.K_ESCAPE, '$', '$', QuakeLib.K_ESCAPE, '$', '$', '0', // 0.. 7
- '1', '2', '3', '4', '5', '6', '7', '8', // 8..15
- '9', '$', '$', QuakeLib.K_UPARROW, QuakeLib.K_DOWNARROW, QuakeLib.K_LEFTARROW, QuakeLib.K_RIGHTARROW, QuakeLib.K_ENTER, // 16..23
- '$', '$', '$', QuakeLib.K_HOME, '$', 'a', 'b', 'c', // 24..31
-
- 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', // 32..39
- 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', // 40..47
- 't', 'u', 'v', 'w', 'x', 'y', 'z', ',', // 48..55
- '.', QuakeLib.K_ALT, QuakeLib.K_ALT, QuakeLib.K_SHIFT, QuakeLib.K_SHIFT, QuakeLib.K_TAB, ' ', '$', // 56..63
- '$', '$', QuakeLib.K_ENTER, QuakeLib.K_BACKSPACE, '`', '-', '=', '[', // 64..71
- ']', '\\', ';', '\'', '/', QuakeLib.K_CTRL, '#', '$', // 72..79
- QuakeLib.K_HOME, '$', QuakeLib.K_ESCAPE, '$', '$', 0, 0, 0, 0, // 80..
- 0, 0, QuakeLib.K_PGUP, QuakeLib.K_PGDN, 0, 0, 0, 0, 0, 0, // 90..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 100..
- 0, QuakeLib.K_ESCAPE, QuakeLib.K_DEL, QuakeLib.K_CTRL, QuakeLib.K_CTRL, 0, 0, 0, 0, 0, // 110..
- 0, 0, QuakeLib.K_HOME, QuakeLib.K_END, QuakeLib.K_INS, 0, 0, 0, 0, 0, // 120..
- 0, QuakeLib.K_F1, QuakeLib.K_F2, QuakeLib.K_F3, QuakeLib.K_F4, // 130..134
- QuakeLib.K_F5, QuakeLib.K_F6, QuakeLib.K_F7, QuakeLib.K_F8, QuakeLib.K_F9, // 135..139
- QuakeLib.K_F10, QuakeLib.K_F11, QuakeLib.K_F12, 0, 0, 0, 0, 0, 0, 0, // 140..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 180..
- };
-
- private static final int sKeyCodeToQuakeCodeShift[] =
- {
- 0, 0, 0, 0, 0, 0, 0, ')', // 0.. 7
- '!', '@', '#', '$', '%', '^', '&', '*', // 8..15
- '(', 0, 0, 0, 0, 0, 0, 0, // 16..23
- 0, 0, 0, 0, 0, 0, ']', 0, // 24..31
-
- '\\', '_', '{', '}', ':', '-', ';', '"', // 32..39
- '\'', '>', '<', '+', '=', 0, 0, '|', // 40..47
- 0, 0, '[', '`', 0, 0, QuakeLib.K_PAUSE, ';', // 48..55
- 0, 0, 0, 0, 0, 0, 0, 0, // 56..63
- 0, 0, 0, 0, 0, 0, 0, 0, // 64..71
- 0, 0, '?', '0', 0, QuakeLib.K_CTRL, 0, 0, // 72..79
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80..
- 0, 0, QuakeLib.K_PGUP, QuakeLib.K_PGDN, 0, 0, 0, 0, 0, 0, // 90..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 100..
- 0, QuakeLib.K_ESCAPE, QuakeLib.K_DEL, QuakeLib.K_CTRL, QuakeLib.K_CTRL, 0, 0, 0, 0, 0, // 110..
- 0, 0, QuakeLib.K_HOME, QuakeLib.K_END, QuakeLib.K_INS, 0, 0, 0, 0, 0, // 120..
- 0, QuakeLib.K_F1, QuakeLib.K_F2, QuakeLib.K_F3, QuakeLib.K_F4, // 130..134
- QuakeLib.K_F5, QuakeLib.K_F6, QuakeLib.K_F7, QuakeLib.K_F8, QuakeLib.K_F9, // 135..139
- QuakeLib.K_F10, QuakeLib.K_F11, QuakeLib.K_F12, 0, 0, 0, 0, 0, 0, 0, // 140..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 180..
- };
-
- private static final int sKeyCodeToQuakeCodeAlt[] =
- {
- 0, 0, 0, 0, 0, 0, 0, QuakeLib.K_F10, // 0.. 7
- QuakeLib.K_F1, QuakeLib.K_F2, QuakeLib.K_F3, QuakeLib.K_F4, QuakeLib.K_F5, QuakeLib.K_F6, QuakeLib.K_F7, QuakeLib.K_F8, // 8..15
- QuakeLib.K_F9, 0, 0, 0, 0, 0, 0, 0, // 16..23
- 0, 0, 0, 0, 0, 0, 0, 0, // 24..31
-
- 0, 0, 0, 0, 0, 0, 0, 0, // 32..39
- 0, 0, 0, 0, 0, 0, 0, 0, // 40..47
- QuakeLib.K_F11, 0, 0, 0, 0, QuakeLib.K_F12, 0, 0, // 48..55
- 0, 0, 0, 0, 0, 0, 0, 0, // 56..63
- 0, 0, 0, 0, 0, 0, 0, 0, // 64..71
- 0, 0, 0, 0, 0, 0, 0, 0, // 72..79
- 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80..
- 0, 0, QuakeLib.K_PGUP, QuakeLib.K_PGDN, 0, 0, 0, 0, 0, 0, // 90..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 100..
- 0, QuakeLib.K_ESCAPE, QuakeLib.K_DEL, QuakeLib.K_CTRL, QuakeLib.K_CTRL, 0, 0, 0, 0, 0, // 110..
- 0, 0, QuakeLib.K_HOME, QuakeLib.K_END, QuakeLib.K_INS, 0, 0, 0, 0, 0, // 120..
- 0, QuakeLib.K_F1, QuakeLib.K_F2, QuakeLib.K_F3, QuakeLib.K_F4, // 130..134
- QuakeLib.K_F5, QuakeLib.K_F6, QuakeLib.K_F7, QuakeLib.K_F8, QuakeLib.K_F9, // 135..139
- QuakeLib.K_F10, QuakeLib.K_F11, QuakeLib.K_F12, 0, 0, 0, 0, 0, 0, 0, // 140..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170..
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // 180..
- };
-
- private class QuakeRenderer implements GLSurfaceView.Renderer {
- private static final String TAG = "QuakeRenderer";
- public void onDrawFrame(GL10 gl) {
- if (mWidth != 0 && mHeight != 0) {
- mGameMode = mQuakeLib.step(mWidth, mHeight);
- // ToDo: draw fps
- if (false) {
- ////ToDo: the following doesn't work
- mCanvas.drawText((mode ? "LLVM" : "GCC") + " Frame: " + Integer.toString(20), 100, 100, mPaint);
- //Generate one texture pointer...
- //gl.glDeleteTextures(1, mTextures, 1);
- gl.glGenTextures(1, mTextures, 0);
- //...and bind it to our array
- gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
- //Create Nearest Filtered Texture
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
- //Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
- //Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
- GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
- //Clean up
- //mBitmap.recycle();
- } else if (false) {
- ////ToDo: the following doesn't work either
- //Create an empty, mutable bitmap
- Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
- //get a canvas to paint over the bitmap
- Canvas canvas = new Canvas(bitmap);
- bitmap.eraseColor(0);
- //get a background image from resources
- //note the image format must match the bitmap format
- //Drawable background = context.getResources().getDrawable(R.drawable.background);
- //background.setBounds(0, 0, 256, 256);
- //background.draw(canvas); // draw the background to our bitmap
- //Draw the text
- Paint textPaint = new Paint();
- textPaint.setTextSize(32);
- textPaint.setAntiAlias(true);
- textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
- //draw the text centered
- canvas.drawText("Hello World", 16,112, textPaint);
- //Generate one texture pointer...
- gl.glGenTextures(1, mTextures, 0);
- //...and bind it to our array
- gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextures[0]);
- //Create Nearest Filtered Texture
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
- //Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
- gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);
- //Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
- GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
- //Clean up
- bitmap.recycle();
- }
- }
- }
-
- public void onSurfaceChanged(GL10 gl, int width, int height) {
- mWidth = width;
- mHeight = height;
- mQuakeLib.init();
- }
-
- public void onSurfaceCreated(GL10 gl, EGLConfig config) {
- // Do nothing.
- }
- private int mWidth;
- private int mHeight;
- }
-
- private QuakeLib mQuakeLib;
- private boolean mGameMode;
-}
-
diff --git a/samples/quake/src/com/android/quake/llvm/QuakeViewNoData.java b/samples/quake/src/com/android/quake/llvm/QuakeViewNoData.java
deleted file mode 100644
index 93266a9..0000000
--- a/samples/quake/src/com/android/quake/llvm/QuakeViewNoData.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * 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.quake.llvm;
-
-import android.view.View;
-import android.content.Context;
-import android.graphics.Paint;
-import android.graphics.Canvas;
-
-public class QuakeViewNoData extends View {
- public QuakeViewNoData(Context context, int reason)
- {
- super(context);
- mReason = reason;
- }
-
- public static final int E_NODATA = 1;
- public static final int E_INITFAILED = 2;
-
- @Override
- protected void onDraw(Canvas canvas) {
- Paint paint = new Paint();
- paint.setColor(0xffffffff);
- paint.setStyle(Paint.Style.FILL);
- canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
- paint.setColor(0xff000000);
- switch(mReason)
- {
- case E_NODATA:
- canvas.drawText("Missing data files. Looking for one of:",
- 10.0f, 20.0f, paint);
- canvas.drawText("/sdcard/data/quake/id1/pak0.pak",
- 10.0f, 35.0f, paint);
- canvas.drawText("/data/quake/id1/pak0.pak",
- 10.0f, 50.0f, paint);
- canvas.drawText("Please copy a pak file to the device and reboot.",
- 10.0f, 65.0f, paint);
- break;
- case E_INITFAILED:
- canvas.drawText("Quake C library initialization failed.",
- 10.0f, 20.0f, paint);
- canvas.drawText("Try stopping and restarting the simulator.",
- 10.0f, 35.0f, paint);
- break;
- }
- }
-
- private int mReason;
-
-}