mirror of
https://github.com/cocos/cocos4.git
synced 2026-12-05 19:12:40 +08:00
Merge branch 'v3.5.0' into v3.6_merge_v3.5
This commit is contained in:
@@ -48,6 +48,7 @@ import java.util.concurrent.TimeUnit;
|
||||
// and https://github.com/PatriceJiang/okio/tree/cocos2dx-rename-1.15.0
|
||||
import org.cocos2dx.okhttp3.Call;
|
||||
import org.cocos2dx.okhttp3.Callback;
|
||||
import org.cocos2dx.okhttp3.Dispatcher;
|
||||
import org.cocos2dx.okhttp3.OkHttpClient;
|
||||
import org.cocos2dx.okhttp3.Request;
|
||||
import org.cocos2dx.okhttp3.Response;
|
||||
@@ -56,6 +57,7 @@ public class CocosDownloader {
|
||||
|
||||
private int _id;
|
||||
private OkHttpClient _httpClient = null;
|
||||
private static Dispatcher dispatcher = null;
|
||||
|
||||
private String _tempFileNameSuffix;
|
||||
private int _countOfMaxProcessingTasks;
|
||||
@@ -91,14 +93,20 @@ public class CocosDownloader {
|
||||
CocosDownloader downloader = new CocosDownloader();
|
||||
downloader._id = id;
|
||||
|
||||
if(dispatcher == null) {
|
||||
dispatcher = new Dispatcher();
|
||||
}
|
||||
|
||||
if (timeoutInSeconds > 0) {
|
||||
downloader._httpClient = new OkHttpClient().newBuilder()
|
||||
.dispatcher(dispatcher)
|
||||
.followRedirects(true)
|
||||
.followSslRedirects(true)
|
||||
.callTimeout(timeoutInSeconds, TimeUnit.SECONDS)
|
||||
.build();
|
||||
} else {
|
||||
downloader._httpClient = new OkHttpClient().newBuilder()
|
||||
.dispatcher(dispatcher)
|
||||
.followRedirects(true)
|
||||
.followSslRedirects(true)
|
||||
.build();
|
||||
@@ -179,6 +187,17 @@ public class CocosDownloader {
|
||||
|
||||
final Request request = builder.build();
|
||||
task = downloader._httpClient.newCall(request);
|
||||
if (null == task) {
|
||||
final String errStr = "Can't create DownloadTask for " + url;
|
||||
CocosHelper.runOnGameThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
downloader.nativeOnFinish(downloader._id, id, 0, errStr, null);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
downloader._taskMap.put(id, task);
|
||||
}
|
||||
task.enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(Call call, IOException e) {
|
||||
@@ -200,7 +219,7 @@ public class CocosDownloader {
|
||||
if (file.exists() && file.isFile()) {
|
||||
file.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
downloader.onFinish(id, -2, response.message(), null);
|
||||
return;
|
||||
}
|
||||
@@ -289,18 +308,6 @@ public class CocosDownloader {
|
||||
}
|
||||
});
|
||||
} while (false);
|
||||
|
||||
if (null == task) {
|
||||
final String errStr = "Can't create DownloadTask for " + url;
|
||||
CocosHelper.runOnGameThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
downloader.nativeOnFinish(downloader._id, id, 0, errStr, null);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
downloader._taskMap.put(id, task);
|
||||
}
|
||||
}
|
||||
};
|
||||
downloader.enqueueTask(taskRunnable);
|
||||
@@ -355,9 +362,9 @@ public class CocosDownloader {
|
||||
|
||||
private void runNextTaskIfExists() {
|
||||
synchronized (_taskQueue) {
|
||||
while (_runningTaskCount < _countOfMaxProcessingTasks &&
|
||||
while (_runningTaskCount < _countOfMaxProcessingTasks &&
|
||||
CocosDownloader.this._taskQueue.size() > 0) {
|
||||
|
||||
|
||||
Runnable taskRunnable = CocosDownloader.this._taskQueue.poll();
|
||||
GlobalObject.getActivity().runOnUiThread(taskRunnable);
|
||||
_runningTaskCount += 1;
|
||||
|
||||
@@ -345,6 +345,8 @@ public class CocosHelper {
|
||||
}
|
||||
}
|
||||
|
||||
public static Activity getActivity() {return sActivity;}
|
||||
|
||||
public static float[] getSafeArea() {
|
||||
if (android.os.Build.VERSION.SDK_INT >= 28) {
|
||||
do {
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.cocos.lib.websocket;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
|
||||
/**
|
||||
* An SSL socket factory that forwards all calls to a delegate. Override {@link
|
||||
* #configureSocket} to customize a created socket before it is returned.
|
||||
*/
|
||||
class CocosDelegatingSSLSocketFactory extends SSLSocketFactory {
|
||||
protected final SSLSocketFactory delegate;
|
||||
|
||||
CocosDelegatingSSLSocketFactory(SSLSocketFactory delegate) {
|
||||
this.delegate = delegate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getDefaultCipherSuites() {
|
||||
return delegate.getDefaultCipherSuites();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getSupportedCipherSuites() {
|
||||
return delegate.getSupportedCipherSuites();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(Socket socket, String host, int port,
|
||||
boolean autoClose) throws IOException {
|
||||
return configureSocket(
|
||||
(SSLSocket)delegate.createSocket(socket, host, port, autoClose));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(String host, int port) throws IOException {
|
||||
return configureSocket((SSLSocket)delegate.createSocket(host, port));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(String host, int port, InetAddress localHost,
|
||||
int localPort) throws IOException {
|
||||
return configureSocket(
|
||||
(SSLSocket)delegate.createSocket(host, port, localHost, localPort));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(InetAddress host, int port) throws IOException {
|
||||
return configureSocket((SSLSocket)delegate.createSocket(host, port));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Socket createSocket(InetAddress address, int port,
|
||||
InetAddress localAddress, int localPort)
|
||||
throws IOException {
|
||||
return configureSocket((SSLSocket)delegate.createSocket(
|
||||
address, port, localAddress, localPort));
|
||||
}
|
||||
|
||||
protected SSLSocket configureSocket(SSLSocket socket) throws IOException {
|
||||
return socket;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.cocos.lib.websocket;
|
||||
|
||||
import org.cocos2dx.okhttp3.Interceptor;
|
||||
import org.cocos2dx.okhttp3.MediaType;
|
||||
import org.cocos2dx.okhttp3.Request;
|
||||
import org.cocos2dx.okhttp3.RequestBody;
|
||||
import org.cocos2dx.okhttp3.Response;
|
||||
import org.cocos2dx.okio.BufferedSink;
|
||||
import org.cocos2dx.okio.GzipSink;
|
||||
import org.cocos2dx.okio.Okio;
|
||||
import java.io.IOException;
|
||||
|
||||
public class CocosGzipRequestInterceptor implements Interceptor {
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request originalRequest = chain.request();
|
||||
if (originalRequest.body() == null ||
|
||||
originalRequest.header("Content-Encoding") != null) {
|
||||
return chain.proceed(originalRequest);
|
||||
}
|
||||
|
||||
Request compressedRequest =
|
||||
originalRequest.newBuilder()
|
||||
.header("Content-Encoding", "gzip")
|
||||
.method(originalRequest.method(), gzip(originalRequest.body()))
|
||||
.build();
|
||||
return chain.proceed(compressedRequest);
|
||||
}
|
||||
|
||||
private RequestBody gzip(final RequestBody body) {
|
||||
return new RequestBody() {
|
||||
@Override
|
||||
public MediaType contentType() {
|
||||
return body.contentType();
|
||||
}
|
||||
|
||||
@Override
|
||||
public long contentLength() {
|
||||
return -1; // 无法提前知道压缩后的数据大小
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writeTo(BufferedSink sink) throws IOException {
|
||||
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
|
||||
body.writeTo(gzipSink);
|
||||
gzipSink.close();
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package com.cocos.lib.websocket;
|
||||
|
||||
import android.os.Build;
|
||||
import android.util.Log;
|
||||
import com.cocos.lib.CocosActivity;
|
||||
import com.cocos.lib.CocosHelper;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocket;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import org.cocos2dx.okhttp3.CipherSuite;
|
||||
import org.cocos2dx.okhttp3.Dispatcher;
|
||||
import org.cocos2dx.okhttp3.OkHttpClient;
|
||||
import org.cocos2dx.okhttp3.Request;
|
||||
import org.cocos2dx.okhttp3.Response;
|
||||
import org.cocos2dx.okhttp3.WebSocketListener;
|
||||
import org.cocos2dx.okio.ByteString;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public class CocosWebSocket extends WebSocketListener {
|
||||
private final static String _TAG = "cocos-websocket";
|
||||
|
||||
static {
|
||||
NativeInit();
|
||||
}
|
||||
|
||||
private static class _WebSocketContext {
|
||||
long identifier;
|
||||
long handlerPtr;
|
||||
}
|
||||
private static Dispatcher dispatcher = null;
|
||||
|
||||
private final long _timeout;
|
||||
private final boolean _perMessageDeflate;
|
||||
private final boolean _tcpNoDelay;
|
||||
private final String[] _header;
|
||||
private final _WebSocketContext _wsContext =
|
||||
new _WebSocketContext();
|
||||
|
||||
private org.cocos2dx.okhttp3.WebSocket _webSocket;
|
||||
private OkHttpClient _client;
|
||||
|
||||
CocosWebSocket(long ptr, long handler, String[] header, boolean tcpNoDelay,
|
||||
boolean perMessageDeflate, long timeout) {
|
||||
_wsContext.identifier = ptr;
|
||||
_wsContext.handlerPtr = handler;
|
||||
_header = header;
|
||||
_tcpNoDelay = tcpNoDelay;
|
||||
_perMessageDeflate = perMessageDeflate;
|
||||
_timeout = timeout;
|
||||
}
|
||||
|
||||
private void _removeHandler() {
|
||||
synchronized (_wsContext) {
|
||||
_wsContext.identifier = 0;
|
||||
_wsContext.handlerPtr = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void _send(final byte[] msg) {
|
||||
// Log.d(_TAG, "try sending binary msg");
|
||||
if (null == _webSocket) {
|
||||
Log.e(_TAG, "WebSocket hasn't connected yet");
|
||||
return;
|
||||
}
|
||||
|
||||
ByteString byteString = ByteString.of(msg);
|
||||
_webSocket.send(byteString);
|
||||
}
|
||||
|
||||
private void _send(final String msg) {
|
||||
// Log.d(_TAG, "try sending string msg: " + msg);
|
||||
if (null == _webSocket) {
|
||||
Log.e(_TAG, "WebSocket hasn't connected yet");
|
||||
return;
|
||||
}
|
||||
|
||||
_webSocket.send(msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the VM's default SSL socket factory, using {@code trustManager} for
|
||||
* trusted root certificates.
|
||||
*/
|
||||
private SSLSocketFactory
|
||||
defaultSslSocketFactory(X509TrustManager trustManager)
|
||||
throws NoSuchAlgorithmException, KeyManagementException {
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
SecureRandom random;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
random = SecureRandom.getInstanceStrong();
|
||||
} else {
|
||||
random = SecureRandom.getInstance("SHA1PRNG");
|
||||
}
|
||||
sslContext.init(null, new TrustManager[] {trustManager}, random);
|
||||
return sslContext.getSocketFactory();
|
||||
}
|
||||
|
||||
private String[] javaNames(List<CipherSuite> cipherSuites) {
|
||||
if (cipherSuites == null) {
|
||||
return new String[0];
|
||||
} else {
|
||||
String[] result = new String[cipherSuites.size()];
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
result[i] = cipherSuites.get(i).javaName();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
private void _connect(final String url, final String protocols,
|
||||
final String caFilePath) {
|
||||
Log.d(_TAG, "connect ws url: '" + url + "' ,protocols: '" + protocols + "' ,ca_: '" + caFilePath + "'");
|
||||
Request.Builder requestBuilder = new Request.Builder().url(url);
|
||||
try {
|
||||
requestBuilder = requestBuilder.url(url);
|
||||
} catch (NullPointerException | IllegalArgumentException e) {
|
||||
synchronized (_wsContext) {
|
||||
nativeOnError("invalid url", _wsContext.identifier,
|
||||
_wsContext.handlerPtr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!protocols.isEmpty()) {
|
||||
requestBuilder.addHeader("Sec-WebSocket-Protocol", protocols);
|
||||
}
|
||||
if (_header != null) {
|
||||
for (int index = 0; index < _header.length; index += 2) {
|
||||
requestBuilder.header(_header[index], _header[index + 1]);
|
||||
}
|
||||
}
|
||||
Request request = requestBuilder.build();
|
||||
|
||||
if(dispatcher == null) {
|
||||
dispatcher = new Dispatcher();
|
||||
}
|
||||
|
||||
OkHttpClient.Builder builder =
|
||||
new OkHttpClient.Builder()
|
||||
.dispatcher(dispatcher)
|
||||
.readTimeout(_timeout, TimeUnit.MILLISECONDS)
|
||||
.writeTimeout(_timeout, TimeUnit.MILLISECONDS)
|
||||
.connectTimeout(_timeout, TimeUnit.MILLISECONDS);
|
||||
|
||||
if (_perMessageDeflate) {
|
||||
// 开启压缩扩展, 开启 Gzip 压缩
|
||||
builder.addInterceptor(new CocosGzipRequestInterceptor());
|
||||
}
|
||||
KeyStore keyStore = null;
|
||||
if (url.toLowerCase().startsWith("wss://") && !caFilePath.isEmpty()) {
|
||||
try {
|
||||
InputStream caInput = null;
|
||||
|
||||
if (caFilePath.startsWith("assets/")) {
|
||||
caInput = CocosHelper.getActivity().getResources().getAssets().open(caFilePath);
|
||||
} else {
|
||||
caInput = new FileInputStream(caFilePath);
|
||||
}
|
||||
if (caFilePath.toLowerCase().endsWith(".pem")) {
|
||||
keyStore = CocosWebSocketUtils.GetPEMKeyStore(caInput);
|
||||
} else {
|
||||
keyStore = CocosWebSocketUtils.GetCERKeyStore(caInput);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
String errMsg = e.getMessage();
|
||||
if (errMsg == null) {
|
||||
errMsg = "unknown error";
|
||||
}
|
||||
synchronized (_wsContext) {
|
||||
nativeOnError(errMsg, _wsContext.identifier, _wsContext.handlerPtr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
builder.hostnameVerifier(new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String hostname, SSLSession session) {
|
||||
Log.d(_TAG, "ca hostname: " + hostname);
|
||||
HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
|
||||
return hv.verify(hostname, session);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (url.toLowerCase().startsWith("wss://") || _tcpNoDelay) {
|
||||
try {
|
||||
X509TrustManager trustManager =
|
||||
CocosWebSocketUtils.GetTrustManager(keyStore);
|
||||
SSLContext sslContext = SSLContext.getInstance("TLS");
|
||||
SecureRandom random;
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
random = SecureRandom.getInstanceStrong();
|
||||
} else {
|
||||
random = SecureRandom.getInstance("SHA1PRNG");
|
||||
}
|
||||
sslContext.init(null, new TrustManager[] {trustManager}, random);
|
||||
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
|
||||
SSLSocketFactory customSslSocketFactory =
|
||||
new CocosDelegatingSSLSocketFactory(sslSocketFactory) {
|
||||
@Override
|
||||
protected SSLSocket configureSocket(SSLSocket socket)
|
||||
throws IOException {
|
||||
socket.setTcpNoDelay(_tcpNoDelay);
|
||||
// TLSv1.2 is disabled default below API20----
|
||||
// https://developer.android.com/reference/javax/net/ssl/SSLSocket
|
||||
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT_WATCH) {
|
||||
socket.setEnabledProtocols(new String[] {"TLSv1.2"});
|
||||
}
|
||||
return socket;
|
||||
}
|
||||
};
|
||||
builder.sslSocketFactory(customSslSocketFactory, trustManager);
|
||||
} catch (GeneralSecurityException e) {
|
||||
e.printStackTrace();
|
||||
String errMsg = e.getMessage();
|
||||
if (errMsg == null) {
|
||||
errMsg = "unknown error";
|
||||
}
|
||||
synchronized (_wsContext) {
|
||||
nativeOnError(errMsg, _wsContext.identifier, _wsContext.handlerPtr);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
_client = builder.build();
|
||||
_webSocket = _client.newWebSocket(request, this);
|
||||
}
|
||||
|
||||
private void _close(final int code, final String reason) {
|
||||
_webSocket.close(code, reason);
|
||||
// _client.dispatcher().executorService().shutdown();
|
||||
}
|
||||
|
||||
private long _getBufferedAmountID() {
|
||||
return _webSocket.queueSize();
|
||||
}
|
||||
|
||||
private void output(final String content) {
|
||||
Log.w(_TAG, content);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOpen(org.cocos2dx.okhttp3.WebSocket _webSocket, Response response) {
|
||||
output("WebSocket onOpen _client: " + _client);
|
||||
synchronized (_wsContext) {
|
||||
nativeOnOpen(response.protocol().toString(),
|
||||
response.headers().toString(), _wsContext.identifier,
|
||||
_wsContext.handlerPtr);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(org.cocos2dx.okhttp3.WebSocket _webSocket, String text) {
|
||||
// output("Receiving string msg: " + text);
|
||||
synchronized (_wsContext) {
|
||||
nativeOnStringMessage(text, _wsContext.identifier, _wsContext.handlerPtr);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(org.cocos2dx.okhttp3.WebSocket _webSocket, ByteString bytes) {
|
||||
// output("Receiving binary msg");
|
||||
synchronized (_wsContext) {
|
||||
nativeOnBinaryMessage(bytes.toByteArray(), _wsContext.identifier,
|
||||
_wsContext.handlerPtr);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosing(org.cocos2dx.okhttp3.WebSocket _webSocket, int code,
|
||||
String reason) {
|
||||
output("Closing : " + code + " / " + reason);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(org.cocos2dx.okhttp3.WebSocket _webSocket, Throwable t,
|
||||
Response response) {
|
||||
String msg = "";
|
||||
if (t != null) {
|
||||
msg = t.getMessage() == null ? t.getClass().getSimpleName() : t.getMessage();
|
||||
}
|
||||
output("onFailure Error : " + msg);
|
||||
synchronized (_wsContext) {
|
||||
nativeOnError(msg, _wsContext.identifier, _wsContext.handlerPtr);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClosed(org.cocos2dx.okhttp3.WebSocket _webSocket, int code,
|
||||
String reason) {
|
||||
output("onClosed : " + code + " / " + reason);
|
||||
synchronized (_wsContext) {
|
||||
nativeOnClosed(code, reason, _wsContext.identifier,
|
||||
_wsContext.handlerPtr);
|
||||
}
|
||||
}
|
||||
|
||||
private static native void NativeInit();
|
||||
|
||||
private native void nativeOnStringMessage(final String msg, long identifier,
|
||||
long handler);
|
||||
|
||||
private native void nativeOnBinaryMessage(final byte[] msg, long identifier,
|
||||
long handler);
|
||||
|
||||
private native void nativeOnOpen(final String protocol,
|
||||
final String headerString, long identifier,
|
||||
long handler);
|
||||
|
||||
private native void nativeOnClosed(final int code, final String reason,
|
||||
long identifier, long handler);
|
||||
|
||||
private native void nativeOnError(final String msg, long identifier,
|
||||
long handler);
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package com.cocos.lib.websocket;
|
||||
|
||||
import android.util.Base64;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.util.Arrays;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
|
||||
class CocosWebSocketUtils {
|
||||
static X509TrustManager GetTrustManager(KeyStore keyStore)
|
||||
throws GeneralSecurityException {
|
||||
String algorithm = TrustManagerFactory.getDefaultAlgorithm();
|
||||
TrustManagerFactory trustManagerFactory =
|
||||
TrustManagerFactory.getInstance(algorithm);
|
||||
trustManagerFactory.init(keyStore);
|
||||
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
|
||||
if (trustManagers.length != 1 ||
|
||||
!(trustManagers[0] instanceof X509TrustManager)) {
|
||||
String prefixErrorMessage = "Unexpected default trust managers:";
|
||||
throw new IllegalStateException(prefixErrorMessage +
|
||||
Arrays.toString(trustManagers));
|
||||
}
|
||||
return (X509TrustManager)trustManagers[0];
|
||||
}
|
||||
|
||||
static KeyStore GetCERKeyStore(InputStream inputStream)
|
||||
throws CertificateException, KeyStoreException, IOException,
|
||||
NoSuchAlgorithmException {
|
||||
CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
Certificate certificate = factory.generateCertificate(inputStream);
|
||||
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
keyStore.load(null);
|
||||
keyStore.setCertificateEntry("0", certificate);
|
||||
return keyStore;
|
||||
}
|
||||
|
||||
static KeyStore GetPEMKeyStore(InputStream inputStream) throws Exception {
|
||||
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
|
||||
keyStore.load(null);
|
||||
int index = 0;
|
||||
|
||||
BufferedReader bufferedReader =
|
||||
new BufferedReader(new InputStreamReader(inputStream));
|
||||
String carBegin;
|
||||
while ((carBegin = bufferedReader.readLine()) != null) {
|
||||
if (carBegin.contains("BEGIN CERTIFICATE")) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
while ((carBegin = bufferedReader.readLine()) != null) {
|
||||
if (carBegin.contains("END CERTIFICATE")) {
|
||||
String hexString = stringBuilder.toString();
|
||||
byte[] bytes = Base64.decode(hexString, Base64.DEFAULT);
|
||||
Certificate certificate = _GenerateCertificateFromDER(bytes);
|
||||
keyStore.setCertificateEntry(Integer.toString(index++),
|
||||
certificate);
|
||||
break;
|
||||
} else {
|
||||
stringBuilder.append(carBegin);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
bufferedReader.close();
|
||||
if (index == 0) {
|
||||
throw new IllegalArgumentException("No CERTIFICATE found");
|
||||
}
|
||||
return keyStore;
|
||||
}
|
||||
|
||||
private static Certificate _GenerateCertificateFromDER(byte[] certBytes)
|
||||
throws CertificateException {
|
||||
CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
return factory.generateCertificate(new ByteArrayInputStream(certBytes));
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.google.androidgamesdk;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.Choreographer;
|
||||
import android.util.Log;
|
||||
|
||||
|
||||
public class ChoreographerCallback implements Choreographer.FrameCallback {
|
||||
private static final String LOG_TAG = "ChoreographerCallback";
|
||||
private long mCookie;
|
||||
private LooperThread mLooper;
|
||||
|
||||
private class LooperThread extends Thread {
|
||||
public Handler mHandler;
|
||||
|
||||
public void run() {
|
||||
Log.i(LOG_TAG, "Starting looper thread");
|
||||
Looper.prepare();
|
||||
mHandler = new Handler();
|
||||
Looper.loop();
|
||||
Log.i(LOG_TAG, "Terminating looper thread");
|
||||
}
|
||||
}
|
||||
|
||||
public ChoreographerCallback(long cookie) {
|
||||
mCookie = cookie;
|
||||
mLooper = new LooperThread();
|
||||
mLooper.start();
|
||||
}
|
||||
|
||||
public void postFrameCallback() {
|
||||
mLooper.mHandler.post(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Choreographer.getInstance().postFrameCallback(ChoreographerCallback.this);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void postFrameCallbackDelayed(long delayMillis) {
|
||||
Choreographer.getInstance().postFrameCallbackDelayed(this, delayMillis);
|
||||
}
|
||||
|
||||
public void terminate() {
|
||||
mLooper.mHandler.getLooper().quit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFrame(long frameTimeNanos) {
|
||||
nOnChoreographer(mCookie, frameTimeNanos);
|
||||
}
|
||||
|
||||
public native void nOnChoreographer(long cookie, long frameTimeNanos);
|
||||
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.google.androidgamesdk;
|
||||
|
||||
/** JNI api for getting device information */
|
||||
public class GameSdkDeviceInfoJni {
|
||||
private static Throwable initializationExceptionOrError;
|
||||
|
||||
static {
|
||||
try {
|
||||
System.loadLibrary("game_sdk_device_info_jni");
|
||||
} catch(Exception exception) {
|
||||
// Catch SecurityException, NullPointerException (or any potential unchecked exception)
|
||||
// as we don't want to crash the app if the library failed to load.
|
||||
initializationExceptionOrError = exception;
|
||||
} catch(Error error) {
|
||||
// Catch UnsatisfiedLinkError (or any potential unchecked error)
|
||||
// as we don't want to crash the app if the library failed to load.
|
||||
initializationExceptionOrError = error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a byte array, which is a serialized proto containing device information, or
|
||||
* null if the native library "game_sdk_device_info_jni" could not be loaded.
|
||||
*
|
||||
* @return Optional with the serialized byte array, representing game sdk device info with errors,
|
||||
* or null.
|
||||
*/
|
||||
public static byte[] tryGetProtoSerialized() {
|
||||
if (initializationExceptionOrError != null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return getProtoSerialized();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns the exception or error that was caught when trying to load the library, if any.
|
||||
* Otherwise, returns null.
|
||||
*
|
||||
* @return The caught Throwable or null.
|
||||
*/
|
||||
public static Throwable getInitializationExceptionOrError() {
|
||||
return initializationExceptionOrError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a byte array, which is a serialized proto.
|
||||
*
|
||||
* @return serialized byte array, representing game sdk device info with errors.
|
||||
*/
|
||||
private static native byte[] getProtoSerialized();
|
||||
|
||||
private GameSdkDeviceInfoJni() {}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package com.google.androidgamesdk;
|
||||
|
||||
import android.annotation.TargetApi;
|
||||
import android.app.Activity;
|
||||
import android.content.ComponentName;
|
||||
import android.content.pm.ActivityInfo;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.hardware.display.DisplayManager;
|
||||
import android.os.Build;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.Log;
|
||||
import android.view.Display;
|
||||
import android.view.Window;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import java.util.concurrent.locks.Condition;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
import static android.app.NativeActivity.META_DATA_LIB_NAME;
|
||||
|
||||
public class SwappyDisplayManager implements DisplayManager.DisplayListener {
|
||||
final private String LOG_TAG = "SwappyDisplayManager";
|
||||
final private boolean DEBUG = false;
|
||||
final private long ONE_MS_IN_NS = 1000000;
|
||||
final private long ONE_S_IN_NS = ONE_MS_IN_NS * 1000;
|
||||
|
||||
private long mCookie;
|
||||
private Activity mActivity;
|
||||
private WindowManager mWindowManager;
|
||||
private Display.Mode mCurrentMode;
|
||||
|
||||
private LooperThread mLooper;
|
||||
|
||||
private class LooperThread extends Thread {
|
||||
public Handler mHandler;
|
||||
private Lock mLock = new ReentrantLock();
|
||||
private Condition mCondition = mLock.newCondition();
|
||||
|
||||
@Override
|
||||
public void start() {
|
||||
mLock.lock();
|
||||
super.start();
|
||||
try {
|
||||
mCondition.await();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
mLock.unlock();
|
||||
|
||||
}
|
||||
|
||||
public void run() {
|
||||
Log.i(LOG_TAG, "Starting looper thread");
|
||||
|
||||
mLock.lock();
|
||||
Looper.prepare();
|
||||
mHandler = new Handler();
|
||||
mCondition.signal();
|
||||
mLock.unlock();
|
||||
|
||||
Looper.loop();
|
||||
|
||||
Log.i(LOG_TAG, "Terminating looper thread");
|
||||
}
|
||||
}
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.M)
|
||||
private boolean modeMatchesCurrentResolution(Display.Mode mode) {
|
||||
return mode.getPhysicalHeight() == mCurrentMode.getPhysicalHeight() &&
|
||||
mode.getPhysicalWidth() == mCurrentMode.getPhysicalWidth();
|
||||
|
||||
}
|
||||
|
||||
public SwappyDisplayManager(long cookie, Activity activity) {
|
||||
// Load the native library for cases where an NDK application is running
|
||||
// without a java componenet
|
||||
try {
|
||||
ActivityInfo ai = activity.getPackageManager().getActivityInfo(
|
||||
activity.getIntent().getComponent(), PackageManager.GET_META_DATA);
|
||||
if (ai.metaData != null) {
|
||||
String nativeLibName = ai.metaData.getString(META_DATA_LIB_NAME);
|
||||
if (nativeLibName != null) {
|
||||
System.loadLibrary(nativeLibName);
|
||||
}
|
||||
}
|
||||
} catch (java.lang.Throwable e) {
|
||||
Log.e(LOG_TAG, e.getMessage());
|
||||
}
|
||||
|
||||
mCookie = cookie;
|
||||
mActivity = activity;
|
||||
|
||||
mWindowManager = mActivity.getSystemService(WindowManager.class);
|
||||
Display display = mWindowManager.getDefaultDisplay();
|
||||
mCurrentMode = display.getMode();
|
||||
updateSupportedRefreshRates(display);
|
||||
|
||||
// Register display listener callbacks
|
||||
DisplayManager dm = mActivity.getSystemService(DisplayManager.class);
|
||||
|
||||
synchronized(this) {
|
||||
mLooper = new LooperThread();
|
||||
mLooper.start();
|
||||
dm.registerDisplayListener(this, mLooper.mHandler);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateSupportedRefreshRates(Display display) {
|
||||
Display.Mode[] supportedModes = display.getSupportedModes();
|
||||
int totalModes = 0;
|
||||
for (int i = 0; i < supportedModes.length; i++) {
|
||||
if (!modeMatchesCurrentResolution(supportedModes[i])) {
|
||||
continue;
|
||||
}
|
||||
totalModes++;
|
||||
}
|
||||
|
||||
long[] supportedRefreshPeriods = new long[totalModes];
|
||||
int[] supportedDisplayModeIds = new int[totalModes];
|
||||
totalModes = 0;
|
||||
for (int i = 0; i < supportedModes.length; i++) {
|
||||
if (!modeMatchesCurrentResolution(supportedModes[i])) {
|
||||
continue;
|
||||
}
|
||||
supportedRefreshPeriods[totalModes] =
|
||||
(long) (ONE_S_IN_NS / supportedModes[i].getRefreshRate());
|
||||
supportedDisplayModeIds[totalModes] = supportedModes[i].getModeId();
|
||||
totalModes++;
|
||||
|
||||
}
|
||||
// Call down to native to set the supported refresh rates
|
||||
nSetSupportedRefreshPeriods(mCookie, supportedRefreshPeriods, supportedDisplayModeIds);
|
||||
}
|
||||
|
||||
public void setPreferredDisplayModeId(final int modeId) {
|
||||
mActivity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Window w = mActivity.getWindow();
|
||||
WindowManager.LayoutParams l = w.getAttributes();
|
||||
if (DEBUG) {
|
||||
Log.v(LOG_TAG, "set preferredDisplayModeId to " + modeId);
|
||||
}
|
||||
l.preferredDisplayModeId = modeId;
|
||||
|
||||
|
||||
w.setAttributes(l);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void terminate() {
|
||||
mLooper.mHandler.getLooper().quit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisplayAdded(int displayId) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisplayRemoved(int displayId) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisplayChanged(int displayId) {
|
||||
synchronized(this) {
|
||||
Display display = mWindowManager.getDefaultDisplay();
|
||||
float newRefreshRate = display.getRefreshRate();
|
||||
Display.Mode newMode = display.getMode();
|
||||
boolean resolutionChanged =
|
||||
(newMode.getPhysicalWidth() != mCurrentMode.getPhysicalWidth()) |
|
||||
(newMode.getPhysicalHeight() != mCurrentMode.getPhysicalHeight());
|
||||
boolean refreshRateChanged = (newRefreshRate != mCurrentMode.getRefreshRate());
|
||||
mCurrentMode = newMode;
|
||||
|
||||
if (resolutionChanged) {
|
||||
updateSupportedRefreshRates(display);
|
||||
}
|
||||
|
||||
if (refreshRateChanged) {
|
||||
final long appVsyncOffsetNanos = display.getAppVsyncOffsetNanos();
|
||||
final long vsyncPresentationDeadlineNanos =
|
||||
mWindowManager.getDefaultDisplay().getPresentationDeadlineNanos();
|
||||
|
||||
final long vsyncPeriodNanos = (long)(ONE_S_IN_NS / newRefreshRate);
|
||||
final long sfVsyncOffsetNanos =
|
||||
vsyncPeriodNanos - (vsyncPresentationDeadlineNanos - ONE_MS_IN_NS);
|
||||
|
||||
nOnRefreshPeriodChanged(mCookie,
|
||||
vsyncPeriodNanos,
|
||||
appVsyncOffsetNanos,
|
||||
sfVsyncOffsetNanos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private native void nSetSupportedRefreshPeriods(long cookie,
|
||||
long[] refreshPeriods,
|
||||
int[] modeIds);
|
||||
private native void nOnRefreshPeriodChanged(long cookie,
|
||||
long refreshPeriod,
|
||||
long appOffset,
|
||||
long sfOffset);
|
||||
}
|
||||
Reference in New Issue
Block a user